<commit_before>CLAZZ("cmp.ThreeParticles", {
	INJECT:["entity", "asset", "game", "type", "texture"],

	'@type':{type:'enum', options:['fountain', 'exhaust']},
	type:"fountain",

	'@texture':{type:'texture'},
	texture:'resources/image/smoke.jpg',

    '@enabled':{type:'bool'},
    enabled:true,

    '@rate':{type:'float', min:0},
    rate:10,

    // used by server
    acc:0,

    setParticlesEnabled:function( enabled ){

        this.enabled = enabled;

    },

	onReady:function(){

		cmp.ThreeParticles.Server.add(this);

	},

	destroy:function(){

		cmp.ThreeParticles.Server.remove(this);

	}
});

CLAZZ("cmp.ThreeParticles.Server", {
    INJECT:['pool', 'scene', 'game'],

    index:null,

    vertexShader:`
uniform float size;
uniform float scale;

#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>

void main() {

	#include <color_vertex>
	#include <begin_vertex>
	#include <project_vertex>

    gl_PointSize = size * scale / - mvPosition.z;

	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>

}
    `,

    fragmentShader:`
uniform vec3 diffuse;
uniform float opacity;

#include <common>
#include <packing>
#include <color_pars_fragment>

uniform vec4 offsetRepeat;
uniform sampler2D map;
// # include <map_particle_pars_fragment>

#include <fog_pars_fragment>
#include <shadowmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>

void main() {

	#include <clipping_planes_fragment>

	vec3 outgoingLight = vec3( 1.0 );
	vec4 diffuseColor = vec4( diffuse, opacity );

	#include <logdepthbuf_fragment>
    vec4 mapTexel = texture2D( map,
        vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )
        * offsetRepeat.zw
        + offsetRepeat.xy );

    diffuseColor *= mapTexelToLinear( mapTexel );

	#include <map_particle_fragment>
	#include <color_fragment>
	#include <alphatest_fragment>

	outgoingLight = diffuseColor.rgb;

	gl_FragColor = vec4( outgoingLight, diffuseColor.a );

	#include <premultiplied_alpha_fragment>
	#include <tonemapping_fragment>
	#include <encodings_fragment>
	#include <fog_fragment>

}
    `,

    CONSTRUCTOR:function(){
        this.index = {};

        cmp.ThreeParticles.Server.instances[ this.scene.id ] = this;

        this.pool.add(this);
    },

    getIndex:function( texture, create ){
        var index = this.index[texture];
        if( index ) return index;
        if( create === false ) return null;

        var geometry = this.getGeometry();
        var material = this.getMaterial( texture );
        var mesh = new THREE.Points( geometry, material );
        this.scene.add( mesh );

        return this.index[texture] = {
            mesh:mesh,
            geometry:geometry,
            material:material,
            emitters:[]
        };
    },

    getGeometry:function(){
        var position = new THREE.Float32BufferAttribute(1000*3, 3);
        position.setDynamic( true );

        var geometry = new THREE.BufferGeometry();
        geometry.addAttribute("position", position);
        geometry.drawRange.count = 0;

        position.array[0] = 500; // Necessary. I don't know why.

        return geometry;
    },

    getMaterial:function( texture ){
        // var mat = new THREE.PointsMaterial( { color:0xffffff, size:100, opacity:1 } );
        // mat.map = (new THREE.TextureLoader()).load(texture);
        // mat.blending = THREE.AdditiveBlending;
        // mat.depthWrite = false;
        // mat.transparent = true;
        // return mat;

        var mat = new THREE.ShaderMaterial({
            fragmentShader: this.fragmentShader,
            vertexShader: this.vertexShader,
            uniforms: THREE.UniformsUtils.merge( [
				THREE.UniformsLib.points,
				THREE.UniformsLib.fog,
                {
                    time: {value:0},
                }
			] )
        });

        mat.uniforms.map.value = (new THREE.TextureLoader()).load(texture);

        mat.uniforms.size.value = 60;
        // mat.uniforms.opacity = 1;
        // mat.uniforms.diffuse.value = new THREE.Color(0xFFFFFF);
        // mat.uniforms.offsetRepeat.value.set( 0, 0, 1, 1 );

        mat.blending = THREE.AdditiveBlending;
        mat.transparent = true;
        return mat;
    },

    add:function( emitter ){
        var index = this.getIndex( emitter.texture );
        index.emitters.push( emitter );
    },

    remove:function( emitter ){
        var index = this.getIndex(emitter, false);
        if( !index ) return;

        var pos = index.emitters.indexOf( emitter );
        if( pos == -1 ) return;

        this.emitters.splice( pos, 1 );
    },

    particleCount:0,
    onTick:function(delta){
    	if( delta < 0 )
    		return;

        var scale = this.game.height / this.game.camera.aspect;

        for( var k in this.index ){
            var dirty = false;
            var index = this.index[k];
            var emitters = index.emitters;
            var geometry = index.geometry;
            var material = index.material;
            var position = geometry.attributes.position.array;
            material.uniforms.time.value += delta;
            material.uniforms.scale.value = scale;

            for( var i=0, l=emitters.length; i<l; ++i ){

                var emitter = emitters[i];
                if( !emitter.enabled || !emitter.rate )
                    cotinue;

                var pos = emitter.asset.position;

                var acc = emitter.acc;
                acc += delta * emitter.rate;
                emitter.acc = acc - Math.floor(acc);
                acc = Math.floor(acc);

                for( var j=0; j<acc; ++j ){

                    var p = geometry.drawRange.count++;
                    p *= 3;

                    position[p++] = pos.x;
                    position[p++] = pos.y;
                    position[p++] = pos.z;
                }

                if( acc > 0 )
                    dirty = true;
            }
            if( dirty )
                geometry.attributes.position.needsUpdate = true;
        }
    },

    destroy:function(){
        cmp.ThreeParticles.Server.instances[ this.scene.id ] = null;
        this.pool.remove(this);
    },

	STATIC:{
		instances:{},

		add:function( emitter ){
			var instances = cmp.ThreeParticles.Server.instances;
			var asset = emitter.asset;
            var instance = instances[ emitter.game.scene.id ];

            if( !instance ){
                instance = CLAZZ.get( cmp.ThreeParticles.Server, {
                    pool:emitter.entity.pool,
                    scene:emitter.game.scene,
                    game:emitter.game
                });
            }

            instance.add( emitter )
		},

        remove:function( emitter ){
			var instances = cmp.ThreeParticles.Server.instances;
            var instance = instances[ emitter.game.scene.id ];
            instance.remove( emitter );
        }
	}

});<commit_msg>particles<commit_after>CLAZZ("cmp.ThreeParticles", {
	INJECT:["entity", "asset", "game", "type", "texture"],

	'@type':{type:'enum', options:['fountain', 'exhaust']},
	type:"fountain",

	'@texture':{type:'texture'},
	texture:'resources/image/smoke.jpg',

    '@enabled':{type:'bool'},
    enabled:true,

    '@rate':{type:'float', min:0},
    rate:10,

    // used by server
    acc:0,

    setParticlesEnabled:function( enabled ){

        this.enabled = enabled;

    },

	onReady:function(){

		cmp.ThreeParticles.Server.add(this);

	},

	destroy:function(){

		cmp.ThreeParticles.Server.remove(this);

	}
});

CLAZZ("cmp.ThreeParticles.Server", {
    INJECT:['pool', 'scene', 'game'],

    index:null,

    vertexShader:`
uniform float size;
uniform float scale;
attribute vec4 particle;

#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>

void main() {

	#include <color_vertex>
	#include <begin_vertex>
	#include <project_vertex>

    gl_PointSize = size * scale / - mvPosition.z;

	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>

}
    `,

    fragmentShader:`
uniform vec3 diffuse;
uniform float opacity;

#include <common>
#include <packing>
#include <color_pars_fragment>

uniform vec4 offsetRepeat;
uniform sampler2D map;
// # include <map_particle_pars_fragment>

#include <fog_pars_fragment>
#include <shadowmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>

void main() {

	#include <clipping_planes_fragment>

	vec3 outgoingLight = vec3( 1.0 );
	vec4 diffuseColor = vec4( diffuse, opacity );

	#include <logdepthbuf_fragment>
    vec4 mapTexel = texture2D( map,
        vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )
        * offsetRepeat.zw
        + offsetRepeat.xy );

    diffuseColor *= mapTexelToLinear( mapTexel );

	#include <map_particle_fragment>
	#include <color_fragment>
	#include <alphatest_fragment>

	outgoingLight = diffuseColor.rgb;

	gl_FragColor = vec4( outgoingLight, diffuseColor.a );

	#include <premultiplied_alpha_fragment>
	#include <tonemapping_fragment>
	#include <encodings_fragment>
	#include <fog_fragment>

}
    `,

    CONSTRUCTOR:function(){
        this.index = {};

        cmp.ThreeParticles.Server.instances[ this.scene.id ] = this;

        this.pool.add(this);
    },

    getIndex:function( texture, create, max ){
        var index = this.index[texture];
        if( index ) return index;
        if( create === false ) return null;

        var geometry = this.getGeometry( max );
        var material = this.getMaterial( texture );
        var mesh = new THREE.Points( geometry, material );
        this.scene.add( mesh );

        return this.index[texture] = {
            next: 0,
            max: max,
            mesh:mesh,
            geometry:geometry,
            material:material,
            emitters:[]
        };
    },

    getGeometry:function( max ){
        var particle = new THREE.Float32BufferAttribute(max*4, 4);
        particle.setDynamic( true );
        var position = new THREE.Float32BufferAttribute(max*3, 3);
        position.setDynamic( true );

        var geometry = new THREE.BufferGeometry();
        geometry.addAttribute("position", position);
        geometry.addAttribute("particle", particle);
        geometry.drawRange.count = 0;

        // Necessary. I don't know why.
        position.array[0] = 500;
        particle.array[0] = 500;

        return geometry;
    },

    getMaterial:function( texture ){
        // var mat = new THREE.PointsMaterial( { color:0xffffff, size:100, opacity:1 } );
        // mat.map = (new THREE.TextureLoader()).load(texture);
        // mat.blending = THREE.AdditiveBlending;
        // mat.depthWrite = false;
        // mat.transparent = true;
        // return mat;

        var mat = new THREE.ShaderMaterial({
            fragmentShader: this.fragmentShader,
            vertexShader: this.vertexShader,
            uniforms: THREE.UniformsUtils.merge( [
				THREE.UniformsLib.points,
				THREE.UniformsLib.fog,
                {
                    time: {value:0},
                }
			] )
        });

        mat.uniforms.map.value = (new THREE.TextureLoader()).load(texture);

        mat.uniforms.size.value = 60;
        // mat.uniforms.opacity = 1;
        // mat.uniforms.diffuse.value = new THREE.Color(0xFFFFFF);
        // mat.uniforms.offsetRepeat.value.set( 0, 0, 1, 1 );

        mat.blending = THREE.AdditiveBlending;
        mat.transparent = true;
        mat.depthWrite = false;
        return mat;
    },

    add:function( emitter ){
        var index = this.getIndex( emitter.texture, true, 100 );
        index.emitters.push( emitter );
    },

    remove:function( emitter ){
        var index = this.getIndex(emitter, false);
        if( !index ) return;

        var pos = index.emitters.indexOf( emitter );
        if( pos == -1 ) return;

        this.emitters.splice( pos, 1 );
    },

    time:0,
    onTick:function(delta){
    	if( delta < 0 )
    		return;

        var scale = this.game.height / this.game.camera.aspect;
        var time = this.time += delta;

        for( var k in this.index ){
            var dirty = false;
            var index = this.index[k];
            var max = index.max;
            var emitters = index.emitters;
            var geometry = index.geometry;
            var material = index.material;
            var position = geometry.attributes.position.array;
            var particle = geometry.attributes.particle.array;
            material.uniforms.time.value += delta;
            material.uniforms.scale.value = scale;

            for( var i=0, l=emitters.length; i<l; ++i ){

                var emitter = emitters[i];
                if( !emitter.enabled || !emitter.rate )
                    cotinue;

                var pos = emitter.asset.position;

                var acc = emitter.acc;
                acc += delta * emitter.rate;
                emitter.acc = acc - Math.floor(acc);
                acc = Math.floor(acc);

                for( var j=0; j<acc; ++j ){
                    var count = (index.next++) % max;
                    if( count > geometry.drawRange.count )
                        geometry.drawRange.count = count;

                    var p = count * 4;
                    particle[p++] = time;
                    particle[p++] = time;
                    particle[p++] = time;
                    particle[p++] = time;

                    p = count * 3;
                    position[p++] = pos.x;
                    position[p++] = pos.y;
                    position[p++] = pos.z;
                }

                if( acc > 0 )
                    dirty = true;
            }
            if( dirty ){
                geometry.attributes.particle.needsUpdate = true;
                geometry.attributes.position.needsUpdate = true;
            }
        }
    },

    destroy:function(){
        cmp.ThreeParticles.Server.instances[ this.scene.id ] = null;
        this.pool.remove(this);
    },

	STATIC:{
		instances:{},

		add:function( emitter ){
			var instances = cmp.ThreeParticles.Server.instances;
			var asset = emitter.asset;
            var instance = instances[ emitter.game.scene.id ];

            if( !instance ){
                instance = CLAZZ.get( cmp.ThreeParticles.Server, {
                    pool:emitter.entity.pool,
                    scene:emitter.game.scene,
                    game:emitter.game
                });
            }

            instance.add( emitter )
		},

        remove:function( emitter ){
			var instances = cmp.ThreeParticles.Server.instances;
            var instance = instances[ emitter.game.scene.id ];
            instance.remove( emitter );
        }
	}

});<|endoftext|>


<commit_before>/**
 * Checks if the URL can be found in the supplied set of redirection rules.
 * @param {string} url - The url to check.
 * @param {array} rules - Array of 'rules' objects to check against. {src:"Source", dest:"Destination"}
 * @return {string|null} String containing the newly redirected URL. Null if a redirection doesn't exist.
 */
function isRedirectRule(url, rules) {
  var replaced = null;
  var i = 0;
  while(!replaced && i < rules.length) {
    /* Make sure that the destination isn't already in the URL. (ex amazon.com -> smile.amazon.com) */
    if(url.search(rules[i].dest) < 0) {
      var attempt = url.replace(rules[i].src, rules[i].dest);
      if(url !== attempt) {
        replaced = attempt;
      }
    }
    i++;
  }
  return replaced;
}

/**
 * Checks if the URL is a mobile URL. (ex. en.m.wikipedia.org or mobile.twitter.com)
 * @param {string} url - The url to check.
 * @return {string|null} String containing the now non-mobile URL. Null if it's not a mobile URL.
 */
function isMobile(url) {
  var mobileSubdomains = ['m', 'mobile'];

  var domain = /\/\/(\S+?)\//.exec(url)[1];
  var domainTokens = domain.split('.');

  /* Basically, just loop through the array of domain tokens and check each mobile subdomain against it.
     If a match is found, stop the loop, and replace the url's domain with the new non-mobile one. Theres probaby a better way to do this. */
  var domainIndex = 0;
  var mobileIndex = 0;
  var match = null;
  while(!match && domainIndex < domainTokens.length) {
    while(!match && mobileIndex < mobileSubdomains.length) {
      if(domainTokens[domainIndex] === mobileSubdomains[mobileIndex]) {
        domainTokens.splice(domainIndex, 1);
        match = url.replace(domain, domainTokens.join('.'));
      }
      mobileIndex++;
    }
    domainIndex++;
    mobileIndex = 0;
  }
  return match;
}

/* Listener Init */
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'loading' && tab.active) {
    chrome.storage.sync.get({ redirection: 1  }, function(items) { // Default to redirection enabled.
        /* Make sure that redirection is enabled */
        if(items.redirection === 1) {
          chrome.storage.sync.get("redirectionRules", function(result) {
            var rules = result.redirectionRules;

            /* Check and see if the url exists in the list of redirection rules */
            var redirectRuleMatch = isRedirectRule(tab.url, rules);
            if(redirectRuleMatch !== null) {
              chrome.tabs.update(tabId, {url: redirectRuleMatch});
              return;
            }

            /* Check and see if the page is mobile */
            var mobileMatch = isMobile(tab.url);
            if(mobileMatch !== null) {
              chrome.tabs.update(tabId, {url: mobileMatch});
            }

            /* Else do nothing */
          })
        }
    })
  }
})
/* End Listener Init */<commit_msg>Added check for falsy URLs in isMobile()<commit_after>/**
 * Checks if the URL can be found in the supplied set of redirection rules.
 * @param {string} url - The url to check.
 * @param {array} rules - Array of 'rules' objects to check against. {src:"Source", dest:"Destination"}
 * @return {string|null} String containing the newly redirected URL. Null if a redirection doesn't exist.
 */
function isRedirectRule(url, rules) {
  var replaced = null;
  var i = 0;
  while(!replaced && i < rules.length) {
    /* Make sure that the destination isn't already in the URL. (ex amazon.com -> smile.amazon.com) */
    if(url.search(rules[i].dest) < 0) {
      var attempt = url.replace(rules[i].src, rules[i].dest);
      if(url !== attempt) {
        replaced = attempt;
      }
    }
    i++;
  }
  return replaced;
}

/**
 * Checks if the URL is a mobile URL. (ex. en.m.wikipedia.org or mobile.twitter.com)
 * @param {string} url - The url to check.
 * @return {string|null} String containing the now non-mobile URL. Null if it's not a mobile URL.
 */
function isMobile(url) {
  if(!url) {
    return null;
  }

  var mobileSubdomains = ['m', 'mobile'];

  try {
    var domain = /\/\/(\S+?)\//.exec(url)[1];
    var domainTokens = domain.split('.');
  }
  catch(error) {
    console.log(error);
    return null;
  }

  /* Basically, just loop through the array of domain tokens and check each mobile subdomain against it.
     If a match is found, stop the loop, and replace the url's domain with the new non-mobile one. Theres probaby a better way to do this. */
  var domainIndex = 0;
  var mobileIndex = 0;
  var match = null;
  while(!match && domainIndex < domainTokens.length) {
    while(!match && mobileIndex < mobileSubdomains.length) {
      if(domainTokens[domainIndex] === mobileSubdomains[mobileIndex]) {
        domainTokens.splice(domainIndex, 1);
        match = url.replace(domain, domainTokens.join('.'));
      }
      mobileIndex++;
    }
    domainIndex++;
    mobileIndex = 0;
  }
  return match;
}

/* Listener Init */
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'loading' && tab.active) {
    chrome.storage.sync.get({ redirection: 1  }, function(items) { // Default to redirection enabled.
        /* Make sure that redirection is enabled */
        if(items.redirection === 1) {
          chrome.storage.sync.get("redirectionRules", function(result) {
            var rules = result.redirectionRules;

            /* Check and see if the url exists in the list of redirection rules */
            var redirectRuleMatch = isRedirectRule(tab.url, rules);
            if(redirectRuleMatch !== null) {
              chrome.tabs.update(tabId, {url: redirectRuleMatch});
              return;
            }

            /* Check and see if the page is mobile */
            var mobileMatch = isMobile(tab.url);
            if(mobileMatch !== null) {
              chrome.tabs.update(tabId, {url: mobileMatch});
            }

            /* Else do nothing */
          })
        }
    })
  }
})
/* End Listener Init */<|endoftext|>


<commit_before>var mnemonics = {
    "ld": {
        type: "memory"
    }
  , "st": {
        type: "memory"
    }
  , "sethi": {
        type: "sethi"
    }
  , "branch": {
        type: "branch"
    }

  , "be": {
        type: "branch"
    }
  , "bcs": {
        type: "branch"
    }
  , "bneg": {
        type: "branch"
    }
  , "bvs": {
        type: "branch"
    }
  , "ba": {
        type: "branch"
    }
  , "ba": {
        type: "branch"
    }
  , "call": {
        type: "control"
    }

  , "addcc": {
        type: "arithmetic"
    }
  , "andcc": {
        type: "arithmetic"
    }
  , "orcc": {
        type: "arithmetic"
    }
  , "orncc": {
        type: "arithmetic"
    }
  , "srl": {
        type: "arithmetic"
    }
  , "jmpl": {
        type: "arithmetic"
    }
};

const ALL_MNEMONICS = "\\b(?:" + Object.keys(mnemonics).join("|") + ")\\b";

function parse(lines) {
    var result = {
        lines: []
      , labels: []
      , addresses: {}
      , _sAddress: 0
      , _cAddress: -1
    };

    var lastLabel = null;
    for (var i in lines) {
        var c = lines[i];
        c = c.replace(/\!.*$/g, "");
        if (!c.trim().length) {
            continue;
        }

        var op = ((c.match(/\.([a-z]+)/) || [])[1] || "").trim()
          , label = ((c.match(/^([a-z]+):\ /) || [])[1] || "").trim()
          , instruction = null
          , iArgs = []
          , oArgs = []
          , lValue = ""
          , cLine = {}
          ;

        label = label || lastLabel;

        if (new RegExp(ALL_MNEMONICS).test(c)) {
            var m = c.match(new RegExp("(" + ALL_MNEMONICS + ")( (.*))?")) || [];
            instruction = m[1];
            iArgs = (m[2] || "").split(/[ ,]+/).filter(function (c) { return c; });
        }

        if (op) {
            lValue = "";
            lastLabel = "";
            label = "";
            oArgs = c.replace("." + op, "").split(/[ ,]+/).filter(function (c) { return c; });
        }

        if (op || label || instruction)
            console.log("Line " + (parseInt(i) + 1) + ":");

        if (op)
            console.log("  > Pseudo ops: " + op);

        if (oArgs.length)
            console.log("  > Operator Args: " + JSON.stringify(oArgs));

        if (label) {
            lastLabel = label;
            lValue = c.replace(new RegExp("^" + label + "\:"), "").trim();
            console.log("  > Label: " + label);
            console.log("  > Content: " + lValue);
        }

        if (instruction)
            console.log("  > Instruction: " + instruction);

        if (iArgs.length)
            console.log("  > Instruction Arguments: " + JSON.stringify(iArgs));

        cLine.op = op;
        cLine._c = c;
        cLine.label = label;
        cLine.instruction = instruction;
        cLine.iArgs = iArgs;
        cLine.oArgs = oArgs;
        cLine.c = lValue;

        if (instruction) {
            if (!mnemonics[instruction]) {
                throw new Error("Invalid instruction: " + instruction);
            }
            cLine.type = mnemonics[instruction].type
        }

        if (result._cAddress === -1 && cLine.label === "main") {
            result._cAddress = result._sAddress;
        }

        if (cLine.op === "org") {
            result._sAddress = parseInt(oArgs[0]);
            if (!(result._sAddress >= 0)) {
                throw new Error(".org value should be positive integer");
            }
        }

        if (cLine.label) {
            result.addresses[cLine.label] = {
                value: cLine.content
              , address: result._cAddress
            };
        }

        if (c.trim() && result._cAddress !== -1) {
            result._cAddress += 4;
        }

        result.lines.push(cLine);
    }
    return result;
}

module.exports = parse;
<commit_msg>Fixed label regex and address setting<commit_after>var mnemonics = {
    "ld": {
        type: "memory"
    }
  , "st": {
        type: "memory"
    }
  , "sethi": {
        type: "sethi"
    }
  , "branch": {
        type: "branch"
    }

  , "be": {
        type: "branch"
    }
  , "bcs": {
        type: "branch"
    }
  , "bneg": {
        type: "branch"
    }
  , "bvs": {
        type: "branch"
    }
  , "ba": {
        type: "branch"
    }
  , "ba": {
        type: "branch"
    }
  , "call": {
        type: "control"
    }

  , "addcc": {
        type: "arithmetic"
    }
  , "andcc": {
        type: "arithmetic"
    }
  , "orcc": {
        type: "arithmetic"
    }
  , "orncc": {
        type: "arithmetic"
    }
  , "srl": {
        type: "arithmetic"
    }
  , "jmpl": {
        type: "arithmetic"
    }
};

const ALL_MNEMONICS = "\\b(?:" + Object.keys(mnemonics).join("|") + ")\\b";

function parse(lines) {
    var result = {
        lines: []
      , labels: []
      , addresses: {}
      , _sAddress: 0
      , _cAddress: -1
    };

    var lastLabel = null;
    for (var i in lines) {
        var c = lines[i];
        c = c.replace(/\!.*$/g, "");

        var op = ((c.match(/\.([a-z]+)/) || [])[1] || "").trim()
          , label = ((c.match(/^([a-z,_]+):\ /) || [])[1] || "").trim()
          , instruction = null
          , iArgs = []
          , oArgs = []
          , lValue = ""
          , cLine = {}
          ;

        label = label || lastLabel;

        if (new RegExp(ALL_MNEMONICS).test(c)) {
            var m = c.match(new RegExp("(" + ALL_MNEMONICS + ")( (.*))?")) || [];
            instruction = m[1];
            iArgs = (m[2] || "").split(/[ ,]+/).filter(function (c) { return c; });
        }

        if (op) {
            lValue = "";
            lastLabel = "";
            label = "";
            oArgs = c.replace("." + op, "").split(/[ ,]+/).filter(function (c) { return c; });
        }

        if (op || label || instruction)
            console.log("Line " + (parseInt(i) + 1) + ":");

        if (op)
            console.log("  > Pseudo ops: " + op);

        if (oArgs.length)
            console.log("  > Operator Args: " + JSON.stringify(oArgs));

        if (label) {
            lastLabel = label;
            lValue = c.replace(new RegExp("^" + label + "\:"), "").trim();
            console.log("  > Label: " + label);
            console.log("  > Content: " + lValue);
        }

        if (instruction)
            console.log("  > Instruction: " + instruction);

        if (iArgs.length)
            console.log("  > Instruction Arguments: " + JSON.stringify(iArgs));

        cLine.op = op;
        cLine._c = c;
        cLine.label = label;
        cLine.instruction = instruction;
        cLine.iArgs = iArgs;
        cLine.oArgs = oArgs;
        cLine.c = lValue;

        if (instruction) {
            if (!mnemonics[instruction]) {
                throw new Error("Invalid instruction: " + instruction);
            }
            cLine.type = mnemonics[instruction].type
        }

        if (result._cAddress === -1 && cLine.label === "main") {
            result._cAddress = result._sAddress;
        }

        if (cLine.op === "org") {
            result._sAddress = parseInt(oArgs[0]);
            if (!(result._sAddress >= 0)) {
                throw new Error(".org value should be positive integer");
            }
        }

        if (cLine.label && !result.addresses[cLine.label]) {
            result.addresses[cLine.label] = {
                address: result._cAddress
            };
        }

        if (cLine._c && result._cAddress !== -1) {
            result._cAddress += 4;
        }

        result.lines.push(cLine);
    }
    return result;
}

module.exports = parse;
<|endoftext|>


<commit_before>/*jslint indent: 2, maxlen: 80, nomen: true */
"use strict";

// keywords: js, javascript, nodejs events.EventEmitter

/**
 * Inspired by nodejs EventEmitter class
 * http://nodejs.org/api/events.html
 *
 * When an EventEmitter instance experiences an error, the typical action is
 * to emit an 'error' event. Error events are treated as a special case in
 * node. If there is no listener for it, then the default action throws the
 * exception again.
 *
 * All EventEmitters emit the event 'newListener' when new listeners are added
 * and 'removeListener' when a listener is removed.
 *
 * @class EventEmitter
 * @constructor
 */
function EventEmitter() {
  this._events = {};
  this._maxListeners = 10;
}

/**
 * Adds a listener to the end of the listeners array for the specified
 * event.
 *
 * @method addListener
 * @param  {String} event The event name
 * @param  {Function} listener The listener callback
 * @return {EventEmitter} This emitter
 */
EventEmitter.prototype.addListener = function (event, listener) {
  var listener_list;
  if (typeof listener !== "function") {
    return this;
  }
  this.emit("newListener", event, listener);
  listener_list = this._events[event];
  if (listener_list === undefined) {
    this._events[event] = listener;
    listener_list = listener;
  } else if (typeof listener_list === "function") {
    this._events[event] = [listener_list, listener];
  } else {
    listener_list[listener_list.length] = listener;
  }
  if (this._maxListeners > 0 &&
      typeof listener_list !== "function" &&
      listener_list.length > this._maxListeners &&
      listener_list.warned !== true) {
    console.warn("warning: possible EventEmitter memory leak detected. " +
                 listener_list.length + " listeners added. " +
                 "Use emitter.setMaxListeners() to increase limit.");
    listener_list.warned = true;
  }
  return this;
};

/**
 * #crossLink "EventEmitter/addListener:method"
 *
 * @method on
 */
EventEmitter.prototype.on = EventEmitter.prototype.addListener;

/**
 * Adds a one time listener for the event. This listener is invoked only the
 * next time the event is fired, after which it is removed.
 *
 * @method once
 * @param  {String} event The event name
 * @param  {Function} listener The listener callback
 * @return {EventEmitter} This emitter
 */
EventEmitter.prototype.once = function (event, listener) {
  var that = this, wrapper = function () {
    that.removeListener(event, wrapper);
    listener.apply(that, arguments);
  };
  wrapper.original = listener;
  return that.on(event, wrapper);
};

/**
 * Remove a listener from the listener array for the specified event.
 * Caution: changes array indices in the listener array behind the listener
 *
 * @method removeListener
 * @param  {String} event The event name
 * @param  {Function} listener The listener callback
 * @return {EventEmitter} This emitter
 */
EventEmitter.prototype.removeListener = function (event, listener) {
  var listener_list, i;
  if (this._events[event]) {
    listener_list = this._events[event];
    if (typeof listener_list === "function") {
      if (listener_list === listener || listener_list.original === listener) {
        delete this._events[event];
      }
      return this;
    }
    for (i = 0; i < listener_list.length; i += 1) {
      if (listener_list[i] === listener ||
          listener_list.original === listener) {
        listener_list.splice(i, 1);
        this.emit("removeListener", event, listener);
        break;
      }
    }
    if (listener_list.length === 1) {
      this._events[event] = listener_list[0];
    }
    if (listener_list.length === 0) {
      this._events[event] = undefined;
    }
  }
  return this;
};

/**
 * Removes all listeners, or those of the specified event.
 *
 * @method removeAllListeners
 * @param  {String} event The event name (optional)
 * @return {EventEmitter} This emitter
 */
EventEmitter.prototype.removeAllListeners = function (event) {
  var key;
  if (event === undefined) {
    for (key in this._events) {
      if (this._events.hasOwnProperty(key)) {
        this.removeAllListeners(key);
      }
    }
    return this;
  }
  this._events[event] = undefined;
  return this;
};

/**
 * By default EventEmitters will print a warning if more than 10 listeners
 * are added for a particular event. This is a useful default which helps
 * finding memory leaks. Obviously not all Emitters should be limited to 10.
 * This function allows that to be increased. Set to zero for unlimited.
 *
 * @method setMaxListeners
 * @param  {Number} max_listeners The maximum of listeners
 */
EventEmitter.prototype.setMaxListeners = function (max_listeners) {
  this._maxListeners = max_listeners;
};

/**
 * Execute each of the listeners in order with the supplied arguments.
 *
 * @method emit
 * @param  {String} event The event name
 * @param  {Any} [args]* The listener argument to give
 * @return {Boolean} true if event had listeners, false otherwise.
 */
EventEmitter.prototype.emit = function (event) {
  var i, argument_list, listener_list;
  if (!this._events[event]) {
    return false;
  }
  listener_list = this._events[event].slice();
  argument_list = Array.prototype.slice.call(arguments, 1);
  for (i = 0; i < listener_list.length; i += 1) {
    try {
      listener_list[i].apply(this, argument_list);
    } catch (e) {
      if (this.listeners("error").length > 0) {
        this.emit("error", e);
        break;
      } else {
        throw e;
      }
    }
  }
  return true;
};

/**
 * Returns an array of listeners for the specified event.
 *
 * @method listeners
 * @param  {String} event The event name
 * @return {Array} The array of listeners
 */
EventEmitter.prototype.listeners = function (event) {
  if (this._events[event]) {
    return this._events[event];
  }
  return [];
};

/**
 * Static method; Return the number of listeners for a given event.
 *
 * @method listenerCount
 * @static
 * @param  {EventEmitter} emitter The event emitter
 * @param  {String} event The event name
 * @return {Number} The number of listener
 */
EventEmitter.listenerCount = function (emitter, event) {
  return emitter.listeners(event).length;
};

exports.EventEmitter = EventEmitter;

////////////////////////////////////////////////////////////////////////////////

// keywords: js, javascript, nodejs events.EventEmitter, clonable

var util = require('util');
var deepClone = require('./deepClone.js').deepClone;

/**
 * An EventEmitter with an added method to clone this object.
 *
 * @class ClonableEventEmitter
 * @constructor
 */
function ClonableEventEmitter() {
  EventEmitter.call(this);
}
util.inherits(ClonableEventEmitter, EventEmitter);

/**
 * Returns a clone of this object.
 *
 * @method clone
 * @return {ClonableEventEmitter} The clone of this object
 */
ClonableEventEmitter.prototype.clone = function () {
  var new_one = new ClonableEventEmitter(), i, j;
  new_one._maxListeners = deepClone(this._maxListeners);
  new_one._events = deepClone(this._events);
  return new_one;
};

exports.ClonableEventEmitter = ClonableEventEmitter;
<commit_msg>events.js: eventemitter access to length of function bug -> fixed<commit_after>/*jslint indent: 2, maxlen: 80, nomen: true */
"use strict";

// keywords: js, javascript, nodejs events.EventEmitter

/**
 * Inspired by nodejs EventEmitter class
 * http://nodejs.org/api/events.html
 *
 * When an EventEmitter instance experiences an error, the typical action is
 * to emit an 'error' event. Error events are treated as a special case in
 * node. If there is no listener for it, then the default action throws the
 * exception again.
 *
 * All EventEmitters emit the event 'newListener' when new listeners are added
 * and 'removeListener' when a listener is removed.
 *
 * @class EventEmitter
 * @constructor
 */
function EventEmitter() {
  this._events = {};
  this._maxListeners = 10;
}

/**
 * Adds a listener to the end of the listeners array for the specified
 * event.
 *
 * @method addListener
 * @param  {String} event The event name
 * @param  {Function} listener The listener callback
 * @return {EventEmitter} This emitter
 */
EventEmitter.prototype.addListener = function (event, listener) {
  var listener_list;
  if (typeof listener !== "function") {
    return this;
  }
  this.emit("newListener", event, listener);
  listener_list = this._events[event];
  if (listener_list === undefined) {
    this._events[event] = listener;
    listener_list = listener;
  } else if (typeof listener_list === "function") {
    this._events[event] = [listener_list, listener];
    listener_list = this._events[event]
  } else {
    listener_list[listener_list.length] = listener;
  }
  if (this._maxListeners > 0 &&
      typeof listener_list !== "function" &&
      listener_list.length > this._maxListeners &&
      listener_list.warned !== true) {
    console.warn("warning: possible EventEmitter memory leak detected. " +
                 listener_list.length + " listeners added. " +
                 "Use emitter.setMaxListeners() to increase limit.");
    listener_list.warned = true;
  }
  return this;
};

/**
 * #crossLink "EventEmitter/addListener:method"
 *
 * @method on
 */
EventEmitter.prototype.on = EventEmitter.prototype.addListener;

/**
 * Adds a one time listener for the event. This listener is invoked only the
 * next time the event is fired, after which it is removed.
 *
 * @method once
 * @param  {String} event The event name
 * @param  {Function} listener The listener callback
 * @return {EventEmitter} This emitter
 */
EventEmitter.prototype.once = function (event, listener) {
  var that = this, wrapper = function () {
    that.removeListener(event, wrapper);
    listener.apply(that, arguments);
  };
  wrapper.original = listener;
  return that.on(event, wrapper);
};

/**
 * Remove a listener from the listener array for the specified event.
 * Caution: changes array indices in the listener array behind the listener
 *
 * @method removeListener
 * @param  {String} event The event name
 * @param  {Function} listener The listener callback
 * @return {EventEmitter} This emitter
 */
EventEmitter.prototype.removeListener = function (event, listener) {
  var listener_list, i;
  if (this._events[event]) {
    listener_list = this._events[event];
    if (typeof listener_list === "function") {
      if (listener_list === listener || listener_list.original === listener) {
        delete this._events[event];
      }
      return this;
    }
    for (i = 0; i < listener_list.length; i += 1) {
      if (listener_list[i] === listener ||
          listener_list.original === listener) {
        listener_list.splice(i, 1);
        this.emit("removeListener", event, listener);
        break;
      }
    }
    if (listener_list.length === 1) {
      this._events[event] = listener_list[0];
    }
    if (listener_list.length === 0) {
      this._events[event] = undefined;
    }
  }
  return this;
};

/**
 * Removes all listeners, or those of the specified event.
 *
 * @method removeAllListeners
 * @param  {String} event The event name (optional)
 * @return {EventEmitter} This emitter
 */
EventEmitter.prototype.removeAllListeners = function (event) {
  var key;
  if (event === undefined) {
    for (key in this._events) {
      if (this._events.hasOwnProperty(key)) {
        this.removeAllListeners(key);
      }
    }
    return this;
  }
  this._events[event] = undefined;
  return this;
};

/**
 * By default EventEmitters will print a warning if more than 10 listeners
 * are added for a particular event. This is a useful default which helps
 * finding memory leaks. Obviously not all Emitters should be limited to 10.
 * This function allows that to be increased. Set to zero for unlimited.
 *
 * @method setMaxListeners
 * @param  {Number} max_listeners The maximum of listeners
 */
EventEmitter.prototype.setMaxListeners = function (max_listeners) {
  this._maxListeners = max_listeners;
};

/**
 * Execute each of the listeners in order with the supplied arguments.
 *
 * @method emit
 * @param  {String} event The event name
 * @param  {Any} [args]* The listener argument to give
 * @return {Boolean} true if event had listeners, false otherwise.
 */
EventEmitter.prototype.emit = function (event) {
  var i, argument_list, listener_list;
  if (!this._events[event]) {
    return false;
  }
  listener_list = this._events[event].slice();
  argument_list = Array.prototype.slice.call(arguments, 1);
  for (i = 0; i < listener_list.length; i += 1) {
    try {
      listener_list[i].apply(this, argument_list);
    } catch (e) {
      if (this.listeners("error").length > 0) {
        this.emit("error", e);
        break;
      } else {
        throw e;
      }
    }
  }
  return true;
};

/**
 * Returns an array of listeners for the specified event.
 *
 * @method listeners
 * @param  {String} event The event name
 * @return {Array} The array of listeners
 */
EventEmitter.prototype.listeners = function (event) {
  if (this._events[event]) {
    return this._events[event];
  }
  return [];
};

/**
 * Static method; Return the number of listeners for a given event.
 *
 * @method listenerCount
 * @static
 * @param  {EventEmitter} emitter The event emitter
 * @param  {String} event The event name
 * @return {Number} The number of listener
 */
EventEmitter.listenerCount = function (emitter, event) {
  return emitter.listeners(event).length;
};

exports.EventEmitter = EventEmitter;

////////////////////////////////////////////////////////////////////////////////

// keywords: js, javascript, nodejs events.EventEmitter, clonable

var util = require('util');
var deepClone = require('./deepClone.js').deepClone;

/**
 * An EventEmitter with an added method to clone this object.
 *
 * @class ClonableEventEmitter
 * @constructor
 */
function ClonableEventEmitter() {
  EventEmitter.call(this);
}
util.inherits(ClonableEventEmitter, EventEmitter);

/**
 * Returns a clone of this object.
 *
 * @method clone
 * @return {ClonableEventEmitter} The clone of this object
 */
ClonableEventEmitter.prototype.clone = function () {
  var new_one = new ClonableEventEmitter(), i, j;
  new_one._maxListeners = deepClone(this._maxListeners);
  new_one._events = deepClone(this._events);
  return new_one;
};

exports.ClonableEventEmitter = ClonableEventEmitter;
<|endoftext|>


<commit_before>// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Functions for dealing with Date formatting & Parsing,
 * County and language name, TimeZone list.
 */

/**
 * Namespace for locale related functions.
 */
goog.provide('goog.locale');

goog.require('goog.locale.nativeNameConstants');

/**
 * Set currnet locale to the specified one.
 * @param {string} localeName Locale name string. We are following the usage
 *     in CLDR, but can make a few compromise for existing name compatibility.
 */
goog.locale.setLocale = function(localeName) {
  // it is common to see people use '-' as locale part separator, normalize it.
  localeName = localeName.replace(/-/g, '_');
  goog.locale.activeLocale_ = localeName;
};

/**
 * Retrieve the currnet locale
 * @return {string} Current locale name string.
 */
goog.locale.getLocale = function() {
  if (!goog.locale.activeLocale_) {
    goog.locale.activeLocale_ = 'en';
  }
  return goog.locale.activeLocale_;
};

// Couple of constants to represent predefined Date/Time format type.
/**
 * Enum of resources that can be registered.
 * @enum {string}
 */
goog.locale.Resource = {
  DATE_TIME_CONSTANTS: 'DateTimeConstants',
  NUMBER_FORMAT_CONSTANTS: 'NumberFormatConstants',
  TIME_ZONE_CONSTANTS: 'TimeZoneConstants',
  LOCAL_NAME_CONSTANTS: 'LocaleNameConstants',

  TIME_ZONE_SELECTED_IDS: 'TimeZoneSelectedIds',
  TIME_ZONE_SELECTED_SHORT_NAMES: 'TimeZoneSelectedShortNames',
  TIME_ZONE_SELECTED_LONG_NAMES: 'TimeZoneSelectedLongNames',
  TIME_ZONE_ALL_LONG_NAMES: 'TimeZoneAllLongNames'
};

// BCP 47 language code:
//
// LanguageCode := LanguageSubtag
//                ("-" ScriptSubtag)?
//                ("-" RegionSubtag)?
//                ("-" VariantSubtag)?
//                ("@" Keyword "=" Value ("," Keyword "=" Value)* )?
//
// e.g. en-Latn-GB
//
// NOTICE:
// No special format checking is performed. If you pass a none valid
// language code as parameter to the following functions,
// you might get an unexpected result.

/**
 * Returns the language-subtag of the given language code.
 *
 * @param {string} languageCode Language code to extract language subtag from.
 * @return {string} Language subtag (in lowercase).
 */
goog.locale.getLanguageSubTag = function(languageCode) {
  var result = languageCode.match(/^\w{2,3}([-_]|$)/);
  return result ? result[0].replace(/[_-]/g, '') : '';
};

/**
 * Returns the region-sub-tag of the given language code.
 *
 * @param {string} languageCode Language code to extract region subtag from.
 * @return {string} Region sub-tag (in uppercase).
 */
goog.locale.getRegionSubTag = function(languageCode) {
  var result = languageCode.match(/[-_]([a-zA-Z]{2}|\d{3})([-_]|$)/);
  return result ? result[0].replace(/[_-]/g, '') : '';
};

/**
 * Returns the script subtag of the locale with the first alphabet in uppercase
 * and the rest 3 characters in lower case.
 *
 * @param {string} languageCode Language Code to extract script subtag from.
 * @return {string} Script subtag.
 */
goog.locale.getScriptSubTag = function(languageCode) {
  var result = languageCode.split(/[-_]/g);
  return result.length > 1 && result[1].match(/^[a-zA-Z]{4}$/) ?
      result[1] : '';
};

/**
 * Returns the variant-sub-tag of the given language code.
 *
 * @param {string} languageCode Language code to extract variant subtag from.
 * @return {string} Variant sub-tag.
 */
goog.locale.getVariantSubTag = function(languageCode) {
  var result = languageCode.match(/[-_]([a-z]{2,})/);
  return result ? result[1] : '';
};

/**
 * Returns the country name of the provided language code in its native
 * language.
 *
 * This method depends on goog.locale.nativeNameConstants available from
 * nativenameconstants.js. User of this method has to add dependency to this.
 *
 * @param {string} countryCode Code to lookup the country name for.
 *
 * @return {string} Country name for the provided language code.
 */
goog.locale.getNativeCountryName = function(countryCode) {
  var key = goog.locale.getLanguageSubTag(countryCode) + '_' +
            goog.locale.getRegionSubTag(countryCode);
  return key in goog.locale.nativeNameConstants.COUNTRY ?
      goog.locale.nativeNameConstants.COUNTRY[key] : countryCode;
};

/**
 * Returns the localized country name for the provided language code in the
 * current or provided locale symbols set.
 *
 * This method depends on goog.locale.LocaleNameConstants__<locale> available
 * from //javascript/googledata/i18n/js_locale_data. User of this method
 * has to add dependency to this.
 *
 * @param {string} languageCode Language code to lookup the country name for.
 * @param {Object=} opt_localeSymbols If omitted the current locale symbol
 *     set is used.
 *
 * @return {string} Localized country name.
 */
goog.locale.getLocalizedCountryName = function(languageCode,
                                               opt_localeSymbols) {
  if (!opt_localeSymbols) {
    opt_localeSymbols = goog.locale.getResource('LocaleNameConstants',
        goog.locale.getLocale());
  }
  var code = goog.locale.getRegionSubTag(languageCode);
  return code in opt_localeSymbols.COUNTRY ?
      opt_localeSymbols.COUNTRY[code] : languageCode;
};

/**
 * Returns the language name of the provided language code in its native
 * language.
 *
 * This method depends on goog.locale.nativeNameConstants available from
 * nativenameconstants.js. User of this method has to add dependency to this.
 *
 * @param {string} languageCode Language code to lookup the language name for.
 *
 * @return {string} Language name for the provided language code.
 */
goog.locale.getNativeLanguageName = function(languageCode) {
  var code = goog.locale.getLanguageSubTag(languageCode);
  return code in goog.locale.nativeNameConstants.LANGUAGE ?
      goog.locale.nativeNameConstants.LANGUAGE[code] : languageCode;
};

/**
 * Returns the localized language name for the provided language code in
 * the current or provided locale symbols set.
 *
 * This method depends on goog.locale.LocaleNameConstants__<locale> available
 * from //javascript/googledata/i18n/js_locale_data. User of this method
 * has to add dependency to this.
 *
 * @param {string} languageCode Language code to lookup the language name for.
 * @param {Object=} opt_localeSymbols locale symbol set if given.
 *
 * @return {string} Localized language name of the provided language code.
 */
goog.locale.getLocalizedLanguageName = function(languageCode,
                                                opt_localeSymbols) {
  if (!opt_localeSymbols) {
    opt_localeSymbols = goog.locale.getResource('LocaleNameConstants',
        goog.locale.getLocale());
  }
  var code = goog.locale.getLanguageSubTag(languageCode);
  return code in opt_localeSymbols.LANGUAGE ?
      opt_localeSymbols.LANGUAGE[code] : languageCode;
};

/**
 * Register a resource object for certain locale.
 * @param {Object} dataObj The resource object being registered.
 * @param {goog.locale.Resource|string} resourceName String that represents
 *     the type of resource.
 * @param {string} localeName Locale ID.
 */
goog.locale.registerResource = function(dataObj, resourceName, localeName) {
  if (!goog.locale.resourceRegistry_[resourceName]) {
    goog.locale.resourceRegistry_[resourceName] = {};
  }
  goog.locale.resourceRegistry_[resourceName][localeName] = dataObj;
  // the first registered locale becomes active one. Usually there will be
  // only one locale per js binary bundle.
  if (!goog.locale.activeLocale_) {
    goog.locale.activeLocale_ = localeName;
  }
};

/**
 * Returns true if the required resource has already been registered.
 * @param {goog.locale.Resource|string} resourceName String that represents
 *     the type of resource.
 * @param {string} localeName Locale ID.
 * @return {boolean} Whether the required resource has already been registered.
 */
goog.locale.isResourceRegistered = function(resourceName, localeName) {
  return resourceName in goog.locale.resourceRegistry_ &&
      localeName in goog.locale.resourceRegistry_[resourceName];
};

/**
 * This object maps (resourceName, localeName) to a resourceObj.
 * @type {Object}
 * @private
 */
goog.locale.resourceRegistry_ = {};

/**
 * Registers the timezone constants object for a given locale name.
 * @param {Object} dataObj The resource object.
 * @param {string} localeName Locale ID.
 * @deprecated Use goog.i18n.TimeZone, no longer need this.
 */
goog.locale.registerTimeZoneConstants = function(dataObj, localeName) {
  goog.locale.registerResource(
      dataObj, goog.locale.Resource.TIME_ZONE_CONSTANTS, localeName);
};

/**
 * Registers the LocaleNameConstants constants object for a given locale name.
 * @param {Object} dataObj The resource object.
 * @param {string} localeName Locale ID.
 */
goog.locale.registerLocaleNameConstants = function(dataObj, localeName) {
  goog.locale.registerResource(
      dataObj, goog.locale.Resource.LOCAL_NAME_CONSTANTS, localeName);
};

/**
 * Registers the TimeZoneSelectedIds constants object for a given locale name.
 * @param {Object} dataObj The resource object.
 * @param {string} localeName Locale ID.
 */
goog.locale.registerTimeZoneSelectedIds = function(dataObj, localeName) {
  goog.locale.registerResource(
      dataObj, goog.locale.Resource.TIME_ZONE_SELECTED_IDS, localeName);
};

/**
 * Registers the TimeZoneSelectedShortNames constants object for a given
 *     locale name.
 * @param {Object} dataObj The resource object.
 * @param {string} localeName Locale ID.
 */
goog.locale.registerTimeZoneSelectedShortNames = function(dataObj, localeName) {
  goog.locale.registerResource(
      dataObj, goog.locale.Resource.TIME_ZONE_SELECTED_SHORT_NAMES, localeName);
};

/**
 * Registers the TimeZoneSelectedLongNames constants object for a given locale
 *     name.
 * @param {Object} dataObj The resource object.
 * @param {string} localeName Locale ID.
 */
goog.locale.registerTimeZoneSelectedLongNames = function(dataObj, localeName) {
  goog.locale.registerResource(
      dataObj, goog.locale.Resource.TIME_ZONE_SELECTED_LONG_NAMES, localeName);
};

/**
 * Registers the TimeZoneAllLongNames constants object for a given locale name.
 * @param {Object} dataObj The resource object.
 * @param {string} localeName Locale ID.
 */
goog.locale.registerTimeZoneAllLongNames = function(dataObj, localeName) {
  goog.locale.registerResource(
      dataObj, goog.locale.Resource.TIME_ZONE_ALL_LONG_NAMES, localeName);
};

/**
 * Retrieve specified resource for certain locale.
 * @param {string} resourceName String that represents the type of resource.
 * @param {string=} opt_locale Locale ID, if not given, current locale
 *     will be assumed.
 * @return {Object|undefined} The resource object that hold all the resource
 *     data, or undefined if not available.
 */
goog.locale.getResource = function(resourceName, opt_locale) {
  var locale = opt_locale ? opt_locale : goog.locale.getLocale();

  if (!(resourceName in goog.locale.resourceRegistry_)) {
    return undefined;
  }
  return goog.locale.resourceRegistry_[resourceName][locale];
};

/**
 * Retrieve specified resource for certain locale with fallback. For example,
 * request of 'zh_CN' will be resolved in following order: zh_CN, zh, en.
 * If none of the above succeeds, of if the resource as indicated by
 * resourceName does not exist at all, undefined will be returned.
 *
 * @param {string} resourceName String that represents the type of resource.
 * @param {string=} opt_locale locale ID, if not given, current locale
 *     will be assumed.
 * @return {Object|undefined} The resource object for desired locale.
 */
goog.locale.getResourceWithFallback = function(resourceName, opt_locale) {
  var locale = opt_locale ? opt_locale : goog.locale.getLocale();

  if (!(resourceName in goog.locale.resourceRegistry_)) {
    return undefined;
  }

  if (locale in goog.locale.resourceRegistry_[resourceName]) {
    return goog.locale.resourceRegistry_[resourceName][locale];
  }

  // if locale has multiple parts (2 atmost in reality), fallback to base part.
  var locale_parts = locale.split('_');
  if (locale_parts.length > 1 &&
      locale_parts[0] in goog.locale.resourceRegistry_[resourceName]) {
    return goog.locale.resourceRegistry_[resourceName][locale_parts[0]];
  }

  // otherwise, fallback to 'en'
  return goog.locale.resourceRegistry_[resourceName]['en'];
};

// Export global functions that are used by the date time constants files.
// See http://go/js_locale_data
var registerLocalNameConstants = goog.locale.registerLocaleNameConstants;

var registerTimeZoneSelectedIds = goog.locale.registerTimeZoneSelectedIds;
var registerTimeZoneSelectedShortNames =
    goog.locale.registerTimeZoneSelectedShortNames;
var registerTimeZoneSelectedLongNames =
    goog.locale.registerTimeZoneSelectedLongNames;
var registerTimeZoneAllLongNames = goog.locale.registerTimeZoneAllLongNames;

<commit_msg><commit_after>// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Functions for dealing with Date formatting & Parsing,
 * County and language name, TimeZone list.
 */

/**
 * Namespace for locale related functions.
 */
goog.provide('goog.locale');

goog.require('goog.locale.nativeNameConstants');

/**
 * Set currnet locale to the specified one.
 * @param {string} localeName Locale name string. We are following the usage
 *     in CLDR, but can make a few compromise for existing name compatibility.
 */
goog.locale.setLocale = function(localeName) {
  // it is common to see people use '-' as locale part separator, normalize it.
  localeName = localeName.replace(/-/g, '_');
  goog.locale.activeLocale_ = localeName;
};

/**
 * Retrieve the currnet locale
 * @return {string} Current locale name string.
 * @deprecated Use goog.LOCALE instead.
 */
goog.locale.getLocale = function() {
  if (!goog.locale.activeLocale_) {
    goog.locale.activeLocale_ = 'en';
  }
  return goog.locale.activeLocale_;
};

// Couple of constants to represent predefined Date/Time format type.
/**
 * Enum of resources that can be registered.
 * @enum {string}
 */
goog.locale.Resource = {
  DATE_TIME_CONSTANTS: 'DateTimeConstants',
  NUMBER_FORMAT_CONSTANTS: 'NumberFormatConstants',
  TIME_ZONE_CONSTANTS: 'TimeZoneConstants',
  LOCAL_NAME_CONSTANTS: 'LocaleNameConstants',

  TIME_ZONE_SELECTED_IDS: 'TimeZoneSelectedIds',
  TIME_ZONE_SELECTED_SHORT_NAMES: 'TimeZoneSelectedShortNames',
  TIME_ZONE_SELECTED_LONG_NAMES: 'TimeZoneSelectedLongNames',
  TIME_ZONE_ALL_LONG_NAMES: 'TimeZoneAllLongNames'
};

// BCP 47 language code:
//
// LanguageCode := LanguageSubtag
//                ("-" ScriptSubtag)?
//                ("-" RegionSubtag)?
//                ("-" VariantSubtag)?
//                ("@" Keyword "=" Value ("," Keyword "=" Value)* )?
//
// e.g. en-Latn-GB
//
// NOTICE:
// No special format checking is performed. If you pass a none valid
// language code as parameter to the following functions,
// you might get an unexpected result.

/**
 * Returns the language-subtag of the given language code.
 *
 * @param {string} languageCode Language code to extract language subtag from.
 * @return {string} Language subtag (in lowercase).
 */
goog.locale.getLanguageSubTag = function(languageCode) {
  var result = languageCode.match(/^\w{2,3}([-_]|$)/);
  return result ? result[0].replace(/[_-]/g, '') : '';
};

/**
 * Returns the region-sub-tag of the given language code.
 *
 * @param {string} languageCode Language code to extract region subtag from.
 * @return {string} Region sub-tag (in uppercase).
 */
goog.locale.getRegionSubTag = function(languageCode) {
  var result = languageCode.match(/[-_]([a-zA-Z]{2}|\d{3})([-_]|$)/);
  return result ? result[0].replace(/[_-]/g, '') : '';
};

/**
 * Returns the script subtag of the locale with the first alphabet in uppercase
 * and the rest 3 characters in lower case.
 *
 * @param {string} languageCode Language Code to extract script subtag from.
 * @return {string} Script subtag.
 */
goog.locale.getScriptSubTag = function(languageCode) {
  var result = languageCode.split(/[-_]/g);
  return result.length > 1 && result[1].match(/^[a-zA-Z]{4}$/) ?
      result[1] : '';
};

/**
 * Returns the variant-sub-tag of the given language code.
 *
 * @param {string} languageCode Language code to extract variant subtag from.
 * @return {string} Variant sub-tag.
 */
goog.locale.getVariantSubTag = function(languageCode) {
  var result = languageCode.match(/[-_]([a-z]{2,})/);
  return result ? result[1] : '';
};

/**
 * Returns the country name of the provided language code in its native
 * language.
 *
 * This method depends on goog.locale.nativeNameConstants available from
 * nativenameconstants.js. User of this method has to add dependency to this.
 *
 * @param {string} countryCode Code to lookup the country name for.
 *
 * @return {string} Country name for the provided language code.
 */
goog.locale.getNativeCountryName = function(countryCode) {
  var key = goog.locale.getLanguageSubTag(countryCode) + '_' +
            goog.locale.getRegionSubTag(countryCode);
  return key in goog.locale.nativeNameConstants.COUNTRY ?
      goog.locale.nativeNameConstants.COUNTRY[key] : countryCode;
};

/**
 * Returns the localized country name for the provided language code in the
 * current or provided locale symbols set.
 *
 * This method depends on goog.locale.LocaleNameConstants__<locale> available
 * from //javascript/googledata/i18n/js_locale_data. User of this method
 * has to add dependency to this.
 *
 * @param {string} languageCode Language code to lookup the country name for.
 * @param {Object=} opt_localeSymbols If omitted the current locale symbol
 *     set is used.
 *
 * @return {string} Localized country name.
 */
goog.locale.getLocalizedCountryName = function(languageCode,
                                               opt_localeSymbols) {
  if (!opt_localeSymbols) {
    opt_localeSymbols = goog.locale.getResource('LocaleNameConstants',
        goog.locale.getLocale());
  }
  var code = goog.locale.getRegionSubTag(languageCode);
  return code in opt_localeSymbols.COUNTRY ?
      opt_localeSymbols.COUNTRY[code] : languageCode;
};

/**
 * Returns the language name of the provided language code in its native
 * language.
 *
 * This method depends on goog.locale.nativeNameConstants available from
 * nativenameconstants.js. User of this method has to add dependency to this.
 *
 * @param {string} languageCode Language code to lookup the language name for.
 *
 * @return {string} Language name for the provided language code.
 */
goog.locale.getNativeLanguageName = function(languageCode) {
  var code = goog.locale.getLanguageSubTag(languageCode);
  return code in goog.locale.nativeNameConstants.LANGUAGE ?
      goog.locale.nativeNameConstants.LANGUAGE[code] : languageCode;
};

/**
 * Returns the localized language name for the provided language code in
 * the current or provided locale symbols set.
 *
 * This method depends on goog.locale.LocaleNameConstants__<locale> available
 * from //javascript/googledata/i18n/js_locale_data. User of this method
 * has to add dependency to this.
 *
 * @param {string} languageCode Language code to lookup the language name for.
 * @param {Object=} opt_localeSymbols locale symbol set if given.
 *
 * @return {string} Localized language name of the provided language code.
 */
goog.locale.getLocalizedLanguageName = function(languageCode,
                                                opt_localeSymbols) {
  if (!opt_localeSymbols) {
    opt_localeSymbols = goog.locale.getResource('LocaleNameConstants',
        goog.locale.getLocale());
  }
  var code = goog.locale.getLanguageSubTag(languageCode);
  return code in opt_localeSymbols.LANGUAGE ?
      opt_localeSymbols.LANGUAGE[code] : languageCode;
};

/**
 * Register a resource object for certain locale.
 * @param {Object} dataObj The resource object being registered.
 * @param {goog.locale.Resource|string} resourceName String that represents
 *     the type of resource.
 * @param {string} localeName Locale ID.
 */
goog.locale.registerResource = function(dataObj, resourceName, localeName) {
  if (!goog.locale.resourceRegistry_[resourceName]) {
    goog.locale.resourceRegistry_[resourceName] = {};
  }
  goog.locale.resourceRegistry_[resourceName][localeName] = dataObj;
  // the first registered locale becomes active one. Usually there will be
  // only one locale per js binary bundle.
  if (!goog.locale.activeLocale_) {
    goog.locale.activeLocale_ = localeName;
  }
};

/**
 * Returns true if the required resource has already been registered.
 * @param {goog.locale.Resource|string} resourceName String that represents
 *     the type of resource.
 * @param {string} localeName Locale ID.
 * @return {boolean} Whether the required resource has already been registered.
 */
goog.locale.isResourceRegistered = function(resourceName, localeName) {
  return resourceName in goog.locale.resourceRegistry_ &&
      localeName in goog.locale.resourceRegistry_[resourceName];
};

/**
 * This object maps (resourceName, localeName) to a resourceObj.
 * @type {Object}
 * @private
 */
goog.locale.resourceRegistry_ = {};

/**
 * Registers the timezone constants object for a given locale name.
 * @param {Object} dataObj The resource object.
 * @param {string} localeName Locale ID.
 * @deprecated Use goog.i18n.TimeZone, no longer need this.
 */
goog.locale.registerTimeZoneConstants = function(dataObj, localeName) {
  goog.locale.registerResource(
      dataObj, goog.locale.Resource.TIME_ZONE_CONSTANTS, localeName);
};

/**
 * Registers the LocaleNameConstants constants object for a given locale name.
 * @param {Object} dataObj The resource object.
 * @param {string} localeName Locale ID.
 */
goog.locale.registerLocaleNameConstants = function(dataObj, localeName) {
  goog.locale.registerResource(
      dataObj, goog.locale.Resource.LOCAL_NAME_CONSTANTS, localeName);
};

/**
 * Registers the TimeZoneSelectedIds constants object for a given locale name.
 * @param {Object} dataObj The resource object.
 * @param {string} localeName Locale ID.
 */
goog.locale.registerTimeZoneSelectedIds = function(dataObj, localeName) {
  goog.locale.registerResource(
      dataObj, goog.locale.Resource.TIME_ZONE_SELECTED_IDS, localeName);
};

/**
 * Registers the TimeZoneSelectedShortNames constants object for a given
 *     locale name.
 * @param {Object} dataObj The resource object.
 * @param {string} localeName Locale ID.
 */
goog.locale.registerTimeZoneSelectedShortNames = function(dataObj, localeName) {
  goog.locale.registerResource(
      dataObj, goog.locale.Resource.TIME_ZONE_SELECTED_SHORT_NAMES, localeName);
};

/**
 * Registers the TimeZoneSelectedLongNames constants object for a given locale
 *     name.
 * @param {Object} dataObj The resource object.
 * @param {string} localeName Locale ID.
 */
goog.locale.registerTimeZoneSelectedLongNames = function(dataObj, localeName) {
  goog.locale.registerResource(
      dataObj, goog.locale.Resource.TIME_ZONE_SELECTED_LONG_NAMES, localeName);
};

/**
 * Registers the TimeZoneAllLongNames constants object for a given locale name.
 * @param {Object} dataObj The resource object.
 * @param {string} localeName Locale ID.
 */
goog.locale.registerTimeZoneAllLongNames = function(dataObj, localeName) {
  goog.locale.registerResource(
      dataObj, goog.locale.Resource.TIME_ZONE_ALL_LONG_NAMES, localeName);
};

/**
 * Retrieve specified resource for certain locale.
 * @param {string} resourceName String that represents the type of resource.
 * @param {string=} opt_locale Locale ID, if not given, current locale
 *     will be assumed.
 * @return {Object|undefined} The resource object that hold all the resource
 *     data, or undefined if not available.
 */
goog.locale.getResource = function(resourceName, opt_locale) {
  var locale = opt_locale ? opt_locale : goog.locale.getLocale();

  if (!(resourceName in goog.locale.resourceRegistry_)) {
    return undefined;
  }
  return goog.locale.resourceRegistry_[resourceName][locale];
};

/**
 * Retrieve specified resource for certain locale with fallback. For example,
 * request of 'zh_CN' will be resolved in following order: zh_CN, zh, en.
 * If none of the above succeeds, of if the resource as indicated by
 * resourceName does not exist at all, undefined will be returned.
 *
 * @param {string} resourceName String that represents the type of resource.
 * @param {string=} opt_locale locale ID, if not given, current locale
 *     will be assumed.
 * @return {Object|undefined} The resource object for desired locale.
 */
goog.locale.getResourceWithFallback = function(resourceName, opt_locale) {
  var locale = opt_locale ? opt_locale : goog.locale.getLocale();

  if (!(resourceName in goog.locale.resourceRegistry_)) {
    return undefined;
  }

  if (locale in goog.locale.resourceRegistry_[resourceName]) {
    return goog.locale.resourceRegistry_[resourceName][locale];
  }

  // if locale has multiple parts (2 atmost in reality), fallback to base part.
  var locale_parts = locale.split('_');
  if (locale_parts.length > 1 &&
      locale_parts[0] in goog.locale.resourceRegistry_[resourceName]) {
    return goog.locale.resourceRegistry_[resourceName][locale_parts[0]];
  }

  // otherwise, fallback to 'en'
  return goog.locale.resourceRegistry_[resourceName]['en'];
};

// Export global functions that are used by the date time constants files.
// See http://go/js_locale_data
var registerLocalNameConstants = goog.locale.registerLocaleNameConstants;

var registerTimeZoneSelectedIds = goog.locale.registerTimeZoneSelectedIds;
var registerTimeZoneSelectedShortNames =
    goog.locale.registerTimeZoneSelectedShortNames;
var registerTimeZoneSelectedLongNames =
    goog.locale.registerTimeZoneSelectedLongNames;
var registerTimeZoneAllLongNames = goog.locale.registerTimeZoneAllLongNames;

<|endoftext|>


<commit_before>'use strict';

var Flicking = function() {
}

Flicking.prototype.init = function($obj){
    var startX = 0,
        currentX = 0,
        isMoveArr = [],
        arrList = [],
        i = 0,
        elasticsWidth = $obj.elastic,
        _self = this,
        isMove = false;

    this.wrapper = $obj.wrapper;
    if(this.wrapper){
        this.list = document.querySelectorAll('.' + $obj.wrapper + ' .' + $obj.container);
    }else{
        this.list = document.querySelectorAll('.' + $obj.container);
    }
    this.length = this.list.length;
    this.moveX = 0;
    this.btnWidth = $obj.btnWidth;

    for(; i < this.length; i++) {
        var _list;
        arrList[i] = this.list[i];
        _list = arrList[i];
        isMoveArr[i] = false;
        _list.no = i;
        _list.addEventListener('touchstart', function(e) {
            this.className = $obj.container;
            startX = e.changedTouches[0].pageX;
        }, false);

        _list.addEventListener('touchmove', function(e) {
            currentX = e.changedTouches[0].pageX;
            if(isMoveArr[this.no]) {
                _self.moveX = _self.btnWidth - (currentX - startX);
            }else{
                _self.moveX = startX - currentX;
            }

            if(_self.moveX > _self.btnWidth + elasticsWidth) {
                _self.moveX = _self.btnWidth + elasticsWidth;
            } else if(_self.moveX < -elasticsWidth) {
                _self.moveX = -elasticsWidth;
            }

            _self.move(this, false);
            isMove = true;
        }, false);

        _list.addEventListener('touchend', function(e) {
            if(isMove){
                this.className = $obj.container + ' ' + $obj.transitionClass;
                _self.move(this, true);
            }
            isMove = false;
        }, false);

        _list.addEventListener('transitionend', function(e) {
            if(_self.moveX === _self.btnWidth) {
                isMoveArr[this.no] = true;
            }else{
                isMoveArr[this.no] = false;
            }
            this.className = $obj.container;
        });
    }
};

Flicking.prototype.move = function($target, $isEnd){
    if($isEnd){
        if(this.moveX >= this.btnWidth / 2){
            this.moveX = this.btnWidth;
        }else{
            this.moveX = 0;
        }
    }
    $target.querySelector('.list-content').style.transform = 'translate3d(' + (-this.moveX) + 'px, 0, 0)';
    //$target.querySelector('.list-content').style.left = String(-this.moveX) + 'px';
    if(!$isEnd){
        if(this.moveX < 0) {
        this.moveX = 0;
        }else if(this.moveX > this.btnWidth + 20) {
            this.moveX = this.btnWidth + 20;
        }
    }
    $target.querySelector('.list-btns').style.transform = 'translate3d(0, 0, 0) scaleX(' + (this.moveX / this.btnWidth) + ')';
    //$target.querySelector('.edit-btn').style.width = String(this.moveX / 2) + 'px';
    //$target.querySelector('.delete-btn').style.width = String(this.moveX / 2) + 'px';
};

(function(window) {
    var flicking = new Flicking();
    flicking.init({
        wrapper:'list',
        container: 'list-item',
        transitionClass: 'transition-item',
        btnWidth: 120,
        elastic: 40
    });
})(window);
<commit_msg>add comments<commit_after>'use strict';

var Flicking = function() {
}

Flicking.prototype.init = function($obj){
    var startX = 0,                     // 시작 x 좌표
        currentX = 0,                   // move 중 x 좌표
        isMoveArr = [],                 // 펼쳐져 있는지 닫혀있는지 boolean값
        arrList = [],                   // list 배열
        i = 0,                          // for문 돌릴 i
        elasticsWidth = $obj.elastic,   // 탄력값
        _self = this,
        isMove = false;                 // 그냥 클릭만 했는지 움직였는지 체크

    this.wrapper = $obj.wrapper;        // wrapper 설정
    if(this.wrapper){
        this.list = document.querySelectorAll('.' + $obj.wrapper + ' .' + $obj.container);
    }else{
        this.list = document.querySelectorAll('.' + $obj.container);
    }
    this.length = this.list.length;     // list 길이
    this.moveX = 0;                     // start 와 current값 계산한 최종 움직일 값
    this.btnWidth = $obj.btnWidth;      // 나타날 버튼 가로 사이즈

    for(; i < this.length; i++) {
        var _list = this.list[i];       // _list에 list안에 있는 객체를 차례로 담아 이벤트 타겟으로 지정해 준다.
        isMoveArr[i] = false;           // 다 닫혀 있으므로 false를 넣어준다.
        _list.no = i;                   // 이벤트 리스너 안에서 i를 받아줄 역할
        _list.addEventListener('touchstart', function(e) {
            this.className = $obj.container;
            startX = e.changedTouches[0].pageX;     // 시작 지점 설정
        }, false);

        _list.addEventListener('touchmove', function(e) {
            currentX = e.changedTouches[0].pageX;   // 현재 x좌표값
            if(isMoveArr[this.no]) {                // moveX값은 열려있을때와 닫혀있을때가 달라야 하므로 현재 리스트의 boolean값으로 체크
                _self.moveX = _self.btnWidth - (currentX - startX);
                // 열려 있을 경우 현재 열려있는 x좌표에서 움직이는 동안의 x좌표를 빼줘야 한다.
            }else{
                _self.moveX = startX - currentX;
                // 닫혀 있을 경우 시작점에서 현재 x좌표값을 빼준다.
            }

            if(_self.moveX > _self.btnWidth + elasticsWidth) {
                _self.moveX = _self.btnWidth + elasticsWidth;       // 최대값 설정
            } else if(_self.moveX < -elasticsWidth) {
                _self.moveX = -elasticsWidth;                       // 최소값 설정
            }

            _self.move(this, false);
            isMove = true;                                          // 움직이고 있는 상태인지 아닌지 체크
        }, false);

        _list.addEventListener('touchend', function(e) {
            if(isMove){
                this.className = $obj.container + ' ' + $obj.transitionClass;
                _self.move(this, true);
                // touchmove가 이루어진 상황이면 트랜지션을 하여 지정한 btnWidth값으로 이동
            }
            isMove = false;
        }, false);

        _list.addEventListener('transitionend', function(e) {
            if(_self.moveX === _self.btnWidth) {
                isMoveArr[this.no] = true;
            }else{
                isMoveArr[this.no] = false;
            }
            this.className = $obj.container;
            // 트랜지션이 끝나면 클래스 이름 초기화 해주고 isMoveArr에 닫혔는지 열렸는지 boolean값 삽입
        });
    }
};

/**
 * list의 움직임 설정
 * @param  {[Object]} $target [현재 선택된 리스트]
 * @param  {[Boolean]} $isEnd  [touchmove인지 touchend인지 구분]
 * @return {[none]}
 */
Flicking.prototype.move = function($target, $isEnd){
    if($isEnd){                 //  touch가 끝났을 때 움직인거리가 설정한 width값 / 2 보다 클 경우 설정한 width값으로 이동하고 아니면 다시 0으로 이동
        if(this.moveX >= this.btnWidth / 2){
            this.moveX = this.btnWidth;
        }else{
            this.moveX = 0;
        }
    }
    $target.querySelector('.list-content').style.transform = 'translate3d(' + (-this.moveX) + 'px, 0, 0)';
    if(!$isEnd){                //  버튼은 최대 width값 + 20까지만 제한한다.
        if(this.moveX < 0) {
        this.moveX = 0;
        }else if(this.moveX > this.btnWidth + 20) {
            this.moveX = this.btnWidth + 20;
        }
    }
    $target.querySelector('.list-btns').style.transform = 'translate3d(0, 0, 0) scaleX(' + (this.moveX / this.btnWidth) + ')';
};

(function(window) {
    var flicking = new Flicking();
    flicking.init({
        wrapper:'list',
        container: 'list-item',
        transitionClass: 'transition-item',
        btnWidth: 120,
        elastic: 40
    });
})(window);
<|endoftext|>


<commit_before>angular.module('NoteWrangler')
.config(function($routeProvider){
  $routeProvider
    .when('/notes',{
      templateUrl: 'templates/pages/notes/index.html'
    })
    .when('/users',{
      templateUrl: 'templates/pages/users/index.html'
    })
});
<commit_msg>add root url and catch all url<commit_after>angular.module('NoteWrangler')
.config(function($routeProvider){
  $routeProvider
    .when('/notes',{
      templateUrl: 'templates/pages/notes/index.html'
    })
    .when('/users',{
      templateUrl: 'templates/pages/users/index.html'
    })
    .when('/',{
      templateUrl: 'templates/pages/notes/index.html'
    })
    .otherwise({redirectTo: '/'})
});
<|endoftext|>


<commit_before>module.exports = function(RED) {
    function TaCmiCoeOutNode(config) {
        RED.nodes.createNode(this,config);
	this.topic_prefix = config.topic_prefix
        var node = this;
        this.on('input', function(msg) {
		var re = new RegExp(["^", node.topic_prefix].join(""));
		var topic = msg.topic.replace(re, "");
		node.warn(topic);
		topic = topic.replace(/\/set$/, "");
		node.warn(topic);
		var vals = topic.split("\/");
		nodeid = vals[0];
		port = parseInt(vals[1]);
		value = parseInt(msg.payload);
		buf = new Buffer(14);
		buf.fill(0);
                if (port >= 1 && port <= 16) {
	        	buf.writeUInt8(nodeid, 0);
			buf.writeUInt16LE(value, 2);
		} else {
			buf.writeUInt8(1, 1);
	        	buf.writeUInt8(nodeid, 0);
			buf.writeUInt16LE(value, 2);
		}
		node.send({payload: buf});
		node.send({payload: {nodeid: vals[0], port: vals[1], value: msg.payload} });
	});
    }
    RED.nodes.registerType("coe-out",TaCmiCoeOutNode);
}
<commit_msg>Support different analog port<commit_after>module.exports = function(RED) {
    function TaCmiCoeOutNode(config) {
        RED.nodes.createNode(this,config);
	this.topic_prefix = config.topic_prefix
        var node = this;
        this.on('input', function(msg) {
		var re = new RegExp(["^", node.topic_prefix].join(""));
		var topic = msg.topic.replace(re, "");
		node.warn(topic);
		topic = topic.replace(/\/set$/, "");
		node.warn(topic);
		var vals = topic.split("\/");
		nodeid = vals[0];
		port = parseInt(vals[1]);
		value = parseInt(msg.payload);
		buf = new Buffer(14);
		buf.fill(0);
                if (port >= 1 && port <= 16) {
	        	buf.writeUInt8(nodeid, 0);
			buf.writeUInt16LE(value, 2);
		} else {
                        var group = Math.floor(((port-17)/4)+1);
			buf.writeUInt8(group, 1);
	        	buf.writeUInt8(nodeid, 0);
			buf.writeUInt16LE(value, 2);
		}
		node.send({payload: buf});
		node.send({payload: {nodeid: vals[0], port: vals[1], value: msg.payload} });
	});
    }
    RED.nodes.registerType("coe-out",TaCmiCoeOutNode);
}
<|endoftext|>


<commit_before>(function($) {

  var isIE = /*@cc_on!@*/false || document.documentMode,
      globalIdCounter = 0;

  var blurText = function($spoiler, radius) {
    var textShadow = "black 0 0 " + radius + "px";
    if (isIE) { textShadow = radius <= 0 ? "0 0 0 0 black" : "0 0 " + radius + "px .1px black"; }

    $spoiler.css("background-color", "transparent")
            .css("color", "rgba(0, 0, 0, 0)")
            .css("text-shadow", textShadow);
  };

  var blurImage = function($spoiler, radius) {
    // on the first pass, transform images into SVG
    $("img", $spoiler).each(function(index, image) {
      var transform = function() {
        var w = image.width,
            h = image.height,
            id = ++globalIdCounter;
        var svg = "<svg data-spoiler-id='" + id + "' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='" + w + "' height='" + h + "'>" +
                  "<defs><filter id='blur-" + id + "'><feGaussianBlur id='gaussian-" + id + "' stdDeviation='" + radius + "'></feGaussianBlur></filter></defs>" +
                  "<image xlink:href='" + image.src + "' filter='url(#blur-" + id + ")' width='" + w + "' height='" + h + "'></image>" +
                  "</svg>";
        $(image).replaceWith(svg);
      };
      // do we need to wait for the image to load?
      if (image.naturalWidth === 0 || image.naturalHeight === 0) {
        image.onload = transform;
      } else {
        transform();
      }
    });

    // change the blur radius
    $("svg", $spoiler).each(function(index, svg) {
      var id = svg.getAttribute("data-spoiler-id");
      svg.getElementById("gaussian-" + id).setAttribute("stdDeviation", radius);
    });
  };

  var applySpoilers = function($spoiler, options, applyBlur) {
    var maxBlur = options.max,
        partialBlur = options.partial;

    $spoiler.data("spoiler-state", "blurred");

    applyBlur($spoiler, maxBlur);

    $spoiler.on("mouseover", function() {
      $spoiler.css("cursor", "pointer");
      if ($spoiler.data("spoiler-state") === "blurred") { applyBlur($spoiler, partialBlur); }
    }).on("mouseout", function() {
      if ($spoiler.data("spoiler-state") === "blurred") { applyBlur($spoiler, maxBlur); }
    }).on("click", function(e) {
      if ($spoiler.data("spoiler-state") === "blurred") {
        $spoiler.data("spoiler-state", "revealed").css("cursor", "auto");
        applyBlur($spoiler, 0);
      } else {
        $spoiler.data("spoiler-state", "blurred").css("cursor", "pointer");
        applyBlur($spoiler, partialBlur);
      }
      e.preventDefault();
    });

  };

  $.fn.spoilText = function(options) {
    var defaults = { max: 10, partial: 5 },
        opts = $.extend(defaults, options || {});

    return this.each(function() {
      applySpoilers($(this), opts, blurText);
    });
  };

  $.fn.spoilImage = function(options) {
    var defaults = { max: 20, partial: 6 },
        opts = $.extend(defaults, options || {});

    return this.each(function() {
      applySpoilers($(this), opts, blurImage);
    });
  };

})(jQuery);
<commit_msg>FIX: make plugin compatible with dark theme<commit_after>(function($) {

  var isIE = /*@cc_on!@*/false || document.documentMode,
      globalIdCounter = 0;

  var blurText = function($spoiler, radius) {
    var textShadow = "gray 0 0 " + radius + "px";
    if (isIE) { textShadow = radius <= 0 ? "0 0 0 0 gray" : "0 0 " + radius + "px .1px gray"; }

    $spoiler.css("background-color", "transparent")
            .css("color", "rgba(0, 0, 0, 0)")
            .css("text-shadow", textShadow);
  };

  var blurImage = function($spoiler, radius) {
    // on the first pass, transform images into SVG
    $("img", $spoiler).each(function(index, image) {
      var transform = function() {
        var w = image.width,
            h = image.height,
            id = ++globalIdCounter;
        var svg = "<svg data-spoiler-id='" + id + "' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='" + w + "' height='" + h + "'>" +
                  "<defs><filter id='blur-" + id + "'><feGaussianBlur id='gaussian-" + id + "' stdDeviation='" + radius + "'></feGaussianBlur></filter></defs>" +
                  "<image xlink:href='" + image.src + "' filter='url(#blur-" + id + ")' width='" + w + "' height='" + h + "'></image>" +
                  "</svg>";
        $(image).replaceWith(svg);
      };
      // do we need to wait for the image to load?
      if (image.naturalWidth === 0 || image.naturalHeight === 0) {
        image.onload = transform;
      } else {
        transform();
      }
    });

    // change the blur radius
    $("svg", $spoiler).each(function(index, svg) {
      var id = svg.getAttribute("data-spoiler-id");
      svg.getElementById("gaussian-" + id).setAttribute("stdDeviation", radius);
    });
  };

  var applySpoilers = function($spoiler, options, applyBlur) {
    var maxBlur = options.max,
        partialBlur = options.partial;

    $spoiler.data("spoiler-state", "blurred");

    applyBlur($spoiler, maxBlur);

    $spoiler.on("mouseover", function() {
      $spoiler.css("cursor", "pointer");
      if ($spoiler.data("spoiler-state") === "blurred") { applyBlur($spoiler, partialBlur); }
    }).on("mouseout", function() {
      if ($spoiler.data("spoiler-state") === "blurred") { applyBlur($spoiler, maxBlur); }
    }).on("click", function(e) {
      if ($spoiler.data("spoiler-state") === "blurred") {
        $spoiler.data("spoiler-state", "revealed").css("cursor", "auto");
        applyBlur($spoiler, 0);
      } else {
        $spoiler.data("spoiler-state", "blurred").css("cursor", "pointer");
        applyBlur($spoiler, partialBlur);
      }
      e.preventDefault();
    });

  };

  $.fn.spoilText = function(options) {
    var defaults = { max: 10, partial: 5 },
        opts = $.extend(defaults, options || {});

    return this.each(function() {
      applySpoilers($(this), opts, blurText);
    });
  };

  $.fn.spoilImage = function(options) {
    var defaults = { max: 20, partial: 6 },
        opts = $.extend(defaults, options || {});

    return this.each(function() {
      applySpoilers($(this), opts, blurImage);
    });
  };

})(jQuery);
<|endoftext|>