<commit_before>// ==UserScript==
// @name        e-hentai retriever
// @namespace   http://e-hentai.org
// @description e-hentai retriever
// @include     http://exhentai.org/s/*
// @include     http://g.e-hentai.org/s/*
// @version     2.1.0
// @grant       GM_xmlhttpRequest
// ==/UserScript==

/* This script is licensed under under MIT License
 * http://opensource.org/licenses/MIT
 */

(function (document) {
  var e_hen_download = {
        current: {},
        settings: {
          getNextPageInterval: 1000
        }
      },
      $ = function $(selector) {
        return [].slice.call(document.querySelectorAll(selector), 0);
      };

  (function init(document) {
    var buttons_wrapper;

    if (document.getElementsByTagName("h1")[0]) {
      buttons_wrapper = document.createElement('div');

      buttons_wrapper.setAttribute('id', 'ehd_btn');
      buttons_wrapper.innerHTML = '<input id="ehd_enlargebtn" type="button" value="Enlarge"><input id="ehd_dlbtn" type="button" value="Generate img Link"><input id="ehd_scbtn" type="button" value="Unlimited Scroll!"><input id="ehd_stopbtn" type="button" value="Stop At" disabled="disabled">

please wait, now:

';

      $('#i1')[0].insertBefore(buttons_wrapper, $('#i2')[0]);

      $("#ehd_dlbtn")[0].addEventListener('click', DLbtnHandler);
      $("#ehd_scbtn")[0].addEventListener('click', SCbtnHandler);
      $("#ehd_enlargebtn")[0].addEventListener('click', function (event) {
        if (event.target.value.match('enlarge')) {
          try { unsafeWindow.onresize = null; } catch (e) { console.log(e); };
          $('#i1')[0].style.maxWidth = $('#i1')[0].style.maxWidth.toString().replace(/\D/g, '') * 2 + 'px';
          $('#i1')[0].style.width = $('#i1')[0].style.width.toString().replace(/\D/g, '') * 2 + 'px';
          event.target.setAttribute('value', 'diminish');
        }
        else {
          try { unsafeWindow.onresize = unsafeWindow.update_window_extents; unsafeWindow.update_window_extents(); } catch (e) { console.log(e); };
          event.target.setAttribute('value', 'enlarge');
        }
      });
      $("#ehd_stopbtn")[0].addEventListener('click', function (event) {
        event.target.setAttribute('disabled', 'disabled');
        var stopAt = parseInt(prompt('Stop at page:', e_hen_download.current.total), 10);
        if (isNaN(stopAt)) {
          alert('Not a number!');
          event.target.removeAttribute('disabled');
        }
        else {
          e_hen_download.settings.stopAt = stopAt;
        }
      })

    }
    else {
      setTimeout(init, 500);
    }
  }(document));

  function DLbtnHandler() {
    $('#ehd_btn input').forEach(function (e) { e.setAttribute('disabled', 'disabled') });
    $("#ehd_stopbtn")[0].removeAttribute('disabled');
    $("#ehd_enlargebtn")[0].removeAttribute('disabled');
    $('#ehd_output')[0].style.display = 'block';

    GetHtml(DLout);
  };

  function DLout(html) {
      var c = e_hen_download.current,
          s = e_hen_download.settings,

      parseResult = parse(html);

      $('#ehd_output')[0].innerHTML += '' + parseResult.filename + ' ';

      $('#ehd_now')[0].innerHTML = c.current + '/' + c.total;

      if (c.current >= c.total || c.current >= s.stopAt) $('#ehd_status')[0].innerHTML = 'Done!';
      else setTimeout(function () {
        GetHtml(DLout);
      }, s.getNextPageInterval);
  }

  function SCbtnHandler() {
    $('#ehd_btn input').forEach(function (e) { e.setAttribute('disabled', 'disabled') });
    $("#ehd_stopbtn")[0].removeAttribute('disabled');
    $("#ehd_enlargebtn")[0].removeAttribute('disabled');
    $('#ehd_output')[0].style.display = 'block';
    $('#i3 a')[0].style.display =  'none';

    GetHtml(SCout);
  };

  function SCout(html, url) {
    var c = e_hen_download.current,
        s = e_hen_download.settings,
        img_node = document.createElement('a');

    parseResult = parse(html, url);

    img_node.setAttribute('href', 'javascript:;');
    img_node.innerHTML = '';

    img_node.dataset.failnl = parseResult.failnl;
    img_node.dataset.currentUrl = parseResult.currentUrl;
    img_node.dataset.locked = 'false';

    img_node.addEventListener('click', FailLoad);
    img_node.childNodes[0].addEventListener('error', FailLoad);

    $('#i3')[0].appendChild(img_node);

    $('#ehd_now')[0].innerHTML = c.current + '/' + c.total;

    if(c.current >= c.total || c.current >= s.stopAt) $('#ehd_status')[0].innerHTML = 'Done!';
    else setTimeout(function () {
        GetHtml(SCout);
    }, s.getNextPageInterval);
  }

  function GetHtml(callback, current) {
    var c = current || e_hen_download.current;

    if(c.next) {
      GM_xmlhttpRequest({
        'method': 'GET',
        'url': c.next,

        'headers': {
          'User-Agent': navigator.userAgent,
          'Referer': c.currentUrl,
          'Cookie': document.cookie
        },

        'onload': function (xhr) {
          callback(xhr.responseText, xhr.finalUrl);
        },

        'onerror': function (e) {
          console.log(e);
        }
      });
    }
    else callback(document.body.innerHTML, document.location + '');
  }

  function FailLoad(event) {
    var e = event.target.parentNode,
        failnl = e.dataset.failnl,
        currentUrl = e.dataset.currentUrl,
        c = {
          'next': currentUrl + (currentUrl.indexOf('?') > -1 ? '&' : '?') + 'nl=' + failnl,
          'currentUrl': currentUrl
        };
console.log(event);
    if (e.dataset.locked === 'true') {
      return false;
    }

    e.dataset.locked = 'true';

    GetHtml(function (html, url) {
      var regex = /
([^ ]*) ::.*]*id="img"[^>]*src="([^"]*)"[^>]*style="([^"]*)".*onclick="return nl\('([0-9-]+)'\)/,
          parsed = html.match(regex),
          result;

      if(parsed) {
        result = {
          'filename': parsed[1],
          'src': parsed[2],
          'style': parsed[3],
          'failnl': parsed[4],
          'currentUrl': url
        };

        e.innerHTML = '';

        e.dataset.failnl = result.failnl;
        e.dataset.currentUrl = result.currentUrl;
        e.dataset.locked = 'false';
      }
    }, c);
  }

  function parse(html, currentUrl) {
    var c = e_hen_download.current,
        regex = /(\d+)<\/span> \/ (\d+)<\/span>.*
([^ ]*) ::.*]*href="([^"]*)">]*src="([^"]*)"[^>]*style="([^"]*)".*onclick="return nl\('([0-9-]+)'\)/,
        parsed = html.match(regex),
        result;

    if (parsed) {
      c.current = parseInt(parsed[1], 10);
      c.total = parseInt(parsed[2], 10);
      c.next = parsed[4];
      c.currentUrl = currentUrl;

      result = {
        'filename': parsed[3],
        'src': parsed[5],
        'style': parsed[6],
        'failnl': parsed[7],
        'currentUrl': currentUrl
      };
    }

    return result;
  }

}(document));<commit_msg>fix typo<commit_after>// ==UserScript==
// @name        e-hentai retriever
// @namespace   http://e-hentai.org
// @description e-hentai retriever
// @include     http://exhentai.org/s/*
// @include     http://g.e-hentai.org/s/*
// @version     2.1.0
// @grant       GM_xmlhttpRequest
// ==/UserScript==

/* This script is licensed under under MIT License
 * http://opensource.org/licenses/MIT
 */

(function (document) {
  var e_hen_download = {
        current: {},
        settings: {
          getNextPageInterval: 1000
        }
      },
      $ = function $(selector) {
        return [].slice.call(document.querySelectorAll(selector), 0);
      };

  (function init(document) {
    var buttons_wrapper;

    if (document.getElementsByTagName("h1")[0]) {
      buttons_wrapper = document.createElement('div');

      buttons_wrapper.setAttribute('id', 'ehd_btn');
      buttons_wrapper.innerHTML = '<input id="ehd_enlargebtn" type="button" value="Enlarge"><input id="ehd_dlbtn" type="button" value="Generate img Link"><input id="ehd_scbtn" type="button" value="Unlimited Scroll!"><input id="ehd_stopbtn" type="button" value="Stop At" disabled="disabled">

please wait, now:

';

      $('#i1')[0].insertBefore(buttons_wrapper, $('#i2')[0]);

      $("#ehd_dlbtn")[0].addEventListener('click', DLbtnHandler);
      $("#ehd_scbtn")[0].addEventListener('click', SCbtnHandler);
      $("#ehd_enlargebtn")[0].addEventListener('click', function (event) {
        if (event.target.value.match('Enlarge')) {
          try { unsafeWindow.onresize = null; } catch (e) { console.log(e); };
          $('#i1')[0].style.maxWidth = $('#i1')[0].style.maxWidth.toString().replace(/\D/g, '') * 2 + 'px';
          $('#i1')[0].style.width = $('#i1')[0].style.width.toString().replace(/\D/g, '') * 2 + 'px';
          event.target.setAttribute('value', 'Diminish');
        }
        else {
          try { unsafeWindow.onresize = unsafeWindow.update_window_extents; unsafeWindow.update_window_extents(); } catch (e) { console.log(e); };
          event.target.setAttribute('value', 'Enlarge');
        }
      });
      $("#ehd_stopbtn")[0].addEventListener('click', function (event) {
        event.target.setAttribute('disabled', 'disabled');
        var stopAt = parseInt(prompt('Stop at page:', e_hen_download.current.total), 10);
        if (isNaN(stopAt)) {
          alert('Not a number!');
          event.target.removeAttribute('disabled');
        }
        else {
          e_hen_download.settings.stopAt = stopAt;
        }
      })

    }
    else {
      setTimeout(init, 500);
    }
  }(document));

  function DLbtnHandler() {
    $('#ehd_btn input').forEach(function (e) { e.setAttribute('disabled', 'disabled') });
    $("#ehd_stopbtn")[0].removeAttribute('disabled');
    $("#ehd_enlargebtn")[0].removeAttribute('disabled');
    $('#ehd_output')[0].style.display = 'block';

    GetHtml(DLout);
  };

  function DLout(html) {
      var c = e_hen_download.current,
          s = e_hen_download.settings,

      parseResult = parse(html);

      $('#ehd_output')[0].innerHTML += '' + parseResult.filename + ' ';

      $('#ehd_now')[0].innerHTML = c.current + '/' + c.total;

      if (c.current >= c.total || c.current >= s.stopAt) $('#ehd_status')[0].innerHTML = 'Done!';
      else setTimeout(function () {
        GetHtml(DLout);
      }, s.getNextPageInterval);
  }

  function SCbtnHandler() {
    $('#ehd_btn input').forEach(function (e) { e.setAttribute('disabled', 'disabled') });
    $("#ehd_stopbtn")[0].removeAttribute('disabled');
    $("#ehd_enlargebtn")[0].removeAttribute('disabled');
    $('#ehd_output')[0].style.display = 'block';
    $('#i3 a')[0].style.display =  'none';

    GetHtml(SCout);
  };

  function SCout(html, url) {
    var c = e_hen_download.current,
        s = e_hen_download.settings,
        img_node = document.createElement('a');

    parseResult = parse(html, url);

    img_node.setAttribute('href', 'javascript:;');
    img_node.innerHTML = '';

    img_node.dataset.failnl = parseResult.failnl;
    img_node.dataset.currentUrl = parseResult.currentUrl;
    img_node.dataset.locked = 'false';

    img_node.addEventListener('click', FailLoad);
    img_node.childNodes[0].addEventListener('error', FailLoad);

    $('#i3')[0].appendChild(img_node);

    $('#ehd_now')[0].innerHTML = c.current + '/' + c.total;

    if(c.current >= c.total || c.current >= s.stopAt) $('#ehd_status')[0].innerHTML = 'Done!';
    else setTimeout(function () {
        GetHtml(SCout);
    }, s.getNextPageInterval);
  }

  function GetHtml(callback, current) {
    var c = current || e_hen_download.current;

    if(c.next) {
      GM_xmlhttpRequest({
        'method': 'GET',
        'url': c.next,

        'headers': {
          'User-Agent': navigator.userAgent,
          'Referer': c.currentUrl,
          'Cookie': document.cookie
        },

        'onload': function (xhr) {
          callback(xhr.responseText, xhr.finalUrl);
        },

        'onerror': function (e) {
          console.log(e);
        }
      });
    }
    else callback(document.body.innerHTML, document.location + '');
  }

  function FailLoad(event) {
    var e = event.target.parentNode,
        failnl = e.dataset.failnl,
        currentUrl = e.dataset.currentUrl,
        c = {
          'next': currentUrl + (currentUrl.indexOf('?') > -1 ? '&' : '?') + 'nl=' + failnl,
          'currentUrl': currentUrl
        };
console.log(event);
    if (e.dataset.locked === 'true') {
      return false;
    }

    e.dataset.locked = 'true';

    GetHtml(function (html, url) {
      var regex = /
([^ ]*) ::.*]*id="img"[^>]*src="([^"]*)"[^>]*style="([^"]*)".*onclick="return nl\('([0-9-]+)'\)/,
          parsed = html.match(regex),
          result;

      if(parsed) {
        result = {
          'filename': parsed[1],
          'src': parsed[2],
          'style': parsed[3],
          'failnl': parsed[4],
          'currentUrl': url
        };

        e.innerHTML = '';

        e.dataset.failnl = result.failnl;
        e.dataset.currentUrl = result.currentUrl;
        e.dataset.locked = 'false';
      }
    }, c);
  }

  function parse(html, currentUrl) {
    var c = e_hen_download.current,
        regex = /(\d+)<\/span> \/ (\d+)<\/span>.*
([^ ]*) ::.*]*href="([^"]*)">]*src="([^"]*)"[^>]*style="([^"]*)".*onclick="return nl\('([0-9-]+)'\)/,
        parsed = html.match(regex),
        result;

    if (parsed) {
      c.current = parseInt(parsed[1], 10);
      c.total = parseInt(parsed[2], 10);
      c.next = parsed[4];
      c.currentUrl = currentUrl;

      result = {
        'filename': parsed[3],
        'src': parsed[5],
        'style': parsed[6],
        'failnl': parsed[7],
        'currentUrl': currentUrl
      };
    }

    return result;
  }

}(document));<|endoftext|>


<commit_before>import WebGPUUniformsGroup from './WebGPUUniformsGroup.js';
import { FloatUniform, Vector3Uniform } from './WebGPUUniform.js';

import NodeSlot from '../nodes/core/NodeSlot.js';
import NodeBuilder from '../nodes/core/NodeBuilder.js';

class WebGPUNodeUniformsGroup extends WebGPUUniformsGroup {

	constructor( shaderStage ) {

		super( 'nodeUniforms' );

		let shaderStageVisibility;

		if ( shaderStage === 'vertex' ) shaderStageVisibility = GPUShaderStage.VERTEX;
		else if ( shaderStage === 'fragment' ) shaderStageVisibility = GPUShaderStage.FRAGMENT;

		this.setVisibility( shaderStageVisibility );

		//this.setOnBeforeUpdate( this._onBeforeUpdate );

	}
	/*
	_onBeforeUpdate( object, camera ) {

		const material = object.material;

	}
	*/

}

class WebGPUNodeBuilder extends NodeBuilder {

	constructor( material, renderer ) {

		super( material, renderer );

		this.uniformsGroup = {};

		this._parseMaterial();

	}

	_parseMaterial() {

		const material = this.material;

		if ( material.isMeshBasicMaterial || material.isPointsMaterial ) {

			if ( material.colorNode !== undefined ) {

				this.addSlot( 'fragment', new NodeSlot( material.colorNode, 'COLOR', 'vec3' ) );

			}

			if ( material.opacityNode !== undefined ) {

				this.addSlot( 'fragment', new NodeSlot( material.opacityNode, 'OPACITY', 'float' ) );

			}

		}

	}

	getUniformNSName( nodeUniform ) {

		return `nodeUniforms.${nodeUniform.name}`;

	}

	getBindings() {

		const bindings = [];

		const uniformsVertexGroup = this.uniformsGroup[ 'vertex' ];
		const uniformsFragmentGroup = this.uniformsGroup[ 'fragment' ];

		if ( uniformsVertexGroup ) bindings.push( uniformsVertexGroup );
		if ( uniformsFragmentGroup ) bindings.push( uniformsFragmentGroup );

		return bindings;

	}

	getUniformFromNode( node, shaderStage, type ) {

		const uniformNode = super.getUniformFromNode( node, shaderStage, type );
		const nodeData = this.getDataFromNode( node, shaderStage );

		if ( nodeData.uniformGroup === undefined ) {

			let uniformsGroup = this.uniformsGroup[ shaderStage ];

			if ( uniformsGroup === undefined ) {

				uniformsGroup = new WebGPUNodeUniformsGroup( shaderStage );

				this.uniformsGroup[ shaderStage ] = uniformsGroup;

			}

			let uniform;

			if ( type === 'float' ) {

				uniform = new FloatUniform( uniformNode.name, uniformNode.value );

			} else if ( type === 'vec3' ) {

				uniform = new Vector3Uniform( uniformNode.name, uniformNode.value );

			} else {

				console.error( `Uniform "${type}" not declared.` );

			}

			uniformsGroup.addUniform( uniform );

			nodeData.uniform = uniform;

		}

		return uniformNode;

	}

	buildShader( shaderStage, code ) {

		// use regex maybe for security?
		const versionStrIndex = code.indexOf( "\n" );

		let finalCode = code.substr( 0, versionStrIndex ) + "\n\n";

		const shaderCodes = this.build( shaderStage );

		finalCode += shaderCodes.defines;

		finalCode += code.substr( versionStrIndex );

		return finalCode;

	}

	parse( vertexShader, fragmentShader ) {

		vertexShader = this.buildShader( 'vertex', vertexShader );
		fragmentShader = this.buildShader( 'fragment', fragmentShader );

		return {
			vertexShader,
			fragmentShader
		};

	}

}

export default WebGPUNodeBuilder;
<commit_msg>fix rename https://github.com/mrdoob/three.js/pull/20421/commits/6793b34c144dcc533d8be9d9f76bf31ce5d88547<commit_after>import WebGPUUniformsGroup from './WebGPUUniformsGroup.js';
import { FloatUniform, Vector3Uniform } from './WebGPUUniform.js';

import NodeSlot from '../nodes/core/NodeSlot.js';
import NodeBuilder from '../nodes/core/NodeBuilder.js';

class WebGPUNodeUniformsGroup extends WebGPUUniformsGroup {

	constructor( shaderStage ) {

		super( 'nodeUniforms' );

		let shaderStageVisibility;

		if ( shaderStage === 'vertex' ) shaderStageVisibility = GPUShaderStage.VERTEX;
		else if ( shaderStage === 'fragment' ) shaderStageVisibility = GPUShaderStage.FRAGMENT;

		this.setVisibility( shaderStageVisibility );

		//this.setOnBeforeUpdate( this._onBeforeUpdate );

	}
	/*
	_onBeforeUpdate( object, camera ) {

		const material = object.material;

	}
	*/

}

class WebGPUNodeBuilder extends NodeBuilder {

	constructor( material, renderer ) {

		super( material, renderer );

		this.uniformsGroup = {};

		this._parseMaterial();

	}

	_parseMaterial() {

		const material = this.material;

		if ( material.isMeshBasicMaterial || material.isPointsMaterial ) {

			if ( material.colorNode !== undefined ) {

				this.addSlot( 'fragment', new NodeSlot( material.colorNode, 'COLOR', 'vec3' ) );

			}

			if ( material.opacityNode !== undefined ) {

				this.addSlot( 'fragment', new NodeSlot( material.opacityNode, 'OPACITY', 'float' ) );

			}

		}

	}

	getUniformNSName( nodeUniform ) {

		return `nodeUniforms.${nodeUniform.name}`;

	}

	getBindings() {

		const bindings = [];

		const uniformsVertexGroup = this.uniformsGroup[ 'vertex' ];
		const uniformsFragmentGroup = this.uniformsGroup[ 'fragment' ];

		if ( uniformsVertexGroup ) bindings.push( uniformsVertexGroup );
		if ( uniformsFragmentGroup ) bindings.push( uniformsFragmentGroup );

		return bindings;

	}

	getUniformFromNode( node, shaderStage, type ) {

		const uniformNode = super.getUniformFromNode( node, shaderStage, type );
		const nodeData = this.getDataFromNode( node, shaderStage );

		if ( nodeData.uniform === undefined ) {

			let uniformsGroup = this.uniformsGroup[ shaderStage ];

			if ( uniformsGroup === undefined ) {

				uniformsGroup = new WebGPUNodeUniformsGroup( shaderStage );

				this.uniformsGroup[ shaderStage ] = uniformsGroup;

			}

			let uniform;

			if ( type === 'float' ) {

				uniform = new FloatUniform( uniformNode.name, uniformNode.value );

			} else if ( type === 'vec3' ) {

				uniform = new Vector3Uniform( uniformNode.name, uniformNode.value );

			} else {

				console.error( `Uniform "${type}" not declared.` );

			}

			uniformsGroup.addUniform( uniform );

			nodeData.uniform = uniform;

		}

		return uniformNode;

	}

	buildShader( shaderStage, code ) {

		// use regex maybe for security?
		const versionStrIndex = code.indexOf( "\n" );

		let finalCode = code.substr( 0, versionStrIndex ) + "\n\n";

		const shaderCodes = this.build( shaderStage );

		finalCode += shaderCodes.defines;

		finalCode += code.substr( versionStrIndex );

		return finalCode;

	}

	parse( vertexShader, fragmentShader ) {

		vertexShader = this.buildShader( 'vertex', vertexShader );
		fragmentShader = this.buildShader( 'fragment', fragmentShader );

		return {
			vertexShader,
			fragmentShader
		};

	}

}

export default WebGPUNodeBuilder;
<|endoftext|>


<commit_before>/**
 * Interactive map for place list.
 */

var Backbone = require('backbone');
var Leaflet = require('leaflet');

var Place = require('../../models/place');
var PlaceList = require('../../collections/place-list');

Leaflet.Icon.Default.imagePath = '/img/leaflet';

var PlaceRow = Backbone.View.extend({

    events: {
        'mouseenter': 'activate',
        'mouseleave': 'deactivate',
    },

    initialize: function () {
        this.listenTo(this.model, 'change:active', this.updateActive);
    },

    updateActive: function () {
        if (this.model.get('active')) {
            this.$el.addClass('active');
        } else {
            this.$el.removeClass('active');
        }
    },

    activate: function () {
        this.model.set('active', true);
        this.trigger('activate', this);
    },

    deactivate: function () {
        this.model.set('active', false);
    },

    scrollTo: function () {
        $('#place-list').scrollTo(this.el, 300, {offset: -80});
    }

});

var PlaceMarker = Backbone.View.extend({

    initialize: function () {
        var lat = this.model.get('latitude');
        var lng = this.model.get('longitude');

        if (lat && lng) {
            this.marker = Leaflet.marker([lat, lng]).bindPopup('' + this.model.get('name') + '');
            this.marker.on('click', this.activate, this);
        }

        this.listenTo(this.model, 'change:active', this.closePopup);
    },

    activate: function () {
        this.model.set('active', true);
        this.trigger('activate', this);
    },

    openPopup: function () {
        if (this.marker) {
            this.marker.openPopup();
        }
    },

    closePopup: function () {
        if (this.marker && !this.model.get('active')) {
            this.marker.closePopup();
        }
    }

});

module.exports = Backbone.View.extend({

    initialize: function (options) {
        _.extend(this, _.pick(options, 'latitude', 'longitude'));

        if (!this.latitude || !this.longitude) {
            this.latitude = this.$('#place-map').data('latitude');
            this.longitude = this.$('#place-map').data('longitude');
        }

        this.map = Leaflet.map('place-map').setView([this.latitude, this.longitude], 13);

        this.tile = Leaflet.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors',
            detectRetina: true,
        }).addTo(this.map);

        this.collection = new PlaceList();

        var that = this;

        this.$('#place-list article').each(function () {
            var model = new Place($(this).data('model'));

            var placeRow = new PlaceRow({el: this, model: model});

            var placeMarker = new PlaceMarker({model: model});

            if (placeMarker.marker) {
                placeMarker.marker.addTo(that.map);
            }

            that.collection.add(model);

            that.listenTo(placeRow, 'activate', that.activateRow);

            that.listenTo(placeMarker, 'activate', that.activateMarker);

            placeMarker.listenTo(placeRow, 'activate', placeMarker.openPopup);

            placeRow.listenTo(placeMarker, 'activate', placeRow.scrollTo);
        });
    },

    activateRow: function (placeRow) {
        var lat = placeRow.model.get('latitude');
        var lng = placeRow.model.get('longitude');
        if (lat && lng) {
            this.map.setView([lat, lng]);
        }
        this.collection.each(function (m) {
            if (m != placeRow.model) {
                m.set('active', false);
            }
        });
    },

    activateMarker: function (placeMarker) {
        this.collection.each(function (m) {
            if (m != placeMarker.model) {
                m.set('active', false);
            }
        });
    },
});
<commit_msg>Replace OpenStreetMap with Mapbox tiles #87<commit_after>/**
 * Interactive map for place list.
 */

var Backbone = require('backbone');
var Leaflet = require('leaflet');

var Place = require('../../models/place');
var PlaceList = require('../../collections/place-list');

Leaflet.Icon.Default.imagePath = '/img/leaflet';

var PlaceRow = Backbone.View.extend({

    events: {
        'mouseenter': 'activate',
        'mouseleave': 'deactivate',
    },

    initialize: function () {
        this.listenTo(this.model, 'change:active', this.updateActive);
    },

    updateActive: function () {
        if (this.model.get('active')) {
            this.$el.addClass('active');
        } else {
            this.$el.removeClass('active');
        }
    },

    activate: function () {
        this.model.set('active', true);
        this.trigger('activate', this);
    },

    deactivate: function () {
        this.model.set('active', false);
    },

    scrollTo: function () {
        $('#place-list').scrollTo(this.el, 300, {offset: -80});
    }

});

var PlaceMarker = Backbone.View.extend({

    initialize: function () {
        var lat = this.model.get('latitude');
        var lng = this.model.get('longitude');

        if (lat && lng) {
            this.marker = Leaflet.marker([lat, lng]).bindPopup('' + this.model.get('name') + '');
            this.marker.on('click', this.activate, this);
        }

        this.listenTo(this.model, 'change:active', this.closePopup);
    },

    activate: function () {
        this.model.set('active', true);
        this.trigger('activate', this);
    },

    openPopup: function () {
        if (this.marker) {
            this.marker.openPopup();
        }
    },

    closePopup: function () {
        if (this.marker && !this.model.get('active')) {
            this.marker.closePopup();
        }
    }

});

module.exports = Backbone.View.extend({

    initialize: function (options) {
        _.extend(this, _.pick(options, 'latitude', 'longitude'));

        if (!this.latitude || !this.longitude) {
            this.latitude = this.$('#place-map').data('latitude');
            this.longitude = this.$('#place-map').data('longitude');
        }

        this.map = Leaflet.map('place-map').setView([this.latitude, this.longitude], 13);

        this.tile = Leaflet.tileLayer('https://api.mapbox.com/styles/v1/mapbox/streets-v10/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic2FudGFrYW5pIiwiYSI6ImNpcW02em1lZzAwMWpoeW5tdmRiOHh4MTcifQ.sE-MLInkW3KwjlwoaaKuAQ', {
            attribution: '© Mapbox © OpenStreetMap Improve this map',
            detectRetina: true,
        }).addTo(this.map);

        this.collection = new PlaceList();

        var that = this;

        this.$('#place-list article').each(function () {
            var model = new Place($(this).data('model'));

            var placeRow = new PlaceRow({el: this, model: model});

            var placeMarker = new PlaceMarker({model: model});

            if (placeMarker.marker) {
                placeMarker.marker.addTo(that.map);
            }

            that.collection.add(model);

            that.listenTo(placeRow, 'activate', that.activateRow);

            that.listenTo(placeMarker, 'activate', that.activateMarker);

            placeMarker.listenTo(placeRow, 'activate', placeMarker.openPopup);

            placeRow.listenTo(placeMarker, 'activate', placeRow.scrollTo);
        });
    },

    activateRow: function (placeRow) {
        var lat = placeRow.model.get('latitude');
        var lng = placeRow.model.get('longitude');
        if (lat && lng) {
            this.map.setView([lat, lng]);
        }
        this.collection.each(function (m) {
            if (m != placeRow.model) {
                m.set('active', false);
            }
        });
    },

    activateMarker: function (placeMarker) {
        this.collection.each(function (m) {
            if (m != placeMarker.model) {
                m.set('active', false);
            }
        });
    },
});
<|endoftext|>


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

  angular.module('favForm.directives').directive('favformSteps', FavFormSteps);

  function FavFormSteps () {
    return {
      restrict: 'E',
      scope: {
        steps: '@',
        selectedStep: '='
      },
      templateUrl: '/views/steps.html',
      controller: FavFormController,
      controllerAs: 'vm'
    };

    function FavFormController ($scope) {
      var vm = this;
      vm.stepsCompletion = [];

      vm.init = function () {
        var stepCompletion;

        for (var i = parseInt($scope.steps); i > 0; i--) {
          stepCompletion = {
            completion: 0,
            completed: false
          };

          vm.stepsCompletion.push(stepCompletion);
        }
      };

      vm.getFlexNumber = function (isLast) {
        return isLast ? 5 : 'auto';
      };

      vm.init();

      $scope.$on('fillInputCompletion', function (evts, completionStatus) {
        var completionPercentage = completionStatus.value;
        var step = completionStatus.step - 1;

        if (vm.stepsCompletion[step].completion < 100) {
          vm.stepsCompletion[step].completion += completionPercentage;
        }
      });

      $scope.$on('drainInputCompletion', function (evts, completionStatus) {
        var completionPercentage = completionStatus.value;
        var step = completionStatus.step - 1;

        if (vm.stepsCompletion[step].completion > 0) {
          vm.stepsCompletion[step].completion -= completionPercentage;
        }
      });

      $scope.$on('nextStep', function (evts) {
        if (vm.stepsCompletion[$scope.selectedStep].completion >= 100) {
          vm.stepsCompletion[$scope.selectedStep].completed = true;
        }
      });
    }
  }
})();
<commit_msg>Giving a better name to the steps.directive.js controller<commit_after>(function () {
  'use strict';

  angular.module('favForm.directives').directive('favformSteps', FavFormSteps);

  function FavFormSteps () {
    return {
      restrict: 'E',
      scope: {
        steps: '@',
        selectedStep: '='
      },
      templateUrl: '/views/steps.html',
      controller: FavFormController,
      controllerAs: 'vm'
    };

    function FavFormStepsController ($scope) {
      var vm = this;
      vm.stepsCompletion = [];

      vm.init = function () {
        var stepCompletion;

        for (var i = parseInt($scope.steps); i > 0; i--) {
          stepCompletion = {
            completion: 0,
            completed: false
          };

          vm.stepsCompletion.push(stepCompletion);
        }
      };

      vm.getFlexNumber = function (isLast) {
        return isLast ? 5 : 'auto';
      };

      vm.init();

      $scope.$on('fillInputCompletion', function (evts, completionStatus) {
        var completionPercentage = completionStatus.value;
        var step = completionStatus.step - 1;

        if (vm.stepsCompletion[step].completion < 100) {
          vm.stepsCompletion[step].completion += completionPercentage;
        }
      });

      $scope.$on('drainInputCompletion', function (evts, completionStatus) {
        var completionPercentage = completionStatus.value;
        var step = completionStatus.step - 1;

        if (vm.stepsCompletion[step].completion > 0) {
          vm.stepsCompletion[step].completion -= completionPercentage;
        }
      });

      $scope.$on('nextStep', function (evts) {
        if (vm.stepsCompletion[$scope.selectedStep].completion >= 100) {
          vm.stepsCompletion[$scope.selectedStep].completed = true;
        }
      });
    }
  }
})();
<|endoftext|>


<commit_before>// Copyright 2002-2015, University of Colorado Boulder

/**
 * Main entry point for PhET translation web app.
 */

// modules
var express = require( 'express' );
var https = require( 'https' );
var doT = require( 'express-dot' );
var LocaleInfo = require( __dirname + '/js/LocaleInfo' );
var TranslatableSimInfo = require( __dirname + '/js/TranslatableSimInfo' );

// constants
var LISTEN_PORT = 16372;

// Create and configure the ExpressJS app
var app = express();
app.set( 'views', __dirname + '/html/views' );
app.set( 'view engine', 'dot' );
app.engine( 'html', doT.__express );
app.use( '/translate/css', express.static( __dirname + '/public/css' ) );
app.use( '/translate/sim/css', express.static( __dirname + '/public/css' ) );
app.use( '/translate/img', express.static( __dirname + '/public/img' ) );
app.use( '/translate/js', express.static( __dirname + '/public/js' ) );
app.use( '/translate/sim/js', express.static( __dirname + '/public/js' ) );
app.use( '/translate/fonts', express.static( __dirname + '/public/fonts' ) );

//----------------------------------------------------------------------------
// Set up the routes
//----------------------------------------------------------------------------

// convenience function for presenting escaped HTML
function escapeHTML( s ) {
  return s.replace( /&/g, '&' )
    .replace( /"/g, '"' )
    .replace( /</g, '<' )
    .replace( />/g, '>' );
}

// need cookieParser middleware before we can do anything with cookies
app.use( express.cookieParser() );

// check for the presence of the PhET login cookie
app.get( '/translate/*', function( req, res, next ) {
  console.log( 'all cookies :' );
  for ( var k in req.cookies ) {
    if ( req.cookies.hasOwnProperty( k ) ) {
      console.log( "Key is " + k + ", value is: " + req.cookies[ k ] );
    }
  }
  console.log( '------------' );
  console.log( 'Checking for login cookie (bypassed for localhost)' );
  var cookie = req.cookies.JSESSIONID;
  //if ( req.get( 'host' ).indexOf( 'localhost' ) !== 0 && cookie === undefined ) {
  if ( cookie === undefined ) {
    // no: the user must log in
    console.log( 'session cookie not found, sending to login page' );
    console.log( 'host = ' + req.get( 'host' ) );
    console.log( 'req.url = ' + req.url );
    res.render( 'login-required.html', { title: 'Login Required', host: req.get( 'host' ), destinationUrl: req.url } );
  }
  else {
    // yes, cookie was present, go to the next route
    console.log( 'session cookie found, moving to next step' );
    next(); // send to next route
  }
} );

// Initial page for the translation utility
app.get( '/translate/', function( req, res, next ) {

  // Pull the username from the cookie
  var username = req.cookies[ 'sign-in-panel.sign-in-form.username' ] || 'Not logged in';

  res.render( 'translate-home.html', {
    title: 'PhET Translation Utility',
    simInfoArray: TranslatableSimInfo.simInfoArray,
    username: username
  } );
} );

// route for translating a specific sim to a specific language
app.get( '/translate/sim/:simName?/:targetLocale?', function( req, res ) {
  var simName = req.param( 'simName' );
  var targetLocale = req.param( 'targetLocale' );
  var path = '/phetsims/' + simName + '/master/strings/' + simName + '-strings_en.json';

  // Pull the English string data from github.
  https.get( { host: 'raw.githubusercontent.com', path: path }, function( response ) {
    response.on( 'data', function( data ) {

      if ( response.statusCode === 200 ) {
        // Parse the returned JSON data into a JavaScript object.
        strings = JSON.parse( data );

        // Create a table for the strings to be translated.
        //var stringsTable = '';
        //for ( var key in strings ) {
        //  if ( strings.hasOwnProperty( key ) ) {
        //    stringsTable += '
';
        //    stringsTable += '' + escapeHTML( strings[ key ] ) + '	';
        //    stringsTable += '<input type=\"text\" 	';
        //    stringsTable += '
';
        //  }
        //}

        // Create the strings array to pass in to the HTML template
        var englishStringsArray = [];
        for ( var key in strings ) {
          if ( strings.hasOwnProperty( key ) ) {
            englishStringsArray.push( {
              key: key,
              string: escapeHTML( strings[ key ] )
            } );
          }
        }

        // Pull the username from the cookie
        var username = req.cookies[ 'sign-in-panel.sign-in-form.username' ] || 'Not logged in';

        // Assemble the data that will be supplied to the template.
        var templateData = {
          title: "PhET Translation Utility",
          subtitle: "Please enter a translation for each English string:",
          destinationLanguage: LocaleInfo.localeToLanguageString( targetLocale ),
          englishStringsArray: englishStringsArray,
          simName: simName,
          simUrl: TranslatableSimInfo.getSimInfoByProjectName( simName ).testUrl,
          username: username
        };

        // Render the page.
        res.render( 'translate-sim.html', templateData );
      }
      else {
        res.send( 'Error: Sim data not found' );
      }
    } );
  } );
} );

app.get( '/*', function( req, res ) {
  res.send( '
Error: Page not found.  URL = ' + req.url + '
' );
} );

app.listen( LISTEN_PORT, function() { console.log( 'Listening on port ' + LISTEN_PORT ) } );
<commit_msg>Added the ability to get user info from server based on session cookie.  This is the first version that successfully retrieves the data.<commit_after>// Copyright 2002-2015, University of Colorado Boulder

/**
 * Main entry point for PhET translation web app.
 */

// modules
var express = require( 'express' );
var https = require( 'https' );
var http = require( 'http' );
var doT = require( 'express-dot' );
var LocaleInfo = require( __dirname + '/js/LocaleInfo' );
var TranslatableSimInfo = require( __dirname + '/js/TranslatableSimInfo' );

// constants
var LISTEN_PORT = 16372;

// Create and configure the ExpressJS app
var app = express();
app.set( 'views', __dirname + '/html/views' );
app.set( 'view engine', 'dot' );
app.engine( 'html', doT.__express );
app.use( '/translate/css', express.static( __dirname + '/public/css' ) );
app.use( '/translate/sim/css', express.static( __dirname + '/public/css' ) );
app.use( '/translate/img', express.static( __dirname + '/public/img' ) );
app.use( '/translate/js', express.static( __dirname + '/public/js' ) );
app.use( '/translate/sim/js', express.static( __dirname + '/public/js' ) );
app.use( '/translate/fonts', express.static( __dirname + '/public/fonts' ) );

//----------------------------------------------------------------------------
// Set up the routes
//----------------------------------------------------------------------------

// convenience function for presenting escaped HTML
function escapeHTML( s ) {
  return s.replace( /&/g, '&' )
    .replace( /"/g, '"' )
    .replace( /</g, '<' )
    .replace( />/g, '>' );
}

// need cookieParser middleware before we can do anything with cookies
app.use( express.cookieParser() );

// check for the presence of the PhET login cookie
app.get( '/translate/*', function( req, res, next ) {
  console.log( 'all cookies :' );
  for ( var k in req.cookies ) {
    if ( req.cookies.hasOwnProperty( k ) ) {
      console.log( "Key is " + k + ", value is: " + req.cookies[ k ] );
    }
  }
  console.log( '------------' );
  console.log( 'Checking for login cookie (bypassed for localhost)' );
  var cookie = req.cookies.JSESSIONID;
  console.log( 'headers: ' + JSON.stringify( req.headers ) );
  console.log( 'cookie: ' + cookie );
  if ( req.get( 'host' ).indexOf( 'localhost' ) !== 0 && cookie === undefined ) {
    // no: the user must log in
    console.log( 'session cookie not found, sending to login page' );
    console.log( 'host = ' + req.get( 'host' ) );
    console.log( 'req.url = ' + req.url );
    res.render( 'login-required.html', { title: 'Login Required', host: req.get( 'host' ), destinationUrl: req.url } );
  }
  else {
     // yes, session cookie was present, attempt to extract session information
/*
      return https.get({
        host: 'phet-dev.colorado.edu',
        path: '/check-login',
        headers: {
           'Cookie': 'JSESSIONID='+cookie
        }
    }, function(response) {
        var data = '';

        response.on('data', function(d) {
            console.log( '--> data, value = ' + d);

        });
        response.on('end', function() {
            console.log( '--> end' );
        });
        response.on('error', function() {
            console.log( '--> error' );
        });
    });
*/
    ///////////////////////////////////////////////
    var options = {
      host: 'phet-dev.colorado.edu',
      path: '/check-login',
      method: 'GET',
      headers: {
        'Cookie': 'JSESSIONID='+cookie
      }
    };

    callback = function(response) {
      var data = '';

      // another chunk of data has been recieved, so append it
      response.on('data', function (chunk) {
        data += chunk;
      });

      // the whole response has been recieved, so we just print it out here
      response.on('end', function () {
        console.log('data received: ' + data);
      });
    }

    var httpRequest = https.request(options, callback);
    console.log( 'request headers: ' + httpRequest.headers );
    console.log( 'temp: ' + httpRequest.cookie );
    httpRequest.end();
    ///////////////////////////////////////////////

    console.log( 'session cookie found, moving to next step' );
    next(); // send to next route
  }
} );

// Initial page for the translation utility
app.get( '/translate/', function( req, res, next ) {

  // Pull the username from the cookie
  var username = req.cookies[ 'sign-in-panel.sign-in-form.username' ] || 'Not logged in';

  res.render( 'translate-home.html', {
    title: 'PhET Translation Utility',
    simInfoArray: TranslatableSimInfo.simInfoArray,
    username: username
  } );
} );

// route for translating a specific sim to a specific language
app.get( '/translate/sim/:simName?/:targetLocale?', function( req, res ) {
  var simName = req.param( 'simName' );
  var targetLocale = req.param( 'targetLocale' );
  var path = '/phetsims/' + simName + '/master/strings/' + simName + '-strings_en.json';

  // Pull the English string data from github.
  https.get( { host: 'raw.githubusercontent.com', path: path }, function( response ) {
    response.on( 'data', function( data ) {

      if ( response.statusCode === 200 ) {
        // Parse the returned JSON data into a JavaScript object.
        strings = JSON.parse( data );

        // Create a table for the strings to be translated.
        //var stringsTable = '';
        //for ( var key in strings ) {
        //  if ( strings.hasOwnProperty( key ) ) {
        //    stringsTable += '
';
        //    stringsTable += '' + escapeHTML( strings[ key ] ) + '	';
        //    stringsTable += '<input type=\"text\" 	';
        //    stringsTable += '
';
        //  }
        //}

        // Create the strings array to pass in to the HTML template
        var englishStringsArray = [];
        for ( var key in strings ) {
          if ( strings.hasOwnProperty( key ) ) {
            englishStringsArray.push( {
              key: key,
              string: escapeHTML( strings[ key ] )
            } );
          }
        }

        // Pull the username from the cookie
        var username = req.cookies[ 'sign-in-panel.sign-in-form.username' ] || 'Not logged in';

        // Assemble the data that will be supplied to the template.
        var templateData = {
          title: "PhET Translation Utility",
          subtitle: "Please enter a translation for each English string:",
          destinationLanguage: LocaleInfo.localeToLanguageString( targetLocale ),
          englishStringsArray: englishStringsArray,
          simName: simName,
          simUrl: TranslatableSimInfo.getSimInfoByProjectName( simName ).testUrl,
          username: username
        };

        // Render the page.
        res.render( 'translate-sim.html', templateData );
      }
      else {
        res.send( 'Error: Sim data not found' );
      }
    } );
  } );
} );

app.get( '/*', function( req, res ) {
  res.send( '
Error: Page not found.  URL = ' + req.url + '
' );
} );

app.listen( LISTEN_PORT, function() { console.log( 'Listening on port ' + LISTEN_PORT ) } );
<|endoftext|>


<commit_before>import { Board } from '../board.js';
import { generateBombs } from '../bombs.js';
import { Events } from '../events.js';

function beginnerGame() {
    let $board = $('#table');
    $board.empty();
    $board.addClass('table-styles'); // added this class here because if it's static broke visually the minefield
    var smallBoard = new Board(9, 9);

    $board.append(smallBoard.createBoard());

    let numberBombs = 10;
    $('#display-bomb-number').html('Number of Bombs ' + numberBombs);
    let arrayOfBombs = generateBombs(smallBoard.numberElements, numberBombs);

    for (let bomb of arrayOfBombs) {
        bomb.bomb = true;
    }

    let events = new Events(); // created for events
    events.startTimer('game-time'); // starts the timer

    console.log(arrayOfBombs);

    $('button').on('click', function (ev) {

        if (ev.target.bomb) {
            var show = function showBombs() {
                for (var i = 0; i < arrayOfBombs.length; i++) {
                    arrayOfBombs[i].className += ' bomb';//not jquery object to use addClass
                }
            };
            show();
            alert("Game Over");
            events.stopTimer(); // stop the timer
        } else {
            let button = ev.target;
            let x = button.coordX;
            let y = button.coordY;

            function howManyBombsArroundClickedButton(x, y, smallBoard) {
                let counterBomb = 0;

                let yMoving;
                if (y === 0) {
                    yMoving = y;
                } else {
                    yMoving = y - 1;
                }
                function FindByAttributeValue(coordX, coordY, value, value2) {
                    let allElements = document.getElementsByTagName('button');
                    for (let i = 0; i < allElements.length; i++) {
                        if (allElements[i].coordX === value && allElements[i].coordY === value2) {

                            return allElements[i];
                        }
                    }
                }

                for (; yMoving <= y + 1 && yMoving < smallBoard.rows; yMoving++) {
                    let xMoving = x == 0 ? x : x - 1;
                    for (; xMoving <= x + 1 && xMoving < smallBoard.cols; xMoving++) {
                        let selEl = FindByAttributeValue('coordX', 'coordY', xMoving, yMoving);
                        if (selEl.bomb) {
                            counterBomb++;

                        }
                    }
                }

                return counterBomb;
            }

                let number = howManyBombsArroundClickedButton(x, y, smallBoard);
                let colors=['red','teal','brown','rebeccapurple','purple','darkgreen','green','navy'];
                ev.target.style.color=colors[number];

                ev.target.innerHTML=number;
            }
        }
    });

    $('button').on('contextmenu', function (ev) {
        let flag = $('<img>');
        flag.attr('src', '../../img/flag.png');
        flag.addClass('img');

        let $target = $(ev.target);
        ev.preventDefault();//don't show context menu

        if ($target.hasClass('flag')) {
            $target.removeClass('flag')
            numberBombs++;
            $('#display-bomb-number').html('Number of Bombs ' + numberBombs);
        } else {

            $target.addClass('flag');
            // $target.html('*');
            numberBombs--;
            $('#display-bomb-number').html('Number of Bombs ' + numberBombs);
        }

        //think to simplifie,duplicate on each controller
    });

    $(window).on('hashchange', function () {
        events.stopTimer(); // stop the timer when page is changed
    });
}

export { beginnerGame }

<commit_msg>} missing bug<commit_after>import { Board } from '../board.js';
import { generateBombs } from '../bombs.js';
import { Events } from '../events.js';

function beginnerGame() {
    let $board = $('#table');
    $board.empty();
    $board.addClass('table-styles'); // added this class here because if it's static broke visually the minefield
    var smallBoard = new Board(9, 9);

    $board.append(smallBoard.createBoard());

    let numberBombs = 10;
    $('#display-bomb-number').html('Number of Bombs ' + numberBombs);
    let arrayOfBombs = generateBombs(smallBoard.numberElements, numberBombs);

    for (let bomb of arrayOfBombs) {
        bomb.bomb = true;
    }

    let events = new Events(); // created for events
    events.startTimer('game-time'); // starts the timer

    console.log(arrayOfBombs);

    $('button').on('click', function (ev) {

        if (ev.target.bomb) {
            var show = function showBombs() {
                for (var i = 0; i < arrayOfBombs.length; i++) {
                    arrayOfBombs[i].className += ' bomb';//not jquery object to use addClass
                }
            };
            show();
            alert("Game Over");
            events.stopTimer(); // stop the timer
        } else {
            let button = ev.target;
            let x = button.coordX;
            let y = button.coordY;

            function howManyBombsArroundClickedButton(x, y, smallBoard) {
                let counterBomb = 0;

                let yMoving;
                if (y === 0) {
                    yMoving = y;
                } else {
                    yMoving = y - 1;
                }
                function FindByAttributeValue(coordX, coordY, value, value2) {
                    let allElements = document.getElementsByTagName('button');
                    for (let i = 0; i < allElements.length; i++) {
                        if (allElements[i].coordX === value && allElements[i].coordY === value2) {

                            return allElements[i];
                        }
                    }
                }

                for (; yMoving <= y + 1 && yMoving < smallBoard.rows; yMoving++) {
                    let xMoving = x == 0 ? x : x - 1;
                    for (; xMoving <= x + 1 && xMoving < smallBoard.cols; xMoving++) {
                        let selEl = FindByAttributeValue('coordX', 'coordY', xMoving, yMoving);
                        if (selEl.bomb) {
                            counterBomb++;

                        }
                    }
                }

                return counterBomb;
            }

                let number = howManyBombsArroundClickedButton(x, y, smallBoard);
                let colors=['red','teal','brown','rebeccapurple','purple','darkgreen','green','navy'];
                ev.target.style.color=colors[number];

                ev.target.innerHTML=number;
            }
    });

    $('button').on('contextmenu', function (ev) {
        let flag = $('<img>');
        flag.attr('src', '../../img/flag.png');
        flag.addClass('img');

        let $target = $(ev.target);
        ev.preventDefault();//don't show context menu

        if ($target.hasClass('flag')) {
            $target.removeClass('flag')
            numberBombs++;
            $('#display-bomb-number').html('Number of Bombs ' + numberBombs);
        } else {

            $target.addClass('flag');
            // $target.html('*');
            numberBombs--;
            $('#display-bomb-number').html('Number of Bombs ' + numberBombs);
        }

        //think to simplifie,duplicate on each controller
    });

    $(window).on('hashchange', function () {
        events.stopTimer(); // stop the timer when page is changed
    });
}

export { beginnerGame }

<|endoftext|>


<commit_before>'use strict';
/*globals SockJS*/

/**
 * Minimum viable SockJS client. This function is stringified and written in
 * to our client side library.
 *
 * @runat client
 * @api private
 */
module.exports = function client() {
  var primus = this
    , socket;

  //
  // Selects an available Engine.IO factory.
  //
  var Factory = (function Factory() {
    if ('undefined' !== typeof SockJS) return SockJS;

    try { return Primus.require('sockjs-client-node'); }
    catch (e) {}

    return undefined;
  })();

  if (!Factory) return primus.critical(new Error('Missing required `sockjs-client-node` module. Please run `npm install --save sockjs-client-node`'));

  //
  // Connect to the given URL.
  //
  primus.on('outgoing::open', function opening() {
    if (socket) socket.close();

    primus.socket = socket = new Factory(
      primus.uri({ protocol: 'http' }),
      null,
      primus.merge(primus.transport, {
      info: {
        websocket: !primus.AVOID_WEBSOCKETS
      }
    }));

    //
    // Setup the Event handlers.
    //
    socket.onopen = primus.emits('open');
    socket.onerror = primus.emits('error');
    socket.onclose = function (e) {
      var event = e && e.code === 1002 ? 'error' : 'end';

      //
      // The timeout replicates the behaviour of primus.emits so we're not
      // affected by any timing bugs.
      //
      setTimeout(function timeout() {
        primus.emit('incoming::'+ event, e);
      }, 0);
    };
    socket.onmessage = primus.emits('data', function parse(evt) {
      return evt.data;
    });
  });

  //
  // We need to write a new message to the socket.
  //
  primus.on('outgoing::data', function write(message) {
    if (socket) socket.send(message);
  });

  //
  // Attempt to reconnect the socket. It assumes that the `outgoing::end` event is
  // called if it failed to disconnect.
  //
  primus.on('outgoing::reconnect', function reconnect() {
    if (socket) primus.emit('outgoing::end');
    primus.emit('outgoing::open');
  });

  //
  // We need to close the socket.
  //
  primus.on('outgoing::end', function close() {
    if (socket) {
      socket.close();
      socket = null;
    }
  });
};
<commit_msg>[fix] Simular to #117 but this completely disables the use of the xdomainrequest<commit_after>'use strict';
/*globals SockJS*/

/**
 * Minimum viable SockJS client. This function is stringified and written in
 * to our client side library.
 *
 * @runat client
 * @api private
 */
module.exports = function client() {
  var primus = this
    , socket;

  //
  // Selects an available Engine.IO factory.
  //
  var Factory = (function Factory() {
    if ('undefined' !== typeof SockJS) return SockJS;

    try { return Primus.require('sockjs-client-node'); }
    catch (e) {}

    return undefined;
  })();

  if (!Factory) return primus.critical(new Error('Missing required `sockjs-client-node` module. Please run `npm install --save sockjs-client-node`'));

  //
  // Connect to the given URL.
  //
  primus.on('outgoing::open', function opening() {
    if (socket) socket.close();

    primus.socket = socket = new Factory(
      primus.uri({ protocol: 'http' }),
      null,
      primus.merge(primus.transport, {
      info: {
        websocket: !primus.AVOID_WEBSOCKETS,  // Prevent WebSocket crashes
        cookie_needed: true                   // Disables xdomainrequest bugs
      }
    }));

    //
    // Setup the Event handlers.
    //
    socket.onopen = primus.emits('open');
    socket.onerror = primus.emits('error');
    socket.onclose = function (e) {
      var event = e && e.code === 1002 ? 'error' : 'end';

      //
      // The timeout replicates the behaviour of primus.emits so we're not
      // affected by any timing bugs.
      //
      setTimeout(function timeout() {
        primus.emit('incoming::'+ event, e);
      }, 0);
    };
    socket.onmessage = primus.emits('data', function parse(evt) {
      return evt.data;
    });
  });

  //
  // We need to write a new message to the socket.
  //
  primus.on('outgoing::data', function write(message) {
    if (socket) socket.send(message);
  });

  //
  // Attempt to reconnect the socket. It assumes that the `outgoing::end` event is
  // called if it failed to disconnect.
  //
  primus.on('outgoing::reconnect', function reconnect() {
    if (socket) primus.emit('outgoing::end');
    primus.emit('outgoing::open');
  });

  //
  // We need to close the socket.
  //
  primus.on('outgoing::end', function close() {
    if (socket) {
      socket.close();
      socket = null;
    }
  });
};
<|endoftext|>


<commit_before>var Properties = function ( editor ) {

	var container = new UI.Panel();

	// signals

	var signals = editor.signals;

	var selected = null;
	var values;

	editor.signals.elementSelected.add( function ( element ) {

		container.clear();

		selected = element;
		values = {};

		var elementPanel = new UI.Panel();
		container.add( elementPanel );

		elementPanel.add( new UI.Text( element.name ).setWidth( '90px' ).setId( 'name' ) );
		elementPanel.add( new UI.HorizontalRule() );

		var parameters = element.module.parameters;

		for ( var key in parameters ) {

			var parameter = parameters[ key ];

			if ( parameter === null ) continue;

			var parameterRow = new UI.Panel();
			parameterRow.add( new UI.Text( parameter.name ).setWidth( '90px' ) );

			( function ( key ) {

				if ( parameter instanceof FRAME.ModuleParameter.Boolean ) {

					var parameterValue = new UI.Checkbox()
						.setValue( element.parameters[ key ] )
						.onChange( function () {

							element.parameters[ key ] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( parameterValue );

					values[ key ] = parameterValue;

				} else if ( parameter instanceof FRAME.ModuleParameter.Integer ) {

					var parameterValue = new UI.Integer()
						.setRange( parameter.min, parameter.max )
						.setValue( element.parameters[ key ] )
						.setWidth( '150px' )
						.onChange( function () {

							element.parameters[ key ] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( parameterValue );

					values[ key ] = parameterValue;

				} else if ( parameter instanceof FRAME.ModuleParameter.Float ) {

					var parameterValue = new UI.Number()
						.setRange( parameter.min, parameter.max )
						.setValue( element.parameters[ key ] )
						.setWidth( '150px' )
						.onChange( function () {

							element.parameters[ key ] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( parameterValue );

					values[ key ] = parameterValue;

				} else if ( parameter instanceof FRAME.ModuleParameter.Vector2 ) {

					var vectorX = new UI.Number()
						.setValue( element.parameters[ key ][1] )
						.setWidth( '50px' )
						.onChange( function () {

							element.parameters[ key ][0] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					var vectorY = new UI.Number()
						.setValue( element.parameters[ key ][1] )
						.setWidth( '50px' )
						.onChange( function () {

							element.parameters[ key ][1] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( vectorX );
					parameterRow.add( vectorY );

				} else if ( parameter instanceof FRAME.ModuleParameter.Vector3 ) {

					var vectorX = new UI.Number()
						.setValue( element.parameters[ key ][1] )
						.setWidth( '50px' )
						.onChange( function () {

							element.parameters[ key ][0] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					var vectorY = new UI.Number()
						.setValue( element.parameters[ key ][1] )
						.setWidth( '50px' )
						.onChange( function () {

							element.parameters[ key ][1] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					var vectorZ = new UI.Number()
						.setValue( element.parameters[ key ][2] )
						.setWidth( '50px' )
						.onChange( function () {

							element.parameters[ key ][2] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( vectorX );
					parameterRow.add( vectorY );
					parameterRow.add( vectorZ );

				} else if ( parameter instanceof FRAME.ModuleParameter.String ) {

					var parameterValue = new UI.Input()
						.setValue( element.parameters[ key ] )
						.setWidth( '150px' )
						.onKeyUp( function () {

							element.parameters[ key ] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( parameterValue );

				} else if ( parameter instanceof FRAME.ModuleParameter.Color ) {

					var parameterValue = new UI.Color()
						.setHexValue( element.parameters[ key ] )
						.setWidth( '150px' )
						.onChange( function () {

							element.parameters[ key ] = this.getHexValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( parameterValue );

				}

			} )( key );

			elementPanel.add( parameterRow );

		};

	} );

	editor.signals.timeChanged.add( function () {

		if ( selected !== null ) {

			var element = selected;

			for ( var key in values ) {

				values[ key ].setValue( element.parameters[ key] );

			}

		}

	} );

	return container;

}
<commit_msg>Fixed Properties Vector2 and Vector3 handling.<commit_after>var Properties = function ( editor ) {

	var container = new UI.Panel();

	// signals

	var signals = editor.signals;

	var selected = null;
	var values;

	editor.signals.elementSelected.add( function ( element ) {

		container.clear();

		selected = element;
		values = {};

		var elementPanel = new UI.Panel();
		container.add( elementPanel );

		elementPanel.add( new UI.Text( element.name ).setWidth( '90px' ).setId( 'name' ) );
		elementPanel.add( new UI.HorizontalRule() );

		var parameters = element.module.parameters;

		for ( var key in parameters ) {

			var parameter = parameters[ key ];

			if ( parameter === null ) continue;

			var parameterRow = new UI.Panel();
			parameterRow.add( new UI.Text( parameter.name ).setWidth( '90px' ) );

			( function ( key ) {

				if ( parameter instanceof FRAME.ModuleParameter.Boolean ) {

					var parameterValue = new UI.Checkbox()
						.setValue( element.parameters[ key ] )
						.onChange( function () {

							element.parameters[ key ] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( parameterValue );

					values[ key ] = parameterValue;

				} else if ( parameter instanceof FRAME.ModuleParameter.Integer ) {

					var parameterValue = new UI.Integer()
						.setRange( parameter.min, parameter.max )
						.setValue( element.parameters[ key ] )
						.setWidth( '150px' )
						.onChange( function () {

							element.parameters[ key ] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( parameterValue );

					values[ key ] = parameterValue;

				} else if ( parameter instanceof FRAME.ModuleParameter.Float ) {

					var parameterValue = new UI.Number()
						.setRange( parameter.min, parameter.max )
						.setValue( element.parameters[ key ] )
						.setWidth( '150px' )
						.onChange( function () {

							element.parameters[ key ] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( parameterValue );

					values[ key ] = parameterValue;

				} else if ( parameter instanceof FRAME.ModuleParameter.Vector2 ) {

					var vectorX = new UI.Number()
						.setValue( element.parameters[ key ][0] )
						.setWidth( '50px' )
						.onChange( function () {

							element.parameters[ key ][0] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					var vectorY = new UI.Number()
						.setValue( element.parameters[ key ][1] )
						.setWidth( '50px' )
						.onChange( function () {

							element.parameters[ key ][1] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( vectorX );
					parameterRow.add( vectorY );

				} else if ( parameter instanceof FRAME.ModuleParameter.Vector3 ) {

					var vectorX = new UI.Number()
						.setValue( element.parameters[ key ][0] )
						.setWidth( '50px' )
						.onChange( function () {

							element.parameters[ key ][0] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					var vectorY = new UI.Number()
						.setValue( element.parameters[ key ][1] )
						.setWidth( '50px' )
						.onChange( function () {

							element.parameters[ key ][1] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					var vectorZ = new UI.Number()
						.setValue( element.parameters[ key ][2] )
						.setWidth( '50px' )
						.onChange( function () {

							element.parameters[ key ][2] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( vectorX );
					parameterRow.add( vectorY );
					parameterRow.add( vectorZ );

				} else if ( parameter instanceof FRAME.ModuleParameter.String ) {

					var parameterValue = new UI.Input()
						.setValue( element.parameters[ key ] )
						.setWidth( '150px' )
						.onKeyUp( function () {

							element.parameters[ key ] = this.getValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( parameterValue );

				} else if ( parameter instanceof FRAME.ModuleParameter.Color ) {

					var parameterValue = new UI.Color()
						.setHexValue( element.parameters[ key ] )
						.setWidth( '150px' )
						.onChange( function () {

							element.parameters[ key ] = this.getHexValue();
							signals.timelineElementChanged.dispatch( element );

						} );

					parameterRow.add( parameterValue );

				}

			} )( key );

			elementPanel.add( parameterRow );

		};

	} );

	editor.signals.timeChanged.add( function () {

		if ( selected !== null ) {

			var element = selected;

			for ( var key in values ) {

				values[ key ].setValue( element.parameters[ key] );

			}

		}

	} );

	return container;

}
<|endoftext|>


<commit_before>'use strict';

var PrimusError = require('../../errors').PrimusError;

/**
 * Minimum viable WebSocket server for Node.js that works through the Primus
 * interface.
 *
 * @runat server
 * @api private
 */
module.exports = function server() {
  var Engine = require('socket.io').Manager
    , Spark = this.Spark
    , primus = this.primus;

  //
  // Socket.IO is not, and will never be supported as long as it's using
  // Engine.IO.
  //
  if ('function' !== typeof Engine) {
    [
      '',
      'We\'ve detected that you are using Socket.IO 1.x',
      'This version is not supported as it\'s just a layer on top of Engine.IO.',
      'It\'s much more efficient to use Engine.IO directly as all features of Socket.IO',
      'are already available in Primus and it\'s more stable due to our extra patches.',
      '',
      'Either run `npm install --save engine.io` or `npm install --save socket.io@0.9.x`',
      '',
      'See https://github.com/primus/primus#socketio for more information.',
      ''
    ].forEach(function each(line) {
      console.error('Primus: '+ line);
    });
    throw new PrimusError('Unsupported Socket.IO version', primus);
  }

  //
  // Listen to upgrade requests.
  //
  var service = this.service = new Engine(this, {
    'resource': primus.pathname,

    //
    // This is a security feature of Socket.IO which was build to prevent people
    // from spamming your server with data. But as outlined in
    // LearnBoost/socket.io#1519 they forgot to clear the internal _dataLength
    // property. So long running connections or sending frequent data will
    // result in to random disconnects. Setting this property to infinity solves
    // the disconnects for now..
    //
    'destroy buffer size': Infinity,

    //
    // Don't destroy upgrades, this should be handled by Primus so it can return
    // a human readable response.
    //
    'destroy upgrade': false,

    //
    // We're not serving the Socket.IO client, disable this.
    //
    'browser client': false,

    //
    // Use our own custom logger instance so we can emit `log` events instead of
    // writing/spamming terminals.
    //
    'logger': this.logger
  });

  //
  // We've received a new connection, create a new Spark. The Spark will
  // automatically announce it self as a new connection once it's created (after
  // the next tick).
  //
  this.service.on('connection', function connection(socket) {
    var spark = new Spark(
        socket.handshake.headers                  // HTTP request headers.
      , socket.handshake                          // IP address location.
      , socket.handshake.query                    // Optional query string.
      , socket.id                                 // Unique connection id.
      , service.transports[socket.id].req         // Reference to an HTTP req.
    );

    spark.on('outgoing::end', function end() {
      if (socket) socket.disconnect();
    }).on('outgoing::data', function write(data) {
      socket.send(data);
    });

    socket.on('message', spark.emits('incoming::data'));
    socket.on('error', spark.emits('incoming::error'));
    socket.on('disconnect', spark.emits('incoming::end', function parser() {
      socket.removeAllListeners();
      socket = null;
    }));
  });

  this.once('close', function close() {
    service.sockets.clients().forEach(function shutdown(socket) {
      socket.disconnect();
    });

    service.store.destroy();
    service.store.removeAllListeners();
  });
};
<commit_msg>[fix] Set client-store-expire option to 0 for socket.io<commit_after>'use strict';

var PrimusError = require('../../errors').PrimusError;

/**
 * Minimum viable WebSocket server for Node.js that works through the Primus
 * interface.
 *
 * @runat server
 * @api private
 */
module.exports = function server() {
  var Engine = require('socket.io').Manager
    , Spark = this.Spark
    , primus = this.primus;

  //
  // Socket.IO is not, and will never be supported as long as it's using
  // Engine.IO.
  //
  if ('function' !== typeof Engine) {
    [
      '',
      'We\'ve detected that you are using Socket.IO 1.x',
      'This version is not supported as it\'s just a layer on top of Engine.IO.',
      'It\'s much more efficient to use Engine.IO directly as all features of Socket.IO',
      'are already available in Primus and it\'s more stable due to our extra patches.',
      '',
      'Either run `npm install --save engine.io` or `npm install --save socket.io@0.9.x`',
      '',
      'See https://github.com/primus/primus#socketio for more information.',
      ''
    ].forEach(function each(line) {
      console.error('Primus: '+ line);
    });
    throw new PrimusError('Unsupported Socket.IO version', primus);
  }

  //
  // Listen to upgrade requests.
  //
  var service = this.service = new Engine(this, {
    'resource': primus.pathname,

    //
    // This is a security feature of Socket.IO which was build to prevent people
    // from spamming your server with data. But as outlined in
    // LearnBoost/socket.io#1519 they forgot to clear the internal _dataLength
    // property. So long running connections or sending frequent data will
    // result in to random disconnects. Setting this property to infinity solves
    // the disconnects for now..
    //
    'destroy buffer size': Infinity,

    //
    // Don't destroy upgrades, this should be handled by Primus so it can return
    // a human readable response.
    //
    'destroy upgrade': false,

    //
    // We're not serving the Socket.IO client, disable this.
    //
    'browser client': false,

    //
    // Use our own custom logger instance so we can emit `log` events instead of
    // writing/spamming terminals.
    //
    'logger': this.logger,

    //
    // Set client store expiration to 0 for consistency with other
    // transformers.
    //
    'client store expiration': 0
  });

  //
  // We've received a new connection, create a new Spark. The Spark will
  // automatically announce it self as a new connection once it's created (after
  // the next tick).
  //
  this.service.on('connection', function connection(socket) {
    var spark = new Spark(
        socket.handshake.headers                  // HTTP request headers.
      , socket.handshake                          // IP address location.
      , socket.handshake.query                    // Optional query string.
      , socket.id                                 // Unique connection id.
      , service.transports[socket.id].req         // Reference to an HTTP req.
    );

    spark.on('outgoing::end', function end() {
      if (socket) socket.disconnect();
    }).on('outgoing::data', function write(data) {
      socket.send(data);
    });

    socket.on('message', spark.emits('incoming::data'));
    socket.on('error', spark.emits('incoming::error'));
    socket.on('disconnect', spark.emits('incoming::end', function parser() {
      socket.removeAllListeners();
      socket = null;
    }));
  });

  this.once('close', function close() {
    service.sockets.clients().forEach(function shutdown(socket) {
      socket.disconnect();
    });

    service.store.destroy();
    service.store.removeAllListeners();
  });
};
<|endoftext|>


<commit_before>$(document).ready(function() {
    var $table, $messages;
    var btnName = [ 'edit', 'delete' ];

    var isSelected = function() {
        return !($('#main_' + btnName[0]).hasClass('disabled'));
    };
    var getSelectedRow = function() {
        return $table.row('.selected').data();
    };
    var createPostData = function(form) {
        var data = form.serialize();
        data += '&id=' + getSelectedRow().id;

        return data;
    };
    var validErr = function(errors) {
        var $msg = $messages.invalid;
        $msg.message = '
';
        for (key in errors) {
            errors[key].forEach(function(error) {
                $msg.message += error + '
';
            });
        }
        $msg.message += '
';

        $.notify($msg, { type: 'warning' });
    };

    $.notifyDefaults({
        placement: {
            from: 'bottom',
            align: 'right',
        },
        mouse_over: 'pause',
    });

    $.getJSON('assets/messages.json', function(obj) {
        var lang = document.documentElement.lang;
        $messages = obj[lang];

        if (lang == 'ja') {
            $.extend($.fn.dataTable.defaults, {
                language: { url: '//cdn.datatables.net/plug-ins/' + $.fn.dataTable.version + '/i18n/Japanese.json' },
            });
        }

        $table = $('#main').DataTable({
            columns: [
                { data: 'title' },
                { data: 'volume' },
                { data: 'authors' },
                { data: 'published_date' },
                { data: 'ndl_url' },
            ],
            columnDefs: [
                { visible: false, targets: 4 },
            ],
            order: [[ 0, 'asc' ], [ 3, 'asc' ]],
            lengthMenu: [ 10, 20, 30, 50, 100, 200 ],
            displayLength: 100,
            scrollY: true,
            deferRender: true,
            ajax: 'list',
            rowCallback: function(row, data, index) {
                $('td:eq(0)', row).html('' + data.title + '');
            },
            drawCallback: function(settings) {
                var btnElem = function(name) {
                    return '
' + eval('$messages.' + name + '.label') + '
';
                };
                btnName.forEach(function(name) {
                    $('.pagination').append(btnElem(name));
                });

                $('#btn-edit').on('click', function() {
                    if (!isSelected()) return false;

                    var obj = getSelectedRow();
                    for (var key in obj) $('#input-' + key).val(obj[key]);
                });

                $('#btn-delete').on('click', function() {
                    if (!isSelected()) return false;
                });
            },
        });

        if (typeof showResult == 'function') showResult();
    });

    $('#main tbody').on('click', 'tr', function() {
        var $row = $(this);

        if ($row.hasClass('selected')) {
            $row.removeClass('selected');

            btnName.forEach(function(name) {
                $('#main_' + name).addClass('disabled');
            });
        } else {
            $('tr.selected').removeClass('selected');

            $row.addClass('selected');
            if ($table.row('.selected').data() != null) {
                btnName.forEach(function(name) {
                    $('#main_' + name).removeClass('disabled');
                });
            }
        }
    });

    $('#form-register').on('submit', function(event) {
        event.preventDefault();

        var $form = $(this);
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            success: function(result) {
                $table.row.add(result.data).draw(false);
                $form[0].reset();
                $.notify($messages.add.success, { type: 'success' });
            },
            error: function(result) {
                var f = {
                    404: function() { $.notify($messages.not_exist, { type: 'warning' }); },
                    409: function() { $.notify($messages.add.failure, { type: 'danger' }); },
                    422: function() { validErr(result.responseJSON); },
                };
                f[result.status]();
            },
        });
    });

    $('#form-edit').on('submit', function(event) {
        event.preventDefault();

        var $form = $(this);
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: createPostData($form),
            success: function(result) {
                $('#modal-edit').modal('hide');
                $table.row('.selected').remove();
                $table.row.add(result.data).draw(false);
                $form[0].reset();
            },
            error: function(result) {
                if (result.status == 422) validErr(result.responseJSON);
            }
        });
    });

    $('#form-delete').on('submit', function(event) {
        event.preventDefault();

        var $form = $(this);
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: createPostData($form),
            success: function(result) {
                $('#modal-delete').modal('hide');
                $table.row('.selected').remove().draw(false);
                $.notify($messages.delete.success, { type: 'success' });
            },
            error: function(result) {
                var f = {
                    404: function() { $.notify($messages.delete.failure, { type: 'danger' }); },
                    422: function() { validErr(result.responseJSON); },
                };
                f[result.status]();
            },
        });
    });

    $('#btn-scan').on('click', function() {
        var url = location.origin + '/create?code={CODE}&_token=' + document.head.querySelector('meta[name="csrf-token"]').content;
        location.href = 'http://zxing.appspot.com/scan?ret=' + escape(url);
    });
});
<commit_msg>Tiny fix<commit_after>$(document).ready(function() {
    var $table, $messages;
    var btnName = [ 'edit', 'delete' ];

    var isSelected = function() {
        return !($('#main_' + btnName[0]).hasClass('disabled'));
    };
    var getSelectedRow = function() {
        return $table.row('.selected').data();
    };
    var createPostData = function(form) {
        var data = form.serialize();
        data += '&id=' + getSelectedRow().id;

        return data;
    };
    var validErr = function(errors) {
        var $msg = $messages.invalid;
        $msg.message = '
';
        for (key in errors) {
            errors[key].forEach(function(error) {
                $msg.message += error + '
';
            });
        }
        $msg.message += '
';

        $.notify($msg, { type: 'warning' });
    };

    $.notifyDefaults({
        placement: {
            from: 'bottom',
            align: 'right',
        },
        mouse_over: 'pause',
    });

    $.getJSON('assets/messages.json', function(obj) {
        var lang = document.documentElement.lang;
        $messages = obj[lang];

        if (lang == 'ja') {
            $.extend($.fn.dataTable.defaults, {
                language: { url: '//cdn.datatables.net/plug-ins/' + $.fn.dataTable.version + '/i18n/Japanese.json' },
            });
        }

        $table = $('#main').DataTable({
            columns: [
                { data: 'title' },
                { data: 'volume' },
                { data: 'authors' },
                { data: 'published_date' },
                { data: 'ndl_url' },
            ],
            columnDefs: [
                { visible: false, targets: 4 },
            ],
            order: [[ 0, 'asc' ], [ 3, 'asc' ]],
            lengthMenu: [ 10, 20, 30, 50, 100, 200 ],
            displayLength: 100,
            scrollY: true,
            deferRender: true,
            ajax: 'list',
            rowCallback: function(row, data, index) {
                $('td:eq(0)', row).html('' + data.title + '');
            },
            drawCallback: function(settings) {
                var btnElem = function(name) {
                    return '
' + eval('$messages.' + name + '.label') + '
';
                };
                btnName.forEach(function(name) {
                    $('.pagination').append(btnElem(name));
                });

                $('#btn-edit').on('click', function() {
                    if (!isSelected()) return false;

                    var obj = getSelectedRow();
                    for (var key in obj) $('#input-' + key).val(obj[key]);
                });

                $('#btn-delete').on('click', function() {
                    if (!isSelected()) return false;
                });
            },
        });

        if (typeof showResult == 'function') showResult();
    });

    $('#main tbody').on('click', 'tr', function() {
        var $row = $(this);

        if ($row.hasClass('selected')) {
            $row.removeClass('selected');

            btnName.forEach(function(name) {
                $('#main_' + name).addClass('disabled');
            });
        } else {
            $('tr.selected').removeClass('selected');
            $row.addClass('selected');

            if ($table.row('.selected').data() != null) {
                btnName.forEach(function(name) {
                    $('#main_' + name).removeClass('disabled');
                });
            }
        }
    });

    $('#form-register').on('submit', function(event) {
        event.preventDefault();

        var $form = $(this);
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            success: function(result) {
                $table.row.add(result.data).draw(false);
                $form[0].reset();
                $.notify($messages.add.success, { type: 'success' });
            },
            error: function(result) {
                var f = {
                    404: function() { $.notify($messages.not_exist, { type: 'warning' }); },
                    409: function() { $.notify($messages.add.failure, { type: 'danger' }); },
                    422: function() { validErr(result.responseJSON); },
                };
                f[result.status]();
            },
        });
    });

    $('#form-edit').on('submit', function(event) {
        event.preventDefault();

        var $form = $(this);
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: createPostData($form),
            success: function(result) {
                $('#modal-edit').modal('hide');
                $table.row('.selected').remove();
                $table.row.add(result.data).draw(false);
                $form[0].reset();
            },
            error: function(result) {
                if (result.status == 422) validErr(result.responseJSON);
            }
        });
    });

    $('#form-delete').on('submit', function(event) {
        event.preventDefault();

        var $form = $(this);
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: createPostData($form),
            success: function(result) {
                $('#modal-delete').modal('hide');
                $table.row('.selected').remove().draw(false);
                $.notify($messages.delete.success, { type: 'success' });
            },
            error: function(result) {
                var f = {
                    404: function() { $.notify($messages.delete.failure, { type: 'danger' }); },
                    422: function() { validErr(result.responseJSON); },
                };
                f[result.status]();
            },
        });
    });

    $('#btn-scan').on('click', function() {
        var url = location.origin + '/create?code={CODE}&_token=' + document.head.querySelector('meta[name="csrf-token"]').content;
        location.href = 'http://zxing.appspot.com/scan?ret=' + escape(url);
    });
});
<|endoftext|>


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

/* global glowroot */

glowroot.factory('login', [
  '$location',
  function ($location) {
    var originalUrl;
    var message;
    return {
      goToLogin: function (msg, doNotSaveLocation) {
        message = msg;
        originalUrl = doNotSaveLocation ? '/' : $location.url();
        if (originalUrl !== '/login') {
          $location.url('/login');
          $location.replace();
        }
      },
      getMessage: function () {
        return message;
      },
      returnToOriginalPath: function () {
        // originalPath can be undefined if user hits login page directly
        if (originalUrl && originalUrl !== '/login') {
          // don't do .replace() here, since then back button goes back to page right before /login, which is the same
          // page as right after /login, which is then confusing
          // (this is relevant when anonymous access is enabled)
          $location.url(originalUrl);
        } else {
          // don't do .replace() here for same reason as above
          $location.url('/');
        }
      }
    };
  }
]);

<commit_msg>Improve back button behavior around login page<commit_after>/*
 * Copyright 2013-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* global glowroot */

glowroot.factory('login', [
  '$location',
  function ($location) {
    var originalUrl;
    var message;
    return {
      goToLogin: function (msg, doNotSaveLocation) {
        message = msg;
        originalUrl = doNotSaveLocation ? '/' : $location.url();
        if (originalUrl !== '/login') {
          // don't do .replace() here, since then back button doesn't work after clicking login
          // (this is relevant when anonymous access is enabled)
          $location.url('/login');
        }
      },
      getMessage: function () {
        return message;
      },
      returnToOriginalPath: function () {
        // originalPath can be undefined if user hits login page directly
        if (originalUrl && originalUrl !== '/login') {
          // don't do .replace() here, since then back button goes back to page right before /login, which is the same
          // page as right after /login, which is then confusing
          // (this is relevant when anonymous access is enabled)
          $location.url(originalUrl);
        } else {
          // don't do .replace() here for same reason as above
          $location.url('/');
        }
      }
    };
  }
]);

<|endoftext|>


<commit_before>const fs = require('fs');
const tokensDirectory = './src/tokens/';
const web3 = require('web3');
const path = require('path');
const Schema = require('validate');
const token = new Schema({
  symbol: {
    type: String,
    required: true
  },
  name: {
    type: String,
    required: true
  },
  type: {
    type: String,
    required: true
  },
  address: {
    type: String,
    required: true
  },
  ens_address: {
    type: String
  },
  decimals: {
    type: Number,
    required: true
  },
  website: {
    type: String
  },
  logo: {
    src: {
      type: String
    },
    width: {
      type: String
    },
    height: {
      type: String
    },
    ipfs_hash: {
      type: String
    }
  },
  support: {
    email: {
      type: String
    },
    url: {
      type: String
    }
  },
  social: {
    blog: {
      type: String
    },
    chat: {
      type: String
    },
    facebook: {
      type: String
    },
    forum: {
      type: String
    },
    github: {
      type: String
    },
    gitter: {
      type: String
    },
    instagram: {
      type: String
    },
    linkedin: {
      type: String
    },
    reddit: {
      type: String
    },
    slack: {
      type: String
    },
    telegram: {
      type: String
    },
    twitter: {
      type: String
    },
    youtube: {
      type: String
    }
  }
});

function run() {
  fs.readdirSync(tokensDirectory).forEach(folder => {
    fs.readdirSync(`${tokensDirectory}/${folder}`).forEach(file => {
      if (
        path.extname(file) === '.json' &&
        web3.utils.isAddress(file.replace('.json', ''))
      ) {
        const obj = JSON.parse(
          fs.readFileSync(`${tokensDirectory}/${folder}/${file}`, 'utf8')
        );
        if (token.validate(obj) === false) {
          process.exit(1);
        }
      } else {
        process.exit(1);
      }
    });
  });
  console.log('No errors');
  process.exit(0);
}

run();
<commit_msg>Remove console.log<commit_after>const fs = require('fs');
const tokensDirectory = './src/tokens/';
const web3 = require('web3');
const path = require('path');
const Schema = require('validate');
const token = new Schema({
  symbol: {
    type: String,
    required: true
  },
  name: {
    type: String,
    required: true
  },
  type: {
    type: String,
    required: true
  },
  address: {
    type: String,
    required: true
  },
  ens_address: {
    type: String
  },
  decimals: {
    type: Number,
    required: true
  },
  website: {
    type: String
  },
  logo: {
    src: {
      type: String
    },
    width: {
      type: String
    },
    height: {
      type: String
    },
    ipfs_hash: {
      type: String
    }
  },
  support: {
    email: {
      type: String
    },
    url: {
      type: String
    }
  },
  social: {
    blog: {
      type: String
    },
    chat: {
      type: String
    },
    facebook: {
      type: String
    },
    forum: {
      type: String
    },
    github: {
      type: String
    },
    gitter: {
      type: String
    },
    instagram: {
      type: String
    },
    linkedin: {
      type: String
    },
    reddit: {
      type: String
    },
    slack: {
      type: String
    },
    telegram: {
      type: String
    },
    twitter: {
      type: String
    },
    youtube: {
      type: String
    }
  }
});

function run() {
  fs.readdirSync(tokensDirectory).forEach(folder => {
    fs.readdirSync(`${tokensDirectory}/${folder}`).forEach(file => {
      if (
        path.extname(file) === '.json' &&
        web3.utils.isAddress(file.replace('.json', ''))
      ) {
        const obj = JSON.parse(
          fs.readFileSync(`${tokensDirectory}/${folder}/${file}`, 'utf8')
        );
        if (token.validate(obj) === false) {
          process.exit(1);
        }
      } else {
        process.exit(1);
      }
    });
  });
  process.exit(0);
}

run();
<|endoftext|>