<commit_before>/* global angular: true */

(function()
{

function onOff(value)
{
    return value ? 'on' : 'off';
} // end onOff

var queryID = 0;

angular.module('webPGQ.services')
    .service('sql', ['$exceptionHandler', 'eventEmitter', 'socket', 'logger', 'promise',
    function($exceptionHandler, eventEmitter, socket, logger, promise)
    {
        var channel;

        socket.on('connected', function()
        {
            socket.channel('sql')
                .then(function(chan)
                {
                    channel = chan;

                    channel.on('notice', function(notice)
                    {
                        logger.info('Notice:', notice, 'sql');

                        sqlService.emit.apply(sqlService, ['notice'].concat(Array.slice.call(arguments)));
                    });

                    sqlService.emit('ready');
                });
        });

        var explainOptions = {
            VERBOSE: {
                enabled: true,
                description: 'TODO',
                icon: 'bullhorn'
            },
            COSTS: {
                enabled: true,
                description: 'TODO',
                icon: 'dollar'
            },
            BUFFERS: {
                enabled: true,
                description: 'TODO',
                icon: 'tasks'
            },
            TIMING: {
                enabled: true,
                description: 'TODO',
                icon: 'time'
            }
        };

        var sqlService = {
            explainOptions: explainOptions,

            connect: function(connectionInfo)
            {
                logger.debug('Connecting to:', connectionInfo, 'sql');

                return promise(function(resolve)
                {
                    resolve(channel.request('connect', connectionInfo));
                })
                .then(function()
                {
                    logger.success('Connected to:', connectionInfo, 'sql');
                    return true;
                })
                .catch(function(error)
                {
                    logger.error('Error connecting to ' + angular.toJson(connectionInfo) + ':', error, 'sql');
                    throw error;
                });
            }, // end connect

            run: function(queryDef)
            {
                queryDef.queryID = queryID;
                logger.debug('Running query:', queryDef, 'sql');

                return promise(function(resolve)
                {
                    var onFields = this.emit.bind(this, 'fields');
                    var onRow = this.emit.bind(this, 'row');

                    channel.on('fields', onFields);
                    channel.on('row', onRow);

                    resolve(channel.request('query', queryDef)
                        .finally(function()
                        {
                            channel.removeListener('fields', onFields);
                            channel.removeListener('row', onRow);
                        })
                        .then(function(response)
                        {
                            logger.success('Query finished:', response, 'sql');
                            return response;
                        })
                        .catch(function(error)
                        {
                            logger.error('Error running query:', error, 'sql');
                            throw error;
                        })
                    );
                });
            }, // end run

            formatExplain: function(explainOptions, analyze)
            {
                console.log("Explaining query" + (analyze ? " with ANALYZE" : ""));
                console.log("explainOptions:", explainOptions);

                return "EXPLAIN(" +
                    ["ANALYZE " + onOff(analyze)]
                        .concat(
                            Object.keys(explainOptions)
                                .map(function(key)
                                {
                                    var value = explainOptions[key].enabled;

                                    if(!analyze && (key == 'BUFFERS' || key == 'TIMING'))
                                    {
                                        // BUFFERS and TIMING are not valid unless using ANALYZE.
                                        value = false;
                                    } // end if

                                    return key + ' ' + onOff(value);
                                }),
                            "FORMAT JSON"
                        )
                    .join(', ') +
                    ") ";
            }, // end formatExplain

            explain: function(queryDef, explainOptions, analyze)
            {
                queryDef.text = this.formatExplain(explainOptions, analyze) + queryDef.text;

                return this.run(queryDef);
            } // end explain
        };

        eventEmitter.inject({prototype: sqlService});
        sqlService.removeListener = sqlService.off;

        return sqlService;
    }]);

})();
<commit_msg>Cleaned up log messages from 'sql' service.<commit_after>/* global angular: true */

(function()
{

function onOff(value)
{
    return value ? 'on' : 'off';
} // end onOff

var queryID = 0;

angular.module('webPGQ.services')
    .service('sql', ['$exceptionHandler', 'eventEmitter', 'socket', 'logger', 'promise',
    function($exceptionHandler, eventEmitter, socket, logger, promise)
    {
        var channel;

        socket.on('connected', function()
        {
            socket.channel('sql')
                .then(function(chan)
                {
                    channel = chan;

                    channel.on('notice', function(notice)
                    {
                        logger.info('Notice:', notice, 'sql');

                        sqlService.emit.apply(sqlService, ['notice'].concat(Array.slice.call(arguments)));
                    });

                    sqlService.emit('ready');
                });
        });

        var explainOptions = {
            VERBOSE: {
                enabled: true,
                description: 'TODO',
                icon: 'bullhorn'
            },
            COSTS: {
                enabled: true,
                description: 'TODO',
                icon: 'dollar'
            },
            BUFFERS: {
                enabled: true,
                description: 'TODO',
                icon: 'tasks'
            },
            TIMING: {
                enabled: true,
                description: 'TODO',
                icon: 'time'
            }
        };

        var sqlService = {
            explainOptions: explainOptions,

            connect: function(connectionInfo)
            {
                logger.debug('Connecting...', connectionInfo, 'sql');

                return promise(function(resolve)
                {
                    resolve(channel.request('connect', connectionInfo));
                })
                .then(function()
                {
                    logger.success('Connected to database.', connectionInfo, 'sql');
                    return true;
                })
                .catch(function(error)
                {
                    logger.error('Error connecting to ' + angular.toJson(connectionInfo) + ':', error, 'sql');
                    throw error;
                });
            }, // end connect

            run: function(queryDef)
            {
                queryDef.queryID = queryID;
                logger.debug('Running query:', queryDef, 'sql');

                return promise(function(resolve)
                {
                    var onFields = this.emit.bind(this, 'fields');
                    var onRow = this.emit.bind(this, 'row');

                    channel.on('fields', onFields);
                    channel.on('row', onRow);

                    resolve(channel.request('query', queryDef)
                        .finally(function()
                        {
                            channel.removeListener('fields', onFields);
                            channel.removeListener('row', onRow);
                        })
                        .spread(function(response)
                        {
                            logger.success('Query finished:', response, 'sql');
                            return response;
                        })
                        .catch(function(error)
                        {
                            logger.error('Error running query:', error, 'sql');
                            throw error;
                        })
                    );
                });
            }, // end run

            formatExplain: function(explainOptions, analyze)
            {
                console.log("Explaining query" + (analyze ? " with ANALYZE" : ""));
                console.log("explainOptions:", explainOptions);

                return "EXPLAIN(" +
                    ["ANALYZE " + onOff(analyze)]
                        .concat(
                            Object.keys(explainOptions)
                                .map(function(key)
                                {
                                    var value = explainOptions[key].enabled;

                                    if(!analyze && (key == 'BUFFERS' || key == 'TIMING'))
                                    {
                                        // BUFFERS and TIMING are not valid unless using ANALYZE.
                                        value = false;
                                    } // end if

                                    return key + ' ' + onOff(value);
                                }),
                            "FORMAT JSON"
                        )
                    .join(', ') +
                    ") ";
            }, // end formatExplain

            explain: function(queryDef, explainOptions, analyze)
            {
                queryDef.text = this.formatExplain(explainOptions, analyze) + queryDef.text;

                return this.run(queryDef);
            } // end explain
        };

        eventEmitter.inject({prototype: sqlService});
        sqlService.removeListener = sqlService.off;

        return sqlService;
    }]);

})();
<|endoftext|>


<commit_before>/// <reference path="../typings/node/node.d.ts"/>
/// <reference path="../typings/mocha/mocha.d.ts"/>
/*eslint-env node */
/*eslint-env mocha*/
'use strict';

var networkId = 'TEST NETWORK ID';
var adleria
	= require('../')(networkId, 'TEST API TOKEN', {url: 'http://localhost:2341/cms/'});

var chai = require('chai');
chai.use(require('chai-datetime'));
var expect = require('chai').expect;
var chaiThings = require('chai-things');

chai.use(chaiThings);

var BASE_URL = process.env.ADSHER_HOST + ':' + process.env.ADSHER_PORT;

describe('Adspaces', function(){
	var adspaceId;

	before(function(){
		return adleria.adspaces.create({name: 'Test Adspace'}).then(function(adspace){
			adspaceId = adspace._id;
		});
	});

	it('should be possible to create a player into an adspace', function(){
		return adleria.adspaces(adspaceId).players.create({name: 'Test Player'}).then(function(player){
			return adleria.adspaces(adspaceId).players.list().then(function(players){
				expect(players).to.be.an('array');
				expect(players.length).to.be.equal(1);
				expect(players[0]).to.be.an('object');
				expect(players[0]).to.have.property('name', 'Test Player');
			});
		});
	});

	it('should be possible to assign/unassign a player to an adspace', function(){
		var playerId;
		return adleria.adspaces(adspaceId).players.create({name: 'Test Player'}).then(function(player){
			playerId = player._id;
			return adleria.adspaces(adspaceId).players.unassign(playerId);
		}).then(function(){
			return adleria.adspaces(adspaceId).players.assign(playerId);
		});
	});

	it('should be possible to assign many players to an adspace', function(){
		//return adleria.adspaces(adspaceId).players.create({name: 'Test Player'});
	});
});
<commit_msg>Added tests for adspaces<commit_after>/// <reference path="../typings/node/node.d.ts"/>
/// <reference path="../typings/mocha/mocha.d.ts"/>
/*eslint-env node */
/*eslint-env mocha*/
'use strict';

var networkId = 'text-network-id';
var adleria
  = require('../')(networkId, 'test-x-test', {url: 'http://localhost:2341/cms/'});

var chai = require('chai');
chai.use(require('chai-datetime'));
var expect = require('chai').expect;
var chaiThings = require('chai-things');

chai.use(chaiThings);

var BASE_URL = process.env.ADSHER_HOST + ':' + process.env.ADSHER_PORT;

describe('Adleria API', function(){

  describe('Adspaces', function(){
    var adspaceId = null;
    var ownerId = '12345';
    it('should be posible to create adspace', function(){
      var data = {
        name: 'Test Adspace',
        ownerId: ownerId
      }
      return adleria.adspaces.create(data).then(function(adspace){
        expect(adspace.name).to.equal(data.name);
        expect(adspace.ownerId).to.be.equal(data.ownerId);
        adspaceId = adspace._id;
      });
    });
    it('should be posible to list adspaces', function(){
      var filter = {
        ownerId: ownerId
      }
      return adleria.adspaces.list(filter).then(function(adspaces){
        adspaces.forEach(function(adspace){
          expect(adspace.ownerId).to.equal(ownerId);
        });
      });
    });
    it('should be posible to edit adspace', function(){
      var update = {
        name: 'edited adspace',
        ownerId: ownerId
      };

      return adleria.adspaces.edit(adspaceId, update).then(function(adspace){
        expect(adspace.name).to.equal(update.name);
        expect(adspace.ownerId).to.equal(ownerId);
      })
    });
    it('should be posible to delete adspace', function(){
      return adleria.adspaces.delete(adspaceId, {ownerId: ownerId}).then(function(res){
        expect(res);
      });
    });
    describe('Players', function(){
      var adspaceId;

      before(function(){
        return adleria.adspaces.create({name: 'Test Adspace'}).then(function(adspace){
          adspaceId = adspace._id;
        });
      });
      it('should be possible to create a player into an adspace', function(){
        return adleria.adspaces(adspaceId).players.create({name: 'Test Player'}).then(function(player){
          return adleria.adspaces(adspaceId).players.list().then(function(players){
            expect(players).to.be.an('array');
            expect(players.length).to.be.equal(1);
            expect(players[0]).to.be.an('object');
            expect(players[0]).to.have.property('name', 'Test Player');
          });
        });
      });

      it('should be possible to assign/unassign a player to an adspace', function(){
        var playerId;
        return adleria.adspaces(adspaceId).players.create({name: 'Test Player'}).then(function(player){
          playerId = player._id;
          return adleria.adspaces(adspaceId).players.unassign(playerId);
        }).then(function(){
          return adleria.adspaces(adspaceId).players.assign(playerId);
        });
      });

      it('should be possible to assign many players to an adspace', function(){
        //return adleria.adspaces(adspaceId).players.create({name: 'Test Player'});
      });
    });
  });
});
<|endoftext|>


<commit_before>/*
Language: Apache
Author: Ruslan Keba <rukeba@gmail.com>
Website: http://rukeba.com/
Description: language definition for Apache configuration files (httpd.conf & .htaccess)
Version 1.1
Date: 2008-12-27
*/

hljs.LANGUAGES.apache =
{
  case_insensitive: true,
  defaultMode: {
    lexems: [hljs.IDENT_RE],
    contains: ['comment', 'sqbracket', 'cbracket', 'number', 'tag'],
    keywords: {
      'keyword': {
        'acceptfilter': 1,
        'acceptmutex': 1,
        'acceptpathinfo': 1,
        'accessfilename': 1,
        'action': 1,
        'addalt': 1,
        'addaltbyencoding': 1,
        'addaltbytype': 1,
        'addcharset': 1,
        'adddefaultcharset': 1,
        'adddescription': 1,
        'addencoding': 1,
        'addhandler': 1,
        'addicon': 1,
        'addiconbyencoding': 1,
        'addiconbytype': 1,
        'addinputfilter': 1,
        'addlanguage': 1,
        'addmoduleinfo': 1,
        'addoutputfilter': 1,
        'addoutputfilterbytype': 1,
        'addtype': 1,
        'alias': 1,
        'aliasmatch': 1,
        'allowconnect': 1,
        'allowencodedslashes': 1,
        'allowoverride': 1,
        'anonymous': 1,
        'anonymous_logemail': 1,
        'anonymous_mustgiveemail': 1,
        'anonymous_nouserid': 1,
        'anonymous_verifyemail': 1,
        'authbasicauthoritative': 1,
        'authbasicprovider': 1,
        'authdbduserpwquery': 1,
        'authdbduserrealmquery': 1,
        'authdbmgroupfile': 1,
        'authdbmtype': 1,
        'authdbmuserfile': 1,
        'authdefaultauthoritative': 1,
        'authdigestalgorithm': 1,
        'authdigestdomain': 1,
        'authdigestnccheck': 1,
        'authdigestnonceformat': 1,
        'authdigestnoncelifetime': 1,
        'authdigestprovider': 1,
        'authdigestqop': 1,
        'authdigestshmemsize': 1,
        'authgroupfile': 1,
        'authldapbinddn': 1,
        'authldapbindpassword': 1,
        'authldapcharsetconfig': 1,
        'authldapcomparednonserver': 1,
        'authldapdereferencealiases': 1,
        'authldapgroupattribute': 1,
        'authldapgroupattributeisdn': 1,
        'authldapremoteuserattribute': 1,
        'authldapremoteuserisdn': 1,
        'authldapurl': 1,
        'authname': 1,
        'authnprovideralias': 1,
        'authtype': 1,
        'authuserfile': 1,
        'authzdbmauthoritative': 1,
        'authzdbmtype': 1,
        'authzdefaultauthoritative': 1,
        'authzgroupfileauthoritative': 1,
        'authzldapauthoritative': 1,
        'authzownerauthoritative': 1,
        'authzuserauthoritative': 1,
        'balancermember': 1,
        'browsermatch': 1,
        'browsermatchnocase': 1,
        'bufferedlogs': 1,
        'cachedefaultexpire': 1,
        'cachedirlength': 1,
        'cachedirlevels': 1,
        'cachedisable': 1,
        'cacheenable': 1,
        'cachefile': 1,
        'cacheignorecachecontrol': 1,
        'cacheignoreheaders': 1,
        'cacheignorenolastmod': 1,
        'cacheignorequerystring': 1,
        'cachelastmodifiedfactor': 1,
        'cachemaxexpire': 1,
        'cachemaxfilesize': 1,
        'cacheminfilesize': 1,
        'cachenegotiateddocs': 1,
        'cacheroot': 1,
        'cachestorenostore': 1,
        'cachestoreprivate': 1,
        'cgimapextension': 1,
        'charsetdefault': 1,
        'charsetoptions': 1,
        'charsetsourceenc': 1,
        'checkcaseonly': 1,
        'checkspelling': 1,
        'chrootdir': 1,
        'contentdigest': 1,
        'cookiedomain': 1,
        'cookieexpires': 1,
        'cookielog': 1,
        'cookiename': 1,
        'cookiestyle': 1,
        'cookietracking': 1,
        'coredumpdirectory': 1,
        'customlog': 1,
        'dav': 1,
        'davdepthinfinity': 1,
        'davgenericlockdb': 1,
        'davlockdb': 1,
        'davmintimeout': 1,
        'dbdexptime': 1,
        'dbdkeep': 1,
        'dbdmax': 1,
        'dbdmin': 1,
        'dbdparams': 1,
        'dbdpersist': 1,
        'dbdpreparesql': 1,
        'dbdriver': 1,
        'defaulticon': 1,
        'defaultlanguage': 1,
        'defaulttype': 1,
        'deflatebuffersize': 1,
        'deflatecompressionlevel': 1,
        'deflatefilternote': 1,
        'deflatememlevel': 1,
        'deflatewindowsize': 1,
        'directoryindex': 1,
        'directorymatch': 1,
        'directoryslash': 1,
        'documentroot': 1,
        'dumpioinput': 1,
        'dumpiologlevel': 1,
        'dumpiooutput': 1,
        'enableexceptionhook': 1,
        'enablemmap': 1,
        'enablesendfile': 1,
        'errordocument': 1,
        'example': 1,
        'expiresactive': 1,
        'expiresbytype': 1,
        'expiresdefault': 1,
        'extendedstatus': 1,
        'extfilterdefine': 1,
        'extfilteroptions': 1,
        'fileetag': 1,
        'filterchain': 1,
        'filterdeclare': 1,
        'filterprotocol': 1,
        'filterprovider': 1,
        'filtertrace': 1,
        'forcelanguagepriority': 1,
        'forcetype': 1,
        'forensiclog': 1,
        'gracefulshutdowntimeout': 1,
        'group': 1,
        'header': 1,
        'headername': 1,
        'hostnamelookups': 1,
        'identitycheck': 1,
        'identitychecktimeout': 1,
        'imapbase': 1,
        'imapdefault': 1,
        'imapmenu': 1,
        'include': 1,
        'indexheadinsert': 1,
        'indexignore': 1,
        'indexoptions': 1,
        'indexorderdefault': 1,
        'indexstylesheet': 1,
        'isapiappendlogtoerrors': 1,
        'isapiappendlogtoquery': 1,
        'isapicachefile': 1,
        'isapifakeasync': 1,
        'isapilognotsupported': 1,
        'isapireadaheadbuffer': 1,
        'keepalive': 1,
        'keepalivetimeout': 1,
        'languagepriority': 1,
        'ldapcacheentries': 1,
        'ldapcachettl': 1,
        'ldapconnectiontimeout': 1,
        'ldapopcacheentries': 1,
        'ldapopcachettl': 1,
        'ldapsharedcachefile': 1,
        'ldapsharedcachesize': 1,
        'ldaptrustedclientcert': 1,
        'ldaptrustedglobalcert': 1,
        'ldaptrustedmode': 1,
        'ldapverifyservercert': 1,
        'limitinternalrecursion': 1,
        'limitrequestbody': 1,
        'limitrequestfields': 1,
        'limitrequestfieldsize': 1,
        'limitrequestline': 1,
        'limitxmlrequestbody': 1,
        'listen': 1,
        'listenbacklog': 1,
        'loadfile': 1,
        'loadmodule': 1,
        'lockfile': 1,
        'logformat': 1,
        'loglevel': 1,
        'maxclients': 1,
        'maxkeepaliverequests': 1,
        'maxmemfree': 1,
        'maxrequestsperchild': 1,
        'maxrequestsperthread': 1,
        'maxspareservers': 1,
        'maxsparethreads': 1,
        'maxthreads': 1,
        'mcachemaxobjectcount': 1,
        'mcachemaxobjectsize': 1,
        'mcachemaxstreamingbuffer': 1,
        'mcacheminobjectsize': 1,
        'mcacheremovalalgorithm': 1,
        'mcachesize': 1,
        'metadir': 1,
        'metafiles': 1,
        'metasuffix': 1,
        'mimemagicfile': 1,
        'minspareservers': 1,
        'minsparethreads': 1,
        'mmapfile': 1,
        'mod_gzip_on': 1,
        'mod_gzip_add_header_count': 1,
        'mod_gzip_keep_workfiles': 1,
        'mod_gzip_dechunk': 1,
        'mod_gzip_min_http': 1,
        'mod_gzip_minimum_file_size': 1,
        'mod_gzip_maximum_file_size': 1,
        'mod_gzip_maximum_inmem_size': 1,
        'mod_gzip_temp_dir': 1,
        'mod_gzip_item_include': 1,
        'mod_gzip_item_exclude': 1,
        'mod_gzip_command_version': 1,
        'mod_gzip_can_negotiate': 1,
        'mod_gzip_handle_methods': 1,
        'mod_gzip_static_suffix': 1,
        'mod_gzip_send_vary': 1,
        'mod_gzip_update_static': 1,
        'modmimeusepathinfo': 1,
        'multiviewsmatch': 1,
        'namevirtualhost': 1,
        'noproxy': 1,
        'nwssltrustedcerts': 1,
        'nwsslupgradeable': 1,
        'options': 1,
        'passenv': 1,
        'pidfile': 1,
        'protocolecho': 1,
        'proxybadheader': 1,
        'proxyblock': 1,
        'proxydomain': 1,
        'proxyerroroverride': 1,
        'proxyftpdircharset': 1,
        'proxyiobuffersize': 1,
        'proxymaxforwards': 1,
        'proxypass': 1,
        'proxypassinterpolateenv': 1,
        'proxypassmatch': 1,
        'proxypassreverse': 1,
        'proxypassreversecookiedomain': 1,
        'proxypassreversecookiepath': 1,
        'proxypreservehost': 1,
        'proxyreceivebuffersize': 1,
        'proxyremote': 1,
        'proxyremotematch': 1,
        'proxyrequests': 1,
        'proxyset': 1,
        'proxystatus': 1,
        'proxytimeout': 1,
        'proxyvia': 1,
        'readmename': 1,
        'receivebuffersize': 1,
        'redirect': 1,
        'redirectmatch': 1,
        'redirectpermanent': 1,
        'redirecttemp': 1,
        'removecharset': 1,
        'removeencoding': 1,
        'removehandler': 1,
        'removeinputfilter': 1,
        'removelanguage': 1,
        'removeoutputfilter': 1,
        'removetype': 1,
        'requestheader': 1,
        'require': 2,
        'rewritebase': 1,
        'rewritecond': 10,
        'rewriteengine': 1,
        'rewritelock': 1,
        'rewritelog': 1,
        'rewriteloglevel': 1,
        'rewritemap': 1,
        'rewriteoptions': 1,
        'rewriterule': 10,
        'rlimitcpu': 1,
        'rlimitmem': 1,
        'rlimitnproc': 1,
        'satisfy': 1,
        'scoreboardfile': 1,
        'script': 1,
        'scriptalias': 1,
        'scriptaliasmatch': 1,
        'scriptinterpretersource': 1,
        'scriptlog': 1,
        'scriptlogbuffer': 1,
        'scriptloglength': 1,
        'scriptsock': 1,
        'securelisten': 1,
        'seerequesttail': 1,
        'sendbuffersize': 1,
        'serveradmin': 1,
        'serveralias': 1,
        'serverlimit': 1,
        'servername': 1,
        'serverpath': 1,
        'serverroot': 1,
        'serversignature': 1,
        'servertokens': 1,
        'setenv': 1,
        'setenvif': 1,
        'setenvifnocase': 1,
        'sethandler': 1,
        'setinputfilter': 1,
        'setoutputfilter': 1,
        'ssienableaccess': 1,
        'ssiendtag': 1,
        'ssierrormsg': 1,
        'ssistarttag': 1,
        'ssitimeformat': 1,
        'ssiundefinedecho': 1,
        'sslcacertificatefile': 1,
        'sslcacertificatepath': 1,
        'sslcadnrequestfile': 1,
        'sslcadnrequestpath': 1,
        'sslcarevocationfile': 1,
        'sslcarevocationpath': 1,
        'sslcertificatechainfile': 1,
        'sslcertificatefile': 1,
        'sslcertificatekeyfile': 1,
        'sslciphersuite': 1,
        'sslcryptodevice': 1,
        'sslengine': 1,
        'sslhonorciperorder': 1,
        'sslmutex': 1,
        'ssloptions': 1,
        'sslpassphrasedialog': 1,
        'sslprotocol': 1,
        'sslproxycacertificatefile': 1,
        'sslproxycacertificatepath': 1,
        'sslproxycarevocationfile': 1,
        'sslproxycarevocationpath': 1,
        'sslproxyciphersuite': 1,
        'sslproxyengine': 1,
        'sslproxymachinecertificatefile': 1,
        'sslproxymachinecertificatepath': 1,
        'sslproxyprotocol': 1,
        'sslproxyverify': 1,
        'sslproxyverifydepth': 1,
        'sslrandomseed': 1,
        'sslrequire': 1,
        'sslrequiressl': 1,
        'sslsessioncache': 1,
        'sslsessioncachetimeout': 1,
        'sslusername': 1,
        'sslverifyclient': 1,
        'sslverifydepth': 1,
        'startservers': 1,
        'startthreads': 1,
        'substitute': 1,
        'suexecusergroup': 1,
        'threadlimit': 1,
        'threadsperchild': 1,
        'threadstacksize': 1,
        'timeout': 1,
        'traceenable': 1,
        'transferlog': 1,
        'typesconfig': 1,
        'unsetenv': 1,
        'usecanonicalname': 1,
        'usecanonicalphysicalport': 1,
        'user': 1,
        'userdir': 1,
        'virtualdocumentroot': 1,
        'virtualdocumentrootip': 1,
        'virtualscriptalias': 1,
        'virtualscriptaliasip': 1,
        'win32disableacceptex': 1,
        'xbithack': 1
      },
      'literal': {'on': 1, 'off': 1}
    }
  },
  modes: [
    hljs.HASH_COMMENT_MODE,
    {
      /* TODO: check tag content: Location, Files, VirtualHost, ... */
      className: 'tag',
      begin: '</?', end: '>'
    },
    {
      className: 'sqbracket',
      begin: '\\s\\[', end: '\\]$'
    },
    {
      className: 'cbracket',
      begin: '[\\$%]\\{', end: '\\}',
      contains: ['cbracket', 'number']
    },
    {
      className: 'number',
      begin: '[\\$%]\\d+', end: '^'
    },
    hljs.BACKSLASH_ESCAPE
  ]
};
<commit_msg>ErrorLog, Allow, Deny keywords and string mode for apache.js<commit_after>/*
Language: Apache
Author: Ruslan Keba <rukeba@gmail.com>
Website: http://rukeba.com/
Description: language definition for Apache configuration files (httpd.conf & .htaccess)
Version 1.1
Date: 2008-12-27
*/

hljs.LANGUAGES.apache =
{
  case_insensitive: true,
  defaultMode: {
    lexems: [hljs.IDENT_RE],
    contains: ['comment', 'sqbracket', 'cbracket', 'number', 'tag', 'string'],
    keywords: {
      'keyword': {
        'acceptfilter': 1,
        'acceptmutex': 1,
        'acceptpathinfo': 1,
        'accessfilename': 1,
        'action': 1,
        'addalt': 1,
        'addaltbyencoding': 1,
        'addaltbytype': 1,
        'addcharset': 1,
        'adddefaultcharset': 1,
        'adddescription': 1,
        'addencoding': 1,
        'addhandler': 1,
        'addicon': 1,
        'addiconbyencoding': 1,
        'addiconbytype': 1,
        'addinputfilter': 1,
        'addlanguage': 1,
        'addmoduleinfo': 1,
        'addoutputfilter': 1,
        'addoutputfilterbytype': 1,
        'addtype': 1,
        'alias': 1,
        'aliasmatch': 1,
        'allow': 1,
        'allowconnect': 1,
        'allowencodedslashes': 1,
        'allowoverride': 1,
        'anonymous': 1,
        'anonymous_logemail': 1,
        'anonymous_mustgiveemail': 1,
        'anonymous_nouserid': 1,
        'anonymous_verifyemail': 1,
        'authbasicauthoritative': 1,
        'authbasicprovider': 1,
        'authdbduserpwquery': 1,
        'authdbduserrealmquery': 1,
        'authdbmgroupfile': 1,
        'authdbmtype': 1,
        'authdbmuserfile': 1,
        'authdefaultauthoritative': 1,
        'authdigestalgorithm': 1,
        'authdigestdomain': 1,
        'authdigestnccheck': 1,
        'authdigestnonceformat': 1,
        'authdigestnoncelifetime': 1,
        'authdigestprovider': 1,
        'authdigestqop': 1,
        'authdigestshmemsize': 1,
        'authgroupfile': 1,
        'authldapbinddn': 1,
        'authldapbindpassword': 1,
        'authldapcharsetconfig': 1,
        'authldapcomparednonserver': 1,
        'authldapdereferencealiases': 1,
        'authldapgroupattribute': 1,
        'authldapgroupattributeisdn': 1,
        'authldapremoteuserattribute': 1,
        'authldapremoteuserisdn': 1,
        'authldapurl': 1,
        'authname': 1,
        'authnprovideralias': 1,
        'authtype': 1,
        'authuserfile': 1,
        'authzdbmauthoritative': 1,
        'authzdbmtype': 1,
        'authzdefaultauthoritative': 1,
        'authzgroupfileauthoritative': 1,
        'authzldapauthoritative': 1,
        'authzownerauthoritative': 1,
        'authzuserauthoritative': 1,
        'balancermember': 1,
        'browsermatch': 1,
        'browsermatchnocase': 1,
        'bufferedlogs': 1,
        'cachedefaultexpire': 1,
        'cachedirlength': 1,
        'cachedirlevels': 1,
        'cachedisable': 1,
        'cacheenable': 1,
        'cachefile': 1,
        'cacheignorecachecontrol': 1,
        'cacheignoreheaders': 1,
        'cacheignorenolastmod': 1,
        'cacheignorequerystring': 1,
        'cachelastmodifiedfactor': 1,
        'cachemaxexpire': 1,
        'cachemaxfilesize': 1,
        'cacheminfilesize': 1,
        'cachenegotiateddocs': 1,
        'cacheroot': 1,
        'cachestorenostore': 1,
        'cachestoreprivate': 1,
        'cgimapextension': 1,
        'charsetdefault': 1,
        'charsetoptions': 1,
        'charsetsourceenc': 1,
        'checkcaseonly': 1,
        'checkspelling': 1,
        'chrootdir': 1,
        'contentdigest': 1,
        'cookiedomain': 1,
        'cookieexpires': 1,
        'cookielog': 1,
        'cookiename': 1,
        'cookiestyle': 1,
        'cookietracking': 1,
        'coredumpdirectory': 1,
        'customlog': 1,
        'dav': 1,
        'davdepthinfinity': 1,
        'davgenericlockdb': 1,
        'davlockdb': 1,
        'davmintimeout': 1,
        'dbdexptime': 1,
        'dbdkeep': 1,
        'dbdmax': 1,
        'dbdmin': 1,
        'dbdparams': 1,
        'dbdpersist': 1,
        'dbdpreparesql': 1,
        'dbdriver': 1,
        'defaulticon': 1,
        'defaultlanguage': 1,
        'defaulttype': 1,
        'deflatebuffersize': 1,
        'deflatecompressionlevel': 1,
        'deflatefilternote': 1,
        'deflatememlevel': 1,
        'deflatewindowsize': 1,
        'deny': 1,
        'directoryindex': 1,
        'directorymatch': 1,
        'directoryslash': 1,
        'documentroot': 1,
        'dumpioinput': 1,
        'dumpiologlevel': 1,
        'dumpiooutput': 1,
        'enableexceptionhook': 1,
        'enablemmap': 1,
        'enablesendfile': 1,
        'errordocument': 1,
        'errorlog': 1,
        'example': 1,
        'expiresactive': 1,
        'expiresbytype': 1,
        'expiresdefault': 1,
        'extendedstatus': 1,
        'extfilterdefine': 1,
        'extfilteroptions': 1,
        'fileetag': 1,
        'filterchain': 1,
        'filterdeclare': 1,
        'filterprotocol': 1,
        'filterprovider': 1,
        'filtertrace': 1,
        'forcelanguagepriority': 1,
        'forcetype': 1,
        'forensiclog': 1,
        'gracefulshutdowntimeout': 1,
        'group': 1,
        'header': 1,
        'headername': 1,
        'hostnamelookups': 1,
        'identitycheck': 1,
        'identitychecktimeout': 1,
        'imapbase': 1,
        'imapdefault': 1,
        'imapmenu': 1,
        'include': 1,
        'indexheadinsert': 1,
        'indexignore': 1,
        'indexoptions': 1,
        'indexorderdefault': 1,
        'indexstylesheet': 1,
        'isapiappendlogtoerrors': 1,
        'isapiappendlogtoquery': 1,
        'isapicachefile': 1,
        'isapifakeasync': 1,
        'isapilognotsupported': 1,
        'isapireadaheadbuffer': 1,
        'keepalive': 1,
        'keepalivetimeout': 1,
        'languagepriority': 1,
        'ldapcacheentries': 1,
        'ldapcachettl': 1,
        'ldapconnectiontimeout': 1,
        'ldapopcacheentries': 1,
        'ldapopcachettl': 1,
        'ldapsharedcachefile': 1,
        'ldapsharedcachesize': 1,
        'ldaptrustedclientcert': 1,
        'ldaptrustedglobalcert': 1,
        'ldaptrustedmode': 1,
        'ldapverifyservercert': 1,
        'limitinternalrecursion': 1,
        'limitrequestbody': 1,
        'limitrequestfields': 1,
        'limitrequestfieldsize': 1,
        'limitrequestline': 1,
        'limitxmlrequestbody': 1,
        'listen': 1,
        'listenbacklog': 1,
        'loadfile': 1,
        'loadmodule': 1,
        'lockfile': 1,
        'logformat': 1,
        'loglevel': 1,
        'maxclients': 1,
        'maxkeepaliverequests': 1,
        'maxmemfree': 1,
        'maxrequestsperchild': 1,
        'maxrequestsperthread': 1,
        'maxspareservers': 1,
        'maxsparethreads': 1,
        'maxthreads': 1,
        'mcachemaxobjectcount': 1,
        'mcachemaxobjectsize': 1,
        'mcachemaxstreamingbuffer': 1,
        'mcacheminobjectsize': 1,
        'mcacheremovalalgorithm': 1,
        'mcachesize': 1,
        'metadir': 1,
        'metafiles': 1,
        'metasuffix': 1,
        'mimemagicfile': 1,
        'minspareservers': 1,
        'minsparethreads': 1,
        'mmapfile': 1,
        'mod_gzip_on': 1,
        'mod_gzip_add_header_count': 1,
        'mod_gzip_keep_workfiles': 1,
        'mod_gzip_dechunk': 1,
        'mod_gzip_min_http': 1,
        'mod_gzip_minimum_file_size': 1,
        'mod_gzip_maximum_file_size': 1,
        'mod_gzip_maximum_inmem_size': 1,
        'mod_gzip_temp_dir': 1,
        'mod_gzip_item_include': 1,
        'mod_gzip_item_exclude': 1,
        'mod_gzip_command_version': 1,
        'mod_gzip_can_negotiate': 1,
        'mod_gzip_handle_methods': 1,
        'mod_gzip_static_suffix': 1,
        'mod_gzip_send_vary': 1,
        'mod_gzip_update_static': 1,
        'modmimeusepathinfo': 1,
        'multiviewsmatch': 1,
        'namevirtualhost': 1,
        'noproxy': 1,
        'nwssltrustedcerts': 1,
        'nwsslupgradeable': 1,
        'options': 1,
        'order': 1,
        'passenv': 1,
        'pidfile': 1,
        'protocolecho': 1,
        'proxybadheader': 1,
        'proxyblock': 1,
        'proxydomain': 1,
        'proxyerroroverride': 1,
        'proxyftpdircharset': 1,
        'proxyiobuffersize': 1,
        'proxymaxforwards': 1,
        'proxypass': 1,
        'proxypassinterpolateenv': 1,
        'proxypassmatch': 1,
        'proxypassreverse': 1,
        'proxypassreversecookiedomain': 1,
        'proxypassreversecookiepath': 1,
        'proxypreservehost': 1,
        'proxyreceivebuffersize': 1,
        'proxyremote': 1,
        'proxyremotematch': 1,
        'proxyrequests': 1,
        'proxyset': 1,
        'proxystatus': 1,
        'proxytimeout': 1,
        'proxyvia': 1,
        'readmename': 1,
        'receivebuffersize': 1,
        'redirect': 1,
        'redirectmatch': 1,
        'redirectpermanent': 1,
        'redirecttemp': 1,
        'removecharset': 1,
        'removeencoding': 1,
        'removehandler': 1,
        'removeinputfilter': 1,
        'removelanguage': 1,
        'removeoutputfilter': 1,
        'removetype': 1,
        'requestheader': 1,
        'require': 2,
        'rewritebase': 1,
        'rewritecond': 10,
        'rewriteengine': 1,
        'rewritelock': 1,
        'rewritelog': 1,
        'rewriteloglevel': 1,
        'rewritemap': 1,
        'rewriteoptions': 1,
        'rewriterule': 10,
        'rlimitcpu': 1,
        'rlimitmem': 1,
        'rlimitnproc': 1,
        'satisfy': 1,
        'scoreboardfile': 1,
        'script': 1,
        'scriptalias': 1,
        'scriptaliasmatch': 1,
        'scriptinterpretersource': 1,
        'scriptlog': 1,
        'scriptlogbuffer': 1,
        'scriptloglength': 1,
        'scriptsock': 1,
        'securelisten': 1,
        'seerequesttail': 1,
        'sendbuffersize': 1,
        'serveradmin': 1,
        'serveralias': 1,
        'serverlimit': 1,
        'servername': 1,
        'serverpath': 1,
        'serverroot': 1,
        'serversignature': 1,
        'servertokens': 1,
        'setenv': 1,
        'setenvif': 1,
        'setenvifnocase': 1,
        'sethandler': 1,
        'setinputfilter': 1,
        'setoutputfilter': 1,
        'ssienableaccess': 1,
        'ssiendtag': 1,
        'ssierrormsg': 1,
        'ssistarttag': 1,
        'ssitimeformat': 1,
        'ssiundefinedecho': 1,
        'sslcacertificatefile': 1,
        'sslcacertificatepath': 1,
        'sslcadnrequestfile': 1,
        'sslcadnrequestpath': 1,
        'sslcarevocationfile': 1,
        'sslcarevocationpath': 1,
        'sslcertificatechainfile': 1,
        'sslcertificatefile': 1,
        'sslcertificatekeyfile': 1,
        'sslciphersuite': 1,
        'sslcryptodevice': 1,
        'sslengine': 1,
        'sslhonorciperorder': 1,
        'sslmutex': 1,
        'ssloptions': 1,
        'sslpassphrasedialog': 1,
        'sslprotocol': 1,
        'sslproxycacertificatefile': 1,
        'sslproxycacertificatepath': 1,
        'sslproxycarevocationfile': 1,
        'sslproxycarevocationpath': 1,
        'sslproxyciphersuite': 1,
        'sslproxyengine': 1,
        'sslproxymachinecertificatefile': 1,
        'sslproxymachinecertificatepath': 1,
        'sslproxyprotocol': 1,
        'sslproxyverify': 1,
        'sslproxyverifydepth': 1,
        'sslrandomseed': 1,
        'sslrequire': 1,
        'sslrequiressl': 1,
        'sslsessioncache': 1,
        'sslsessioncachetimeout': 1,
        'sslusername': 1,
        'sslverifyclient': 1,
        'sslverifydepth': 1,
        'startservers': 1,
        'startthreads': 1,
        'substitute': 1,
        'suexecusergroup': 1,
        'threadlimit': 1,
        'threadsperchild': 1,
        'threadstacksize': 1,
        'timeout': 1,
        'traceenable': 1,
        'transferlog': 1,
        'typesconfig': 1,
        'unsetenv': 1,
        'usecanonicalname': 1,
        'usecanonicalphysicalport': 1,
        'user': 1,
        'userdir': 1,
        'virtualdocumentroot': 1,
        'virtualdocumentrootip': 1,
        'virtualscriptalias': 1,
        'virtualscriptaliasip': 1,
        'win32disableacceptex': 1,
        'xbithack': 1
      },
      'literal': {'on': 1, 'off': 1}
    }
  },
  modes: [
    hljs.HASH_COMMENT_MODE,
    {
      /* TODO: check tag content: Location, Files, VirtualHost, ... */
      className: 'tag',
      begin: '</?', end: '>'
    },
    {
      className: 'sqbracket',
      begin: '\\s\\[', end: '\\]$'
    },
    {
      className: 'cbracket',
      begin: '[\\$%]\\{', end: '\\}',
      contains: ['cbracket', 'number']
    },
    {
      className: 'number',
      begin: '[\\$%]\\d+', end: '^'
    },
    hljs.QUOTE_STRING_MODE,
    hljs.BACKSLASH_ESCAPE
  ]
};
<|endoftext|>


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

  var Video =  (function() {
    var Video = function() {

    };

    Video.prototype.loadFromFile = function() {

    };

    Video.prototype.play = function() {

    };

    Video.prototype.pause = function() {

    };

    Video.prototype.stop = function() {

    };

    return Video;
  })();

  return Video;

});
<commit_msg>Updated documentation for lyria/video<commit_after>define(function() {
  'use strict';

  /**
   * @module lyria/video
   */

  var Video =  (function() {
    /**
     * @class
     * @alias module:lyria/video
     */
    var Video = function() {

    };

    Video.prototype.loadFromFile = function() {

    };

    Video.prototype.play = function() {

    };

    Video.prototype.pause = function() {

    };

    Video.prototype.stop = function() {

    };

    return Video;
  })();

  return Video;

});
<|endoftext|>


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

    angular.module('app').controller('GeneratorController', ['$http', '$scope', function ($http, $scope) {
        var c = this;

        c.configData = null;
        $http.get('resources/blockValues.json').then(function (data) {
            c.configData = data.data;
            c.config = [];
            for (var key in c.configData) {
                c.config.push({ block: key, quantity: 0 });
            }
        });

        c.calcMod = function (fn, qty) {
            return qty == 0 ? 0 : Math.max(fn.floor, Math.min(fn.ceiling, ((fn.scaleFactorNumerator / fn.scaleFactorDenominator) * (Math.pow((qty + fn.xOffset), fn.power))) + fn.yOffset));
        };
        c.calc = function () {
            var sum = function (arr) { return _.reduce(arr, function (a, i) { return a + i; }, 0); }
            var calcFunc = function (funcName) { return sum(_.map(c.config, function (i) { return c.calcMod(c.configData[i.block][funcName], i.quantity); })); }

            var blocksUsed = sum(_.map(c.config, function (i) { return i.quantity; }));
            var speed = calcFunc('speedFunction');
            var eff = calcFunc('efficiencyFunction');
            var mult = calcFunc('multiplicityFunction') + 1;
            var rfTick = (8 * mult * -1 * speed);
            var tickMod = (1600 + eff) / 1600;
            var rfPerCoal = rfTick * (1600 * tickMod) / 3;
            return {
                speed: speed,
                eff: eff,
                mult: mult,
                rfTick: rfTick,
                tickMod: tickMod,
                rfPerCoal: rfPerCoal,
                blocksUsed: blocksUsed
            };
        };

        var allCubes = [];
        var maxSize = 20;
        for (var i = 1; i < maxSize; i++) {
            for (var j = 1; j <= i; j++) {
                for (var k = 1; k <= j; k++) {
                    allCubes.push({ size: (i + 2) + 'x' + (j + 2) + 'x' + (i + 2), blocks: (i + 2) * (j + 2) * (k + 2) - i * j * k });
                }
            }
        }
        allCubes.sort(function (a, b) { return a.blocks - b.blocks; });

        $scope.$watch('c.config', function () {
            c.calcResult = c.calc();

            var targetIx = _.sortedIndex(allCubes, { blocks: c.calcResult.blocksUsed }, 'blocks');
            c.cubes = allCubes.slice(Math.max(0, targetIx - 3), targetIx + 5);
        }, true);

    }]);
})();<commit_msg>multiplier now affects how long the piece of coal lasts<commit_after>(function() {
    'use strict;'

    angular.module('app').controller('GeneratorController', ['$http', '$scope', function ($http, $scope) {
        var c = this;

        c.configData = null;
        $http.get('resources/blockValues.json').then(function (data) {
            c.configData = data.data;
            c.config = [];
            for (var key in c.configData) {
                c.config.push({ block: key, quantity: 0 });
            }
        });

        c.calcMod = function (fn, qty) {
            return qty == 0 ? 0 : Math.max(fn.floor, Math.min(fn.ceiling, ((fn.scaleFactorNumerator / fn.scaleFactorDenominator) * (Math.pow((qty + fn.xOffset), fn.power))) + fn.yOffset));
        };
        c.calc = function () {
            var sum = function (arr) { return _.reduce(arr, function (a, i) { return a + i; }, 0); }
            var calcFunc = function (funcName) { return sum(_.map(c.config, function (i) { return c.calcMod(c.configData[i.block][funcName], i.quantity); })); }

            var blocksUsed = sum(_.map(c.config, function (i) { return i.quantity; }));
            var speed = calcFunc('speedFunction');
            var eff = calcFunc('efficiencyFunction');
            var mult = calcFunc('multiplicityFunction') + 1;
            var rfTick = (8 * mult * -1 * speed);
            var tickMod = (1600 + eff) / 1600 / mult;
            var rfPerCoal = Math.max(0, rfTick) * (1600 * tickMod) / 3;
            return {
                speed: speed,
                eff: eff,
                mult: mult,
                rfTick: rfTick,
                tickMod: tickMod,
                rfPerCoal: rfPerCoal,
                blocksUsed: blocksUsed
            };
        };

        var allCubes = [];
        var maxSize = 20;
        for (var i = 1; i < maxSize; i++) {
            for (var j = 1; j <= i; j++) {
                for (var k = 1; k <= j; k++) {
                    allCubes.push({ size: (i + 2) + 'x' + (j + 2) + 'x' + (i + 2), blocks: (i + 2) * (j + 2) * (k + 2) - i * j * k });
                }
            }
        }
        allCubes.sort(function (a, b) { return a.blocks - b.blocks; });

        $scope.$watch('c.config', function () {
            c.calcResult = c.calc();

            var targetIx = _.sortedIndex(allCubes, { blocks: c.calcResult.blocksUsed }, 'blocks');
            c.cubes = allCubes.slice(Math.max(0, targetIx - 3), targetIx + 5);
        }, true);

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


<commit_before>var BaseContainer = require("./base.js");
var Point         = require("../geometry/point.js");

/**
 * Rows Elements one after the other
 *
 * @implements BaseContainer
 * @implements BaseShape
 */
class RowContainer extends BaseContainer {
    static get ALIGNMENT_LEFT() { return -1; }
    static get ALIGNMENT_RIGHT() { return 1; }

    constructor(key, alignment) {
        super(key);
        this._shapeList = [];
        this._alignment = alignment;
    };

    _updateDimensions(newShapeDimensions) {
        this.dimensions.length = Math.max(newShapeDimensions.length, this.dimensions.length);
        this.dimensions.width += newShapeDimensions.width;
    }

    add(shape) {
        // this._shapeList.unshift(shape);
        this._shapeList.push(shape);
        this._updateDimensions(shape.displayDimensions)

    };

    get alignment() {
        return this._alignment;
    }

    get countElements() {
        return this._shapeList.length;
    }

    finalize() {
        if (!this._shapeList.length) {
            return;
        }

        var barrierXAxis = (this.dimensions.length / 2) * this._alignment;
        var firstFreePosition = this.dimensions.width / 2;

        this._shapeList.forEach(function(shape) {
            shape.relativePosition.x = barrierXAxis - (shape.centroid.x * this._alignment);
            shape.relativePosition.y = firstFreePosition - shape.centroid.y;
            firstFreePosition -= shape.displayDimensions.width;
        }.bind(this));
    };

    draw(parentPosition, parentRotation) {
        // TODO
        super.draw(parentPosition, parentRotation);

        var s = [];
        for (var shape of this._shapeList) {

            var res = shape.draw(this._absolutePosition, this._absoluteRotation);
            if (Object.prototype.toString.call( res ) !== '[object Array]') {
                s.push(res);
            } else {
                for(var o of res) {
                    s.push(o);
                }
            }
        }
        return s;
    };
}

module.exports = RowContainer;
<commit_msg>CodeQuality<commit_after>var BaseContainer = require("./base.js");
var Point         = require("../geometry/point.js");

/**
 * Rows Elements one after the other
 *
 * @implements BaseContainer
 * @implements BaseShape
 */
class RowContainer extends BaseContainer {
    static get ALIGNMENT_LEFT() { return -1; }
    static get ALIGNMENT_RIGHT() { return 1; }

    constructor(key, alignment) {
        super(key);
        this._shapeList = [];
        this._alignment = alignment;
    };

    _updateDimensions(newShapeDimensions) {
        this.dimensions.length = Math.max(newShapeDimensions.length, this.dimensions.length);
        this.dimensions.width += newShapeDimensions.width;
    }

    add(shape) {
        this._shapeList.push(shape);
        this._updateDimensions(shape.displayDimensions)

    };

    get alignment() {
        return this._alignment;
    }

    get countElements() {
        return this._shapeList.length;
    }

    finalize() {
        if (!this._shapeList.length) {
            return;
        }

        var barrierXAxis = (this.dimensions.length / 2) * this._alignment;
        var firstFreePosition = this.dimensions.width / 2;

        this._shapeList.forEach(function(shape) {
            shape.relativePosition.x = barrierXAxis - (shape.centroid.x * this._alignment);
            shape.relativePosition.y = firstFreePosition - shape.centroid.y;
            firstFreePosition -= shape.displayDimensions.width;
        }.bind(this));
    };

    draw(parentPosition, parentRotation) {
        // TODO
        super.draw(parentPosition, parentRotation);

        var s = [];
        for (var shape of this._shapeList) {

            var res = shape.draw(this._absolutePosition, this._absoluteRotation);
            if (Object.prototype.toString.call( res ) !== '[object Array]') {
                s.push(res);
            } else {
                for(var o of res) {
                    s.push(o);
                }
            }
        }
        return s;
    };
}

module.exports = RowContainer;
<|endoftext|>


<commit_before>// product-test.js
//
// Test the product module
//
// Copyright 2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require('assert'),
    vows = require('vows');

vows.describe('product module interface').addBatch({
    'When we check for a test suite': {
        topic: function() {
            return false;
        },
        'there is one': function(tsExists) {
            assert.isTrue(tsExists);
        }
    }
}).export(module);

<commit_msg>Product unit test<commit_after>// product-test.js
//
// Test the product module
//
// Copyright 2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require('assert'),
    vows = require('vows'),
    databank = require('databank'),
    URLMaker = require('../lib/urlmaker').URLMaker,
    modelBatch = require('./lib/model').modelBatch,
    Databank = databank.Databank,
    DatabankObject = databank.DatabankObject;

// Need this to make IDs

URLMaker.hostname = "example.net";

// Dummy databank

DatabankObject.bank = Databank.get('memory', {});

var suite = vows.describe('product module interface');

var testSchema = {
    pkey: "id",
    fields: ['author',
             'displayName',
             'fullImage',
             'image',
             'published',
             'summary',
             'updated',
             'url']
};

var testData = {
    'create': {
        displayName: "ActivityPump",
        summary: "DUH what it sounds like LOL",
        url: "http://activitypump.org/"
    },
    'update': {
        summary: "Network infrastructure for social tools."
    }
};

suite.addBatch(modelBatch('product', 'Product', testSchema, testData));

suite.export(module);
<|endoftext|>


<commit_before>// @flow
/* eslint-disable no-console */
import sane from 'sane';
import chalk from 'chalk';
import ora from 'ora';
import { queue } from 'async';
import execCommand from './utils/exec';

const check = (bool?: boolean) => (bool ? chalk.green('✓') : chalk.red('✗'));

const printDefinition = (wd, {
  change,
  add,
  delete: del,
  command,
  patterns,
}: WatchDefinition) => {
  let warning = '';
  if (change === false && del === false && add === false) {
    warning = `\n${chalk.yellow('WARNING')}: not listening to any triggers`;
    return;
  }

  console.log(`
> Watching ${wd}
> Patterns: ${patterns.join(', ')}
> Command: '${command}'
> Triggers: add ${check(add)} change ${check(change)} delete ${check(del)} ${warning}`);
};

async function exec(wd, command, files, appendFiles, config) {
  if (files.length === 0) {
    return;
  }

  let commandToRun;
  if (appendFiles) {
    commandToRun = `${command} ${files.join(' ')}`;
  } else {
    commandToRun = command;
  }

  console.log(`\n> Watch triggered at: ${wd}\n> ${commandToRun}`);
  const options = { shell: true, cwd: wd, env: process.env };
  await execCommand(commandToRun, options, config);
}

export default (watchman: boolean) => {
  const spinner = ora('Watching for changes');
  const startSpinner = () => {
    spinner.start();
  };

  const taskQueue = queue((fn, cb) => {
    fn().then(cb).catch((err) => {
      console.error('Task failed', err);
      cb();
    });
  }, 1);
  taskQueue.drain = startSpinner;

  const addDefinition = (wd: string, config: PhaseConfig = {}) => ({
    patterns,
    command,
    appendFiles = false,
    add = true,
    delete: del = false,
    change = true,
  }: WatchDefinition) => {
    const watchDefinition = {
      patterns,
      command,
      appendFiles,
      add,
      delete: del,
      change,
    };

    printDefinition(wd, watchDefinition);

    const watcher = sane(wd, { glob: patterns, watchman });
    const newChanges = new Set();

    const newChange = file => {
      newChanges.add(file);
      taskQueue.push(async () => {
        spinner.stop();
        const files = Array.from(newChanges);
        newChanges.clear();

        await exec(wd, command, files, appendFiles, config);
      });
    };

    if (change) {
      watcher.on('change', newChange);
    }
    if (add) {
      watcher.on('add', newChange);
    }
    if (del) {
      watcher.on('delete', newChange);
    }
  };

  return {
    add: addDefinition,
    start: startSpinner,
  };
};
<commit_msg>easier to identify where a trigger starts<commit_after>// @flow
/* eslint-disable no-console */
import sane from 'sane';
import chalk from 'chalk';
import ora from 'ora';
import { queue } from 'async';
import execCommand from './utils/exec';

const check = (bool?: boolean) => (bool ? chalk.green('✓') : chalk.red('✗'));

const printDefinition = (wd, {
  change,
  add,
  delete: del,
  command,
  patterns,
}: WatchDefinition) => {
  let warning = '';
  if (change === false && del === false && add === false) {
    warning = `\n${chalk.yellow('WARNING')}: not listening to any triggers`;
    return;
  }

  console.log(`
> Watching ${wd}
> Patterns: ${patterns.join(', ')}
> Command: '${command}'
> Triggers: add ${check(add)} change ${check(change)} delete ${check(del)} ${warning}`);
};

async function exec(wd, command, files, appendFiles, config) {
  if (files.length === 0) {
    return;
  }

  let commandToRun;
  if (appendFiles) {
    commandToRun = `${command} ${files.join(' ')}`;
  } else {
    commandToRun = command;
  }

  console.log(`\n> ${chalk.green('Watch triggered at')}: ${wd}\n> ${commandToRun}`);
  const options = { shell: true, cwd: wd, env: process.env };
  await execCommand(commandToRun, options, config);
}

export default (watchman: boolean) => {
  const spinner = ora('Watching for changes');
  const startSpinner = () => {
    spinner.start();
  };

  const taskQueue = queue((fn, cb) => {
    fn().then(cb).catch((err) => {
      console.error('Task failed', err);
      cb();
    });
  }, 1);
  taskQueue.drain = startSpinner;

  const addDefinition = (wd: string, config: PhaseConfig = {}) => ({
    patterns,
    command,
    appendFiles = false,
    add = true,
    delete: del = false,
    change = true,
  }: WatchDefinition) => {
    const watchDefinition = {
      patterns,
      command,
      appendFiles,
      add,
      delete: del,
      change,
    };

    printDefinition(wd, watchDefinition);

    const watcher = sane(wd, { glob: patterns, watchman });
    const newChanges = new Set();

    const newChange = file => {
      newChanges.add(file);
      taskQueue.push(async () => {
        spinner.stop();
        const files = Array.from(newChanges);
        newChanges.clear();

        await exec(wd, command, files, appendFiles, config);
      });
    };

    if (change) {
      watcher.on('change', newChange);
    }
    if (add) {
      watcher.on('add', newChange);
    }
    if (del) {
      watcher.on('delete', newChange);
    }
  };

  return {
    add: addDefinition,
    start: startSpinner,
  };
};
<|endoftext|>


<commit_before>var tld = require('../index.js');
var expect = require('expect.js');

suite('http://publicsuffix.org/list/test.txt', function(){
  test('NULL input', function(){
    expect(tld.getDomain(null)).to.be(null);
  });

  test('Mixed case', function(){
    expect(tld.getDomain('COM')).to.be(null);
    expect(tld.getDomain('example.COM')).to.be('example.com');
    expect(tld.getDomain('WwW.example.COM')).to.be('example.com');
  });

  test('Leading dot', function(){
    expect(tld.getDomain('.com')).to.be(null);
    expect(tld.getDomain('.example')).to.be(null);
    expect(tld.getDomain('.example.com')).to.be(null);
    expect(tld.getDomain('example.example')).to.be(null);
  });

  test('Unlisted TLD', function(){
    expect(tld.getDomain('example')).to.be(null);
    expect(tld.getDomain('example.example')).to.be(null);
    expect(tld.getDomain('b.example.example')).to.be(null);
    expect(tld.getDomain('a.b.example.example')).to.be(null);
  });

  /*test('Listed, but non-Internet, TLD', function(){
    expect(tld.getDomain('local')).to.be(null);
    expect(tld.getDomain('example.local')).to.be(null);
    expect(tld.getDomain('b.example.local')).to.be(null);
    expect(tld.getDomain('a.b.example.local')).to.be(null);
  });*/

  test('TLD with only 1 rule', function(){
    expect(tld.getDomain('biz')).to.be(null);
    expect(tld.getDomain('domain.biz')).to.be('domain.biz');
    expect(tld.getDomain('b.domain.biz')).to.be('domain.biz');
    expect(tld.getDomain('a.b.domain.biz')).to.be('domain.biz');
  });

  test('TLD with some 2-level rules', function(){
    expect(tld.getDomain('com')).to.be(null);
    expect(tld.getDomain('example.com')).to.be('example.com');
    expect(tld.getDomain('b.example.com')).to.be('example.com');
    expect(tld.getDomain('a.b.example.com')).to.be('example.com');
    expect(tld.getDomain('uk.com')).to.be(null);
    expect(tld.getDomain('example.uk.com')).to.be('example.uk.com');
    expect(tld.getDomain('b.example.uk.com')).to.be('example.uk.com');
    expect(tld.getDomain('a.b.example.uk.com')).to.be('example.uk.com');
    expect(tld.getDomain('test.ac')).to.be('test.ac');
  });

  test('TLD with only 1 (wildcard) rule', function(){
    expect(tld.getDomain('cy')).to.be(null);
    expect(tld.getDomain('c.cy')).to.be(null);
    expect(tld.getDomain('b.c.cy')).to.be('b.c.cy');
    expect(tld.getDomain('a.b.c.cy')).to.be('b.c.cy');
  });

  test('More complex TLD', function(){
    expect(tld.getDomain('jp')).to.be(null);
    expect(tld.getDomain('test.jp')).to.be('test.jp');
    expect(tld.getDomain('www.test.jp')).to.be('test.jp');
    expect(tld.getDomain('ac.jp')).to.be(null);
    expect(tld.getDomain('test.ac.jp')).to.be('test.ac.jp');
    expect(tld.getDomain('www.test.ac.jp')).to.be('test.ac.jp');
    expect(tld.getDomain('kyoto.jp')).to.be(null);
    expect(tld.getDomain('c.kyoto.jp')).to.be(null);   //@see https://gist.github.com/2727303
    expect(tld.getDomain('b.c.kyoto.jp')).to.be('b.c.kyoto.jp');
    expect(tld.getDomain('a.b.c.kyoto.jp')).to.be('b.c.kyoto.jp');
    expect(tld.getDomain('pref.kyoto.jp')).to.be('pref.kyoto.jp');      //exception
    expect(tld.getDomain('www.pref.kyoto.jp')).to.be('pref.kyoto.jp');  //exception
    expect(tld.getDomain('city.kyoto.jp')).to.be('city.kyoto.jp');      //exception
    expect(tld.getDomain('www.city.kyoto.jp')).to.be('city.kyoto.jp');  //exception
  });

  test('TLD with a wildcard rule and exceptions', function(){
    expect(tld.getDomain('om')).to.be(null);
    expect(tld.getDomain('test.om')).to.be(null);     //@see https://gist.github.com/2727303
    expect(tld.getDomain('b.test.om')).to.be('b.test.om');
    expect(tld.getDomain('a.b.test.om')).to.be('b.test.om');
    expect(tld.getDomain('songfest.om')).to.be('songfest.om');
    expect(tld.getDomain('www.songfest.om')).to.be('songfest.om');
  });

  test('US K12', function(){
    expect(tld.getDomain('us')).to.be(null);
    expect(tld.getDomain('test.us')).to.be('test.us');
    expect(tld.getDomain('www.test.us')).to.be('test.us');
    expect(tld.getDomain('ak.us')).to.be(null);
    expect(tld.getDomain('test.ak.us')).to.be('test.ak.us');
    expect(tld.getDomain('www.test.ak.us')).to.be('test.ak.us');
    expect(tld.getDomain('k12.ak.us')).to.be(null);
    expect(tld.getDomain('test.k12.ak.us')).to.be('test.k12.ak.us');
    expect(tld.getDomain('www.test.k12.ak.us')).to.be('test.k12.ak.us');
  });
});<commit_msg>Removing gist hint<commit_after>var tld = require('../index.js');
var expect = require('expect.js');

suite('http://publicsuffix.org/list/test.txt', function(){
  test('NULL input', function(){
    expect(tld.getDomain(null)).to.be(null);
  });

  test('Mixed case', function(){
    expect(tld.getDomain('COM')).to.be(null);
    expect(tld.getDomain('example.COM')).to.be('example.com');
    expect(tld.getDomain('WwW.example.COM')).to.be('example.com');
  });

  test('Leading dot', function(){
    expect(tld.getDomain('.com')).to.be(null);
    expect(tld.getDomain('.example')).to.be(null);
    expect(tld.getDomain('.example.com')).to.be(null);
    expect(tld.getDomain('example.example')).to.be(null);
  });

  test('Unlisted TLD', function(){
    expect(tld.getDomain('example')).to.be(null);
    expect(tld.getDomain('example.example')).to.be(null);
    expect(tld.getDomain('b.example.example')).to.be(null);
    expect(tld.getDomain('a.b.example.example')).to.be(null);
  });

  /*test('Listed, but non-Internet, TLD', function(){
    expect(tld.getDomain('local')).to.be(null);
    expect(tld.getDomain('example.local')).to.be(null);
    expect(tld.getDomain('b.example.local')).to.be(null);
    expect(tld.getDomain('a.b.example.local')).to.be(null);
  });*/

  test('TLD with only 1 rule', function(){
    expect(tld.getDomain('biz')).to.be(null);
    expect(tld.getDomain('domain.biz')).to.be('domain.biz');
    expect(tld.getDomain('b.domain.biz')).to.be('domain.biz');
    expect(tld.getDomain('a.b.domain.biz')).to.be('domain.biz');
  });

  test('TLD with some 2-level rules', function(){
    expect(tld.getDomain('com')).to.be(null);
    expect(tld.getDomain('example.com')).to.be('example.com');
    expect(tld.getDomain('b.example.com')).to.be('example.com');
    expect(tld.getDomain('a.b.example.com')).to.be('example.com');
    expect(tld.getDomain('uk.com')).to.be(null);
    expect(tld.getDomain('example.uk.com')).to.be('example.uk.com');
    expect(tld.getDomain('b.example.uk.com')).to.be('example.uk.com');
    expect(tld.getDomain('a.b.example.uk.com')).to.be('example.uk.com');
    expect(tld.getDomain('test.ac')).to.be('test.ac');
  });

  test('TLD with only 1 (wildcard) rule', function(){
    expect(tld.getDomain('cy')).to.be(null);
    expect(tld.getDomain('c.cy')).to.be(null);
    expect(tld.getDomain('b.c.cy')).to.be('b.c.cy');
    expect(tld.getDomain('a.b.c.cy')).to.be('b.c.cy');
  });

  test('More complex TLD', function(){
    expect(tld.getDomain('jp')).to.be(null);
    expect(tld.getDomain('test.jp')).to.be('test.jp');
    expect(tld.getDomain('www.test.jp')).to.be('test.jp');
    expect(tld.getDomain('ac.jp')).to.be(null);
    expect(tld.getDomain('test.ac.jp')).to.be('test.ac.jp');
    expect(tld.getDomain('www.test.ac.jp')).to.be('test.ac.jp');
    expect(tld.getDomain('kyoto.jp')).to.be(null);
    expect(tld.getDomain('c.kyoto.jp')).to.be(null);
    expect(tld.getDomain('b.c.kyoto.jp')).to.be('b.c.kyoto.jp');
    expect(tld.getDomain('a.b.c.kyoto.jp')).to.be('b.c.kyoto.jp');
    expect(tld.getDomain('pref.kyoto.jp')).to.be('pref.kyoto.jp');      //exception
    expect(tld.getDomain('www.pref.kyoto.jp')).to.be('pref.kyoto.jp');  //exception
    expect(tld.getDomain('city.kyoto.jp')).to.be('city.kyoto.jp');      //exception
    expect(tld.getDomain('www.city.kyoto.jp')).to.be('city.kyoto.jp');  //exception
  });

  test('TLD with a wildcard rule and exceptions', function(){
    expect(tld.getDomain('om')).to.be(null);
    expect(tld.getDomain('test.om')).to.be(null);
    expect(tld.getDomain('b.test.om')).to.be('b.test.om');
    expect(tld.getDomain('a.b.test.om')).to.be('b.test.om');
    expect(tld.getDomain('songfest.om')).to.be('songfest.om');
    expect(tld.getDomain('www.songfest.om')).to.be('songfest.om');
  });

  test('US K12', function(){
    expect(tld.getDomain('us')).to.be(null);
    expect(tld.getDomain('test.us')).to.be('test.us');
    expect(tld.getDomain('www.test.us')).to.be('test.us');
    expect(tld.getDomain('ak.us')).to.be(null);
    expect(tld.getDomain('test.ak.us')).to.be('test.ak.us');
    expect(tld.getDomain('www.test.ak.us')).to.be('test.ak.us');
    expect(tld.getDomain('k12.ak.us')).to.be(null);
    expect(tld.getDomain('test.k12.ak.us')).to.be('test.k12.ak.us');
    expect(tld.getDomain('www.test.k12.ak.us')).to.be('test.k12.ak.us');
  });
});<|endoftext|>


<commit_before><commit_msg>修改zhichi<commit_after>/**
 * Created by liuyubobobo on 14-4-11.
 * my site: http://www.liuyubobobo.com
 */

documentWidth = window.screen.availWidth;
gridContainerWidth = 0.92 * documentWidth;
cellSideLength = 0.18 * documentWidth;
cellSpace = 0.04*documentWidth;

function getPosTop( i , j ){
    return cellSpace + i*( cellSpace + cellSideLength );
}

function getPosLeft( i , j ){
    return cellSpace + j*( cellSpace + cellSideLength );
}

function getNumberBackgroundColor( number ){
    switch( number ){
        case 2:return "#eee4da";break;
        case 4:return "#ede0c8";break;
        case 8:return "#f2b179";break;
        case 16:return "#f59563";break;
        case 32:return "#f67c5f";break;
        case 64:return "#f65e3b";break;
        case 128:return "#edcf72";break;
        case 256:return "#edcc61";break;
        case 512:return "#9c0";break;
        case 1024:return "#33b5e5";break;
        case 2048:return "#09c";break;
        case 4096:return "#a6c";break;
        case 8192:return "#93c";break;
    }

    return "black";
}

function getNumberColor( number ){
    if( number <= 4 )
        return "#776e65";

    return "white";
}

function nospace( board ){

    for( var i = 0 ; i < 4 ; i ++ )
        for( var j = 0 ; j < 4 ; j ++ )
            if( board[i][j] == 0 )
                return false;

    return true;
}

function canMoveLeft( board ){

    for( var i = 0 ; i < 4 ; i ++ )
        for( var j = 1; j < 4 ; j ++ )
            if( board[i][j] != 0 )
                if( board[i][j-1] == 0 || board[i][j-1] == board[i][j] )
                    return true;

    return false;
}

function canMoveRight( board ){

    for( var i = 0 ; i < 4 ; i ++ )
        for( var j = 2; j >= 0 ; j -- )
            if( board[i][j] != 0 )
                if( board[i][j+1] == 0 || board[i][j+1] == board[i][j] )
                    return true;

    return false;
}

function canMoveUp( board ){

    for( var j = 0 ; j < 4 ; j ++ )
        for( var i = 1 ; i < 4 ; i ++ )
            if( board[i][j] != 0 )
                if( board[i-1][j] == 0 || board[i-1][j] == board[i][j] )
                    return true;

    return false;
}

function canMoveDown( board ){

    for( var j = 0 ; j < 4 ; j ++ )
        for( var i = 2 ; i >= 0 ; i -- )
            if( board[i][j] != 0 )
                if( board[i+1][j] == 0 || board[i+1][j] == board[i][j] )
                    return true;

    return false;
}

function noBlockHorizontal( row , col1 , col2 , board ){
    for( var i = col1 + 1 ; i < col2 ; i ++ )
        if( board[row][i] != 0 )
            return false;
    return true;
}

function noBlockVertical( col , row1 , row2 , board ){
    for( var i = row1 + 1 ; i < row2 ; i ++ )
        if( board[i][col] != 0 )
            return false;
    return true;
}

function nomove( board ){
    if( canMoveLeft( board ) ||
        canMoveRight( board ) ||
        canMoveUp( board ) ||
        canMoveDown( board ) )
        return false;

    return true;
}

<|endoftext|>


<commit_before>import React, {Component} from "react"
import Popup from './components/Popup'
import Gallery from './components/Gallery'
import vanillaColorPicker from '../helpers/VanillaColorPicker';

export default class ImageManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isVisible: false,
            settings: {}
        };

        this.updateImageList();

    }

    updateImageList(){
        this.props.api && this.props.api.getImageList && this.props.api.getImageList(this.state.pieceData).then((list) => {
            // add index to item if not set by the server
            list.forEach((item, index) => {
                if(!item.Id){
                    item.id = index;
                }
            });
            this.setState({gallery: list})
        });
    }

    toggleImagePopup() {
        this.setState({isVisible: !this.state.isVisible})
    }

    onClose() {
        this.toggleImagePopup();
        this.state.onClose && this.state.onClose();
        this.resetData();
    }

    onSave() {
        this.toggleImagePopup();
        this.state.onSave && this.state.onSave(this.getImageData());
        this.resetData();
    }

    onUrlChange(imageData) {
        this.setState({url: imageData.url, alt: ""});
        this.getImageSize(imageData);
    }

    getImageSize(imageData, getOriginalSizeOnly) {

        //if is image from gallery
        if(imageData.width &&  imageData.height) {
            !getOriginalSizeOnly && this.setState({width: imageData.width, height: imageData.height});
            this.setState({originalWidth: imageData.width, originalHeight: imageData.height});
        } else {
            //if set by hands
            var that = this;
            var img = new Image();
            img.onload = function () {
                !getOriginalSizeOnly && that.setState({width: this.width, height: this.height});
                that.setState({originalWidth: this.width, originalHeight: this.height});
            }
            img.src = imageData.url;
        }

    }

    setBgSize(e) {
        let bgSize = e.target.value;
        this.setState({bgSize});
    }

    setBgPosition(e) {
        let bgPosition = e.target.value;
        this.setState({bgPosition});
    }

    setBgColor(e) {
        let bgColor = e.target.value;
        this.setState({bgColor});
    }

    pickBgColor(e) {
        this.attachPickerAndInvoke();
    }

    setBgRepeat(e) {
        let bgRepeat = e.target.value;
        this.setState({bgRepeat});
    }

    attachPickerAndInvoke() {
        // colors for picker
        let pickerColors = [
            "inherit",
            "#9b59b6",
            "#34495e",
            "#16a085",
            "#27ae60",
            "#2980b9",
            "#8e44ad",
            "#2c3e50",
            "#f1c40f",
            "#e67e22",
            "#e74c3c",
            "#bdc3c7",
            "#95a5a6",
            "#666",
            "#212121",
            "#f39c12",
            "#d2d064",
            "#4fbbf7",
            "#ffffff"
        ];

        /**
         * If we have previously created color picker that is not bound to correct element, kill it
         */
        if (this.picker) {
            if (this.picker.__boundElement != this.colorDiv) {
                this.picker.destroyPicker();
                this.picker = null;
            }
        }

        /**
         * If we still have a picker, open it
         */
        if (this.picker) {
            this.picker.openPicker();
        } else {
            //Create new picker
            this.picker = vanillaColorPicker(this.colorDiv);
            this.picker.set("customColors", pickerColors);
            this.picker.set("positionOnTop");
            this.picker.openPicker();
            this.picker.on("colorChosen", (color) => {
                if (color == "inherit") {
                    this.setState({
                        bgColor: ""
                    })
                } else {
                    this.setState({
                        bgColor: color
                    })
                }
            });
            this.picker.__boundElement = this.colorDiv;
        }
    }

    onWidthChange(e) {
        let newWidth = e.target.value;
        this.setState({width: newWidth});
        if (this.state.proportions) {
            this.setState({height: parseInt(newWidth * this.state.originalHeight / this.state.originalWidth)});
        }
    }

    onHeightChange(e) {
        let newHeight = e.target.value;
        this.setState({height: newHeight});
        if (this.state.proportions) {
            this.setState({width: parseInt(newHeight * this.state.originalWidth / this.state.originalHeight)});
        }
    }

    closePopup() {
        this.setState({isVisible: false})
    }

    showPopup() {
        this.setState({isVisible: true})
    }

    getImageData() {
        let data = {
            url: this.state.url,
            alt: this.state.alt || "",
        };

        /**
         * If image was resized, export new sizes
         */
        if (this.state.originalHeight != this.state.height || this.state.originalWidth != this.state.width) {
            data = {
                width: this.state.width,
                height: this.state.height,
                ...data
            }
        }

        /**
         * If editing background, pass backgrounds too
         */
        if (this.state.settings.editBackground) {
            data = {
                bgColor: this.state.bgColor,
                bgPosition: this.state.bgPosition,
                bgRepeat: this.state.bgRepeat,
                bgSize: this.state.bgSize,
                ...data
            }
        }

        return data;
    }

    setImageData(data) {
        (!data.alt && data.url) && (data.alt = "");
        this.setState(data);
        data.url && this.getImageSize(data, !!data.width);
        if(data.pieceData){
            this.updateImageList();
        }
    }

    sendFile() {
        if (this.props.api.uploadImage) {
            if (!this.state.file || !this.state.file[0]) return;
            var file = this.state.file[0],
                formdata = new FormData();

            formdata.append("image", file);

            this.props.api.uploadImage(formdata).then((response) => {
                let newImageData = {
                    url: response.url,
                    thumbnailUrl: response.thumbnailUrl,
                    width: response.width,
                    height: response.height,
                    id: response.id || this.state.gallery.length
                };

                this.onUrlChange(newImageData);
                if (this.state.gallery) {
                    this.state.gallery.push(newImageData);
                    this.setState({file: null})
                }
            })
        }
    }

    /**
     * save new images data
     * @param data {object} new image data
     */
    selectGalleryItem(data) {

        //change URL
        if(data.url != this.state.url){
            this.onUrlChange(data)
        }
        this.setImageData(data)

    }

    deleteGalleryItem(id) {
        if (this.props.api.deleteImage) {
            this.props.api.deleteImage(id).then(() => {
                var index = this.state.gallery.findIndex(element => element.id === id);
                this.state.gallery.splice(index, 1);
                this.forceUpdate()
            })
        }
    }

    resetData() {
        this.setState({
            url: null,
            alt: null,
            api: {},
            width: null,
            height: null,
            originalHeight: null,
            originalWidth: null,
            onClose: null,
            onSave: null,
            settings: {}
        })
    }

    render() {
        return (

                { this.state.isVisible && <Popup isOpen={this.state.isVisible}>

                                <input onChange={e => this.onUrlChange.call(this, {url: e.target.value})}
                                       placeholder="Enter image URL" value={this.state.url || ""}/>

                                <input onChange={e => this.setState({alt: e.target.value})}
                                       placeholder="Enter image alt" value={this.state.alt || ""}/>

                            {this.state.settings.editDimensions &&

                                    <input onChange={this.onWidthChange.bind(this)}
                                           placeholder="width" value={this.state.width || ""}
                                           style={{width: "65px", marginRight: "10px"}}/>

                                X

                                    <input onChange={this.onHeightChange.bind(this)}
                                           placeholder="height" value={this.state.height || ""}
                                           style={{width: "65px", marginLeft: "10px"}}/>

                                    <input type="checkbox" id="proportions" name="proportions"
                                           onChange={e => {
                                               this.setState({proportions: e.target.checked})
                                           }}
                                           defaultChecked={this.state.proportions}/>
                                    Constrain proportions

                            }
                            {this.state.settings.editBackground &&

                                    <select name="background-size" value={this.state.bgSize}
                                            onChange={this.setBgSize.bind(this)}>
                                        <option value="">Don't Resize</option>
                                        <option value="cover">Resize to Fill</option>
                                        <option value="contain">Resize to Fit</option>
                                    </select>

                                    <select name="background-repeat" value={this.state.bgRepeat}
                                            onChange={this.setBgRepeat.bind(this)}>
                                        <option value="no-repeat">No Tiling</option>
                                        <option value="repeat">Tile</option>
                                        <option value="repeat-x">Tile Horizontally</option>
                                        <option value="repeat-y">Tile Vertically</option>
                                    </select>

                                    <select name="background-position" value={this.state.bgPosition}
                                            onChange={this.setBgPosition.bind(this)}>
                                        <option value="50% 50%">Center</option>
                                        <option value="0px 0px">Top Left</option>
                                    </select>

                                    <input ref={(input) => {
                                        this.colorInput = input;
                                    }} onChange={this.setBgColor.bind(this)}
                                           onClick={this.pickBgColor.bind(this)}
                                           placeholder="Color" value={this.state.bgColor || ""}
                                           style={{width: "150px", marginRight: "5px"}}/>

 {
                                        this.colorDiv = div;
                                    }} onClick={this.pickBgColor.bind(this)} className="color-pick"
                                         style={{backgroundColor: this.state.bgColor || ""}}>

                            }

                    {
                        this.props.api.uploadImage &&

{this.state.file ? this.state.file[0].name : "Choose a file to upload"}

                            <input type="file" className="upload" title="Choose a file to upload"
                                   onChange={(e) => {
                                       this.setState({file: e.target.files})
                                   }}/>
                            <button type="submit" className="button" onClick={this.sendFile.bind(this)}>Upload File
                            </button>

                    }
                    {
                        this.state.gallery &&
                        <Gallery gallery={this.state.gallery} api={this.props.api}
                                 onChange={(imageData) => {
                                     this.selectGalleryItem.call(this, imageData)
                                 }}
                                 onDelete={(id) => this.deleteGalleryItem.call(this, id)}
                        />
                    }

Cancel

Save

                </Popup>
                }

        )
    }
}<commit_msg>renamed pieceData to pieceRef; added a dataset field to the PieceRef object; added pieceRef to HTML Editor<commit_after>import React, {Component} from "react"
import Popup from './components/Popup'
import Gallery from './components/Gallery'
import vanillaColorPicker from '../helpers/VanillaColorPicker';

export default class ImageManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isVisible: false,
            settings: {}
        };

        this.updateImageList();

    }

    updateImageList(){
        this.props.api && this.props.api.getImageList && this.props.api.getImageList(this.state.pieceRef).then((list) => {
            // add index to item if not set by the server
            list.forEach((item, index) => {
                if(!item.Id){
                    item.id = index;
                }
            });
            this.setState({gallery: list})
        });
    }

    toggleImagePopup() {
        this.setState({isVisible: !this.state.isVisible})
    }

    onClose() {
        this.toggleImagePopup();
        this.state.onClose && this.state.onClose();
        this.resetData();
    }

    onSave() {
        this.toggleImagePopup();
        this.state.onSave && this.state.onSave(this.getImageData());
        this.resetData();
    }

    onUrlChange(imageData) {
        this.setState({url: imageData.url, alt: ""});
        this.getImageSize(imageData);
    }

    getImageSize(imageData, getOriginalSizeOnly) {

        //if is image from gallery
        if(imageData.width &&  imageData.height) {
            !getOriginalSizeOnly && this.setState({width: imageData.width, height: imageData.height});
            this.setState({originalWidth: imageData.width, originalHeight: imageData.height});
        } else {
            //if set by hands
            var that = this;
            var img = new Image();
            img.onload = function () {
                !getOriginalSizeOnly && that.setState({width: this.width, height: this.height});
                that.setState({originalWidth: this.width, originalHeight: this.height});
            }
            img.src = imageData.url;
        }

    }

    setBgSize(e) {
        let bgSize = e.target.value;
        this.setState({bgSize});
    }

    setBgPosition(e) {
        let bgPosition = e.target.value;
        this.setState({bgPosition});
    }

    setBgColor(e) {
        let bgColor = e.target.value;
        this.setState({bgColor});
    }

    pickBgColor(e) {
        this.attachPickerAndInvoke();
    }

    setBgRepeat(e) {
        let bgRepeat = e.target.value;
        this.setState({bgRepeat});
    }

    attachPickerAndInvoke() {
        // colors for picker
        let pickerColors = [
            "inherit",
            "#9b59b6",
            "#34495e",
            "#16a085",
            "#27ae60",
            "#2980b9",
            "#8e44ad",
            "#2c3e50",
            "#f1c40f",
            "#e67e22",
            "#e74c3c",
            "#bdc3c7",
            "#95a5a6",
            "#666",
            "#212121",
            "#f39c12",
            "#d2d064",
            "#4fbbf7",
            "#ffffff"
        ];

        /**
         * If we have previously created color picker that is not bound to correct element, kill it
         */
        if (this.picker) {
            if (this.picker.__boundElement != this.colorDiv) {
                this.picker.destroyPicker();
                this.picker = null;
            }
        }

        /**
         * If we still have a picker, open it
         */
        if (this.picker) {
            this.picker.openPicker();
        } else {
            //Create new picker
            this.picker = vanillaColorPicker(this.colorDiv);
            this.picker.set("customColors", pickerColors);
            this.picker.set("positionOnTop");
            this.picker.openPicker();
            this.picker.on("colorChosen", (color) => {
                if (color == "inherit") {
                    this.setState({
                        bgColor: ""
                    })
                } else {
                    this.setState({
                        bgColor: color
                    })
                }
            });
            this.picker.__boundElement = this.colorDiv;
        }
    }

    onWidthChange(e) {
        let newWidth = e.target.value;
        this.setState({width: newWidth});
        if (this.state.proportions) {
            this.setState({height: parseInt(newWidth * this.state.originalHeight / this.state.originalWidth)});
        }
    }

    onHeightChange(e) {
        let newHeight = e.target.value;
        this.setState({height: newHeight});
        if (this.state.proportions) {
            this.setState({width: parseInt(newHeight * this.state.originalWidth / this.state.originalHeight)});
        }
    }

    closePopup() {
        this.setState({isVisible: false})
    }

    showPopup() {
        this.setState({isVisible: true})
    }

    getImageData() {
        let data = {
            url: this.state.url,
            alt: this.state.alt || "",
        };

        /**
         * If image was resized, export new sizes
         */
        if (this.state.originalHeight != this.state.height || this.state.originalWidth != this.state.width) {
            data = {
                width: this.state.width,
                height: this.state.height,
                ...data
            }
        }

        /**
         * If editing background, pass backgrounds too
         */
        if (this.state.settings.editBackground) {
            data = {
                bgColor: this.state.bgColor,
                bgPosition: this.state.bgPosition,
                bgRepeat: this.state.bgRepeat,
                bgSize: this.state.bgSize,
                ...data
            }
        }

        return data;
    }

    setImageData(data) {
        (!data.alt && data.url) && (data.alt = "");
        this.setState(data);
        data.url && this.getImageSize(data, !!data.width);
        this.updateImageList();
    }

    sendFile() {
        if (this.props.api.uploadImage) {
            if (!this.state.file || !this.state.file[0]) return;
            var file = this.state.file[0],
                formdata = new FormData();

            formdata.append("image", file);

            this.props.api.uploadImage(formdata).then((response) => {
                let newImageData = {
                    url: response.url,
                    thumbnailUrl: response.thumbnailUrl,
                    width: response.width,
                    height: response.height,
                    id: response.id || this.state.gallery.length
                };

                this.onUrlChange(newImageData);
                if (this.state.gallery) {
                    this.state.gallery.push(newImageData);
                    this.setState({file: null})
                }
            })
        }
    }

    /**
     * save new images data
     * @param data {object} new image data
     */
    selectGalleryItem(data) {

        //change URL
        if(data.url != this.state.url){
            this.onUrlChange(data)
        }
        data.pieceRef = this.state.pieceRef;
        this.setImageData(data)

    }

    deleteGalleryItem(id) {
        if (this.props.api.deleteImage) {
            this.props.api.deleteImage(id).then(() => {
                var index = this.state.gallery.findIndex(element => element.id === id);
                this.state.gallery.splice(index, 1);
                this.forceUpdate()
            })
        }
    }

    resetData() {
        this.setState({
            url: null,
            alt: null,
            api: {},
            width: null,
            height: null,
            originalHeight: null,
            originalWidth: null,
            onClose: null,
            onSave: null,
            settings: {}
        })
    }

    render() {
        return (

                { this.state.isVisible && <Popup isOpen={this.state.isVisible}>

                                <input onChange={e => this.onUrlChange.call(this, {url: e.target.value})}
                                       placeholder="Enter image URL" value={this.state.url || ""}/>

                                <input onChange={e => this.setState({alt: e.target.value})}
                                       placeholder="Enter image alt" value={this.state.alt || ""}/>

                            {this.state.settings.editDimensions &&

                                    <input onChange={this.onWidthChange.bind(this)}
                                           placeholder="width" value={this.state.width || ""}
                                           style={{width: "65px", marginRight: "10px"}}/>

                                X

                                    <input onChange={this.onHeightChange.bind(this)}
                                           placeholder="height" value={this.state.height || ""}
                                           style={{width: "65px", marginLeft: "10px"}}/>

                                    <input type="checkbox" id="proportions" name="proportions"
                                           onChange={e => {
                                               this.setState({proportions: e.target.checked})
                                           }}
                                           defaultChecked={this.state.proportions}/>
                                    Constrain proportions

                            }
                            {this.state.settings.editBackground &&

                                    <select name="background-size" value={this.state.bgSize}
                                            onChange={this.setBgSize.bind(this)}>
                                        <option value="">Don't Resize</option>
                                        <option value="cover">Resize to Fill</option>
                                        <option value="contain">Resize to Fit</option>
                                    </select>

                                    <select name="background-repeat" value={this.state.bgRepeat}
                                            onChange={this.setBgRepeat.bind(this)}>
                                        <option value="no-repeat">No Tiling</option>
                                        <option value="repeat">Tile</option>
                                        <option value="repeat-x">Tile Horizontally</option>
                                        <option value="repeat-y">Tile Vertically</option>
                                    </select>

                                    <select name="background-position" value={this.state.bgPosition}
                                            onChange={this.setBgPosition.bind(this)}>
                                        <option value="50% 50%">Center</option>
                                        <option value="0px 0px">Top Left</option>
                                    </select>

                                    <input ref={(input) => {
                                        this.colorInput = input;
                                    }} onChange={this.setBgColor.bind(this)}
                                           onClick={this.pickBgColor.bind(this)}
                                           placeholder="Color" value={this.state.bgColor || ""}
                                           style={{width: "150px", marginRight: "5px"}}/>

 {
                                        this.colorDiv = div;
                                    }} onClick={this.pickBgColor.bind(this)} className="color-pick"
                                         style={{backgroundColor: this.state.bgColor || ""}}>

                            }

                    {
                        this.props.api.uploadImage &&

{this.state.file ? this.state.file[0].name : "Choose a file to upload"}

                            <input type="file" className="upload" title="Choose a file to upload"
                                   onChange={(e) => {
                                       this.setState({file: e.target.files})
                                   }}/>
                            <button type="submit" className="button" onClick={this.sendFile.bind(this)}>Upload File
                            </button>

                    }
                    {
                        this.state.gallery &&
                        <Gallery gallery={this.state.gallery} api={this.props.api}
                                 onChange={(imageData) => {
                                     this.selectGalleryItem.call(this, imageData)
                                 }}
                                 onDelete={(id) => this.deleteGalleryItem.call(this, id)}
                        />
                    }

Cancel

Save

                </Popup>
                }

        )
    }
}<|endoftext|>