<commit_before>(function() {
    'use strict';

    var DIR         = __dirname + '/../../',
        DIR_HTML    = DIR       + 'tmpl/',
        DIR_LIB     = DIR       + 'lib/',
        DIR_SERVER  = __dirname + '/',
        DIR_FS      = DIR_HTML  + 'fs/',

        fs          = require('fs'),

        mellow      = require('mellow'),
        ponse       = require('ponse'),
        files       = require('files-io'),
        rendy       = require('rendy'),
        exec        = require('execon'),

        minify      = require('minify'),
        format      = require('format-io'),

        config      = require(DIR_SERVER + 'config'),
        root        = require(DIR_SERVER + 'root'),

        CloudFunc   = require(DIR_LIB + 'cloudfunc'),

        PATH_INDEX  = DIR_FS   + 'index.hbs',

        TMPL_PATH   = [
            'file',
            'panel',
            'path',
            'pathLink',
            'link'
        ],

        Template    = {},

        FS          = CloudFunc.FS;

    module.exports  = function(req, res, next) {
        readFiles(function() {
            route(req, res, next);
        });
    };

    /**
     * additional processing of index file
     */
    function indexProcessing(options) {
        var left, right, from, to,
            keysPanel   = '<div id="js-keyspanel" class="{{ className }}',
            data        = options.data,
            panel       = options.panel;

        if (!config('showKeysPanel')) {
            from        = rendy(keysPanel, {
                className: 'keyspanel'
            });

            to          = rendy(keysPanel, {
                className: 'keyspanel hidden'
            });

            data        = data.replace(from, to);
        }

        left = rendy(Template.panel, {
            side    : 'left',
            content : panel
        });

        right = rendy(Template.panel, {
            side    : 'right',
            content : panel
        });

        data = rendy(data, {
            title   : CloudFunc.getTitle(),
            fm      : left + right
        });

        return data;
    }

    function readFiles(callback) {
        var filesList,
            paths       = {},

            lengthTmpl  = Object.keys(Template).length,
            lenthPath   = TMPL_PATH.length,
            isRead      = lengthTmpl === lenthPath;

        if (typeof callback !== 'function')
            throw Error('callback should be function!');

        if (isRead) {
            callback();
        } else {
            filesList   = TMPL_PATH.map(function(name) {
                var path = DIR_FS + name + '.hbs';

                paths[path] = name;

                return path;
            });

            files.read(filesList, 'utf8', function(error, files) {
                if (error)
                    throw error;
                else
                    Object.keys(files).forEach(function(path) {
                        var name = paths[path];

                        Template[name] = files[path];
                    });

                callback();
            });
        }
    }

    /**
     * routing of server queries
     */
    function route(request, response, callback) {
        var name, p, isAuth, isFS, fullPath;

        if (!request)
            throw Error('request could not be empty!');

        if (!response)
            throw Error('response could not be empty!');

        if (typeof callback !== 'function')
            throw Error('callback should be function!');

        name    = ponse.getPathName(request);

        isAuth  = RegExp('^(/auth|/auth/github)$').test(name);
        isFS    = RegExp('^/$|^' + FS).test(name);

        p       = {
            request     : request,
            response    : response,
            gzip        : true,
            name        : name,
            mime        : 'text/html'
        };
        console.log(p.mime, '...')
        if (!isAuth && !isFS)
            callback();
        else if (isAuth) {
            console.log('* Routing' + '-> ' + name);

            p.name = DIR_HTML + name + '.html';
            ponse.sendFile(p);
        } else if (isFS) {
            name        = name.replace(CloudFunc.FS, '') || '/';
            fullPath    = root(name);

            mellow.read(fullPath, function(error, dir) {
                if (dir)
                    dir.path = format.addSlashToEnd(name);

                if (!error)
                    buildIndex(dir, function(error, data) {
                        p.name = PATH_INDEX;
                        console.log(p, '88888')
                        if (error)
                            ponse.sendError(error, p);
                        else
                            ponse.send(data, p);
                    });
                else if (error.code !== 'ENOTDIR')
                    ponse.sendError(error, p);
                else
                    fs.realpath(fullPath, function(error, pathReal) {
                        if (!error)
                            p.name = pathReal;
                        else
                            p.name = name;

                        p.gzip = false;
                        ponse.sendFile(p);
                    });
            });
        }
    }

    function buildIndex(json, callback) {
        var isMinify = config('minify');

        exec.if(!isMinify, function(error, name) {
            fs.readFile(name || PATH_INDEX, 'utf8', function(error, template) {
                var panel, data;

                if (!error) {
                    panel   = CloudFunc.buildFromJSON({
                        data        : json,
                        template    : Template
                    }),

                    data    = indexProcessing({
                        panel   : panel,
                        data    : template
                    });
                }

                exec(callback, error, data);
            });
        },  function(callback) {
                minify(PATH_INDEX, 'name', callback);
        });
    }
})();
<commit_msg>chore(route) rm console.log<commit_after>(function() {
    'use strict';

    var DIR         = __dirname + '/../../',
        DIR_HTML    = DIR       + 'tmpl/',
        DIR_LIB     = DIR       + 'lib/',
        DIR_SERVER  = __dirname + '/',
        DIR_FS      = DIR_HTML  + 'fs/',

        fs          = require('fs'),

        mellow      = require('mellow'),
        ponse       = require('ponse'),
        files       = require('files-io'),
        rendy       = require('rendy'),
        exec        = require('execon'),

        minify      = require('minify'),
        format      = require('format-io'),

        config      = require(DIR_SERVER + 'config'),
        root        = require(DIR_SERVER + 'root'),

        CloudFunc   = require(DIR_LIB + 'cloudfunc'),

        PATH_INDEX  = DIR_FS   + 'index.hbs',

        TMPL_PATH   = [
            'file',
            'panel',
            'path',
            'pathLink',
            'link'
        ],

        Template    = {},

        FS          = CloudFunc.FS;

    module.exports  = function(req, res, next) {
        readFiles(function() {
            route(req, res, next);
        });
    };

    /**
     * additional processing of index file
     */
    function indexProcessing(options) {
        var left, right, from, to,
            keysPanel   = '<div id="js-keyspanel" class="{{ className }}',
            data        = options.data,
            panel       = options.panel;

        if (!config('showKeysPanel')) {
            from        = rendy(keysPanel, {
                className: 'keyspanel'
            });

            to          = rendy(keysPanel, {
                className: 'keyspanel hidden'
            });

            data        = data.replace(from, to);
        }

        left = rendy(Template.panel, {
            side    : 'left',
            content : panel
        });

        right = rendy(Template.panel, {
            side    : 'right',
            content : panel
        });

        data = rendy(data, {
            title   : CloudFunc.getTitle(),
            fm      : left + right
        });

        return data;
    }

    function readFiles(callback) {
        var filesList,
            paths       = {},

            lengthTmpl  = Object.keys(Template).length,
            lenthPath   = TMPL_PATH.length,
            isRead      = lengthTmpl === lenthPath;

        if (typeof callback !== 'function')
            throw Error('callback should be function!');

        if (isRead) {
            callback();
        } else {
            filesList   = TMPL_PATH.map(function(name) {
                var path = DIR_FS + name + '.hbs';

                paths[path] = name;

                return path;
            });

            files.read(filesList, 'utf8', function(error, files) {
                if (error)
                    throw error;
                else
                    Object.keys(files).forEach(function(path) {
                        var name = paths[path];

                        Template[name] = files[path];
                    });

                callback();
            });
        }
    }

    /**
     * routing of server queries
     */
    function route(request, response, callback) {
        var name, p, isAuth, isFS, fullPath;

        if (!request)
            throw Error('request could not be empty!');

        if (!response)
            throw Error('response could not be empty!');

        if (typeof callback !== 'function')
            throw Error('callback should be function!');

        name    = ponse.getPathName(request);

        isAuth  = RegExp('^(/auth|/auth/github)$').test(name);
        isFS    = RegExp('^/$|^' + FS).test(name);

        p       = {
            request     : request,
            response    : response,
            gzip        : true,
            name        : name,
            mime        : 'text/html'
        };

        if (!isAuth && !isFS)
            callback();
        else if (isAuth) {
            //'* Routing' + '-> ' + name

            p.name = DIR_HTML + name + '.html';
            ponse.sendFile(p);
        } else if (isFS) {
            name        = name.replace(CloudFunc.FS, '') || '/';
            fullPath    = root(name);

            mellow.read(fullPath, function(error, dir) {
                if (dir)
                    dir.path = format.addSlashToEnd(name);

                if (!error)
                    buildIndex(dir, function(error, data) {
                        p.name = PATH_INDEX;

                        if (error)
                            ponse.sendError(error, p);
                        else
                            ponse.send(data, p);
                    });
                else if (error.code !== 'ENOTDIR')
                    ponse.sendError(error, p);
                else
                    fs.realpath(fullPath, function(error, pathReal) {
                        if (!error)
                            p.name = pathReal;
                        else
                            p.name = name;

                        p.gzip = false;
                        ponse.sendFile(p);
                    });
            });
        }
    }

    function buildIndex(json, callback) {
        var isMinify = config('minify');

        exec.if(!isMinify, function(error, name) {
            fs.readFile(name || PATH_INDEX, 'utf8', function(error, template) {
                var panel, data;

                if (!error) {
                    panel   = CloudFunc.buildFromJSON({
                        data        : json,
                        template    : Template
                    }),

                    data    = indexProcessing({
                        panel   : panel,
                        data    : template
                    });
                }

                exec(callback, error, data);
            });
        },  function(callback) {
                minify(PATH_INDEX, 'name', callback);
        });
    }
})();
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import Video from './Video';
import VideoInput from './VideoInput';

const Player = (props) => {
  return (

      {props.video.videoId ? (
        <Video video={props.video} setAllowSeek={props.setAllowSeek} />
      ) : (

No video is playing.

      )}

      <VideoInput {...props} />

  );
};

Player.propTypes = {
  addMessage: PropTypes.func.isRequired,
  addVideo: PropTypes.func.isRequired,
  setAllowSeek: PropTypes.func.isRequired,
  username: PropTypes.string.isRequired,
  video: PropTypes.shape({
    allowSeek: PropTypes.bool.isRequired,
    host: PropTypes.string.isRequired,
    start: PropTypes.number.isRequired,
    videoId: PropTypes.string.isRequired
  }).isRequired
};

export default Player;
<commit_msg>Add host<commit_after>import React, {PropTypes} from 'react';
import Video from './Video';
import VideoInput from './VideoInput';
import hashColor from '../hashColor';

const Player = (props) => {
  const {videoId, host} = props.video;

  return (

      {videoId ? (

          <Video video={props.video} setAllowSeek={props.setAllowSeek} />

              Host: {host}

      ) : (

No video is playing.

      )}
      <VideoInput {...props} />

  );
};

Player.propTypes = {
  addMessage: PropTypes.func.isRequired,
  addVideo: PropTypes.func.isRequired,
  setAllowSeek: PropTypes.func.isRequired,
  username: PropTypes.string.isRequired,
  video: PropTypes.shape({
    allowSeek: PropTypes.bool.isRequired,
    host: PropTypes.string.isRequired,
    start: PropTypes.number.isRequired,
    videoId: PropTypes.string.isRequired
  }).isRequired
};

export default Player;
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var cluster = require('cluster');
var EventEmitter = require('events').EventEmitter;
var bcoin = require('bcoin');
var Peer = bcoin.peer;
var NetAddress = bcoin.netaddress;

var config = require('../config');

var P2pService = function() {
  this.peer = Peer.fromOptions({
    network: config.network,
    agent: 'fullNodePlus',
    hasWitness: function(){
      return false;
    }
  });
};

util.inherits(P2pService, EventEmitter);

P2pService.prototype.start = function(ready) {
  var self = this;
  if (cluster.isWorker){
    return setImmediate(ready);
  }
  this.peer.on('packet', function(msg){
    if(msg.cmd === 'block') {
      var block = msg.block.toBlock();
      self.emit(block.rhash(), block);
      self.emit('block', block);
      return;
    }
    if(msg.cmd === 'tx') {
      self.emit('transaction', msg.tx);
      return;
    }
    if(msg.cmd === 'headers') {
      self.emit('headers', msg.items);
      return;
    }
    if(msg.cmd === 'inv') {
      self.emit('inv', msg.items);
      self.peer.getData(msg.items);
      return;
    }
  });
  var addr = NetAddress.fromHostname(config.p2pHost, config.network);
  this.peer.connect(addr);
  this.peer.tryOpen();
  this.peer.on('open', function(){
    ready();
  });
};

P2pService.prototype.stop = function() {

};

P2pService.prototype.getPeerHeight = function() {
  return this.peer.height;
};

P2pService.prototype.getHeaders = function(candidateHashes, callback) {
  candidateHashes = candidateHashes.map(function(candidateHash){
    return bcoin.util.revHex(candidateHash);
  });
  this.peer.sendGetHeaders(candidateHashes);
  this.once('headers', function(headers){
    headers.map(function(header){
      return header.getJSON();
    });
    callback(null, headers);
  });
};

P2pService.prototype.getBlock = function(hash, callback) {
  var self = this;
  self.peer.getBlock([hash]);
  var rhash = bcoin.util.revHex(hash);
  self.once(rhash, function(block){
    callback(null, block);
  });
};

module.exports = new P2pService();<commit_msg>non-contextual verify of block<commit_after>'use strict';
var util = require('util');
var cluster = require('cluster');
var EventEmitter = require('events').EventEmitter;
var bcoin = require('bcoin');
var Peer = bcoin.peer;
var NetAddress = bcoin.netaddress;

var config = require('../config');

var P2pService = function() {
  this.peer = Peer.fromOptions({
    network: config.network,
    agent: 'fullNodePlus',
    hasWitness: function(){
      return false;
    }
  });
};

util.inherits(P2pService, EventEmitter);

P2pService.prototype.start = function(ready) {
  var self = this;
  if (cluster.isWorker){
    return setImmediate(ready);
  }
  this.peer.on('packet', function(msg){
    if(msg.cmd === 'block') {
      var block = msg.block.toBlock();
      if(!block.verify()){
        return;
      }
      self.emit(block.rhash(), block);
      self.emit('block', block);
      return;
    }
    if(msg.cmd === 'tx') {
      self.emit('transaction', msg.tx);
      return;
    }
    if(msg.cmd === 'headers') {
      self.emit('headers', msg.items);
      return;
    }
    if(msg.cmd === 'inv') {
      self.emit('inv', msg.items);
      self.peer.getData(msg.items);
      return;
    }
  });
  var addr = NetAddress.fromHostname(config.p2pHost, config.network);
  this.peer.connect(addr);
  this.peer.tryOpen();
  this.peer.on('open', function(){
    ready();
  });
};

P2pService.prototype.stop = function() {

};

P2pService.prototype.getPeerHeight = function() {
  return this.peer.height;
};

P2pService.prototype.getHeaders = function(candidateHashes, callback) {
  candidateHashes = candidateHashes.map(function(candidateHash){
    return bcoin.util.revHex(candidateHash);
  });
  this.peer.sendGetHeaders(candidateHashes);
  this.once('headers', function(headers){
    headers.map(function(header){
      return header.getJSON();
    });
    callback(null, headers);
  });
};

P2pService.prototype.getBlock = function(hash, callback) {
  var self = this;
  self.peer.getBlock([hash]);
  var rhash = bcoin.util.revHex(hash);
  self.once(rhash, function(block){
    callback(null, block);
  });
};

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


<commit_before>
const RG = require('../src/rg');
RG.Random = require('../src/random');

const Castle = {};

Castle.corridorDoorThr = 0.2;

Castle.tiles = {};

// Corners
Castle.tiles.corner = [
`
dir:NW
name:corner_se
X=.
Y=#

#X...X#
#.....#
Y.....#
......#
Y.....#
......#
#######`,

`
dir:NW
name:corner_se
X=#
Y=#

#X#+#X#
Y.....#
+.....#
+...#.#
+..####
Y...###
#######`,

`
dir:NE
name:corner_sw
X=.
Y=#

#X...X#
#.....#
Y......
#......
Y......
#.....#
#######`,

`
dir:SW
name:corner_ne
X=#
Y=.

#X###X#
Y.....#
......#
......#
......#
Y.....#
#.....#`,

`
dir:SE
name:corner_nw
X=#
Y=#

#X###X#
#......
Y......
#......
Y......
#......
#.....#`
];

// Terminals
Castle.tiles.term = [
`
dir:N
name:term_n
X=#
Y=#

#X#+#X#
#.....#
Y.....#
#.....#
Y.....#
#.....#
#######`,

`
dir:S
name:term_s
X=#
Y=#

#X###X#
#.....#
Y.....#
#.....#
Y.....#
#.....#
###+###`,

`
dir:E
name:term_e
X=#
Y=#

#X###X#
#.....#
Y.....#
#.....+
Y.....#
#.....#
#######`,

`
dir:W
name:term_w
X=#
Y=#

#X###X#
#.....#
Y.....#
+.....#
Y.....#
#.....#
#######`
];

// Entrances
Castle.tiles.entrance = [
`
dir:NEW
name:entrance_n
X=.
Y=#

#X...X#
##...##
Y##.###
..#+#..
.......
Y.....#
#######`,

`
dir:SEW
name:entrance_s
X=#
Y=#

#X###X#
Y......
..#.##.
.##+##.
Y#...##
#.....#
##...##`
];

// Entrances
Castle.tiles.entranceWall = [
`
dir:NEW
name:entrance_n
X=.
Y=#

#X...X#
##...##
Y##.###
..#+#..
.......
Y.....#
##...##`,

`
dir:SEW
name:entrance_s
X=#
Y=#

#X...X#
Y.....#
..#.#..
.##+##.
Y#...##
#.....#
#.....#`
];

// Corridors
Castle.tiles.corridor = [
`
dir:NS
name:corridor_east
X=.
Y=#

#X...X#
#.....#
Y.....#
#.....#
Y.....#
#.....#
#.....#`,

`
dir:NS
name:corridor_west
X=.
Y=#

#X...X#
#.....#
Y.....#
#.....#
Y.....#
#.....#
#.....#`,

`
dir:EW
name:corridor_north
X=#
Y=.

#X###X#
.......
Y......
.......
Y......
.......
#######`,

`
dir:EW
name:corridor_south
X=#
Y=.

#X###X#
.......
Y......
.......
Y......
.......
#######`
];

// These provide exit from the main wall, however their exit direction is not
// specified thus they're treated as normal bi-directional corridors for PCG
Castle.tiles.corridorWithExit = [
`
dir:NS
name:corridor_east
X=.
Y=#

#X...X#
#.....#
Y#....#
......#
Y#....#
#.....#
#.....#`,

`
dir:NS
name:corridor_west
X=.
Y=#

#X...X#
#.....#
Y....##
#......
Y....##
#.....#
#.....#`,

`
dir:EW
name:corridor_north
X=#
Y=.

#X###X#
.......
Y......
.......
Y......
..#.#..
###.###`,

`
dir:EW
name:corridor_south
X=#
Y=.

#X#.#X#
..#.#..
Y......
.......
Y......
..#.#..
#######`
];

// Branching from the main wall
Castle.tiles.branch = [
`
dir:NSE
name:corridor_nse
X=.
Y=#

#X...X#
#.....#
Y.....#
#.....+
Y.....#
#.....#
#.....#`,

`
dir:NSW
name:corridor_nsw
X=#
Y=#

#X...X#
#.....#
Y.....#
+.....#
Y.....#
#.....#
##...##`,

`
dir:NEW
name:corridor_new
X=#
Y=.

#X#+#X#
.......
Y......
.......
Y......
.......
#######`,

`
dir:SEW
name:corridor_sew
X=#
Y=.

#X###X#
.......
Y......
.......
Y......
.......
###+###`
];

// Filler cell
Castle.tiles.fillerFloor = `
name:FILLER
X=.
Y=.

.X...X.
Y......
.......
.......
.......
Y......
.......`;

Castle.tiles.fillerWall = `
name:FILLER
X=#
Y=#

#X###X#
Y######
#######
#######
#######
Y######
#######`;

/* Returns the starting room for castle generation. */
Castle.startRoomFunc = function() {
    const midX = Math.floor(this.tilesX / 2);
    let templ = null;
    const north = RG.RAND.getUniform() <= 0.5;
    let y = 0;
    if (north) {
        templ = this.findTemplate({name: 'entrance_n'});
    }
    else {
        templ = this.findTemplate({name: 'entrance_s'});
        y = this.tilesY - 1;
    }
    return {
        x: midX, y, room: templ
    };
};

/* Constraint function how to generate the castle level. */
Castle.constraintFunc = function(x, y, exitReqd) {

    // Constraints for 4 corners
    if (x === 0 && y === 0) {
        return this.findTemplate({name: 'corner_nw'});
    }
    if (x === 0 && y === this.tilesY - 1) {
        return this.findTemplate({name: 'corner_sw'});
    }
    if (x === this.tilesX - 1 && y === 0) {
        return this.findTemplate({name: 'corner_ne'});
    }
    if (x === this.tilesX - 1 && y === this.tilesY - 1) {
        return this.findTemplate({name: 'corner_se'});
    }

    // Northern wall
    if (y === 0 ) {
        const ew = this.findTemplate({name: 'corridor_north'});
        const sew = this.findTemplate({name: 'corridor_sew'});
        if (sew) {
            if (exitReqd === 'S') {
                return sew;
            }
            if (RG.RAND.getUniform() < Castle.corridorDoorThr) {
                return sew;
            }
        }
        return ew;
    }
    // Southern wall
    else if (y === this.tilesY - 1) {
        const ew = this.findTemplate({name: 'corridor_south'});
        const corrNew = this.findTemplate({name: 'corridor_new'});
        if (corrNew) {
            if (exitReqd === 'N') {
                return corrNew;
            }
            if (RG.RAND.getUniform() < Castle.corridorDoorThr) {
                return corrNew;
            }
        }
        return ew;
    }

    // Western wall
    if (x === 0) {
        const corrNs = this.findTemplate({name: 'corridor_west'});
        const corrNse = this.findTemplate({name: 'corridor_nse'});
        if (corrNse) {
            if (exitReqd === 'E') {
                return corrNse;
            }
            if (RG.RAND.getUniform() < Castle.corridorDoorThr) {
                return corrNse;
            }
        }
        return corrNs;
    }
    // Eastern wall
    else if (x === this.tilesX - 1) {
        const corrNs = this.findTemplate({name: 'corridor_east'});
        const corrNsw = this.findTemplate({name: 'corridor_nsw'});
        if (corrNsw) {
            if (exitReqd === 'W') {
                return corrNsw;
            }
            if (RG.RAND.getUniform() < Castle.corridorDoorThr) {
                return corrNsw;
            }
        }
        return corrNs;
    }
    return null;
};

Castle.roomCount = -1; // Fill until no more exits

Castle.Models = {};

Castle.Models.full = []
    .concat(Castle.tiles.branch)
    .concat(Castle.tiles.corner)
    .concat(Castle.tiles.term)
    .concat(Castle.tiles.entrance)
    .concat(Castle.tiles.corridor);

Castle.Models.outerWall = []
    .concat(Castle.tiles.entranceWall)
    .concat(Castle.tiles.corner)
    .concat(Castle.tiles.corridor)
    .concat(Castle.tiles.corridorWithExit);

module.exports = Castle;
<commit_msg>Added startFuncTwoGates().<commit_after>
const RG = require('../src/rg');
RG.Random = require('../src/random');
const Vault = require('./tiles.vault');

const Castle = {};

Castle.corridorDoorThr = 0.2;

Castle.tiles = {};

// Corners
Castle.tiles.corner = [
`
dir:NW
name:corner_se
X=.
Y=#

#X...X#
#.....#
Y.....#
......#
Y.....#
......#
#######`,

`
dir:NW
name:corner_se
X=#
Y=#

#X#+#X#
Y.....#
+.....#
+...#.#
+..####
Y...###
#######`,

`
dir:NE
name:corner_sw
X=.
Y=#

#X...X#
#.....#
Y......
#......
Y......
#.....#
#######`,

`
dir:SW
name:corner_ne
X=#
Y=.

#X###X#
Y.....#
......#
......#
......#
Y.....#
#.....#`,

`
dir:SE
name:corner_nw
X=#
Y=#

#X###X#
#......
Y......
#......
Y......
#......
#.....#`
];

// Terminals
Castle.tiles.term = [
`
dir:N
name:term_n
X=#
Y=#

#X#+#X#
#.....#
Y.....#
#.....#
Y.....#
#.....#
#######`,

`
dir:S
name:term_s
X=#
Y=#

#X###X#
#.....#
Y.....#
#.....#
Y.....#
#.....#
###+###`,

`
dir:E
name:term_e
X=#
Y=#

#X###X#
#.....#
Y.....#
#.....+
Y.....#
#.....#
#######`,

`
dir:W
name:term_w
X=#
Y=#

#X###X#
#.....#
Y.....#
+.....#
Y.....#
#.....#
#######`
];

// Entrances
Castle.tiles.entrance = [
`
dir:NEW
name:entrance_n
X=.
Y=#

#X...X#
##...##
Y##.###
..#+#..
.......
Y.....#
#######`,

`
dir:SEW
name:entrance_s
X=#
Y=#

#X###X#
Y......
..#.#..
.##+##.
Y#...##
#.....#
##...##`
];

// Entrances
Castle.tiles.entranceWall = [
`
dir:NEW
name:entrance_n
X=.
Y=#

#X...X#
##...##
Y##.###
..#+#..
.......
Y.....#
##...##`,

`
dir:SEW
name:entrance_s
X=#
Y=#

#X...X#
Y.....#
..#.#..
.##+##.
Y#...##
#.....#
#.....#`
];

// Corridors
Castle.tiles.corridor = [
`
dir:NS
name:corridor_east
X=.
Y=#

#X...X#
#.....#
Y.....#
#.....#
Y.....#
#.....#
#.....#`,

`
dir:NS
name:corridor_west
X=.
Y=#

#X...X#
#.....#
Y.....#
#.....#
Y.....#
#.....#
#.....#`,

`
dir:EW
name:corridor_north
X=#
Y=.

#X###X#
.......
Y......
.......
Y......
.......
#######`,

`
dir:EW
name:corridor_south
X=#
Y=.

#X###X#
.......
Y......
.......
Y......
.......
#######`
];

// These provide exit from the main wall, however their exit direction is not
// specified thus they're treated as normal bi-directional corridors for PCG
Castle.tiles.corridorWithExit = [
`
dir:NS
name:corridor_east
X=.
Y=#

#X...X#
#.....#
Y#....#
......#
Y#....#
#.....#
#.....#`,

`
dir:NS
name:corridor_west
X=.
Y=#

#X...X#
#.....#
Y....##
#......
Y....##
#.....#
#.....#`,

`
dir:EW
name:corridor_north
X=#
Y=.

#X###X#
.......
Y......
.......
Y......
..#.#..
###.###`,

`
dir:EW
name:corridor_south
X=#
Y=.

#X#.#X#
..#.#..
Y......
.......
Y......
..#.#..
#######`
];

// Branching from the main wall
Castle.tiles.branch = [
`
dir:NSE
name:corridor_nse
X=.
Y=#

#X...X#
#.....#
Y.....#
#.....+
Y.....#
#.....#
#.....#`,

`
dir:NSW
name:corridor_nsw
X=#
Y=#

#X...X#
#.....#
Y.....#
+.....#
Y.....#
#.....#
##...##`,

`
dir:NEW
name:corridor_new
X=#
Y=.

#X#+#X#
.......
Y......
.......
Y......
.......
#######`,

`
dir:SEW
name:corridor_sew
X=#
Y=.

#X###X#
.......
Y......
.......
Y......
.......
###+###`
];

// Filler cell
Castle.tiles.fillerFloor = `
name:FILLER
X=.
Y=.

.X...X.
Y......
.......
.......
.......
Y......
.......`;

Castle.tiles.fillerWall = `
name:FILLER
X=#
Y=#

#X###X#
Y######
#######
#######
#######
Y######
#######`;

/* Returns the starting room for castle generation. */
Castle.startRoomFunc = function() {
    const midX = Math.floor(this.tilesX / 2);
    const north = RG.RAND.getUniform() <= 0.5;

    let templ = null;
    let y = 0;

    if (north) {
        templ = this.findTemplate({name: 'entrance_n'});
    }
    else {
        templ = this.findTemplate({name: 'entrance_s'});
        y = this.tilesY - 1;
    }
    return {
        x: midX, y, room: templ
    };
};

/* Start function if two fixed entrances are required. */
Castle.startFuncTwoGates = function() {
  const midX = Math.floor(this.tilesX / 2);
  const midY = Math.floor(this.tilesY / 2);
  const gateN = this.findTemplate({name: 'entrance_n'});
  const gateS = this.findTemplate({name: 'entrance_s'});

  // const vault = this.findTemplate({name: 'vault_small_s'});
  const corridor = this.findTemplate({name: 'corridor_new'});

  this.addRoom(gateN, midX, 0);

  Vault.func.createMediumVault(midX, midY - 1, this, corridor);
  Vault.func.createLargeVault(1, 1, this, corridor);
  // this.addRoom(corridor, midX, midY + 1);

  return {
    x: midX, y: this.tilesY - 1, room: gateS
  };

};

/* Constraint function how to generate the castle level. */
Castle.constraintFunc = function(x, y, exitReqd) {

    // Constraints for 4 corners
    if (x === 0 && y === 0) {
        return this.findTemplate({name: 'corner_nw'});
    }
    if (x === 0 && y === this.tilesY - 1) {
        return this.findTemplate({name: 'corner_sw'});
    }
    if (x === this.tilesX - 1 && y === 0) {
        return this.findTemplate({name: 'corner_ne'});
    }
    if (x === this.tilesX - 1 && y === this.tilesY - 1) {
        return this.findTemplate({name: 'corner_se'});
    }

    // Northern wall
    if (y === 0 ) {
        const ew = this.findTemplate({name: 'corridor_north'});
        const sew = this.findTemplate({name: 'corridor_sew'});
        if (sew) {
            if (exitReqd === 'S') {
                return sew;
            }
            if (RG.RAND.getUniform() < Castle.corridorDoorThr) {
                return sew;
            }
        }
        return ew;
    }
    // Southern wall
    else if (y === this.tilesY - 1) {
        const ew = this.findTemplate({name: 'corridor_south'});
        const corrNew = this.findTemplate({name: 'corridor_new'});
        if (corrNew) {
            if (exitReqd === 'N') {
                return corrNew;
            }
            if (RG.RAND.getUniform() < Castle.corridorDoorThr) {
                return corrNew;
            }
        }
        return ew;
    }

    // Western wall
    if (x === 0) {
        const corrNs = this.findTemplate({name: 'corridor_west'});
        const corrNse = this.findTemplate({name: 'corridor_nse'});
        if (corrNse) {
            if (exitReqd === 'E') {
                return corrNse;
            }
            if (RG.RAND.getUniform() < Castle.corridorDoorThr) {
                return corrNse;
            }
        }
        return corrNs;
    }
    // Eastern wall
    else if (x === this.tilesX - 1) {
        const corrNs = this.findTemplate({name: 'corridor_east'});
        const corrNsw = this.findTemplate({name: 'corridor_nsw'});
        if (corrNsw) {
            if (exitReqd === 'W') {
                return corrNsw;
            }
            if (RG.RAND.getUniform() < Castle.corridorDoorThr) {
                return corrNsw;
            }
        }
        return corrNs;
    }
    return null;
};

Castle.roomCount = -1; // Fill until no more exits

Castle.Models = {};

Castle.Models.full = []
    .concat(Castle.tiles.branch)
    .concat(Castle.tiles.corner)
    .concat(Castle.tiles.term)
    .concat(Castle.tiles.entrance)
    .concat(Castle.tiles.corridor)
    .concat(Vault.tiles.vault)
    .concat(Vault.tiles.corner);

Castle.Models.outerWall = []
    .concat(Castle.tiles.entranceWall)
    .concat(Castle.tiles.corner)
    .concat(Castle.tiles.corridor)
    .concat(Castle.tiles.corridorWithExit);

module.exports = Castle;
<|endoftext|>


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

function ActorSystem(name, node) {
    var counter = 0;
    this.name = name;
    this.path = "sactors://" + name;
    this.children = { };
    this.node = node;

    this.nextName = function () {
        counter++;
        return '_' + counter;
    }
}

ActorSystem.prototype.actorOf = function(clss, name, options) {
    var actor = newActor(clss, this, null, name, options);
    this.children[name] = actor;
    return actor;
}

ActorSystem.prototype.actorFor = function (name) {
    if (name.indexOf(':') > 0) {
        var path = parsePath(name);

        if (path.server) {
            var servername = path.server + ':' + path.port;
            if (servername !== this.node.name)
                return this.node.getNode(servername).getSystem(path.system).actorFor(path.path);
        }

        name = path.path;
    }

    if (name && name[0] === '/')
        name = name.substring(1);

    var position = name.indexOf('/');

    if (position > 0) {
        var rest = name.substring(position + 1);
        name = name.substring(0, position);
        return this.children[name].context.actorFor(rest);
    }
    else
        return this.children[name];
}

function RemoteActorSystem(name, node) {
    this.name = name;
    this.path = "sactors://" + name;
    this.node = node;
}

RemoteActorSystem.prototype.actorFor = function (name) {
    var path = this.path;

    if (name[0] === '/')
        path += name;
    else
        path += '/' + name;

    return new RemoteActorRef(this.node, path);
}

function newActor(clss, system, parent, name, options) {
    var actor;

    if (typeof clss === 'function')
        actor = new clss();
    else
        actor = clss;

    if (!name)
        name = system.nextName();

    var ref = new ActorRef(actor, parent ? parent.path : system.path, name);

    if (options && options.router)
        ref = new ActorRouterRef(ref);

    var context = new ActorContext(actor, ref, system, parent);

    return ref;
}

function ActorContext(actor, reference, system, parent) {
    actor.context = this;
    actor.self = reference;
    reference.context = this;
    this.system = system;
    this.self = reference;
    this.parent = parent;
    this.children = { };
}

ActorContext.prototype.actorOf = function(clss, name, options) {
    var child = newActor(clss, this.system, this.self, name, options);
    this.children[name] = child;
    return child;
}

ActorContext.prototype.actorFor = function(name) {
    if (name[0] === '/')
        return this.system.actorFor(name);

    if (name === '..')
        return this.parent;

    if (name.substring(0, 3) === '../')
        return this.parent.context.actorFor(name.substring(3));

    if (name.indexOf(':') > 0)
        return this.system.actorFor(name);

    var position = name.indexOf('/');

    if (position > 0) {
        var rest = name.substring(position + 1);
        name = name.substring(0, position);
        return this.children[name].context.actorFor(rest);
    }
    else
        return this.children[name];
}

function ActorRef(actor, parentpath, name) {
    this.actor = actor;

    this.path = parentpath + "/" + name;
}

ActorRef.prototype.tell = function (msg) {
    var self = this;
    process.nextTick(function () { self.actor.receive(msg); });
}

function ActorRouterRef(reference) {
    this.references = [ reference ];
    this.path = reference.path;
    this.position = 0;
}

ActorRouterRef.prototype.tell = function (msg) {
    var visited = 0;
    var length = this.references.length;

    for (var visited = 0; visited < length; visited++) {
        if (this.references[this.position])
            try {
                this.references[this.position].tell(msg);
                this.position = (this.position + 1) % this.references.length;
                return;
            }
            catch (err) {
            }

        this.position = (this.position + 1) % this.references.length;
    }
}

ActorRouterRef.prototype.add = function (reference) {
    this.references.push(reference);

    if (reference.actor) {
        reference.actor.self = this;
        reference.actor.context.self = this;
    }
}

function RemoteActorRef(node, path, remotenodename) {
    this.path = path;
    this.node = node;
    this.remote = remotenodename;
}

RemoteActorRef.prototype.tell = function (msg) {
    if (this.remote)
        this.node.tellNode(this.remote, this.path, msg);
    else
        this.node.process({ path: this.path, message: msg });
}

exports.create = function (name) {
    return new ActorSystem(name);
}

function parsePath(path) {
    var result = { };
    var position = path.indexOf(':');

    result.protocol = path.substring(0, position);

    var rest = path.substring(position + 3);

    var positionat = rest.indexOf('@');
    position = rest.indexOf('/');

    if (positionat >= 0 && positionat < position) {
        result.system = rest.substring(0, positionat);
        result.server = rest.substring(positionat + 1, position);

        var poscolon = result.server.indexOf(':');

        if (poscolon > 0) {
            result.port = parseInt(result.server.substring(poscolon + 1));
            result.server = result.server.substring(0, poscolon);
        }
    }
    else
        result.system = rest.substring(0, position);

    result.path = rest.substring(position);

    return result;
}

function makeName(port, host) {
    if (!port)
        return host;

    if (!host)
        host = 'localhost';

    return host + ':' + port;
}

function parseName(name) {
    var position = name.indexOf(':');
    var host;
    var port;

    if (position > 0) {
        host = name.substring(0, position);
        port = parseInt(name.substring(position+1));
    }
    else
        host = name;

    return { host: host, port: port };
}

exports.parsePath = parsePath;

function Node(port, host) {
    if (typeof port === 'string') {
        this.name = port;
        var porthost = parseName(port);
        port = porthost.port;
        host = porthost.host;
    }
    else
        this.name = makeName(port, host);

    var server;
    var systems = { };
    var nodes = [];
    var clients = [];

    this.create = function (name) {
        var fullname = name + '@' + this.name;
        var system = new ActorSystem(fullname, this);
        systems[name] = system;
        return system;
    }

    this.getSystem = function (name) {
        return systems[name];
    }

    this.start = function () {
        var self = this;
        server = simplemessages.createServer(function (stream) {
            stream.on('data', function (msg) {
                self.process(msg, stream);
            });
        });

        server.listen(port, host);
    }

    this.createRemoteNode = function (port, host) {
        if (typeof port === 'string')
            return new RemoteNode(port, this);
        else
            return new RemoteNode(port, host, this);
    }

    this.process = function (msg, sender) {
        // Tell message to actor
        if (msg.path) {
            var path = msg.path;
            var message = msg.message;
            var ph = parsePath(path);
            systems[ph.system].actorFor(ph.path).tell(message);
            return;
        }
        // New node
        if (msg.node) {
            new RemoteNode(msg.node, this, sender);
            return;
        }
    }

    this.registerNode = function (name, node) {
        nodes[name] = node;
    }

    this.getNode = function (name) {
        return nodes[name];
    }

    this.unregisterNode = function (name) {
        delete nodes[name];
    }

    this.tellNode = function (name, path, message) {
        nodes[name].process({ path: path, message: message });
    }

    this.stop = function () {
        if (server) {
            server.close();
            server = null;
        }

        nodes.forEach(function (node) { node.stop(); });
    }
}

function RemoteNode(port, host, local, client) {
    if (typeof port === 'string') {
        client = local;
        local = host;
        this.name = port;
        var porthost = parseName(port);
        port = porthost.port;
        host = porthost.host;
    }
    else
        this.name = makeName(port, host);

    var systems = { };

    if (local)
        local.registerNode(this.name, this);

    this.create = function (name) {
        var fullname = name + '@' + this.name;
        var system = new RemoteActorSystem(fullname, this);
        systems[name] = system;
        return system;
    }

    this.getSystem = function (name) {
        if (systems[name])
            return systems[name];

        return this.create(name);
    }

    this.start = function (fn) {
        var self = this;
        client = simplemessages.createClient(port, host, function() {
            client.on('end', function () { console.log('end'); client = null; });
            client.on('error', function () { console.log('error'); client = null; });
            client.on('close', function () { console.log('close'); client = null; });

            if (local) {
                client.on('end', function () { local.unregisterNode(this.name); });
                client.on('error', function () { local.unregisterNode(this.name); });
                client.on('close', function () { local.unregisterNode(this.name); });
                client.on('data', function (msg) { local.process(msg); });
                client.write({ node: local.name });
            }

            if (fn)
                fn(client);
        });
    }

    this.process = function (msg) {
        if (!client)
            throw "invalid socket";
        client.write(msg);
    }

    this.stop = function () {
        if (client) {
            client.end();
            client = null;
        }
    }
}

exports.createNode = function (port,host) {
    return new Node(port, host);
}

<commit_msg>Adding error handling on disconnection, router with invalid client<commit_after>
var simplemessages = require('simplemessages');

function ActorSystem(name, node) {
    var counter = 0;
    this.name = name;
    this.path = "sactors://" + name;
    this.children = { };
    this.node = node;

    this.nextName = function () {
        counter++;
        return '_' + counter;
    }
}

ActorSystem.prototype.actorOf = function(clss, name, options) {
    var actor = newActor(clss, this, null, name, options);
    this.children[name] = actor;
    return actor;
}

ActorSystem.prototype.actorFor = function (name) {
    if (name.indexOf(':') > 0) {
        var path = parsePath(name);

        if (path.server) {
            var servername = path.server + ':' + path.port;
            if (servername !== this.node.name)
                return this.node.getNode(servername).getSystem(path.system).actorFor(path.path);
        }

        name = path.path;
    }

    if (name && name[0] === '/')
        name = name.substring(1);

    var position = name.indexOf('/');

    if (position > 0) {
        var rest = name.substring(position + 1);
        name = name.substring(0, position);
        return this.children[name].context.actorFor(rest);
    }
    else
        return this.children[name];
}

function RemoteActorSystem(name, node) {
    this.name = name;
    this.path = "sactors://" + name;
    this.node = node;
}

RemoteActorSystem.prototype.actorFor = function (name) {
    var path = this.path;

    if (name[0] === '/')
        path += name;
    else
        path += '/' + name;

    return new RemoteActorRef(this.node, path);
}

function newActor(clss, system, parent, name, options) {
    var actor;

    if (typeof clss === 'function')
        actor = new clss();
    else
        actor = clss;

    if (!name)
        name = system.nextName();

    var ref = new ActorRef(actor, parent ? parent.path : system.path, name);

    if (options && options.router)
        ref = new ActorRouterRef(ref);

    var context = new ActorContext(actor, ref, system, parent);

    return ref;
}

function ActorContext(actor, reference, system, parent) {
    actor.context = this;
    actor.self = reference;
    reference.context = this;
    this.system = system;
    this.self = reference;
    this.parent = parent;
    this.children = { };
}

ActorContext.prototype.actorOf = function(clss, name, options) {
    var child = newActor(clss, this.system, this.self, name, options);
    this.children[name] = child;
    return child;
}

ActorContext.prototype.actorFor = function(name) {
    if (name[0] === '/')
        return this.system.actorFor(name);

    if (name === '..')
        return this.parent;

    if (name.substring(0, 3) === '../')
        return this.parent.context.actorFor(name.substring(3));

    if (name.indexOf(':') > 0)
        return this.system.actorFor(name);

    var position = name.indexOf('/');

    if (position > 0) {
        var rest = name.substring(position + 1);
        name = name.substring(0, position);
        return this.children[name].context.actorFor(rest);
    }
    else
        return this.children[name];
}

function ActorRef(actor, parentpath, name) {
    this.actor = actor;

    this.path = parentpath + "/" + name;
}

ActorRef.prototype.tell = function (msg) {
    var self = this;
    process.nextTick(function () { self.actor.receive(msg); });
}

function ActorRouterRef(reference) {
    this.references = [ reference ];
    this.path = reference.path;
    this.position = 0;
}

ActorRouterRef.prototype.tell = function (msg) {
    var visited = 0;
    var length = this.references.length;

    for (var visited = 0; visited < length; visited++) {
        if (this.references[this.position])
            try {
                this.references[this.position].tell(msg);
                this.position = (this.position + 1) % this.references.length;
                return;
            }
            catch (err) {
                this.references[this.position] = null;
                this.position = (this.position + 1) % this.references.length;
            }

        this.position = (this.position + 1) % this.references.length;
    }
}

ActorRouterRef.prototype.add = function (reference) {
    this.references.push(reference);

    if (reference.actor) {
        reference.actor.self = this;
        reference.actor.context.self = this;
    }
}

function RemoteActorRef(node, path, remotenodename) {
    this.path = path;
    this.node = node;
    this.remote = remotenodename;
}

RemoteActorRef.prototype.tell = function (msg) {
    if (this.remote)
        this.node.tellNode(this.remote, this.path, msg);
    else
        this.node.process({ path: this.path, message: msg });
}

exports.create = function (name) {
    return new ActorSystem(name);
}

function parsePath(path) {
    var result = { };
    var position = path.indexOf(':');

    result.protocol = path.substring(0, position);

    var rest = path.substring(position + 3);

    var positionat = rest.indexOf('@');
    position = rest.indexOf('/');

    if (positionat >= 0 && positionat < position) {
        result.system = rest.substring(0, positionat);
        result.server = rest.substring(positionat + 1, position);

        var poscolon = result.server.indexOf(':');

        if (poscolon > 0) {
            result.port = parseInt(result.server.substring(poscolon + 1));
            result.server = result.server.substring(0, poscolon);
        }
    }
    else
        result.system = rest.substring(0, position);

    result.path = rest.substring(position);

    return result;
}

function makeName(port, host) {
    if (!port)
        return host;

    if (!host)
        host = 'localhost';

    return host + ':' + port;
}

function parseName(name) {
    var position = name.indexOf(':');
    var host;
    var port;

    if (position > 0) {
        host = name.substring(0, position);
        port = parseInt(name.substring(position+1));
    }
    else
        host = name;

    return { host: host, port: port };
}

exports.parsePath = parsePath;

function Node(port, host) {
    if (typeof port === 'string') {
        this.name = port;
        var porthost = parseName(port);
        port = porthost.port;
        host = porthost.host;
    }
    else
        this.name = makeName(port, host);

    var server;
    var systems = { };
    var nodes = [];
    var clients = [];

    this.create = function (name) {
        var fullname = name + '@' + this.name;
        var system = new ActorSystem(fullname, this);
        systems[name] = system;
        return system;
    }

    this.getSystem = function (name) {
        return systems[name];
    }

    this.start = function () {
        var self = this;
        server = simplemessages.createServer(function (stream) {
            stream.on('data', function (msg) {
                self.process(msg, stream);
            });
            stream.on('error', function (err) {
                console.log('error', err);
            });
        });

        server.listen(port, host);
    }

    this.createRemoteNode = function (port, host) {
        if (typeof port === 'string')
            return new RemoteNode(port, this);
        else
            return new RemoteNode(port, host, this);
    }

    this.process = function (msg, sender) {
        // Tell message to actor
        if (msg.path) {
            var path = msg.path;
            var message = msg.message;
            var ph = parsePath(path);
            systems[ph.system].actorFor(ph.path).tell(message);
            return;
        }
        // New node
        if (msg.node) {
            new RemoteNode(msg.node, this, sender);
            return;
        }
    }

    this.registerNode = function (name, node) {
        nodes[name] = node;
    }

    this.getNode = function (name) {
        return nodes[name];
    }

    this.unregisterNode = function (name) {
        delete nodes[name];
    }

    this.tellNode = function (name, path, message) {
        nodes[name].process({ path: path, message: message });
    }

    this.stop = function () {
        if (server) {
            server.close();
            server = null;
        }

        nodes.forEach(function (node) { node.stop(); });
    }
}

function RemoteNode(port, host, local, client) {
    if (typeof port === 'string') {
        client = local;
        local = host;
        this.name = port;
        var porthost = parseName(port);
        port = porthost.port;
        host = porthost.host;
    }
    else
        this.name = makeName(port, host);

    var systems = { };

    if (local)
        local.registerNode(this.name, this);

    this.create = function (name) {
        var fullname = name + '@' + this.name;
        var system = new RemoteActorSystem(fullname, this);
        systems[name] = system;
        return system;
    }

    this.getSystem = function (name) {
        if (systems[name])
            return systems[name];

        return this.create(name);
    }

    this.start = function (fn) {
        var self = this;
        client = simplemessages.createClient(port, host, function() {
            client.on('end', function () { console.log('end'); client = null; });
            client.on('error', function (err) { console.log('error', err); client = null; });
            client.on('close', function () { console.log('close'); client = null; });

            if (local) {
                client.on('end', function () { local.unregisterNode(this.name); });
                client.on('error', function (err) { local.unregisterNode(this.name); });
                client.on('close', function () { local.unregisterNode(this.name); });
                client.on('data', function (msg) { local.process(msg); });
                client.write({ node: local.name });
            }

            if (fn)
                fn(client);
        });
    }

    this.process = function (msg) {
        if (!client)
            throw "Disconnected remote node";

        client.write(msg);
    }

    this.stop = function () {
        if (client) {
            client.end();
            client = null;
        }
    }
}

exports.createNode = function (port,host) {
    return new Node(port, host);
}

<|endoftext|>


<commit_before>TileMill.colors = {};

/**
 * Initialize colors - initialize colorpicker.
 */
TileMill.colors.init = function() {
  var color = $(TileMill.template('color', {}));
  return color;
};

TileMill.colors.initFarb = function(color) {
  var farb = $('#farbtastic', color);
  TileMill.colors.farbtastic = $.farbtastic(farb, {
      callback: 'input#color',
      width: 200,
      height: 200
  });

  $('a.color-picker', color).click(function() {
    farb.toggle('fast');
    return false;
  });
};

/**
 * Reload the color palatte. Find all color references and display a palette of
 * all unique colors.
 */
TileMill.colors.reload = function(stylesheets) {
  // Collect text from all tabs.
  var data = [];
  $('a.tab:not(.active) input', stylesheets).each(function() {
    data.push($(this).val());
  });
  data.push(TileMill.mirror.getCode());
  data = data.join('\n');

  var colors = [];
  var colors_div = $('div#colors div').empty();
  var matches = data.match(/\#[A-Fa-f0-9]{3,6}/g);
  if (matches) {
    for (var i = 0; i < matches.length; i++) {
      // Split up the color into an HSL triplet.
      var color = TileMill.colors.farbtastic.RGBToHSL(
          TileMill.colors.farbtastic.unpack(matches[i]));
      // Add the RGB to the color.
      color.push(matches[i]);
      var pass = false;
      for (var key in colors) {
        if (colors[key][3] == matches[i]) {
          pass = true;
          continue;
        }
      }
      if (!pass) {
        colors.push(color);
      }
    }
    // Sort the colors by lightness.
    colors.sort(function(a, b) { return a[2] - b[2]; });

    // Go through the colors and add them to the color palette. When one is
    // clicked, it's inserted into the document at the current cursor.
    $.each(colors, function(key, value) {
      colors_div.append(
        $(TileMill.template('color-swatch', {
            color: value[3]
        })));
    });
    $('a', colors_div).click(function() {
      TileMill.colors.insert($(this).text());
    });
  }
};

/**
 * Insert a color into the document
 *
 * @TODO Make this much better (replace selections etc).
 */
TileMill.colors.insert = function(color) {
  var position = TileMill.mirror.cursorPosition();
  TileMill.mirror.insertIntoLine(
      position.line,
      position.character, color);
};
<commit_msg>Fix color clicking to page loading. Fixes #26<commit_after>TileMill.colors = {};

/**
 * Initialize colors - initialize colorpicker.
 */
TileMill.colors.init = function() {
  var color = $(TileMill.template('color', {}));
  return color;
};

TileMill.colors.initFarb = function(color) {
  var farb = $('#farbtastic', color);
  TileMill.colors.farbtastic = $.farbtastic(farb, {
      callback: 'input#color',
      width: 200,
      height: 200
  });

  $('a.color-picker', color).click(function() {
    farb.toggle('fast');
    return false;
  });
};

/**
 * Reload the color palatte. Find all color references and display a palette of
 * all unique colors.
 */
TileMill.colors.reload = function(stylesheets) {
  // Collect text from all tabs.
  var data = [];
  $('a.tab:not(.active) input', stylesheets).each(function() {
    data.push($(this).val());
  });
  data.push(TileMill.mirror.getCode());
  data = data.join('\n');

  var colors = [];
  var colors_div = $('div#colors div').empty();
  var matches = data.match(/\#[A-Fa-f0-9]{3,6}/g);
  if (matches) {
    for (var i = 0; i < matches.length; i++) {
      // Split up the color into an HSL triplet.
      var color = TileMill.colors.farbtastic.RGBToHSL(
          TileMill.colors.farbtastic.unpack(matches[i]));
      // Add the RGB to the color.
      color.push(matches[i]);
      var pass = false;
      for (var key in colors) {
        if (colors[key][3] == matches[i]) {
          pass = true;
          continue;
        }
      }
      if (!pass) {
        colors.push(color);
      }
    }
    // Sort the colors by lightness.
    colors.sort(function(a, b) { return a[2] - b[2]; });

    // Go through the colors and add them to the color palette. When one is
    // clicked, it's inserted into the document at the current cursor.
    $.each(colors, function(key, value) {
      colors_div.append(
        $(TileMill.template('color-swatch', {
            color: value[3]
        })));
    });
    $('a', colors_div).click(function() {
      return TileMill.colors.insert($(this).text());
    });
  }
};

/**
 * Insert a color into the document
 *
 * @TODO Make this much better (replace selections etc).
 */
TileMill.colors.insert = function(color) {
  var position = TileMill.mirror.cursorPosition();
  TileMill.mirror.insertIntoLine(
      position.line,
      position.character, color);
  return false;
};
<|endoftext|>


<commit_before>/* globals qq, ExifRestorer */
/**
 * Controls generation of scaled images based on a reference image encapsulated in a `File` or `Blob`.
 * Scaled images are generated and converted to blobs on-demand.
 * Multiple scaled images per reference image with varying sizes and other properties are supported.
 *
 * @param spec Information about the scaled images to generate.
 * @param log Logger instance
 * @constructor
 */
qq.Scaler = function(spec, log) {
    "use strict";

    var includeReference = spec.sendOriginal,
        orient = spec.orient,
        defaultType = spec.defaultType,
        defaultQuality = spec.defaultQuality / 100,
        failedToScaleText = spec.failureText,
        includeExif = spec.includeExif,
        sizes = this._getSortedSizes(spec.sizes);

    // Revealed API for instances of this module
    qq.extend(this, {
        // If no targeted sizes have been declared or if this browser doesn't support
        // client-side image preview generation, there is no scaling to do.
        enabled: qq.supportedFeatures.imagePreviews && sizes.length > 0,

        getFileRecords: function(originalFileUuid, originalFileName, originalBlobOrBlobData) {
            var self = this,
                records = [],
                originalBlob = originalBlobOrBlobData.blob ? originalBlobOrBlobData.blob : originalBlobOrBlobData,
                idenitifier = new qq.Identify(originalBlob, log);

            // If the reference file cannot be rendered natively, we can't create scaled versions.
            if (idenitifier.isPreviewableSync()) {
                // Create records for each scaled version & add them to the records array, smallest first.
                qq.each(sizes, function(idx, sizeRecord) {
                    var outputType = self._determineOutputType({
                        defaultType: defaultType,
                        requestedType: sizeRecord.type,
                        refType: originalBlob.type
                    });

                    records.push({
                        uuid: qq.getUniqueId(),
                        name: self._getName(originalFileName, {
                            name: sizeRecord.name,
                            type: outputType,
                            refType: originalBlob.type
                        }),
                        blob: new qq.BlobProxy(originalBlob,
                            qq.bind(self._generateScaledImage, self, {
                                maxSize: sizeRecord.maxSize,
                                orient: orient,
                                type: outputType,
                                quality: defaultQuality,
                                failedText: failedToScaleText,
                                includeExif: includeExif,
                                log: log
                            }))
                        }
                    );
                });
            }

            // Finally, add a record for the original file (if requested)
            includeReference && records.push({
                uuid: originalFileUuid,
                name: originalFileName,
                blob: originalBlob
            });

            return records;
        }
    });
};

qq.extend(qq.Scaler.prototype, {
    // NOTE: We cannot reliably determine at this time if the UA supports a specific MIME type for the target format.
    // image/jpeg and image/png are the only safe choices at this time.
    _determineOutputType: function(spec) {
        "use strict";

        var requestedType = spec.requestedType,
            defaultType = spec.defaultType,
            referenceType = spec.refType;

        // If a default type and requested type have not been specified, this should be a
        // JPEG if the original type is a JPEG, otherwise, a PNG.
        if (!defaultType && !requestedType) {
            if (referenceType !== "image/jpeg") {
                return "image/png";
            }
            return referenceType;
        }

        // A specified default type is used when a requested type is not specified.
        if (!requestedType) {
            return defaultType;
        }

        // If requested type is specified, use it, as long as this recognized type is supported by the current UA
        if (qq.indexOf(Object.keys(qq.Identify.prototype.PREVIEWABLE_MIME_TYPES), requestedType) >= 0) {
            if (requestedType === "image/tiff") {
                return qq.supportedFeatures.tiffPreviews ? requestedType : defaultType;
            }

            return requestedType;
        }

        return defaultType;
    },

    // Get a file name for a generated scaled file record, based on the provided scaled image description
    _getName: function(originalName, scaledVersionProperties) {
        "use strict";

        var startOfExt = originalName.lastIndexOf("."),
            nameAppendage = " (" + scaledVersionProperties.name + ")",
            versionType = scaledVersionProperties.type || "image/png",
            referenceType = scaledVersionProperties.refType,
            scaledName = "",
            scaledExt = qq.getExtension(originalName);

        if (startOfExt >= 0) {
            scaledName = originalName.substr(0, startOfExt);

            if (referenceType !== versionType) {
                scaledExt = versionType.split("/")[1];
            }

            scaledName += nameAppendage + "." + scaledExt;
        }
        else {
            scaledName = originalName + nameAppendage;
        }

        return scaledName;
    },

    // We want the smallest scaled file to be uploaded first
    _getSortedSizes: function(sizes) {
        "use strict";

        sizes = qq.extend([], sizes);

        return sizes.sort(function(a, b) {
            if (a.maxSize > b.maxSize) {
                return 1;
            }
            if (a.maxSize < b.maxSize) {
                return -1;
            }
            return 0;
        });
    },

    _generateScaledImage: function(spec, sourceFile) {
        "use strict";

        var self = this,
            log = spec.log,
            maxSize = spec.maxSize,
            orient = spec.orient,
            type = spec.type,
            quality = spec.quality,
            failedText = spec.failedText,
            includeExif = spec.includeExif && sourceFile.type === "image/jpeg" && type === "image/jpeg",
            scalingEffort = new qq.Promise(),
            imageGenerator = new qq.ImageGenerator(log),
            canvas = document.createElement("canvas");

        log("Attempting to generate scaled version for " + sourceFile.name);

        imageGenerator.generate(sourceFile, canvas, {maxSize: maxSize, orient: orient}).then(function() {
            var scaledImageDataUri = canvas.toDataURL(type, quality),
                reader = includeExif && new FileReader(),
                signalSuccess = function() {
                    log("Success generating scaled version for " + sourceFile.name);
                    var blob = self._dataUriToBlob(scaledImageDataUri);
                    scalingEffort.success(blob);
                };

            if (includeExif) {
                // Attempt to re-insert EXIF header from original image into scaled image
                reader.onload = function () {
                    var originalImageDataUri = reader.result;
                    scaledImageDataUri = ExifRestorer.restore(originalImageDataUri, scaledImageDataUri);
                    signalSuccess();
                };

                reader.readAsDataURL(sourceFile);
            }
            else {
                signalSuccess();
            }
        }, function() {
            log("Failed attempt to generate scaled version for " + sourceFile.name, "error");
            scalingEffort.failure(failedText);
        });

        return scalingEffort;
    },

    _dataUriToBlob: function(dataUri) {
        "use strict";

        var byteString, mimeString, arrayBuffer, intArray;

        // convert base64 to raw binary data held in a string
        if (dataUri.split(",")[0].indexOf("base64") >= 0) {
            byteString = atob(dataUri.split(",")[1]);
        }
        else {
            byteString = decodeURI(dataUri.split(",")[1]);
        }

        // extract the MIME
        mimeString = dataUri.split(",")[0]
            .split(":")[1]
            .split(";")[0];

        // write the bytes of the binary string to an ArrayBuffer
        arrayBuffer = new ArrayBuffer(byteString.length);
        intArray = new Uint8Array(arrayBuffer);
        qq.each(byteString, function(idx, char) {
            intArray[idx] = char.charCodeAt(0);
        });

        return this._createBlob(arrayBuffer, mimeString);
    },

    _createBlob: function(data, mime) {
        "use strict";

        var BlobBuilder = window.BlobBuilder ||
                window.WebKitBlobBuilder ||
                window.MozBlobBuilder ||
                window.MSBlobBuilder,
            blobBuilder = BlobBuilder && new BlobBuilder();

        if (blobBuilder) {
            blobBuilder.append(data);
            return blobBuilder.getBlob(mime);
        }
        else {
            return new Blob([data], {type: mime});
        }
    }
});
<commit_msg>feat($scaling): cleanup EXIF parser code a bit #1136<commit_after>/* globals qq, ExifRestorer */
/**
 * Controls generation of scaled images based on a reference image encapsulated in a `File` or `Blob`.
 * Scaled images are generated and converted to blobs on-demand.
 * Multiple scaled images per reference image with varying sizes and other properties are supported.
 *
 * @param spec Information about the scaled images to generate.
 * @param log Logger instance
 * @constructor
 */
qq.Scaler = function(spec, log) {
    "use strict";

    var includeReference = spec.sendOriginal,
        orient = spec.orient,
        defaultType = spec.defaultType,
        defaultQuality = spec.defaultQuality / 100,
        failedToScaleText = spec.failureText,
        includeExif = spec.includeExif,
        sizes = this._getSortedSizes(spec.sizes);

    // Revealed API for instances of this module
    qq.extend(this, {
        // If no targeted sizes have been declared or if this browser doesn't support
        // client-side image preview generation, there is no scaling to do.
        enabled: qq.supportedFeatures.imagePreviews && sizes.length > 0,

        getFileRecords: function(originalFileUuid, originalFileName, originalBlobOrBlobData) {
            var self = this,
                records = [],
                originalBlob = originalBlobOrBlobData.blob ? originalBlobOrBlobData.blob : originalBlobOrBlobData,
                idenitifier = new qq.Identify(originalBlob, log);

            // If the reference file cannot be rendered natively, we can't create scaled versions.
            if (idenitifier.isPreviewableSync()) {
                // Create records for each scaled version & add them to the records array, smallest first.
                qq.each(sizes, function(idx, sizeRecord) {
                    var outputType = self._determineOutputType({
                        defaultType: defaultType,
                        requestedType: sizeRecord.type,
                        refType: originalBlob.type
                    });

                    records.push({
                        uuid: qq.getUniqueId(),
                        name: self._getName(originalFileName, {
                            name: sizeRecord.name,
                            type: outputType,
                            refType: originalBlob.type
                        }),
                        blob: new qq.BlobProxy(originalBlob,
                            qq.bind(self._generateScaledImage, self, {
                                maxSize: sizeRecord.maxSize,
                                orient: orient,
                                type: outputType,
                                quality: defaultQuality,
                                failedText: failedToScaleText,
                                includeExif: includeExif,
                                log: log
                            }))
                        }
                    );
                });
            }

            // Finally, add a record for the original file (if requested)
            includeReference && records.push({
                uuid: originalFileUuid,
                name: originalFileName,
                blob: originalBlob
            });

            return records;
        }
    });
};

qq.extend(qq.Scaler.prototype, {
    // NOTE: We cannot reliably determine at this time if the UA supports a specific MIME type for the target format.
    // image/jpeg and image/png are the only safe choices at this time.
    _determineOutputType: function(spec) {
        "use strict";

        var requestedType = spec.requestedType,
            defaultType = spec.defaultType,
            referenceType = spec.refType;

        // If a default type and requested type have not been specified, this should be a
        // JPEG if the original type is a JPEG, otherwise, a PNG.
        if (!defaultType && !requestedType) {
            if (referenceType !== "image/jpeg") {
                return "image/png";
            }
            return referenceType;
        }

        // A specified default type is used when a requested type is not specified.
        if (!requestedType) {
            return defaultType;
        }

        // If requested type is specified, use it, as long as this recognized type is supported by the current UA
        if (qq.indexOf(Object.keys(qq.Identify.prototype.PREVIEWABLE_MIME_TYPES), requestedType) >= 0) {
            if (requestedType === "image/tiff") {
                return qq.supportedFeatures.tiffPreviews ? requestedType : defaultType;
            }

            return requestedType;
        }

        return defaultType;
    },

    // Get a file name for a generated scaled file record, based on the provided scaled image description
    _getName: function(originalName, scaledVersionProperties) {
        "use strict";

        var startOfExt = originalName.lastIndexOf("."),
            nameAppendage = " (" + scaledVersionProperties.name + ")",
            versionType = scaledVersionProperties.type || "image/png",
            referenceType = scaledVersionProperties.refType,
            scaledName = "",
            scaledExt = qq.getExtension(originalName);

        if (startOfExt >= 0) {
            scaledName = originalName.substr(0, startOfExt);

            if (referenceType !== versionType) {
                scaledExt = versionType.split("/")[1];
            }

            scaledName += nameAppendage + "." + scaledExt;
        }
        else {
            scaledName = originalName + nameAppendage;
        }

        return scaledName;
    },

    // We want the smallest scaled file to be uploaded first
    _getSortedSizes: function(sizes) {
        "use strict";

        sizes = qq.extend([], sizes);

        return sizes.sort(function(a, b) {
            if (a.maxSize > b.maxSize) {
                return 1;
            }
            if (a.maxSize < b.maxSize) {
                return -1;
            }
            return 0;
        });
    },

    _generateScaledImage: function(spec, sourceFile) {
        "use strict";

        var self = this,
            log = spec.log,
            maxSize = spec.maxSize,
            orient = spec.orient,
            type = spec.type,
            quality = spec.quality,
            failedText = spec.failedText,
            includeExif = spec.includeExif && sourceFile.type === "image/jpeg" && type === "image/jpeg",
            scalingEffort = new qq.Promise(),
            imageGenerator = new qq.ImageGenerator(log),
            canvas = document.createElement("canvas");

        log("Attempting to generate scaled version for " + sourceFile.name);

        imageGenerator.generate(sourceFile, canvas, {maxSize: maxSize, orient: orient}).then(function() {
            var scaledImageDataUri = canvas.toDataURL(type, quality),
                signalSuccess = function() {
                    log("Success generating scaled version for " + sourceFile.name);
                    var blob = self._dataUriToBlob(scaledImageDataUri);
                    scalingEffort.success(blob);
                };

            if (includeExif) {
                self._insertExifHeader(sourceFile, scaledImageDataUri, log).then(function(scaledImageDataUriWithExif) {
                    scaledImageDataUri = scaledImageDataUriWithExif;
                    signalSuccess();
                },
                function() {
                    log("Problem inserting EXIF header into scaled image.  Using scaled image w/out EXIF data.", "error");
                    signalSuccess();
                });
            }
            else {
                signalSuccess();
            }
        }, function() {
            log("Failed attempt to generate scaled version for " + sourceFile.name, "error");
            scalingEffort.failure(failedText);
        });

        return scalingEffort;
    },

    // Attempt to insert the original image's EXIF header into a scaled version.
    _insertExifHeader: function(originalImage, scaledImageDataUri, log) {
        "use strict";

        var reader = new FileReader(),
            insertionEffort = new qq.Promise(),
            originalImageDataUri = "";

        reader.onload = function() {
            originalImageDataUri = reader.result;
            insertionEffort.success(ExifRestorer.restore(originalImageDataUri, scaledImageDataUri));
        };

        reader.onerror = function() {
            log("Problem reading " + originalImage.name + " during attempt to transfer EXIF data to scaled version.", "error");
            insertionEffort.failure();
        };

        reader.readAsDataURL(originalImage);

        return insertionEffort;
    },

    _dataUriToBlob: function(dataUri) {
        "use strict";

        var byteString, mimeString, arrayBuffer, intArray;

        // convert base64 to raw binary data held in a string
        if (dataUri.split(",")[0].indexOf("base64") >= 0) {
            byteString = atob(dataUri.split(",")[1]);
        }
        else {
            byteString = decodeURI(dataUri.split(",")[1]);
        }

        // extract the MIME
        mimeString = dataUri.split(",")[0]
            .split(":")[1]
            .split(";")[0];

        // write the bytes of the binary string to an ArrayBuffer
        arrayBuffer = new ArrayBuffer(byteString.length);
        intArray = new Uint8Array(arrayBuffer);
        qq.each(byteString, function(idx, char) {
            intArray[idx] = char.charCodeAt(0);
        });

        return this._createBlob(arrayBuffer, mimeString);
    },

    _createBlob: function(data, mime) {
        "use strict";

        var BlobBuilder = window.BlobBuilder ||
                window.WebKitBlobBuilder ||
                window.MozBlobBuilder ||
                window.MSBlobBuilder,
            blobBuilder = BlobBuilder && new BlobBuilder();

        if (blobBuilder) {
            blobBuilder.append(data);
            return blobBuilder.getBlob(mime);
        }
        else {
            return new Blob([data], {type: mime});
        }
    }
});
<|endoftext|>


<commit_before>import React,{Component,PropTypes} from "react";
import {
    PickerIOS,
    Platform,
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Modal,
    Dimensions
} from "react-native";

import PickerAndroid,{PickerItemAndroid} from './androidPicker';
import langs from '../lang';

const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;

let _Picker = Platform.OS === 'ios' ? PickerIOS : PickerAndroid;
let _PickerItem = Platform.OS === 'ios' ? _Picker.Item : PickerItemAndroid;

export default class SinglePicker extends Component {
    constructor(props) {
        super(props);
        this.lang = langs[this.props.lang];
        this.state = {
            options: this.props.options,
            modalVisible: false,
            selectedOption: this.props.options.filter((op)=> op.key === this.props.defaultSelectedValue)[0] || {}
        }
    }

    static propTypes = {
        options: PropTypes.array.isRequired,
        defaultSelectedValue: PropTypes.any,
        onConfirm: PropTypes.func,
        onSelect: PropTypes.func,
        onCancel: PropTypes.func,
        lang: PropTypes.string,
        style: PropTypes.object
    }

    static defaultProps = {
        lang: "zh-CN",
        style: {backgroundColor: "white"},
        onConfirm: ()=> {
        },
        onSelect: ()=> {
        },
        onCancel: ()=> {
        },
        setOption: ()=> {
        },
    }

    show() {
        this.setState(Object.assign({}, this.state, {modalVisible: true}));
    }

    hide() {
        this.setState({modalVisible: false});
    }

    setOption(options, defaultSelectedValue) {
        this.setState(Object.assign({}, this.state, {
            options: options,
            selectedOption: options.filter((op)=> op.key === defaultSelectedValue)[0] || {}
        }))
    }

    render() {
        return (
            <Modal
                animationType={'slide'}
                transparent={true}
                onRequestClose={()=>{}}
                visible={this.state.modalVisible}>
                <View style={styles.basicContainer}>
                    <View style={[styles.modalContainer,this.props.style]}>
                        <View style={{backgroundColor:'#CACACA',height:0.5,width: SCREEN_WIDTH}}/>
                        <View style={styles.buttonView}>
                            <TouchableOpacity style={[styles.button,styles.buttonLeft]} onPress={() => {
                                    this.props.onCancel();
                                    this.setState({modalVisible: false});
                                }}>
                                <Text>{this.lang.BTN_CANCEL}</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={[styles.button,styles.buttonRight]} onPress={() => {
                                if (this.props.onConfirm) {
                                    if (!this.state.selectedOption.key && this.state.selectedOption.key !== 0) {
                                        let submitData = this.state.options[0] || {};
                                        if (!submitData && this.state.defaultSelectedValue) {
                                            submitData = this.state.options.filter((op)=> op.key === this.state.defaultSelectedValue)[0];
                                        }
                                        this.props.onConfirm(submitData);
                                    } else {
                                        this.props.onConfirm(this.state.selectedOption);
                                    }
                                }
                                this.setState({modalVisible: false});
                            }}>
                                <Text>{this.lang.BTN_CONFIRM}</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={{backgroundColor:'#CACACA',height:0.5,width: SCREEN_WIDTH}}/>
                        <View style={styles.mainBox}>
                            <_Picker
                                ref={'picker'}
                                style={styles.bottomPicker}
                                selectedValue={(this.state.selectedOption.key || this.state.selectedOption === 0) ? this.state.selectedOption.key : this.state.defaultSelectedValue}
                                onValueChange={val => {
                                    let curOption = this.state.options.filter((op)=> op.key === val)[0];
                                    this.props.onSelect(curOption);
                                    this.setState(
                                        Object.assign({},this.state,{selectedOption:curOption}));
                                }}>
                                {this.state.options.map((option, i) => {
                                    return (
                                        <_PickerItem
                                            key={i}
                                            value={option.key}
                                            label={option.value}
                                        />
                                    )
                                })}
                            </_Picker>
                        </View>
                    </View>
                </View>
            </Modal>
        )
    }
}

var styles = StyleSheet.create({
    basicContainer: {
        flex: 1,
        justifyContent: 'flex-end',
        alignItems: 'center'
    },
    modalContainer: {
        width: SCREEN_WIDTH,
        justifyContent: 'center',
        alignItems: 'center',
        padding: 0
    },
    buttonView: {
        height: 30,
        width: SCREEN_WIDTH,
        justifyContent: 'space-between',
        alignItems: 'center',
        flexDirection: 'row'
    },
    bottomPicker: {
        width: SCREEN_WIDTH,
        height: SCREEN_HEIGHT / 3 * 1,
    },
    mainBox: {},
    button: {
        flex: 0.5,
        flexDirection: 'row',
        alignItems: 'center'
    },
    buttonLeft: {
        justifyContent: 'flex-start'
    },
    buttonRight: {
        justifyContent: 'flex-end'
    }
})<commit_msg>add styles AcceptButtonStyle, CancelButtonStyle, HeaderStyle<commit_after>import React,{Component,PropTypes} from "react";
import {
    PickerIOS,
    Platform,
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Modal,
    Dimensions
} from "react-native";

import PickerAndroid,{PickerItemAndroid} from './androidPicker';
import langs from '../lang';

const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;

let _Picker = Platform.OS === 'ios' ? PickerIOS : PickerAndroid;
let _PickerItem = Platform.OS === 'ios' ? _Picker.Item : PickerItemAndroid;

export default class SinglePicker extends Component {
    constructor(props) {
        super(props);
        this.lang = langs[this.props.lang];
        this.state = {
            options: this.props.options,
            modalVisible: false,
            selectedOption: this.props.options.filter((op)=> op.key === this.props.defaultSelectedValue)[0] || {}
        }
    }

    static propTypes = {
        options: PropTypes.array.isRequired,
        defaultSelectedValue: PropTypes.any,
        onConfirm: PropTypes.func,
        onSelect: PropTypes.func,
        onCancel: PropTypes.func,
        lang: PropTypes.string,
        style: PropTypes.object,
        buttonCancelStyle: PropTypes.any,
        buttonAcceptStyle: PropTypes.any,
        headerStyle: PropTypes.any,
    }

    static defaultProps = {
        lang: "zh-CN",
        style: {backgroundColor: "white"},
        onConfirm: ()=> {
        },
        onSelect: ()=> {
        },
        onCancel: ()=> {
        },
        setOption: ()=> {
        },
    }

    show() {
        this.setState(Object.assign({}, this.state, {modalVisible: true}));
    }

    hide() {
        this.setState({modalVisible: false});
    }

    setOption(options, defaultSelectedValue) {
        this.setState(Object.assign({}, this.state, {
            options: options,
            selectedOption: options.filter((op)=> op.key === defaultSelectedValue)[0] || {}
        }))
    }

    render() {
        return (
            <Modal
                animationType={'slide'}
                transparent={true}
                onRequestClose={()=>{}}
                visible={this.state.modalVisible}>
                <View style={styles.basicContainer}>
                    <View style={[styles.modalContainer,this.props.style]}>
                        <View style={{backgroundColor:'#CACACA',height:0.5,width: SCREEN_WIDTH}}/>
                        <View style={[styles.buttonView, this.props.headerStyle]}>
                            <TouchableOpacity style={[styles.button,styles.buttonLeft]} onPress={() => {
                                    this.props.onCancel();
                                    this.setState({modalVisible: false});
                                }}>
                                <Text style={this.props.buttonCancelStyle}>{this.lang.BTN_CANCEL}</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={[styles.button,styles.buttonRight]} onPress={() => {
                                if (this.props.onConfirm) {
                                    if (!this.state.selectedOption.key && this.state.selectedOption.key !== 0) {
                                        let submitData = this.state.options[0] || {};
                                        if (!submitData && this.state.defaultSelectedValue) {
                                            submitData = this.state.options.filter((op)=> op.key === this.state.defaultSelectedValue)[0];
                                        }
                                        this.props.onConfirm(submitData);
                                    } else {
                                        this.props.onConfirm(this.state.selectedOption);
                                    }
                                }
                                this.setState({modalVisible: false});
                            }}>
                                <Text style={this.props.buttonAcceptStyle}>{this.lang.BTN_CONFIRM}</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={{backgroundColor:'#CACACA',height:0.5,width: SCREEN_WIDTH}}/>
                        <View style={styles.mainBox}>
                            <_Picker
                                ref={'picker'}
                                style={styles.bottomPicker}
                                selectedValue={(this.state.selectedOption.key || this.state.selectedOption === 0) ? this.state.selectedOption.key : this.state.defaultSelectedValue}
                                onValueChange={val => {
                                    let curOption = this.state.options.filter((op)=> op.key === val)[0];
                                    this.props.onSelect(curOption);
                                    this.setState(
                                        Object.assign({},this.state,{selectedOption:curOption}));
                                }}>
                                {this.state.options.map((option, i) => {
                                    return (
                                        <_PickerItem
                                            key={i}
                                            value={option.key}
                                            label={option.value}
                                        />
                                    )
                                })}
                            </_Picker>
                        </View>
                    </View>
                </View>
            </Modal>
        )
    }
}

var styles = StyleSheet.create({
    basicContainer: {
        flex: 1,
        justifyContent: 'flex-end',
        alignItems: 'center'
    },
    modalContainer: {
        width: SCREEN_WIDTH,
        justifyContent: 'center',
        alignItems: 'center',
        padding: 0
    },
    buttonView: {
        height: 30,
        width: SCREEN_WIDTH,
        justifyContent: 'space-between',
        alignItems: 'center',
        flexDirection: 'row'
    },
    bottomPicker: {
        width: SCREEN_WIDTH,
        height: SCREEN_HEIGHT / 3 * 1,
    },
    mainBox: {},
    button: {
        flex: 0.5,
        flexDirection: 'row',
        alignItems: 'center'
    },
    buttonLeft: {
        justifyContent: 'flex-start'
    },
    buttonRight: {
        justifyContent: 'flex-end'
    }
})<|endoftext|>


<commit_before>const express = require('express');
const path = require('path');
const serveStatic = require('serve-static');
const app = express();

app.use(serveStatic(__dirname));

app.listen(8080);
console.log('server started on 8080');<commit_msg>fixed port issue for production(heroku)<commit_after>const express = require('express');
const path = require('path');
const serveStatic = require('serve-static');
const app = express();

app.use(serveStatic(__dirname));

app.listen(process.env.PORT || 8080)
console.log('server started on 8080');<|endoftext|>


<commit_before>'use strict';

let Relay  = require('./relay');
let Socket = require('./socket');
let config = Bento.config.socket;

// ### IO
// Instatiate the IO emitter that lets instances communicate with
// the socket.io server instance.

let io = require('redis-emitter')({
  host : config.redis.host,
  port : config.redis.port
});

// ### IO
// Gives direct access to the instanced IO as well as a sugar user method
// to communicate directly with authenticated sockets.

Bento.IO = new Socket(io);

// ### Relay
// Custom functions provides a easy way to send relay payloads to the front end.

Bento.Relay = new Relay(io);
<commit_msg>socket updates<commit_after>'use strict';

let Relay  = require('./relay');
let Socket = require('./socket');
let config = Bento.config.socket;

const { Emitter } = require('@socket.io/redis-emitter');
const { createClient } = require("redis");

const redisClient = createClient({
    host : config.redis.host,
    port : config.redis.port
});
const io = new Emitter(redisClient);

// Gives direct access to the instanced IO as well as a sugar user method
// to communicate directly with authenticated sockets.
Bento.IO = new Socket(io);

// Custom functions provides a easy way to send relay payloads to the front end.
Bento.Relay = new Relay(io);
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var net = require('net')
  , Emitter = require('events').EventEmitter;

/**
 * Expose `Socket`.
 */

module.exports = Socket;

/**
 * Initialize a new `Socket`.
 *
 * A super socket "Socket" encapsulates the
 * reconnection logic with exponential backoff,
 * serving as a base for the `Queue`.
 *
 * @api private
 */

function Socket() {
  var self = this;
  var sock = this.sock = new net.Socket;

  this.retryTimeout = this.retry = 100;
  this.retryMaxTimeout = 2000;

  sock.on('error', function(err){
    if ('ECONNREFUSED' != err.code) {
      self.emit('error', err);
    }
  });

  sock.on('data', function(chunk){
    self.emit('data', chunk);
  });

  sock.on('close', function(){
    self.connected = false;
    if (self.closing) return self.emit('close');
    setTimeout(function(){
      self.emit('reconnect attempt');
      sock.destroy();
      self.connect(self.port);
      self.retry = Math.min(self.retryMaxTimeout, self.retry * 1.5);
    }, self.retry);
  });

  sock.on('connect', function(){
    self.connected = true;
    self.retry = self.retryTimeout;
    self.emit('connect');
    self.callback && self.callback();
  });
}

/**
 * Inherit from `Emitter.prototype`.
 */

Socket.prototype.__proto__ = Emitter.prototype;

/**
 * Connect to `port` and invoke `fn()`.
 *
 * TODO: host
 *
 * @param {Number} port
 * @param {Function} fn
 * @api public
 */

Socket.prototype.connect = function(port, fn){
  this.type = 'client';
  this.port = port;
  this.sock.connect(port, '127.0.0.1');
  this.callback = fn;
  return this;
};

/**
 * Close the socket.
 *
 * @api public
 */

Socket.prototype.close = function(){
  this.closing = true;
  this.sock.destroy();
  return this;
};
<commit_msg>add socket debug() instrumentation<commit_after>
/**
 * Module dependencies.
 */

var net = require('net')
  , Emitter = require('events').EventEmitter
  , debug = require('debug')('ss:sock');

/**
 * Expose `Socket`.
 */

module.exports = Socket;

/**
 * Initialize a new `Socket`.
 *
 * A super socket "Socket" encapsulates the
 * reconnection logic with exponential backoff,
 * serving as a base for the `Queue`.
 *
 * @api private
 */

function Socket() {
  var self = this;
  var sock = this.sock = new net.Socket;

  this.retryTimeout = this.retry = 100;
  this.retryMaxTimeout = 2000;

  sock.on('error', function(err){
    if ('ECONNREFUSED' != err.code) {
      self.emit('error', err);
    }
  });

  sock.on('data', function(chunk){
    self.emit('data', chunk);
  });

  sock.on('close', function(){
    self.connected = false;
    if (self.closing) return self.emit('close');
    setTimeout(function(){
      debug('attempting reconnect');
      self.emit('reconnect attempt');
      sock.destroy();
      self.connect(self.port);
      self.retry = Math.min(self.retryMaxTimeout, self.retry * 1.5);
    }, self.retry);
  });

  sock.on('connect', function(){
    debug('connect');
    self.connected = true;
    self.retry = self.retryTimeout;
    self.emit('connect');
    self.callback && self.callback();
  });
}

/**
 * Inherit from `Emitter.prototype`.
 */

Socket.prototype.__proto__ = Emitter.prototype;

/**
 * Connect to `port` and invoke `fn()`.
 *
 * TODO: host
 *
 * @param {Number} port
 * @param {Function} fn
 * @api public
 */

Socket.prototype.connect = function(port, fn){
  debug('connect %s', port);
  this.type = 'client';
  this.port = port;
  this.sock.connect(port, '127.0.0.1');
  this.callback = fn;
  return this;
};

/**
 * Close the socket.
 *
 * @api public
 */

Socket.prototype.close = function(){
  debug('close');
  this.closing = true;
  this.sock.destroy();
  return this;
};
<|endoftext|>


<commit_before>module.exports = {
	start,
}

function start({state, actions, opts: {ws}}) {
	ws.receive(event => {
		let data = JSON.parse(event.data)
		actions[data.topic](data.payload)
	})

	actions.getConfig()
	actions.getTree("/")
	actions.getStorage()

	return state
}
<commit_msg>Remove call to getTree<commit_after>module.exports = {
	start,
}

function start({state, actions, opts: {ws}}) {
	ws.receive(event => {
		let data = JSON.parse(event.data)
		actions[data.topic](data.payload)
	})

	actions.getConfig()
	// actions.getTree("/")
	actions.getStorage()

	return state
}
<|endoftext|>