<commit_before>// regeneratorRuntime is needed for async await
import 'babel-polyfill'

import { getRandomId } from './utils/functions'
import program from './utils/program'

const mainMethods = [
  'build',
  'configure',
  'connect',
  'console',
  'check',
  'create',
  'deploy',
  'dump',
  'exec',
  'get',
  'init',
  'install',
  'map',
  'push',
  'read',
  'replace',
  'run',
  'set',
  'start',
  'write'
]
const subModules = mainMethods.map(method => require(`./methods/${method}`))
const collectionNames = ['servers', 'types']

class Teleport {
  constructor (extraProgram) {
    // welcome
    console.log('\n\n** Welcome to teleport node-side ! **\n'.bold)
    // bind methods from sub modules
    subModules.forEach(module =>
      Object.keys(module).forEach(key => {
        this[key] = module[key].bind(this)
      })
    )
    // bind program
    this.program = Object.assign({}, program, extraProgram)
    const app = this.app = {}
    this.setAppEnvironment()
    // level is saying
    // if you are actually working in a project, the app itself,
    // or in somewhere not defined yet
    this.level = null
    const project = this.project = {}
    // determine where we are
    this.currentDir = this.program.dir || process.cwd()
    // if we want to create something, then we return because we are not in a project yet
    if (typeof this.program.create !== 'undefined') {
      // in the case where no project name was given, we need to invent one based on a uniq ID
      if (typeof this.program.name !== 'string') {
        this.consoleWarn('You didn\'t mention any particular name, we are going to give you one')
        this.program.name = `app-${getRandomId()}`
      }
      this.level = 'project'
      return
    }
    // if it is not a create method, it means that we are either in a scope or in a
    // project to do something
    this.currentConfig = this.getConfig(this.currentDir)
    // split given where we are
    if (this.currentConfig || typeof this.program.init !== 'undefined') {
      this.level = 'project'
      project.dir = this.currentDir
      this.setProjectEnvironment()
    }
    // exit else
    if (!this.level) {
      this.consoleWarn('You are not in a project folder')
      process.exit()
    }
  }

  launch () {
    // unpack
    const { program } = this
    // we can pass args to the cli, either object, or direct values or nothing
    this.kwarg = null
    if (typeof program.kwarg === 'string') {
      this.kwarg = program.kwarg[0] === '{'
      ? JSON.parse(program.kwarg)
      : program.kwarg
    }
    // it is maybe a call of a main mainMethods
    const programmedMethod = mainMethods.find(method => program[method])
    if (this[programmedMethod]) {
      // check for mapping ? let's see if there is already a collections of arg defined
      if (typeof program.collections === 'undefined') {
        // so there is no clear mapping to collections
        // but maybe there are some pluralized args
        // suggesting that the method has to be done
        // with a map protocol
        const collectionSlugs = []
        collectionNames.forEach(collectionName => {
          const value = program[collectionName]
          if (typeof value === 'string') {
            if (value === 'all') {
              collectionSlugs.push(`${collectionName}ByName`)
            } else {
              collectionSlugs.push(`${collectionName}ByName[${value}]`)
            }
          }
        })
        const collections = collectionSlugs.join(',')
        // if collections is not empty, so yes, it is mapping
        // method request, do it and return in that case
        if (collections !== '') {
          program.collections = collections
          program.method = programmedMethod
          this.map()
          return
        }
      }
      // if no collection, it is a simple unit call
      // call it
      return this[programmedMethod]()
    }
    // default return
    this.consoleWarn('Welcome to teleport... But you didn\'t specify any particular command !')
  }

  pass () {}
}

export default Teleport
<commit_msg>added a warning if there is no python venv<commit_after>// regeneratorRuntime is needed for async await
import 'babel-polyfill'

import { getRandomId } from './utils/functions'
import program from './utils/program'

const mainMethods = [
  'build',
  'configure',
  'connect',
  'console',
  'check',
  'create',
  'deploy',
  'dump',
  'exec',
  'get',
  'init',
  'install',
  'map',
  'push',
  'read',
  'replace',
  'run',
  'set',
  'start',
  'write'
]
const subModules = mainMethods.map(method => require(`./methods/${method}`))
const collectionNames = ['servers', 'types']

class Teleport {
  constructor (extraProgram) {
    // welcome
    console.log('\n\n** Welcome to teleport node-side ! **\n'.bold)
    // bind methods from sub modules
    subModules.forEach(module =>
      Object.keys(module).forEach(key => {
        this[key] = module[key].bind(this)
      })
    )
    // bind program
    this.program = Object.assign({}, program, extraProgram)
    const app = this.app = {}
    this.setAppEnvironment()
    // check for a python venv
    if (!app.venvDir) {
      const warn = 'You did not defined a virtualenv... This may be not good for the pip install time'
      this.consoleWarn(warn.toUpperCase())
    }
    // level is saying
    // if you are actually working in a project, the app itself,
    // or in somewhere not defined yet
    this.level = null
    const project = this.project = {}
    // determine where we are
    this.currentDir = this.program.dir || process.cwd()
    // if we want to create something, then we return because we are not in a project yet
    if (typeof this.program.create !== 'undefined') {
      // in the case where no project name was given, we need to invent one based on a uniq ID
      if (typeof this.program.name !== 'string') {
        this.consoleWarn('You didn\'t mention any particular name, we are going to give you one')
        this.program.name = `app-${getRandomId()}`
      }
      this.level = 'project'
      return
    }
    // if it is not a create method, it means that we are either in a scope or in a
    // project to do something
    this.currentConfig = this.getConfig(this.currentDir)
    // split given where we are
    if (this.currentConfig || typeof this.program.init !== 'undefined') {
      this.level = 'project'
      project.dir = this.currentDir
      this.setProjectEnvironment()
    }
    // exit else
    if (!this.level) {
      this.consoleWarn('You are not in a project folder')
      process.exit()
    }
  }

  launch () {
    // unpack
    const { program } = this
    // we can pass args to the cli, either object, or direct values or nothing
    this.kwarg = null
    if (typeof program.kwarg === 'string') {
      this.kwarg = program.kwarg[0] === '{'
      ? JSON.parse(program.kwarg)
      : program.kwarg
    }
    // it is maybe a call of a main mainMethods
    const programmedMethod = mainMethods.find(method => program[method])
    if (this[programmedMethod]) {
      // check for mapping ? let's see if there is already a collections of arg defined
      if (typeof program.collections === 'undefined') {
        // so there is no clear mapping to collections
        // but maybe there are some pluralized args
        // suggesting that the method has to be done
        // with a map protocol
        const collectionSlugs = []
        collectionNames.forEach(collectionName => {
          const value = program[collectionName]
          if (typeof value === 'string') {
            if (value === 'all') {
              collectionSlugs.push(`${collectionName}ByName`)
            } else {
              collectionSlugs.push(`${collectionName}ByName[${value}]`)
            }
          }
        })
        const collections = collectionSlugs.join(',')
        // if collections is not empty, so yes, it is mapping
        // method request, do it and return in that case
        if (collections !== '') {
          program.collections = collections
          program.method = programmedMethod
          this.map()
          return
        }
      }
      // if no collection, it is a simple unit call
      // call it
      return this[programmedMethod]()
    }
    // default return
    this.consoleWarn('Welcome to teleport... But you didn\'t specify any particular command !')
  }

  pass () {}
}

export default Teleport
<|endoftext|>


<commit_before>'use strict';

function platform_init(){
}

var platform_players = {};
<commit_msg>added platform_player_reset() and platform_score_goal<commit_after>'use strict';

function platform_init(){
}

// Required args: player
// Optional args: all
function platform_player_reset(args){
    args = core_args({
      'args': args,
      'defaults': {
        'all': false,
      },
    });

    if(args['all']){
        platform_players[args['player']] = {};
    }

    platform_players[args['player']] = core_handle_defaults({
      'default': {
        'coins': 0,
        'lives': 1,
        'x': 0,
        'y': 0,
        'y-velocity': 0,
      },
      'var': platform_players[args['player']],
    });
}

var platform_players = {};
var platform_score_goal = 1;
<|endoftext|>


<commit_before>/**
 * Philip Crotwell
 * University of South Carolina, 2016
 * http://www.seis.sc.edu
 */

import * as distaz from 'seisplotjs-distaz';
import * as fdsnevent from 'seisplotjs-fdsnevent';
import * as fdsnstation from 'seisplotjs-fdsnstation';
import * as fdsndataselect from 'seisplotjs-fdsndataselect';
import * as miniseed from 'seisplotjs-miniseed';
import * as seedcodec from 'seisplotjs-seedcodec';
import * as seedlink from 'seisplotjs-seedlink';
import * as traveltime from 'seisplotjs-traveltime';
import * as waveformplot from 'seisplotjs-waveformplot';
let d3 = waveformplot.d3;

/* reexport */
export { distaz,
         fdsnevent,
         fdsnstation,
         fdsndataselect,
         seedcodec,
         miniseed,
         seedlink,
         traveltime,
         waveformplot,
         d3 };

<commit_msg>better lint of example, add filter<commit_after>/**
 * Philip Crotwell
 * University of South Carolina, 2016
 * http://www.seis.sc.edu
 */

import * as distaz from 'seisplotjs-distaz';
import * as fdsnevent from 'seisplotjs-fdsnevent';
import * as fdsnstation from 'seisplotjs-fdsnstation';
import * as fdsndataselect from 'seisplotjs-fdsndataselect';
import * as filter from 'seisplotjs-filter';
import * as miniseed from 'seisplotjs-miniseed';
import * as seedcodec from 'seisplotjs-seedcodec';
import * as seedlink from 'seisplotjs-seedlink';
import * as traveltime from 'seisplotjs-traveltime';
import * as waveformplot from 'seisplotjs-waveformplot';
let d3 = waveformplot.d3;

/* reexport */
export { distaz,
         fdsnevent,
         fdsnstation,
         fdsndataselect,
         filter,
         seedcodec,
         miniseed,
         seedlink,
         traveltime,
         waveformplot,
         d3 };

<|endoftext|>


<commit_before>function Playlist() {
    var self = this;
    // Change in local playlist should be pushed into server.
    self.playlist = [];
    self.renderPlaylistRow = function(music, idx){
        if (!music.id)
            return "";
        if (!self.rowTemplate)
            self.rowTemplate =
                _.template($(playlistManager.elems.playlistRowTemplate).html());
        return self.rowTemplate({music:music, idx:idx});
    };
    self.init = function(params) {
        // `params` should be Array of music.
        if (params instanceof Array) {
            self.playlist = self.playlist.concat(params);
        }
    };

    self.getWithIdx = function(idx) {
        if (idx < self.playlist.length) {
            return self.playlist[idx];
        }
    };

    self.add = function(music, updateView) {
        var idx = self.findIdx(music.id);
        if (idx !== -1) {
            // Already exists
            return false;
        }
        self.playlist.push(music);
        if (updateView) {
            self.toTable(true);
            var elems = playlistManager.elems;
            $(elems.playlist).stop();
            $(elems.playlist).animate({
                scrollTop: 100 * self.length()
            }, '1000');
        }

        if (playlistManager.playingLocalSeq === PlaylistTabs.currentIdx()) {
            musicQ.push(music);
        }
        return true;
    };

    self.remove = function(music, updateView) {
        var idx = self.findIdx(music.id);
        if (idx > -1) {
            self.playlist.splice(idx, 1);
        }
        if (updateView) {
            self.toTable(true);
        }

        if (playlistManager.playingLocalSeq === PlaylistTabs.currentIdx()) {

            musicQ.removeWithId(music.id);
        }

    };

    self.slicePlaylist = function(musicId) {
        // find idx
        var idx = self.findIdx(musicId);
        return self.playlist.slice(idx+1);
    };

    self.findIdx = function(musicId) {
        var idx = -1;
        for (var i=0; i<self.playlist.length; i++) {
            if (self.playlist[i].id === musicId) {
                idx = i;
            }
        }
        return idx;
    };

    self.sync = function() {
        // We don't sync if we are on shared Playlist!
        if (onSharedList) {
            return;
        }
        self.localSync();
    };

    self.localSync = function() {
        // Sync all local playlists.
        var idx = PlaylistTabs.currentIdx();
        LocalStorage.setPlaylist(JSON.stringify(self.playlist), idx);
    };

    // Sync this playlist with server.
    self.remoteSync = function() {
    };

    self.toTable = function(clean) {
        // Convertes `Playlist` to Table in HTML.
        // var table = document.creatElement('table'); doesn't work.

        var playlistView = $(playlistManager.elems.playlistInner);

        if (clean) {
            var playlistRow =
                $(playlistManager.elems.playlistMusicContainer, playlistView);
            playlistRow.remove();
        }
        for (var i=0; i<self.playlist.length; i++) {
            playlistView.append(self.renderPlaylistRow(self.playlist[i], i+1));
        }
        ViewControl.resizePlaylistRow();
        $(playlistManager.elems.playlistMusicCount).text(self.playlist.length);

        // Is bold needed for filter?

        // Re-bold current music if playing.
        if (playerManager.currentMusic
            && playlistManager.playingLocalSeq === PlaylistTabs.currentIdx()) {
            var title = playerManager.currentMusic.title;
            boldPlaylistTitle(title);
        }
    };

    self.raw = function() {
        return self.playlist;
    };

    self.toJsonStr = function(reverse_quote) {
        for (var i=0; i<self.playlist.length; i++) {
            m = self.playlist[i];
            if (reverse_quote) {
                m.title = m.title.replace(/'/g, "`");
                m.title = m.title.replace(/"/g, "`");
            } else {
                m.title = m.title.replace(/`/g, "'");
            }
        }
        raw = JSON.stringify(self.playlist);
        return raw;
    };

    self.clear = function(updateView) {
        self.playlist = []
        if (updateView) {
            self.toTable(true);
        }
    };

    self.length = function() {
        return self.playlist.length;
    };

    self.empty = function() {
        return self.length() === 0;
    };
}

function boldPlaylistTitle (title) {
    // XXX: Should bold with `id` (not `title`) later.
    var $rows = $('.playlist-section .playlist .a-playlist-music');
    $.each($rows, function(idx) {
        if ($(".music-title", $(this)).text() === title) {
            $(this).addClass("on");
        }
    });
}

function unboldPlaylistTitle() {
    var $rows = $('.playlist-section .playlist .a-playlist-music');
    $rows.removeClass("on");
}

function initialPlaylistToNewComer() {
    // Returns initial playlist containing 5 tracks.
    // XXX: Why initial playlist is in js? Should move them to our database.

    var initial = [];
    m = new Music(
        {
            'id':'rLMas3USFbA',
            'title':'Bassjackers - Mush Mush (Original Mix)',
            'type':'youtube'
        }
    );
    initial.push(m);
    m = new Music(
        {
            'id':'id5NQwWX5zM',
            'title':'Dominik Eulberg - Opel Tantra (Original Mix)',
            'type':'youtube'
        }
    );
    initial.push(m);

    m = new Music(
        {
            'id':'82523324',
            'title':'Alesso Vs OneRepublic - If I Lose Myself (Alesso Remix)',
            'type':'soundcloud'
        }
    );
    initial.push(m);

    m = new Music(
        {
            'id':'5RcSht6kiQw',
            'title':'Julian Jeweil - Techno Corner (Original Mix)',
            'type':'youtube'
        }
    );
    initial.push(m);

    m = new Music(
        {
            'id':'uaY81jB93S8',
            'title':'Nicky Romero, Sunnery James & Ryan Marciano' +
            '- Jack To The Sound Of The Underground (Original Mix)',
            'type':'youtube'
        }
    );
    initial.push(m);

    m = new Music(
        {
            'id':'V9BJSixyqcQ',
            'title':'Julian Calor - Storm [OUT NOW!]',
            'type':'youtube'
        }
    );
    initial.push(m);

    var initialPlaylist = new Playlist();
    initialPlaylist.init(initial);
    initialPlaylist.sync();
}
<commit_msg>removed broken initial music<commit_after>function Playlist() {
    var self = this;
    // Change in local playlist should be pushed into server.
    self.playlist = [];
    self.renderPlaylistRow = function(music, idx){
        if (!music.id)
            return "";
        if (!self.rowTemplate)
            self.rowTemplate =
                _.template($(playlistManager.elems.playlistRowTemplate).html());
        return self.rowTemplate({music:music, idx:idx});
    };
    self.init = function(params) {
        // `params` should be Array of music.
        if (params instanceof Array) {
            self.playlist = self.playlist.concat(params);
        }
    };

    self.getWithIdx = function(idx) {
        if (idx < self.playlist.length) {
            return self.playlist[idx];
        }
    };

    self.add = function(music, updateView) {
        var idx = self.findIdx(music.id);
        if (idx !== -1) {
            // Already exists
            return false;
        }
        self.playlist.push(music);
        if (updateView) {
            self.toTable(true);
            var elems = playlistManager.elems;
            $(elems.playlist).stop();
            $(elems.playlist).animate({
                scrollTop: 100 * self.length()
            }, '1000');
        }

        if (playlistManager.playingLocalSeq === PlaylistTabs.currentIdx()) {
            musicQ.push(music);
        }
        return true;
    };

    self.remove = function(music, updateView) {
        var idx = self.findIdx(music.id);
        if (idx > -1) {
            self.playlist.splice(idx, 1);
        }
        if (updateView) {
            self.toTable(true);
        }

        if (playlistManager.playingLocalSeq === PlaylistTabs.currentIdx()) {

            musicQ.removeWithId(music.id);
        }

    };

    self.slicePlaylist = function(musicId) {
        // find idx
        var idx = self.findIdx(musicId);
        return self.playlist.slice(idx+1);
    };

    self.findIdx = function(musicId) {
        var idx = -1;
        for (var i=0; i<self.playlist.length; i++) {
            if (self.playlist[i].id === musicId) {
                idx = i;
            }
        }
        return idx;
    };

    self.sync = function() {
        // We don't sync if we are on shared Playlist!
        if (onSharedList) {
            return;
        }
        self.localSync();
    };

    self.localSync = function() {
        // Sync all local playlists.
        var idx = PlaylistTabs.currentIdx();
        LocalStorage.setPlaylist(JSON.stringify(self.playlist), idx);
    };

    // Sync this playlist with server.
    self.remoteSync = function() {
    };

    self.toTable = function(clean) {
        // Convertes `Playlist` to Table in HTML.
        // var table = document.creatElement('table'); doesn't work.

        var playlistView = $(playlistManager.elems.playlistInner);

        if (clean) {
            var playlistRow =
                $(playlistManager.elems.playlistMusicContainer, playlistView);
            playlistRow.remove();
        }
        for (var i=0; i<self.playlist.length; i++) {
            playlistView.append(self.renderPlaylistRow(self.playlist[i], i+1));
        }
        ViewControl.resizePlaylistRow();
        $(playlistManager.elems.playlistMusicCount).text(self.playlist.length);

        // Is bold needed for filter?

        // Re-bold current music if playing.
        if (playerManager.currentMusic
            && playlistManager.playingLocalSeq === PlaylistTabs.currentIdx()) {
            var title = playerManager.currentMusic.title;
            boldPlaylistTitle(title);
        }
    };

    self.raw = function() {
        return self.playlist;
    };

    self.toJsonStr = function(reverse_quote) {
        for (var i=0; i<self.playlist.length; i++) {
            m = self.playlist[i];
            if (reverse_quote) {
                m.title = m.title.replace(/'/g, "`");
                m.title = m.title.replace(/"/g, "`");
            } else {
                m.title = m.title.replace(/`/g, "'");
            }
        }
        raw = JSON.stringify(self.playlist);
        return raw;
    };

    self.clear = function(updateView) {
        self.playlist = []
        if (updateView) {
            self.toTable(true);
        }
    };

    self.length = function() {
        return self.playlist.length;
    };

    self.empty = function() {
        return self.length() === 0;
    };
}

function boldPlaylistTitle (title) {
    // XXX: Should bold with `id` (not `title`) later.
    var $rows = $('.playlist-section .playlist .a-playlist-music');
    $.each($rows, function(idx) {
        if ($(".music-title", $(this)).text() === title) {
            $(this).addClass("on");
        }
    });
}

function unboldPlaylistTitle() {
    var $rows = $('.playlist-section .playlist .a-playlist-music');
    $rows.removeClass("on");
}

function initialPlaylistToNewComer() {
    // Returns initial playlist containing 5 tracks.
    // XXX: Why initial playlist is in js? Should move them to our database.

    var initial = [];
    m = new Music(
        {
            'id':'rLMas3USFbA',
            'title':'Bassjackers - Mush Mush (Original Mix)',
            'type':'youtube'
        }
    );
    initial.push(m);

    m = new Music(
        {
            'id':'id5NQwWX5zM',
            'title':'Dominik Eulberg - Opel Tantra (Original Mix)',
            'type':'youtube'
        }
    );
    initial.push(m);

    m = new Music(
        {
            'id':'5RcSht6kiQw',
            'title':'Julian Jeweil - Techno Corner (Original Mix)',
            'type':'youtube'
        }
    );
    initial.push(m);

    m = new Music(
        {
            'id':'uaY81jB93S8',
            'title':'Nicky Romero, Sunnery James & Ryan Marciano' +
            '- Jack To The Sound Of The Underground (Original Mix)',
            'type':'youtube'
        }
    );
    initial.push(m);

    m = new Music(
        {
            'id':'V9BJSixyqcQ',
            'title':'Julian Calor - Storm [OUT NOW!]',
            'type':'youtube'
        }
    );
    initial.push(m);

    var initialPlaylist = new Playlist();
    initialPlaylist.init(initial);
    initialPlaylist.sync();
}
<|endoftext|>


<commit_before>"use strict";

var path = require("path");
var extract = require("./extract");

var htmlExtensions = [
  ".erb",
  ".handelbars",
  ".hbs",
  ".htm",
  ".html",
  ".mustache",
  ".php",
  ".tag",
  ".twig",
  ".vue",
  ".we",
];

var xmlExtensions = [
  ".xhtml",
  ".xml",
];

// Disclaimer:
//
// This is not a long term viable solution. ESLint needs to improve its processor API to
// provide access to the configuration before actually preprocess files, but it's not
// planed yet. This solution is quite ugly but shouldn't alter eslint process.
//
// Related github issues:
// https://github.com/eslint/eslint/issues/3422
// https://github.com/eslint/eslint/issues/4153

var needle = path.join("lib", "eslint.js");
var eslint;
for (var key in require.cache) {
  if (key.indexOf(needle, key.length - needle.length) >= 0) {
    eslint = require(key);
    if (typeof eslint.verify === "function") {
      break;
    }
  }
}

if (!eslint) {
  throw new Error("eslint-plugin-html error: It seems that eslint is not loaded. " +
                  "If you think it is a bug, please file a report at " +
                  "https://github.com/BenoitZugmeyer/eslint-plugin-html/issues");
}

function createProcessor(defaultXMLMode) {
  var verify = eslint.verify;
  var reportBadIndent;

  var currentInfos;

  function patch() {
    eslint.verify = function (textOrSourceCode, config, filenameOrOptions, saveState) {
      var indentDescriptor = config.settings && config.settings["html/indent"];
      var xmlMode = config.settings && config.settings["html/xml-mode"];
      reportBadIndent = config.settings && config.settings["html/report-bad-indent"];

      if (typeof xmlMode !== "boolean") {
        xmlMode = defaultXMLMode;
      }

      currentInfos = extract(textOrSourceCode, {
        indent: indentDescriptor,
        reportBadIndent: Boolean(reportBadIndent),
        xmlMode: xmlMode,
      });
      return verify.call(this, currentInfos.code, config, filenameOrOptions, saveState);
    };
  }

  function unpatch() {
    eslint.verify = verify;
  }
  return {

    preprocess: function (content) {
      patch();
      return [content];
    },

    postprocess: function (messages) {
      unpatch();

      messages[0].forEach(function (message) {
        message.column += currentInfos.map[message.line] || 0;
      });

      currentInfos.badIndentationLines.forEach(function (line) {
        messages[0].push({
          message: "Bad line indentation.",
          line: line,
          column: 1,
          ruleId: "(html plugin)",
          severity: reportBadIndent === true ? 2 : reportBadIndent,
        });
      });

      messages[0].sort(function (ma, mb) {
        return ma.line - mb.line || ma.column - mb.column;
      });

      return messages[0];
    },

  };

}

var htmlProcessor = createProcessor(false);
var xmlProcessor = createProcessor(true);

var processors = {};

htmlExtensions.forEach(function(ext) {
  processors[ext] = htmlProcessor;
});

xmlExtensions.forEach(function(ext) {
  processors[ext] = xmlProcessor;
});

exports.processors = processors;
<commit_msg>fix reference to linter<commit_after>"use strict";

var path = require("path");
var extract = require("./extract");
var linter = require("eslint").linter;

var htmlExtensions = [
  ".erb",
  ".handelbars",
  ".hbs",
  ".htm",
  ".html",
  ".mustache",
  ".php",
  ".tag",
  ".twig",
  ".vue",
  ".we",
];

var xmlExtensions = [
  ".xhtml",
  ".xml",
];

// Disclaimer:
//
// This is not a long term viable solution. ESLint needs to improve its processor API to
// provide access to the configuration before actually preprocess files, but it's not
// planed yet. This solution is quite ugly but shouldn't alter eslint process.
//
// Related github issues:
// https://github.com/eslint/eslint/issues/3422
// https://github.com/eslint/eslint/issues/4153

var needle = path.join("lib", "eslint.js");
var eslint;
for (var key in require.cache) {
  if (key.indexOf(needle, key.length - needle.length) >= 0) {
    eslint = require(key);
    if (typeof eslint.verify === "function") {
      break;
    }
  }
}

if (!eslint) {
  throw new Error("eslint-plugin-html error: It seems that eslint is not loaded. " +
                  "If you think it is a bug, please file a report at " +
                  "https://github.com/BenoitZugmeyer/eslint-plugin-html/issues");
}

function createProcessor(defaultXMLMode) {
  var verify = linter.verify;
  var reportBadIndent;

  var currentInfos;

  function patch() {
    linter.verify = function (textOrSourceCode, config, filenameOrOptions, saveState) {
      var indentDescriptor = config.settings && config.settings["html/indent"];
      var xmlMode = config.settings && config.settings["html/xml-mode"];
      reportBadIndent = config.settings && config.settings["html/report-bad-indent"];

      if (typeof xmlMode !== "boolean") {
        xmlMode = defaultXMLMode;
      }

      currentInfos = extract(textOrSourceCode, {
        indent: indentDescriptor,
        reportBadIndent: Boolean(reportBadIndent),
        xmlMode: xmlMode,
      });
      return verify.call(this, currentInfos.code, config, filenameOrOptions, saveState);
    };
  }

  function unpatch() {
    linter.verify = verify;
  }
  return {

    preprocess: function (content) {
      patch();
      return [content];
    },

    postprocess: function (messages) {
      unpatch();

      messages[0].forEach(function (message) {
        message.column += currentInfos.map[message.line] || 0;
      });

      currentInfos.badIndentationLines.forEach(function (line) {
        messages[0].push({
          message: "Bad line indentation.",
          line: line,
          column: 1,
          ruleId: "(html plugin)",
          severity: reportBadIndent === true ? 2 : reportBadIndent,
        });
      });

      messages[0].sort(function (ma, mb) {
        return ma.line - mb.line || ma.column - mb.column;
      });

      return messages[0];
    },

  };

}

var htmlProcessor = createProcessor(false);
var xmlProcessor = createProcessor(true);

var processors = {};

htmlExtensions.forEach(function(ext) {
  processors[ext] = htmlProcessor;
});

xmlExtensions.forEach(function(ext) {
  processors[ext] = xmlProcessor;
});

exports.processors = processors;
<|endoftext|>


<commit_before>var fs = require('fs');
var express = require('express');
var app = express();

var Canvas = require('canvas');
var Image = Canvas.Image;
var Font = Canvas.Font;

fs.readFile(__dirname + '/images/bg.jpg', function(err, data){
    if (err) throw err;

    // データをcanvasのcontextに設定
    var img = new Image;
    img.src = data;
    var canvas = new Canvas(img.width, img.height);
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, img.width, img.height);

    var text = 'どこでもドア岩本';
    var textMeasure = ctx.measureText(text);

    //var myFont = new Font('MyFont', 'rounded-mgenplus-1c-heavy.ttf');

    ctx.font = '45px "Rounded Mgen+ 1c"';
    ctx.textAlign = 'center';

	ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
	ctx.fillText(text, canvas.width / 2, 110);

	console.log(canvas.width, textMeasure.width);

    app.set('port', (process.env.PORT || 5000));
	app.use(express.static(__dirname + '/public'));

	app.get('/', function(request, response) {
	    response.send('');
	});

	app.listen(app.get('port'), function() {
	  console.log("Node app is running at localhost:" + app.get('port'));
	});
});<commit_msg>text test<commit_after>var fs = require('fs');
var express = require('express');
var app = express();

var Canvas = require('canvas');
var Image = Canvas.Image;
var Font = Canvas.Font;

fs.readFile(__dirname + '/images/bg.jpg', function(err, data){
    if (err) throw err;

    // データをcanvasのcontextに設定
    var img = new Image;
    img.src = data;
    var canvas = new Canvas(img.width, img.height);
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, img.width, img.height);

    var text = 'どこでもドア岩本hogehogheohgoehgheghoehgoeh/nhogehoge';
    var textMeasure = ctx.measureText(text);

    ctx.font = '45px "Rounded Mgen+ 1c"';
    ctx.textAlign = 'center';

	ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
	ctx.fillText(text, canvas.width / 2, 110);

	console.log(canvas.width, textMeasure.width);

    app.set('port', (process.env.PORT || 5000));
	app.use(express.static(__dirname + '/public'));

	app.get('/', function(request, response) {
	    response.send('');
	});

	app.listen(app.get('port'), function() {
	  console.log("Node app is running at localhost:" + app.get('port'));
	});
});<|endoftext|>


<commit_before>
/*!
 * Skeleton.js - I18n
 * Copyright(c) 2012 Rubén Norte <rubennorte@gmail.com>
 * MIT Licensed
 */

define([
  'require',
  'backbone',
  'underscore',
  'underscore.string',
  './util/url'
], function(require, Backbone, _, _s, url){

  'use strict';

  var rLocale = /^([a-zA-Z]{2})([\-_]([a-zA-Z]{2}))?$/,
      rStrictLocale = /^([a-z]{2})([_]([A-Z]{2}))?$/;

  var LOCALE_FORMAT_ERROR = 'The locale must have a valid format ' +
    '(e.g. en, es_ES)';

  /**
   * Skeleton I18n module definition
   */
  var I18n = _.extend({}, Backbone.Events, {

    // Current locale
    _locale: null,

    // Default locale
    _defaultLocale: null,

    // The object containing the current locale translations
    _translations: {},

    // The object containing counters for all missing translations
    _missingTranslations: {},

    // List of all available locales.
    // If null, the existence of each locale file is not verified before
    // trying to load it
    _availableLocales: null,

    // Relative path to the locale directory
    _loadPath: '',

    /**
     * Translates the specified parameter.
     * If it's an object, we assume that the object keys are the language code
     * and the object values are the translations for that language.
     * Otherwise, search the translation for that key in the stored translations
     */
    t: function(text){
      var locale = this.getLocale(),
          language = this.getLanguage();

      if (typeof text === 'boolean'){
        text = text ? 'true' : 'false';
      } else if (typeof text === 'number'){
        text = '' + text;
      }

      switch (typeof text){
      case 'string':
        // If text is a string, search in translation object
        if (!this._translations[text] && !this._missingTranslations[text]){
          // The translation is not found, so increment the counter for
          // that key in the missing translations object
          this._missingTranslations[text] =
            (this._missingTranslations[text] || 0) + 1;
          this._translations[text] = text;
          console.info('skeleton/i18n', 'Missing translation for key', text);
        }

        // Set the translated text as the value in the translations object or
        // the translation key itself (if the translation is missing)
        text = this._translations[text] || text;
        break;

      case 'object':
        if (text){
          // If text is an object (and not null), get the translations from it according
          // to the current locale
          if (locale in text){
            text = text[locale];
          } else if (language in text){
            text = text[language];
          } else if (this._defaultLocale in text){
            text = text[this._defaultLocale];
          }
        }
        break;

      case 'function':
        // If text is a function, get the result of this function passing
        // the locale as a parameter
        text = text(this._locale);
        break;
      }

      // If text is a string and the key is not the only specified parameter, return interpolated
      if (typeof text === 'string' && arguments.length > 1){
        arguments[0] = text;
        return _s.sprintf.apply(null, arguments);
      }

      return text;
    },

    /**
     * Returns the system locale according to the information provided
     * by the navigator
     */
    getSystemLocale: function(fn){
      if (typeof navigator === 'undefined'){
        return fn(null, this.getDefaultLocale());
      }

      // Cordova/Phonegap support
      if (navigator.globalization && typeof navigator.globalization.getLocaleName === 'function'){
        navigator.globalization.getLocaleName(function(locale){
          fn(null, locale);
        }, function(err){
          fn(err);
        });
        return;
      }

      var locale = toPOSIXLocale(navigator.language);
      fn(null, locale);
    },

    getDefaultLocale: function(){
      return this._defaultLocale;
    },

    /**
     * Returns the current locale
     */
    getLocale: function(){
      return this._locale;
    },

    /**
     * Returns the current language
     */
    getLanguage: function(){
      return this._locale.substr(0,2);
    },

    /**
     * Returns the current region
     */
    getRegion: function(){
      return this._locale.substr(3,2);
    },

    /**
     * Returns true if exists any valid locale file for the specified locale
     */
    isLocaleAvailable: function(locale){
      if (!this._availableLocales){
        return undefined;
      }

      var language = locale.substr(0,2),
          languageAvailable = _(this._availableLocales).include(language);

      if (languageAvailable){
        return true;
      }

      return locale.length === 5 && _(this._availableLocales).include(locale);
    },

    /**
     * Sets the current locale. The translation object can be passed or
     * it will be loaded from a JSON in the load path. When the locale is set
     * and the translations are loaded, callback function is invoked
     */
    setLocale: function(locale, translations, callback){
      if (!rLocale.test(locale)){
        throw new Error(LOCALE_FORMAT_ERROR + ': ' + locale);
      }

      locale = toPOSIXLocale(locale);

      // Check if translations object is defined
      if (_.isFunction(translations)){
        callback = translations;
        translations = null;
      }

      // If the locale is the current one, return immediatelly
      if (locale === this.getLocale()){
        return callback && callback();
      }

      if (translations){
        // If the translations are defined, we don't have to load them and can
        // set the locale inmediately
        this._setLocaleAndTranslations(locale, translations, callback);
      } else {
        // Otherwise, we have to load them (as AMD modules to cache)
        var language = locale.substr(0,2),
            region = locale.substr(3,2),
            localeFiles = [];

        if (!this._availableLocales ||
            _(this._availableLocales).include(language)){
          localeFiles.push('json!' + this._getLocaleUrl(language));
        }

        if (region &&
            (!this._availableLocales || _(this._availableLocales).include(locale))){
          localeFiles.push('json!' + this._getLocaleUrl(locale));
        }

        if (localeFiles.length === 0){
          if (callback){
            callback('The specified locale is not available: ' + locale);
          }
          return false;
        }

        this._loadLocaleFiles(locale, localeFiles, callback);
      }
    },

    /**
     * Sets the available locale files in the project
     */
    setAvailableLocales: function(availableLocales){
      _(availableLocales).each(function(availableLocale){
        if (!rStrictLocale.test(availableLocale)){
          throw new Error(LOCALE_FORMAT_ERROR + ': ' + availableLocale);
        }
      });
      var prevAvailableLocales = this._availableLocales;
      this._availableLocales = availableLocales;
      this.trigger('change:availableLocales', this, availableLocales, prevAvailableLocales);
    },

    /**
     * Sets the default locale
     */
    setDefaultLocale: function(locale){
      if (!rStrictLocale.test(locale)){
        throw new Error(LOCALE_FORMAT_ERROR + ': ' + locale);
      }

      var prevLocale = this._defaultLocale;
      this._defaultLocale = locale;
      this.trigger('change:defaultLocale', this, locale, prevLocale);
    },

    /**
     * Sets the locale file load path
     */
    setLoadPath: function(path){
      this._loadPath = path;
    },

    // Returns the URL of the JSON containing the translations for the specified
    // locale
    _getLocaleUrl: function(locale){
      return url.join(_.result(this, '_loadPath'), locale + '.json');
    },

    // Assigns the locale, the translations object and invokes the callback
    _setLocaleAndTranslations: function(locale, translations, callback){
      if (this._locale !== locale || !_.isEqual(this._translations, translations)){
        console.info('skeleton/i18n', 'Locale set to', locale);
        this._locale = locale;
        this._translations = translations;
        this._missingTranslations = {};
        this.trigger('change:locale', this);
      }
      if (callback){
        callback(null, locale);
      }
    },

    // Loads the locale files and merges the translation objects
    // into one
    _loadLocaleFiles: function(locale, localeFiles, callback){
      var self = this;

      var results = 0;
      var resultTranslations = _.map(localeFiles, function(){
        return {};
      });

      var onResponse = function(){
        results++;
        if (results === resultTranslations.length){
          var translations = {};
          _.each(resultTranslations, function(current){
            translations = _.extend(translations, current);
          });
          self._setLocaleAndTranslations(locale, translations, callback);
        }
      };

      _.each(localeFiles, function(localeFile, index){
        require([localeFile], function(localeTranslations){
          resultTranslations[index] = localeTranslations;
          onResponse();
        }, function(){
          onResponse();
        });
      });
    }

  });

  function toPOSIXLocale(locale){
    if (!locale){
      return locale;
    }

    if (locale.length === 2){
      return locale.toLowerCase();
    }

    return locale.substr(0,2).toLowerCase() + '_' +
      locale.substr(3,2).toUpperCase();
  }

  return I18n;

});
<commit_msg>Refactors and adds methods to the I18n module.<commit_after>
/*!
 * Skeleton.js - I18n
 * Copyright(c) 2012 Rubén Norte <rubennorte@gmail.com>
 * MIT Licensed
 */

define([
  'backbone',
  'underscore',
  'underscore.string',
  './util/url',
  'q',
  'jquery'
], function(Backbone, _, _s, url, Q, $){

  'use strict';

  var TAG = 'skeleton/i18n';

  var rLocale = /^([a-zA-Z]{2})([\-_]?([a-zA-Z]{2}))?/;

  var LOCALE_FORMAT_ERROR = 'The locale must have a valid format (e.g. "en", "es_ES")';

  /**
   * Skeleton I18n module definition
   */
  var I18n = _.extend({}, Backbone.Events, {

    // Current locale
    _locale: null,

    // Default locale
    _defaultLocale: null,

    // The object containing the current locale translations
    _translations: {},

    // The object containing counters for all missing translations
    _missingTranslations: {},

    // List of all available locales.
    // If null, the existence of each locale file is not verified before
    // trying to load it
    _availableLocales: null,

    // Relative path to the locale directory
    _loadPath: '',

    /**
     * Translates a string interpreted as a key in the translations object
     */
    translateString: function(str){
      str = str || 'undefined';
      var result = this._translations[str];
      if (!result && !this._missingTranslations[str]){
        // The translation is not found, so increment the counter for
        // that key in the missing translations object
        this._missingTranslations[str] =
          (this._missingTranslations[str] || 0) + 1;
        console.info(TAG, 'Missing translation for key', str);
      }
      str = result || str;
      arguments[0] = str;
      return this.interpolate.apply(this, arguments);
    },

    /**
     * Translates an object, returning the value for the current
     * locale or language used as key
     */
    translateObject: function(obj){
      var locale = this.getLocale();
      var language = this.getLanguage();
      if (!obj){
        return obj;
      } else if (_.has(obj, locale)){
        obj = obj[locale];
      } else if (_.has(obj, language)){
        obj = obj[language];
      } else if (_.has(obj, this._defaultLocale)){
        obj = obj[this._defaultLocale];
      } else {
        return null;
      }
      arguments[0] = obj;
      return this.interpolate.apply(this, arguments);
    },

    /**
     * Translates a boolean, searching the key "true" or "false" in the
     * translations object
     */
    translateBoolean: function(bool){
      bool = String(!!bool);
      return this.translateString.apply(this, arguments);
    },

    /**
     * Translates a number, searching the number as a key in the translations
     * object
     */
    translateNumber: function(number){
      number = String(number);
      return this.translateString.apply(this, arguments);
    },

    /**
     * Returns the result of the given function using the current locale as
     * a parameter
     */
    translateFunction: function(fn){
      arguments[0] = fn.apply(this, [this._locale].concat(arguments));
      return this.interpolate.apply(this, arguments);
    },

    /**
     * Interpolates the given string with the rest of parameters
     */
    interpolate: function(str){
      if (arguments.length > 1){
        return _s.sprintf.apply(null, arguments);
      }
      return str;
    },

    /**
     * Translates the specified parameter, determining it's type and calling
     * the proper function (translateString, translateObject...)
     */
    t: function(value){
      switch (typeof value){
      case 'string':
        return this.translateString.apply(this, arguments);
      case 'object':
        return this.translateObject.apply(this, arguments);
      case 'function':
        return this.translateFunction.apply(this, arguments);
      case 'number':
        return this.translateNumber.apply(this, arguments);
      case 'boolean':
        return this.translateBoolean.apply(this, arguments);
      default:
        return value;
      }
    },

    /**
     * Returns the system locale according to the information provided
     * by the navigator
     */
    getNavigatorLocale: function(fn){
      var deferred = Q.defer();
      var promise = deferred.promise;
      promise.nodeify(fn);

      if (typeof navigator === 'undefined'){
        deferred.resolve(this.getDefaultLocale());
      } else if (navigator.globalization && _.isFunction(navigator.globalization.getLocaleName)){
        // Cordova/Phonegap support
        navigator.globalization.getLocaleName(deferred.resolve,
            returnNavigatorLanguage(deferred));
      } else {
        returnNavigatorLanguage(deferred);
      }

      return promise;
    },

    getSystemLocale: function(){
      console.warn(TAG, 'getSystemLocale is deprecated and will be removed. ' +
          'Use getNavigatorLocale instead');
      return this.getNavigatorLocale();
    },

    /**
     * Returns the default locale
     */
    getDefaultLocale: function(){
      return this._defaultLocale;
    },

    /**
     * Returns the current locale
     */
    getLocale: function(){
      return this._locale;
    },

    /**
     * Returns the language of the specified locale or the current one
     */
    getLanguage: function(locale){
      var loc = locale ? this._tryConvertLocale(locale) : this._locale;
      return loc && loc.substr(0,2);
    },

    /**
     * Returns the region of the specified locale or the current one
     */
    getRegion: function(locale){
      var loc = locale ? this._tryConvertLocale(locale) : this._locale;
      return loc && (loc.substr(3,2) || undefined);
    },

    /**
     * Returns true if exists any valid locale file for the specified locale
     */
    isLocaleAvailable: function(locale){
      var available = this._availableLocales;
      if (!available){
        return undefined;
      }

      var loc = this._convertLocale(locale);
      var language = this.getLanguage(loc);
      return _.include(available, language) || _.include(available, loc);
    },

    /**
     * Sets the current locale. The translation object can be passed or
     * it will be loaded from a JSON in the load path. When the locale is set
     * and the translations are loaded, callback function is invoked
     */
    setLocale: function(locale, translations, callback){
      // Check optional translations argument
      if (_.isFunction(translations)){
        callback = translations;
        translations = null;
      }

      var deferred = Q.defer();
      var promise = deferred.promise;
      promise.nodeify(callback);

      var loc = this._tryConvertLocale(locale);

      // Check locale format
      if (!loc){
        deferred.reject(new Error(LOCALE_FORMAT_ERROR + ': ' + locale));
        return promise;
      }

      // If the locale is the current one, return immediatelly
      if (loc === this.getLocale()){
        deferred.resolve();
        return promise;
      }

      // If the translations are defined, we don't have to load them and can
      // set the locale inmediately
      if (translations){
        this._setLocaleAndTranslations(loc, translations);
        deferred.resolve();
        return promise;
      }

      // Load translations from files
      var localeFiles = this.getPathsForLocale(loc);
      if (localeFiles.length === 0){
        deferred.reject(new Error('The specified locale is not available: ' + loc));
        return promise;
      }

      return this._loadLocaleFiles(loc, localeFiles, callback).nodeify(callback);
    },

    /**
     * Sets the available locale files in the project
     */
    setAvailableLocales: function(available){
      var self = this;
      available = _.map(available, _.bind(this._convertLocale, this));
      var prevAvailable = this._availableLocales;
      this._availableLocales = available;
      this.trigger('change:availableLocales', this, available, prevAvailable);
    },

    /**
     * Sets the default locale
     */
    setDefaultLocale: function(locale){
      var loc = this._convertLocale(locale);
      var prevLocale = this._defaultLocale;
      this._defaultLocale = loc;
      this.trigger('change:defaultLocale', this, locale, prevLocale);
    },

    /**
     * Sets the locale file load path
     */
    setLoadPath: function(path){
      this._loadPath = path;
    },

    /**
     * Returns a list of files that contains the translations for
     * the specified locale
     */
    getPathsForLocale: function(locale){
      var language = this.getLanguage(locale);
      var region = this.getRegion(locale);
      var available = this._availableLocales;
      var localeFiles = [];

      if (!available || _.include(available, language)){
        localeFiles.push(this.getPathForLocale(language));
      }

      if (!available || _.include(available, locale)){
        localeFiles.push(this.getPathForLocale(locale));
      }

      return localeFiles;
    },

    // Returns the URL of the JSON containing the translations for the specified
    // locale
    getPathForLocale: function(locale){
      return url.join(_.result(this, '_loadPath'), locale + '.json');
    },

    // Assigns the locale, the translations object and invokes the callback
    _setLocaleAndTranslations: function(locale, translations){
      if (this._locale !== locale || !_.isEqual(this._translations, translations)){
        console.info(TAG, 'Locale set to', locale);
        this._locale = locale;
        this._translations = translations;
        this._missingTranslations = {};
        this.trigger('change:locale', this);
      }
    },

    // Loads the locale files and merges the translation objects
    // into one
    _loadLocaleFiles: function(locale, localeFiles){
      var self = this;
      var requests = _.map(localeFiles, _.bind(this._loadLocaleFile, this));
      return Q.all(requests).then(function(results){
        results.unshift({});
        var translations = _.extend.apply(_, results);
        self._setLocaleAndTranslations(locale, translations);
      });
    },

    _loadLocaleFile: function(localeFile){
      return $.getJSON(localeFile).error(function(){
        return null;
      });
    },

    _tryConvertLocale: function(locale){
      var matches = rLocale.exec(locale);
      if (!matches){
        return;
      }
      var language = matches[1].toLowerCase();
      var region = matches[3];
      if (region){
        return language + '_' + region.toUpperCase();
      } else {
        return language;
      }
    },

    _convertLocale: function(locale){
      var loc = this._tryConvertLocale(locale);
      if (!loc){
        throw new Error(LOCALE_FORMAT_ERROR + ': ' + locale);
      }
      return loc;
    }

  });

  function returnNavigatorLanguage(deferred){
    var navLang = navigator.language;
    var locale = I18n._tryConvertLocale(navLang);
    if (locale){
      deferred.resolve(locale);
    } else {
      deferred.reject(LOCALE_FORMAT_ERROR + ': ' + navLang);
    }
  }

  return I18n;

});
<|endoftext|>


<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const ccxt = require ('ccxt');

//  ---------------------------------------------------------------------------

module.exports = class poloniex extends ccxt.poloniex {
    describe () {
        return this.deepExtend (super.describe (), {
            'has': {
                'ws': true,
                'fetchWsTicker': true,
                'fetchWsOrderBook': true,
            },
            'urls': {
                'api': {
                    'ws': 'wss://api2.poloniex.com/',
                },
            },
        });
    }

    // getWsMessageHash (client, response) {
    //     const channelId = response[0].toString ();
    //     const length = response.length;
    //     if (length <= 2) {
    //         return;
    //     }
    //     if (channelId === '1002') {
    //         return channelId + response[2][0].toString ();
    //     } else {
    //         return channelId;
    //     }
    // }

    handleWsTicker (response) {
        const data = response[2];
        const market = this.safeValue (this.options['marketsByNumericId'], data[0].toString ());
        const symbol = this.safeString (market, 'symbol');
        return {
            'info': response,
            'symbol': symbol,
            'last': parseFloat (data[1]),
            'ask': parseFloat (data[2]),
            'bid': parseFloat (data[3]),
            'change': parseFloat (data[4]),
            'baseVolume': parseFloat (data[5]),
            'quoteVolume': parseFloat (data[6]),
            'active': data[7] ? false : true,
            'high': parseFloat (data[8]),
            'low': parseFloat (data[9]),
        };
    }

    async fetchWsTickers (symbol) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const numericId = market['info']['id'].toString ();
        const url = this.urls['api']['websocket']['public'];
        return await this.WsTickerMessage (url, '1002' + numericId, {
            'command': 'subscribe',
            'channel': 1002,
        });
    }

    async loadMarkets (reload = false, params = {}) {
        const markets = await super.loadMarkets (reload, params);
        let marketsByNumericId = this.safeValue (this.options, 'marketsByNumericId');
        if ((marketsByNumericId === undefined) || reload) {
            marketsByNumericId = {};
            for (let i = 0; i < this.symbols.length; i++) {
                const symbol = this.symbols[i];
                const market = this.markets[symbol];
                const numericId = this.safeString (market, 'numericId');
                marketsByNumericId[numericId] = market;
            }
            this.options['marketsByNumericId'] = marketsByNumericId;
        }
        return markets;
    }

    async fetchWsOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const numericId = this.safeString (market, 'numericId');
        const url = this.urls['api']['ws'];
        const orderbook = await this.sendWsMessage (url, numericId, {
            'command': 'subscribe',
            'channel': numericId,
        });
        return orderbook.limit (limit);
    }

    handleWsHeartbeat (message) {
        //
        // every second
        //
        //     [ 1010 ]
        //
        return message;
    }

    handleWsOrderBookAndTrades (message) {
        //
        // first response
        //
        //     [
        //         14, // channelId === market['numericId']
        //         8767, // nonce
        //         [
        //             [
        //                 "i", // initial snapshot
        //                 {
        //                     "currencyPair": "BTC_BTS",
        //                     "orderBook": [
        //                         { "0.00001853": "2537.5637", "0.00001854": "1567238.172367" }, // asks, price, size
        //                         { "0.00001841": "3645.3647", "0.00001840": "1637.3647" } // bids
        //                     ]
        //                 }
        //             ]
        //         ]
        //     ]
        //
        // subsequent updates
        //
        //     [
        //         14,
        //         8768,
        //         [
        //             [ "o", 1, "0.00001823", "5534.6474" ], // orderbook delta, bids, price, size
        //             [ "o", 0, "0.00001824", "6575.464" ], // orderbook delta, asks, price, size
        //             [ "t", "42706057", 1, "0.05567134", "0.00181421", 1522877119 ] // trade, id, sell, price, size, timestamp
        //         ]
        //     ]
        //
        // TODO: handle incremental trades too
        const marketId = message[0].toString ();
        const nonce = message[1];
        const data = message[2];
        const market = this.safeValue (this.options['marketsByNumericId'], marketId);
        const symbol = this.safeString (market, 'symbol');
        let orderbookCount = 0;
        let tradesCount = 0;
        for (let i = 0; i < data.length; i++) {
            const delta = data[i];
            if (delta[0] === 'i') {
                const snapshot = this.safeValue (delta[1], 'orderBook', []);
                const sides = [ 'asks', 'bids' ];
                this.orderbooks[symbol] = this.orderbook ();
                const orderbook = this.orderbooks[symbol];
                for (let j = 0; j < snapshot.length; j++) {
                    const side = sides[j];
                    const bookside = orderbook[side];
                    const orders = snapshot[j];
                    const prices = Object.keys (orders);
                    for (let k = 0; k < prices.length; k++) {
                        const price = prices[k];
                        const amount = parseFloat (orders[price]);
                        bookside.store (price, amount);
                    }
                }
                orderbook['nonce'] = nonce;
                orderbookCount += 1;
            } else if (delta[0] === 'o') {
                const orderbook = this.orderbooks[symbol];
                const side = delta[1] ? 'bids' : 'asks';
                const bookside = orderbook[side];
                const price = delta[2];
                const amount = parseFloat (delta[3]);
                bookside.store (price, amount);
                orderbookCount += 1;
            } else if (delta[0] === 't') {
                const trade = this.parseWsTrade (delta);
                this.trades.push (trade);
                tradesCount += 1;
            }
        }
        if (orderbookCount) {
            // resolve the orderbook future
        }
        if (tradesCount) {
            // resolve the trades future
        }
    }

    handleWsMessage (client, message) {
        const channelId = message[0].toString ();
        const market = this.safeValue (this.options['marketsByNumericId'], channelId);
        if (market === undefined) {
            const methods = {
                // '<numericId>': 'handleWsOrderBookAndTrades', // Price Aggregated Book
                '1000': 'handleWsPrivateAccountNotifications', // (Beta)
                '1002': 'handleWsTicker', // Ticker Data
                // '1003': undefined, // 24 Hour Exchange Volume
                '1010': 'handleWsHeartbeat',
            };
            const method = this.safeString (methods, channelId);
            if (method === undefined) {
                return message;
            } else {
                return this[method] (message);
            }
        } else {
            return this.handleWsOrderBookAndTrades (message);
        }
        // if (channelId in this.options['marketsByNumericId']) {
        //     return this.handleWsOrderBookAndTrades (message);
        // } else {
        //     const methods = {
        //         // '<numericId>': 'handleWsOrderBookAndTrades', // Price Aggregated Book
        //         '1000': 'handleWsPrivateAccountNotifications', // (Beta)
        //         '1002': 'handleWsTicker', // Ticker Data
        //         // '1003': undefined, // 24 Hour Exchange Volume
        //         '1010': 'handleWsHeartbeat',
        //     };
        //     const method = this.safeString (methods, channelId);
        //     if (method === undefined) {
        //         return message;
        //     } else {
        //         return this[method] (message);
        //     }
        // }
    }
};
<commit_msg>poloniex ws<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const ccxt = require ('ccxt');

//  ---------------------------------------------------------------------------

module.exports = class poloniex extends ccxt.poloniex {
    describe () {
        return this.deepExtend (super.describe (), {
            'has': {
                'ws': true,
                'fetchWsTicker': true,
                'fetchWsOrderBook': true,
            },
            'urls': {
                'api': {
                    'ws': 'wss://api2.poloniex.com/',
                },
            },
        });
    }

    // getWsMessageHash (client, response) {
    //     const channelId = response[0].toString ();
    //     const length = response.length;
    //     if (length <= 2) {
    //         return;
    //     }
    //     if (channelId === '1002') {
    //         return channelId + response[2][0].toString ();
    //     } else {
    //         return channelId;
    //     }
    // }

    handleWsTicker (client, response) {
        const data = response[2];
        const market = this.safeValue (this.options['marketsByNumericId'], data[0].toString ());
        const symbol = this.safeString (market, 'symbol');
        return {
            'info': response,
            'symbol': symbol,
            'last': parseFloat (data[1]),
            'ask': parseFloat (data[2]),
            'bid': parseFloat (data[3]),
            'change': parseFloat (data[4]),
            'baseVolume': parseFloat (data[5]),
            'quoteVolume': parseFloat (data[6]),
            'active': data[7] ? false : true,
            'high': parseFloat (data[8]),
            'low': parseFloat (data[9]),
        };
    }

    async fetchWsTickers (symbol) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const numericId = market['info']['id'].toString ();
        const url = this.urls['api']['websocket']['public'];
        return await this.WsTickerMessage (url, '1002' + numericId, {
            'command': 'subscribe',
            'channel': 1002,
        });
    }

    async loadMarkets (reload = false, params = {}) {
        const markets = await super.loadMarkets (reload, params);
        let marketsByNumericId = this.safeValue (this.options, 'marketsByNumericId');
        if ((marketsByNumericId === undefined) || reload) {
            marketsByNumericId = {};
            for (let i = 0; i < this.symbols.length; i++) {
                const symbol = this.symbols[i];
                const market = this.markets[symbol];
                const numericId = this.safeString (market, 'numericId');
                marketsByNumericId[numericId] = market;
            }
            this.options['marketsByNumericId'] = marketsByNumericId;
        }
        return markets;
    }

    async fetchWsTrades (symbol, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const numericId = this.safeString (market, 'numericId');
        const messageHash = numericId + ':trades';
        const url = this.urls['api']['ws'];
        const subscribe = {
            'command': 'subscribe',
            'channel': numericId,
        };
        return this.sendWsMessage (url, messageHash, subscribe, numericId);
    }

    async fetchWsOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const numericId = this.safeString (market, 'numericId');
        const messageHash = numericId + ':orderbook';
        const url = this.urls['api']['ws'];
        const subscribe = {
            'command': 'subscribe',
            'channel': numericId,
        };
        // const orderbook = await this.sendWsMessage (url, messageHash, {
        //     'command': 'subscribe',
        //     'channel': numericId,
        // });
        // return orderbook.limit (limit);
        return this.sendWsMessage (url, messageHash, subscribe, numericId);
    }

    async fetchWsHeartbeat (params = {}) {
        await this.loadMarkets ();
        const channelId = '1010';
        const url = this.urls['api']['ws'];
        return this.sendWsMessage (url, channelId);
    }

    signWsMessage (message, params = {}) {
        const nonce = this.nonce ();
        const payload = this.urlencode ({ 'nonce': nonce })
        const signature = this.hmac (this.encode (payload), this.encode (this.secret), 'sha512');
        message = this.extend (message, {
            'key': this.apiKey,
            'payload': payload,
            'sign': signature,
        });
        return message;
    }

    handleWsHeartbeat (client, message) {
        //
        // every second
        //
        //     [ 1010 ]
        //
        const channelId = '1010';
        this.resolveWsFuture (client, channelId, message);
    }

    parseWsTrade (client, trade, market = undefined) {
        //
        // public trades
        //
        //     [
        //         "t", // trade
        //         "42706057", // id
        //         1, // 1 = buy, 0 = sell
        //         "0.05567134", // price
        //         "0.00181421", // amount
        //         1522877119, // timestamp
        //     ]
        //
        const id = trade[1].toString ();
        const side = trade[2] ? 'buy' : 'sell';
        const price = parseFloat (trade[3]);
        const amount = parseFloat (trade[4]);
        const timestamp = trade[5] * 1000;
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        return {
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'id': id,
            'order': undefined,
            'type': undefined,
            'takerOrMaker': undefined,
            'side': side,
            'price': price,
            'amount': amount,
            'cost': price * amount,
            'fee': undefined,
        };
    }

    handleWsOrderBookAndTrades (client, message) {
        //
        // first response
        //
        //     [
        //         14, // channelId === market['numericId']
        //         8767, // nonce
        //         [
        //             [
        //                 "i", // initial snapshot
        //                 {
        //                     "currencyPair": "BTC_BTS",
        //                     "orderBook": [
        //                         { "0.00001853": "2537.5637", "0.00001854": "1567238.172367" }, // asks, price, size
        //                         { "0.00001841": "3645.3647", "0.00001840": "1637.3647" } // bids
        //                     ]
        //                 }
        //             ]
        //         ]
        //     ]
        //
        // subsequent updates
        //
        //     [
        //         14,
        //         8768,
        //         [
        //             [ "o", 1, "0.00001823", "5534.6474" ], // orderbook delta, bids, price, size
        //             [ "o", 0, "0.00001824", "6575.464" ], // orderbook delta, asks, price, size
        //             [ "t", "42706057", 1, "0.05567134", "0.00181421", 1522877119 ] // trade, id, side (1 for buy, 0 for sell), price, size, timestamp
        //         ]
        //     ]
        //
        const marketId = message[0].toString ();
        const nonce = message[1];
        const data = message[2];
        const market = this.safeValue (this.options['marketsByNumericId'], marketId);
        const symbol = this.safeString (market, 'symbol');
        let orderbookUpdatesCount = 0;
        let tradesCount = 0;
        for (let i = 0; i < data.length; i++) {
            const delta = data[i];
            if (delta[0] === 'i') {
                const snapshot = this.safeValue (delta[1], 'orderBook', []);
                const sides = [ 'asks', 'bids' ];
                this.orderbooks[symbol] = this.orderbook ();
                const orderbook = this.orderbooks[symbol];
                for (let j = 0; j < snapshot.length; j++) {
                    const side = sides[j];
                    const bookside = orderbook[side];
                    const orders = snapshot[j];
                    const prices = Object.keys (orders);
                    for (let k = 0; k < prices.length; k++) {
                        const price = prices[k];
                        const amount = parseFloat (orders[price]);
                        bookside.store (price, amount);
                    }
                }
                orderbook['nonce'] = nonce;
                orderbookUpdatesCount += 1;
            } else if (delta[0] === 'o') {
                const orderbook = this.orderbooks[symbol];
                const side = delta[1] ? 'bids' : 'asks';
                const bookside = orderbook[side];
                const price = delta[2];
                const amount = parseFloat (delta[3]);
                bookside.store (price, amount);
                orderbookUpdatesCount += 1;
            } else if (delta[0] === 't') {
                const trade = this.parseWsTrade (client, delta, market);
                this.trades.push (trade);
                tradesCount += 1;
            }
        }
        if (orderbookUpdatesCount) {
            // resolve the orderbook future
            const messageHash = marketId + ':orderbook';
            const orderbook = this.orderbooks[symbol];
            this.resolveWsFuture (client, messageHash, orderbook.limit ());
        }
        if (tradesCount) {
            // resolve the trades future
            const messageHash = marketId + ':trades';
            this.resolveWsFuture (client, messageHash, this.trades);
        }
    }

    handleWsMessage (client, message) {
        const channelId = message[0].toString ();
        const market = this.safeValue (this.options['marketsByNumericId'], channelId);
        if (market === undefined) {
            const methods = {
                // '<numericId>': 'handleWsOrderBookAndTrades', // Price Aggregated Book
                '1000': 'handleWsPrivateAccountNotifications', // (Beta)
                '1002': 'handleWsTicker', // Ticker Data
                // '1003': undefined, // 24 Hour Exchange Volume
                '1010': 'handleWsHeartbeat',
            };
            const method = this.safeString (methods, channelId);
            if (method === undefined) {
                return message;
            } else {
                return this[method] (client, message);
            }
        } else {
            return this.handleWsOrderBookAndTrades (client, message);
        }
        // if (channelId in this.options['marketsByNumericId']) {
        //     return this.handleWsOrderBookAndTrades (message);
        // } else {
        //     const methods = {
        //         // '<numericId>': 'handleWsOrderBookAndTrades', // Price Aggregated Book
        //         '1000': 'handleWsPrivateAccountNotifications', // (Beta)
        //         '1002': 'handleWsTicker', // Ticker Data
        //         // '1003': undefined, // 24 Hour Exchange Volume
        //         '1010': 'handleWsHeartbeat',
        //     };
        //     const method = this.safeString (methods, channelId);
        //     if (method === undefined) {
        //         return message;
        //     } else {
        //         return this[method] (message);
        //     }
        // }
    }
};
<|endoftext|>


<commit_before>import parser from 'minimist'
import pkginfo from 'pkginfo'
import path from 'path'

class Commander {
  constructor() {
    this.details = {
      options: [],
      commands: []
    }

    this.option('help', 'Output usage information')
    this.command('help', 'Display help')
  }

  option (name, description, defaultValue) {
    let usage = []

    switch (name.constructor) {
      case String:
        usage[0] = name.charAt(0)
        usage[1] = name

        break
      case Array:
        usage = usage.concat(name)
        break
      default:
        throw new Error('Invalid name for option')
    }

    if (usage.length > 0 && usage[0].length > 1) {
      throw new Error('Short version of option is longer than 1 char')
    }

    this.details.options.push({
      defaultValue,
      usage,
      description
    })

    return this
  }

  command (usage, description) {
    this.details.commands.push({
      usage,
      description
    })
  }

  handleType (value) {
    const type = value.constructor

    switch (type) {
      case String:
        return ['[value]', toString]
        break
      case Array:
        return ['<list>']
        break
      case Number:
        return ['<n>', parseInt]
        break
      default:
        return false
    }
  }

  setProperties (names, initial) {
    let value = false

    for (let name of names) {
      let fromArgs = this.args[name]

      if (fromArgs) {
        value = fromArgs
      }
    }

    for (let name of names) {
      this[name] = value
    }
  }

  generateDetails (kind) {
    const items = this.details[kind]
    let parts = []

    for (let item in items) {
      let usage = items[item].usage,
          initial = items[item].defaultValue

      if (usage.constructor === Array) {
        usage = `-${usage[0]}, --${usage[1]}`
        usage += initial ? ' ' + this.handleType(initial)[0] : ''
      }

      items[item].usage = usage
    }

    const longest = items.sort((a, b) => {
      return b.usage.length - a.usage.length
    })[0].usage.length

    for (let item of items) {
      let usage = item.usage,
          difference = longest - usage.length

      usage += ' '.repeat(difference)
      parts.push('  ' + usage + '  ' + item.description)
    }

    return parts
  }

  renderHelp () {
    const binary = path.basename(this.args._[0])

    let details = [
      '',
      `Usage: ${binary} [options] [command]`,
      '',
      '',
      'Commands:',
      ''
    ]

    const commands = this.generateDetails('commands'),
          options = this.generateDetails('options')

    details = details.concat(
      commands,
      [
        '',
        'Options:',
        ''
      ],
      options,
      ''
    )

    console.log(details.join('\n  '))
    process.exit()
  }

  parse (argv) {
    this.args = parser(argv.slice(1))

    const parent = module.parent

    pkginfo(parent)
    const version = parent.exports.version

    if (version) {
      this.option('version', 'Output the version number', version)

      if (this.args.v || this.args.version) {
        console.log(version)
        process.exit()
      }
    }

    if (this.args._[1] == 'help' || this.args.h || this.args.help) {
      this.renderHelp()
    }

    for (let option of this.details.options) {
      this.setProperties(option.usage, option.defaultValue)
    }

    const args = this.args
    args._.shift()

    this.raw = args
  }
}

export default new Commander
<commit_msg>Custom initializers<commit_after>import parser from 'minimist'
import pkginfo from 'pkginfo'
import path from 'path'

class Commander {
  constructor() {
    this.details = {
      options: [],
      commands: []
    }

    this.option('help', 'Output usage information')
    this.command('help', 'Display help')
  }

  option (name, description, init, defaultValue) {
    let usage = []

    switch (name.constructor) {
      case String:
        usage[0] = name.charAt(0)
        usage[1] = name

        break
      case Array:
        usage = usage.concat(name)
        break
      default:
        throw new Error('Invalid name for option')
    }

    if (usage.length > 0 && usage[0].length > 1) {
      throw new Error('Short version of option is longer than 1 char')
    }

    let optionDetails = {
      defaultValue,
      usage,
      description
    }

    if (defaultValue) {
      let initFunction = typeof init === 'function'
      optionDetails.init = initFunction ? init : this.handleType(defaultValue)[1]
    }

    this.details.options.push(optionDetails)
    return this
  }

  command (usage, description) {
    this.details.commands.push({
      usage,
      description
    })
  }

  handleType (value) {
    const type = value.constructor

    switch (type) {
      case String:
        return ['[value]', toString]
        break
      case Array:
        return ['<list>']
        break
      case Number:
        return ['<n>', parseInt]
        break
      default:
        return false
    }
  }

  setProperties (option) {
    let value = false

    for (let name of option.usage) {
      let fromArgs = this.args[name]

      if (fromArgs) {
        value = fromArgs
      }
    }

    for (let name of option.usage) {
      let propVal = value || option.defaultValue

      if (option.init) {
        propVal = option.init(propVal)
      }

      this[name] = propVal
    }
  }

  generateDetails (kind) {
    const items = this.details[kind]
    let parts = []

    for (let item in items) {
      let usage = items[item].usage,
          initial = items[item].defaultValue

      if (usage.constructor === Array) {
        usage = `-${usage[0]}, --${usage[1]}`
        usage += initial ? ' ' + this.handleType(initial)[0] : ''
      }

      items[item].usage = usage
    }

    const longest = items.sort((a, b) => {
      return b.usage.length - a.usage.length
    })[0].usage.length

    for (let item of items) {
      let usage = item.usage,
          difference = longest - usage.length

      usage += ' '.repeat(difference)
      parts.push('  ' + usage + '  ' + item.description)
    }

    return parts
  }

  renderHelp () {
    const binary = path.basename(this.args._[0])

    let details = [
      '',
      `Usage: ${binary} [options] [command]`,
      '',
      '',
      'Commands:',
      ''
    ]

    const commands = this.generateDetails('commands'),
          options = this.generateDetails('options')

    details = details.concat(
      commands,
      [
        '',
        'Options:',
        ''
      ],
      options,
      ''
    )

    console.log(details.join('\n  '))
    process.exit()
  }

  parse (argv) {
    this.args = parser(argv.slice(1))

    const parent = module.parent

    pkginfo(parent)
    const version = parent.exports.version

    if (version) {
      this.option('version', 'Output the version number', version)

      if (this.args.v || this.args.version) {
        console.log(version)
        process.exit()
      }
    }

    if (this.args._[1] == 'help' || this.args.h || this.args.help) {
      this.renderHelp()
    }

    for (let option of this.details.options) {
      this.setProperties(option)
    }

    const args = this.args
    args._.shift()

    this.raw = args
  }
}

export default new Commander
<|endoftext|>


<commit_before>
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function postForm(){
    var formData = JSON.stringify($('form').serializeObject());

    $.ajax({
        type: "POST",
        url: "/validateLogin",
        data: formData,
        success: function(response){
            console.log(response);
            if(response['error'] == 'a1'){

                Materialize.toast('Account or Password Error', 3000, 'rounded');
            }
        },
        dataType: "json",
        contentType : "application/json"
    });
}

function postForm_sign_up(){
    var formData = JSON.stringify($('form').serializeObject());

    $.ajax({
        type: "POST",
        url: "/signup",
        data: formData,
        success: function(){
            if(response['error'] == 'a2'){
                Materialize.toast('Email already registered!!', 3000, 'rounded');
            }
        },
        dataType: "json",
        contentType : "application/json"
    });
}
<commit_msg>url fix<commit_after>
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function postForm(){
    var formData = JSON.stringify($('form').serializeObject());
    var  dictPost  =  [{"plugin":"user_model"},{"action":"validate_login"},{"data":formData}];
    $.ajax({
        type: "POST",
        url: "/plugin",
        data: dictPost,
        success: function(response){
            console.log(response);
            if(response['error'] == 'a1'){

                Materialize.toast('Account or Password Error', 3000, 'rounded');
            }
        },
        dataType: "json",
        contentType : "application/json"
    });
}

function postForm_sign_up(){
    var formData = JSON.stringify($('form').serializeObject());
    var  dictPost  =  [{"plugin":"user_model"},{"action":"create_user"},{"data":formData}];
    $.ajax({
        type: "POST",
        url: "/plugin",
        data: dictPost,
        success: function(){
            if(response['error'] == 'a2'){
                Materialize.toast('Email already registered!!', 3000, 'rounded');
            }
        },
        dataType: "json",
        contentType : "application/json"
    });
}
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var mixin = require('merge-descriptors');
var proto = require('./drafterbit');
var express = require('express');

function createApplication(_ROOT) {
  var app = function(req, res, next) {
    app.handle(req, res, next);
  };

  mixin(app, EventEmitter.prototype, false);
  mixin(app, proto, false);

  app.request = { __proto__: express.request, app: app };
  app.response = { __proto__: express.response, app: app };
  app.init();
  return app;
}

exports = module.exports = createApplication;
exports.Module = require('./module');
<commit_msg>unused var<commit_after>var EventEmitter = require('events').EventEmitter;
var mixin = require('merge-descriptors');
var proto = require('./drafterbit');
var express = require('express');

function createApplication() {
  var app = function(req, res, next) {
    app.handle(req, res, next);
  };

  mixin(app, EventEmitter.prototype, false);
  mixin(app, proto, false);

  app.request = { __proto__: express.request, app: app };
  app.response = { __proto__: express.response, app: app };
  app.init();
  return app;
}

exports = module.exports = createApplication;
exports.Module = require('./module');
<|endoftext|>