<commit_before>'use strict';

import React, { Component, PropTypes } from 'react';
import { Image, Platform, Dimensions } from 'react-native';

const IMG_CENTER_MODE = Platform.OS === 'ios' ? 'center' : 'contain';

class Ikon extends Component {

  constructor(props) {
    super(props);

    const {disabled, name, style} = props;

    this.iconSet = __iconSet;

    const resizeMode = props.resizeMode ? props.resizeMode : this.traverseIconSet(name, 'resizeMode');
    const autoScale = props.autoScale ? props.autoScale : this.traverseIconSet(name, 'autoScale');

    const doScale = (value) => {
      return autoScale ? Ikon.__normalize(value) : value;
    }

    const width = doScale( props.width ? props.width : this.traverseIconSet(name, 'width') );
    const height = doScale( props.height ? props.height : this.traverseIconSet(name, 'height') );
    const source = props.source ? props.source : this.traverseIconSet(name, 'source');

    let _style = style ? style : {};
    _style = [..._style, {width, height}];

    if(!!disabled) {
      let disabledStyle = this.traverseIconSet(name, '$disabled')
      if(!disabledStyle) {
        disabledStyle = {opacity: 0.5};
      }
      _style = [..._style, disabledStyle];
    }

    this.state = {
        style: _style,
        resizeMode: resizeMode ? resizeMode : IMG_CENTER_MODE,
        width,
        height,
        source
    }
  }

  // register an IconSet
  static registerIconSet(iconSet) {
      __iconSet = iconSet;
  }

  render() {
    return (
      <Image resizeMode={this.state.resizeMode} width={this.state.width} height={this.state.height}
            source={this.state.source} style={this.state.style}>
      </Image>
    )
  }

  // try to find a value while traversing up the iconSet structure
  traverseIconSet(name, property) {
    let obj = Ikon.__resolvePropertyByKey(this.iconSet, name);
    while(obj) {
      if(obj[property]) {
        return obj[property];
      }

      const p = name.lastIndexOf('.');
      if(!p) return null;
      name = name.substr(0, p);
      obj = Ikon.__resolvePropertyByKey(this.iconSet, name);
    }
    return null;
  }

  // traverse down a nested object to resolve the 'path'
  static __resolvePropertyByKey(obj, path) {
      return path.split('.').reduce(function(prev, curr) {
          return prev ? prev[curr] : undefined
      }, obj)
  }

  static __normalize(value : number) {
    console.log(value, __scale, Math.round(__scale * value));
    return Math.round(__scale * value);
  }

}

const __scale = Dimensions ? Dimensions.get('window').width / 375 : 1;

// global iconSet
// assign your personal IconSet with Ikon.registerIconSet()
let __iconSet = null;

Ikon.propTypes = {
  name: PropTypes.string.isRequired,
  style: PropTypes.object,
  resizeMode: PropTypes.string,
  autoScale: PropTypes.boolean,
}

Ikon.defaultProps = {
}

module.exports = Ikon;
<commit_msg>Debug-code removed<commit_after>'use strict';

import React, { Component, PropTypes } from 'react';
import { Image, Platform, Dimensions } from 'react-native';

const IMG_CENTER_MODE = Platform.OS === 'ios' ? 'center' : 'contain';

class Ikon extends Component {

  constructor(props) {
    super(props);

    const {disabled, name, style} = props;

    this.iconSet = __iconSet;

    const resizeMode = props.resizeMode ? props.resizeMode : this.traverseIconSet(name, 'resizeMode');
    const autoScale = props.autoScale ? props.autoScale : this.traverseIconSet(name, 'autoScale');

    const doScale = (value) => {
      return autoScale ? Ikon.__normalize(value) : value;
    }

    const width = doScale( props.width ? props.width : this.traverseIconSet(name, 'width') );
    const height = doScale( props.height ? props.height : this.traverseIconSet(name, 'height') );
    const source = props.source ? props.source : this.traverseIconSet(name, 'source');

    let _style = style ? style : {};
    _style = [..._style, {width, height}];

    if(!!disabled) {
      let disabledStyle = this.traverseIconSet(name, '$disabled')
      if(!disabledStyle) {
        disabledStyle = {opacity: 0.5};
      }
      _style = [..._style, disabledStyle];
    }

    this.state = {
        style: _style,
        resizeMode: resizeMode ? resizeMode : IMG_CENTER_MODE,
        width,
        height,
        source
    }
  }

  // register an IconSet
  static registerIconSet(iconSet) {
      __iconSet = iconSet;
  }

  render() {
    return (
      <Image resizeMode={this.state.resizeMode} width={this.state.width} height={this.state.height}
            source={this.state.source} style={this.state.style}>
      </Image>
    )
  }

  // try to find a value while traversing up the iconSet structure
  traverseIconSet(name, property) {
    let obj = Ikon.__resolvePropertyByKey(this.iconSet, name);
    while(obj) {
      if(obj[property]) {
        return obj[property];
      }

      const p = name.lastIndexOf('.');
      if(!p) return null;
      name = name.substr(0, p);
      obj = Ikon.__resolvePropertyByKey(this.iconSet, name);
    }
    return null;
  }

  // traverse down a nested object to resolve the 'path'
  static __resolvePropertyByKey(obj, path) {
      return path.split('.').reduce(function(prev, curr) {
          return prev ? prev[curr] : undefined
      }, obj)
  }

  static __normalize(value : number) {
    return Math.round(__scale * value);
  }

}

const __scale = Dimensions ? Dimensions.get('window').width / 375 : 1;

// global iconSet
// assign your personal IconSet with Ikon.registerIconSet()
let __iconSet = null;

Ikon.propTypes = {
  name: PropTypes.string.isRequired,
  style: PropTypes.object,
  resizeMode: PropTypes.string,
  autoScale: PropTypes.boolean,
}

Ikon.defaultProps = {
}

module.exports = Ikon;
<|endoftext|>


<commit_before>/*

*/

(function( $, undefined ) {

    $.kbWidget("kbaseIrisTutorial", 'kbaseWidget', {
        version: "1.0.0",
        options: {
            configURL : 'http://www.prototypesite.net/kbase/tutorials.cfg',
        },

        format_tutorial_url : function (doc_format_string, repo, filespec) {
            var url = doc_format_string;
            url = url.replace(/\$repo/, repo);
            url = url.replace(/\$filespec/, filespec);

            return url;
        },

        list : function() {
            var output = [];
            for (key in this.repos) {

                for (var idx = 0; idx < this.repos[key].length; idx++) {
                    var tutorial = this.repos[key][idx];

                    var url = this.format_tutorial_url(
                        this.doc_format_string,
                        key,
                        tutorial.file
                    );

                    output.push(
                        {
                            title : tutorial.title,
                            url : url,
                        }
                    );
                }
            }

            return output.sort(this.sortByKey('title', 'insensitively'));
        },

        init : function (options) {
            this._super(options);

            this.pages = [];
            this.currentPage = -1;

            $.getJSON(
                this.options.configURL,
                $.proxy(function(data) {
                    this.repos = data.repos;
                    this.doc_format_string = data.doc_format_string;
                    if (this.options.tutorial == undefined) {
                        this.options.tutorial = data.default;
                    }

                    if (this.options.tutorial) {
                        this.retrieveTutorial(this.options.tutorial);
                    }

                }, this)
            );

            return this;
        },

        retrieveTutorial : function(url) {

            this.pages = [];

            var token = undefined;

            $.ajax(
                {
    		        async : true,
            		dataType: "text",
            		url: url,
            		crossDomain : true,
            		beforeSend: function (xhr) {
		                if (token) {
                			xhr.setRequestHeader('Authorization', token);
		                }
            		},
            		success: $.proxy(function (data, status, xhr) {

            		    var $resp = $('

').append(data);

            		    $.each(
            		        $resp.children(),
            		        $.proxy( function(idx, page) {
            		            $(page).find('.example').remove();
                                this.pages.push($(page));
            		        }, this)
            		    );

            		    this.renderAsHTML();
		            }, this),
            		error: $.proxy(function(xhr, textStatus, errorThrown) {
            		    this.dbg(xhr);
                        throw xhr;
		            }, this),
                    type: 'GET',
    	        }
    	    );

        },

        renderAsHTML : function() {
            this.$elem.empty();
            $.each(
                this.pages,
                $.proxy(function (idx, page) {
                    this.$elem.append(page);
                }, this)
            );
        },

        lastPage : function() {
            return this.pages.length - 1;
        },

        currentPage : function() {
            page = this.currentPage;
            if (this.currentPage < 0) {
                page = 0;
            }
            return this.pages[page];
        },

        goToPrevPage : function () {
            var page = this.currentPage - 1;
            if (page < 0) {
                page = 0;
            }
            this.currentPage = page;
            return page;
        },

        goToNextPage : function () {
            var page = this.currentPage + 1;
            if (page >= this.pages.length) {
                page = this.pages.length - 1;
            }
            this.currentPage = page;
            return page;
        },

        contentForPage : function(idx) {
            if (this.pages.length == 0) {
                return undefined;
            }
            else {
                return this.pages[this.currentPage];
            }
        },

        contentForCurrentPage : function () {
            return this.contentForPage(this.currentPage);
        },

    });

}( jQuery ) );
<commit_msg>pointed to live tutorials.cfg<commit_after>/*

*/

(function( $, undefined ) {

    $.kbWidget("kbaseIrisTutorial", 'kbaseWidget', {
        version: "1.0.0",
        options: {
            configURL : 'http://www.kbase.us/docs/tutorials.cfg',
        },

        format_tutorial_url : function (doc_format_string, repo, filespec) {
            var url = doc_format_string;
            url = url.replace(/\$repo/, repo);
            url = url.replace(/\$filespec/, filespec);

            return url;
        },

        list : function() {
            var output = [];
            for (key in this.repos) {

                for (var idx = 0; idx < this.repos[key].length; idx++) {
                    var tutorial = this.repos[key][idx];

                    var url = this.format_tutorial_url(
                        this.doc_format_string,
                        key,
                        tutorial.file
                    );

                    output.push(
                        {
                            title : tutorial.title,
                            url : url,
                        }
                    );
                }
            }

            return output.sort(this.sortByKey('title', 'insensitively'));
        },

        init : function (options) {
            this._super(options);

            this.pages = [];
            this.currentPage = -1;

            $.getJSON(
                this.options.configURL,
                $.proxy(function(data) {
                    this.repos = data.repos;
                    this.doc_format_string = data.doc_format_string;
                    if (this.options.tutorial == undefined) {
                        this.options.tutorial = data.default;
                    }

                    if (this.options.tutorial) {
                        this.retrieveTutorial(this.options.tutorial);
                    }

                }, this)
            );

            return this;
        },

        retrieveTutorial : function(url) {

            this.pages = [];

            var token = undefined;

            $.ajax(
                {
    		        async : true,
            		dataType: "text",
            		url: url,
            		crossDomain : true,
            		beforeSend: function (xhr) {
		                if (token) {
                			xhr.setRequestHeader('Authorization', token);
		                }
            		},
            		success: $.proxy(function (data, status, xhr) {

            		    var $resp = $('

').append(data);

            		    $.each(
            		        $resp.children(),
            		        $.proxy( function(idx, page) {
            		            $(page).find('.example').remove();
                                this.pages.push($(page));
            		        }, this)
            		    );

            		    this.renderAsHTML();
		            }, this),
            		error: $.proxy(function(xhr, textStatus, errorThrown) {
            		    this.dbg(xhr);
                        throw xhr;
		            }, this),
                    type: 'GET',
    	        }
    	    );

        },

        renderAsHTML : function() {
            this.$elem.empty();
            $.each(
                this.pages,
                $.proxy(function (idx, page) {
                    this.$elem.append(page);
                }, this)
            );
        },

        lastPage : function() {
            return this.pages.length - 1;
        },

        currentPage : function() {
            page = this.currentPage;
            if (this.currentPage < 0) {
                page = 0;
            }
            return this.pages[page];
        },

        goToPrevPage : function () {
            var page = this.currentPage - 1;
            if (page < 0) {
                page = 0;
            }
            this.currentPage = page;
            return page;
        },

        goToNextPage : function () {
            var page = this.currentPage + 1;
            if (page >= this.pages.length) {
                page = this.pages.length - 1;
            }
            this.currentPage = page;
            return page;
        },

        contentForPage : function(idx) {
            if (this.pages.length == 0) {
                return undefined;
            }
            else {
                return this.pages[this.currentPage];
            }
        },

        contentForCurrentPage : function () {
            return this.contentForPage(this.currentPage);
        },

    });

}( jQuery ) );
<|endoftext|>


<commit_before>var bodyParser = require('body-parser').json();

module.exports = function(protoValidator) {
	protoValidator.bodyParser = function(schema, options) {
		if(!schema) throw new Error('skeemas.bodyParser called without schema');

		var validator = this,
			failureCode = options && options.failureCode || 422,
			failureResponse = options && options.failureResponse || function(result) {
				return {
					status: 'fail',
					data: {
						validation: result.errors
					}
				};
			};

		return [bodyParser, function(req, res, next) { console.log('before', req.body); next(); }, function(req, res, next) {
			var result = validator.validate(req.body, schema);

			if(!result.valid) return res.status(failureCode).json(failureResponse(result));

			req.body = result.cleanInstance;

			next();
		}];
	};
};
<commit_msg>Removing another console stmt<commit_after>var bodyParser = require('body-parser').json();

module.exports = function(protoValidator) {
	protoValidator.bodyParser = function(schema, options) {
		if(!schema) throw new Error('skeemas.bodyParser called without schema');

		var validator = this,
			failureCode = options && options.failureCode || 422,
			failureResponse = options && options.failureResponse || function(result) {
				return {
					status: 'fail',
					data: {
						validation: result.errors
					}
				};
			};

		return [bodyParser, function(req, res, next) {
			var result = validator.validate(req.body, schema);

			if(!result.valid) return res.status(failureCode).json(failureResponse(result));

			req.body = result.cleanInstance;

			next();
		}];
	};
};
<|endoftext|>


<commit_before>/* eslint-disable no-use-before-define */

const levenshtein = require("fast-levenshtein");

exports.run = async (client, msg) => {
  if (msg.author.bot) return;
  if (client.config.selfbot && msg.author.id !== client.user.id) return;

  const info = parseCommand(client, msg);
  const { prefixLength } = info;
  if (!prefixLength) return;
  const { command } = info;
  if (command.length && !(client.commands.has(command) || client.aliases.has(command))) {
    const distances = [];
    client.commands.filter(c => c.conf.permLevel <= msg.member.permLevel).forEach((val, cmd) => distances.push({
      dist: levenshtein.get(cmd, command),
      cmd,
    }));
    distances.sort((a, b) => (a.score < b.score ? 1 : -1));
    if (distances[0] && distances[0].dist <= 1) {
      const message = await msg.channel.send(`|\`❔\`| Did you mean \`${info.prefix + distances[0].cmd}\`?`);
      if (message.deletable) message.delete({ timeout: 10000 });
    }
  }
};

exports.conf = {
  enabled: true,
  requiredModules: ["fast-levenshtein"],
};

exports.help = {
  name: "didyoumean",
  type: "monitors",
  description: "Helps users that type in commands incorrectly.",
};

const parseCommand = async (client, msg) => {
  const prefix = client.funcs.getPrefix(client, msg);
  if (!prefix) return false;
  const prefixLength = getLength(client, msg, prefix);
  return {
    command: msg.content.slice(prefixLength).trim().split(" ")[0].toLowerCase(),
    prefix,
    prefixLength,
  };
};

const getLength = (client, msg, prefix) => {
  if (client.config.prefixMention === prefix) return prefix.exec(msg.content)[0].length + 1;
  return prefix.exec(msg.content)[0].length;
};
<commit_msg>Appease Kyra senpai<commit_after>/* eslint-disable no-use-before-define */

const levenshtein = require("fast-levenshtein");

exports.run = async (client, msg) => {
  if (msg.author.bot) return;
  if (client.config.selfbot && msg.author.id !== client.user.id) return;

  const info = parseCommand(client, msg);
  const { prefixLength, command, prefix } = info;
  if (!prefixLength) return;
  if (command.length && !(client.commands.has(command) || client.aliases.has(command))) {
    const distances = [];
    client.commands.filter(c => c.conf.permLevel <= msg.member.permLevel).forEach((val, cmd) => distances.push({
      dist: levenshtein.get(cmd, command),
      cmd,
    }));
    distances.sort((a, b) => (a.score < b.score ? 1 : -1));
    if (distances[0] && distances[0].dist <= 1) {
      const message = await msg.channel.send(`|\`❔\`| Did you mean \`${prefix + distances[0].cmd}\`?`);
      if (message.deletable) message.delete({ timeout: 10000 });
    }
  }
};

exports.conf = {
  enabled: true,
  requiredModules: ["fast-levenshtein"],
};

exports.help = {
  name: "didyoumean",
  type: "monitors",
  description: "Helps users that type in commands incorrectly.",
};

const parseCommand = async (client, msg) => {
  const prefix = client.funcs.getPrefix(client, msg);
  if (!prefix) return false;
  const prefixLength = getLength(client, msg, prefix);
  return {
    command: msg.content.slice(prefixLength).trim().split(" ")[0].toLowerCase(),
    prefix,
    prefixLength,
  };
};

const getLength = (client, msg, prefix) => {
  if (client.config.prefixMention === prefix) return prefix.exec(msg.content)[0].length + 1;
  return prefix.exec(msg.content)[0].length;
};
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const jetpack = require('fs-jetpack');

import {SET_SOUNDS, SELECT_SOUND, SPAWN_SYNTH, SET_MASTER_CONTROLS} from '../actionTypes';
import callActionOnMain from '../ipc/callActionOnMain';

/**
 * Load synthdefs from included sound directory
 */
export function loadSounds(synthDefsDir) {
  return (dispatch) => {
    fs.readdir(synthDefsDir, (err, files) => {
      if (err) {
        throw new Error(err);
      }

      let sounds = [];

      files.forEach((p) => {
        // should be objects with synthdef descriptions
        // loaded from ?
        //
        if (path.extname(p) === '.json' && (p !== 'master.json')) {
          let fullpath = path.join(synthDefsDir, p);
          let data = jetpack.read(fullpath, 'json');
          data.path = fullpath;
          sounds.push(data);
        }
      });

      dispatch(setSounds(sounds));
    });
  };
}

/**
 * Set sounds (objects with synthdef descriptions) to store
 */
export function setSounds(sounds) {
  return {
    type: SET_SOUNDS,
    payload: sounds
  };
}

/**
 * Select sound by name from interface
 */
export function selectSound(name) {
  return {
    type: SELECT_SOUND,
    payload: name
  };
}

export function spawnSynth(event) {
  callActionOnMain({
    type: SPAWN_SYNTH,
    payload: event
  });
}

export function setMasterControls(event) {
  callActionOnMain({
    type: SET_MASTER_CONTROLS,
    payload: event
  });
}
<commit_msg>comments<commit_after>const fs = require('fs');
const path = require('path');
const jetpack = require('fs-jetpack');

import {SET_SOUNDS, SELECT_SOUND, SPAWN_SYNTH, SET_MASTER_CONTROLS} from '../actionTypes';
import callActionOnMain from '../ipc/callActionOnMain';

/**
 * Load synthdefs from included sound directory
 */
export function loadSounds(synthDefsDir) {
  return (dispatch) => {
    fs.readdir(synthDefsDir, (err, files) => {
      if (err) {
        throw new Error(err);
      }

      let sounds = [];

      files.forEach((p) => {
        // should be objects with synthdef descriptions
        // loaded from ?
        //
        if (path.extname(p) === '.json' && (p !== 'master.json')) {
          let fullpath = path.join(synthDefsDir, p);
          let data = jetpack.read(fullpath, 'json');
          data.path = fullpath;
          sounds.push(data);
        }
      });

      dispatch(setSounds(sounds));
    });
  };
}

/**
 * Set sounds (objects with synthdef descriptions) to store
 */
export function setSounds(sounds) {
  return {
    type: SET_SOUNDS,
    payload: sounds
  };
}

/**
 * Select sound by name from interface
 */
export function selectSound(name) {
  return {
    type: SELECT_SOUND,
    payload: name
  };
}

/**
 * Spawn a Synth (from a brush event)
 */
export function spawnSynth(event) {
  callActionOnMain({
    type: SPAWN_SYNTH,
    payload: event
  });
}

/**
 * Set master level controls.
 *
 * amp:
 */
export function setMasterControls(event) {
  callActionOnMain({
    type: SET_MASTER_CONTROLS,
    payload: event
  });
}
<|endoftext|>


<commit_before>require('babel-polyfill');
var childProcess = require('child_process');
var http = require("http");
var httpProxy = require('http-proxy');
var spawn = childProcess.spawn;
var ServiceManager = require('./service_manager');
var app = http.createServer(dispatch);
var proxy = httpProxy.createProxyServer({ ws: true });
var config = require('./config');
var promisify = require('promisify-node');
var fs = promisify('fs');
var gitClone = require('git-clone');
var portForwardMatcher = /\/port\/([0-9]+)(\/.*)/;

process.on('unhandledRejection', function(reason, p){
  console.log("Possibly Unhandled Rejection at: Promise ", p, " reason: ", reason);
});

function startLivelyServerInBackground() {
  console.log("start lively server")
  if (!fs.existsSync(config.logsDir)){
    fs.mkdirSync(config.logsDir);
  }

  out = fs.openSync('./logs/lively-server.log', 'a');
  err = fs.openSync('./logs/lively-server.log', 'a');

  var livelyServerProcess = spawn('node', [
      config.LIVELY_SERVER_PATH,
      '--port=' + config.LIVELY_SERVER_PORT,
      '--directory=services'
    ], {
    stdio: [ 'ignore', out, err ]
  });

  console.log('lively-server (#' + livelyServerProcess.pid + ') is listenting on ' +
              config.LIVELY_SERVER_PORT + '...');
}

function dispatch(req, res) {
  // Set CORS headers
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Request-Method', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');

  if (req.url.indexOf("/mount/") === 0) {
    req.url = req.url.substr('/mount'.length, req.url.length);
    proxy.web(req, res, {
      target: 'http://localhost:' + config.LIVELY_SERVER_PORT
    });
    return;
  }

  if (req.url.indexOf("/debug/") === 0) {
    req.url = req.url.substr('/debug'.length, req.url.length);
    proxy.web(req, res, {
      target: 'http://localhost:' + config.NODE_INSPECTOR_WEB_PORT
    });
    return;
  }

  var matches = portForwardMatcher.exec(req.url);
  if (matches) {
    var port = matches[1];
    req.url = matches[2];
    proxy.web(req, res, {
      target: 'http://localhost:' + parseInt(port)
    });
    return;
  }

  if (req.method === "GET") {
    if (req.url === "/") {
      return jsonResponse(res, { status: 'running' });
    } else if (req.url === "/list") {
      return jsonResponse(res, ServiceManager.listProcesses());
    } else {
      notFound(res);
    }
  } else if (req.method === "POST") {
    var body = [];
    req.on('data', function(chunk) {
      body.push(chunk);
    }).on('end', function() {
      body = Buffer.concat(body).toString();
      try {
        var data = JSON.parse(body);
        if (req.url === "/get") {
          postGet(req, res, data);
        } else if (req.url === "/start") {
          postStart(req, res, data);
        } else if (req.url === "/clone") {
          postClone(req, res, data);
        } else if (req.url === "/stop") {
          postStop(req, res, data);
        } else if (req.url === "/remove") {
          postRemove(req, res, data);
        } else {
          notFound(res);
        }
      } catch (ex) {
        console.error(ex);
      }
   });
  } else if (req.method === "OPTIONS") {
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    res.writeHead(200);
    res.end();
  } else {
    notFound(res);
  }
}

function postGet(req, res, data) {
  return ServiceManager.getProcessInfo(data.id).then(function(info) {
    return jsonResponse(res, info);
  }).catch(function(error) {
    return jsonResponse(res, { status: 'failed', message: error });
  });
}

function postStart(req, res, data) {
  var promise;
  if (data.id !== undefined && ServiceManager.serviceExists(data.id)) {
    ServiceManager.killProcess(data.id);
    promise = Promise.resolve();
  } else {
    promise = ServiceManager.addService(data.entryPoint).then(function(id) {
      data.id = id;
    });
  }
  promise.then(function() {
    ServiceManager.spawnProcess(data.id);
    jsonResponse(res, { status: 'success', pid: data.id });
  }).catch(function(error) {
    jsonResponse(res, { status: 'failed', message: error });
  });
}
function postClone(req, res, data) {
  var repoUrl = data.url;
  var repoName = repoUrl.split("/").slice(-1)[0].split(".git")[0];
  var dirName = config.servicesDir + "/" + repoName;
  gitClone(repoUrl, dirName, function(error) {
    if (error) {
      jsonResponse(res, { status: 'failed', message: error });
    } else {
      var npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
      var npmInstall = spawn(npm, ["install", "--dev"], {cwd : dirName});
      npmInstall.stdout.on('data', function(data) {
        console.log(data.toString());
      });
      npmInstall.stderr.on('data', function(data) {
        console.log(data.toString());
      });
      npmInstall.on('close', function(exitCode) {
        jsonResponse(res, { status: 'success'});
      });
    }
  });
}
function postStop(req, res, data) {
  ServiceManager.killProcess(data.id);
  return jsonResponse(res, { status: 'success' });
}
function postRemove(req, res, data) {
  ServiceManager.removeProcess(data.id);
  return jsonResponse(res, { status: 'success'});
}

function notFound(res) {
  res.writeHead(404);
  res.end();
}

function jsonResponse(res, obj) {
  res.writeHead(200, {
    'Content-Type': 'application/json'
  });
  res.end(JSON.stringify(obj));
}

app.on('upgrade', function (req, socket, head) {
  var matches = portForwardMatcher.exec(req.url);
  if (matches) {
    var port = matches[1];
    req.url = matches[2];
    proxy.ws(req, socket, head, {
      target: 'ws://localhost:' + parseInt(port)
    });
    return;
  }
  proxy.ws(req, socket, head, {
      target: 'ws://localhost:' + config.NODE_INSPECTOR_WEB_PORT
    });
});

function start(cb) {
  app.listen(config.PORT, function () {
    startLivelyServerInBackground();
    ServiceManager.startDebugServer();
    console.log('Listening on port ' + config.PORT + '...');
    if (cb) {
      cb();
    }
  });
}

if (!module.parent) {
  // the script was directly executed
  start();
}

module.exports = {
  start: start
};
<commit_msg>AUTO-COMMIT index.js<commit_after>require('babel-polyfill');
var childProcess = require('child_process');
var http = require("http");
var httpProxy = require('http-proxy');
var spawn = childProcess.spawn;
var ServiceManager = require('./service_manager');
var app = http.createServer(dispatch);
var proxy = httpProxy.createProxyServer({ ws: true });
var config = require('./config');
var promisify = require('promisify-node');
var fs = promisify('fs');
var gitClone = require('git-clone');
var portForwardMatcher = /\/port\/([0-9]+)(\/.*)/;

process.on('unhandledRejection', function(reason, p){
  console.log("Possibly Unhandled Rejection at: Promise ", p, " reason: ", reason);
});

function startLivelyServerInBackground() {
  console.log("start lively server")
  if (!fs.existsSync(config.logsDir)){
    fs.mkdirSync(config.logsDir);
  }

  out = fs.openSync('./logs/lively-server.log', 'a');
  err = fs.openSync('./logs/lively-server.log', 'a');

  var livelyServerProcess = spawn('node', [
      config.LIVELY_SERVER_PATH,
      '--port=' + config.LIVELY_SERVER_PORT,
      '--directory=services',
      '--server='+config.LIVELY_SERVER_DIR,
      '--auto-commit=true',
      '--index-files=false'
    ], {
    stdio: [ 'ignore', out, err ]
  });

  console.log('lively-server (#' + livelyServerProcess.pid + ') is listenting on ' +
              config.LIVELY_SERVER_PORT + '...');
}

function dispatch(req, res) {
  // Set CORS headers
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Request-Method', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');

  if (req.url.indexOf("/mount/") === 0) {
    req.url = req.url.substr('/mount'.length, req.url.length);
    proxy.web(req, res, {
      target: 'http://localhost:' + config.LIVELY_SERVER_PORT
    });
    return;
  }

  if (req.url.indexOf("/debug/") === 0) {
    req.url = req.url.substr('/debug'.length, req.url.length);
    proxy.web(req, res, {
      target: 'http://localhost:' + config.NODE_INSPECTOR_WEB_PORT
    });
    return;
  }

  var matches = portForwardMatcher.exec(req.url);
  if (matches) {
    var port = matches[1];
    req.url = matches[2];
    proxy.web(req, res, {
      target: 'http://localhost:' + parseInt(port)
    });
    return;
  }

  if (req.method === "GET") {
    if (req.url === "/") {
      return jsonResponse(res, { status: 'running' });
    } else if (req.url === "/list") {
      return jsonResponse(res, ServiceManager.listProcesses());
    } else {
      notFound(res);
    }
  } else if (req.method === "POST") {
    var body = [];
    req.on('data', function(chunk) {
      body.push(chunk);
    }).on('end', function() {
      body = Buffer.concat(body).toString();
      try {
        var data = JSON.parse(body);
        if (req.url === "/get") {
          postGet(req, res, data);
        } else if (req.url === "/start") {
          postStart(req, res, data);
        } else if (req.url === "/clone") {
          postClone(req, res, data);
        } else if (req.url === "/stop") {
          postStop(req, res, data);
        } else if (req.url === "/remove") {
          postRemove(req, res, data);
        } else {
          notFound(res);
        }
      } catch (ex) {
        console.error(ex);
      }
   });
  } else if (req.method === "OPTIONS") {
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    res.writeHead(200);
    res.end();
  } else {
    notFound(res);
  }
}

function postGet(req, res, data) {
  return ServiceManager.getProcessInfo(data.id).then(function(info) {
    return jsonResponse(res, info);
  }).catch(function(error) {
    return jsonResponse(res, { status: 'failed', message: error });
  });
}

function postStart(req, res, data) {
  var promise;
  if (data.id !== undefined && ServiceManager.serviceExists(data.id)) {
    ServiceManager.killProcess(data.id);
    promise = Promise.resolve();
  } else {
    promise = ServiceManager.addService(data.entryPoint).then(function(id) {
      data.id = id;
    });
  }
  promise.then(function() {
    ServiceManager.spawnProcess(data.id);
    jsonResponse(res, { status: 'success', pid: data.id });
  }).catch(function(error) {
    jsonResponse(res, { status: 'failed', message: error });
  });
}
function postClone(req, res, data) {
  var repoUrl = data.url;
  var repoName = repoUrl.split("/").slice(-1)[0].split(".git")[0];
  var dirName = config.servicesDir + "/" + repoName;
  gitClone(repoUrl, dirName, function(error) {
    if (error) {
      jsonResponse(res, { status: 'failed', message: error });
    } else {
      var npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
      var npmInstall = spawn(npm, ["install", "--dev"], {cwd : dirName});
      npmInstall.stdout.on('data', function(data) {
        console.log(data.toString());
      });
      npmInstall.stderr.on('data', function(data) {
        console.log(data.toString());
      });
      npmInstall.on('close', function(exitCode) {
        jsonResponse(res, { status: 'success'});
      });
    }
  });
}
function postStop(req, res, data) {
  ServiceManager.killProcess(data.id);
  return jsonResponse(res, { status: 'success' });
}
function postRemove(req, res, data) {
  ServiceManager.removeProcess(data.id);
  return jsonResponse(res, { status: 'success'});
}

function notFound(res) {
  res.writeHead(404);
  res.end();
}

function jsonResponse(res, obj) {
  res.writeHead(200, {
    'Content-Type': 'application/json'
  });
  res.end(JSON.stringify(obj));
}

app.on('upgrade', function (req, socket, head) {
  var matches = portForwardMatcher.exec(req.url);
  if (matches) {
    var port = matches[1];
    req.url = matches[2];
    proxy.ws(req, socket, head, {
      target: 'ws://localhost:' + parseInt(port)
    });
    return;
  }
  proxy.ws(req, socket, head, {
      target: 'ws://localhost:' + config.NODE_INSPECTOR_WEB_PORT
    });
});

function start(cb) {
  app.listen(config.PORT, function () {
    startLivelyServerInBackground();
    ServiceManager.startDebugServer();
    console.log('Listening on port ' + config.PORT + '...');
    if (cb) {
      cb();
    }
  });
}

if (!module.parent) {
  // the script was directly executed
  start();
}

module.exports = {
  start: start
};
<|endoftext|>


<commit_before>/* eslint consistent-return: 0, no-else-return: 0*/
import { polyfill } from 'es6-promise';
import request from 'axios';
import md5 from 'spark-md5';
import * as types from 'types';

polyfill();

/*
 * Utility function to make AJAX requests using isomorphic fetch.
 * You can also use jquery's $.ajax({}) if you do not want to use the
 * /fetch API.
 * Note: this function relies on an external variable `API_ENDPOINT`
 *        and isn't a pure function
 * @param Object Data you wish to pass to the server
 * @param String HTTP method, e.g. post, get, put, delete
 * @param String endpoint
 * @return Promise
 */
export function makeTopicRequest(method, id, data, api = '/questionnaire') {
  // console.log('method', method);
  // console.log('id', id);
  return request[method](api + (id && method !== 'post' ? ('/' + id) : ''), data);
}

export function destroy(index) {
  return { type: types.DESTROY_TOPIC, index };
}

export function typing(text) {
  return {
    type: types.TYPING,
    newTopic: text
  };
}

/*
 * @param data
 * @return a simple JS object
 */
export function createTopicRequest(data) {
  return {
    type: types.CREATE_TOPIC_REQUEST,
    id: data.id,
    title: data.title,
    description: data.description,
    questionnaireType: data.questionnaireType
  };
}

export function createTopicSuccess() {
  return {
    type: types.CREATE_TOPIC_SUCCESS
  };
}

export function createTopicFailure(data) {
  return {
    type: types.CREATE_TOPIC_FAILURE,
    id: data.id,
    error: data.error
  };
}

export function createTopicDuplicate() {
  return {
    type: types.CREATE_TOPIC_DUPLICATE
  };
}

// This action creator returns a function,
// which will get executed by Redux-Thunk middleware
// This function does not need to be pure, and thus allowed
// to have side effects, including executing asynchronous API calls.
export function createTopic(formObj) {
  const title = formObj.title;
  const description = formObj.description;
  const questionnaireType = 'master';
  const questions = formObj.questions;

  return (dispatch, getState) => {
    // If the text box is empty
    if (title.trim().length <= 0) return;

    const id = md5.hash(title);
    // Redux thunk's middleware receives the store methods `dispatch`
    // and `getState` as parameters
    const { topic } = getState();

    const data = {
      id,
      title,
      description,
      questionnaireType,
      questions
    };

    // First dispatch an optimistic update
    dispatch(createTopicRequest(data));

    return makeTopicRequest('post', id, data)
      .then(res => {
        if (res.status === 200) {
          // We can actually dispatch a CREATE_TOPIC_SUCCESS
          // on success, but I've opted to leave that out
          // since we already did an optimistic update
          // We could return res.json();
          return dispatch(createTopicSuccess());
        }
      })
      .catch(() => {
        return dispatch(createTopicFailure({ id, error: 'Oops! Something went wrong and we couldn\'t create your topic'}));
      });
  };
}

// Fetch posts logic
export function fetchTopics() {
  return {
    type: types.GET_TOPICS,
    promise: makeTopicRequest('get')
  };
}

export function destroyTopic(id, index) {
  return dispatch => {
    return makeTopicRequest('delete', id)
      .then(() => dispatch(destroy(index)))
      .catch(() => dispatch(createTopicFailure({id,
        error: 'Oops! Something went wrong and we couldn\'t add your vote'})));
  };
}
<commit_msg>redirect to home after saving a new questionnaire<commit_after>/* eslint consistent-return: 0, no-else-return: 0*/
import { polyfill } from 'es6-promise';
import request from 'axios';
import md5 from 'spark-md5';
import * as types from 'types';
import { push } from 'react-router-redux';

polyfill();

/*
 * Utility function to make AJAX requests using isomorphic fetch.
 * You can also use jquery's $.ajax({}) if you do not want to use the
 * /fetch API.
 * Note: this function relies on an external variable `API_ENDPOINT`
 *        and isn't a pure function
 * @param Object Data you wish to pass to the server
 * @param String HTTP method, e.g. post, get, put, delete
 * @param String endpoint
 * @return Promise
 */
export function makeTopicRequest(method, id, data, api = '/questionnaire') {
  // console.log('method', method);
  // console.log('id', id);
  return request[method](api + (id && method !== 'post' ? ('/' + id) : ''), data);
}

export function destroy(index) {
  return { type: types.DESTROY_TOPIC, index };
}

export function typing(text) {
  return {
    type: types.TYPING,
    newTopic: text
  };
}

/*
 * @param data
 * @return a simple JS object
 */
export function createTopicRequest(data) {
  return {
    type: types.CREATE_TOPIC_REQUEST,
    id: data.id,
    title: data.title,
    description: data.description,
    questionnaireType: data.questionnaireType
  };
}

export function createTopicSuccess() {
  return {
    type: types.CREATE_TOPIC_SUCCESS
  };
}

export function createTopicFailure(data) {
  return {
    type: types.CREATE_TOPIC_FAILURE,
    id: data.id,
    error: data.error
  };
}

export function createTopicDuplicate() {
  return {
    type: types.CREATE_TOPIC_DUPLICATE
  };
}

// This action creator returns a function,
// which will get executed by Redux-Thunk middleware
// This function does not need to be pure, and thus allowed
// to have side effects, including executing asynchronous API calls.
export function createTopic(formObj) {
  const title = formObj.title;
  const description = formObj.description;
  const questionnaireType = 'master';
  const questions = formObj.questions;

  return (dispatch, getState) => {
    // If the text box is empty
    if (title.trim().length <= 0) return;

    const id = md5.hash(title);
    // Redux thunk's middleware receives the store methods `dispatch`
    // and `getState` as parameters
    const { topic } = getState();

    const data = {
      id,
      title,
      description,
      questionnaireType,
      questions
    };

    // First dispatch an optimistic update
    dispatch(createTopicRequest(data));

    return makeTopicRequest('post', id, data)
      .then(res => {
        if (res.status === 200) {
          // We can actually dispatch a CREATE_TOPIC_SUCCESS
          // on success, but I've opted to leave that out
          // since we already did an optimistic update
          // We could return res.json();
          console.log("yoyoyoyoyo");
          dispatch(push('/'));
          return dispatch(createTopicSuccess());
        }
      })
      .catch(() => {
        return dispatch(createTopicFailure({ id, error: 'Oops! Something went wrong and we couldn\'t create your topic'}));
      });
  };
}

// Fetch posts logic
export function fetchTopics() {
  return {
    type: types.GET_TOPICS,
    promise: makeTopicRequest('get')
  };
}

export function destroyTopic(id, index) {
  return dispatch => {
    return makeTopicRequest('delete', id)
      .then(() => dispatch(destroy(index)))
      .catch(() => dispatch(createTopicFailure({id,
        error: 'Oops! Something went wrong and we couldn\'t add your vote'})));
  };
}
<|endoftext|>


<commit_before>
'use strict';

/**
 * index.js
 *
 * App entry point
 */

var fs = require('mz/fs')
var cuid = require('cuid')
var sharp = require('sharp')
var busboy = require('co-busboy')
var mimetypes = require('mime-types')
var mongo = require('yieldb').connect
var escapeString = require('escape-string-regexp')

var koa = require('koa')
var logger = require('koa-logger')
var bodyParser = require('koa-bodyparser')
var routerFactory = require('koa-router')
var staticFile = require('koa-static')

var templateLoader = require('./templates/marko-template-loader')
var homeTemplate = templateLoader('./home.marko')
var shotTemplate = templateLoader('./shot.marko')
var searchTemplate = templateLoader('./search.marko')
var recentTemplate = templateLoader('./recent.marko')
var analyticsTemplate = templateLoader('./analytics.marko')
var headerTemplate = templateLoader('./header.marko')
var searchBoxTemplate = templateLoader('./search-box.marko')
var pagingTemplate = templateLoader('./paging.marko')
var commonMetaTemplate = templateLoader('./common-meta.marko')

var tmpDirectory = 'upload-tmp/'
var uploadDirectory = 'public/upload/'
var databaseUrl = 'mongodb://localhost:27017/animeshot?w=1'
var siteDomain = 'https://as.bitinn.net'
var assetRevision = 'r2'

var app = koa()
var router = routerFactory()
var mongoConnection

app.use(logger())

// only serve file from node.js during development
if (app.env === 'dev') {
	app.use(staticFile('public', {
		maxage: 1000 * 60 * 60 * 24
	}))
}

// database connection
app.use(function *(next) {
	try {
		if (!mongoConnection) {
			mongoConnection = yield mongo(databaseUrl)
		}
		this.db = mongoConnection
	} catch(err) {
		this.db = false
		this.app.emit('error', err, this)
	}

	yield next
})

// error handler
app.use(function *(next) {
	if (this.db === false) {
		this.status = 500
		this.body = 'mongodb down'
		return
	}

	try {
		yield next
	} catch (err) {
		this.app.emit('error', err, this)
		this.status = 500
		this.body = 'internal error'
		return
	}
})

app.use(bodyParser())

// home page
router.get('/', function *(next) {
	yield next
	var db = this.db
	var Shots = db.col('shots')
	var result = yield Shots.find().sort({ created: -1 }).limit(4)
	var data = {
		shots: result
		, analytics: analyticsTemplate
		, header: headerTemplate
		, searchBox: searchBoxTemplate
		, meta: commonMetaTemplate
		, rev: assetRevision
	}
	this.body = homeTemplate.renderSync(data)
})

// shot page
router.get('/shots/:id', function *(next) {
	yield next
	var db = this.db
	var Shots = db.col('shots')
	var shot = yield Shots.findOne({ sid: this.params.id })
	if (!shot) {
		this.redirect('/')
		return
	}
	var data = {
		text: shot.text
		, sid: shot.sid
		, size: ['300', '600', '1200']
		, domain: siteDomain
		, analytics: analyticsTemplate
		, header: headerTemplate
		, searchBox: searchBoxTemplate
		, meta: commonMetaTemplate
		, rev: assetRevision
	}
	this.body = shotTemplate.renderSync(data)
})

// search page
router.get('/search', function *(next) {
	yield next
	var db = this.db
	var Shots = db.col('shots')
	var result = []
	if (!!this.query.q && this.query.q.length > 0 && this.query.q.length < 100) {
		result = yield Shots.find({
			text: {
				$regex: new RegExp('(.*)' + escapeString(this.query.q) + '(.*)', 'i')
			}
		}).sort({ created: -1 }).limit(20)
	}
	var data = {
		shots: result
		, q: this.query.q
		, analytics: analyticsTemplate
		, header: headerTemplate
		, searchBox: searchBoxTemplate
		, paging: pagingTemplate
		, meta: commonMetaTemplate
		, rev: assetRevision
		, next: result.length === 20 ? 2 : 1
		, page: 'search'
	}
	this.body = searchTemplate.renderSync(data)
})

// search paging
router.get('/search/page/:page', function *(next) {
	yield next
	var db = this.db
	var page = parseInt(this.params.page, 10) || 1
	if (page < 1) {
		this.redirect('/recent')
		return
	}
	var Shots = db.col('shots')
	var result = []
	if (!!this.query.q && this.query.q.length > 0 && this.query.q.length < 100) {
		result = yield Shots.find({
			text: {
				$regex: new RegExp('(.*)' + escapeString(this.query.q) + '(.*)', 'i')
			}
		}).sort({ created: -1 }).limit(20).skip((page - 1) * 20)
	}
	var data = {
		shots: result
		, q: this.query.q
		, analytics: analyticsTemplate
		, header: headerTemplate
		, searchBox: searchBoxTemplate
		, paging: pagingTemplate
		, meta: commonMetaTemplate
		, rev: assetRevision
		, prev: page - 1
		, next: result.length === 20 ? page + 1 : 1
		, page: 'search'
	}
	this.body = searchTemplate.renderSync(data)
})

// recent page
router.get('/recent', function *(next) {
	yield next
	var db = this.db
	var Shots = db.col('shots')
	var result = yield Shots.find().sort({ created: -1 }).limit(20)
	var data = {
		shots: result
		, analytics: analyticsTemplate
		, header: headerTemplate
		, searchBox: searchBoxTemplate
		, paging: pagingTemplate
		, meta: commonMetaTemplate
		, rev: assetRevision
		, next: result.length === 20 ? 2 : 1
		, page: 'recent'
	}
	this.body = recentTemplate.renderSync(data)
})

// recent paging
router.get('/recent/page/:page', function *(next) {
	yield next
	var db = this.db
	var page = parseInt(this.params.page, 10) || 1
	if (page < 1) {
		this.redirect('/recent')
		return
	}
	var Shots = db.col('shots')
	var result = yield Shots.find().sort({ created: -1 }).limit(20).skip((page - 1) * 20)
	var data = {
		shots: result
		, analytics: analyticsTemplate
		, header: headerTemplate
		, searchBox: searchBoxTemplate
		, paging: pagingTemplate
		, meta: commonMetaTemplate
		, rev: assetRevision
		, prev: page - 1
		, next: result.length === 20 ? page + 1 : 1
		, page: 'recent'
	}
	this.body = recentTemplate.renderSync(data)
})

// file upload
router.post('/api/files', function *(next) {
	yield next
	var headers = this.headers
	var body = busboy(this, {
		autoFields: true
		, checkFile: function (fn, file, name, enc, mime) {
			var ext = mimetypes.extension(mime)
			if (ext !== 'jpeg' && ext !== 'png') {
				return new Error('file type not supported')
			}
		}
	})
	var part, p1, p2, p3, hash, s1
	while (part = yield body) {
		hash = cuid()
		s1 = sharp().limitInputPixels(4000 * 4000)
		s1 = part.pipe(s1)
		p1 = s1.clone().resize(300).quality(95).toFile(tmpDirectory + hash + '.300.jpg')
		p2 = s1.clone().resize(600).quality(95).toFile(tmpDirectory + hash + '.600.jpg')
		p3 = s1.clone().resize(1200).quality(95).toFile(tmpDirectory + hash + '.1200.jpg')
		yield Promise.all([p1, p2, p3])
	}
	this.body = hash
})

// create shot
router.post('/api/shots', function *(next) {
	yield next
	var db = this.db
	var body = this.request.body
	var hash = body.hash.replace(/\W/g, '').substr(0, 25)
	var text = body.text.substr(0, 140)
	var size = [300, 600, 1200]
	var filename
	for (var i = 0; i < size.length; i++) {
		filename = hash + '.' + size[i] + '.jpg'
		yield fs.rename(tmpDirectory + filename, uploadDirectory + filename)
	}
	var Shots = db.col('shots')
	var now = new Date()
	yield Shots.insert({
		sid: hash
		, text: text
		, created: now
		, updated: now
	})
	this.body = 'done'
})

router.get('/api/shots', function *(next) {
	yield next
	var db = this.db
	var page = parseInt(this.query.page, 10) > 1 ? parseInt(this.query.page, 10) : 1
	var Shots = db.col('shots')
	var search = {}
	var result
	if (!!this.query.q && this.query.q.length > 0 && this.query.q.length < 100) {
		search.text = {
			$regex: new RegExp('(.*)' + escapeString(this.query.q) + '(.*)', 'i')
		}
	}
	result = yield Shots.find(search).sort({ created: -1 }).limit(20).skip((page - 1) * 20)
	var data = result.map(function (shot) {
		delete shot._id
		shot.url = siteDomain + '/shots/' + shot.sid
		shot.image_thumbnail = siteDomain + '/upload/' + shot.sid + '.300.jpg'
		shot.image_preview = siteDomain + '/upload/' + shot.sid + '.600.jpg'
		shot.image_large = siteDomain + '/upload/' + shot.sid + '.1200.jpg'
		return shot
	})
	this.body = data
})

app.use(router.routes())
app.use(router.allowedMethods())

if (app.env === 'dev') {
	app.listen(8080)
} else {
	app.listen(8081)
}
<commit_msg>bump asset revision<commit_after>
'use strict';

/**
 * index.js
 *
 * App entry point
 */

var fs = require('mz/fs')
var cuid = require('cuid')
var sharp = require('sharp')
var busboy = require('co-busboy')
var mimetypes = require('mime-types')
var mongo = require('yieldb').connect
var escapeString = require('escape-string-regexp')

var koa = require('koa')
var logger = require('koa-logger')
var bodyParser = require('koa-bodyparser')
var routerFactory = require('koa-router')
var staticFile = require('koa-static')

var templateLoader = require('./templates/marko-template-loader')
var homeTemplate = templateLoader('./home.marko')
var shotTemplate = templateLoader('./shot.marko')
var searchTemplate = templateLoader('./search.marko')
var recentTemplate = templateLoader('./recent.marko')
var analyticsTemplate = templateLoader('./analytics.marko')
var headerTemplate = templateLoader('./header.marko')
var searchBoxTemplate = templateLoader('./search-box.marko')
var pagingTemplate = templateLoader('./paging.marko')
var commonMetaTemplate = templateLoader('./common-meta.marko')

var tmpDirectory = 'upload-tmp/'
var uploadDirectory = 'public/upload/'
var databaseUrl = 'mongodb://localhost:27017/animeshot?w=1'
var siteDomain = 'https://as.bitinn.net'
var assetRevision = 'r3'

var app = koa()
var router = routerFactory()
var mongoConnection

app.use(logger())

// only serve file from node.js during development
if (app.env === 'dev') {
	app.use(staticFile('public', {
		maxage: 1000 * 60 * 60 * 24
	}))
}

// database connection
app.use(function *(next) {
	try {
		if (!mongoConnection) {
			mongoConnection = yield mongo(databaseUrl)
		}
		this.db = mongoConnection
	} catch(err) {
		this.db = false
		this.app.emit('error', err, this)
	}

	yield next
})

// error handler
app.use(function *(next) {
	if (this.db === false) {
		this.status = 500
		this.body = 'mongodb down'
		return
	}

	try {
		yield next
	} catch (err) {
		this.app.emit('error', err, this)
		this.status = 500
		this.body = 'internal error'
		return
	}
})

app.use(bodyParser())

// home page
router.get('/', function *(next) {
	yield next
	var db = this.db
	var Shots = db.col('shots')
	var result = yield Shots.find().sort({ created: -1 }).limit(4)
	var data = {
		shots: result
		, analytics: analyticsTemplate
		, header: headerTemplate
		, searchBox: searchBoxTemplate
		, meta: commonMetaTemplate
		, rev: assetRevision
	}
	this.body = homeTemplate.renderSync(data)
})

// shot page
router.get('/shots/:id', function *(next) {
	yield next
	var db = this.db
	var Shots = db.col('shots')
	var shot = yield Shots.findOne({ sid: this.params.id })
	if (!shot) {
		this.redirect('/')
		return
	}
	var data = {
		text: shot.text
		, sid: shot.sid
		, size: ['300', '600', '1200']
		, domain: siteDomain
		, analytics: analyticsTemplate
		, header: headerTemplate
		, searchBox: searchBoxTemplate
		, meta: commonMetaTemplate
		, rev: assetRevision
	}
	this.body = shotTemplate.renderSync(data)
})

// search page
router.get('/search', function *(next) {
	yield next
	var db = this.db
	var Shots = db.col('shots')
	var result = []
	if (!!this.query.q && this.query.q.length > 0 && this.query.q.length < 100) {
		result = yield Shots.find({
			text: {
				$regex: new RegExp('(.*)' + escapeString(this.query.q) + '(.*)', 'i')
			}
		}).sort({ created: -1 }).limit(20)
	}
	var data = {
		shots: result
		, q: this.query.q
		, analytics: analyticsTemplate
		, header: headerTemplate
		, searchBox: searchBoxTemplate
		, paging: pagingTemplate
		, meta: commonMetaTemplate
		, rev: assetRevision
		, next: result.length === 20 ? 2 : 1
		, page: 'search'
	}
	this.body = searchTemplate.renderSync(data)
})

// search paging
router.get('/search/page/:page', function *(next) {
	yield next
	var db = this.db
	var page = parseInt(this.params.page, 10) || 1
	if (page < 1) {
		this.redirect('/recent')
		return
	}
	var Shots = db.col('shots')
	var result = []
	if (!!this.query.q && this.query.q.length > 0 && this.query.q.length < 100) {
		result = yield Shots.find({
			text: {
				$regex: new RegExp('(.*)' + escapeString(this.query.q) + '(.*)', 'i')
			}
		}).sort({ created: -1 }).limit(20).skip((page - 1) * 20)
	}
	var data = {
		shots: result
		, q: this.query.q
		, analytics: analyticsTemplate
		, header: headerTemplate
		, searchBox: searchBoxTemplate
		, paging: pagingTemplate
		, meta: commonMetaTemplate
		, rev: assetRevision
		, prev: page - 1
		, next: result.length === 20 ? page + 1 : 1
		, page: 'search'
	}
	this.body = searchTemplate.renderSync(data)
})

// recent page
router.get('/recent', function *(next) {
	yield next
	var db = this.db
	var Shots = db.col('shots')
	var result = yield Shots.find().sort({ created: -1 }).limit(20)
	var data = {
		shots: result
		, analytics: analyticsTemplate
		, header: headerTemplate
		, searchBox: searchBoxTemplate
		, paging: pagingTemplate
		, meta: commonMetaTemplate
		, rev: assetRevision
		, next: result.length === 20 ? 2 : 1
		, page: 'recent'
	}
	this.body = recentTemplate.renderSync(data)
})

// recent paging
router.get('/recent/page/:page', function *(next) {
	yield next
	var db = this.db
	var page = parseInt(this.params.page, 10) || 1
	if (page < 1) {
		this.redirect('/recent')
		return
	}
	var Shots = db.col('shots')
	var result = yield Shots.find().sort({ created: -1 }).limit(20).skip((page - 1) * 20)
	var data = {
		shots: result
		, analytics: analyticsTemplate
		, header: headerTemplate
		, searchBox: searchBoxTemplate
		, paging: pagingTemplate
		, meta: commonMetaTemplate
		, rev: assetRevision
		, prev: page - 1
		, next: result.length === 20 ? page + 1 : 1
		, page: 'recent'
	}
	this.body = recentTemplate.renderSync(data)
})

// file upload
router.post('/api/files', function *(next) {
	yield next
	var headers = this.headers
	var body = busboy(this, {
		autoFields: true
		, checkFile: function (fn, file, name, enc, mime) {
			var ext = mimetypes.extension(mime)
			if (ext !== 'jpeg' && ext !== 'png') {
				return new Error('file type not supported')
			}
		}
	})
	var part, p1, p2, p3, hash, s1
	while (part = yield body) {
		hash = cuid()
		s1 = sharp().limitInputPixels(4000 * 4000)
		s1 = part.pipe(s1)
		p1 = s1.clone().resize(300).quality(95).toFile(tmpDirectory + hash + '.300.jpg')
		p2 = s1.clone().resize(600).quality(95).toFile(tmpDirectory + hash + '.600.jpg')
		p3 = s1.clone().resize(1200).quality(95).toFile(tmpDirectory + hash + '.1200.jpg')
		yield Promise.all([p1, p2, p3])
	}
	this.body = hash
})

// create shot
router.post('/api/shots', function *(next) {
	yield next
	var db = this.db
	var body = this.request.body
	var hash = body.hash.replace(/\W/g, '').substr(0, 25)
	var text = body.text.substr(0, 140)
	var size = [300, 600, 1200]
	var filename
	for (var i = 0; i < size.length; i++) {
		filename = hash + '.' + size[i] + '.jpg'
		yield fs.rename(tmpDirectory + filename, uploadDirectory + filename)
	}
	var Shots = db.col('shots')
	var now = new Date()
	yield Shots.insert({
		sid: hash
		, text: text
		, created: now
		, updated: now
	})
	this.body = 'done'
})

router.get('/api/shots', function *(next) {
	yield next
	var db = this.db
	var page = parseInt(this.query.page, 10) > 1 ? parseInt(this.query.page, 10) : 1
	var Shots = db.col('shots')
	var search = {}
	var result
	if (!!this.query.q && this.query.q.length > 0 && this.query.q.length < 100) {
		search.text = {
			$regex: new RegExp('(.*)' + escapeString(this.query.q) + '(.*)', 'i')
		}
	}
	result = yield Shots.find(search).sort({ created: -1 }).limit(20).skip((page - 1) * 20)
	var data = result.map(function (shot) {
		delete shot._id
		shot.url = siteDomain + '/shots/' + shot.sid
		shot.image_thumbnail = siteDomain + '/upload/' + shot.sid + '.300.jpg'
		shot.image_preview = siteDomain + '/upload/' + shot.sid + '.600.jpg'
		shot.image_large = siteDomain + '/upload/' + shot.sid + '.1200.jpg'
		return shot
	})
	this.body = data
})

app.use(router.routes())
app.use(router.allowedMethods())

if (app.env === 'dev') {
	app.listen(8080)
} else {
	app.listen(8081)
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Microprofiler: export main function.
 * (C) 2014 Alex Fernández.
 */

// requires
var profiler = require('./lib/profiler.js');

// exports
exports.overwriteWith(profiler);

<commit_msg>Import prototypes in index.js.<commit_after>'use strict';

/**
 * Microprofiler: export main function.
 * (C) 2014 Alex Fernández.
 */

// requires
require('prototypes');
var profiler = require('./lib/profiler.js');

// exports
exports.overwriteWith(profiler);

<|endoftext|>


<commit_before>let mix = require('laravel-mix');

/**
 * We'll load jQuery globaly, uncomment if you need it's
 */

mix.autoload({
    jquery: ['$', 'window.jQuery']
});

mix.setPublicPath('./');
mix.js('resources/assets/js/app.js', 'js/app.min.js')
    .sass('resources/assets/sass/app.scss', 'css/app.min.css')
    .options({
        processCssUrls: false,
    })
    .browserSync({
        proxy: 'mini-framework.dev',
        files: [
            './resources/views/**/*.twig',
            './js/**/*',
            './css/**/*',
        ]
    })

<commit_msg>Removed jquery autoload<commit_after>let mix = require('laravel-mix');

mix.setPublicPath('./');

mix.sass('resources/assets/sass/app.scss', 'css/app.min.css')
    .js('resources/assets/js/app.js', 'js/app.min.js')
    .options({
        processCssUrls: false,
    })
    .browserSync({
        proxy: 'mini-framework.dev',
        files: [
            './resources/views/**/*.twig',
            './css/**/*.css',
            './js/**/*.js',
        ],
        injectChanges: true,
    })

<|endoftext|>


<commit_before>const fs            = require('fs');
const path          = require('path');
const panini        = require('panini');
const inky          = require('inky');
const siphon        = require('siphon-media-query');
const lazypipe      = require('lazypipe');

const gulp          = require('gulp');
const inlineCss     = require('gulp-inline-css');
const replace       = require('gulp-replace');
const htmlmin       = require('gulp-htmlmin');

class InkyMailOutput {
    constructor(tplPath) {
        this._tplPath       = tplPath;
        this._fullTplPath   = path.join(__dirname, this._tplPath);
        this._mailDataObj   = undefined;
        this._tplName       = undefined;
    }

    produceMail(emailTemplateName, emailConfObj, emailDataObj) {
        this._mailDataObj = {
            root: path.join(this._fullTplPath, emailConfObj.root),
            layouts: path.join(this._tplPath, emailConfObj.layouts),
            partials: path.join(this._tplPath, emailConfObj.partials),
            helpers: path.join(this._tplPath, emailConfObj.helpers),
            css: path.join(this._tplPath, emailConfObj.css),
            data: path.join(this._tplPath, emailConfObj.data)
        };
        this._mailContentObj = emailDataObj;
        this._tplName = emailTemplateName;

        // write tech data json file
        let techObj = {
            css: `../${emailConfObj.css}`
        };
        fs.writeFileSync(`${this._mailDataObj.data}/tech.json`, JSON.stringify(techObj), null, function(err) {
            if(err) return console.log('tech data error in file write: ', err);
        });

        // write main data json file
        let mainObj = {
            subject: emailConfObj.subject
        }
        fs.writeFileSync(`${this._mailDataObj.data}/main.json`, JSON.stringify(mainObj), null, function(err) {
            if(err) return console.log('main data error in file write: ', err);
        });

        // write data json file
        fs.writeFileSync(`${this._mailDataObj.data}/${this._tplName}.json`, JSON.stringify(this._mailContentObj), null, function(err) {
            if(err) return console.log('mail data error in file write: ', err);
        });

        return new Promise((resolve, reject) => {
            this.streamToString(this.buildMail(),
                function(resp) { resolve(resp); },
                function(error) { reject(error); }
            )
        });
    };

    buildMail() {
        return gulp.src(`${this._mailDataObj.root}/${this._tplName}.html`)
                .pipe(panini(this._mailDataObj))
                .pipe(inky())
                .pipe(this.inliner(this._mailDataObj.css))
    };

    streamToString(stream, successCB, errorCB) {
        let chunks = [];
        stream.on('data', function(chunk) {
            chunks.push(chunk);
        });
        stream.on('error', errorCB);
        stream.on('end', function() {
            // extract content string from Vinyl file object
            let fileContent = JSON.parse(JSON.stringify(chunks))[0];
            let bufferedData = new Buffer(fileContent._contents.data);
            successCB(bufferedData.toString());
        });
    };

    inliner(cssFilePath) {
        let css = fs.readFileSync(cssFilePath).toString();
        let mqCss = siphon(css);

        let pipe = lazypipe()
            .pipe(inlineCss, {
                applyStyleTags: false,
                removeStyleTags: true,
                preserveMediaQueries: true,
                removeLinkTags: false
            })
            .pipe(replace, '<!-- <style> -->', `<style>${mqCss}</style>`)
            .pipe(replace, '<link rel="stylesheet" type="text/css" href="css/app.css">', '')
            .pipe(htmlmin, {
                collapseWhitespace: true,
                minifyCSS: true
            });

        return pipe();
    }
}

/* Sample usage */
// provide relative root path to template assets folder
let instance = new InkyMailOutput('email-template');

// provide mail data & conf --> return promised processed email
instance.produceMail('dev-report', {
        root: 'pages',
        layouts: 'layouts',
        partials: 'partials',
        helpers: 'helpers',
        css: 'css/app.css', // must be repeated in tech data (relative to index.js)
        subject: 'Sprint 3 daily report - CPX Mobile - February 19th 2017, 9:37 am (GMT +1)',
        data: 'data'
    }, {
        reportTitle: 'Sprint daily report',
        reportReleaseSprint: 'EG-CPX Order Visibility R1 / Sprint 3',
        reportTopic:'CPX Mobile Report',
        reportDate: 'February 19th 2017, 9:37 am (GMT +1)',
        overallStatus: 'green',
        subStatuses: [
            { status: 'green', name: 'Portal-Portal Services', usCount: 15 },
            { status: 'green', name: 'Portal-Content Services and Search', usCount: 8 },
            { status: 'red', name: 'Portal-Integration Services', usCount: 2 },
            { status: 'yellow', name: 'Portal-User Services', usCount: 3 }
        ],
        overallIndicators: {
            blockedCount: 0,
            greenCount: 3,
            yellowCount: 2,
            redCount: 23,
            approvedCount: 28,
            approvedPercentage: 100,
            taskedCount: 25,
            taskedPercentage: 82,
            inProgressCount: 28,
            inProgressPercentage: 100,
            inTestingCount: 25,
            inTestingPercentage: 100,
            estimatedLOE: 153,
            currentLOE: 167,
            deviationPercentage: -9
        },
        backlog: {
            usCount: 28,
            backlogItems: [
                { id:4419, name:'rate delivery - feedback webservice [CPX backend]', team:'Portal-Portal Services', status:'In Testing', itStatus:'Green', br:92, link:'https://agilemanager-syd.saas.hp.com/agm/webui/alm/t718469238_hp_com/Channel_Partner_Portal/apm/@3OuIaATvClATx/?TENANTID=718469238#release/release_backlog/shared.update;entityTypeName=requirement;productGroupId=1000;entityId=4419' },
                { id:4449, name:'rate delivery - Feedback system data sharing (access to PRP database)', team:'Portal-Portal Services', status:'In Testing', itStatus:'Green', br:92, link:'https://agilemanager-syd.saas.hp.com/agm/webui/alm/t718469238_hp_com/Channel_Partner_Portal/apm/@3OuIaATvClATx/?TENANTID=718469238#release/release_backlog/shared.update;entityTypeName=requirement;productGroupId=1000;entityId=4449' },
                { id:4507, name:'in-app simulation : backend API modification to handle impersonate [CPX backend]', team:'Portal-Portal Services', status:'In Testing', itStatus:'Yellow', br:92, link:'https://agilemanager-syd.saas.hp.com/agm/webui/alm/t718469238_hp_com/Channel_Partner_Portal/apm/@3OuIaATvClATx/?TENANTID=718469238#release/release_backlog/shared.update;entityTypeName=requirement;productGroupId=1000;entityId=4419' },
                { id:4511, name:'Support Page in the Portal Internal Site to display mobile app data and monitoring data', team:'Portal-Portal Services', status:'In Testing', itStatus:'Red', br:92, link:'https://agilemanager-syd.saas.hp.com/agm/webui/alm/t718469238_hp_com/Channel_Partner_Portal/apm/@3OuIaATvClATx/?TENANTID=718469238#release/release_backlog/shared.update;entityTypeName=requirement;productGroupId=1000;entityId=4419' }
            ]
        },
        metaData: {
            scopeChangeHistory: [
                { date:'13th Dec 2016', unscoped:'', scoped:'#4419', comment:'added to scope (fixing inconsisitency)' },
                { date:'14th Dec 2016', unscoped:'#4673', scoped:'', comment:'removed form AGM' }
            ],
            risks: [
                { date:'6th Jan 2017', type:'Issue', description:'US - 4523 - Advanced Tibco Consumer : development complexity Difficult compregension, too much time passed on explanation', owner:'Hongbin Xu', dueDate:'10th Jan 2017', status:'yellow', comment:'prototype provided waiting for' },
                { date:'9th Jan 2017', type:'Issue', description:'Techdata beta users unable to see their orders in the mobile app Need reindexing on ITG, erfc scheduled for prod on Monday 16', owner:'David George', dueDate:'10th Jan 2017', status:'green', comment:'tested successfuly on ITG, waiting scheduling of erfc David G. availibility checked for next monday Backup identified for other day if erfc moved' }
            ],
            accomplishments: [
                { date:'1st Dec 2016', accomplishment:'Design started' },
                { date:'8th Dec 2016', accomplishment:'Scope lock' }
            ]
        }
    }
).then(
    function(resp) {
        console.log('successful email render');

        fs.writeFileSync(`email-sample.html`, resp, null, function(err) {
            if(err) return console.log('rendered mail HTMLdata error in file write: ', err);
        });
    },
    function(error) { console.log(error); }
);

module.exports = InkyMailOutput;<commit_msg>clean sample code from final code<commit_after>const fs            = require('fs');
const path          = require('path');
const panini        = require('panini');
const inky          = require('inky');
const siphon        = require('siphon-media-query');
const lazypipe      = require('lazypipe');

const gulp          = require('gulp');
const inlineCss     = require('gulp-inline-css');
const replace       = require('gulp-replace');
const htmlmin       = require('gulp-htmlmin');

class InkyMailOutput {
    constructor(tplPath) {
        this._tplPath       = tplPath;
        this._fullTplPath   = path.join(__dirname, this._tplPath);
        this._mailDataObj   = undefined;
        this._tplName       = undefined;
    }

    produceMail(emailTemplateName, emailConfObj, emailDataObj) {
        this._mailDataObj = {
            root: path.join(this._fullTplPath, emailConfObj.root),
            layouts: path.join(this._tplPath, emailConfObj.layouts),
            partials: path.join(this._tplPath, emailConfObj.partials),
            helpers: path.join(this._tplPath, emailConfObj.helpers),
            css: path.join(this._tplPath, emailConfObj.css),
            data: path.join(this._tplPath, emailConfObj.data)
        };
        this._mailContentObj = emailDataObj;
        this._tplName = emailTemplateName;

        // write tech data json file
        let techObj = {
            css: `../${emailConfObj.css}`
        };
        fs.writeFileSync(`${this._mailDataObj.data}/tech.json`, JSON.stringify(techObj), null, function(err) {
            if(err) return console.log('tech data error in file write: ', err);
        });

        // write main data json file
        let mainObj = {
            subject: emailConfObj.subject
        }
        fs.writeFileSync(`${this._mailDataObj.data}/main.json`, JSON.stringify(mainObj), null, function(err) {
            if(err) return console.log('main data error in file write: ', err);
        });

        // write data json file
        fs.writeFileSync(`${this._mailDataObj.data}/${this._tplName}.json`, JSON.stringify(this._mailContentObj), null, function(err) {
            if(err) return console.log('mail data error in file write: ', err);
        });

        return new Promise((resolve, reject) => {
            this.streamToString(this.buildMail(),
                function(resp) { resolve(resp); },
                function(error) { reject(error); }
            )
        });
    };

    buildMail() {
        return gulp.src(`${this._mailDataObj.root}/${this._tplName}.html`)
                .pipe(panini(this._mailDataObj))
                .pipe(inky())
                .pipe(this.inliner(this._mailDataObj.css))
    };

    streamToString(stream, successCB, errorCB) {
        let chunks = [];
        stream.on('data', function(chunk) {
            chunks.push(chunk);
        });
        stream.on('error', errorCB);
        stream.on('end', function() {
            // extract content string from Vinyl file object
            let fileContent = JSON.parse(JSON.stringify(chunks))[0];
            let bufferedData = new Buffer(fileContent._contents.data);
            successCB(bufferedData.toString());
        });
    };

    inliner(cssFilePath) {
        let css = fs.readFileSync(cssFilePath).toString();
        let mqCss = siphon(css);

        let pipe = lazypipe()
            .pipe(inlineCss, {
                applyStyleTags: false,
                removeStyleTags: true,
                preserveMediaQueries: true,
                removeLinkTags: false
            })
            .pipe(replace, '<!-- <style> -->', `<style>${mqCss}</style>`)
            .pipe(replace, '<link rel="stylesheet" type="text/css" href="css/app.css">', '')
            .pipe(htmlmin, {
                collapseWhitespace: true,
                minifyCSS: true
            });

        return pipe();
    }
}

module.exports = InkyMailOutput;<|endoftext|>


<commit_before>const { mix } = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');
<commit_msg>add webpack to support NPM packages<commit_after>let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.copy('node_modules/fullcalendar/main.css', 'public/plugins/fullcalendar/css/main.css');
mix.copy('node_modules/fullcalendar/main.js', 'public/plugins/fullcalendar/js/main.js');
mix.copy('node_modules/fullcalendar/main.min.js', 'public/plugins/fullcalendar/js/main.min.js');
mix.copy('node_modules/fullcalendar/locales/de.js', 'public/plugins/fullcalendar/locales/de.js');
mix.copy('node_modules/fullcalendar/locales-all.js', 'public/plugins/fullcalendar/locales-all.js');
mix.copy('node_modules/fullcalendar/locales-all.min.js', 'public/plugins/fullcalendar/locales-all.min.js');

//mix.js('resources/assets/js/app.js', 'public/js').sass('resources/assets/sass/app.scss', 'public/css');
<|endoftext|>


<commit_before>var path = require('path')
  , fs = require('fs')

var mkdirp = require('mkdirp')

var normal = path.normalize
  , join = path.join

var CWD = process.cwd()

module.exports = fs_back

function fs_back(_meta_dir, _user_dir, _tarballs_dir) {
  var tarballs_dir = normal(_tarballs_dir) || join(CWD, 'tarballs')
    , user_dir = normal(_user_dir) || join(CWD, 'users')
    , meta_dir = normal(_meta_dir) || join(CWD, 'meta')

  mkdirp.sync(tarballs_dir)
  mkdirp.sync(user_dir)
  mkdirp.sync(meta_dir)

  return {
      get_user: get_user
    , set_user: set_user
    , get_meta: get_meta
    , set_meta: set_meta
    , get_tarball: get_tarball
    , set_tarball: set_tarball
  }

  function get_user(name, done) {
    read_json(join(user_dir, name), done)
  }

  function set_user(name, data, done) {
    write_json(join(user_dir, name), data, done)
  }

  function get_meta(name, done) {
    read_json(join(meta_dir, name), done)
  }

  function set_meta(name, data, done) {
    write_json(join(meta_dir, name), data, done)
  }

  function get_tarball(name, version) {
    return fs.createReadStream(
        join(tarballs_dir, name + '@' + version + '.tgz')
    )
  }

  function set_tarball(name, version) {
    return fs.createWriteStream(
        join(tarballs_dir, name + '@' + version + '.tgz')
    )
  }
}

function write_json(filename, data, ready) {
  try {
    var json_data = JSON.stringify(data, null, 2)
  } catch(e) {
    return ready(e)
  }

  fs.writeFile(filename + '.json', json_data, write_done)

  function write_done(err) {
    if(err) return ready(err)

    ready(null, json_data)
  }
}

function read_json(filename, ready) {
  fs.readFile(filename + '.json', parse_json)

  function parse_json(err, data) {
    if(err) return err.code === 'ENOENT' ? ready(null, []) : ready(err)

    try {
      return ready(null, JSON.parse(data))
    } catch(e) {
      return ready(e)
    }
  }
}
<commit_msg>returning null instead of empty array for no meta found<commit_after>var path = require('path')
  , fs = require('fs')

var mkdirp = require('mkdirp')

var normal = path.normalize
  , join = path.join

var CWD = process.cwd()

module.exports = fs_back

function fs_back(_meta_dir, _user_dir, _tarballs_dir) {
  var tarballs_dir = normal(_tarballs_dir) || join(CWD, 'tarballs')
    , user_dir = normal(_user_dir) || join(CWD, 'users')
    , meta_dir = normal(_meta_dir) || join(CWD, 'meta')

  mkdirp.sync(tarballs_dir)
  mkdirp.sync(user_dir)
  mkdirp.sync(meta_dir)

  return {
      get_user: get_user
    , set_user: set_user
    , get_meta: get_meta
    , set_meta: set_meta
    , get_tarball: get_tarball
    , set_tarball: set_tarball
  }

  function get_user(name, done) {
    read_json(join(user_dir, name), done)
  }

  function set_user(name, data, done) {
    write_json(join(user_dir, name), data, done)
  }

  function get_meta(name, done) {
    read_json(join(meta_dir, name), done)
  }

  function set_meta(name, data, done) {
    write_json(join(meta_dir, name), data, done)
  }

  function get_tarball(name, version) {
    return fs.createReadStream(
        join(tarballs_dir, name + '@' + version + '.tgz')
    )
  }

  function set_tarball(name, version) {
    return fs.createWriteStream(
        join(tarballs_dir, name + '@' + version + '.tgz')
    )
  }
}

function write_json(filename, data, ready) {
  try {
    var json_data = JSON.stringify(data, null, 2)
  } catch(e) {
    return ready(e)
  }

  fs.writeFile(filename + '.json', json_data, write_done)

  function write_done(err) {
    if(err) return ready(err)

    ready(null, json_data)
  }
}

function read_json(filename, ready) {
  fs.readFile(filename + '.json', parse_json)

  function parse_json(err, data) {
    if(err) return err.code === 'ENOENT' ? ready(null, null) : ready(err)

    try {
      return ready(null, JSON.parse(data))
    } catch(e) {
      return ready(e)
    }
  }
}
<|endoftext|>


<commit_before>var path = require("path");
var components = path.resolve(__dirname, "remoteappmanager/static/components");
var js = path.resolve(__dirname, "remoteappmanager/static/js");

module.exports = {
    entry: {
        admin: path.resolve(js, "admin/main.js"),
        user: path.resolve(js, "home/controller.js")
    },
    output: {
        path: path.resolve(__dirname, "remoteappmanager/static/dist"),
        filename: "[name].js"
    },
    resolve: {
        extensions: ["*", ".js"],
        alias: {
            jquery: path.resolve(components, "admin-lte/plugins/jQuery/jquery-2.2.3.min"),
            vuejs: path.resolve(components, "vue/dist/vue"),

            resources: path.resolve(js, "resources"),
            gamodule: path.resolve(js, "gamodule"),
            urlutils: path.resolve(js, "urlutils"),
            utils: path.resolve(js, "utils"),

            filters: path.resolve(js, "vue/filters"),
            toolkit: path.resolve(js, "admin/vue-components/toolkit/toolkit"),
        }
    }
}
<commit_msg>Add aliases for vue-router and vue-form<commit_after>var path = require("path");
var components = path.resolve(__dirname, "remoteappmanager/static/components");
var js = path.resolve(__dirname, "remoteappmanager/static/js");

module.exports = {
    entry: {
        admin: path.resolve(js, "admin/main.js"),
        user: path.resolve(js, "home/controller.js")
    },

    output: {
        path: path.resolve(__dirname, "remoteappmanager/static/dist"),
        filename: "[name].js"
    },

    resolve: {
        extensions: ["*", ".js"],
        alias: {
            jquery: path.resolve(components, "admin-lte/plugins/jQuery/jquery-2.2.3.min"),
            vuejs: path.resolve(components, "vue/dist/vue"),
            "vue-router": path.resolve(components, "vue-router/dist/vue-router"),
            "vue-form": path.resolve(components, "vue-form/dist/vue-form"),

            resources: path.resolve(js, "resources"),
            gamodule: path.resolve(js, "gamodule"),
            urlutils: path.resolve(js, "urlutils"),
            utils: path.resolve(js, "utils"),

            filters: path.resolve(js, "vue/filters"),
            toolkit: path.resolve(js, "admin/vue-components/toolkit/toolkit"),
        }
    }
}
<|endoftext|>


<commit_before>/*
 * Ben Postlethwaite
 * January 2013
 * License MIT
 */
'use strict';

var colorScale = require('./colorScale');
var lerp = require('lerp')

module.exports = createColormap;

function createColormap (spec) {
    /*
     * Default Options
     */
    var indicies, rgba, fromrgba, torgba,
        nsteps, cmap, colormap, format,
        nshades, colors, alpha, index, i,
        r = [],
        g = [],
        b = [],
        a = [];

    if ( !spec ) spec = {};

    nshades = (spec.nshades || 72) - 1;
    format = spec.format || 'hex';

    colormap = spec.colormap;
    if (!colormap) colormap = 'jet';

    if (typeof colormap === 'string') {
        colormap = colormap.toLowerCase();

        if (!colorScale[colormap]) {
            throw Error(colormap + ' not a supported colorscale');
        }

        cmap = colorScale[colormap];

    } else if (Array.isArray(colormap)) {
        cmap = colormap.slice();

    } else {
        throw Error('unsupported colormap option', colormap);
    }

    if (cmap.length > nshades) {
        throw new Error(
            colormap+' map requires nshades to be at least size '+cmap.length
        );
    }

    if (!Array.isArray(spec.alpha)) {

        if (typeof spec.alpha === 'number') {
            alpha = [spec.alpha, spec.alpha];

        } else {
            alpha = [1, 1];
        }

    } else if (spec.alpha.length !== 2) {
        alpha = [1, 1];

    } else {
        alpha = spec.alpha.slice();
    }

    // map index points from 0..1 to 0..n-1
    indicies = cmap.map(function(c) {
        return Math.round(c.index * nshades);
    });

    // Add alpha channel to the map
    alpha[0] = Math.min(Math.max(alpha[0], 0), 1);
    alpha[1] = Math.min(Math.max(alpha[1], 0), 1);

    var steps = cmap.map(function(c, i) {
        var index = cmap[i].index

        var rgba = cmap[i].rgb.slice();

        // if user supplies their own map use it
        if (rgba.length === 4 && rgba[3] >= 0 && rgba[3] <= 1) {
            return rgba
        }
        rgba[3] = alpha[0] + (alpha[1] - alpha[0])*index;

        return rgba
    })

    /*
     * map increasing linear values between indicies to
     * linear steps in colorvalues
     */
    var colors = []
    for (i = 0; i < indicies.length-1; ++i) {
        nsteps = indicies[i+1] - indicies[i];
        fromrgba = steps[i];
        torgba = steps[i+1];

        for (var j = 0; j < nsteps; j++) {
            var amt = j / nsteps
            colors.push([
                Math.round(lerp(fromrgba[0], torgba[0], amt)),
                Math.round(lerp(fromrgba[1], torgba[1], amt)),
                Math.round(lerp(fromrgba[2], torgba[2], amt)),
                lerp(fromrgba[3], torgba[3], amt)
            ])
        }
    }

    //add 1 step as last value
    colors.push(cmap[cmap.length - 1].rgb.concat(alpha[1]))

    if (format === 'hex') colors = colors.map( rgb2hex );
    else if (format === 'rgbaString') colors = colors.map( rgbaStr );
    else if (format === 'float') colors = colors.map( rgb2float );

    return colors;
};

function rgb2float (rgba) {
    return [
        rgba[0] / 255,
        rgba[1] / 255,
        rgba[2] / 255,
        rgba[3]
    ]
}

function rgb2hex (rgba) {
    var dig, hex = '#';
    for (var i = 0; i < 3; ++i) {
        dig = rgba[i];
        dig = dig.toString(16);
        hex += ('00' + dig).substr( dig.length );
    }
    return hex;
}

function rgbaStr (rgba) {
    return 'rgba(' + rgba.join(',') + ')';
}
<commit_msg>removed few unused variables and expanded colormap to support 256 colors<commit_after>/*
 * Ben Postlethwaite
 * January 2013
 * License MIT
 */
'use strict';

var colorScale = require('./colorScale');
var lerp = require('lerp')

module.exports = createColormap;

function createColormap (spec) {
    /*
     * Default Options
     */
    var indicies, fromrgba, torgba,
        nsteps, cmap, colormap, format,
        nshades, colors, alpha, i;

    if ( !spec ) spec = {};

    nshades = (spec.nshades || 72) - 1;
    format = spec.format || 'hex';

    colormap = spec.colormap;
    if (!colormap) colormap = 'jet';

    if (typeof colormap === 'string') {
        colormap = colormap.toLowerCase();

        if (!colorScale[colormap]) {
            throw Error(colormap + ' not a supported colorscale');
        }

        cmap = colorScale[colormap];

    } else if (Array.isArray(colormap)) {
        cmap = colormap.slice();

    } else {
        throw Error('unsupported colormap option', colormap);
    }

    if (cmap.length > nshades + 1) {
        throw new Error(
            colormap+' map requires nshades to be at least size '+cmap.length
        );
    }

    if (!Array.isArray(spec.alpha)) {

        if (typeof spec.alpha === 'number') {
            alpha = [spec.alpha, spec.alpha];

        } else {
            alpha = [1, 1];
        }

    } else if (spec.alpha.length !== 2) {
        alpha = [1, 1];

    } else {
        alpha = spec.alpha.slice();
    }

    // map index points from 0..1 to 0..n-1
    indicies = cmap.map(function(c) {
        return Math.round(c.index * nshades);
    });

    // Add alpha channel to the map
    alpha[0] = Math.min(Math.max(alpha[0], 0), 1);
    alpha[1] = Math.min(Math.max(alpha[1], 0), 1);

    var steps = cmap.map(function(c, i) {
        var index = cmap[i].index

        var rgba = cmap[i].rgb.slice();

        // if user supplies their own map use it
        if (rgba.length === 4 && rgba[3] >= 0 && rgba[3] <= 1) {
            return rgba
        }
        rgba[3] = alpha[0] + (alpha[1] - alpha[0])*index;

        return rgba
    })

    /*
     * map increasing linear values between indicies to
     * linear steps in colorvalues
     */
    var colors = []
    for (i = 0; i < indicies.length-1; ++i) {
        nsteps = indicies[i+1] - indicies[i];
        fromrgba = steps[i];
        torgba = steps[i+1];

        for (var j = 0; j < nsteps; j++) {
            var amt = j / nsteps
            colors.push([
                Math.round(lerp(fromrgba[0], torgba[0], amt)),
                Math.round(lerp(fromrgba[1], torgba[1], amt)),
                Math.round(lerp(fromrgba[2], torgba[2], amt)),
                lerp(fromrgba[3], torgba[3], amt)
            ])
        }
    }

    //add 1 step as last value
    colors.push(cmap[cmap.length - 1].rgb.concat(alpha[1]))

    if (format === 'hex') colors = colors.map( rgb2hex );
    else if (format === 'rgbaString') colors = colors.map( rgbaStr );
    else if (format === 'float') colors = colors.map( rgb2float );

    return colors;
};

function rgb2float (rgba) {
    return [
        rgba[0] / 255,
        rgba[1] / 255,
        rgba[2] / 255,
        rgba[3]
    ]
}

function rgb2hex (rgba) {
    var dig, hex = '#';
    for (var i = 0; i < 3; ++i) {
        dig = rgba[i];
        dig = dig.toString(16);
        hex += ('00' + dig).substr( dig.length );
    }
    return hex;
}

function rgbaStr (rgba) {
    return 'rgba(' + rgba.join(',') + ')';
}
<|endoftext|>


<commit_before>var Botkit = require('botkit')
var Witbot = require('witbot')

var token = process.env.SLACK_TOKEN
var witToken = process.env.WIT_TOKEN

var controller = Botkit .slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  debug: false
})

// Assume single team mode if we have a SLACK_TOKEN
if (token) {
  console.log('Starting in single-team mode')
  controller.spawn({
    token: token,
    retry: Infinity
  }).startRTM(function (err, bot, payload) {
    if (err) {
      throw new Error(err)
    }

    console.log('Connected to Slack RTM')
  })
// Otherwise assume multi-team mode - setup beep boop resourcer connection
} else {
  console.log('Starting in Beep Boop multi-team mode')
  require('beepboop-botkit').start(controller, { debug: true })
}

var wit = Witbot(witToken)

controller.on('bot_channel_join', function (bot, message) {
  bot.reply(message, "I'm here!")
})

controller.hears(['hello', 'hi'], ['direct_mention'], function (bot, message) {
  bot.reply(message, 'Hello.')
})

controller.hears(['hello', 'hi'], ['direct_message'], function (bot, message) {
  bot.reply(message, 'Hello.')
  bot.reply(message, 'It\'s nice to talk to you directly.')
})

controller.hears('.*', ['mention'], function (bot, message) {
  bot.reply(message, 'You really do care about me. :heart:')
})

controller.hears('help', ['direct_message', 'direct_mention'], function (bot, message) {
  var help = 'I will respond to the following messages: \n' +
      '`bot hi` for a simple message.\n' +
      '`bot attachment` to see a Slack attachment message.\n' +
      '`@<your bot\'s name>` to demonstrate detecting a mention.\n' +
      '`bot help` to see this again.'
  bot.reply(message, help)
})

controller.hears(['attachment'], ['direct_message', 'direct_mention'], function (bot, message) {
  var text = 'Beep Beep Boop is a ridiculously simple hosting platform for your Slackbots.'
  var attachments = [{
    fallback: text,
    pretext: 'We bring bots to life. :sunglasses: :thumbsup:',
    title: 'Host, deploy and share your bot in seconds.',
    image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
    title_link: 'https://beepboophq.com/',
    text: text,
    color: '#7CD197'
  }]

  bot.reply(message, {
    attachments: attachments
  }, function (err, resp) {
    console.log(err, resp)
  })
})

controller.hears('.*', ['direct_message', 'direct_mention'], function (bot, message) {
  bot.reply(message, 'Sorry <@' + message.user + '>, I don\'t understand. \n')
})
<commit_msg>witbot hears test<commit_after>var Botkit = require('botkit')
var Witbot = require('witbot')

var token = process.env.SLACK_TOKEN
var witToken = process.env.WIT_TOKEN

var controller = Botkit .slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  debug: false
})

// Assume single team mode if we have a SLACK_TOKEN
if (token) {
  console.log('Starting in single-team mode')
  controller.spawn({
    token: token,
    retry: Infinity
  }).startRTM(function (err, bot, payload) {
    if (err) {
      throw new Error(err)
    }

    console.log('Connected to Slack RTM')
  })
// Otherwise assume multi-team mode - setup beep boop resourcer connection
} else {
  console.log('Starting in Beep Boop multi-team mode')
  require('beepboop-botkit').start(controller, { debug: true })
}

var wit = Witbot(witToken)

controller.on('bot_channel_join', function (bot, message) {
  bot.reply(message, "I'm here!")
})

wit.hears('hello', 0.5, function(bot, message, outcome) {
  bot.reply(message, 'what it is')
})
// controller.hears(['hello', 'hi'], ['direct_mention'], function (bot, message) {
//   bot.reply(message, 'Hello.')
// })
//
// controller.hears(['hello', 'hi'], ['direct_message'], function (bot, message) {
//   bot.reply(message, 'Hello.')
//   bot.reply(message, 'It\'s nice to talk to you directly.')
// })
//
// controller.hears('.*', ['mention'], function (bot, message) {
//   bot.reply(message, 'You really do care about me. :heart:')
// })

controller.hears('help', ['direct_message', 'direct_mention'], function (bot, message) {
  var help = 'I will respond to the following messages: \n' +
      '`bot hi` for a simple message.\n' +
      '`bot attachment` to see a Slack attachment message.\n' +
      '`@<your bot\'s name>` to demonstrate detecting a mention.\n' +
      '`bot help` to see this again.'
  bot.reply(message, help)
})

controller.hears(['attachment'], ['direct_message', 'direct_mention'], function (bot, message) {
  var text = 'Beep Beep Boop is a ridiculously simple hosting platform for your Slackbots.'
  var attachments = [{
    fallback: text,
    pretext: 'We bring bots to life. :sunglasses: :thumbsup:',
    title: 'Host, deploy and share your bot in seconds.',
    image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
    title_link: 'https://beepboophq.com/',
    text: text,
    color: '#7CD197'
  }]

  bot.reply(message, {
    attachments: attachments
  }, function (err, resp) {
    console.log(err, resp)
  })
})

controller.hears('.*', ['direct_message', 'direct_mention'], function (bot, message) {
  bot.reply(message, 'Sorry <@' + message.user + '>, I don\'t understand. \n')
})
<|endoftext|>


<commit_before>var path = require('path'),
	_ = require('lodash'),
	fs = require('fs'),
	chalk = require('chalk'),
	mime = require('mime-types'),
	mkdirp = require('mkdirp'),
	connect = require('connect');

function fileIOServer(params) {
	params = _.merge({
		port: 3000,
		servePath: "./staticServe",
		debugLevel: 1
	}, params || {});

	var servePath = path.resolve(params.servePath);
	if(params.debugLevel >= 1) console.log('serving ' + servePath + ' on port:', params.port );

	var serveStatic = require('serve-static');
	var app = connect();
	app.use(serveStatic(servePath));

	function respond(msg) {
		msg = msg || 'hello world';

		return function(req, res) {
			if(req.method == 'PUT') {
				if(params.debugLevel >= 1) console.log('putting', req.url);
				var filePath = path.resolve(servePath + '/' + req.url);
				var fileExists = fs.existsSync(filePath);
				var responseStatus =  fileExists ? 200 : 201;
				var started = false;
				mkdirp(path.dirname(filePath), function(err) {
					if(err) {
						throw(err);
					} else {
						req.on('readable', function() {
							if(started) return;
							started = true;
							if(params.debugLevel >= 2) console.log('there is some data to read now');
							req.on('data', function(chunk) {
								if(params.debugLevel >= 2) console.log('got %d bytes of data', chunk.length);
							})
							var writable = fs.createWriteStream(filePath);
							// All the data from readable goes into 'file.txt'
							req.pipe(writable);

							req.on('end', function() {
								if(params.debugLevel >= 2) console.log('there will be no more data.');

								res.setHeader("Access-Control-Allow-Origin", "*");
								res.setHeader("Access-Control-Allow-Methods", "GET, PUT");
								res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
								res.writeHead(responseStatus, { 'Content-Type': mime.lookup(req.url)});
								res.end((fileExists ? 'file updated: ' : 'new file saved: ') + filePath );
								if(params.debugLevel >= 1) console.log('file put complete.');
							});
						});
					}
				});
			} else if(req.url == '/') {
				if(params.debugLevel >= 1) console.log('requesting', req.url);
				res.writeHead(200, { 'Content-Type': mime.lookup('index.html')});
				res.end(msg);
			} else {
				if(params.debugLevel >= 1) console.log('requesting', req.url);
				res.writeHead(404, { 'Content-Type': mime.lookup(req.url)});
				res.end('not found');
			}
		}
	}

	var html = '' +
	'		' +
	'			<title>File IO Server Test</title>' +
	'			<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />' +
	'			' +
	'		' +
	'	' +
	'		If you\'re seeing this message, you are running a fileserver for %%PATH on port %%PORT capable of GET and PUT requests, so please use responsibly.' +
	'	' +
	'';
	html = html.replace('%%PATH', servePath);
	html = html.replace('%%PORT', params.port);
	app.use(respond(html));
	app.listen(params.port);
}

module.exports = fileIOServer;
<commit_msg>cors debugging<commit_after>var path = require('path'),
	_ = require('lodash'),
	fs = require('fs'),
	chalk = require('chalk'),
	mime = require('mime-types'),
	mkdirp = require('mkdirp'),
	connect = require('connect');

function fileIOServer(params) {
	params = _.merge({
		port: 3000,
		servePath: "./staticServe",
		debugLevel: 1
	}, params || {});

	var servePath = path.resolve(params.servePath);
	if(params.debugLevel >= 1) console.log('serving ' + servePath + ' on port:', params.port );

	var serveStatic = require('serve-static');
	var app = connect();
	var allowCrossDomain = function(req, res, next) {
	    res.setHeader('Access-Control-Allow-Origin', '*');
	    res.setHeader('Access-Control-Allow-Methods', 'GET,PUT');
	    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
	    next();
	}
	app.use(allowCrossDomain);
	app.use(serveStatic(servePath));

	function respond(msg) {
		msg = msg || 'hello world';

		return function(req, res) {
			if(req.method == 'PUT') {
				if(params.debugLevel >= 1) console.log('putting', req.url);
				var filePath = path.resolve(servePath + '/' + req.url);
				var fileExists = fs.existsSync(filePath);
				var responseStatus =  fileExists ? 200 : 201;
				var started = false;
				mkdirp(path.dirname(filePath), function(err) {
					if(err) {
						throw(err);
					} else {
						req.on('readable', function() {
							if(started) return;
							started = true;
							if(params.debugLevel >= 2) console.log('there is some data to read now');
							req.on('data', function(chunk) {
								if(params.debugLevel >= 2) console.log('got %d bytes of data', chunk.length);
							})
							var writable = fs.createWriteStream(filePath);
							// All the data from readable goes into 'file.txt'
							req.pipe(writable);

							req.on('end', function() {
								if(params.debugLevel >= 2) console.log('there will be no more data.');
								res.writeHead(responseStatus, { 'Content-Type': mime.lookup(req.url)});
								res.end((fileExists ? 'file updated: ' : 'new file saved: ') + filePath );
								if(params.debugLevel >= 1) console.log('file put complete.');
							});
						});
					}
				});
			} else if(req.url == '/') {
				if(params.debugLevel >= 1) console.log('requesting', req.url);
				res.writeHead(200, { 'Content-Type': mime.lookup('index.html')});
				res.end(msg);
			} else {
				if(params.debugLevel >= 1) console.log('requesting', req.url);
				res.writeHead(404, { 'Content-Type': mime.lookup(req.url)});
				res.end('not found');
			}
		}
	}

	var html = '' +
	'		' +
	'			<title>File IO Server Test</title>' +
	'			<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />' +
	'			' +
	'		' +
	'	' +
	'		If you\'re seeing this message, you are running a fileserver for %%PATH on port %%PORT capable of GET and PUT requests, so please use responsibly.' +
	'	' +
	'';
	html = html.replace('%%PATH', servePath);
	html = html.replace('%%PORT', params.port);
	app.use(respond(html));
	app.listen(params.port);
}

module.exports = fileIOServer;
<|endoftext|>