<commit_before>
"use strict";

var WWW_Applet = null;

(function () {

  // ================================================================
  // Helper Functions
  // ================================================================

  // From:
  // http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript
  var capitalize = function (s) {
    return s.charAt(0).toUpperCase() + s.substring(1);
  };

  var inspect = function (val) {
    var name = func_name(val.constructor || 'Unknown');
    return name + ': ' + val;
  };

  var is_numeric = function (val) {
    return _.isNumber(val) && !_.isNaN(val);
  };

  var log = function () {
    if (!window.console) { return; }
    return console.log.apply(console, arguments);
  };

  var func_name = function (raw) {
    var s    = null;
    var name = null;

    if (_.isString(raw)) {
      s = raw;
    } else {
      s = ('' + raw);
    }

    name = _.last( _.first(s.split('(')).split('function ') );
    return name;
  };

  var each = function (arr, func) {
    var l      = arr.length;
    var i      = 0;
    var each_o = {

      next: function () {
        if (each_o.is_last()) {
          throw new Error('No more items: i: ' + i + ' total: ' + l);
        }
        return arr[i + 1];
      }, // === next

      prev : function () {
        if (each_o.is_first()) {
          throw new Error('No previous items: i: ' + i + ' total: ' + l);
        }
        return arr[i - 1];
      },

      next_or_null: function () {
        if (each_o.is_last()) { return null; }
        return arr[i + 1];
      },

      prev_or_null : function () {
        if (each_o.is_first()) { return null; }
        return arr[i - 1];
      },

      is_first: function () {
        return i < 1;
      },

      is_last: function () {
        return i >= (l - 1);
      },

      grab_next: function () {
        if (each_o.is_last()) {
          throw new Error('Can\'t grab next because already at last position.');
        }
        i = i + 1;
        return arr[i];
      }

    }; // === each_o

    while ( i < l ) {
      each_o.i = i;
      func(arr[i], each_o);
      i = i + 1;
    } // while

  }; // === each

  var to_number_name = function (num) {
    var name = null;
    switch (num) {
      case 0:
        name = 'first';
      break;

      case 1:
        name = 'second';
      break;

      case 2:
        name = 'third';
      break;

      case 3:
        name = 'fourth';
      break;

      case 4:
        name = 'fifth';
      break;

      case 5:
        name = 'sixth';
      break;

      default:
      throw new Error("Unknown value: " + num);
    } // === switch num
    return name;
  }; // function

  var last_types = function (stack, types, stack_name) {
    var o = {};

    if (types.length === 0) {
      throw new Error("No arguments.");
    }

    if (types.length === 1 && types[0] === 'all') {
      return stack;
    }

    var vals = _.last(stack, types.length);

    if (vals.length !== types.length) {
      throw new Error('Not enough values in ' + stack_name + '.');
    }

    _.each(types, function (t, i) {
      var val = vals[i];
      var ignore_type = t === 'any' || t === 'last';

      if (!ignore_type) {
        if (_.isString(t)) {
          throw new Error('Unknown position or type: ' + t);
        }

        if (val.constructor !== t) {
          throw new Error('Value in ' + stack_name + " is not a " + func_name(t) + ': ' + inspect(val));
        }
      }

      o[to_number_name(i)] = val;
    });

    if (types.length === 1) {
      return o.first;
    }

    return o;
  }; // last_types

  // ================================================================
  // === End Helper Functions =======================================
  // ================================================================

  // ================================================================
  // Scope
  // ================================================================
  var Scope = function (parent) {

    var o         = {};
    var vars      = {};
    var stack     = [];
    var first     = null;
    var second    = null;
    var left_args = null;

    if (parent) {
      o.parent = parent;
    }

    // ==============================================================
    // ============== stack functions ===============================
    // ==============================================================

    var right = function () {
      return last_types(stack, _.toArray(arguments), 'stack');
    };

    var push = function () {
      var args = _.toArray(arguments);
      _.each(args, function (v) {
        stack.push(v);
      });
      return args;
    }; // push ========================================

    var concat = function (arr) {
      push.apply(null, arr);
      return arr;
    }; // concat ================================

    // ==============================================================
    // ================ run functions ===============================
    // ==============================================================

    var run = function (code_array) {
      each(code_array, function (item, l) {

        if (_.isArray(item)) {
          throw new Error("Syntax error: args w/o function name.");

        } else if (_.isString(item), _.isArray(l.next_or_null())) {
          run_func(item, l.grab_next());

        } else {
          stack.push(item);
        } // === if

      }); // === .each

      return o;
    }; // run ========================================

    var run_func = function (name, raw_args) {

      var compiled_args = null;

      var run_args = function () {
        if (!compiled_args) {
          compiled_args = child().run(raw_args).right('all');
        }

        return compiled_args;
      }; // run_args

      var left = function () {
        return last_types(run_args(), _.toArray(arguments), 'args');
      };

      var replace_left = function (arr) {
        compiled_args = arr;
        return compiled_args;
      };

      switch (name) {

        case 'focus on':
          set('the focus', $(left(String)));
          return get('the focus');

        case 'focus on ancestor':
          set('the focus', get('the focus').parents(left(String)));
          return get('the focus');

        case 'submit':
            var form   = $(get('the focus'));
            var action = form.attr('action');
            if (/[^a-zA-Z0-9\_\-\/]+/.test(action)) {
              throw new Error("Invalid chars in #" + form.attr('id') + " action: " + action);
            }
            return null;

        case 'array':
          push(run_args());
          return right('last');

        case 'add class':
          get('the focus').addClass(left(String));
          return left('last');

        case 'add to stack':
          concat( run_args() );
          return run_args();

        case "and":
          first     = right(Boolean);
          second    = null;
          left_args = null;

          if (first === true) {
            second = left(Boolean);

            if (first === true && second === true) {
              push(true);
              return true;
            }
          }

          push(false);
          return false;

        case "or":
          first     = right(Boolean);
          second    = null;
          left_args = null;

          if (first === true) {
            push(true);
            return true;
          }

          second = left(Boolean);

          if (second === true) {
            push(true);
            return true;
          }

          push(false);
          return false;

        case "if true":
          first = right(Boolean);

          if (first) {
            run_args();
          }

          return null;

        case "if false":
          first = right(Boolean);

          if (!first) {
            run_args();
          }

          return null;

        case "on click":
          var focus  = get('the focus');
          var scope  = child();
          scope.set('the focus', focus);

          $(focus).click(function () {
            scope.run(raw_args);
          });

          return null;

        case "on":
          throw new Error('Not ready yet: on');

        case 'bigger or equal':
          return run_func('compare numbers', ['>=', left(Number)]);

        case 'bigger':
          return run_func('compare numbers', ['>', left(Number)]);

        case 'less':
          return run_func('compare numbers', ['<', left(Number)]);

        case 'less or equal':
          return run_func('compare numbers', ['<=', left(Number)]);

        case 'equal':
          first  = right('any');
          second = left('any');
          push(first === second);
          return right('last');

        case 'compare numbers':
          first = right(Number);

          var args    = left(String, Number);
          var compare = args.first;
          second  = args.second;

          var result = null;

          switch (compare) {

            case '===':
              result = first === second;
            break;

            case '<=':
              result = first <= second;
            break;

            case '<':
              result = first < second;
            break;

            case '>=':
              result = first >= second;
            break;

            case '>':
              result = first > second;
            break;

            default:
              throw new Error("Unknown value : " + compare);
          } // === switch

          push(result);
          return result;

        default:
          throw new Error("Function not found: " + name);
      } // === switch name

    }; // run_func ===================================

    // ==============================================================
    // ============= miscel. functions ==============================
    // ==============================================================

    var child = function () {
      return( new Scope(o) );
    };

    var set = function (name, val) {
      vars[name] = val;
      return val;
    }; // function

    var get = function (name) {
      if (!vars.hasOwnProperty(name) && !parent) {
        throw new Error('No var found with name: ' + name);
      }

      return (vars.hasOwnProperty(name)) ?
        vars[name] :
        parent.get(name);
    }; // val =========================================

    o.right = right;
    o.get   = get;
    o.set   = get;
    o.run   = run;
    return o;

  // ================================================================
  }; // ===== Scope =================================================
  // ================================================================

  WWW_Applet = {
    Scope : Scope,
    run   : function (code_array) {
      return (new Scope()).run(code_array);
    } // run
  };

})(); // === WWW_Applet scope

<commit_msg>Changed: 'the focus' is always a String. Added: the_focus()<commit_after>
"use strict";

var WWW_Applet = null;

(function () {

  // ================================================================
  // Helper Functions
  // ================================================================

  // From:
  // http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript
  var capitalize = function (s) {
    return s.charAt(0).toUpperCase() + s.substring(1);
  };

  var inspect = function (val) {
    var name = func_name(val.constructor || 'Unknown');
    return name + ': ' + val;
  };

  var is_numeric = function (val) {
    return _.isNumber(val) && !_.isNaN(val);
  };

  var log = function () {
    if (!window.console) { return; }
    return console.log.apply(console, arguments);
  };

  var func_name = function (raw) {
    var s    = null;
    var name = null;

    if (_.isString(raw)) {
      s = raw;
    } else {
      s = ('' + raw);
    }

    name = _.last( _.first(s.split('(')).split('function ') );
    return name;
  };

  var each = function (arr, func) {
    var l      = arr.length;
    var i      = 0;
    var each_o = {

      next: function () {
        if (each_o.is_last()) {
          throw new Error('No more items: i: ' + i + ' total: ' + l);
        }
        return arr[i + 1];
      }, // === next

      prev : function () {
        if (each_o.is_first()) {
          throw new Error('No previous items: i: ' + i + ' total: ' + l);
        }
        return arr[i - 1];
      },

      next_or_null: function () {
        if (each_o.is_last()) { return null; }
        return arr[i + 1];
      },

      prev_or_null : function () {
        if (each_o.is_first()) { return null; }
        return arr[i - 1];
      },

      is_first: function () {
        return i < 1;
      },

      is_last: function () {
        return i >= (l - 1);
      },

      grab_next: function () {
        if (each_o.is_last()) {
          throw new Error('Can\'t grab next because already at last position.');
        }
        i = i + 1;
        return arr[i];
      }

    }; // === each_o

    while ( i < l ) {
      each_o.i = i;
      func(arr[i], each_o);
      i = i + 1;
    } // while

  }; // === each

  var to_number_name = function (num) {
    var name = null;
    switch (num) {
      case 0:
        name = 'first';
      break;

      case 1:
        name = 'second';
      break;

      case 2:
        name = 'third';
      break;

      case 3:
        name = 'fourth';
      break;

      case 4:
        name = 'fifth';
      break;

      case 5:
        name = 'sixth';
      break;

      default:
      throw new Error("Unknown value: " + num);
    } // === switch num
    return name;
  }; // function

  var last_types = function (stack, types, stack_name) {
    var o = {};

    if (types.length === 0) {
      throw new Error("No arguments.");
    }

    if (types.length === 1 && types[0] === 'all') {
      return stack;
    }

    var vals = _.last(stack, types.length);

    if (vals.length !== types.length) {
      throw new Error('Not enough values in ' + stack_name + '.');
    }

    _.each(types, function (t, i) {
      var val = vals[i];
      var ignore_type = t === 'any' || t === 'last';

      if (!ignore_type) {
        if (_.isString(t)) {
          throw new Error('Unknown position or type: ' + t);
        }

        if (val.constructor !== t) {
          throw new Error('Value in ' + stack_name + " is not a " + func_name(t) + ': ' + inspect(val));
        }
      }

      o[to_number_name(i)] = val;
    });

    if (types.length === 1) {
      return o.first;
    }

    return o;
  }; // last_types

  // ================================================================
  // === End Helper Functions =======================================
  // ================================================================

  // ================================================================
  // Scope
  // ================================================================
  var Scope = function (parent) {

    var o         = {};
    var vars      = {};
    var stack     = [];
    var first     = null;
    var second    = null;
    var left_args = null;

    if (parent) {
      o.parent = parent;
    }

    // ==============================================================
    // ============== stack functions ===============================
    // ==============================================================

    var right = function () {
      return last_types(stack, _.toArray(arguments), 'stack');
    };

    var push = function () {
      var args = _.toArray(arguments);
      _.each(args, function (v) {
        stack.push(v);
      });
      return args;
    }; // push ========================================

    var concat = function (arr) {
      push.apply(null, arr);
      return arr;
    }; // concat ================================

    // ==============================================================
    // ================ run functions ===============================
    // ==============================================================

    var run = function (code_array) {
      each(code_array, function (item, l) {

        if (_.isArray(item)) {
          throw new Error("Syntax error: args w/o function name.");

        } else if (_.isString(item), _.isArray(l.next_or_null())) {
          run_func(item, l.grab_next());

        } else {
          stack.push(item);
        } // === if

      }); // === .each

      return o;
    }; // run ========================================

    var run_func = function (name, raw_args) {

      var compiled_args = null;

      var run_args = function () {
        if (!compiled_args) {
          compiled_args = child().run(raw_args).right('all');
        }

        return compiled_args;
      }; // run_args

      var left = function () {
        return last_types(run_args(), _.toArray(arguments), 'args');
      };

      var replace_left = function (arr) {
        compiled_args = arr;
        return compiled_args;
      };

      switch (name) {

        case 'focus on':
          set('the focus', left(String));
          return the_focus();

        case 'focus on ancestor':
          set('the focus', the_focus().parents(left(String)));
          return get('the focus');

        case 'submit':
            var form   = the_focus();
            var action = form.attr('action');
            if (/[^a-zA-Z0-9\_\-\/]+/.test(action)) {
              throw new Error("Invalid chars in #" + form.attr('id') + " action: " + action);
            }
            return null;

        case 'array':
          push(run_args());
          return right('last');

        case 'add class':
          the_focus().addClass(left(String));
          return left('last');

        case 'add to stack':
          concat( run_args() );
          return run_args();

        case "and":
          first     = right(Boolean);
          second    = null;
          left_args = null;

          if (first === true) {
            second = left(Boolean);

            if (first === true && second === true) {
              push(true);
              return true;
            }
          }

          push(false);
          return false;

        case "or":
          first     = right(Boolean);
          second    = null;
          left_args = null;

          if (first === true) {
            push(true);
            return true;
          }

          second = left(Boolean);

          if (second === true) {
            push(true);
            return true;
          }

          push(false);
          return false;

        case "if true":
          first = right(Boolean);

          if (first) {
            run_args();
          }

          return null;

        case "if false":
          first = right(Boolean);

          if (!first) {
            run_args();
          }

          return null;

        case "on click":
          var focus_selector  = get('the focus');
          var scope  = child();
          scope.set('the focus', focus_selector);

          $(focus_selector).click(function () {
            scope.run(raw_args);
          });

          return null;

        case "on":
          throw new Error('Not ready yet: on');

        case 'bigger or equal':
          return run_func('compare numbers', ['>=', left(Number)]);

        case 'bigger':
          return run_func('compare numbers', ['>', left(Number)]);

        case 'less':
          return run_func('compare numbers', ['<', left(Number)]);

        case 'less or equal':
          return run_func('compare numbers', ['<=', left(Number)]);

        case 'equal':
          first  = right('any');
          second = left('any');
          push(first === second);
          return right('last');

        case 'compare numbers':
          first = right(Number);

          var args    = left(String, Number);
          var compare = args.first;
          second  = args.second;

          var result = null;

          switch (compare) {

            case '===':
              result = first === second;
            break;

            case '<=':
              result = first <= second;
            break;

            case '<':
              result = first < second;
            break;

            case '>=':
              result = first >= second;
            break;

            case '>':
              result = first > second;
            break;

            default:
              throw new Error("Unknown value : " + compare);
          } // === switch

          push(result);
          return result;

        default:
          throw new Error("Function not found: " + name);
      } // === switch name

    }; // run_func ===================================

    // ==============================================================
    // ============= miscel. functions ==============================
    // ==============================================================

    var child = function () {
      return( new Scope(o) );
    };

    var the_focus = function () {
      return $(get('the focus'));
    };

    var set = function (name, val) {
      if (name === 'the focus' && !_.isString(val)) {
        throw new Error("Focus selector must be a String.");
      }

      vars[name] = val;
      return val;
    }; // function

    var get = function (name) {
      if (!vars.hasOwnProperty(name) && !parent) {
        throw new Error('No var found with name: ' + name);
      }

      return (vars.hasOwnProperty(name)) ?
        vars[name] :
        parent.get(name);
    }; // val =========================================

    o.right = right;
    o.get   = get;
    o.set   = get;
    o.run   = run;
    return o;

  // ================================================================
  }; // ===== Scope =================================================
  // ================================================================

  WWW_Applet = {
    Scope : Scope,
    run   : function (code_array) {
      return (new Scope()).run(code_array);
    } // run
  };

})(); // === WWW_Applet scope

<|endoftext|>


<commit_before>// When an error occurs
function errorFn(msg, trace) {
  // Log the error and trace
  console.error(msg);
  trace.forEach(function(item) {
      console.error('  ', item.file, ':', item.line);
  });

  // Leave with a bad exit code
  phantom.exit(1);
}
phantom.onError = errorFn;

// Load in dependencies
var system = require('system'),
    webpage = require('webpage');

// Create a webpage
var page = webpage.create();
page.onError = errorFn;

// Grab the arguments
var args = system.args,
    username = args[1];

// If there is no image, throw an error
if (!username) {
  throw new Error('No username was specified.');
}

// Count the resources as they load
var resourceCount = 0,
    resourceExpected = 4; // index.html, light font, heavy font, heart.git
page.onResourceReceived = function (response) {
  if (response.stage === 'end') {
    resourceCount += 1;
  }
};

// Load the screenshot page
var __dirname = phantom.libraryPath;
page.open(__dirname + '/index.html?' + username, function (status) {
  // Wait until the canvas has rendered
  function checkCanvas() {
    // Determine if the canvas is rendered
    var canvasRendered = page.evaluate(function () {
          return window.canvasRendered;
        });

    // console.log('checking', canvasRendered);
    // If it has not, check again in 100ms
    if (!canvasRendered) {
      return setTimeout(checkCanvas, 100);
    }

    // Grab the canvas contents and echo
    var dataPng = page.evaluate(function () {
          var canvas = document.getElementById('canvas');
          return canvas.toDataURL();
        }),
        // 'data:image/png;base64,iVBORw0KGgoAAAANS...'
        // 'data:image/png;base64,'.length === 22
        png = dataPng.slice(22);
    console.log(png);

    // Leave gracefully
    phantom.exit(0);
  }
  checkCanvas();
});

// Set up a timeout to autokill
setTimeout(function () {
  console.error('Timeout occurred at 2 seconds.');
  phantom.exit(1);
}, 2000);<commit_msg>Moving back resource count check<commit_after>// When an error occurs
function errorFn(msg, trace) {
  // Log the error and trace
  console.error(msg);
  trace.forEach(function(item) {
      console.error('  ', item.file, ':', item.line);
  });

  // Leave with a bad exit code
  phantom.exit(1);
}
phantom.onError = errorFn;

// Load in dependencies
var system = require('system'),
    webpage = require('webpage');

// Create a webpage
var page = webpage.create();
page.onError = errorFn;

// Grab the arguments
var args = system.args,
    username = args[1];

// If there is no image, throw an error
if (!username) {
  throw new Error('No username was specified.');
}

// Count the resources as they load
var resourceCount = 0,
    resourceExpected = 4; // index.html, light font, heavy font, heart.git
page.onResourceReceived = function (response) {
  if (response.stage === 'end') {
    resourceCount += 1;
  }
};

// Load the screenshot page
var __dirname = phantom.libraryPath;
page.open(__dirname + '/index.html?' + username, function (status) {
  // Wait until the canvas has rendered
  function checkCanvas() {
    // Determine if the canvas is rendered
    var canvasRendered = page.evaluate(function () {
          return window.canvasRendered;
        });

    // console.log('checking', canvasRendered);
    // If it has not, check again in 100ms
    if (!canvasRendered || resourceCount < resourceExpected) {
      return setTimeout(checkCanvas, 100);
    }

    // Grab the canvas contents and echo
    var dataPng = page.evaluate(function () {
          var canvas = document.getElementById('canvas');
          return canvas.toDataURL();
        }),
        // 'data:image/png;base64,iVBORw0KGgoAAAANS...'
        // 'data:image/png;base64,'.length === 22
        png = dataPng.slice(22);
    console.log(png);

    // Leave gracefully
    phantom.exit(0);
  }
  checkCanvas();
});

// Set up a timeout to autokill
setTimeout(function () {
  console.error('Timeout occurred at 2 seconds.');
  phantom.exit(1);
}, 2000);<|endoftext|>


<commit_before>'use strict';

module.exports = require('../FusebillResource').extend({
  path: 'coupons',
  includeBasic: ['create', 'list', 'update', 'retrieve', 'del'],

  validate: fusebillMethod({
    method: 'POST',
    path: '/Validate'
  }),
});

<commit_msg>added validate coupon ifx<commit_after>'use strict';

var FusebillResource = require('../FusebillResource');
var fusebillMethod = FusebillResource.method;

module.exports = FusebillResource.extend({

  path: 'coupons',
  includeBasic: ['create', 'list', 'update', 'retrieve', 'del'],

  validate: fusebillMethod({
    method: 'POST',
    path: '/Validate'
  }),

});

<|endoftext|>


<commit_before>var db = require('../helpers/db');
var _ = require('underscore');

var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {
  var query = "SELECT country_id, countries.name, continents.name AS continent, countries.image FROM countries, continents WHERE countries.continent_id = continents.continent_id ORDER BY country_id ASC";

  db.query(query)
  .then(function(result) {
    res.status(200).send(result.rows);
  })
  .catch(function(error) {
    res.status(500).send(error);
  });
});

router.post('/', function(req, res) {
  var name = req.body.name;
  var continent_id = Number(req.body.continent_id);
  var image = _.isString(req.body.image) ? req.body.image : null;

  if(!(_.isString(name))) {
    res.status(400).send("Bad Request");
    return;
  }

  var query = 'INSERT INTO countries ("name","continent_id","image")  VALUES ($1, $2, $3) RETURNING country_id';
  var values = [name, continent_id, image];

  db.query(query, values)
  .then(function(result) {
    res.status(201).send(result.rows[0]);
  })
  .catch(function(error) {
    res.status(500).send(error);
  });
});

module.exports = router;
<commit_msg>Add single country get endpoint<commit_after>var db = require('../helpers/db');
var _ = require('underscore');

var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {
  var query = "SELECT country_id, countries.name, continents.name AS continent, countries.image FROM countries, continents WHERE countries.continent_id = continents.continent_id ORDER BY country_id ASC";

  db.query(query)
  .then(function(result) {
    res.status(200).send(result.rows);
  })
  .catch(function(error) {
    res.status(500).send(error);
  });
});

router.post('/', function(req, res) {
  var name = req.body.name;
  var continent_id = Number(req.body.continent_id);
  var image = _.isString(req.body.image) ? req.body.image : null;

  if(!(_.isString(name))) {
    res.status(400).send("Bad Request");
    return;
  }

  var query = 'INSERT INTO countries ("name","continent_id","image")  VALUES ($1, $2, $3) RETURNING country_id';
  var values = [name, continent_id, image];

  db.query(query, values)
  .then(function(result) {
    res.status(201).send(result.rows[0]);
  })
  .catch(function(error) {
    res.status(500).send(error);
  });
});

router.use('/:id', function(req, res, next) {
  var id = Number(req.params.id);

  if(_.isNumber(id)) {
    next();
  } else {
    res.status(400).send("Value should be a number");
  }
});

router.get('/:id', function(req, res) {
  var query = "SELECT * FROM countries WHERE country_id = $1";
  var values = [req.params.id];

  db.query(query, values)
  .then(function(result) {
    var row = result.rows[0];

    if(_.isEmpty(row)) {
      res.status(404).end();
    } else {
      res.status(200).send(result.rows[0]);
    }
  })
  .catch(function(error) {
    res.status(500).send(error);
  });
});

module.exports = router;
<|endoftext|>


<commit_before>'use strict';

const { knex } = require('../db/database');
const Entry = require('../models/entry');

module.exports.show = (req, res) => {
  res.render('entry');
}

module.exports.create = (req, res, err) => {
  console.log(req.body)
  Entry.forge(req.body)
    .save()
    .then((entryObject) => {
      console.log(req.body)
    });
};

// module.exports.getEntries = (req, res, next) => {
//   Entry.fetchAll()
//   .then( (entries) => {
//     res.status(200).json(entries);
//   });
// };
<commit_msg>changed name of function to addEntry<commit_after>'use strict';

const { knex } = require('../db/database');
const Entry = require('../models/entry');

module.exports.addEntry = (req, res, err) => {
  console.log(req.body)
  Entry.forge(req.body)
    .save()
    .then((entryObject) => {
      console.log(req.body)
    });
};
<|endoftext|>


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

'use strict';

const express = require('express');
const pwaModel = require('../../models/pwa');
const router = express.Router(); // eslint-disable-line new-cap
const config = require('../../config/config');
const CLIENT_ID = config.get('CLIENT_ID');
const CLIENT_SECRET = config.get('CLIENT_SECRET');
const crypto = require('crypto');
const LIST_PAGE_SIZE = 10;

/**
 * GET /pwas/add
 *
 * Display a page of PWAs (up to ten at a time).
 */
router.get('/', (req, res, next) => {
  function callback(err, entities, cursor) {
    if (err) {
      return next(err);
    }

    res.render('pwas/list.hbs', {
      pwas: entities,
      nextPageToken: cursor
    });
  }
  pwaModel.list(LIST_PAGE_SIZE, req.query.pageToken, callback);
});

/**
 * GET /pwas/add
 *
 * Display a form for creating a PWA.
 */
router.get('/add', (req, res) => {
  res.render('pwas/form.hbs', {
    pwa: {},
    action: 'Add'
  });
});

/**
 * POST /pwas/add
 *
 * Create a PWA.
 */
// [START add]
router.post('/add', (req, res, next) => {
  const manifestUrl = req.body.manifestUrl;
  const idToken = req.body.idToken;

  if (!manifestUrl) {
    res.render('pwas/form.hbs', {
      pwa: {
        manifestUrl: ''
      },
      error: 'no manifest provided'
    });
    return;
  }

  if (!idToken) {
    res.render('pwas/form.hbs', {
      pwa: {
        manifestUrl: manifestUrl
      },
      error: 'user not logged in'
    });
    return;
  }

  verifyIdToken(CLIENT_ID, CLIENT_SECRET, idToken)
    .then(user => {
      const pwa = {
        manifestUrl: manifestUrl,
        createdOn: new Date(),
        updatedOn: new Date(),
        user: {
          id: crypto.createHash('sha1').update(user.getPayload().sub).digest('hex'),
        }
      };
      const callback = (err, savedData) => {
        if (err) {
          if (typeof err === 'number') {
            switch (err) {
              case pwaModel.E_ALREADY_EXISTS:
                res.render('pwas/form.hbs', {
                  pwa: {
                    manifestUrl: pwa.manifestUrl
                  },
                  error: 'manifest already exists'
                });
                return;
              case pwaModel.E_MANIFEST_ERROR:
                res.render('pwas/form.hbs', {
                  pwa: {
                    manifestUrl: pwa.manifestUrl
                  },
                  error: 'error loading manifest' // could be 404, not JSON, domain does not exist
                });
                return;
              default:
                return next(err);
            }
          }
        }
        res.redirect(req.baseUrl + '/' + savedData.id);
      };
      pwaModel.save(pwa, callback);
    })
    .catch(err => {
      res.render('pwas/form.hbs', {
        pwa: {
          manifestUrl: manifestUrl
        },
        error: err
      });
      return;
    });
});
// [END add]

/**
 * GET /pwas/:id/edit
 *
 * Display a pwa for editing.
 */
router.get('/:pwa/edit', (req, res, next) => {
  pwaModel.find(req.params.pwa, (err, entity) => {
    if (err) {
      return next(err);
    }

    res.render('pwas/form.hbs', {
      pwa: entity,
      action: 'Edit'
    });
  });
});

/**
 * POST /pwas/:id/edit
 *
 * Update a PWA.
 */

router.post('/:pwa/edit', (req, res, next) => {
  const data = req.body;
  data.id = req.params.pwa;

  pwaModel.save(data, (err, savedData) => {
    if (err) {
      return next(err);
    }
    res.redirect(req.baseUrl + '/' + savedData.id);
  });
});

/**
 * GET /pwas/:id
 *
 * Display a PWA.
 */
router.get('/:pwa', (req, res, next) => {
  pwaModel.find(req.params.pwa, (err, entity) => {
    if (err) {
      return next(err);
    }

    res.render('pwas/view.hbs', {
      pwa: entity
    });
  });
});

/**
 * GET /pwas/:id/delete
 *
 * Delete a PWA.
 */
router.get('/:pwa/delete', (req, res, next) => {
  pwaModel.delete(req.params.pwa, err => {
    if (err) {
      return next(err);
    }
    res.redirect(req.baseUrl);
  });
});

/**
 * Errors on "/pwas/*" routes.
 */
router.use((err, req, res, next) => {
  // Format error and forward to generic error handler for logging and
  // responding to the request
  err.response = err.message;
  next(err);
});

/**
 * @param {string} clientId
 * @param {string} clientSecret
 * @param {string} idToken
 * @return {Promise<GoogleLogin>}
 */
function verifyIdToken(clientId, clientSecret, idToken) {
  const authFactory = new (require('google-auth-library'))();
  const client = new authFactory.OAuth2(clientId, clientSecret);
  return new Promise((resolve, reject) => {
    client.verifyIdToken(idToken, clientId, (err, user) => {
      if (err) {
        reject(err);
      }
      resolve(user);
    });
  });
}

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

'use strict';

const express = require('express');
const pwaModel = require('../../models/pwa');
const router = express.Router(); // eslint-disable-line new-cap
const config = require('../../config/config');
const CLIENT_ID = config.get('CLIENT_ID');
const CLIENT_SECRET = config.get('CLIENT_SECRET');
const crypto = require('crypto');
const LIST_PAGE_SIZE = 10;

/**
 * GET /pwas/add
 *
 * Display a page of PWAs (up to ten at a time).
 */
router.get('/', (req, res, next) => {
  function callback(err, entities, cursor) {
    if (err) {
      return next(err);
    }

    res.render('pwas/list.hbs', {
      pwas: entities,
      nextPageToken: cursor
    });
  }
  pwaModel.list(LIST_PAGE_SIZE, req.query.pageToken, callback);
});

/**
 * GET /pwas/add
 *
 * Display a form for creating a PWA.
 */
router.get('/add', (req, res) => {
  res.render('pwas/form.hbs', {
    pwa: {},
    action: 'Add'
  });
});

/**
 * POST /pwas/add
 *
 * Create a PWA.
 */
// [START add]
router.post('/add', (req, res, next) => {
  const manifestUrl = req.body.manifestUrl;
  const idToken = req.body.idToken;

  if (!manifestUrl) {
    res.render('pwas/form.hbs', {
      pwa: {
        manifestUrl: ''
      },
      error: 'no manifest provided'
    });
    return;
  }

  if (!idToken) {
    res.render('pwas/form.hbs', {
      pwa: {
        manifestUrl: manifestUrl
      },
      error: 'user not logged in'
    });
    return;
  }

  verifyIdToken(CLIENT_ID, CLIENT_SECRET, idToken)
    .then(user => {
      const pwa = {
        manifestUrl: manifestUrl,
        createdOn: new Date(),
        updatedOn: new Date(),
        user: {
          id: crypto.createHash('sha1').update(user.getPayload().sub).digest('hex')
        }
      };
      const callback = (err, savedData) => {
        if (err) {
          if (typeof err === 'number') {
            switch (err) {
              case pwaModel.E_ALREADY_EXISTS:
                res.render('pwas/form.hbs', {
                  pwa: {
                    manifestUrl: pwa.manifestUrl
                  },
                  error: 'manifest already exists'
                });
                return;
              case pwaModel.E_MANIFEST_ERROR:
                res.render('pwas/form.hbs', {
                  pwa: {
                    manifestUrl: pwa.manifestUrl
                  },
                  error: 'error loading manifest' // could be 404, not JSON, domain does not exist
                });
                return;
              default:
                return next(err);
            }
          }
        }
        res.redirect(req.baseUrl + '/' + savedData.id);
      };
      pwaModel.save(pwa, callback);
    })
    .catch(err => {
      res.render('pwas/form.hbs', {
        pwa: {
          manifestUrl: manifestUrl
        },
        error: err
      });
      return;
    });
});
// [END add]

/**
 * GET /pwas/:id/edit
 *
 * Display a pwa for editing.
 */
router.get('/:pwa/edit', (req, res, next) => {
  pwaModel.find(req.params.pwa, (err, entity) => {
    if (err) {
      return next(err);
    }

    res.render('pwas/form.hbs', {
      pwa: entity,
      action: 'Edit'
    });
  });
});

/**
 * POST /pwas/:id/edit
 *
 * Update a PWA.
 */

router.post('/:pwa/edit', (req, res, next) => {
  const data = req.body;
  data.id = req.params.pwa;

  pwaModel.save(data, (err, savedData) => {
    if (err) {
      return next(err);
    }
    res.redirect(req.baseUrl + '/' + savedData.id);
  });
});

/**
 * GET /pwas/:id
 *
 * Display a PWA.
 */
router.get('/:pwa', (req, res, next) => {
  pwaModel.find(req.params.pwa, (err, entity) => {
    if (err) {
      return next(err);
    }

    res.render('pwas/view.hbs', {
      pwa: entity
    });
  });
});

/**
 * GET /pwas/:id/delete
 *
 * Delete a PWA.
 */
router.get('/:pwa/delete', (req, res, next) => {
  pwaModel.delete(req.params.pwa, err => {
    if (err) {
      return next(err);
    }
    res.redirect(req.baseUrl);
  });
});

/**
 * Errors on "/pwas/*" routes.
 */
router.use((err, req, res, next) => {
  // Format error and forward to generic error handler for logging and
  // responding to the request
  err.response = err.message;
  next(err);
});

/**
 * @param {string} clientId
 * @param {string} clientSecret
 * @param {string} idToken
 * @return {Promise<GoogleLogin>}
 */
function verifyIdToken(clientId, clientSecret, idToken) {
  const authFactory = new (require('google-auth-library'))();
  const client = new authFactory.OAuth2(clientId, clientSecret);
  return new Promise((resolve, reject) => {
    client.verifyIdToken(idToken, clientId, (err, user) => {
      if (err) {
        reject(err);
      }
      resolve(user);
    });
  });
}

module.exports = router;
<|endoftext|>


<commit_before>var Job = require('../models/job');
var Company = require('../models/company');
var Star = require('../models/company');
var log = require('loglevel');

// GET /api/companies
exports.getCompanies = (req, res) => {
	Company.find({}).sort('title').select('title company location website logo').exec((err,companies)=>res.json(err ? {err: "error fetching companies"} : companies))
}

// GET /api/jobs
exports.getJobs = (req,res) => {
     var daysago = new Date(Date.now() - (60*60*24*1000));
     Job.find({last_seen: {$gte : daysago}})
		 .sort('-first_seen')
		 .exec(function(err, jobs) {
			if (err) {
				console.log(err);
				return res.json({err: "error fetching jobs"});
			}
			res.json(jobs);
    	 }
	 );
};

exports.getStars = (req, res) => {
	Star.find({user_id: req.user._id}).select('job_id').exec((err, stars) => {
		if (err) {
			console.log(err);
			return res.json({err: "error fetching stars"});
		}
		res.json(stars);
	})
}

exports.postStars = (req, res) => {
	var star = new Star({user_id: req.user._id, job_id: req.body.job_id});
	star.save((err, star) => {
		if (err) {
			log.error(err);
			return res.json({err: "error saving star"});
		}
		log.debug(`star saved: star_id: ${star._id}, user: ${req.user._id}`);
		res.json(star);
	})
}

exports.deleteStar = (req, res) => {
	Star.remove({user_id: req.user._id, job_id: req.body.job_id}).exec(err => {
		if (err) {
			console.log(err);
			return res.json({err: "error removing star"});
		}
		log.debug(`star deleted: job_id: ${job_id}, user: ${user.id}`);
		res.json({success:"success"})
	})
}

<commit_msg>fixed stupid bug in controller<commit_after>var Job = require('../models/job');
var Company = require('../models/company');
var Star = require('../models/star');
var log = require('loglevel');

// GET /api/companies
exports.getCompanies = (req, res) => {
	Company.find({}).sort('title').select('title company location website logo').exec((err,companies)=>res.json(err ? {err: "error fetching companies"} : companies))
}

// GET /api/jobs
exports.getJobs = (req,res) => {
     var daysago = new Date(Date.now() - (60*60*24*1000));
     Job.find({last_seen: {$gte : daysago}})
		 .sort('-first_seen')
		 .exec(function(err, jobs) {
			if (err) {
				console.log(err);
				return res.json({err: "error fetching jobs"});
			}
			res.json(jobs);
    	 }
	 );
};

exports.getStars = (req, res) => {
	Star.find({user_id: req.user._id}).select('job_id').exec((err, stars) => {
		if (err) {
			console.log(err);
			return res.json({err: "error fetching stars"});
		}
		res.json(stars);
	})
}

exports.postStars = (req, res) => {
	var star = new Star({user_id: req.user._id, job_id: req.body.job_id});
	star.save((err, star) => {
		if (err) {
			log.error(err);
			return res.json({err: "error saving star"});
		}
		log.debug(`star saved: star_id: ${star._id}, user: ${req.user._id}`);
		res.json(star);
	})
}

exports.deleteStar = (req, res) => {
	Star.remove({user_id: req.user._id, job_id: req.body.job_id}).exec(err => {
		if (err) {
			console.log(err);
			return res.json({err: "error removing star"});
		}
		log.debug(`star deleted: job_id: ${job_id}, user: ${user.id}`);
		res.json({success:"success"})
	})
}

<|endoftext|>


<commit_before>import {Injectable} from 'angular2/src/di/annotations_impl';
import {isPresent, isBlank, RegExpWrapper, BaseException} from 'angular2/src/facade/lang';
import {DOM} from 'angular2/src/dom/dom_adapter';

@Injectable()
export class UrlResolver {
  static a;

  constructor() {
    if (isBlank(UrlResolver.a)) {
      UrlResolver.a = DOM.createElement('a');
    }
  }

  resolve(baseUrl: string, url: string): string {
    if (isBlank(baseUrl)) {
      DOM.resolveAndSetHref(UrlResolver.a, url, null);
      return DOM.getHref(UrlResolver.a);
    }

    if (isBlank(url) || url == '') return baseUrl;

    if (url[0] == '/') {
      throw new BaseException(`Could not resolve the url ${url} from ${baseUrl}`);
    }

    var m = RegExpWrapper.firstMatch(_schemeRe, url);

    if (isPresent(m[1])) {
      return url;
    }

    DOM.resolveAndSetHref(UrlResolver.a, baseUrl, url);
    return DOM.getHref(UrlResolver.a);
  }
}

var _schemeRe = RegExpWrapper.create('^([^:/?#]+:)?');
<commit_msg>doc(UrlResolver): inline doc<commit_after>import {Injectable} from 'angular2/src/di/annotations_impl';
import {isPresent, isBlank, RegExpWrapper, BaseException} from 'angular2/src/facade/lang';
import {DOM} from 'angular2/src/dom/dom_adapter';

@Injectable()
export class UrlResolver {
  static a;

  constructor() {
    if (isBlank(UrlResolver.a)) {
      UrlResolver.a = DOM.createElement('a');
    }
  }

  /**
   * Resolves the `url` given the `baseUrl`.
   *
   * ## When the `baseUrl` is null
   *
   * `url` is resolved in the context of the current document.
   * If the document location is 'http://www.foo.com/base' and the `url` is 'path/to/here', the resolved url will be
   * 'http://www.foo.com/base/path/to/here'
   *
   * ## When the `baseUrl` is not null
   *
   * - when the `url` is null, the `baseUrl` is returned,
   * - due to a limitation in the process used to resolve urls (a HTMLLinkElement), `url` must not start with a `/`,
   * - if `url` is relative ('path/to/here', './path/to/here'), the resolved url is a combination of `baseUrl` and `url`,
   * - if `url` is absolute (it has a scheme: 'http://', 'https://'), the `url` is returned (ignoring the `baseUrl`)
   *
   * @param {string} baseUrl
   * @param {string} url
   * @returns {string} the resolved URL
   */
  resolve(baseUrl: string, url: string): string {
    if (isBlank(baseUrl)) {
      DOM.resolveAndSetHref(UrlResolver.a, url, null);
      return DOM.getHref(UrlResolver.a);
    }

    if (isBlank(url) || url == '') return baseUrl;

    if (url[0] == '/') {
      // The `HTMLLinkElement` does not allow resolving this case (the `url` would be interpreted as relative):
      // - `baseUrl` = 'http://www.foo.com/base'
      // - `url` = '/absolute/path/to/here'
      // - the result would be 'http://www.foo.com/base/absolute/path/to/here' while 'http://www.foo.com/absolute/path/to/here'
      // is expected (without the 'base' segment).
      throw new BaseException(`Could not resolve the url ${url} from ${baseUrl}`);
    }

    var m = RegExpWrapper.firstMatch(_schemeRe, url);

    if (isPresent(m[1])) {
      return url;
    }

    DOM.resolveAndSetHref(UrlResolver.a, baseUrl, url);
    return DOM.getHref(UrlResolver.a);
  }
}

var _schemeRe = RegExpWrapper.create('^([^:/?#]+:)?');
<|endoftext|>


<commit_before>
var hd_rightmenu = '
'
    + '
'
    + '
'
    + '
'
    + '
Panel info
'
    + '
'
    + '
'
    + '
'
    + '
Add and Id
'
    + '
Manage Classes

'
    + '
Add Attributes
'
    + '
Add Styles
'
    + '
Remove
'
    + '
Create Child
'
    + '
'
    + '
'
    +'
'
    +'
'
    +'
';
$(document).ready(function () {
    var hd_currentobj = $('body');
    $('body').append(hd_rightmenu);
    $('body').on('contextmenu', '*', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var position = $(this).offset();
        $('#hd_rightmenu').css({
            top: position.top,
            left:position.left
        })

        var tagname = $(this).prop("tagName").toLowerCase();
        var additionals = "";
        var id = $(this).attr("id");
        var classeslist = $(this).attr("class").split(' ');
        var classes=classeslist.join(',');
        additionals += (id) ? '#' + id : "";
        additionals += (classes) ? '.' + classes : "";
        $('#hd_rightmenu_allclasses').html("")
        $.each(classeslist, function (i, c) {
            if (c) {
                $('#hd_rightmenu_allclasses').append('
'
    + '
'
    + '          '
    + '            <input type="checkbox" checked="">' + c
    + '          '
    + '

');
            }
        })

        $('#hd_rightmenu_header h3').text(tagname+additionals);
        switch (tagname) {
            case 'div': {

                break;
            }
            default: {

                break;
            }
        }

    })

})<commit_msg>new merge<commit_after>(function (old) {
    $.fn.attr = function () {
        if (arguments.length === 0) {
            if (this.length === 0) {
                return null;
            }

            var obj = {};
            $.each(this[0].attributes, function () {
                if (this.specified) {
                    obj[this.name] = this.value;
                }
            });
            return obj;
        }

        return old.apply(this, arguments);
    };
})($.fn.attr);

var hd_rightmenu = '
'
    + '
'
    + '
'
    + '
'
    + '
Panel info
'
    + '
'
    + '
'
    + '
'
    + '
Attributes

'
    + '
Manage Classes

'
    + '
Add Attributes
'
    + '
Add Styles
'
    + '
Remove
'
    + '
Create Child
'
    + '
'
    + '
'
    +'
'
    +'
'
    +'
';
$(document).ready(function () {
    var hd_currentobj = $('body');
    $('body').append(hd_rightmenu);
    $('body').on('click', '*:not("#hd_rightmenu,#hd_rightmenu *")', function (e) {
        $('#hd_rightmenu').hide();
    })
    $('#hd_rightmenu').hide();
    $('body').on('contextmenu', '*', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var t = $(this);
        $('#hd_rightmenu').show();
        var position = t.offset();
        var trypositionright_left = position.left + t.width();
        var trypositionright_overlow = position.left + t.width() + $('#hd_rightmenu').width();
        var trypositionleft_left = position.left - $('#hd_rightmenu').width();

        $('#hd_rightmenu').css({
            top: position.top,
            left: ($(window).width() > trypositionright_overlow) ? trypositionright_left : (trypositionleft_left < 0) ? position.left:trypositionleft_left

        })

        var tagname = t.prop("tagName").toLowerCase();
        var additionals = "";
        var id = t.attr("id");
        var classeslist = (t.attr("class")) ? $(this).attr("class").split(' ') : false;
        var classes=(classeslist)?classeslist.join(','):classeslist;
        additionals += (id) ? '#' + id : "";
        additionals += (classes!="") ? '.' + classes : "";
        $('.hd_rightmenu_clear').html("")

        var attributes = t.attr();
        $.each(attributes, function (i, c) {
            if (c) {
                debugger;
                $('#hd_rightmenu_allattributes').append(''
    + '
'
    + '          '+i+''
    + '            <input type="text" class="form-control" value="' + c + '">' +
    + '          '
    + '
');
            }
        })

        $.each(classeslist, function (i, c) {
            if (c) {
                $('#hd_rightmenu_allclasses').append(''
    + '
'
    + '          '
    + '            <input type="checkbox" checked="">' + c
    + '          '
    + '
');
            }
        })

        $('#hd_rightmenu_header h3').text(tagname+additionals);
        switch (tagname) {
            case 'div': {

                break;
            }
            default: {

                break;
            }
        }

    })

    var autotest = 0;
    if (autotest == 0) {

        var testelements = $('div:first *');
        var testelementslength = testelements.length;
        autotest= Math.floor((Math.random() * (testelementslength-1)) + 1);
        function autotestfn() {
            setTimeout(function () {
                testelements.eq(autotest).trigger('contextmenu');
                if (autotest < testelementslength) {
                    autotestfn();
                }
                autotest++;
            },2000)
        }
        autotestfn();
        $('body').on('mouseover', '#hd_rightmenu")', function (e) {
            autotest = testelementslength;
        })
    }

})<|endoftext|>


<commit_before><commit_msg>Update gamepad.user.js<commit_after><|endoftext|>


<commit_before>
(function() {
	var undefined;

	function execute() {

		//////////////////////////////////////////////////////////////////////////////////////
		// validation events
		var ensureInited = function($el) {
			if (!window.ExoWeb) {
				return;
			}

			if ($el.attr("__validating") === undefined) {
				// register for model validation events
				var bindings = $el.liveBindings();

				for (var i = 0; i < bindings.length; i++) {
					var binding = bindings[i];
					var srcObj = Sys_Binding_getFinalSourceObject(binding);
					var propName = Sys_Binding_getFinalPath(binding);

					var meta = srcObj.meta || srcObj;

					if (meta && meta.addPropertyValidating) {
						// wire up validating/validated events
						meta.addPropertyValidating(propName, function(sender, issues) {
							$el.trigger('validating');
						});
					}

					if (meta && meta.addPropertyValidated) {
						meta.addPropertyValidated(propName, function(sender, issues) {
							$el.trigger("validated", [issues]);
						});
					}
				}

				// don't double register for events
				$el.attr("__validating", true);
			}
		};

		jQuery.fn.validated = function(f) {
			this.each(function() {
				$(this).bind('validated', f);
				ensureInited($(this));
			});

			return this;
		};

		jQuery.fn.validating = function(f) {
			this.each(function() {
				$(this).bind("validating", f);
				ensureInited($(this));
			});

			return this;
		};

		//////////////////////////////////////////////////////////////////////////////////////
		// rendering events
		jQuery.fn.rendering = function(f, onlyRaiseOnTarget) {
			$(this).each(function() {
				var target = this;
				$(this).bind("rendering", function(evt) {
					if (!onlyRaiseOnTarget || evt.target == target) {
						f.apply(this, arguments);
					}
				});
			});
			return this;
		};

		jQuery.fn.rendered = function(f, onlyRaiseOnTarget) {
			$(this).each(function() {
				var target = this;
				$(this).bind("rendered", function(evt) {
					if (!onlyRaiseOnTarget || evt.target == target) {
						f.apply(this, arguments);
					}
				});
			});
			return this;
		};

		//////////////////////////////////////////////////////////////////////////////////////
		// selectors for rules
		jQuery.expr[":"].rule = function(obj, index, meta, stack) {
			if (!(window.ExoWeb && ExoWeb.Model)) {
				return false;
			}

			var ruleName = meta[3];
			var ruleType = ExoWeb.Model.Rule[ruleName];

			if (!ruleType) {
				ExoWeb.trace.throwAndLog(["ui", "jquery"], "Unknown rule in selector: " + ruleName);
			}

			return $(obj).rules(ruleType).length > 0;
		};

		jQuery.expr[":"].bound = function(obj, index, meta, stack) {
			if (!(window.ExoWeb && ExoWeb.Model)) {
				return false;
			}
			return $(obj).liveBindings().length > 0;
		};

		//////////////////////////////////////////////////////////////////////////////////////
		// helpers for working with ms ajax controls

		jQuery.expr[":"].dataview = function(obj, index, meta, stack) {
			return obj.control !== undefined && obj.control instanceof Sys.UI.DataView;
		};

		jQuery.expr[":"].content = function(obj, index, meta, stack) {
			return ExoWeb.UI !== undefined && obj.control !== undefined && obj.control instanceof ExoWeb.UI.Content;
		};

		jQuery.expr[":"].control = function(obj, index, meta, stack) {
			var typeName = meta[3];
			var jstype = new Function("{return " + typeName + ";}");

			return obj.control instanceof jstype;
		};

		jQuery.fn.control = function(propName, propValue) {
			if (arguments.length === 0) {
				return this.get(0).control;
			}
			else if (arguments.length == 1) {
				return this.get(0).control["get_" + propName]();
			}
			else {
				this.each(function(element) {
					element.control["set_" + propName](propValue);
					return this;
				});
			}
		};

		jQuery.fn.commands = function(commands) {
			var control = this.control();
			control.add_command(function(sender, args) {
				var handler = commands[args.get_commandName()];
				if (handler) {
					handler(sender, args);
				}
			});
		};

		//////////////////////////////////////////////////////////////////////////////////////
		// helpers for MS AJAX and model integration
		var everRegs = [];

		function processElements(els, action) {
			for (var e = 0; e < els.length; ++e) {
				var el = els[e];

				for (var i = 0; i < everRegs.length; ++i) {
					var reg = everRegs[i];

					var handler = reg[action];

					if (!handler) {
						continue;
					}

					// test root
					if ($(el).is(reg.selector)) {
						handler.apply(el);
					}

					// test children
					$(reg.selector, el).each(handler);
				}
			}
		}

		var interceptingTemplates = false;
		var interceptingWebForms = false;

		function ensureIntercepting() {
			if (!interceptingTemplates && window.Sys && Sys.UI && Sys.UI.Template) {
				var instantiateInBase = Sys.UI.Template.prototype.instantiateIn;
				Sys.UI.Template.prototype.instantiateIn = function(containerElement, data, dataItem, dataIndex, nodeToInsertTemplateBefore, parentContext) {
					var ret = instantiateInBase.apply(this, arguments);

					processElements(ret.nodes, "added");
					return ret;
				};
				interceptingTemplates = true;
			}

			if (!interceptingWebForms && window.Sys && Sys.WebForms) {
				Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(function(sender, evt) {
					processElements(evt.get_panelsUpdating(), "deleted");
				});

				Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function(sender, evt) {
					processElements(evt.get_panelsCreated(), "added");
					processElements(evt.get_panelsUpdated(), "added");
				});
				interceptingWebForms = true;
			}
		}

		// matches elements as they are dynamically added to the DOM
		jQuery.fn.ever = function(added, deleted) {

			// If the function is called in any way other than as a method on the
			// jQuery object, then intercept and return early.
			if (!(this instanceof jQuery)) {
				ensureIntercepting();
				return;
			}

			// apply now
			this.each(added);

			// and then watch for dom changes
			everRegs.push({
				selector: this.selector,
				context: this.context,
				added: added,
				deleted: deleted
			});

			ensureIntercepting();

			// really shouldn't chain calls b/c only elements
			// currently in the DOM would be affected.
			return null;
		};

		// Gets all Sys.Bindings for an element
		jQuery.fn.liveBindings = function() {
			var bindings = [];
			this.each(function() {
				if(this.__msajaxbindings)
					Array.addRange(bindings, this.__msajaxbindings);
			});

			return bindings;
		};

		// Gets all model rules associated with the property an element is bound to
		jQuery.fn.rules = function(ruleType) {
			if (!(window.ExoWeb && ExoWeb.Model)) {
				return [];
			}

			var rules = [];
			var bindings = $(this).liveBindings();

			for (var i = 0; i < bindings.length; i++) {
				var binding = bindings[i];
				var srcObj = Sys_Binding_getFinalSourceObject(binding);

				var prop;

				if (srcObj instanceof ExoWeb.View.Adapter) {
					prop = srcObj.get_propertyChain().lastProperty();
				}
				else if (srcObj instanceof ExoWeb.View.OptionAdapter) {
					prop = srcObj.get_parent().get_propertyChain().lastProperty();
				}
				else if (srcObj instanceof ExoWeb.Model.ObjectBase) {
					var propName = Sys_Binding_getFinalPath(binding);
					prop = srcObj.meta.property(propName);
				}
				else {
					continue;
				}

				var rule = prop.rule(ruleType);
				if (rule) {
					rules.push(rule);
				}
			}

			return rules;
		};

		jQuery.fn.issues = function() {
			var issues = [];

			var bindings = $(this).liveBindings();

			for (var i = 0; i < bindings.length; i++) {
				var binding = bindings[i];
				var srcObj = Sys_Binding_getFinalSourceObject(binding);

				var target;
				var prop;

				if (srcObj instanceof ExoWeb.View.Adapter) {
					var chain = srcObj.get_propertyChain();
					prop = chain.lastProperty();
					target = chain.lastTarget(srcObj.get_target());
				}
				else if (srcObj instanceof ExoWeb.View.OptionAdapter) {
					var chain = srcObj.get_parent().get_propertyChain();
					prop = chain.lastProperty();
					target = chain.lastTarget(srcObj.get_parent().get_target());
				}
				else if (srcObj instanceof ExoWeb.Model.ObjectBase) {
					var propName = Sys_Binding_getFinalPath(binding);
					prop = srcObj.meta.property(propName);
					target = srcObj;
				}
				else {
					continue;
				}

				Array.addRange(issues, target.meta.issues(prop));
			}
			return issues;
		};

		// Get's the last object in the source path.  Ex: Customer.Address.Street returns the Address object.
		function Sys_Binding_getFinalSourceObject(binding) {
			var src = binding.get_source();

			for (var i = 0; i < binding._pathArray.length - 1; ++i) {
				src = src[binding._pathArray[i]] || src["get_" + binding._pathArray[i]]();
			}

			return src;
		}

		function Sys_Binding_getFinalPath(binding) {
			return binding._pathArray[binding._pathArray.length - 1];
		}
	}

	if (window.Sys && Sys.loader) {
		Sys.loader.registerScript("ExoWebJquery", null, execute);
	}
	else {
		execute();
	}
})();
<commit_msg>JQuery.fn.ever now intercepts Sys.UI.DataView.dispose<commit_after>
(function() {
	var undefined;

	function execute() {

		//////////////////////////////////////////////////////////////////////////////////////
		// validation events
		var ensureInited = function($el) {
			if (!window.ExoWeb) {
				return;
			}

			if ($el.attr("__validating") === undefined) {
				// register for model validation events
				var bindings = $el.liveBindings();

				for (var i = 0; i < bindings.length; i++) {
					var binding = bindings[i];
					var srcObj = Sys_Binding_getFinalSourceObject(binding);
					var propName = Sys_Binding_getFinalPath(binding);

					var meta = srcObj.meta || srcObj;

					if (meta && meta.addPropertyValidating) {
						// wire up validating/validated events
						meta.addPropertyValidating(propName, function(sender, issues) {
							$el.trigger('validating');
						});
					}

					if (meta && meta.addPropertyValidated) {
						meta.addPropertyValidated(propName, function(sender, issues) {
							$el.trigger("validated", [issues]);
						});
					}
				}

				// don't double register for events
				$el.attr("__validating", true);
			}
		};

		jQuery.fn.validated = function(f) {
			this.each(function() {
				$(this).bind('validated', f);
				ensureInited($(this));
			});

			return this;
		};

		jQuery.fn.validating = function(f) {
			this.each(function() {
				$(this).bind("validating", f);
				ensureInited($(this));
			});

			return this;
		};

		//////////////////////////////////////////////////////////////////////////////////////
		// rendering events
		jQuery.fn.rendering = function(f, onlyRaiseOnTarget) {
			$(this).each(function() {
				var target = this;
				$(this).bind("rendering", function(evt) {
					if (!onlyRaiseOnTarget || evt.target == target) {
						f.apply(this, arguments);
					}
				});
			});
			return this;
		};

		jQuery.fn.rendered = function(f, onlyRaiseOnTarget) {
			$(this).each(function() {
				var target = this;
				$(this).bind("rendered", function(evt) {
					if (!onlyRaiseOnTarget || evt.target == target) {
						f.apply(this, arguments);
					}
				});
			});
			return this;
		};

		//////////////////////////////////////////////////////////////////////////////////////
		// selectors for rules
		jQuery.expr[":"].rule = function(obj, index, meta, stack) {
			if (!(window.ExoWeb && ExoWeb.Model)) {
				return false;
			}

			var ruleName = meta[3];
			var ruleType = ExoWeb.Model.Rule[ruleName];

			if (!ruleType) {
				ExoWeb.trace.throwAndLog(["ui", "jquery"], "Unknown rule in selector: " + ruleName);
			}

			return $(obj).rules(ruleType).length > 0;
		};

		jQuery.expr[":"].bound = function(obj, index, meta, stack) {
			if (!(window.ExoWeb && ExoWeb.Model)) {
				return false;
			}
			return $(obj).liveBindings().length > 0;
		};

		//////////////////////////////////////////////////////////////////////////////////////
		// helpers for working with ms ajax controls

		jQuery.expr[":"].dataview = function(obj, index, meta, stack) {
			return obj.control !== undefined && obj.control instanceof Sys.UI.DataView;
		};

		jQuery.expr[":"].content = function(obj, index, meta, stack) {
			return ExoWeb.UI !== undefined && obj.control !== undefined && obj.control instanceof ExoWeb.UI.Content;
		};

		jQuery.expr[":"].control = function(obj, index, meta, stack) {
			var typeName = meta[3];
			var jstype = new Function("{return " + typeName + ";}");

			return obj.control instanceof jstype;
		};

		jQuery.fn.control = function(propName, propValue) {
			if (arguments.length === 0) {
				return this.get(0).control;
			}
			else if (arguments.length == 1) {
				return this.get(0).control["get_" + propName]();
			}
			else {
				this.each(function(element) {
					element.control["set_" + propName](propValue);
					return this;
				});
			}
		};

		jQuery.fn.commands = function(commands) {
			var control = this.control();
			control.add_command(function(sender, args) {
				var handler = commands[args.get_commandName()];
				if (handler) {
					handler(sender, args);
				}
			});
		};

		//////////////////////////////////////////////////////////////////////////////////////
		// helpers for MS AJAX and model integration
		var everRegs = [];

		function processElements(els, action) {
			for (var e = 0; e < els.length; ++e) {
				var el = els[e];

				for (var i = 0; i < everRegs.length; ++i) {
					var reg = everRegs[i];

					var handler = reg[action];

					if (!handler) {
						continue;
					}

					// test root
					if ($(el).is(reg.selector)) {
						handler.apply(el);
					}

					// test children
					$(reg.selector, el).each(handler);
				}
			}
		}

		var interceptingTemplates = false;
		var interceptingWebForms = false;

		function ensureIntercepting() {
			if (!interceptingTemplates && window.Sys && Sys.UI && Sys.UI.Template) {
				var instantiateInBase = Sys.UI.Template.prototype.instantiateIn;
				Sys.UI.Template.prototype.instantiateIn = function(containerElement, data, dataItem, dataIndex, nodeToInsertTemplateBefore, parentContext) {
					var context = instantiateInBase.apply(this, arguments);

					processElements(context.nodes, "added");
					return context;
				};

				// intercept Sys.UI.DataView._clearContainers called conditionally during dispose() and refresh().
				// dispose is too late because the nodes will have been cleared out.
				var clearContainersBase = Sys.UI.DataView.prototype._clearContainers;
				Sys.UI.DataView.prototype._clearContainers = function() {
					var contexts = this.get_contexts();

					for (var i = 0; i < contexts.length; i++)
						processElements(contexts[i].nodes, "deleted");

					clearContainersBase.apply(this, arguments);
				}

				interceptingTemplates = true;
			}

			if (!interceptingWebForms && window.Sys && Sys.WebForms) {
				Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(function(sender, evt) {
					processElements(evt.get_panelsUpdating(), "deleted");
				});

				Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function(sender, evt) {
					processElements(evt.get_panelsCreated(), "added");
					processElements(evt.get_panelsUpdated(), "added");
				});
				interceptingWebForms = true;
			}
		}

		// matches elements as they are dynamically added to the DOM
		jQuery.fn.ever = function(added, deleted) {

			// If the function is called in any way other than as a method on the
			// jQuery object, then intercept and return early.
			if (!(this instanceof jQuery)) {
				ensureIntercepting();
				return;
			}

			// apply now
			this.each(added);

			// and then watch for dom changes
			everRegs.push({
				selector: this.selector,
				context: this.context,
				added: added,
				deleted: deleted
			});

			ensureIntercepting();

			// really shouldn't chain calls b/c only elements
			// currently in the DOM would be affected.
			return null;
		};

		// Gets all Sys.Bindings for an element
		jQuery.fn.liveBindings = function() {
			var bindings = [];
			this.each(function() {
				if (this.__msajaxbindings)
					Array.addRange(bindings, this.__msajaxbindings);
			});

			return bindings;
		};

		// Gets all model rules associated with the property an element is bound to
		jQuery.fn.rules = function(ruleType) {
			if (!(window.ExoWeb && ExoWeb.Model)) {
				return [];
			}

			var rules = [];
			var bindings = $(this).liveBindings();

			for (var i = 0; i < bindings.length; i++) {
				var binding = bindings[i];
				var srcObj = Sys_Binding_getFinalSourceObject(binding);

				var prop;

				if (srcObj instanceof ExoWeb.View.Adapter) {
					prop = srcObj.get_propertyChain().lastProperty();
				}
				else if (srcObj instanceof ExoWeb.View.OptionAdapter) {
					prop = srcObj.get_parent().get_propertyChain().lastProperty();
				}
				else if (srcObj instanceof ExoWeb.Model.ObjectBase) {
					var propName = Sys_Binding_getFinalPath(binding);
					prop = srcObj.meta.property(propName);
				}
				else {
					continue;
				}

				var rule = prop.rule(ruleType);
				if (rule) {
					rules.push(rule);
				}
			}

			return rules;
		};

		jQuery.fn.issues = function() {
			var issues = [];

			var bindings = $(this).liveBindings();

			for (var i = 0; i < bindings.length; i++) {
				var binding = bindings[i];
				var srcObj = Sys_Binding_getFinalSourceObject(binding);

				var target;
				var prop;

				if (srcObj instanceof ExoWeb.View.Adapter) {
					var chain = srcObj.get_propertyChain();
					prop = chain.lastProperty();
					target = chain.lastTarget(srcObj.get_target());
				}
				else if (srcObj instanceof ExoWeb.View.OptionAdapter) {
					var chain = srcObj.get_parent().get_propertyChain();
					prop = chain.lastProperty();
					target = chain.lastTarget(srcObj.get_parent().get_target());
				}
				else if (srcObj instanceof ExoWeb.Model.ObjectBase) {
					var propName = Sys_Binding_getFinalPath(binding);
					prop = srcObj.meta.property(propName);
					target = srcObj;
				}
				else {
					continue;
				}

				Array.addRange(issues, target.meta.issues(prop));
			}
			return issues;
		};

		// Get's the last object in the source path.  Ex: Customer.Address.Street returns the Address object.
		function Sys_Binding_getFinalSourceObject(binding) {
			var src = binding.get_source();

			for (var i = 0; i < binding._pathArray.length - 1; ++i) {
				src = src[binding._pathArray[i]] || src["get_" + binding._pathArray[i]]();
			}

			return src;
		}

		function Sys_Binding_getFinalPath(binding) {
			return binding._pathArray[binding._pathArray.length - 1];
		}
	}

	if (window.Sys && Sys.loader) {
		Sys.loader.registerScript("ExoWebJquery", null, execute);
	}
	else {
		execute();
	}
})();
<|endoftext|>


<commit_before>/*
Gordon Williams (gw@pur3.co.uk)
*/
(function() {
  // Are we on nw.js with chrome.serial? No need for serialport then!
  if (typeof chrome !== 'undefined' && chrome.serial) {
    console.log("We have chrome.serial - not using 'serialport' module");
    return;
  }
  if (typeof require === 'undefined') return;
  var serialport;
  try {
    serialport = require('serialport');
  } catch (e) {
    console.log("No 'serialport' module found");
    return;
  }

  var connection = undefined;

  var getPorts=function(callback) {
    serialport.list(function(err, ports) {
      if (ports===undefined) callback([]);
      else callback(ports
          /**
           * Filter the available serial ports to find the one(s)
           * most likely to be an espruino (genuine, or at least STM32Fxxx based
           *
           * According to http://www.linux-usb.org/usb.ids
           * vendorId === '0x0483' -> STMicroelectronics
           * productId === '0x5740' -> STM32F407
           *
           * What is below works great for both Espruino boards, but fails for:
           *   * USB-TTL adaptors
           *   * Bluetooth Serial
           *   * BBC micro:bit, Nordic devkits, etc
           *
           * So can't be left in. TODO: return an object for each USB serial device
           * and have a `preferred : bool` field in it. Then if many devices are found
           * but only one is preferred, use that.
           */
//          .filter(function(e) {
//            return (e.vendorId === '0x0483' && e.productId === '0x5740');
//          })
          .map(function(port) {
            // port.pnpId could be handy
            var vid = parseInt(port.vendorId);
            var pid = parseInt(port.productId);
            var d = { path : port.comName };
            if (vid||pid) d.usb = [vid,pid];
            if (port.manufacturer) d.description = port.manufacturer;
            if (!port.vendorId || !port.productId) d.unimportant = true;
            return d;
          })
      );
    });
  };

  var openSerial=function(serialPort, openCallback, receiveCallback, disconnectCallback) {
    // https://github.com/voodootikigod/node-serialport#reference-guide
    connection = new serialport(serialPort, {
        baudrate: parseInt(Espruino.Config.BAUD_RATE)
    });
    connection.on('open', function() {
      openCallback("Ok");
    });
    connection.on('data', function(data) {
      if (receiveCallback !== undefined) {
        var a = new Uint8Array(data.length);
        for (var i=0;i<data.length;i++)
          a[i] = data[i];
        receiveCallback(a.buffer);
      }
    });
    connection.on('close', function() {
      disconnectCallback();
      connection = undefined;
    });
  };

  var closeSerial=function(callback) {
    connection.close(callback);
  };

  var writeSerial = function(data, callback) {
    // convert to an array - if we put a string into
    // a Buffer (expected by nodeserial) then I think
    // it gets interpreted as UTF8
    var a = new Buffer(data.length);
    for (var i=0;i<data.length;i++)
      a[i] = data.charCodeAt(i);
    connection.write(a, callback);
  };

  // ----------------------------------------------------------
  Espruino.Core.Serial.devices.push({
    "name" : "Node Serial",
    "getPorts": getPorts,
    "open": openSerial,
    "write": writeSerial,
    "close": closeSerial,
  });
})();
<commit_msg>Fix Typo in serial port connection initialisation<commit_after>/*
Gordon Williams (gw@pur3.co.uk)
*/
(function() {
  // Are we on nw.js with chrome.serial? No need for serialport then!
  if (typeof chrome !== 'undefined' && chrome.serial) {
    console.log("We have chrome.serial - not using 'serialport' module");
    return;
  }
  if (typeof require === 'undefined') return;
  var serialport;
  try {
    serialport = require('serialport');
  } catch (e) {
    console.log("No 'serialport' module found");
    return;
  }

  var connection = undefined;

  var getPorts=function(callback) {
    serialport.list(function(err, ports) {
      if (ports===undefined) callback([]);
      else callback(ports
          /**
           * Filter the available serial ports to find the one(s)
           * most likely to be an espruino (genuine, or at least STM32Fxxx based
           *
           * According to http://www.linux-usb.org/usb.ids
           * vendorId === '0x0483' -> STMicroelectronics
           * productId === '0x5740' -> STM32F407
           *
           * What is below works great for both Espruino boards, but fails for:
           *   * USB-TTL adaptors
           *   * Bluetooth Serial
           *   * BBC micro:bit, Nordic devkits, etc
           *
           * So can't be left in. TODO: return an object for each USB serial device
           * and have a `preferred : bool` field in it. Then if many devices are found
           * but only one is preferred, use that.
           */
//          .filter(function(e) {
//            return (e.vendorId === '0x0483' && e.productId === '0x5740');
//          })
          .map(function(port) {
            // port.pnpId could be handy
            var vid = parseInt(port.vendorId);
            var pid = parseInt(port.productId);
            var d = { path : port.comName };
            if (vid||pid) d.usb = [vid,pid];
            if (port.manufacturer) d.description = port.manufacturer;
            if (!port.vendorId || !port.productId) d.unimportant = true;
            return d;
          })
      );
    });
  };

  var openSerial=function(serialPort, openCallback, receiveCallback, disconnectCallback) {
    // https://github.com/voodootikigod/node-serialport#reference-guide
    connection = new serialport(serialPort, {
        baudRate: parseInt(Espruino.Config.BAUD_RATE)
    });
    connection.on('open', function() {
      openCallback("Ok");
    });
    connection.on('data', function(data) {
      if (receiveCallback !== undefined) {
        var a = new Uint8Array(data.length);
        for (var i=0;i<data.length;i++)
          a[i] = data[i];
        receiveCallback(a.buffer);
      }
    });
    connection.on('close', function() {
      disconnectCallback();
      connection = undefined;
    });
  };

  var closeSerial=function(callback) {
    connection.close(callback);
  };

  var writeSerial = function(data, callback) {
    // convert to an array - if we put a string into
    // a Buffer (expected by nodeserial) then I think
    // it gets interpreted as UTF8
    var a = new Buffer(data.length);
    for (var i=0;i<data.length;i++)
      a[i] = data.charCodeAt(i);
    connection.write(a, callback);
  };

  // ----------------------------------------------------------
  Espruino.Core.Serial.devices.push({
    "name" : "Node Serial",
    "getPorts": getPorts,
    "open": openSerial,
    "write": writeSerial,
    "close": closeSerial,
  });
})();
<|endoftext|>


<commit_before>(function() {

  function getStatus(ignoreSettings) {
    if (typeof navigator == "undefined") {
      return {warning:"Not running in a browser"};
    }
    if (!navigator.serial) {
      if (Espruino.Core.Utils.isChrome())
        return {error:`Chrome currently requires <code>chrome://flags/#enable-experimental-web-platform-features</code> to be enabled.`};
      else if (Espruino.Core.Utils.isFirefox())
        return {error:`Firefox doesn't support Web Serial - try using Chrome`};
      else
        return {error:"No navigator.serial. Do you have a supported browser?"};
    }
    if (window && window.location && window.location.protocol=="http:" &&
        window.location.hostname!="localhost") {
      return {error:"Serving off HTTP (not HTTPS)"};
    }
    if (!ignoreSettings && !Espruino.Config.WEB_SERIAL)
      return {warning:`"Web Serial" disabled in settings`};
    return true;
  }

  var OK = true;
  var testedCompatibility = false;

  var serialPort = undefined;
  var connectionDisconnectCallback;

  function init() {
    Espruino.Core.Config.add("WEB_SERIAL", {
      section : "Communications",
      name : "Connect over Serial (Web Serial)",
      descriptionHTML : 'Allow connection to Espruino from the Web Browser via Serial. The API must currently be enabled by pasting chrome://flags#enable-experimental-web-platform-features into the address bar and clicking Enable',
      type : "boolean",
      defaultValue : true,
    });
  }

  function getPorts(callback) {
    if (!testedCompatibility) {
      testedCompatibility = true;
      if (getStatus(true)!==true)
        OK = false;
    }
    if (Espruino.Config.WEB_SERIAL && OK)
      callback([{path:'Web Serial', description:'Serial', type : "serial"}], true/*instantPorts*/);
    else
      callback(undefined, true/*instantPorts*/);
  }

  function openSerial(_, openCallback, receiveCallback, disconnectCallback) {
    // TODO: Pass USB vendor and product ID filter when supported by Chrome.
    // TODO: Retrieve device name when/if supported and use a pairedDevices list like in Web Bluetooth
    navigator.serial.requestPort({}).then(function(port) {
      Espruino.Core.Status.setStatus("Connecting to serial port");
      serialPort = port;
      return port.open({ baudrate: parseInt(Espruino.Config.BAUD_RATE) });
    }).then(function () {
      function readLoop() {
        var reader = serialPort.readable.getReader();
        reader.read().then(function ({ value, done }) {
          reader.releaseLock();
          if (value) {
            receiveCallback(value.buffer);
          }
          if (done) {
            disconnectCallback();
          } else {
            readLoop();
          }
        });
      }
      readLoop();
      Espruino.Core.Status.setStatus("Serial connected. Receiving data...");
      // TODO: Provide a device name when supported by Chrome.
      openCallback({});
    }).catch(function(error) {
      console.log('Serial> ERROR: ' + error);
      disconnectCallback();
    });
  }

  function closeSerial() {
    if (serialPort) {
      serialPort.close();
      serialPort = undefined;
    }
    if (connectionDisconnectCallback) {
      connectionDisconnectCallback();
      connectionDisconnectCallback = undefined;
    }
  }

  function writeSerial(data, callback) {
    var writer = serialPort.writable.getWriter();
    writer.write(Espruino.Core.Utils.stringToArrayBuffer(data)).then(function() {
      callback();
    }).catch(function(error) {
      console.log('Serial> SEND ERROR: ' + error);
      closeSerial();
    });
    writer.releaseLock();
  }

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

  Espruino.Core.Serial.devices.push({
    "name" : "Web Serial",
    "init" : init,
    "getStatus": getStatus,
    "getPorts": getPorts,
    "open": openSerial,
    "write": writeSerial,
    "close": closeSerial,
  });
})();
<commit_msg>Fix Serial disconnect bug<commit_after>(function() {

  function getStatus(ignoreSettings) {
    if (typeof navigator == "undefined") {
      return {warning:"Not running in a browser"};
    }
    if (!navigator.serial) {
      if (Espruino.Core.Utils.isChrome())
        return {error:`Chrome currently requires <code>chrome://flags/#enable-experimental-web-platform-features</code> to be enabled.`};
      else if (Espruino.Core.Utils.isFirefox())
        return {error:`Firefox doesn't support Web Serial - try using Chrome`};
      else
        return {error:"No navigator.serial. Do you have a supported browser?"};
    }
    if (window && window.location && window.location.protocol=="http:" &&
        window.location.hostname!="localhost") {
      return {error:"Serving off HTTP (not HTTPS)"};
    }
    if (!ignoreSettings && !Espruino.Config.WEB_SERIAL)
      return {warning:`"Web Serial" disabled in settings`};
    return true;
  }

  var OK = true;
  var testedCompatibility = false;

  var serialPort;
  var serialPortReader;
  var connectionDisconnectCallback;

  function init() {
    Espruino.Core.Config.add("WEB_SERIAL", {
      section : "Communications",
      name : "Connect over Serial (Web Serial)",
      descriptionHTML : 'Allow connection to Espruino from the Web Browser via Serial. The API must currently be enabled by pasting chrome://flags#enable-experimental-web-platform-features into the address bar and clicking Enable',
      type : "boolean",
      defaultValue : true,
    });
  }

  function getPorts(callback) {
    if (!testedCompatibility) {
      testedCompatibility = true;
      if (getStatus(true)!==true)
        OK = false;
    }
    if (Espruino.Config.WEB_SERIAL && OK)
      callback([{path:'Web Serial', description:'Serial', type : "serial"}], true/*instantPorts*/);
    else
      callback(undefined, true/*instantPorts*/);
  }

  function openSerial(_, openCallback, receiveCallback, disconnectCallback) {
    // TODO: Pass USB vendor and product ID filter when supported by Chrome.
    // TODO: Retrieve device name when/if supported and use a pairedDevices list like in Web Bluetooth
    navigator.serial.requestPort({}).then(function(port) {
      Espruino.Core.Status.setStatus("Connecting to serial port");
      serialPort = port;
      return port.open({ baudrate: parseInt(Espruino.Config.BAUD_RATE) });
    }).then(function () {
      function readLoop() {
        serialPortReader = serialPort.readable.getReader();
        serialPortReader.read().then(function ({ value, done }) {
          serialPortReader.releaseLock();
          if (value) {
            receiveCallback(value.buffer);
          }
          if (done) {
            disconnectCallback();
          } else {
            readLoop();
          }
        });
      }
      readLoop();
      Espruino.Core.Status.setStatus("Serial connected. Receiving data...");
      // TODO: Provide a device name when supported by Chrome.
      openCallback({});
    }).catch(function(error) {
      console.log('Serial> ERROR: ' + error);
      disconnectCallback();
    });
  }

  function closeSerial() {
    if (serialPort) {
      serialPortReader.cancel().then(function() {
        serialPort.close();
        serialPort = undefined;
        serialPortReader = undefined;
      });
    }
    if (connectionDisconnectCallback) {
      connectionDisconnectCallback();
      connectionDisconnectCallback = undefined;
    }
  }

  function writeSerial(data, callback) {
    var writer = serialPort.writable.getWriter();
    writer.write(Espruino.Core.Utils.stringToArrayBuffer(data)).then(function() {
      callback();
    }).catch(function(error) {
      console.log('Serial> SEND ERROR: ' + error);
      closeSerial();
    });
    writer.releaseLock();
  }

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

  Espruino.Core.Serial.devices.push({
    "name" : "Web Serial",
    "init" : init,
    "getStatus": getStatus,
    "getPorts": getPorts,
    "open": openSerial,
    "write": writeSerial,
    "close": closeSerial,
  });
})();
<|endoftext|>


<commit_before>let attachedTabs = {};

// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
  let tabId = tab.id;

  if (!attachedTabs[tabId]) {
    attachedTabs[tabId] = 'collapsed';
    chrome.browserAction.setIcon({tabId: tabId, path:'icons/pause.png'});
    chrome.browserAction.setTitle({tabId: tabId, title:'Pause collapsing'});

    chrome.tabs.executeScript({file: 'src/bg/collapse.js'});
  } else if (attachedTabs[tabId]) {
    delete attachedTabs[tabId];
    chrome.browserAction.setIcon({tabId: tabId, path:'icons/continue.png'});
    chrome.browserAction.setTitle({tabId: tabId, title:'Enable collapsing'});

    chrome.tabs.executeScript({file: 'src/bg/expand.js'});
  }
});
<commit_msg>Add pre-execution script via message passing<commit_after>let attachedTabs = {};
let textContentArr;
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
  let tabId = tab.id;

  // https://developer.chrome.com/extensions/content_scripts#pi
  chrome.tabs.executeScript(tabId, {file: 'src/bg/textcontent.js'}, function (){
    chrome.tabs.sendMessage(tabId, {}, function(response) {
      textContentArr = response;
      console.log(textContentArr);
    });
  });

  if (!attachedTabs[tabId]) {
    attachedTabs[tabId] = 'collapsed';
    chrome.browserAction.setIcon({tabId: tabId, path:'icons/pause.png'});
    chrome.browserAction.setTitle({tabId: tabId, title:'Pause collapsing'});
    chrome.tabs.executeScript({file: 'src/bg/collapse.js'});

  } else if (attachedTabs[tabId]) {
    delete attachedTabs[tabId];
    chrome.browserAction.setIcon({tabId: tabId, path:'icons/continue.png'});
    chrome.browserAction.setTitle({tabId: tabId, title:'Enable collapsing'});
    chrome.tabs.executeScript({file: 'src/bg/expand.js'});
  }
});
<|endoftext|>