<commit_before>//! © 2015 Nathan Rugg <nmrugg@gmail.com> | MIT
/// See LICENSE for more details.

// jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true, latedef:true, newcap:true, noarg:true, noempty:true, nonew:true, onevar:true, plusplus:true, quotmark:double, undef:true, unused:strict, browser: true, node: true

/// Does the environment support web workers?  If not, let's load the worker manually (without polluting the global scope).
if (typeof Worker === "undefined" || (typeof location !== "undefined" && location.protocol === "file:")) {
    /// Is this Node.js?
    if (typeof global !== "undefined" && typeof require !== "undefined") {
        this.LZMA = function (lzma_path) {
            return require(lzma_path || "./lzma_worker-min.js").LZMA;
        };
    /// Is this a browser?
    } else if (typeof window !== "undefined" && window.document) {
        (function ()
        {
            var that = this,
                global_var,
                req = function req(path) {
                    var script_tag  = document.createElement("script");
                    script_tag.type ="text/javascript";
                    script_tag.src  = path;
                    script_tag.onload = function () {
                        /// Make sure this LZMA variable doesn't get overwritten by the worker's.
                        that.LZMA = non_worker_lzma;
                    };
                    document.getElementsByTagName("head")[0].appendChild(script_tag);
                };

            /// Determine the global variable (it's called "window" in browsers, "global" in Node.js).
            if (typeof window !== "undefined") {
                global_var = window;
            } else if (global) {
                global_var = global;
            }

            function non_worker_lzma(path)
            {
                var fake_lzma;

                req(path);

                fake_lzma = {
                    compress: function compress(mixed, mode, on_finish, on_progress) {
                        if (global_var.LZMA_WORKER) {
                            global_var.LZMA_WORKER.compress(mixed, mode, on_finish, on_progress);
                        } else {
                            /// Wait
                            setTimeout(function ()
                            {
                                fake_lzma.compress(mixed, mode, on_finish, on_progress);
                            }, 50);
                        }
                    },
                    decompress: function decompress(byte_arr, on_finish, on_progress) {
                        if (global_var.LZMA_WORKER) {
                            global_var.LZMA_WORKER.decompress(byte_arr, on_finish, on_progress);
                        } else {
                            /// Wait
                            setTimeout(function ()
                            {
                                fake_lzma.decompress(byte_arr, on_finish, on_progress);
                            }, 50);
                        }
                    },
                    worker: function() { return null; }
                };

                return fake_lzma;
            }

            that.LZMA = non_worker_lzma;
        }());
    } else {
        /// It doesn't seem to be either Node.js or a browser.
        console.log("Can't load the worker. Sorry.");
    }
} else {
    /// Let's use Web Workers.
    ///NOTE: The "this" keyword is the global context ("window" variable) if loaded via a <script> tag
    ///      or the function context if loaded as a module (e.g., in Node.js).
    this.LZMA = function (lzma_path) {
        var action_compress   = 1,
            action_decompress = 2,
            action_progress   = 3,

            callback_obj = {},

            ///NOTE: Node.js needs something like "./" or "../" at the beginning.
            lzma_worker = new Worker(lzma_path || "./lzma_worker-min.js");

        lzma_worker.onmessage = function (e) {
            if (e.data.action === action_progress) {
                if (callback_obj[e.data.cbn] && typeof callback_obj[e.data.cbn].on_progress === "function") {
                    callback_obj[e.data.cbn].on_progress(e.data.result);
                }
            } else {
                if (callback_obj[e.data.cbn] && typeof callback_obj[e.data.cbn].on_finish === "function") {
                    callback_obj[e.data.cbn].on_finish(e.data.result);

                    /// Since the (de)compression is complete, the callbacks are no longer needed.
                    delete callback_obj[e.data.cbn];
                }
            }
        };

        /// Very simple error handling.
        lzma_worker.onerror = function(event) {
            throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
        };

        return (function () {

            function send_to_worker(action, data, mode, on_finish, on_progress) {
                var cbn;

                do {
                    cbn = Math.floor(Math.random() * (10000000));
                } while(typeof callback_obj[cbn] !== "undefined");

                callback_obj[cbn] = {
                    on_finish:   on_finish,
                    on_progress: on_progress
                };

                lzma_worker.postMessage({
                    action: action, /// action_compress = 1, action_decompress = 2, action_progress = 3
                    cbn:    cbn,    /// callback number
                    data:   data,
                    mode:   mode
                });
            }

            return {
                compress: function compress(mixed, mode, on_finish, on_progress) {
                    send_to_worker(action_compress, mixed, mode, on_finish, on_progress);
                },
                decompress: function decompress(byte_arr, on_finish, on_progress) {
                    send_to_worker(action_decompress, byte_arr, false, on_finish, on_progress);
                },
                worker: function worker() {
                    return lzma_worker;
                }
            };
        }());
    };
}
<commit_msg>Include non-minified version of lzma_worker.js in node.js environment<commit_after>//! © 2015 Nathan Rugg <nmrugg@gmail.com> | MIT
/// See LICENSE for more details.

// jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true, latedef:true, newcap:true, noarg:true, noempty:true, nonew:true, onevar:true, plusplus:true, quotmark:double, undef:true, unused:strict, browser: true, node: true

/// Does the environment support web workers?  If not, let's load the worker manually (without polluting the global scope).
if (typeof Worker === "undefined" || (typeof location !== "undefined" && location.protocol === "file:")) {
    /// Is this Node.js?
    if (typeof global !== "undefined" && typeof require !== "undefined") {
        this.LZMA = function (lzma_path) {
            return require(lzma_path || "./lzma_worker.js").LZMA;
        };
    /// Is this a browser?
    } else if (typeof window !== "undefined" && window.document) {
        (function ()
        {
            var that = this,
                global_var,
                req = function req(path) {
                    var script_tag  = document.createElement("script");
                    script_tag.type ="text/javascript";
                    script_tag.src  = path;
                    script_tag.onload = function () {
                        /// Make sure this LZMA variable doesn't get overwritten by the worker's.
                        that.LZMA = non_worker_lzma;
                    };
                    document.getElementsByTagName("head")[0].appendChild(script_tag);
                };

            /// Determine the global variable (it's called "window" in browsers, "global" in Node.js).
            if (typeof window !== "undefined") {
                global_var = window;
            } else if (global) {
                global_var = global;
            }

            function non_worker_lzma(path)
            {
                var fake_lzma;

                req(path);

                fake_lzma = {
                    compress: function compress(mixed, mode, on_finish, on_progress) {
                        if (global_var.LZMA_WORKER) {
                            global_var.LZMA_WORKER.compress(mixed, mode, on_finish, on_progress);
                        } else {
                            /// Wait
                            setTimeout(function ()
                            {
                                fake_lzma.compress(mixed, mode, on_finish, on_progress);
                            }, 50);
                        }
                    },
                    decompress: function decompress(byte_arr, on_finish, on_progress) {
                        if (global_var.LZMA_WORKER) {
                            global_var.LZMA_WORKER.decompress(byte_arr, on_finish, on_progress);
                        } else {
                            /// Wait
                            setTimeout(function ()
                            {
                                fake_lzma.decompress(byte_arr, on_finish, on_progress);
                            }, 50);
                        }
                    },
                    worker: function() { return null; }
                };

                return fake_lzma;
            }

            that.LZMA = non_worker_lzma;
        }());
    } else {
        /// It doesn't seem to be either Node.js or a browser.
        console.log("Can't load the worker. Sorry.");
    }
} else {
    /// Let's use Web Workers.
    ///NOTE: The "this" keyword is the global context ("window" variable) if loaded via a <script> tag
    ///      or the function context if loaded as a module (e.g., in Node.js).
    this.LZMA = function (lzma_path) {
        var action_compress   = 1,
            action_decompress = 2,
            action_progress   = 3,

            callback_obj = {},

            ///NOTE: Node.js needs something like "./" or "../" at the beginning.
            lzma_worker = new Worker(lzma_path || "./lzma_worker-min.js");

        lzma_worker.onmessage = function (e) {
            if (e.data.action === action_progress) {
                if (callback_obj[e.data.cbn] && typeof callback_obj[e.data.cbn].on_progress === "function") {
                    callback_obj[e.data.cbn].on_progress(e.data.result);
                }
            } else {
                if (callback_obj[e.data.cbn] && typeof callback_obj[e.data.cbn].on_finish === "function") {
                    callback_obj[e.data.cbn].on_finish(e.data.result);

                    /// Since the (de)compression is complete, the callbacks are no longer needed.
                    delete callback_obj[e.data.cbn];
                }
            }
        };

        /// Very simple error handling.
        lzma_worker.onerror = function(event) {
            throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
        };

        return (function () {

            function send_to_worker(action, data, mode, on_finish, on_progress) {
                var cbn;

                do {
                    cbn = Math.floor(Math.random() * (10000000));
                } while(typeof callback_obj[cbn] !== "undefined");

                callback_obj[cbn] = {
                    on_finish:   on_finish,
                    on_progress: on_progress
                };

                lzma_worker.postMessage({
                    action: action, /// action_compress = 1, action_decompress = 2, action_progress = 3
                    cbn:    cbn,    /// callback number
                    data:   data,
                    mode:   mode
                });
            }

            return {
                compress: function compress(mixed, mode, on_finish, on_progress) {
                    send_to_worker(action_compress, mixed, mode, on_finish, on_progress);
                },
                decompress: function decompress(byte_arr, on_finish, on_progress) {
                    send_to_worker(action_decompress, byte_arr, false, on_finish, on_progress);
                },
                worker: function worker() {
                    return lzma_worker;
                }
            };
        }());
    };
}
<|endoftext|>


<commit_before>/**
 * @author Arne Simon [arne.simon@slice-dice.de]
 * @author Max Fielker [max.fielker@slice.dice.de]
 */

import madeChannel from './channel';
import madeFile from './file';

class Made {

  constructor( $q, $cookieStore, $rootScope, uuid4, madeUrlService ) {
    'ngInject';
    Object.assign( this, {
      $q,
      $cookieStore,
      $rootScope,
      uuid4,
      madeUrlService,
      contexts: {},
      reconnectTimeout: 1000,
      user: null,
      wss: null
    } );

    this.setupSocket();

    this.afterConnect = this.whenConnected;
  }

  setupSocket() {
    this.wss = new WebSocket( this.madeUrlService() );

    if ( !this.user ) {
      this.user = this.$cookieStore.get( 'user' );
    }
    if ( undefined === this.user ) {
      this.user = null;
    }

    this.wss.onopen = function () {
      $rootScope.$broadcast('made-connection-open');
      console.log( 'socket open!' );
    };

    this.wss.onerror = function ( errorEvent ) {
      $rootScope.$broadcast('made-connection-error');
      console.log( 'socket error, event:', errorEvent );
    };

    this.wss.onclose = function ( closeEvent ) {
      $rootScope.$broadcast('made-connection-closed');
      console.log( 'socket close, event:', closeEvent );
      setTimeout( this.setupSocket, this.reconnectTimeout );

      if ( this.reconnectTimeout < 1000 * 60 * 2 ) {
        this.reconnectTimeout *= 2;
      }
    };

    this.wss.onmessage = function ( msg ) {
      msg = JSON.parse( msg.data );

      switch (msg.action) {
        case 'answer':
          if ( msg.context in this.contexts ) {
            if ( msg.success ) {
              this.contexts[ msg.context ].resolve( msg );
              if ( 'schema' === this.contexts[ msg.context ].action ) {
                console.log( '++ received schema ++', this.contexts[ msg.context ].uri, msg.data.schema );
              } else {
                console.log( '++ received ++', this.contexts[ msg.context ].uri, msg.data, msg.error );
              }
            } else {
              console.log( '-- received --' + (msg.error ? 'ERROR' : ''), this.contexts[ msg.context ].uri, msg );
              if ( this.contexts[ msg.context ].reject ) {
                this.contexts[ msg.context ].reject( msg );
                this.$rootScope.$broadcast( 'made-error', msg );
              }

              // UnknownIssuer exception: because key from the login is not longer valid.
              if ( '15c3ad4d828c5937a721893351c767fd' === msg.error.id ) {
                this.logout();
                this.$rootScope.$broadcast( 'made-logout' );
              }
            }
            delete this.contexts[ msg.context ];
          } else {
            console.log( 'made-js error: message for unknown context' );
          }
          break;
        case 'channel':
          console.log( '-- received --' + (msg.error ? 'ERROR' : ''), msg );
          switch (msg.data.type) {
            case 'open':
              console.log( '!!!FATAL!!! Opening channel to browser not allowed!' );
              break;
            case 'package':
              if ( msg.context in this.contexts ) {
                this.contexts[ msg.context ].handleRecv( msg.data.package );
              } else {
                console.log( 'package for unknown channel' );
              }
              break;
            case 'close':
              if ( msg.context in this.contexts ) {
                this.contexts[ msg.context ].handleClose();
              } else {
                console.log( 'close for unknown channel' );
              }
              break;
          }
      }

    };
  }

  message( action, data ) {
    return {
      'user': this.user,
      'context': 0,
      'action': action,
      'data': data,
      'error': null,
      'success': true,
    };
  }

  whenConnected( callback ) {
    function wait() {
      console.log( 'made-js - wait for connect' );
      setTimeout( function () {
        this.whenConnected( callback );
      }, 750 );
    }

    if ( this.wss ) {
      switch (this.wss.readyState) {
        case WebSocket.CONNECTING:
          wait();
          break;
        case WebSocket.OPEN:
          this.reconnectTimeout = 1000;
          callback();
          break;
        default:
          console.log( 'made-js: try to send over a closed socket!' );
          this.setupSocket();
          wait();
          break;
      }
    } else {
      wait();
    }
  }

  send( action, data ) {
    var defer = this.$q.defer();
    var context = this.uuid4.generate();

    this.contexts[ context ] = defer;

    this.send_with_context( action, data, context );

    return defer.promise;
  }

  send_with_context( action, data, context ) {
    var msg = this.message( action, data );
    msg.context = context;

    if ( msg.action == 'request' ) {
      this.contexts[ context ].uri = msg.data.uri;
      console.log( '-- sending --', msg.data.uri, msg.data.args, msg.data.kwargs );
    } else if ( 'schema' === msg.action ) {
      this.contexts[ context ].uri = msg.data;
      this.contexts[ context ].action = msg.action;
      console.log( '-- schema --', msg.data );
    } else {
      console.log( '-- sending --', msg.action, context );
    }

    var encoded = angular.toJson( msg );

    this.whenConnected( () => {
      this.wss.send( encoded );
    } );
  }

  request( uri, kwargs ) {
    if ( typeof kwargs === 'undefined' ) {
      kwargs = {};
    }

    var data = {
      uri: uri,
      kwargs: kwargs
    };

    return this.send( 'request', data );
  }

  channel( uri ) {
    return new madeChannel( this, uri, this.uuid4.generate() );
  }

  topology() {
    return this
      .send( 'topology', {} )
      .then( result => result.data );
  }

  capabilities() {

    return this
      .send( 'capabilities' )
      .then( result => result.data );
  }

  schema( url ) {
    return this
      .send( 'schema', url )
      .then( result => result.data );
  }

  fileFromData( name, data ) {
    let ctx = {
        filename: name,
        chunk_size: 255 * 1024,
        length: data.byteLength,
        md5: '',
        encoding: 'utf-8',
        meta: {}
      },
      file = new madeFile( this, ctx );
    file.data = data;

    return file;
  }

  file( ctx ) {
    return new madeFile( this, ctx );
  }

  loginByName( user, password ) {

    return this
      .request( 'rpc://crm/user/login', [], {
        user,
        password
      } )
      .then( result => this.login( result.data ) );
  }

  loginByEmail( email, password ) {

    return this
      .request( 'rpc://crm/user/login', [], {
        email,
        password
      } )
      .then( result => this.login( result.data ) );
  }

  login( user ) {
    this.user = user;
    this.$cookieStore.put( 'user', this.user );
    this.$rootScope.$broadcast( 'made-login' );
  }

  logout() {
    if ( this.user ) {
      this.request( 'rpc://crm/user/logout' );
      this.user = null;

      this.$cookieStore.put( 'user', null );
      this.$rootScope.$broadcast( 'made-logout' );
    }
  }

  isLoggedin() {
    return null !== this.user;
  }
}

export default Made;
<commit_msg>Fix UrlServiceProviderUsage<commit_after>/**
 * @author Arne Simon [arne.simon@slice-dice.de]
 * @author Max Fielker [max.fielker@slice.dice.de]
 */

import madeChannel from './channel';
import madeFile from './file';

class Made {

  constructor( $q, $cookieStore, $rootScope, uuid4, madeUrlService ) {
    'ngInject';
    Object.assign( this, {
      $q,
      $cookieStore,
      $rootScope,
      uuid4,
      madeUrlService,
      contexts: {},
      reconnectTimeout: 1000,
      user: null,
      wss: null
    } );

    this.setupSocket();

    this.afterConnect = this.whenConnected;
  }

  setupSocket() {
    this.wss = new WebSocket( this.madeUrlService );

    if ( !this.user ) {
      this.user = this.$cookieStore.get( 'user' );
    }
    if ( undefined === this.user ) {
      this.user = null;
    }

    this.wss.onopen = function () {
      $rootScope.$broadcast('made-connection-open');
      console.log( 'socket open!' );
    };

    this.wss.onerror = function ( errorEvent ) {
      $rootScope.$broadcast('made-connection-error');
      console.log( 'socket error, event:', errorEvent );
    };

    this.wss.onclose = function ( closeEvent ) {
      $rootScope.$broadcast('made-connection-closed');
      console.log( 'socket close, event:', closeEvent );
      setTimeout( this.setupSocket, this.reconnectTimeout );

      if ( this.reconnectTimeout < 1000 * 60 * 2 ) {
        this.reconnectTimeout *= 2;
      }
    };

    this.wss.onmessage = function ( msg ) {
      msg = JSON.parse( msg.data );

      switch (msg.action) {
        case 'answer':
          if ( msg.context in this.contexts ) {
            if ( msg.success ) {
              this.contexts[ msg.context ].resolve( msg );
              if ( 'schema' === this.contexts[ msg.context ].action ) {
                console.log( '++ received schema ++', this.contexts[ msg.context ].uri, msg.data.schema );
              } else {
                console.log( '++ received ++', this.contexts[ msg.context ].uri, msg.data, msg.error );
              }
            } else {
              console.log( '-- received --' + (msg.error ? 'ERROR' : ''), this.contexts[ msg.context ].uri, msg );
              if ( this.contexts[ msg.context ].reject ) {
                this.contexts[ msg.context ].reject( msg );
                this.$rootScope.$broadcast( 'made-error', msg );
              }

              // UnknownIssuer exception: because key from the login is not longer valid.
              if ( '15c3ad4d828c5937a721893351c767fd' === msg.error.id ) {
                this.logout();
                this.$rootScope.$broadcast( 'made-logout' );
              }
            }
            delete this.contexts[ msg.context ];
          } else {
            console.log( 'made-js error: message for unknown context' );
          }
          break;
        case 'channel':
          console.log( '-- received --' + (msg.error ? 'ERROR' : ''), msg );
          switch (msg.data.type) {
            case 'open':
              console.log( '!!!FATAL!!! Opening channel to browser not allowed!' );
              break;
            case 'package':
              if ( msg.context in this.contexts ) {
                this.contexts[ msg.context ].handleRecv( msg.data.package );
              } else {
                console.log( 'package for unknown channel' );
              }
              break;
            case 'close':
              if ( msg.context in this.contexts ) {
                this.contexts[ msg.context ].handleClose();
              } else {
                console.log( 'close for unknown channel' );
              }
              break;
          }
      }

    };
  }

  message( action, data ) {
    return {
      'user': this.user,
      'context': 0,
      'action': action,
      'data': data,
      'error': null,
      'success': true,
    };
  }

  whenConnected( callback ) {
    function wait() {
      console.log( 'made-js - wait for connect' );
      setTimeout( function () {
        this.whenConnected( callback );
      }, 750 );
    }

    if ( this.wss ) {
      switch (this.wss.readyState) {
        case WebSocket.CONNECTING:
          wait();
          break;
        case WebSocket.OPEN:
          this.reconnectTimeout = 1000;
          callback();
          break;
        default:
          console.log( 'made-js: try to send over a closed socket!' );
          this.setupSocket();
          wait();
          break;
      }
    } else {
      wait();
    }
  }

  send( action, data ) {
    var defer = this.$q.defer();
    var context = this.uuid4.generate();

    this.contexts[ context ] = defer;

    this.send_with_context( action, data, context );

    return defer.promise;
  }

  send_with_context( action, data, context ) {
    var msg = this.message( action, data );
    msg.context = context;

    if ( msg.action == 'request' ) {
      this.contexts[ context ].uri = msg.data.uri;
      console.log( '-- sending --', msg.data.uri, msg.data.args, msg.data.kwargs );
    } else if ( 'schema' === msg.action ) {
      this.contexts[ context ].uri = msg.data;
      this.contexts[ context ].action = msg.action;
      console.log( '-- schema --', msg.data );
    } else {
      console.log( '-- sending --', msg.action, context );
    }

    var encoded = angular.toJson( msg );

    this.whenConnected( () => {
      this.wss.send( encoded );
    } );
  }

  request( uri, kwargs ) {
    if ( typeof kwargs === 'undefined' ) {
      kwargs = {};
    }

    var data = {
      uri: uri,
      kwargs: kwargs
    };

    return this.send( 'request', data );
  }

  channel( uri ) {
    return new madeChannel( this, uri, this.uuid4.generate() );
  }

  topology() {
    return this
      .send( 'topology', {} )
      .then( result => result.data );
  }

  capabilities() {

    return this
      .send( 'capabilities' )
      .then( result => result.data );
  }

  schema( url ) {
    return this
      .send( 'schema', url )
      .then( result => result.data );
  }

  fileFromData( name, data ) {
    let ctx = {
        filename: name,
        chunk_size: 255 * 1024,
        length: data.byteLength,
        md5: '',
        encoding: 'utf-8',
        meta: {}
      },
      file = new madeFile( this, ctx );
    file.data = data;

    return file;
  }

  file( ctx ) {
    return new madeFile( this, ctx );
  }

  loginByName( user, password ) {

    return this
      .request( 'rpc://crm/user/login', [], {
        user,
        password
      } )
      .then( result => this.login( result.data ) );
  }

  loginByEmail( email, password ) {

    return this
      .request( 'rpc://crm/user/login', [], {
        email,
        password
      } )
      .then( result => this.login( result.data ) );
  }

  login( user ) {
    this.user = user;
    this.$cookieStore.put( 'user', this.user );
    this.$rootScope.$broadcast( 'made-login' );
  }

  logout() {
    if ( this.user ) {
      this.request( 'rpc://crm/user/logout' );
      this.user = null;

      this.$cookieStore.put( 'user', null );
      this.$rootScope.$broadcast( 'made-logout' );
    }
  }

  isLoggedin() {
    return null !== this.user;
  }
}

export default Made;
<|endoftext|>


<commit_before>import syllable from 'syllable';
import _ from 'lodash';
import wordnet from 'wordnet';
var $ = require('jquery-deferred');
import stopwords from './data/stopwords.js';
import descriptors from './data/descriptors.js';
import cusseth from './data/cusseth.js';
import nouns from './data/nouns.js';
import thesaurus from './data/thesaurus.js';

let adjectives = descriptors.map(word => [word, syllable(word)]);
let curses = cusseth.map(word => [word, syllable(word)]);

const HAIKU_LENGTH = 17;
const separator = '//';
const FOUL = false;

// Chrys' Domain
function addModifier(phrase, length, mod) {
  let tokens = phrase.split(/\W/);
  let nounList = tokens.map(word => _.contains(nouns, word));
  for (var i in nounList) {
    if (nounList[i]) {
      tokens.splice(i, 0, mod);
      return tokens.join(' ');
    }
  }

  return mod + ' ' + phrase;
}

export function addExpletive(phrase, length) {
  var curse = _.sample(curses.filter(tuple => tuple[1] === length));
  if (!curse) {
    return addExpletive(addExpletive(phrase, length - 1), 1);
  }

  return addModifier(phrase, length, curse[0]);
}

export function addAdjective(phrase, length) {
  var adj = _.sample(adjectives.filter(tuple => tuple[1] === length));
  if (!adj) {
    return addAdjective(addAdjective(phrase, length - 1), 1);
  }

  return addModifier(phrase, length, adj[0]);
}

export function removeWords(phrase, length) {
  console.log(phrase, length);
  let tokens = phrase.split(/\W/);
  let newTokens = [];
  tokens.forEach(function(token) {
    if (length && _.contains(stopwords, token)) {
      length -= syllable(token);
    } else {
      newTokens.push(token);
    }
  });

  return newTokens.join(' ');
}

function addWords(phrase, length) {
  if (FOUL) {
    return addExpletive(phrase, length);
  } else {
    return addAdjective(phrase, length);
  }
}

// Nicole WUZ HERE
export function shortenWord(word, adjustment) {
  let possibleNewWord = [];
  let theNewWord;
  let newWordSyllables;
  let adjustedList;
  let otheradjustednotasgoodList;
  let currentWordSyllables = syllable(word);

  adjustment = -adjustment;

  let list = []

  var response = possibleSynonymArray(word);

  if (!_.isEmpty(response)) {
    for (let x=0; x<response.length; x++) {
      list[x] = [response[x], syllable(response[x])]
    }

    adjustedList = list.filter(synonym => synonym[1] - currentWordSyllables === adjustment);

    if (!_.isEmpty(adjustedList)) {
      return adjustedList[0][0];
    }

    else {
      otheradjustednotasgoodList = list.filter(synonym => (synonym[1] - currentWordSyllables > adjustment) && (synonym[1] < currentWordSyllables)).sort(function(a, b) {return a[1]-b[1]});
    }

    if (!_.isEmpty(otheradjustednotasgoodList)) {
      return otheradjustednotasgoodList[0][0]
    } else {
      return word;
    }
  } else {
    return word;
  }

}

function possibleSynonymArray(word) {
  if (thesaurus[word]) {
    return thesaurus[word];
  }
}

function possibleSynonymArrayAsync(word) {
  var promise = $.Deferred();

  var possibleNewWords = [];
  wordnet.lookup(word, function(err, definitions) {
    if (definitions) {
      definitions.forEach(function(definition) {
        var words = definition.meta.words;
        words.forEach(function(word) {
          if (!_.includes(possibleNewWords, word.word)) {
            possibleNewWords.push(word.word);
          }
        });
      });
    }
    promise.resolve(possibleNewWords);
  });
  return promise;
}

export function expandWord(word, adjustment) {
  let possibleNewWord = [];
  let theNewWord;
  let newWordSyllables;
  let adjustedList;
  let otheradjustednotasgoodList;
  let currentWordSyllables = syllable(word);
  let list = []

  var response = possibleSynonymArray(word);

  if (!_.isEmpty(response)){
    for (let x=0; x<response.length; x++) {
      list[x] = [response[x], syllable(response[x])]
    }

    adjustedList = list.filter(synonym => synonym[1] - currentWordSyllables === adjustment);
    if (!_.isEmpty(adjustedList)) {
      return adjustedList[0][0];
    } else {
      otheradjustednotasgoodList = list.filter(synonym => (synonym[1] - currentWordSyllables < adjustment) && (synonym[1] > currentWordSyllables)).sort(function(a, b) {return b[1]-a[1]});
    }

    if (!_.isEmpty(otheradjustednotasgoodList)) {
      return otheradjustednotasgoodList[0][0]
    } else {
      return word;
    }
  } else {
    return word;
  }
}

let countSyllables = function(phrase) {
  let tokens = phrase.split(/\W/);
  return _.sum(tokens.map(syllable));
};

function adjustWord(word, adjustment) {
  if (adjustment > 0) {
    return expandWord(word, adjustment);
  } else if (adjustment < 0) {
    return shortenWord(word, adjustment);
  } else {
    return word;
  }
}

export function adjustPhrase(phrase, adjustment) {
  console.log(phrase, adjustment);
  if (adjustment > 0) {
    return addWords(phrase, adjustment);
  } else if (adjustment < 0) {
    return removeWords(phrase, adjustment);
  } else {
    return phrase;
  }
}

function adjustSyllables(lines, adjustment) {
  let line = 0;
  let idx = 0;
  let token = lines[line][idx];

  // First loop to make small adjustments to existing words' lengths.
  while (adjustment !== 0 && line < 3) {
    let newWord = adjustWord(token, adjustment);

    if (newWord) {
      lines[line][idx] = newWord;
      adjustment -= (syllable(newWord) - syllable(token));
    }

    idx++;
    token = lines[line][idx];
    if (!token) {
      line++;
      idx = 0;
      if (line > 2) {
        break;
      }
      token = lines[line][idx];

    }
  }

  var joined = lines.map(line => line.join(' '));
  line = 0;

  // Second while loop to add / remove extraneous words
  while (adjustment !== 0 && line < 3) {
    let oldPhrase = joined[line];
    let lineCount = countSyllables(oldPhrase);

    if ((line === 1 && lineCount === 7) || lineCount === 5) {
      line++;
    } else {
      var newPhrase;
      var maxLineAdjustment = (line === 1) ? 7 : 5;
      var lineAdjustment;

      if (adjustment < 0) {
        if ((adjustment * -1) > lineCount) {
          lineAdjustment = lineCount * -1;
        } else {
          lineAdjustment = adjustment;
        }
      } else if (adjustment > 0) {

        let maxPossibleAdjustment = (maxLineAdjustment - lineCount);
        lineAdjustment = adjustment > maxPossibleAdjustment ? maxPossibleAdjustment : adjustment;

      }

      newPhrase = adjustPhrase(oldPhrase, lineAdjustment);

      joined[line] = newPhrase;
      adjustment -= (countSyllables(newPhrase) - countSyllables(oldPhrase));
      line++;
    }

  }

  return joined.join(' ' + separator + ' ');
}

export function isHaiku(msg) {
  return countSyllables(msg, separator) === HAIKU_LENGTH;
}

export function breakIntoHaiku(msg) {
  var tokens = msg.trim().split(/\W/);
  var rows = [[], [], []];
  var rowSyllables = 0;
  var line = 0;
  while (tokens.length) {
    let token = tokens.shift();
    let tokenLength = syllable(token);

    if (line === 0) {
      var diff = (rowSyllables + tokenLength) - 5;
      if (diff > 0) {
        line += 1;
        rowSyllables = 0;
      }

    } else if (line === 1) {

      var diff = (rowSyllables + tokenLength) - 7;
      if (diff > 0) {
        line += 1;
        rowSyllables = 0;
      }

    }

    rowSyllables += tokenLength;
    rows[line].push(token);

  }

  return rows;
}

/**
 * steps to check if it is a haiku
 * 1. check syllable length of commit
 * 2. if longer - > check for haikus in commit..
 *  a) if haiku -> print done !
 *  b) if not -> get most of haiku and continue? choose key words and continue?
 * 3. if shorter -> check syllable counts?
 * for what is missing -> fill in rhyme etc. to make up length ?? nonsensical ??
 */
 export function makeHaiku(msg) {
  let syllables = countSyllables(msg);
  let difference = HAIKU_LENGTH - syllables;

  msg = breakIntoHaiku(msg);
  return adjustSyllables(msg, difference);
}<commit_msg>I bought new millinery // rank rank rank weather bitten  // mammering<commit_after>import syllable from 'syllable';
import _ from 'lodash';
import wordnet from 'wordnet';
var $ = require('jquery-deferred');
import stopwords from './data/stopwords.js';
import descriptors from './data/descriptors.js';
import cusseth from './data/cusseth.js';
import nouns from './data/nouns.js';
import thesaurus from './data/thesaurus.js';

let adjectives = descriptors.map(word => [word, syllable(word)]);
let curses = cusseth.map(word => [word, syllable(word)]);

const HAIKU_LENGTH = 17;
const separator = '//';
const FOUL = true;

// Chrys' Domain
function addModifier(phrase, length, mod) {
  let tokens = phrase.split(/\W/);
  let nounList = tokens.map(word => _.contains(nouns, word));
  for (var i in nounList) {
    if (nounList[i]) {
      tokens.splice(i, 0, mod);
      return tokens.join(' ');
    }
  }

  return mod + ' ' + phrase;
}

export function addExpletive(phrase, length) {
  var curse = _.sample(curses.filter(tuple => tuple[1] === length));
  if (!curse) {
    return addExpletive(addExpletive(phrase, length - 1), 1);
  }

  return addModifier(phrase, length, curse[0]);
}

export function addAdjective(phrase, length) {
  var adj = _.sample(adjectives.filter(tuple => tuple[1] === length));
  if (!adj) {
    return addAdjective(addAdjective(phrase, length - 1), 1);
  }

  return addModifier(phrase, length, adj[0]);
}

export function removeWords(phrase, length) {
  console.log(phrase, length);
  let tokens = phrase.split(/\W/);
  let newTokens = [];
  tokens.forEach(function(token) {
    if (length && _.contains(stopwords, token)) {
      length -= syllable(token);
    } else {
      newTokens.push(token);
    }
  });

  return newTokens.join(' ');
}

function addWords(phrase, length) {
  if (FOUL) {
    return addExpletive(phrase, length);
  } else {
    return addAdjective(phrase, length);
  }
}

// Nicole WUZ HERE
export function shortenWord(word, adjustment) {
  let possibleNewWord = [];
  let theNewWord;
  let newWordSyllables;
  let adjustedList;
  let otheradjustednotasgoodList;
  let currentWordSyllables = syllable(word);

  adjustment = -adjustment;

  let list = []

  var response = possibleSynonymArray(word);

  if (!_.isEmpty(response)) {
    for (let x=0; x<response.length; x++) {
      list[x] = [response[x], syllable(response[x])]
    }

    adjustedList = list.filter(synonym => synonym[1] - currentWordSyllables === adjustment);

    if (!_.isEmpty(adjustedList)) {
      return adjustedList[0][0];
    }

    else {
      otheradjustednotasgoodList = list.filter(synonym => (synonym[1] - currentWordSyllables > adjustment) && (synonym[1] < currentWordSyllables)).sort(function(a, b) {return a[1]-b[1]});
    }

    if (!_.isEmpty(otheradjustednotasgoodList)) {
      return otheradjustednotasgoodList[0][0]
    } else {
      return word;
    }
  } else {
    return word;
  }

}

function possibleSynonymArray(word) {
  if (thesaurus[word]) {
    return thesaurus[word];
  }
}

function possibleSynonymArrayAsync(word) {
  var promise = $.Deferred();

  var possibleNewWords = [];
  wordnet.lookup(word, function(err, definitions) {
    if (definitions) {
      definitions.forEach(function(definition) {
        var words = definition.meta.words;
        words.forEach(function(word) {
          if (!_.includes(possibleNewWords, word.word)) {
            possibleNewWords.push(word.word);
          }
        });
      });
    }
    promise.resolve(possibleNewWords);
  });
  return promise;
}

export function expandWord(word, adjustment) {
  let possibleNewWord = [];
  let theNewWord;
  let newWordSyllables;
  let adjustedList;
  let otheradjustednotasgoodList;
  let currentWordSyllables = syllable(word);
  let list = []

  var response = possibleSynonymArray(word);

  if (!_.isEmpty(response)){
    for (let x=0; x<response.length; x++) {
      list[x] = [response[x], syllable(response[x])]
    }

    adjustedList = list.filter(synonym => synonym[1] - currentWordSyllables === adjustment);
    if (!_.isEmpty(adjustedList)) {
      return adjustedList[0][0];
    } else {
      otheradjustednotasgoodList = list.filter(synonym => (synonym[1] - currentWordSyllables < adjustment) && (synonym[1] > currentWordSyllables)).sort(function(a, b) {return b[1]-a[1]});
    }

    if (!_.isEmpty(otheradjustednotasgoodList)) {
      return otheradjustednotasgoodList[0][0]
    } else {
      return word;
    }
  } else {
    return word;
  }
}

let countSyllables = function(phrase) {
  let tokens = phrase.split(/\W/);
  return _.sum(tokens.map(syllable));
};

function adjustWord(word, adjustment) {
  if (adjustment > 0) {
    return expandWord(word, adjustment);
  } else if (adjustment < 0) {
    return shortenWord(word, adjustment);
  } else {
    return word;
  }
}

export function adjustPhrase(phrase, adjustment) {
  console.log(phrase, adjustment);
  if (adjustment > 0) {
    return addWords(phrase, adjustment);
  } else if (adjustment < 0) {
    return removeWords(phrase, adjustment);
  } else {
    return phrase;
  }
}

function adjustSyllables(lines, adjustment) {
  let line = 0;
  let idx = 0;
  let token = lines[line][idx];

  // First loop to make small adjustments to existing words' lengths.
  while (adjustment !== 0 && line < 3) {
    let newWord = adjustWord(token, adjustment);

    if (newWord) {
      lines[line][idx] = newWord;
      adjustment -= (syllable(newWord) - syllable(token));
    }

    idx++;
    token = lines[line][idx];
    if (!token) {
      line++;
      idx = 0;
      if (line > 2) {
        break;
      }
      token = lines[line][idx];

    }
  }

  var joined = lines.map(line => line.join(' '));
  line = 0;

  // Second while loop to add / remove extraneous words
  while (adjustment !== 0 && line < 3) {
    let oldPhrase = joined[line];
    let lineCount = countSyllables(oldPhrase);

    if ((line === 1 && lineCount === 7) || lineCount === 5) {
      line++;
    } else {
      var newPhrase;
      var maxLineAdjustment = (line === 1) ? 7 : 5;
      var lineAdjustment;

      if (adjustment < 0) {
        if ((adjustment * -1) > lineCount) {
          lineAdjustment = lineCount * -1;
        } else {
          lineAdjustment = adjustment;
        }
      } else if (adjustment > 0) {

        let maxPossibleAdjustment = (maxLineAdjustment - lineCount);
        lineAdjustment = adjustment > maxPossibleAdjustment ? maxPossibleAdjustment : adjustment;

      }

      newPhrase = adjustPhrase(oldPhrase, lineAdjustment);

      joined[line] = newPhrase;
      adjustment -= (countSyllables(newPhrase) - countSyllables(oldPhrase));
      line++;
    }

  }

  return joined.join(' ' + separator + ' ');
}

export function isHaiku(msg) {
  return countSyllables(msg, separator) === HAIKU_LENGTH;
}

export function breakIntoHaiku(msg) {
  var tokens = msg.trim().split(/\W/);
  var rows = [[], [], []];
  var rowSyllables = 0;
  var line = 0;
  while (tokens.length) {
    let token = tokens.shift();
    let tokenLength = syllable(token);

    if (line === 0) {
      var diff = (rowSyllables + tokenLength) - 5;
      if (diff > 0) {
        line += 1;
        rowSyllables = 0;
      }

    } else if (line === 1) {

      var diff = (rowSyllables + tokenLength) - 7;
      if (diff > 0) {
        line += 1;
        rowSyllables = 0;
      }

    }

    rowSyllables += tokenLength;
    rows[line].push(token);

  }

  return rows;
}

/**
 * steps to check if it is a haiku
 * 1. check syllable length of commit
 * 2. if longer - > check for haikus in commit..
 *  a) if haiku -> print done !
 *  b) if not -> get most of haiku and continue? choose key words and continue?
 * 3. if shorter -> check syllable counts?
 * for what is missing -> fill in rhyme etc. to make up length ?? nonsensical ??
 */
 export function makeHaiku(msg) {
  let syllables = countSyllables(msg);
  let difference = HAIKU_LENGTH - syllables;

  msg = breakIntoHaiku(msg);
  return adjustSyllables(msg, difference);
}<|endoftext|>


<commit_before>var koa = require("koa")
var app = koa();
var server = require("http").createServer()
var wss = new require("ws").Server({server});
var models = require("./models")
var bodyParser = require("body-parser")
var url_module = require("url")
var tokenAuth = require("./utils/tokenAuth")
var multer = require("multer")()
var models = require("./models")
var msgpack = require("msgpack5")()
var yaml = require("yamljs")
var bodyParser = require("koa-bodyparser");
var _ = require("koa-route")

console.log("###################")
console.log("### Kyoppie API ###")
console.log("###################")
console.log("Repository: https://github.com/kyoppie/kyoppie-api")

app.use(bodyParser())

// CORS
app.use(function* (next){
    this.append("Access-Control-Allow-Origin","*")
    this.append("Access-Control-Allow-Method","GET, POST, OPTIONS");
    this.append("Access-Control-Allow-Headers","X-Kyoppie-Access-Token");
    this.append("Access-Control-Max-Age","86400")
    yield next;
})
app.use(function* (next){
    if(this.request.method === "OPTIONS"){
        this.response_code = 200;
        this.body = "ok";
        return;
    }
    yield next;
})
app.use(function* (next){
    var origpath = this.request.path;
    this.path = this.path.replace(/\.msgpack$/,"");
    this.path = this.path.replace(/\.yaml$/,"");
    yield next;
    this.body = JSON.parse(JSON.stringify(this.body));
    if(/.*\.msgpack$/.test(origpath)){ // msgpack hack
        this.set("Content-Type","application/x-msgpack");
        this.body = msgpack.encode(this.body)
    } else if(/.*\.yaml$/.test(origpath)){ // yaml hack
        this.set("Content-Type","text/yaml")
        this.body = yaml.stringify(this.body)
    } else { // json
        this.set("Content-Type","application/json")
        this.body = JSON.stringify(this.body)
    }
})
// MongoDB Logger
app.use(function* (next){
    if(this.request.method !== "POST") return yield next;
    var log = new models.logs();
    log.ipaddr = this.request.header['x-forwarded-for'] || this.socket.remoteAddress;
    log.path = this.path;
    yield next;
    log.response = JSON.stringify(this.body);
    yield log.save();
})
var routes = require("./routes")
routes.rest.forEach(function(route){
    var login = true;
    if(route.login !== undefined) login = route.login;
    var method = route.method;
    var path = route.name;
    var authFunc = tokenAuth(route,login)
    var checkSuspended = function* (next){
        if(this.request.method == "POST" && login && this.token.user.isSuspended){
            this.status_code = 403
            this.body = {result:false,error:"this-user-is-suspended"}
            return
        }
        yield next;
    }
    app.use(_[method](path,authFunc));
    if(login) app.use(_[method](path,checkSuspended))
    // if(route.file)
    app.use(_[method](path,require("./handlers/web"+path)))
})
var ws_route = {};
routes.websocket.forEach(function(route){
    var login = true;
    if(route.login !== undefined) login = route.login;
    var path = route.name;
    ws_route[path] = route;
    ws_route[path]["login"] = login;
    ws_route[path]["callback"] = require("./handlers/ws"+path)
})
wss.on("connection",function(ws){
    var location = url_module.parse(ws.upgradeReq.url,true);
    var url = location.pathname;
    ws.sendJSON = function(json){
        ws.send(JSON.stringify(json))
    }
    if(!ws_route[url]){
        ws.sendJSON({result:false,error:"api-not-found"})
        ws.close();
        return
    }
    console.log(ws_route)
    if(ws_route[url].login){
        if(location.query.access_token){
            models.access_tokens.findOne({
                secret:location.query.access_token
            }).populate("app user").then(function(token){
                console.log(token)
                if(token){
                    ws.token=token;
                    ws_route[url].callback(ws);
                } else {
                    ws.sendJSON({result:false,error:"please-auth"})
                    ws.close()
                    return
                }
            },function(){
                ws.send(JSON.strigify({response:false,error:"server-side-auth-error"}))
                ws.close()
                return
            })
        } else {
            ws.sendJSON({result:false,error:"please-auth"})
            ws.close()
            return
        }
    } else {
        ws_route[url].callback(ws);
    }
})
app.use(function *(){
    this.status_code = 404;
    this.body = {result:false,error:"not-found"}
})
app.on("error",function(err){
    console.log(err)
    this.body = {result:false,error:"server-side-error"}
})
server.on("request",app.callback());
server.listen(4005,function(){
    console.log("listen for "+server.address().port+" port");
})<commit_msg>remove debug code<commit_after>var koa = require("koa")
var app = koa();
var server = require("http").createServer()
var wss = new require("ws").Server({server});
var models = require("./models")
var bodyParser = require("body-parser")
var url_module = require("url")
var tokenAuth = require("./utils/tokenAuth")
var multer = require("multer")()
var models = require("./models")
var msgpack = require("msgpack5")()
var yaml = require("yamljs")
var bodyParser = require("koa-bodyparser");
var _ = require("koa-route")

console.log("###################")
console.log("### Kyoppie API ###")
console.log("###################")
console.log("Repository: https://github.com/kyoppie/kyoppie-api")

app.use(bodyParser())

// CORS
app.use(function* (next){
    this.append("Access-Control-Allow-Origin","*")
    this.append("Access-Control-Allow-Method","GET, POST, OPTIONS");
    this.append("Access-Control-Allow-Headers","X-Kyoppie-Access-Token");
    this.append("Access-Control-Max-Age","86400")
    yield next;
})
app.use(function* (next){
    if(this.request.method === "OPTIONS"){
        this.response_code = 200;
        this.body = "ok";
        return;
    }
    yield next;
})
app.use(function* (next){
    var origpath = this.request.path;
    this.path = this.path.replace(/\.msgpack$/,"");
    this.path = this.path.replace(/\.yaml$/,"");
    yield next;
    this.body = JSON.parse(JSON.stringify(this.body));
    if(/.*\.msgpack$/.test(origpath)){ // msgpack hack
        this.set("Content-Type","application/x-msgpack");
        this.body = msgpack.encode(this.body)
    } else if(/.*\.yaml$/.test(origpath)){ // yaml hack
        this.set("Content-Type","text/yaml")
        this.body = yaml.stringify(this.body)
    } else { // json
        this.set("Content-Type","application/json")
        this.body = JSON.stringify(this.body)
    }
})
// MongoDB Logger
app.use(function* (next){
    if(this.request.method !== "POST") return yield next;
    var log = new models.logs();
    log.ipaddr = this.request.header['x-forwarded-for'] || this.socket.remoteAddress;
    log.path = this.path;
    yield next;
    log.response = JSON.stringify(this.body);
    yield log.save();
})
// REST APIのrouter
var routes = require("./routes")
routes.rest.forEach(function(route){
    var login = true;
    if(route.login !== undefined) login = route.login;
    var method = route.method;
    var path = route.name;
    var authFunc = tokenAuth(route,login)
    var checkSuspended = function* (next){
        if(this.request.method == "POST" && login && this.token.user.isSuspended){
            this.status_code = 403
            this.body = {result:false,error:"this-user-is-suspended"}
            return
        }
        yield next;
    }
    app.use(_[method](path,authFunc));
    if(login) app.use(_[method](path,checkSuspended))
    // if(route.file)
    app.use(_[method](path,require("./handlers/web"+path)))
})
// WebSocket APIのrouter
var ws_route = {};
routes.websocket.forEach(function(route){
    var login = true;
    if(route.login !== undefined) login = route.login;
    var path = route.name;
    ws_route[path] = route;
    ws_route[path]["login"] = login;
    ws_route[path]["callback"] = require("./handlers/ws"+path)
})
wss.on("connection",function(ws){
    var location = url_module.parse(ws.upgradeReq.url,true);
    var url = location.pathname;
    ws.sendJSON = function(json){
        ws.send(JSON.stringify(json))
    }
    if(!ws_route[url]){
        ws.sendJSON({result:false,error:"api-not-found"})
        ws.close();
        return
    }
    if(ws_route[url].login){
        if(location.query.access_token){
            models.access_tokens.findOne({
                secret:location.query.access_token
            }).populate("app user").then(function(token){
                if(token){
                    ws.token=token;
                    ws_route[url].callback(ws);
                } else {
                    ws.sendJSON({result:false,error:"please-auth"})
                    ws.close()
                    return
                }
            },function(){
                ws.send(JSON.strigify({response:false,error:"server-side-auth-error"}))
                ws.close()
                return
            })
        } else {
            ws.sendJSON({result:false,error:"please-auth"})
            ws.close()
            return
        }
    } else {
        ws_route[url].callback(ws);
    }
})
app.use(function *(){
    this.status_code = 404;
    this.body = {result:false,error:"not-found"}
})
app.on("error",function(err){
    console.log(err)
    this.body = {result:false,error:"server-side-error"}
})
server.on("request",app.callback());
server.listen(4005,function(){
    console.log("listen for "+server.address().port+" port");
})<|endoftext|>


<commit_before>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import store from './store'

import {moment, momentWithYear} from './filter/index'

import 'element-ui/lib/theme-default/index.css'
import 'normalize.css'
import '@/../static/icon/iconfont'
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap/dist/js/bootstrap.min'

Vue.config.productionTip = false
Vue.use(ElementUI)

Vue.filter('moment', moment)
Vue.filter('momentWithYear', momentWithYear)
/* eslint-disable no-new */
const app = new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})
export default app
<commit_msg>markdown directive<commit_after>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import store from './store'

import {moment, momentWithYear} from './filter/index'

import 'element-ui/lib/theme-default/index.css'
import 'normalize.css'
import '@/../static/icon/iconfont'
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap/dist/js/bootstrap.min'
import hljs from 'highlight.js'
import 'highlight.js/styles/default.css' // 样式文件

Vue.config.productionTip = false
Vue.use(ElementUI)

Vue.filter('moment', moment)
Vue.filter('momentWithYear', momentWithYear)

Vue.directive('highlight', function (el) {
  let blocks = el.querySelectorAll('pre code')
  blocks.forEach((block) => {
    hljs.highlightBlock(block)
  })
})

/* eslint-disable no-new */
const app = new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})
export default app
<|endoftext|>


<commit_before>import Vue from 'vue'
import App from './App'
import router from './router'
import './registerServiceWorker'

// vue-firestore
import VueFirestore from 'vue-firestore'
Vue.use(VueFirestore)

// vue-notification
import Notifications from 'vue-notification'
Vue.use(Notifications)

// ionicons
Vue.config.ignoredElements = [/^ion-/]

// vue-sortable
import Sortable from 'sortablejs'
Vue.directive('sortable', {
	inserted: function (el, binding) {
		new Sortable(el, binding.value || {})
	}
})

// vue-clipboard2
import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)

// vue-i18n
import VueI18n from 'vue-i18n'
import messages from './translations'
Vue.use(VueI18n)
let lang = navigator.language.slice(0, 2)
const i18n = new VueI18n({
  locale: ['en', 'de'].indexOf(lang) > -1 ? lang : 'en', // set locale
  messages, // set locale messages
})

// initialize Chart.js with global configuration
import Chart from 'chart.js'
Chart.defaults.global.defaultFontColor = "#7e8d97"
Chart.defaults.global.elements.arc.borderWidth = 0
Chart.defaults.global.legend.display = false
Chart.defaults.global.hover.mode = 'index'
Chart.defaults.global.tooltips.mode = 'index'
Chart.defaults.global.tooltips.intersect = false
Chart.defaults.global.tooltips.multiKeyBackground = '#000'
Chart.defaults.global.tooltips.titleMarginBottom = 10
Chart.defaults.global.tooltips.xPadding = 10
Chart.defaults.global.tooltips.yPadding = 10
Chart.defaults.global.tooltips.cornerRadius = 2

// vue configuration
Vue.config.productionTip = false

// global mixins
let isChordLine = (line) => {
	if (line.trim() == '') return false
	return line.slice(-2) === '  '
}
let keyScale = () => ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'B', 'H']

Vue.mixin({
  methods: {
		// scale to use for song tuning and transponation
		keyScale: keyScale,
		// temporary song language list - shall be managed by admins in future
		songLanguages: () => ({
			de: 'Deutsch',
			en: 'English',
			fr: 'Français',
			li: 'Lingala',
		}),
		/*
			user roles and permissions: Reader, Performer, Editor and Administrator
			RPEA
			XXXX see dashboard, song list and setlist list
			XXXX open single songs (present, tune, export)
			XXXX open single setlists (present, copy, export)
			-XXX create and edit setlists
			-XXX custom tuning in setlists
			-XXX sync setlists
			--XX create and edit songs
			--XX delete songs and setlists
			---X create, edit and delete tags
			---X create, edit and delete users
		*/
		userRoles: () => ({
			reader: 1,
			performer: 2,
			editor: 3,
			admin: 4,
		}),
		// identify chord lines
		isChordLine: isChordLine,
		// parse song content syntax
		parsedContent: (content, tuning, showChords, twoColumns) => {
			// initialize arrays for parsed lines, classes of parts, type abbr., numbers of type and part index
			var parsed = [], classes = [], types = [], numbers = [], part = 0
			var lines = content.split('\n')
			// check every single line of song content
			for (var i = 0; i < lines.length; i++) {
				var line = lines[i]
				// handle display chord lines
				if (isChordLine(line) && !showChords) {
					// skip chord line if no chords shall be displayed
					continue
				}
				// handle chord tuning
				if (isChordLine(line) && tuning != 0) {
					// init the new line to build and the current over- or underflow of spaces due to different chord string lenghts
					var newLine = '', spaces = 0, j = 0
					while (j < line.length) {
						// get single character in line
						var c = line[j]
						// handle over- or underflow of spaces to keep chords on their original position
						if (spaces > 0 && c == ' ') {
							// to few spaces: double next existing space and decrease space count
							c = '  '
							spaces--
						}
						if (spaces < 0 && c == ' ' && line[j+1] == ' ') {
							// to many spaces: skip one of two consecutive spaces and increase space count
							spaces++
							j++
							continue
						}
						// on '#': skip to next character as it will be handled together with tune
						if (c == '#') {
							j++
							continue
						}
						var isHalf = line[j+1] == '#'
						// check if character is a tune with '#'
						if (isHalf) {
							c = c + '#'
						}
						// check if character is a transposable character
						if (keyScale().indexOf(c) > -1) {
							// replace character by next tune character
							var nextTune = keyScale()[(12 + keyScale().indexOf(c) + (tuning % 12)) % 12]
							newLine += nextTune
							// update over- or underflow of spaces
							spaces += c.length - nextTune.length
						} else {
							newLine += c
						}
						j++
					}
					// make sure that last two characters stay spaces for chord line identification (rtrim and add 2 spaces)
					newLine = newLine.replace(/\s+$/, '') + '  '
					// add lines to new content
					if (!parsed[part]) {
						parsed[part] = []
					}
					parsed[part].push(newLine)
					continue
				}
				// handle normal song line
				if (line.trim().indexOf('--') < 0) {
					// only consider line if not empty
					if (line.trim() != '') {
						if (!parsed[part]) {
							parsed[part] = []
						}
						// add line to current part
						parsed[part].push(line)
					}
				}
				// handle song part marker (e.g. --V1)
				else {
					// add class to part
					switch (line.charAt(2).toLowerCase()) {
						case 'v':
							types.push('v')
							classes.push('verse ' + ((!isNaN(parseInt(line.trim().charAt(3)))) ? 'part' + line.trim().charAt(3) : ''))
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						case 'p':
							types.push('p')
							classes.push('prechorus')
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						case 'c':
							types.push('c')
							classes.push('chorus')
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						case 'b':
							types.push('b')
							classes.push('bridge')
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						case 'i':
							types.push('i')
							classes.push('intro')
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						case 'm':
							types.push('m')
							classes.push('mitro')
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						case 'o':
							types.push('o')
							classes.push('outro')
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						default:
							// a non existent part tag was found
					}
					// consider next part
					part++
				}
			}
			var newContent = []
			// if multiple parts: rejoin lines of every part
			if (parsed.length > 1) {
				for (var p = 1; p < parsed.length; p++) {
					newContent.push({
						type: types[p-1],
						number: numbers[p-1],
						class: classes[p-1],
						content: parsed[p].join('\n')
					})
				}
			}
			// if no parts (no markers set): take whole content as one unclassified part
			else {
				newContent.push({
					type: '',
					number: 0,
					class: '',
					content: content
				})
			}
			if (twoColumns) {
				// split content into two columns and return
				let half = Math.ceil(newContent.length / 2)
				return [newContent.slice(0, half), newContent.slice(half, newContent.length)]
			} else {
				return newContent
			}
		},
		// file download
		download: (data, filename) => {
			var a = document.createElement('a')
			var file = new Blob([data], { type:'text/plain;charset=UTF-8' })
			// IE10+
			if (window.navigator.msSaveOrOpenBlob) {
				window.navigator.msSaveOrOpenBlob(file, filename)
			}
			// other browsers
			else {
				var url = URL.createObjectURL(file)
				a.href = url
				a.download = filename
				document.body.appendChild(a)
				a.click()
				setTimeout(function() {
					document.body.removeChild(a)
					window.URL.revokeObjectURL(url)
				}, 0)
			}
		},
		// format human readable date
		humanDate: (d, locale) => {
			if (!d) return ''
			let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }
			return (new Date(d)).toLocaleDateString(locale + '-' + locale.toUpperCase(), options)
		}
  }
})

// extend Object for filtering
Object.filter = (obj, predicate) =>
	Object.keys(obj)
		.filter( key => predicate(obj[key]) )
		.reduce( (res, key) => (res[key] = obj[key], res), {} );

new Vue({
	router,
	i18n,
	render: h => h(App)
}).$mount('#app')
<commit_msg>➕ implement db from environment as global property<commit_after>import Vue from 'vue'
import App from './App'
import router from './router'
import './registerServiceWorker'

// set firebase db config
let firebase = require("firebase/app")
const conf = {
	apiKey: String(process.env.VUE_APP_FB_API_KEY),
	authDomain: process.env.VUE_APP_FB_PROJECT_ID + ".firebaseapp.com",
	databaseURL: "https://" + process.env.VUE_APP_FB_PROJECT_ID + ".firebaseio.com",
	projectId: String(process.env.VUE_APP_FB_PROJECT_ID),
	storageBucket: process.env.VUE_APP_FB_PROJECT_ID + ".appspot.com"
}
let firebaseApp = firebase.initializeApp(conf)

// set global properties
Vue.prototype.$db = firebaseApp.firestore()

// set local config
Vue.config.productionTip = false
Vue.config.ignoredElements = [/^ion-/]

// vue-firestore
import VueFirestore from 'vue-firestore'
Vue.use(VueFirestore)

// vue-notification
import Notifications from 'vue-notification'
Vue.use(Notifications)

// vue-sortable
import Sortable from 'sortablejs'
Vue.directive('sortable', {
	inserted: function (el, binding) {
		new Sortable(el, binding.value || {})
	}
})

// vue-clipboard2
import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)

// vue-i18n
import VueI18n from 'vue-i18n'
import messages from './translations'
Vue.use(VueI18n)
let lang = navigator.language.slice(0, 2)
const i18n = new VueI18n({
  locale: ['en', 'de'].indexOf(lang) > -1 ? lang : 'en', // set locale
  messages, // set locale messages
})

// initialize Chart.js with global configuration
import Chart from 'chart.js'
Chart.defaults.global.defaultFontColor = "#7e8d97"
Chart.defaults.global.elements.arc.borderWidth = 0
Chart.defaults.global.legend.display = false
Chart.defaults.global.hover.mode = 'index'
Chart.defaults.global.tooltips.mode = 'index'
Chart.defaults.global.tooltips.intersect = false
Chart.defaults.global.tooltips.multiKeyBackground = '#000'
Chart.defaults.global.tooltips.titleMarginBottom = 10
Chart.defaults.global.tooltips.xPadding = 10
Chart.defaults.global.tooltips.yPadding = 10
Chart.defaults.global.tooltips.cornerRadius = 2

// global mixins
let isChordLine = (line) => {
	if (line.trim() == '') return false
	return line.slice(-2) === '  '
}
let keyScale = () => ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'B', 'H']

Vue.mixin({
  methods: {
		// scale to use for song tuning and transponation
		keyScale: keyScale,
		// temporary song language list - shall be managed by admins in future
		songLanguages: () => ({
			de: 'Deutsch',
			en: 'English',
			fr: 'Français',
			li: 'Lingala',
		}),
		/*
			user roles and permissions: Reader, Performer, Editor and Administrator
			RPEA
			XXXX see dashboard, song list and setlist list
			XXXX open single songs (present, tune, export)
			XXXX open single setlists (present, copy, export)
			-XXX create and edit setlists
			-XXX custom tuning in setlists
			-XXX sync setlists
			--XX create and edit songs
			--XX delete songs and setlists
			---X create, edit and delete tags
			---X create, edit and delete users
		*/
		userRoles: () => ({
			reader: 1,
			performer: 2,
			editor: 3,
			admin: 4,
		}),
		// identify chord lines
		isChordLine: isChordLine,
		// parse song content syntax
		parsedContent: (content, tuning, showChords, twoColumns) => {
			// initialize arrays for parsed lines, classes of parts, type abbr., numbers of type and part index
			var parsed = [], classes = [], types = [], numbers = [], part = 0
			var lines = content.split('\n')
			// check every single line of song content
			for (var i = 0; i < lines.length; i++) {
				var line = lines[i]
				// handle display chord lines
				if (isChordLine(line) && !showChords) {
					// skip chord line if no chords shall be displayed
					continue
				}
				// handle chord tuning
				if (isChordLine(line) && tuning != 0) {
					// init the new line to build and the current over- or underflow of spaces due to different chord string lenghts
					var newLine = '', spaces = 0, j = 0
					while (j < line.length) {
						// get single character in line
						var c = line[j]
						// handle over- or underflow of spaces to keep chords on their original position
						if (spaces > 0 && c == ' ') {
							// to few spaces: double next existing space and decrease space count
							c = '  '
							spaces--
						}
						if (spaces < 0 && c == ' ' && line[j+1] == ' ') {
							// to many spaces: skip one of two consecutive spaces and increase space count
							spaces++
							j++
							continue
						}
						// on '#': skip to next character as it will be handled together with tune
						if (c == '#') {
							j++
							continue
						}
						var isHalf = line[j+1] == '#'
						// check if character is a tune with '#'
						if (isHalf) {
							c = c + '#'
						}
						// check if character is a transposable character
						if (keyScale().indexOf(c) > -1) {
							// replace character by next tune character
							var nextTune = keyScale()[(12 + keyScale().indexOf(c) + (tuning % 12)) % 12]
							newLine += nextTune
							// update over- or underflow of spaces
							spaces += c.length - nextTune.length
						} else {
							newLine += c
						}
						j++
					}
					// make sure that last two characters stay spaces for chord line identification (rtrim and add 2 spaces)
					newLine = newLine.replace(/\s+$/, '') + '  '
					// add lines to new content
					if (!parsed[part]) {
						parsed[part] = []
					}
					parsed[part].push(newLine)
					continue
				}
				// handle normal song line
				if (line.trim().indexOf('--') < 0) {
					// only consider line if not empty
					if (line.trim() != '') {
						if (!parsed[part]) {
							parsed[part] = []
						}
						// add line to current part
						parsed[part].push(line)
					}
				}
				// handle song part marker (e.g. --V1)
				else {
					// add class to part
					switch (line.charAt(2).toLowerCase()) {
						case 'v':
							types.push('v')
							classes.push('verse ' + ((!isNaN(parseInt(line.trim().charAt(3)))) ? 'part' + line.trim().charAt(3) : ''))
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						case 'p':
							types.push('p')
							classes.push('prechorus')
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						case 'c':
							types.push('c')
							classes.push('chorus')
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						case 'b':
							types.push('b')
							classes.push('bridge')
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						case 'i':
							types.push('i')
							classes.push('intro')
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						case 'm':
							types.push('m')
							classes.push('mitro')
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						case 'o':
							types.push('o')
							classes.push('outro')
							numbers.push((!isNaN(parseInt(line.trim().charAt(3)))) ? line.trim().charAt(3) : '0'); break
						default:
							// a non existent part tag was found
					}
					// consider next part
					part++
				}
			}
			var newContent = []
			// if multiple parts: rejoin lines of every part
			if (parsed.length > 1) {
				for (var p = 1; p < parsed.length; p++) {
					newContent.push({
						type: types[p-1],
						number: numbers[p-1],
						class: classes[p-1],
						content: parsed[p].join('\n')
					})
				}
			}
			// if no parts (no markers set): take whole content as one unclassified part
			else {
				newContent.push({
					type: '',
					number: 0,
					class: '',
					content: content
				})
			}
			if (twoColumns) {
				// split content into two columns and return
				let half = Math.ceil(newContent.length / 2)
				return [newContent.slice(0, half), newContent.slice(half, newContent.length)]
			} else {
				return newContent
			}
		},
		// file download
		download: (data, filename) => {
			var a = document.createElement('a')
			var file = new Blob([data], { type:'text/plain;charset=UTF-8' })
			// IE10+
			if (window.navigator.msSaveOrOpenBlob) {
				window.navigator.msSaveOrOpenBlob(file, filename)
			}
			// other browsers
			else {
				var url = URL.createObjectURL(file)
				a.href = url
				a.download = filename
				document.body.appendChild(a)
				a.click()
				setTimeout(function() {
					document.body.removeChild(a)
					window.URL.revokeObjectURL(url)
				}, 0)
			}
		},
		// format human readable date
		humanDate: (d, locale) => {
			if (!d) return ''
			let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }
			return (new Date(d)).toLocaleDateString(locale + '-' + locale.toUpperCase(), options)
		}
  }
})

// extend Object for filtering
Object.filter = (obj, predicate) =>
	Object.keys(obj)
		.filter( key => predicate(obj[key]) )
		.reduce( (res, key) => (res[key] = obj[key], res), {} );

new Vue({
	router,
	i18n,
	render: h => h(App)
}).$mount('#app')
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/* global _playground */

define(function (require, exports) {
    "use strict";

    /**
     * Version of the Playground adapter plugin API.
     * Follows Semver 2.0.0 conventions: http://semver.org/spec/v2.0.0.html
     *
     * @const
     * @type {string}
     */
    Object.defineProperty(exports, "version", {
        enumerable: true,
        value: _playground.version
    });
});
<commit_msg>Expose the _playground.abort function.<commit_after>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/* global _playground */

define(function (require, exports) {
    "use strict";

    var Promise = require("bluebird");

    Object.defineProperties(exports, {
        /**
         * Version of the Playground adapter plugin API.
         * Follows Semver 2.0.0 conventions: http://semver.org/spec/v2.0.0.html
         *
         * @const
         * @type {string}
         */
        "version": {
            enumerable: true,
            value: _playground.version
        },

        /**
         * Abort the current application and return control to Classic Photoshop.
         * If a message is supplied, Classic Photoshop may display it to the user,
         * e.g., in a dialog.
         *
         * @param {{message: string=}}
         * @return {Promise}
         */
        "abort": {
            enumerable: true,
            value: Promise.promisify(_playground.abort)
        }
    });

});
<|endoftext|>