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

    var gridSize = 3;
    var words = [
        "Staattinen tyypitys",
        "Microservices",
        "Haskell",
        "Clojure",
        "Lisp",
        "ES6",
        "Algebraiset tietotyypit",
        "HATEOAS",
        "Sivuvaikutus",
        "REST",
        "Eventually consistent",
        "Bus",
        "Messaging",
        "Broker",
        "Monadi"
    ];

    var template = Handlebars.default.compile(document.getElementById("grid-template").innerHTML),
        gridInstance = {
            words: shuffleArray(words).slice(0, gridSize*gridSize)
        },
        container = document.getElementById("gridContainer");

    container.innerHTML = template(gridInstance);

    function shuffleArray(array) {
        for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
        return array;
    }

})();
<commit_msg>Even more words.<commit_after>(function () {
    "use strict";

    var gridSize = 3;
    var words = [
        "Staattinen tyypitys",
        "Microservices",
        "Haskell",
        "Clojure",
        "Lisp",
        "ES6",
        "Algebraiset tietotyypit",
        "HATEOAS",
        "Sivuvaikutus",
        "REST",
        "Eventually consistent",
        "Bus",
        "Messaging",
        "Broker",
        "Monadi",
        "Vuotava abstraktio",
        "Monoliittinen",
        "SOA",
        "Reaktiivinen"
    ];

    var template = Handlebars.default.compile(document.getElementById("grid-template").innerHTML),
        gridInstance = {
            words: shuffleArray(words).slice(0, gridSize*gridSize)
        },
        container = document.getElementById("gridContainer");

    container.innerHTML = template(gridInstance);

    function shuffleArray(array) {
        for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
        return array;
    }

})();
<|endoftext|>


<commit_before>/**
 * @FileOverview Load javascript dependencies with integrity check and fallback to multiple source URLs
 *
 * Goals:
 *  1. Check integrity of files loaded (with a cryptographic hash),
 *     to enable the use of untrusted public or third-party repositories
 *  2. Conditionally load polyfills based on object presence
 *  3. Permit synchronous or asynchronous operation
 *  4. No own dependencies
 */

/*
  USAGE:

  If your code needs window.library provided by untrusted
  //cdn1/lib.js and //cdn2/path/lib.js or, as a less desireably
  fallbacks, at /js/lib.js, use the following code where "xHASHxx" is
  the SHA256 hash of the correct lib.js:

  window.library || window.need({"//cdn1/lib.js", "//cdn2/path/lib.js", "/js/lib.js"}, "xHASHxx");

  The first argument (non-present in this example) can optionally hold
  a callback function to be called after the code has been loaded and
  executed by injection into the DOM as a script element.  Code will
  not be evaluated unless it has the correct SHA256 hash.

  NOTE:

  You also have to tell the browser to not enforce the SAME-ORIGIN
  policy with cdn1 and cdn2 because this library uses a XMLHttpRequest
  to load the scripts.

  Execute synchronously if 0 is passed instead of a callback function.

  Open encoding issue:

    Currently, the script is loaded with unspecified encoding (which
    should avoid changing the file's hash through re-encoding), but
    then it utf8-encoded for hash calculation (included in the sha256
    function), and finally injected without this encoding.

    This is likely not the desired approach.
    Either not utf8-encoding at all until injection into the DOM,
    or utf8-encoding starting with the request headers might be correct
    (but those are untested guesses for now).

*/

// sha256 function from sha256.js
// at https://github.com/jbt/js-crypto by James Taylor
// license:
/* By attaching this document to the given files (the “work”), you, the licensee, are hereby granted free usage in both personal and commerical environments, without any obligation of attribution or payment (monetary or otherwise). The licensee is free to use, copy, modify, publish, distribute, sublicence, and/or merchandise the work, subject to the licensee inflecting a positive message unto someone. This includes (but is not limited to): smiling, being nice, saying “thank you”, assisting other persons, or any similar actions percolating the given concept.
The above copyright notice serves as a permissions notice also, and may optionally be included in copies or portions of the work.
The work is provided “as is”, without warranty or support, express or implied. The author(s) are not liable for any damages, misuse, or other claim, whether from or as a consequence of usage of the given work.
*/
sha256 = (function(){
  // Eratosthenes seive to find primes up to 311 for magic constants. This is why SHA256 is better than SHA1
  var i=1,
      j,
      K=[],
      H=[],
      sixteen=16;

  while(++i<18)
    for(j=i*i;j<312;j+=i)
      H[j]=1;

  function x(num,root){
    return(Math.pow(num,1/root)%1)*4294967296|0;
  }

  for(i=1,j=0;i<313;)
    if(!H[++i])
      H[j]=x(i,2), K[j++]=x(i,3);

  function add(x, y){
    return (((x>>1)+(y>>1))<<1)+(x&1)+(y&1) ;
    //var msw = (x >> sixteen) + (y >> sixteen) + ((y=(x & ffff) + (y & ffff)) >> sixteen);
    //return (msw << sixteen) | (y & ffff);
  }

  function S (X, n) { return ( X >>> n ) | (X << (32 - n)); }

  function SHA256(b){
    var HASH = H.slice(i=0),
        s = unescape(encodeURI(b)), /* encode as utf8 */
//      s=b,
        W = [],
        l = s.length,
        m = [],
        a, y, z;
    for(;i<l;) m[i>>2] |= (s.charCodeAt(i) & 0xff) << 8*(3 - i++%4);

    l *= 8;

    m[l >> 5] |= 0x80 << (24 - l % 32);
    m[z=((l + 64 >> 9) << 4) + 15] = l;

    for (i=0 ; i<z; i+=sixteen ) {
      a = HASH.slice(j=0,8);

      for (; j<64;a[4] = add(a[4],y)) {
        if (j < sixteen) W[j] = m[j + i];
        else W[j] = add(
          add(S(y=W[j-2],17) ^ S(y,19) ^ (y>>>10),   W[j - 7]),
          add(S(y=W[j-15],7) ^ S(y,18) ^ (y>>>3),   W[j - sixteen])
        );

        a.unshift(
          add(
            y=add(
              add(
                add(a.pop(),  S(b=a[4],6) ^ S(b,11) ^ S(b,25)),
                add((b&a[5]) ^ ((~b)&a[6]),  K[j])
              ),
              W[j++]
            ),
            add(S(l=a[0],2) ^ S(l,13) ^ S(l,22),  (l&a[1]) ^ (a[1]&a[2]) ^ (a[2]&l))
          )
        );
      }

      for(j=8;j--;) HASH[j] = add(a[j],HASH[j]);
    }

    for(s='';j<63;) s += ((HASH[++j>>3]>>4*(7-j%8))&15).toString(sixteen);

    return s;

  }
  return SHA256;
})();

/*window.*/need = (function(callback, urls, hash) {
    if (typeof callback === "object") {
	// optional parameter callback (which could be a string, function, or 0) is not present
	hash = urls;
	urls = callback;
    }

    xhr=new XMLHttpRequest();
    xhr.open("GET",urls[0],callback!==0);

    // try to log to console, if the browser lets us
    /*dev-only*/ var log = function(msg) { try { console.log(msg) } catch(e) {} };

    var fallback = function() {
	// try again, with the first item of urls (the url that just failed) removed

	/*dev-only*/	log("Need.js: Failed to load " + urls[0]);

	window.need(callback, urls.slice(1), hash)
    }

    var process = function(binStr) {
	// check and evaluate javascript data in binStr (if and only if it has the correct SHA256 hash)
	for (var i = 0, len = binStr.length; i < len; ++i) {
	    var byte = binStr.charCodeAt(i) & 0xff;  // byte at offset i
	}
	var actualHash = sha256(binStr);

	/*dev-only*/ if (typeof hash === 'undefined') {
	    /*dev-only*/ hash = actualHash;
	    /*dev-only*/ log('Need.js called without hash; change to:   need('+((callback!==urls)?callback+', ':'')+JSON.stringify(urls)+', "'+actualHash+'")');
	/*dev-only*/ }

	if (hash == actualHash) {
	    // TODO: Can we handle encodings other than utf8?  To
	    //       reliably form the hash, we had to override it but
	    //       now we need to interpret special charcters as
	    //       text.
	    if ((typeof callback === 'function') || (typeof callback === 'string')) {
		binStr = binStr + "\n;" + callback
	    }

	    // Javascript injection, found at
	    // http://stackoverflow.com/questions/6432984/adding-script-element-to-the-dom-and-have-the-javascript-run
	    var s = document.createElement('script');
	    s.type = 'text/javascript';
	    try {
		s.appendChild(document.createTextNode(binStr));
		document.body.appendChild(s);
	    } catch (e) {
		/*dev-only*/ log("Error appending script from" + urls[0]+": "+e);
	    }

	} else {
	    /*dev-only*/ log("Need.js: " + urls[0] + " has incorrect hash " + actualHash);

	    // TODO: Here some logging (to web server?) could be added
	    //       even for production use.  However, in many cases
	    //       the server logs will already show what is
	    //       happening due to the coming fallback request(s).

	    fallback();
	}
    }

    // Hack to pass bytes through unprocessed. Source:
    // http://www.html5rocks.com/en/tutorials/file/xhr2/
    xhr.overrideMimeType('text/plain; charset=x-user-defined');
    xhr.onreadystatechange = function(e) {
	if (this.readyState == 4 && this.status == 200) {
	    process(this.responseText);
	}
    };
    xhr.send();

    if (callback===0) {
	// synchronous case
	process(xhr.responseText);
    }
});
<commit_msg>clear callback if omitted<commit_after>/**
 * @FileOverview Load javascript dependencies with integrity check and fallback to multiple source URLs
 *
 * Goals:
 *  1. Check integrity of files loaded (with a cryptographic hash),
 *     to enable the use of untrusted public or third-party repositories
 *  2. Conditionally load polyfills based on object presence
 *  3. Permit synchronous or asynchronous operation
 *  4. No own dependencies
 */

/*
  USAGE:

  If your code needs window.library provided by untrusted
  //cdn1/lib.js and //cdn2/path/lib.js or, as a less desireably
  fallbacks, at /js/lib.js, use the following code where "xHASHxx" is
  the SHA256 hash of the correct lib.js:

  window.library || window.need({"//cdn1/lib.js", "//cdn2/path/lib.js", "/js/lib.js"}, "xHASHxx");

  The first argument (non-present in this example) can optionally hold
  a callback function to be called after the code has been loaded and
  executed by injection into the DOM as a script element.  Code will
  not be evaluated unless it has the correct SHA256 hash.

  NOTE:

  You also have to tell the browser to not enforce the SAME-ORIGIN
  policy with cdn1 and cdn2 because this library uses a XMLHttpRequest
  to load the scripts.

  Execute synchronously if 0 is passed instead of a callback function.

  Open encoding issue:

    Currently, the script is loaded with unspecified encoding (which
    should avoid changing the file's hash through re-encoding), but
    then it utf8-encoded for hash calculation (included in the sha256
    function), and finally injected without this encoding.

    This is likely not the desired approach.
    Either not utf8-encoding at all until injection into the DOM,
    or utf8-encoding starting with the request headers might be correct
    (but those are untested guesses for now).

*/

// sha256 function from sha256.js
// at https://github.com/jbt/js-crypto by James Taylor
// license:
/* By attaching this document to the given files (the “work”), you, the licensee, are hereby granted free usage in both personal and commerical environments, without any obligation of attribution or payment (monetary or otherwise). The licensee is free to use, copy, modify, publish, distribute, sublicence, and/or merchandise the work, subject to the licensee inflecting a positive message unto someone. This includes (but is not limited to): smiling, being nice, saying “thank you”, assisting other persons, or any similar actions percolating the given concept.
The above copyright notice serves as a permissions notice also, and may optionally be included in copies or portions of the work.
The work is provided “as is”, without warranty or support, express or implied. The author(s) are not liable for any damages, misuse, or other claim, whether from or as a consequence of usage of the given work.
*/
sha256 = (function(){
  // Eratosthenes seive to find primes up to 311 for magic constants. This is why SHA256 is better than SHA1
  var i=1,
      j,
      K=[],
      H=[],
      sixteen=16;

  while(++i<18)
    for(j=i*i;j<312;j+=i)
      H[j]=1;

  function x(num,root){
    return(Math.pow(num,1/root)%1)*4294967296|0;
  }

  for(i=1,j=0;i<313;)
    if(!H[++i])
      H[j]=x(i,2), K[j++]=x(i,3);

  function add(x, y){
    return (((x>>1)+(y>>1))<<1)+(x&1)+(y&1) ;
    //var msw = (x >> sixteen) + (y >> sixteen) + ((y=(x & ffff) + (y & ffff)) >> sixteen);
    //return (msw << sixteen) | (y & ffff);
  }

  function S (X, n) { return ( X >>> n ) | (X << (32 - n)); }

  function SHA256(b){
    var HASH = H.slice(i=0),
        s = unescape(encodeURI(b)), /* encode as utf8 */
//      s=b,
        W = [],
        l = s.length,
        m = [],
        a, y, z;
    for(;i<l;) m[i>>2] |= (s.charCodeAt(i) & 0xff) << 8*(3 - i++%4);

    l *= 8;

    m[l >> 5] |= 0x80 << (24 - l % 32);
    m[z=((l + 64 >> 9) << 4) + 15] = l;

    for (i=0 ; i<z; i+=sixteen ) {
      a = HASH.slice(j=0,8);

      for (; j<64;a[4] = add(a[4],y)) {
        if (j < sixteen) W[j] = m[j + i];
        else W[j] = add(
          add(S(y=W[j-2],17) ^ S(y,19) ^ (y>>>10),   W[j - 7]),
          add(S(y=W[j-15],7) ^ S(y,18) ^ (y>>>3),   W[j - sixteen])
        );

        a.unshift(
          add(
            y=add(
              add(
                add(a.pop(),  S(b=a[4],6) ^ S(b,11) ^ S(b,25)),
                add((b&a[5]) ^ ((~b)&a[6]),  K[j])
              ),
              W[j++]
            ),
            add(S(l=a[0],2) ^ S(l,13) ^ S(l,22),  (l&a[1]) ^ (a[1]&a[2]) ^ (a[2]&l))
          )
        );
      }

      for(j=8;j--;) HASH[j] = add(a[j],HASH[j]);
    }

    for(s='';j<63;) s += ((HASH[++j>>3]>>4*(7-j%8))&15).toString(sixteen);

    return s;

  }
  return SHA256;
})();

/*window.*/need = (function(callback, urls, hash) {
    if (typeof callback === "object") {
	// optional parameter callback (which could be a string, function, or 0) is not present
	hash = urls;
	urls = callback;
	callback = "";
    }

    xhr=new XMLHttpRequest();
    xhr.open("GET",urls[0],callback!==0);

    // try to log to console, if the browser lets us
    /*dev-only*/ var log = function(msg) { try { console.log(msg) } catch(e) {} };

    var fallback = function() {
	// try again, with the first item of urls (the url that just failed) removed

	/*dev-only*/	log("Need.js: Failed to load " + urls[0]);

	window.need(callback, urls.slice(1), hash)
    }

    var process = function(binStr) {
	// check and evaluate javascript data in binStr (if and only if it has the correct SHA256 hash)
	for (var i = 0, len = binStr.length; i < len; ++i) {
	    var byte = binStr.charCodeAt(i) & 0xff;  // byte at offset i
	}
	var actualHash = sha256(binStr);

	/*dev-only*/ if (typeof hash === 'undefined') {
	    /*dev-only*/ hash = actualHash;
	    /*dev-only*/ log('Need.js called without hash; change to:   need('+((callback!==urls)?callback+', ':'')+JSON.stringify(urls)+', "'+actualHash+'")');
	/*dev-only*/ }

	if (hash == actualHash) {
	    // TODO: Can we handle encodings other than utf8?  To
	    //       reliably form the hash, we had to override it but
	    //       now we need to interpret special charcters as
	    //       text.
	    if ((typeof callback === 'function') || (typeof callback === 'string')) {
		binStr = binStr + "\n;" + callback
	    }

	    // Javascript injection, found at
	    // http://stackoverflow.com/questions/6432984/adding-script-element-to-the-dom-and-have-the-javascript-run
	    var s = document.createElement('script');
	    s.type = 'text/javascript';
	    try {
		s.appendChild(document.createTextNode(binStr));
		document.body.appendChild(s);
	    } catch (e) {
		/*dev-only*/ log("Error appending script from" + urls[0]+": "+e);
	    }

	} else {
	    /*dev-only*/ log("Need.js: " + urls[0] + " has incorrect hash " + actualHash);

	    // TODO: Here some logging (to web server?) could be added
	    //       even for production use.  However, in many cases
	    //       the server logs will already show what is
	    //       happening due to the coming fallback request(s).

	    fallback();
	}
    }

    // Hack to pass bytes through unprocessed. Source:
    // http://www.html5rocks.com/en/tutorials/file/xhr2/
    xhr.overrideMimeType('text/plain; charset=x-user-defined');
    xhr.onreadystatechange = function(e) {
	if (this.readyState == 4 && this.status == 200) {
	    process(this.responseText);
	}
    };
    xhr.send();

    if (callback===0) {
	// synchronous case
	process(xhr.responseText);
    }
});
<|endoftext|>


<commit_before>/*
 * shall we output debug logs?
 * if so start the app with:
 *    DEBUG=ledconodel node app.js
 */
const debug = require('debug')('ledconodel');
const name = 'ledconodel';
debug('booting %s', name);

/*
 * require rpio2 node module to drive GPIO pins and use hardware pin numbering
 */
const Gpio = require('rpio2').Gpio;
var options = {
  gpiomem: true,          /* Use /dev/gpiomem */
  mapping: 'physical',    /* Use the P1-P40 numbering scheme */
}

/*
 * set the hardware pins for the 3 leds as a new instance of Gpio
 */
const greenled = new Gpio(19);
const redled = new Gpio(13);
const blueled = new Gpio(26);

/*
 * Set the initial state to low.  The state is set prior to the pin becoming
 * active, so is safe for devices which require a stable setup.
 */
greenled.open(Gpio.OUTPUT, Gpio.LOW);
redled.open(Gpio.OUTPUT, Gpio.LOW);
blueled.open(Gpio.OUTPUT, Gpio.LOW);

/*
 * include the adafruit.io client library to watch the feed
 */
//require xxx as adaio

/*
 * the name of the Adafruit.io feed we want to watch
 */
var feedname = "ledfeeder";

/*
 * the main watcher function - need to do this asynchronously
 */
void function watchfeed(data) {
	if (data == "red") {
    debug('red on');
    redled.open(Gpio.OUTPUT, Gpio.HIGH);
    redled.sleep(500)
    debug('red off');
		redled.open(Gpio.OUTPUT, Gpio.LOW);
	} else if (data == "green") {
    debug('green on');
    greenled.open(Gpio.OUTPUT, Gpio.HIGH);
    greenled.sleep(500)
    debug('green off');
		greenled.open(Gpio.OUTPUT, Gpio.LOW);
	} else if (data == "blue") {
    debug('blue on');
    blueled.open(Gpio.OUTPUT, Gpio.HIGH);
    blueled.sleep(500)
    debug('blue off');
		blueled.open(Gpio.OUTPUT, Gpio.LOW);
	} else {
		debug('unrecognized payload %s', data);
	}
} ();

watchfeed("red");
watchfeed("green");
watchfeed("blue");
debug('purple led is wrong');
watchfeed("purple");

debug('cloding GPIO');
redled.close();
greenled.close();
blueled.close();
debug('shutdown!');
process.exit(0);

/*
process.on("SIGINT", function(){
  redled.close();
  greenled.close();
  blueled.close();
  debug('shutdown!');
  process.exit(0);
});
*/
<commit_msg>rrote function watchfeed and exported everything<commit_after>var exports = module.exports = {};

/*
 * shall we output debug logs?
 * if so start the app with:
 *    DEBUG=ledconodel node app.js
 */
const debug = require('debug')('ledconodel');
const name = 'ledconodel';
debug('booting %s', name);

/*
 * require rpio2 node module to drive GPIO pins and use hardware pin numbering
 */
const Gpio = require('rpio2').Gpio;
var options = {
  gpiomem: true,          /* Use /dev/gpiomem */
  mapping: 'physical',    /* Use the P1-P40 numbering scheme */
}

/*
 * set the hardware pins for the 3 leds as a new instance of Gpio
 */
const greenled = new Gpio(19);
const redled = new Gpio(13);
const blueled = new Gpio(26);

/*
 * Set the initial state to low.  The state is set prior to the pin becoming
 * active, so is safe for devices which require a stable setup.
 */
greenled.open(Gpio.OUTPUT, Gpio.LOW);
redled.open(Gpio.OUTPUT, Gpio.LOW);
blueled.open(Gpio.OUTPUT, Gpio.LOW);

/*
 * include the adafruit.io client library to watch the feed
 */
//require xxx as adaio

/*
 * the name of the Adafruit.io feed we want to watch
 */
var feedname = "ledfeeder";

/*
 * the main watcher function - need to do this asynchronously
 */
void watchfeed = function(data) {
	if (data == "red") {
    debug('red on');
    redled.open(Gpio.OUTPUT, Gpio.HIGH);
    redled.sleep(500)
    debug('red off');
		redled.open(Gpio.OUTPUT, Gpio.LOW);
	} else if (data == "green") {
    debug('green on');
    greenled.open(Gpio.OUTPUT, Gpio.HIGH);
    greenled.sleep(500)
    debug('green off');
		greenled.open(Gpio.OUTPUT, Gpio.LOW);
	} else if (data == "blue") {
    debug('blue on');
    blueled.open(Gpio.OUTPUT, Gpio.HIGH);
    blueled.sleep(500)
    debug('blue off');
		blueled.open(Gpio.OUTPUT, Gpio.LOW);
	} else {
		debug('unrecognized payload %s', data);
	}
} ();

watchfeed("red");
watchfeed("green");
watchfeed("blue");
debug('purple led is wrong');
watchfeed("purple");

debug('cloding GPIO');
redled.close();
greenled.close();
blueled.close();
debug('shutdown!');
process.exit(0);

/*
process.on("SIGINT", function(){
  redled.close();
  greenled.close();
  blueled.close();
  debug('shutdown!');
  process.exit(0);
});
*/
<|endoftext|>


<commit_before>(function(){ /* Begin of privacy scope */
    "use strict";

/*
    Will be created using JISON but as I am not decided yet, I put everything
    hard-coded
*/

    // name[conditions]

    var
        _VALUE_TYPE_NAME = 0,
        _VALUE_TYPE_TEXT = 1,

        // a/b/c
        _sample1 = {
            nodeType: gpf.xml.NODE_ELEMENT,
            valueType: _VALUE_TYPE_NAME,
            value: "a",
            filter: null,
            then: {
                nodeType: gpf.xml.NODE_ELEMENT,
                valueType: _VALUE_TYPE_NAME,
                value: "b",
                filter: null,
                then: {
                    nodeType: gpf.xml.NODE_ELEMENT,
                    valueType: _VALUE_TYPE_NAME,
                    value: "c",
                    filter: null,
                    then: null
                }
            }
        },

        // a[b and c]
        _sample2 = {
            nodeType: gpf.xml.NODE_ELEMENT,
            valueType: _VALUE_TYPE_NAME,
            value: "a",
            filter: {
                operator: "and",
                items: [
                    {
                        nodeType: gpf.xml.NODE_ELEMENT,
                        valueType: _VALUE_TYPE_NAME,
                        value: "b",
                        filter: null,
                        then: null
                    }, {
                        nodeType: gpf.xml.NODE_ELEMENT,
                        valueType: _VALUE_TYPE_NAME,
                        value: "c",
                        filter: null,
                        then: null
                    }
                ]
            },
            then: null
        },
        // a[@d='1'] => a[@d[.='1']]
        _sample2 = {
            nodeType: gpf.xml.NODE_ELEMENT,
            valueType: _VALUE_TYPE_NAME,
            value: "a",
            filter: {
                operator: "and",
                items: [
                    {
                        nodeType: gpf.xml.NODE_ATTRIBUTE,
                        valueType: _VALUE_TYPE_NAME,
                        value: "d",
                        filter: {
                            operator: "and",
                            items: [{
                                nodeType: gpf.xml.NODE_TEXT,
                                valueType: _VALUE_TYPE_VALUE,
                                value: "1",
                                filter: null,
                                then: null
                            }]
                        },
                        then: null
                    }
                ]
            },
            then: null
        }
    ;

    gpf.xml.XPath = gpf.Class.extend({

        _xpath: null,

        init: function (xpath) {
            this._reset();
            if ("string" === typeof xpath) {
                this._xpath = this._compile(xpath)
            } else {
                this._xpath = xpath;
            }
        },

        /**
         * Compile the XPATH specifier
         *
         * @param {string} xpath
         * @private
         */
        _compile: function (xpath) {
            gpf.interfaces.ignoreParameter(xpath);
            this._xpath = null;
        },

        /**
         *
         * @param {gpf.xml.IXmlConstNode} node
         * @return {gpf.xml.IXmlConstNode|null}
         */
        evaluate: function (node) {
            gpf.interfaces.ignoreParameter(node);
            return null;
        }

    });

}()); /* End of privacy scope */
<commit_msg>XPath (continued)<commit_after>(function(){ /* Begin of privacy scope */
    "use strict";

/*
    Will be created using JISON but as I am not decided yet, I put everything
    hard-coded
*/

/*
    var
        // a/b/c
        _sample1 = {
            nodeType: gpf.xml.NODE_ELEMENT,
            name: "a",
            then: {
                nodeType: gpf.xml.NODE_ELEMENT,
                name: "b",
                then: {
                    nodeType: gpf.xml.NODE_ELEMENT,
                    name: "c"
                }
            }
        },

        // a[b and c]
        _sample2 = {
            nodeType: gpf.xml.NODE_ELEMENT,
            name: "a",
            filter: {
                and: [ {
                    nodeType: gpf.xml.NODE_ELEMENT,
                    name: "b"
                }, {
                    nodeType: gpf.xml.NODE_ELEMENT,
                    name: "c"
                }]
            }
        },
        // a[@d='1']
        _sample3 = {
            nodeType: gpf.xml.NODE_ELEMENT,
            name: "a",
            filter: {
                and: [{
                    nodeType: gpf.xml.NODE_ATTRIBUTE,
                    name: "d",
                    value: "1"
                }]
            }
        },
        //a
        _sample4 = {
            nodeType: gpf.xml.NODE_ELEMENT,
            name: "a",
            relative: false
        }
    ;
*/

    gpf.xml.XPath = gpf.Class.extend({

        _xpath: null,

        init: function (xpath) {
            this._reset();
            if ("string" === typeof xpath) {
                this._xpath = this._compile(xpath);
            } else {
                this._xpath = xpath;
            }
        },

        /**
         * Compile the XPATH specifier
         *
         * @param {string} xpath
         * @private
         */
        _compile: function (xpath) {
            gpf.interfaces.ignoreParameter(xpath);
            this._xpath = null;
        },

        /**
         *
         * @param {gpf.xml.IXmlConstNode} node
         * @return {gpf.xml.IXmlConstNode[]}
         */
        selectNodes: function (node) {
            var
                expr = this._xpath,
                resultSet = [node],
                idx, children;

            if (expr.nodeType === gpf.xml.NODE_ELEMENT) {
                for (idx = 0; idx < resultSet.length; ++idx) {
                    children = node.children();
                    // Select children corresponding to the criteria
                }
            } else {
                for (idx = 0; idx < resultSet.length; ++idx) {
                    children = node.attributes();
                    // Select children corresponding to the criteria
                }
            }

            return resultSet;
        }

    });

}()); /* End of privacy scope */
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var store = require('../dal')(require('../../config/configs.json').db)
var responseHelper = require('../helpers/responseHelper')

/* GET home page. */
router.get('/', (req, res, next) => {
    //TODO 1 = userID à remplacer
    store.repositories.shoots.get(1, (err, shoots) => {
        responseHelper(res, err, shoots)
    })
})

router.get('/:idShoot', (req, res, next) => {
    //TODO : Mettre variable user session ?
    store.repositories.shoots.getById(1, req.params.idShoot, (err, shoot) => {
        responseHelper(res, err, shoot)
    })
})

router.post('/', (req, res) => {
    var shootObject = {
        Title: req.body.title,
        Description: req.body.description,
        nb_Ends: req.body.nbEnds,
        nb_ArrowsByEnd: req.body.nbArrowsEnd,
        Type: req.body.type,
        User: req.body.user, //TODO: voir avec auth pour récuprer l'user
        Location: {
            longitude: req.body.long,
            latitude: req.body.lat
        }
    }
    store.repositories.shoots.add(shootObject, (err, status) => {
        responseHelper(res, err, status)
    })
})

router.post('/:idShoot'), (req, res, next) => {
    store.repositories.shoots.finishShoot(req.params.idShoot, (err, created) => {
        responseHelper(res, err, created)
    })
}

module.exports = router;<commit_msg>add comment<commit_after>var express = require('express');
var router = express.Router();
var store = require('../dal')(require('../../config/configs.json').db)
var responseHelper = require('../helpers/responseHelper')

/* GET home page. */
router.get('/', (req, res, next) => {
    //TODO 1 = userID à remplacer
    store.repositories.shoots.get(1, (err, shoots) => {
        responseHelper(res, err, shoots)
    })
})

router.get('/:idShoot', (req, res, next) => {
    //TODO : Mettre variable user session ?
    store.repositories.shoots.getById(1, req.params.idShoot, (err, shoot) => {
        responseHelper(res, err, shoot)
    })
})

router.post('/', (req, res) => {
    var shootObject = {
        Title: req.body.title,
        Description: req.body.description,
        nb_Ends: req.body.nbEnds,
        nb_ArrowsByEnd: req.body.nbArrowsEnd,
        Type: req.body.type,
        User: req.body.user, //TODO: voir avec auth pour récuprer l'user
        Location: {
            longitude: req.body.long,
            latitude: req.body.lat
        }
    }
    store.repositories.shoots.add(shootObject, (err, status) => {
        responseHelper(res, err, status)
    })
})

router.post('/finish'), (req, res, next) => { //TODO: Voir pourquoi ça marche pas comme ça ?!? --> return 404 page not found direct ?
    store.repositories.shoots.finishShoot(req.body.idShoot, (err, created) => {
        responseHelper(res, err, created)
    })
}

module.exports = router;<|endoftext|>


<commit_before>var superagent = require("superagent"),
    chai = require("chai"),
    expect = chai.expect,
    should = require("should");

describe("Index", function () {
  it("renders HTML", function (done) {
    superagent.get("http://localhost:3000/")
      .end(function (e, res) {
        (e === null).should.equal(true);
        res.text.should.equal("hey_buddy_18!");
        done();
      });
  });
});
<commit_msg>hey_buddy_19<commit_after>var superagent = require("superagent"),
    chai = require("chai"),
    expect = chai.expect,
    should = require("should");

describe("Index", function () {
  it("renders HTML", function (done) {
    superagent.get("http://localhost:3000/")
      .end(function (e, res) {
        (e === null).should.equal(true);
        res.text.should.equal("hey_buddy_19!");
        done();
      });
  });
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import { task, timeout } from 'ember-concurrency';
import ResizeAware from 'ember-resize-for-addons';

const {
  Mixin,
  assign,
  computed,
  get,
  getOwner,
  getProperties,
  isNone,
  isPresent,
  observer,
  on,
  set,
  typeOf
} = Ember;

const {
  RSVP: {
    Promise,
    resolve
  }
} = Ember;

export default Mixin.create(ResizeAware, {
  isInstant: false,
  transitions: computed(() => []),

  _history: computed(() => Ember.A()),
  _transitionQueue: computed(() => Ember.A()),

  didResize() {
    this._handleResize();
  },

  _handleResize() {
    const accumulator = get(this, '_history').reduce((accumulator, transition) => {
      const selector = get(transition, 'element') || '_main';
      const selectorAccumulator = get(accumulator, selector) || set(accumulator, selector, {});

      assign(selectorAccumulator, this._generateEffect(get(transition, 'effect') || {}));

      return accumulator;
    }, {});

    Object.keys(accumulator).forEach((key) => {
      const element = key === '_main' ? this.element : this.$(key).get(0);

      this._performAnimation(element, { effect: accumulator[key], duration: 0, clear: true });
    });
  },

  animatorInstance: computed('animator', {
    get() {
      const adapter = get(this, 'animator') || 'jquery';

      return getOwner(this).lookup(`eab-animation-adapter:${adapter}`);
    }
  }),

  loadAndPerformQueue: on('init', observer('transitions.[]', function() {
    this._queueTransitions();

    get(this, '_mainQueueTask').perform();
  })),

  _queueTransitions() {
    const queue = get(this, '_transitionQueue');
    const history = get(this, '_history');
    const transitions = get(this, 'transitions');

    if (transitions) {
      queue.pushObjects(transitions);
      history.pushObjects(transitions);

      transitions.length = 0;
    }
  },

  _mainQueueTask: task(function * () {
    const queue = get(this, '_transitionQueue');

    if (queue.length > 0) {
      yield get(this, '_queueTask').perform('main', queue);

      if (typeOf(this.attrs.didCompleteQueue) === 'function') {
        this.attrs.didCompleteQueue();
      }
    }
  }).keepLatest(),

  _queueTask: task(function * (queueName, queue) {
    while (queue.length > 0) {
      yield this._executeNextTransition(queueName, queue);
    }
  }),

  _executeNextTransition(parentQueueName, queue) {
    const queueName = get(queue[0], 'queue');

    if (queueName === parentQueueName || isNone(queueName)) {
      return this._transitionSwitch(queue.shift());
    } else {
      this._startParallelQueue(queueName, queue);

      return resolve();
    }
  },

  _startParallelQueue(queueName, queue) {
    const exitTransition = queue.find((transition) => get(transition, 'queue') !== queueName);
    const queueLength = isPresent(exitTransition) ? queue.indexOf(exitTransition) : queue.length;

    get(this, '_queueTask').perform(queueName, queue.splice(0, queueLength));
  },

  _transitionSwitch(transition) {
    if (isPresent(get(transition, 'crossFade'))) {
      return this._crossFade(transition);
    } else if (isPresent(get(transition, 'effect'))) {
      return this._animate(transition);
    } else if (isPresent(get(transition, 'external'))) {
      return this._resolveExternally(transition);
    } else {
      return this._delay(transition);
    }
  },

  _delay(transition) {
    return get(this, 'isInstant') ? resolve() : timeout(get(transition, 'duration'));
  },

  _resolveExternally(transition) {
    return new Promise((resolve) => {
      this.attrs.externalAction(get(transition, 'external'), resolve);
    });
  },

  _animate(transition) {
    const selector = get(transition, 'element');
    const activeInstanceClass = get(this, '_activeInstanceClass');
    const activeInstanceSelector = activeInstanceClass ? `.${activeInstanceClass}` : '';
    const element = this.$(isPresent(selector) ? `${activeInstanceSelector} ${selector}` : undefined).get(0);

    return this._performAnimation(element, transition);
  },

  _performAnimation(element, transition) {
    const effect = this._generateEffect(get(transition, 'effect') || {});
    const options = getProperties(transition, ...Object.keys(transition));

    Reflect.deleteProperty(options, 'queue');
    Reflect.deleteProperty(options, 'element');

    if (get(this, 'isInstant')) {
      set(options, 'duration', 0);
    }

    return get(this, 'animatorInstance').animate(element, effect, options);
  },

  _generateEffect(container) {
    return Object.keys(container).reduce((accumulator, key) => {
      if (key.includes('@media')) {
        if (this._mediaQueryIsValid(key)) {
          assign(accumulator, get(container, key));
        }
      } else {
        accumulator[key] = container[key];
      }

      return accumulator;
    }, {});
  },

  _mediaQueryIsValid(string) {
    return string.match(/\(([^)]+?)\)/g).every((query) => {
      const [property, value] = query.substring(1, query.length - 1).split(':');

      switch (property) {
        case 'min-height': return this._hasMinHeight(value);
        case 'max-height': return this._hasMaxHeight(value);
        case 'min-width': return this._hasMinWidth(value);
        case 'max-width': return this._hasMaxWidth(value);
        default: return false;
      }
    });
  },

  _hasMinHeight(value) {
    return this.element.clientHeight >= parseInt(value, 10);
  },

  _hasMaxHeight(value) {
    return this.element.clientHeight <= parseInt(value, 10);
  },

  _hasMinWidth(value) {
    return this.element.clientWidth >= parseInt(value, 10);
  },

  _hasMaxWidth(value) {
    return this.element.clientWidth <= parseInt(value, 10);
  }
});
<commit_msg>seperate the core logic into a mixin<commit_after>import Ember from 'ember';
import { task, timeout } from 'ember-concurrency';
import ResizeAware from 'ember-resize-for-addons';

const {
  Mixin,
  assign,
  computed,
  get,
  getOwner,
  getProperties,
  isNone,
  isPresent,
  observer,
  on,
  set,
  typeOf
} = Ember;

const {
  RSVP: {
    Promise,
    resolve
  }
} = Ember;

export default Mixin.create(ResizeAware, {
  isInstant: false,
  transitions: computed(() => []),

  _history: computed(() => Ember.A()),
  _transitionQueue: computed(() => Ember.A()),

  didResize() {
    this._handleResize();
  },

  _handleResize() {
    const accumulator = get(this, '_history').reduce((accumulator, transition) => {
      const selector = get(transition, 'element') || '_main';
      const selectorAccumulator = get(accumulator, selector) || set(accumulator, selector, {});

      assign(selectorAccumulator, this._generateEffect(get(transition, 'effect') || {}));

      return accumulator;
    }, {});

    Object.keys(accumulator).forEach((key) => {
      const element = key === '_main' ? this.element : this.$(key).get(0);

      this._performAnimation(element, { effect: accumulator[key], duration: 0, clear: true });
    });
  },

  animatorInstance: computed('animator', {
    get() {
      const adapter = get(this, 'animator') || 'jquery';

      return getOwner(this).lookup(`eab-animation-adapter:${adapter}`);
    }
  }),

  loadAndPerformQueue: on('init', observer('transitions.[]', function() {
    this._queueTransitions();

    get(this, '_mainQueueTask').perform();
  })),

  _queueTransitions() {
    const queue = get(this, '_transitionQueue');
    const history = get(this, '_history');
    const transitions = get(this, 'transitions');

    if (transitions) {
      queue.pushObjects(transitions);
      history.pushObjects(transitions);

      transitions.clear ? transitions.clear() : transitions.length = 0;
    }
  },

  _mainQueueTask: task(function * () {
    const queue = get(this, '_transitionQueue');

    if (queue.length > 0) {
      yield get(this, '_queueTask').perform('main', queue);

      if (typeOf(this.attrs.didCompleteQueue) === 'function') {
        this.attrs.didCompleteQueue();
      } else if (typeOf(this.didCompleteQueue) === 'function') {
        this.didCompleteQueue();
      }
    }
  }).keepLatest(),

  _queueTask: task(function * (queueName, queue) {
    while (queue.length > 0) {
      yield this._executeNextTransition(queueName, queue);
    }
  }),

  _executeNextTransition(parentQueueName, queue) {
    const queueName = get(queue[0], 'queue');

    if (queueName === parentQueueName || isNone(queueName)) {
      return this._transitionSwitch(queue.shift());
    } else {
      this._startParallelQueue(queueName, queue);

      return resolve();
    }
  },

  _startParallelQueue(queueName, queue) {
    const exitTransition = queue.find((transition) => get(transition, 'queue') !== queueName);
    const queueLength = isPresent(exitTransition) ? queue.indexOf(exitTransition) : queue.length;

    get(this, '_queueTask').perform(queueName, queue.splice(0, queueLength));
  },

  _transitionSwitch(transition) {
    if (isPresent(get(transition, 'crossFade'))) {
      return this._crossFade(transition);
    } else if (isPresent(get(transition, 'effect'))) {
      return this._animate(transition);
    } else if (isPresent(get(transition, 'external'))) {
      return this._resolveExternally(transition);
    } else {
      return this._delay(transition);
    }
  },

  _delay(transition) {
    return get(this, 'isInstant') ? resolve() : timeout(get(transition, 'duration'));
  },

  _resolveExternally(transition) {
    return new Promise((resolve) => {
      this.attrs.externalAction(get(transition, 'external'), resolve);
    });
  },

  _animate(transition) {
    const selector = get(transition, 'element');
    const activeInstanceClass = get(this, '_activeInstanceClass');
    const activeInstanceSelector = activeInstanceClass ? `.${activeInstanceClass}` : '';
    const element = this.$(isPresent(selector) ? `${activeInstanceSelector} ${selector}` : undefined).get(0);

    return this._performAnimation(element, transition);
  },

  _performAnimation(element, transition) {
    const effect = this._generateEffect(get(transition, 'effect') || {});
    const options = getProperties(transition, ...Object.keys(transition));

    Reflect.deleteProperty(options, 'queue');
    Reflect.deleteProperty(options, 'element');

    if (get(this, 'isInstant')) {
      set(options, 'duration', 0);
    }

    return get(this, 'animatorInstance').animate(element, effect, options);
  },

  _generateEffect(container) {
    return Object.keys(container).reduce((accumulator, key) => {
      if (key.includes('@media')) {
        if (this._mediaQueryIsValid(key)) {
          assign(accumulator, get(container, key));
        }
      } else {
        accumulator[key] = container[key];
      }

      return accumulator;
    }, {});
  },

  _mediaQueryIsValid(string) {
    return string.match(/\(([^)]+?)\)/g).every((query) => {
      const [property, value] = query.substring(1, query.length - 1).split(':');

      switch (property) {
        case 'min-height': return this._hasMinHeight(value);
        case 'max-height': return this._hasMaxHeight(value);
        case 'min-width': return this._hasMinWidth(value);
        case 'max-width': return this._hasMaxWidth(value);
        default: return false;
      }
    });
  },

  _hasMinHeight(value) {
    return this.element.clientHeight >= parseInt(value, 10);
  },

  _hasMaxHeight(value) {
    return this.element.clientHeight <= parseInt(value, 10);
  },

  _hasMinWidth(value) {
    return this.element.clientWidth >= parseInt(value, 10);
  },

  _hasMaxWidth(value) {
    return this.element.clientWidth <= parseInt(value, 10);
  }
});
<|endoftext|>


<commit_before>/** @namespace */
var THREEx	= THREEx 		|| {};

// forced closure
(function(){

	/**
	 * Take a screenshot of a renderer
	 * - require WebGLRenderer to have "preserveDrawingBuffer: true" to be set
	 * - TODO is it possible to check if this variable is set ? if so check it
	 *   and make advice in the console.log
	 *   - maybe with direct access to the gl context...
	 *
	 * @param {Object} renderer to use
	 * @param {String} mimetype of the output image. default to "image/png"
	 * @param {String} dataUrl of the image
	*/
	var toDataURL	= function(renderer, mimetype)
	{
		mimetype	= mimetype	|| "image/png";
		var dataUrl	= renderer.domElement.toDataURL(mimetype);
		return dataUrl;
	}

	/**
	 * resize an image to another resolution while preserving aspect
	 *
	 * @param {String} srcUrl the url of the image to resize
	 * @param {Number} dstWidth the destination width of the image
	 * @param {Number} dstHeight the destination height of the image
	 * @param {Number} callback the callback to notify once completed with callback(newImageUrl)
	*/
	var _aspectResize	= function(srcUrl, dstW, dstH, callback){
		// to compute the width/height while keeping aspect
		var cpuScaleAspect	= function(maxW, maxH, curW, curH){
			var ratio	= curH / curW;
			if( curW >= maxW && ratio <= 1 ){
				curW	= maxW;
				curH	= maxW * ratio;
			}else if(curH >= maxH){
				curH	= maxH;
				curW	= maxH / ratio;
			}
			return { width: curW, height: curH };
		}
		// callback once the image is loaded
		var onLoad	= function(){
			// init the canvas
			var canvas	= document.createElement('canvas');
			canvas.width	= dstW;	canvas.height	= dstH;
			var ctx		= canvas.getContext('2d');

			// TODO is this needed
			ctx.fillStyle	= "black";
			ctx.fillRect(0, 0, canvas.width, canvas.height);

			// scale the image while preserving the aspect
			var scaled	= cpuScaleAspect(canvas.width, canvas.height, image.width, image.height);

			// actually draw the image on canvas
			var offsetX	= (canvas.width  - scaled.width )/2;
			var offsetY	= (canvas.height - scaled.height)/2;
			ctx.drawImage(image, offsetX, offsetY, scaled.width, scaled.height);

			// dump the canvas to an URL
			var mimetype	= "image/png";
			var newDataUrl	= canvas.toDataURL(mimetype);
			// notify the url to the caller
			callback && callback(newDataUrl)
		}.bind(this);

		// Create new Image object
		var image 	= new Image();
		image.onload	= onLoad;
		image.src	= srcUrl;
	}

	// Super cooked function: THREEx.Screenshot.bindKey(renderer)
	// and you are done to get screenshot on your demo

	/**
	 * Bind a key to renderer screenshot
	*/
	var bindKey	= function(renderer, opts){
		// handle parameters
		opts		= opts		|| {};
		opts.charCode	= opts.charCode	|| 'p'.charCodeAt(0);
		opts.width	= opts.width	|| 640;
		opts.height	= opts.height	|| 480;
		opts.callback	= opts.callback	|| function(url){
			window.open(url);
		};

		// callback to handle keypress
		var onKeyPress	= function(event){
			// return now if the KeyPress isnt for the proper charCode
			if( event.which !== opts.charCode )	return;
			// get the renderer output
			var dataUrl	= this.toDataURL(renderer);
			// resize it and notify the callback
			_aspectResize(dataUrl, opts.width, opts.height, callback);
		}.bind(this);

		// listen to keypress
		// NOTE: for firefox it seems mandatory to listen to document directly
		document.addEventListener('keypress', onKeyPress, false);

		return {
			unbind	: function(){
				document.removeEventListener('keypress', onKeyPress, false);
			}
		};
	}

	// export it
	THREEx.Screenshot	= {
		toDataURL	: toDataURL,
		bindKey		: bindKey
	};
})();
<commit_msg>THREEx.screenshot.js bug fix on callback parameter (thanks datrader)<commit_after>/** @namespace */
var THREEx	= THREEx 		|| {};

// forced closure
(function(){

	/**
	 * Take a screenshot of a renderer
	 * - require WebGLRenderer to have "preserveDrawingBuffer: true" to be set
	 * - TODO is it possible to check if this variable is set ? if so check it
	 *   and make advice in the console.log
	 *   - maybe with direct access to the gl context...
	 *
	 * @param {Object} renderer to use
	 * @param {String} mimetype of the output image. default to "image/png"
	 * @param {String} dataUrl of the image
	*/
	var toDataURL	= function(renderer, mimetype)
	{
		mimetype	= mimetype	|| "image/png";
		var dataUrl	= renderer.domElement.toDataURL(mimetype);
		return dataUrl;
	}

	/**
	 * resize an image to another resolution while preserving aspect
	 *
	 * @param {String} srcUrl the url of the image to resize
	 * @param {Number} dstWidth the destination width of the image
	 * @param {Number} dstHeight the destination height of the image
	 * @param {Number} callback the callback to notify once completed with callback(newImageUrl)
	*/
	var _aspectResize	= function(srcUrl, dstW, dstH, callback){
		// to compute the width/height while keeping aspect
		var cpuScaleAspect	= function(maxW, maxH, curW, curH){
			var ratio	= curH / curW;
			if( curW >= maxW && ratio <= 1 ){
				curW	= maxW;
				curH	= maxW * ratio;
			}else if(curH >= maxH){
				curH	= maxH;
				curW	= maxH / ratio;
			}
			return { width: curW, height: curH };
		}
		// callback once the image is loaded
		var onLoad	= function(){
			// init the canvas
			var canvas	= document.createElement('canvas');
			canvas.width	= dstW;	canvas.height	= dstH;
			var ctx		= canvas.getContext('2d');

			// TODO is this needed
			ctx.fillStyle	= "black";
			ctx.fillRect(0, 0, canvas.width, canvas.height);

			// scale the image while preserving the aspect
			var scaled	= cpuScaleAspect(canvas.width, canvas.height, image.width, image.height);

			// actually draw the image on canvas
			var offsetX	= (canvas.width  - scaled.width )/2;
			var offsetY	= (canvas.height - scaled.height)/2;
			ctx.drawImage(image, offsetX, offsetY, scaled.width, scaled.height);

			// dump the canvas to an URL
			var mimetype	= "image/png";
			var newDataUrl	= canvas.toDataURL(mimetype);
			// notify the url to the caller
			callback && callback(newDataUrl)
		}.bind(this);

		// Create new Image object
		var image 	= new Image();
		image.onload	= onLoad;
		image.src	= srcUrl;
	}

	// Super cooked function: THREEx.Screenshot.bindKey(renderer)
	// and you are done to get screenshot on your demo

	/**
	 * Bind a key to renderer screenshot
	*/
	var bindKey	= function(renderer, opts){
		// handle parameters
		opts		= opts		|| {};
		opts.charCode	= opts.charCode	|| 'p'.charCodeAt(0);
		opts.width	= opts.width	|| 640;
		opts.height	= opts.height	|| 480;
		opts.callback	= opts.callback	|| function(url){
			window.open(url);
		};

		// callback to handle keypress
		var onKeyPress	= function(event){
			// return now if the KeyPress isnt for the proper charCode
			if( event.which !== opts.charCode )	return;
			// get the renderer output
			var dataUrl	= this.toDataURL(renderer);
			// resize it and notify the callback
			_aspectResize(dataUrl, opts.width, opts.height, opts.callback);
		}.bind(this);

		// listen to keypress
		// NOTE: for firefox it seems mandatory to listen to document directly
		document.addEventListener('keypress', onKeyPress, false);

		return {
			unbind	: function(){
				document.removeEventListener('keypress', onKeyPress, false);
			}
		};
	}

	// export it
	THREEx.Screenshot	= {
		toDataURL	: toDataURL,
		bindKey		: bindKey
	};
})();
<|endoftext|>


<commit_before>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');

// create tab group
var tabGroup = Titanium.UI.createTabGroup();

//
// create base UI tab and root window
//
var win1 = Titanium.UI.createWindow({
    title:'Tab 1',
    backgroundColor:'#fff'
});
var tab1 = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Tab 1',
    window:win1
});

var label1 = Titanium.UI.createLabel({
	color:'#999',
	text:'I am Window 1',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

win1.add(label1);

//
// create controls tab and root window
//
var win2 = Titanium.UI.createWindow({
    title:'Tab 2',
    backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
    icon:'KS_nav_ui.png',
    title:'Tab 2',
    window:win2
});

var label2 = Titanium.UI.createLabel({
	color:'#999',
	text:'I am Window 2',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

win2.add(label2);

//
//  add tabs
//
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);

// open tab group
tabGroup.open();
<commit_msg>initializing<commit_after>config = {
	osname: Ti.Platform.osname,
	resPath: Ti.Filesystem.resourcesDirectory,
	platformWidth: Ti.Platform.displayCaps.platformWidth,
	platformHeight: Ti.Platform.displayCaps.platformHeight,
	viewPath: Ti.Filesystem.resourcesDirectory+'views/',
	modelPath: Ti.Filesystem.resourcesDirectory+'model/',
	imgPath: Ti.Filesystem.resourcesDirectory+'images/'
	//dbPath: Ti.Filesystem.resourcesDirectory+'FieldAgent.db',
	//paint: require('ti.paint'),
	//segmentedControl: require('/views/custTabBar')
};
try
{
	//config.db = Ti.Database.install(config.dbPath,'FieldService');
	Ti.include(config.viewPath+'mainView.js');
	mainView.open(config);
}
catch(e)
{
	alert(e);
}<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide('frappe.views');

// opts:
// stats = list of fields
// doctype
// parent
// set_filter = function called on click

frappe.views.ListSidebar = Class.extend({
	init: function(opts) {
		$.extend(this, opts);
		this.make();
		this.get_stats();
	},
	make: function() {
		var sidebar_content = frappe.render_template("list_sidebar", {doctype: this.doclistview.doctype});

		this.offcanvas_list_sidebar = $(".offcanvas .list-sidebar").html(sidebar_content);
		this.page_sidebar = $('

')
			.html(sidebar_content)
			.appendTo(this.page.sidebar.empty());

		this.sidebar = this.page_sidebar.add(this.offcanvas_list_sidebar);

		this.setup_assigned_to_me();

		if(frappe.views.calendar[this.doctype]) {
			this.sidebar.find(".calendar-link, .gantt-link").removeClass("hide");
		}
	},
	setup_assigned_to_me: function() {
		var me = this;
		this.page.sidebar.find(".assigned-to-me a").on("click", function() {
			me.doclistview.assigned_to_me();
		});

		this.offcanvas_list_sidebar.find(".assigned-to-me a").on("click", function() {
			me.doclistview.assigned_to_me();
		});
	},
	get_stats: function() {
		var me = this
		return frappe.call({
			type: "GET",
			method: 'frappe.desk.reportview.get_stats',
			args: {
				stats: me.stats,
				doctype: me.doctype
			},
			callback: function(r) {
				if (me.defined_category ){
					 me.cats = {};
					for (i in me.defined_category){
						if (me.cats[me.defined_category[i].category]===undefined)
							{
							me.cats[me.defined_category[i].category]=[me.defined_category[i].tag];
						}else{

							me.cats[me.defined_category[i].category].push(me.defined_category[i].tag);
						}

					}
					me.tempstats = r.message
					var len = me.cats.length
					$.each(me.cats, function (i, v) {
						me.render_stat(i, (me.tempstats || {})["_user_tags"],v);
					});
					$.each(me.stats, function (i, v) {
					me.render_stat(v, (me.tempstats || {})[v]);
					});
				}
				else
				{
					//render normal stats
					// This gives a predictable stats order
					$.each(me.stats, function (i, v) {
						me.render_stat(v, (r.message || {})[v]);
					});
				}

				// reload button at the end
				// if(me.stats.length) {
				// 	$(''+__('Refresh Stats')+'')
				// 		.css({"margin-top":"15px", "display":"inline-block"})
				// 		.click(function() {
				// 			me.reload_stats();
				// 			return false;
				// 		}).appendTo($('
')
				// 			.appendTo(me.sidebar));
				// }

				me.doclistview.set_sidebar_height();
			}
		});
	},
	render_stat: function(field, stat,tags) {
		var me = this;
		var sum = 0;
		var stats = []
		var label = frappe.meta.docfield_map[this.doctype][field] ?
			frappe.meta.docfield_map[this.doctype][field].label : field;
		var show_tags = '';

		stat = (stat || []).sort(function(a, b) { return b[1] - a[1] });
		$.each(stat, function(i,v) { sum = sum + v[1]; })

		if(tags)
		{
			for (var t in tags) {
				var nfound = -1;
				for (var i in stat) {
					if (tags[t] ===stat[i][0]) {
						stats.push(stat[i]);
						nfound = i;
						break
					}
				}
				if (nfound<0)
				{
					stats.push([tags[t],0])
				}
				else
				{
					me.tempstats["_user_tags"].splice(nfound,1);
				}

			}
			field = "_user_tags"
		}
		else
		{
			stats = stat
		}
		var context = {
			field: field,
			stat: stats,
			sum: sum,
			label: label==='_user_tags' ? (__("UnCatagorised Tags") + show_tags) : tags ? __(label)+ show_tags: __(label),
		};

		var sidebar_stat = $(frappe.render_template("list_sidebar_stat", context))
			.on("click", ".stat-link", function() {
				var fieldname = $(this).attr('data-field');
				var label = $(this).attr('data-label');
				if (label == "No Tags") {
					me.doclistview.filter_list.add_filter(me.doclistview.doctype, fieldname, 'not like', '%,%')
					me.doclistview.run();
				} else {
					me.set_filter(fieldname, label);
				}
				return false;
			})
			.appendTo(this.sidebar);

	},
	reload_stats: function() {
		this.sidebar.find(".sidebar-stat").remove();
		this.get_stats();
	},
});
<commit_msg>add tag category to autocomplete<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide('frappe.views');

// opts:
// stats = list of fields
// doctype
// parent
// set_filter = function called on click

frappe.views.ListSidebar = Class.extend({
	init: function(opts) {
		$.extend(this, opts);
		this.make();
		this.get_stats();
		this.cat_tags = [];
	},
	make: function() {
		var sidebar_content = frappe.render_template("list_sidebar", {doctype: this.doclistview.doctype});

		this.offcanvas_list_sidebar = $(".offcanvas .list-sidebar").html(sidebar_content);
		this.page_sidebar = $('

')
			.html(sidebar_content)
			.appendTo(this.page.sidebar.empty());

		this.sidebar = this.page_sidebar.add(this.offcanvas_list_sidebar);

		this.setup_assigned_to_me();

		if(frappe.views.calendar[this.doctype]) {
			this.sidebar.find(".calendar-link, .gantt-link").removeClass("hide");
		}
	},
	setup_assigned_to_me: function() {
		var me = this;
		this.page.sidebar.find(".assigned-to-me a").on("click", function() {
			me.doclistview.assigned_to_me();
		});

		this.offcanvas_list_sidebar.find(".assigned-to-me a").on("click", function() {
			me.doclistview.assigned_to_me();
		});
	},
	get_cat_tags:function(){
		return this.cat_tags;
	},
	get_stats: function() {
		var me = this
		return frappe.call({
			type: "GET",
			method: 'frappe.desk.reportview.get_stats',
			args: {
				stats: me.stats,
				doctype: me.doctype
			},
			callback: function(r) {
				if (me.defined_category ){
					 me.cats = {};
					for (i in me.defined_category){
						if (me.cats[me.defined_category[i].category]===undefined)
							{
							me.cats[me.defined_category[i].category]=[me.defined_category[i].tag];
						}else{

							me.cats[me.defined_category[i].category].push(me.defined_category[i].tag);
						}
						me.cat_tags[i]=me.defined_category[i].tag
					}
					me.tempstats = r.message
					var len = me.cats.length
					$.each(me.cats, function (i, v) {
						me.render_stat(i, (me.tempstats || {})["_user_tags"],v);
					});
					$.each(me.stats, function (i, v) {
					me.render_stat(v, (me.tempstats || {})[v]);
					});
				}
				else
				{
					//render normal stats
					// This gives a predictable stats order
					$.each(me.stats, function (i, v) {
						me.render_stat(v, (r.message || {})[v]);
					});
				}

				// reload button at the end
				// if(me.stats.length) {
				// 	$(''+__('Refresh Stats')+'')
				// 		.css({"margin-top":"15px", "display":"inline-block"})
				// 		.click(function() {
				// 			me.reload_stats();
				// 			return false;
				// 		}).appendTo($('
')
				// 			.appendTo(me.sidebar));
				// }

				me.doclistview.set_sidebar_height();
			}
		});
	},
	render_stat: function(field, stat,tags) {
		var me = this;
		var sum = 0;
		var stats = []
		var label = frappe.meta.docfield_map[this.doctype][field] ?
			frappe.meta.docfield_map[this.doctype][field].label : field;
		var show_tags = '';

		stat = (stat || []).sort(function(a, b) { return b[1] - a[1] });
		$.each(stat, function(i,v) { sum = sum + v[1]; })

		if(tags)
		{
			for (var t in tags) {
				var nfound = -1;
				for (var i in stat) {
					if (tags[t] ===stat[i][0]) {
						stats.push(stat[i]);
						nfound = i;
						break
					}
				}
				if (nfound<0)
				{
					stats.push([tags[t],0])
				}
				else
				{
					me.tempstats["_user_tags"].splice(nfound,1);
				}

			}
			field = "_user_tags"
		}
		else
		{
			stats = stat
		}
		var context = {
			field: field,
			stat: stats,
			sum: sum,
			label: label==='_user_tags' ? (__("UnCatagorised Tags") + show_tags) : tags ? __(label)+ show_tags: __(label),
		};

		var sidebar_stat = $(frappe.render_template("list_sidebar_stat", context))
			.on("click", ".stat-link", function() {
				var fieldname = $(this).attr('data-field');
				var label = $(this).attr('data-label');
				if (label == "No Tags") {
					me.doclistview.filter_list.add_filter(me.doclistview.doctype, fieldname, 'not like', '%,%')
					me.doclistview.run();
				} else {
					me.set_filter(fieldname, label);
				}
				return false;
			})
			.appendTo(this.sidebar);

	},
	reload_stats: function() {
		this.sidebar.find(".sidebar-stat").remove();
		this.get_stats();
	},
});
<|endoftext|>


<commit_before>/* configure for building harfbuzz
 */

exports.configureCompiler = function(objectFile, compiler) {
	// object files: <conf>/object
	var a = /^([^\/]+)\/([^\/]+)$/.exec(objectFile);
	compiler.configuration = a[1];
	compiler.setSourceFile('repo/src/' + a[2] + '.cc');
	compiler.addIncludeDir('../freetype/repo/include');
	compiler.addIncludeDir('repo/src');
	compiler.addIncludeDir('../ucdn/repo');
	compiler.addIncludeDir('generated');
	compiler.addMacro('HB_NO_MT');
	compiler.addMacro('HAVE_OT');
	compiler.addMacro('HAVE_FREETYPE');
	compiler.addMacro('HAVE_UCDN');
	// crazy hacks for xbox
	if(compiler.platform == 'xbox') {
		compiler.addMacro('getenv=(char*)""+__noop');
		compiler.addMacro('HB_NO_MMAP');
	}

	compiler.strict = false;
};

var objects = [
	// base
	'hb-aat-layout',
	'hb-aat-map',
	'hb-blob',
	'hb-buffer',
	'hb-buffer-serialize',
	'hb-common',
	'hb-coretext',
	'hb-draw',
	'hb-face',
	'hb-fallback-shape',
	'hb-font',
	'hb-gdi',
	'hb-map',
	'hb-number',
	'hb-set',
	'hb-shape',
	'hb-shape-plan',
	'hb-shaper',
	'hb-static',
	'hb-style',
	'hb-subset',
	'hb-subset-cff-common',
	'hb-subset-cff1',
	'hb-subset-cff2',
	'hb-subset-input',
	'hb-subset-plan',
	'hb-ucd',
	'hb-unicode',

	// opentype
	'hb-ot-cff1-table',
	'hb-ot-cff2-table',
	'hb-ot-color',
	'hb-ot-face',
	'hb-ot-font',
	'hb-ot-layout',
	'hb-ot-map',
	'hb-ot-meta',
	'hb-ot-metrics',
	'hb-ot-name',
	'hb-ot-shape',
	'hb-ot-shape-complex-arabic',
	'hb-ot-shape-complex-default',
	'hb-ot-shape-complex-hangul',
	'hb-ot-shape-complex-hebrew',
	'hb-ot-shape-complex-indic',
	'hb-ot-shape-complex-indic-table',
	'hb-ot-shape-complex-khmer',
	'hb-ot-shape-complex-myanmar',
	'hb-ot-shape-complex-thai',
	'hb-ot-shape-complex-use',
	'hb-ot-shape-complex-use-table',
	'hb-ot-shape-complex-vowel-constraints',
	'hb-ot-shape-fallback',
	'hb-ot-shape-normalize',
	'hb-ot-tag',
	'hb-ot-var',

	// freetype
	'hb-ft',
];

exports.configureComposer = function(libraryFile, composer) {
	// library files: <conf>/library
	var a = /^(([^\/]+)\/)([^\/]+)$/.exec(libraryFile);
	var confDir = a[1];
	composer.configuration = a[2];
	for(var i = 0; i < objects.length; ++i)
		composer.addObjectFile(confDir + objects[i]);
};
<commit_msg>build harfbuzz via amalgamation<commit_after>/* configure for building harfbuzz
 */

exports.configureCompiler = function(objectFile, compiler) {
	// object files: <conf>/object
	var a = /^([^\/]+)\/([^\/]+)$/.exec(objectFile);
	compiler.configuration = a[1];
	compiler.setSourceFile('repo/src/' + a[2] + '.cc');
	compiler.addIncludeDir('../freetype/repo/include');
	compiler.addIncludeDir('repo/src');
	compiler.addIncludeDir('../ucdn/repo');
	compiler.addIncludeDir('generated');
	compiler.addMacro('HB_NO_MT');
	compiler.addMacro('HAVE_OT');
	compiler.addMacro('HAVE_FREETYPE');
	compiler.addMacro('HAVE_UCDN');
	// crazy hacks for xbox
	if(compiler.platform == 'xbox') {
		compiler.addMacro('getenv=(char*)""+__noop');
		compiler.addMacro('HB_NO_MMAP');
	}

	compiler.strict = false;
};

var objects = [
	// amalgamation file is available since Harfbuzz 2.6.0
	'harfbuzz'
];

exports.configureComposer = function(libraryFile, composer) {
	// library files: <conf>/library
	var a = /^(([^\/]+)\/)([^\/]+)$/.exec(libraryFile);
	var confDir = a[1];
	composer.configuration = a[2];
	for(var i = 0; i < objects.length; ++i)
		composer.addObjectFile(confDir + objects[i]);
};
<|endoftext|>


<commit_before>/*
 * Nice.js is extension of your JavaScript code to simplify your life.
 *
 * Nice.js extend Array, Number and other built-in types of javaScript
 * with new syntax.
 *
 * @author Anton Danilchenko - http://danilchenko.me
 * @url https://github.com/webui/nice.js
 */

// return Nth element from start
Array.prototype.first = function first (shift) {
    shift = shift || 0;
    return this[shift];
}
// return Nth element from end
Array.prototype.last = function last (shift) {
    shift = shift || 0;
    return this[this.length - shift - 1];
}

// check if number is integer
Number.prototype.isInteger = function isInteger () {
    var value = this.valueOf();
    return (value ^ 0) === value;
}
<commit_msg>Added backward compatibility check for ECMA6 built-in functions<commit_after>/*
 * Nice.js is extension of your JavaScript code to simplify your life.
 *
 * Nice.js extend Array, Number and other built-in types of javaScript
 * with new syntax.
 *
 * @author Anton Danilchenko - http://danilchenko.me
 * @url https://github.com/webui/nice.js
 */

if (! Array.prototype.first)
    // return Nth element from start
    Array.prototype.first = function first (shift) {
        shift = shift || 0;
        return this[shift];
    }

if (! Array.prototype.last)
    // return Nth element from end
    Array.prototype.last = function last (shift) {
        shift = shift || 0;
        return this[this.length - shift - 1];
    }

if (! Number.prototype.isInteger)
    // check if number is integer
    Number.prototype.isInteger = function isInteger () {
        var value = this.valueOf();
        return (value ^ 0) === value;
    }
<|endoftext|>


<commit_before>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/

// Firebase go online whenever the application is open
document.addEventListener("deviceready", function () {
    Firebase.goOnline();
});

// Not available faskes
$('#not-available').on('click', function() {
	alert("Faskes is not available")
})

// Get no antrian function
function getNoAntri(tipe, username, name) {
  // Define firebase URL
  var faskesRef = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username);

  // Log firebase URL
  console.log('Url :' + "https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username);

  // Warn user that this fiture need internet
	alert('Fitur ini membutuhkan internet untuk mengambil data');

  // Confirmation
  alert("Mohon konfirmasi ulang");
  var nama = prompt("Masukan nama"),
  nik = prompt("Masukan NIK:");
  if (nama != "" || nik.length != 16) {
    var pasien = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username + '/pasien/');
    // Initialize data
    faskesRef.on("value", function(snapshot) {
      /* var data = snapshot.val().antrian,
      one = 1,
      sum = data + one;

      faskesRef.update({
        nama: name,
        antrian: sum
      }); */

      // Print data
      alert('No antrian: ' + snapshot.val().antrian);

      // Push data to firebase
      pasien.push().set({
        nama: nama,
        nomor_antrian: snapshot.val().antrian
      })
    });
  } else {
    // Error message
    alert("Input anda tidak valid. \n Anda tidak bisa mendapatkan nomor antrian");
  }
}

function tempatTidur(tipe, username) {
  brea = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + '/faskes/' + username);
  brea.on("value", function(snapshot) {
    data = snapshot.val().tempat_tidur;
    alert('Jumlah Tempat Tidur: ' + data);
  })
}

function doctorProfile(nama, gambar, lulusan, tahun) {
  giant = "Lulusan: " + lulusan + "
" + "Tahun: " + tahun;
  swal({
    title: "Dr. " + nama,
    imageUrl: "../../img/" + gambar,
    text: giant,
    html: true
  })
  console.log('Gambar: ' + gambar)
}
<commit_msg>Some log<commit_after>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/

// Firebase go online whenever the application is open
document.addEventListener("deviceready", function () {
    Firebase.goOnline();
});

// Not available faskes
$('#not-available').on('click', function() {
	alert("Faskes is not available")
})

// Get no antrian function
function getNoAntri(tipe, username, name) {
  // Define firebase URL
  var faskesRef = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username);

  // Log firebase URL
  console.log('Url :' + "https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username);

  // Warn user that this fiture need internet
	alert('Fitur ini membutuhkan internet untuk mengambil data');

  // Confirmation
  alert("Mohon konfirmasi ulang");
  var nama = prompt("Masukan nama"),
  nik = prompt("Masukan NIK:");
  if (nama != "" || nik.length != 16) {
    var pasien = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username + '/pasien/');
    // Initialize data
    faskesRef.on("value", function(snapshot) {
      /* var data = snapshot.val().antrian,
      one = 1,
      sum = data + one;

      faskesRef.update({
        nama: name,
        antrian: sum
      }); */

      // Print data
      alert('No antrian: ' + snapshot.val().antrian);

      // Push data to firebase
      pasien.push().set({
        nama: nama,
        nomor_antrian: snapshot.val().antrian
      })
    });
  } else {
    // Error message
    alert("Input anda tidak valid. \n Anda tidak bisa mendapatkan nomor antrian");
  }
}

function tempatTidur(tipe, username) {
  brea = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + '/faskes/' + username);
  console.log('Getting data..');
  brea.on("value", function(snapshot) {
    data = snapshot.val().tempat_tidur;
    alert('Jumlah Tempat Tidur: ' + data);
  })
}

function doctorProfile(nama, gambar, lulusan, tahun) {
  giant = "Lulusan: " + lulusan + "
" + "Tahun: " + tahun;
  swal({
    title: "Dr. " + nama,
    imageUrl: "../../img/" + gambar,
    text: giant,
    html: true
  })
  console.log('Gambar: ' + gambar)
}
<|endoftext|>


<commit_before>'use strict';
var test = require('ava');
var defaultUid = require('./');

test(function (t) {
	process.platform = 'darwin';
	t.assert(defaultUid() === 501);
	t.assert(defaultUid('linux') === 1000);
	t.assert(defaultUid('unicorn') === undefined);
	t.end();
});
<commit_msg>fix tests on node 0.12<commit_after>'use strict';
var test = require('ava');
var defaultUid = require('./');

test(function (t) {
	if (process.platform === 'darwin') {
		t.assert(defaultUid() === 501);
	}

	if (process.platform === 'linux') {
		t.assert(defaultUid() === 1000);
	}

	t.assert(defaultUid('linux') === 1000);
	t.assert(defaultUid('unicorn') === undefined);

	t.end();
});
<|endoftext|>


<commit_before>frappe.provide("frappe.ui");
frappe.provide("frappe.web_form");
import EventEmitterMixin from '../../frappe/event_emitter';

export default class WebForm extends frappe.ui.FieldGroup {
	constructor(opts) {
		super();
		Object.assign(this, opts);
		frappe.web_form = this;
		frappe.web_form.events = {};
		Object.assign(frappe.web_form.events, EventEmitterMixin);
	}

	prepare(web_form_doc, doc) {
		Object.assign(this, web_form_doc);
		this.fields = web_form_doc.web_form_fields;
		this.doc = doc;
	}

	make() {
		super.make();
		this.set_field_values();
		if (this.introduction_text) this.set_form_description(this.introduction_text);
		if (this.allow_print && !this.is_new) this.setup_print_button();
		if (this.allow_delete && !this.is_new) this.setup_delete_button();
		if (this.is_new) this.setup_cancel_button();
		this.setup_primary_action();
		$(".link-btn").remove();

		// webform client script
		frappe.init_client_script && frappe.init_client_script();
		frappe.web_form.events.trigger('after_load');
		this.after_load && this.after_load();
	}

	on(fieldname, handler) {
		let field = this.fields_dict[fieldname];
		field.df.change = () => {
			handler(field, field.value);
		};
	}

	set_field_values() {
		if (this.doc.name) this.set_values(this.doc);
		else return;
	}

	set_default_values() {
		let values = frappe.utils.get_query_params();
		delete values.new;
		this.set_values(values);
	}

	set_form_description(intro) {
		let intro_wrapper = document.getElementById('introduction');
		intro_wrapper.innerHTML = intro;
	}

	add_button(name, type, action, wrapper_class=".web-form-actions") {
		const button = document.createElement("button");
		button.classList.add("btn", "btn-" + type, "btn-sm", "ml-2");
		button.innerHTML = name;
		button.onclick = action;
		document.querySelector(wrapper_class).appendChild(button);
	}

	add_button_to_footer(name, type, action) {
		this.add_button(name, type, action, '.web-form-footer');
	}

	add_button_to_header(name, type, action) {
		this.add_button(name, type, action, '.web-form-actions');
	}

	setup_primary_action() {
		this.add_button_to_header(this.button_label || "Save", "primary", () =>
			this.save()
		);

		this.add_button_to_footer(this.button_label || "Save", "primary", () =>
			this.save()
		);
	}

	setup_cancel_button() {
		this.add_button_to_header(__("Cancel"), "light", () => this.cancel());
	}

	setup_delete_button() {
		this.add_button_to_header(
			'',
			"light",
			() => this.delete()
		);
	}

	setup_print_button() {
		this.add_button_to_header(
			'',
			"light",
			() => this.print()
		);
	}

	save() {
		if (this.validate && !this.validate()) {
			frappe.throw(__("Couldn't save, please check the data you have entered"), __("Validation Error"));
		}

		// validation hack: get_values will check for missing data
		let doc_values = super.get_values(this.allow_incomplete);

		if (!doc_values) return;

		if (window.saving) return;
		let for_payment = Boolean(this.accept_payment && !this.doc.paid);

		Object.assign(this.doc, doc_values);
		this.doc.doctype = this.doc_type;
		this.doc.web_form_name = this.name;

		// Save
		window.saving = true;
		frappe.form_dirty = false;

		frappe.call({
			type: "POST",
			method: "frappe.website.doctype.web_form.web_form.accept",
			args: {
				data: this.doc,
				web_form: this.name,
				docname: this.doc.name,
				for_payment
			},
			callback: response => {
				// Check for any exception in response
				if (!response.exc) {
					// Success
					this.handle_success(response.message);
					frappe.web_form.events.trigger('after_save');
					this.after_save && this.after_save();
				}
			},
			always: function() {
				window.saving = false;
			}
		});
		return true;
	}

	delete() {
		frappe.call({
			type: "POST",
			method: "frappe.website.doctype.web_form.web_form.delete",
			args: {
				web_form_name: this.name,
				docname: this.doc.name
			}
		});
	}

	print() {
		window.open(`/printview?
			doctype=${this.doc_type}
			&name=${this.doc.name}
			&format=${this.print_format || "Standard"}`, '_blank');
	}

	cancel() {
		window.location.href = window.location.pathname;
	}

	handle_success(data) {
		if (this.accept_payment && !this.doc.paid) {
			window.location.href = data;
		}

		const success_dialog = new frappe.ui.Dialog({
			title: __("Saved Successfully"),
			secondary_action: () => {
				if (this.success_url) {
					window.location.href = this.success_url;
				} else if(this.login_required) {
					window.location.href =
						window.location.pathname + "?name=" + data.name;
				}
			}
		});

		success_dialog.show();
		const success_message =
			this.success_message || __("Your information has been submitted");
		success_dialog.set_message(success_message);
	}
}
<commit_msg>fix(web_form) : web form file attachment link to specific doctype (#222)<commit_after>frappe.provide("frappe.ui");
frappe.provide("frappe.web_form");
import EventEmitterMixin from '../../frappe/event_emitter';

export default class WebForm extends frappe.ui.FieldGroup {
	constructor(opts) {
		super();
		Object.assign(this, opts);
		frappe.web_form = this;
		frappe.web_form.events = {};
		Object.assign(frappe.web_form.events, EventEmitterMixin);
	}

	prepare(web_form_doc, doc) {
		Object.assign(this, web_form_doc);
		this.fields = web_form_doc.web_form_fields;
		this.doc = doc;
	}

	make() {
		super.make();
		this.set_field_values();
		if (this.introduction_text) this.set_form_description(this.introduction_text);
		if (this.allow_print && !this.is_new) this.setup_print_button();
		if (this.allow_delete && !this.is_new) this.setup_delete_button();
		if (this.is_new) this.setup_cancel_button();
		this.setup_primary_action();
		$(".link-btn").remove();

		// webform client script
		frappe.init_client_script && frappe.init_client_script();
		frappe.web_form.events.trigger('after_load');
		this.after_load && this.after_load();
	}

	on(fieldname, handler) {
		let field = this.fields_dict[fieldname];
		field.df.change = () => {
			handler(field, field.value);
		};
	}

	set_field_values() {
		if (this.doc.name) this.set_values(this.doc);
		else return;
	}

	set_default_values() {
		let values = frappe.utils.get_query_params();
		delete values.new;
		this.set_values(values);
	}

	set_form_description(intro) {
		let intro_wrapper = document.getElementById('introduction');
		intro_wrapper.innerHTML = intro;
	}

	add_button(name, type, action, wrapper_class=".web-form-actions") {
		const button = document.createElement("button");
		button.classList.add("btn", "btn-" + type, "btn-sm", "ml-2");
		button.innerHTML = name;
		button.onclick = action;
		document.querySelector(wrapper_class).appendChild(button);
	}

	add_button_to_footer(name, type, action) {
		this.add_button(name, type, action, '.web-form-footer');
	}

	add_button_to_header(name, type, action) {
		this.add_button(name, type, action, '.web-form-actions');
	}

	setup_primary_action() {
		this.add_button_to_header(this.button_label || "Save", "primary", () =>
			this.save()
		);

		this.add_button_to_footer(this.button_label || "Save", "primary", () =>
			this.save()
		);
	}

	setup_cancel_button() {
		this.add_button_to_header(__("Cancel"), "light", () => this.cancel());
	}

	setup_delete_button() {
		this.add_button_to_header(
			'',
			"light",
			() => this.delete()
		);
	}

	setup_print_button() {
		this.add_button_to_header(
			'',
			"light",
			() => this.print()
		);
	}

	save() {
		if (this.validate && !this.validate()) {
			frappe.throw(__("Couldn't save, please check the data you have entered"), __("Validation Error"));
		}

		// validation hack: get_values will check for missing data
		let doc_values = super.get_values(this.allow_incomplete);

		if (!doc_values) return;

		if (window.saving) return;
		let for_payment = Boolean(this.accept_payment && !this.doc.paid);

		Object.assign(this.doc, doc_values);
		this.doc.doctype = this.doc_type;
		this.doc.web_form_name = this.name;

		// Save
		window.saving = true;
		frappe.form_dirty = false;

		frappe.call({
			type: "POST",
			method: "frappe.website.doctype.web_form.web_form.accept",
			args: {
				data: this.doc,
				web_form: this.name,
				docname: this.doc.name,
				for_payment
			},
			callback: response => {
				// Check for any exception in response
				if (!response.exc) {
					// Success
					this.handle_success(response.message);
					frappe.web_form.events.trigger('after_save');
					this.after_save && this.after_save();
					// args doctype and docname added to link doctype in file manager
					frappe.call({
						type: 'POST',
						method: "frappe.handler.upload_file",
						args: {
							file_url: response.message.attachment,
							doctype: response.message.doctype,
							docname: response.message.name
						}
					});
				}
			},
			always: function() {
				window.saving = false;
			}
		});
		return true;
	}

	delete() {
		frappe.call({
			type: "POST",
			method: "frappe.website.doctype.web_form.web_form.delete",
			args: {
				web_form_name: this.name,
				docname: this.doc.name
			}
		});
	}

	print() {
		window.open(`/printview?
			doctype=${this.doc_type}
			&name=${this.doc.name}
			&format=${this.print_format || "Standard"}`, '_blank');
	}

	cancel() {
		window.location.href = window.location.pathname;
	}

	handle_success(data) {
		if (this.accept_payment && !this.doc.paid) {
			window.location.href = data;
		}

		const success_dialog = new frappe.ui.Dialog({
			title: __("Saved Successfully"),
			secondary_action: () => {
				if (this.success_url) {
					window.location.href = this.success_url;
				} else if(this.login_required) {
					window.location.href =
						window.location.pathname + "?name=" + data.name;
				}
			}
		});

		success_dialog.show();
		const success_message =
			this.success_message || __("Your information has been submitted");
		success_dialog.set_message(success_message);
	}
}
<|endoftext|>


<commit_before>// @flow
type IntersectionObserverInit = {
  root: string | null,
  rootMargin: string,
}
declare class IntersectionObserver {
  constructor(function, IntersectionObserverInit): IntersectionObserver;
  observe(HTMLElement): void;
}

export default function lazyLoader (images: NodeList<HTMLElement>): void {
  const callback = function(entries, observer) {
    for (let entry of entries) {
      if (entry.isIntersecting && !entry.target.src) {
        let target = entry.target
        target.setAttribute('src', target.getAttribute('data-src'))
      }
    }
  }
  const options: IntersectionObserverInit = {
    root: null,
    rootMargin: '200px'
  }
  const observer: IntersectionObserver = new IntersectionObserver(callback, options)

  images.forEach(el => observer.observe(el))
}
<commit_msg>fix: Disable flow in LazyLoadApp/index.js<commit_after>
export default function lazyLoader (images: NodeList<HTMLElement>): void {
  const callback = function(entries, observer) {
    for (let entry of entries) {
      if (entry.isIntersecting && !entry.target.src) {
        let target = entry.target
        target.setAttribute('src', target.getAttribute('data-src'))
      }
    }
  }
  const options: IntersectionObserverInit = {
    root: null,
    rootMargin: '200px'
  }
  const observer: IntersectionObserver = new IntersectionObserver(callback, options)

  images.forEach(el => observer.observe(el))
}
<|endoftext|>


<commit_before>var areas = {};
var placeActions = {};
var targetedActions = ['move', 'fight', 'mine'];
var targets = {};
var availableRecipes = {};

function RebirthAction(slot) {
    this.getDiv = function () {
        return $div('action slot' + slot, $div('box', 'Rebirth')).attr('helpText', 'I can regenerate my body, resetting my level and skills. This will be useful if I need to train different abilities in the future.');
    };
    this.action = "rebirth";
    this.addActions = function () {
        placeActions.rebirth = function (params) {
            checkParams(0, params);
            resetCharacter();
            uiNeedsUpdate.area = true;
        };
    };
}
function RestAction(slot) {
    this.getDiv = function () {
        return $div('action slot' + slot, $div('box', 'Rest')).attr('helpText', 'I can restore my health by resting here.').data('helpFunction', function() {
            var healthLost = player.maxHealth - player.health;
            if (healthLost <= 0) {
                return 'My health is full, so there is no reason to rest.';
            }
            return 'Resting will take ' + Math.ceil(healthLost / 10) + ' seconds.';
        });
    };
    this.action = "rest";
    this.addActions = function () {
        placeActions.rest = function (params) {
            checkParams(0, params);
            var healthLost = player.maxHealth - player.health;
            player.time += 1000 * Math.ceil(healthLost / 10);
            player.health = player.maxHealth;
            uiNeedsUpdate.playerStats = true;
        };
    };
}
function SaveAction(slot) {
    this.getDiv = function () {
        return $div('action slot' + slot, $div('box', 'Save')).attr('helpText', 'Save my current progress.');
    };
    this.action = "save";
    this.addActions = function () {
        placeActions.save = function (params) {
            checkParams(0, params);
            saveCurrentGame();
        };
    };
}

function evaluateAction(action) {
    if (typeof(action) === 'function') {
        return action();
    }
    return action;
}

//action only available if the condition method returns true
function ToggleAction(innerAction, condition) {
    this.innerAction = innerAction;
    this.getDiv = function () {
        return condition() ? innerAction.getDiv() : $div('').hide();
    };
    this.action = function () {
        if (!condition()) {
            return '';
        }
        return evaluateAction(innerAction.action);
    }
    this.addActions = function () {
        if (!condition()) {
            return;
        }
        innerAction.addActions();
    };
}
//action only available if the condition method returns true
function DoorAction(innerAction, condition, helpText) {
    this.innerAction = innerAction;
    this.getDiv = function () {
        if (condition()) {
            var $innerDiv = innerAction.getDiv();
            //clone to get help info off of the inner action
            var $doorDiv = $innerDiv.clone().empty();
            $doorDiv.data('helpFunction', $innerDiv.data('helpFunction'));
            return $doorDiv.append($div('innerActionContainer', $innerDiv)).append($div('door open'));
        }
        if (typeof(helpText) == 'undefined') {
            helpText = 'There is a sealed door. Perhaps there is a mechanism for opening it somewhere.';
        }
        return $div('action slot' + innerAction.slot).append($div('door closed')).attr('helpText', helpText);
    };
    this.action = function () {
        if (!condition()) {
            return '';
        }
        return evaluateAction(innerAction.action);
    }
    this.addActions = function () {
        if (!condition()) {
            return;
        }
        innerAction.addActions();
    };
}
//action only available if the condition method returns true
function SpecialAction(slot, actionKey, label, helpFunction, activate) {
    this.slot = slot;
    this.getDiv = function () {
        return $div('action slot' + slot, $div('box wide', label)).attr('helpText', '').data('helpFunction', helpFunction);
    };
    this.action = function () {
        return evaluateAction(actionKey);
    }
    this.addActions = function () {
        placeActions[evaluateAction(actionKey)] = activate;
    };
}

function updateShop() {
    $('.js-shopContainer .js-body .js-shopItem').each(function () {
        var item = $(this).data('item');
        $(this).toggleClass('canBuy', item.value * 2 <= player.gold);
    });
}

function setArea(area) {
    placeActions = {};
    availableRecipes = {};
    targetedActions.forEach(function(action) {
        targets[action] = {};
    });
    var changedAreas = (currentArea != area);
    currentArea = area;
    player.area = area.key;
    if (changedAreas && area.initialize) {
        area.initialize();
    }
    if (area.trackName) {
        setMusic(area.trackName);
    }
    $('.js-currentArea').empty().append(currentArea.$graphic);
    currentArea.actions.forEach(function (action) {
        var $actionDiv = action.getDiv();
        $('.js-currentArea').append($actionDiv);
        action.addActions();
        var actionCode = evaluateAction(action.action);
        if (actionCode) {
            $actionDiv.attr('code', actionCode);
        }
    });
}
function refreshArea() {
    setArea(areas[player.area]);
}

function runCodeFromUI(code) {
    try {
        runLine(code);
        recordAction(code);
        uiNeedsUpdate.area = true;
    } catch(e) {
        if (e instanceof ProgrammingError) {
            alert(e.message);
        } else {
            console.log(e.stack);
            throw e;
        }
    }
}
<commit_msg>Don't trigger change events when the area objects are different, only when the user actually moves to a new area as signified by the area having a different key.<commit_after>var areas = {};
var placeActions = {};
var targetedActions = ['move', 'fight', 'mine'];
var targets = {};
var availableRecipes = {};

function RebirthAction(slot) {
    this.getDiv = function () {
        return $div('action slot' + slot, $div('box', 'Rebirth')).attr('helpText', 'I can regenerate my body, resetting my level and skills. This will be useful if I need to train different abilities in the future.');
    };
    this.action = "rebirth";
    this.addActions = function () {
        placeActions.rebirth = function (params) {
            checkParams(0, params);
            resetCharacter();
            uiNeedsUpdate.area = true;
        };
    };
}
function RestAction(slot) {
    this.getDiv = function () {
        return $div('action slot' + slot, $div('box', 'Rest')).attr('helpText', 'I can restore my health by resting here.').data('helpFunction', function() {
            var healthLost = player.maxHealth - player.health;
            if (healthLost <= 0) {
                return 'My health is full, so there is no reason to rest.';
            }
            return 'Resting will take ' + Math.ceil(healthLost / 10) + ' seconds.';
        });
    };
    this.action = "rest";
    this.addActions = function () {
        placeActions.rest = function (params) {
            checkParams(0, params);
            var healthLost = player.maxHealth - player.health;
            player.time += 1000 * Math.ceil(healthLost / 10);
            player.health = player.maxHealth;
            uiNeedsUpdate.playerStats = true;
        };
    };
}
function SaveAction(slot) {
    this.getDiv = function () {
        return $div('action slot' + slot, $div('box', 'Save')).attr('helpText', 'Save my current progress.');
    };
    this.action = "save";
    this.addActions = function () {
        placeActions.save = function (params) {
            checkParams(0, params);
            saveCurrentGame();
        };
    };
}

function evaluateAction(action) {
    if (typeof(action) === 'function') {
        return action();
    }
    return action;
}

//action only available if the condition method returns true
function ToggleAction(innerAction, condition) {
    this.innerAction = innerAction;
    this.getDiv = function () {
        return condition() ? innerAction.getDiv() : $div('').hide();
    };
    this.action = function () {
        if (!condition()) {
            return '';
        }
        return evaluateAction(innerAction.action);
    }
    this.addActions = function () {
        if (!condition()) {
            return;
        }
        innerAction.addActions();
    };
}
//action only available if the condition method returns true
function DoorAction(innerAction, condition, helpText) {
    this.innerAction = innerAction;
    this.getDiv = function () {
        if (condition()) {
            var $innerDiv = innerAction.getDiv();
            //clone to get help info off of the inner action
            var $doorDiv = $innerDiv.clone().empty();
            $doorDiv.data('helpFunction', $innerDiv.data('helpFunction'));
            return $doorDiv.append($div('innerActionContainer', $innerDiv)).append($div('door open'));
        }
        if (typeof(helpText) == 'undefined') {
            helpText = 'There is a sealed door. Perhaps there is a mechanism for opening it somewhere.';
        }
        return $div('action slot' + innerAction.slot).append($div('door closed')).attr('helpText', helpText);
    };
    this.action = function () {
        if (!condition()) {
            return '';
        }
        return evaluateAction(innerAction.action);
    }
    this.addActions = function () {
        if (!condition()) {
            return;
        }
        innerAction.addActions();
    };
}
//action only available if the condition method returns true
function SpecialAction(slot, actionKey, label, helpFunction, activate) {
    this.slot = slot;
    this.getDiv = function () {
        return $div('action slot' + slot, $div('box wide', label)).attr('helpText', '').data('helpFunction', helpFunction);
    };
    this.action = function () {
        return evaluateAction(actionKey);
    }
    this.addActions = function () {
        placeActions[evaluateAction(actionKey)] = activate;
    };
}

function updateShop() {
    $('.js-shopContainer .js-body .js-shopItem').each(function () {
        var item = $(this).data('item');
        $(this).toggleClass('canBuy', item.value * 2 <= player.gold);
    });
}

function setArea(area) {
    placeActions = {};
    availableRecipes = {};
    targetedActions.forEach(function(action) {
        targets[action] = {};
    });
    var changedAreas = (currentArea.key != area.key);
    currentArea = area;
    player.area = area.key;
    if (changedAreas && area.initialize) {
        area.initialize();
    }
    if (area.trackName) {
        setMusic(area.trackName);
    }
    $('.js-currentArea').empty().append(currentArea.$graphic);
    currentArea.actions.forEach(function (action) {
        var $actionDiv = action.getDiv();
        $('.js-currentArea').append($actionDiv);
        action.addActions();
        var actionCode = evaluateAction(action.action);
        if (actionCode) {
            $actionDiv.attr('code', actionCode);
        }
    });
}
function refreshArea() {
    setArea(areas[player.area]);
}

function runCodeFromUI(code) {
    try {
        runLine(code);
        recordAction(code);
        uiNeedsUpdate.area = true;
    } catch(e) {
        if (e instanceof ProgrammingError) {
            alert(e.message);
        } else {
            console.log(e.stack);
            throw e;
        }
    }
}
<|endoftext|>


<commit_before>var test = require('tap').test,
    wd = require('wd'),
    results = require('./');

var user = process.env.SAUCE_USER,
    key = process.env.SAUCE_KEY;

function startBrowser(options, callback) {
    var browser = wd.remote('ondemand.saucelabs.com', 80, user, key);
    browser.init(options, init);

    function init(err) {
        if (err) {
            return callback(err);
        }

        browser.quit(quit);
    }

    function quit() {
        callback();
    }
}

test('set passed results', function(t) {
    t.ok(user, 'Sauce Labs user provided');
    t.ok(key, 'Sauce Labs key provided');

    startBrowser({
        name: 'Passed test',
        platform: 'Linux',
        browserName: 'firefox'
    }, started);

    function started(err) {
        t.error(err, 'started browser');

        results({
            user: user,
            key: key,
            passed: true
        }, setResults);
    }

    function setResults(err) {
        t.error(err, 'set results');
        t.end();
    }
});

test('set failed results', function(t) {
    t.ok(user, 'Sauce Labs user provided');
    t.ok(key, 'Sauce Labs key provided');

    startBrowser({
        name: 'Failed test',
        platform: 'Linux',
        browserName: 'chrome'
    }, started);

    function started(err) {
        t.error(err, 'started browser');

        results({
            user: user,
            key: key,
            passed: false
        }, setResults);
    }

    function setResults(err) {
        t.error(err, 'set results');
        t.end();
    }
});
<commit_msg>Provide build number to Sauce Labs from Drone.io<commit_after>var test = require('tap').test,
    wd = require('wd'),
    results = require('./');

var user = process.env.SAUCE_USER,
    key = process.env.SAUCE_KEY,
    build = process.env.DRONE_BUILD_NUMBER;

function startBrowser(options, callback) {
    var browser = wd.remote('ondemand.saucelabs.com', 80, user, key);
    browser.init(options, init);

    function init(err) {
        if (err) {
            return callback(err);
        }

        browser.quit(quit);
    }

    function quit() {
        callback();
    }
}

test('set passed results', { timeout: 60000 }, function(t) {
    t.ok(user, 'Sauce Labs user provided');
    t.ok(key, 'Sauce Labs key provided');

    startBrowser({
        name: 'Passed test',
        platform: 'Linux',
        browserName: 'firefox',
        build: build
    }, started);

    function started(err) {
        t.error(err, 'started browser');

        results({
            user: user,
            key: key,
            passed: true,
        }, setResults);
    }

    function setResults(err) {
        t.error(err, 'set results');
        t.end();
    }
});

test('set failed results', { timeout: 60000 }, function(t) {
    t.ok(user, 'Sauce Labs user provided');
    t.ok(key, 'Sauce Labs key provided');

    startBrowser({
        name: 'Failed test',
        platform: 'Linux',
        browserName: 'chrome',
        build: build
    }, started);

    function started(err) {
        t.error(err, 'started browser');

        results({
            user: user,
            key: key,
            passed: false
        }, setResults);
    }

    function setResults(err) {
        t.error(err, 'set results');
        t.end();
    }
});
<|endoftext|>


<commit_before>
export default function lazyLoader (images: NodeList<HTMLElement>): void {
  const callback = function(entries, observer) {
    for (let entry of entries) {
      if (entry.isIntersecting && !entry.target.src) {
        let target = entry.target
        target.setAttribute('src', target.getAttribute('data-src'))
        target.addEventListener('load', () => {
          target.removeAttribute('style')
        })
      }
    }
  }
  const options: IntersectionObserverInit = {
    root: null,
    rootMargin: '200px'
  }
  const observer: IntersectionObserver = new IntersectionObserver(callback, options)

  images.forEach(el => observer.observe(el))
}
<commit_msg>:bug: IntersectionObserverのpolyfillを適用した<commit_after>// importだと静的に解決されてpolifillにならないのでrequire
import 'intersection-observer'

export default function lazyLoader (images: NodeList<HTMLElement>): void {
  const callback = function(entries, observer) {
    for (let entry of entries) {
      if (entry.isIntersecting && !entry.target.src) {
        let target = entry.target
        target.setAttribute('src', target.getAttribute('data-src'))
        target.addEventListener('load', () => {
          target.removeAttribute('style')
        })
      }
    }
  }
  const options: IntersectionObserverInit = {
    root: null,
    rootMargin: '200px'
  }
  const observer: IntersectionObserver = new IntersectionObserver(callback, options)

  images.forEach(el => observer.observe(el))
}
<|endoftext|>