<commit_before>/**
 * @name jsondir
 * @description Convert JSON objects to directories and back again.
 *
 * @author Daniel Imhoff
 */

'use strict';

var ASYNC = require('async');

var File = require('./File').File;

var knownAttributes = Object.freeze([
  '-name',
  '-type',
  '-path',
  '-mode',
  '-owner',
  '-group',
  '-dest',
  '-content'
]);

var inheritableAttributes = Object.freeze([
  '-mode',
  '-owner',
  '-group'
]);

/**
 * Split up given object into children and valid attributes that are ready for
 * the File constructor.
 *
 * @param  {object} options
 * @param  {object} parentAttributes Normalized attributes of the parent.
 * @return {object}
 */
var normalizeOptions = function(options, parentAttributes) {
  var opts = {
    attributes: {},
    inheritedAttributes: [],
    children: {}
  };

  if (typeof options === 'object') {
    for (var i in options) {
      // If the starting character is a hyphen, the option is an attribute,
      // because having files prepended with a hyphen in Unix is a terrible
      // idea.
      if (i.indexOf('-') === 0) {
        if (knownAttributes.indexOf(i) === -1) {
          throw new Error("Unknown attribute '" + i + "' in object.");
        }

        // Attributes can have objects as values, for attributes of the attributes,
        // such as inherit. In that case, the value attribute is taken as the value.
        if (typeof options[i] === 'object') {
          if (!('value' in options[i])) {
            throw new Error("Attribute object '" + i + "' needs 'value'.");
          }

          if ('inherit' in options[i] && options[i].inherit) {
            if (inheritableAttributes.indexOf(i) === -1) {
              throw new Error("Unknown inheritable attribute '" + i + "' in object.");
            }

            opts.inheritedAttributes.push(i);
          }

          opts.attributes[i.substring(1)] = options[i].value;
        }
        else {
          opts.attributes[i.substring(1)] = options[i];
        }
      }
      else {
        opts.children[i] = options[i];
      }
    }

    if ('owner' in opts.attributes && opts.attributes.owner !== process.env.USER && opts.attributes.owner !== 'root') {
      throw new Error("Must be run as root if owner differs from you.");
    }

    if (!('path' in opts.attributes)) {
      if (typeof parentAttributes === 'object') {
        opts.attributes.path = parentAttributes.path + File.DIRECTORY_SEPARATOR + opts.attributes.name;
      }
      else {
        opts.attributes.path = '.';
      }
    }

    if (!('type' in opts.attributes)) {
      if ('dest' in opts.attributes) {
        opts.attributes.type = 'l';
      }
      else if (Object.keys(opts.children).length > 0) {
        opts.attributes.type = 'd';
      }
      else {
        opts.attributes.type = '-';
      }
    }
  }

  return opts;
};

/**
 * Converts a formatted, structured object to a directory structure.
 *
 * @param  {object} json
 * @param  {object} options
 */
var json2dir = function(json, options) {
  options = options || {};

  /**
   * Recursive function which recurses through the object and asynchronously
   * creates the directory structure based upon normalized options.
   *
   * @param  {object} json
   * @param  {object} parentAttributes
   */
  var _json2dir = function(json, parentAttributes) {
    if (typeof json === 'object') {
      // Validate and normalize the options into children and attributes.
      var options = normalizeOptions(json, parentAttributes);

      // Create the File object given the set of attributes parsed which
      // represents the file in question.
      var f = new File(options.attributes);

      f.create(function(err) {
        if (err) throw err;

        // For each of the children parsed, call this function in parallel.
        ASYNC.each(Object.keys(options.children), function(name, callback) {
          // normalizeOptions() needs the key of the child object, which is the name.
          options.children[name]['-name'] = name;

          // If there are any inherited attributes of the parent, we need to add
          // them to the child object.
          if (options.inheritedAttributes.length > 0) {
            for (var i in options.inheritedAttributes) {
              options.children[name][options.inheritedAttributes[i]] = { value: options.attributes[options.inheritedAttributes[i].substring(1)], inherit: true };
            }
          }

          // Recurse, given the unnormalized options of the child and normalized
          // attributes of the parent.
          _json2dir(options.children[name], options.attributes);

          // Async has us call callback() to know when this function is done.
          callback();
        }, function(err) {
          if (err) throw err;
        });
      });
    }
  };

  _json2dir(json);
};

json2dir({
  "foo": {},
  "bar": {
    "file.txt": {
      "-content": "some text"
    },
    "a": {
      "b": {
        "c": {
          "d": {
            "e": {
              "f": {
                "example.txt": {
                  "-type": "f"
                }
              }
            }
          }
        }
      }
    }
  },
  "-path": "output"
});

module.exports = {
  json2dir: json2dir
};
<commit_msg>json2dir has callback option. sync version to come (maybe). dir2json started<commit_after>/**
 * @name jsondir
 * @description Convert JSON objects to directories and back again.
 *
 * @author Daniel Imhoff
 */

'use strict';

var ASYNC = require('async');
var FS = require('fs');

var File = require('./File').File;

var knownAttributes = Object.freeze([
  '-name',
  '-type',
  '-path',
  '-mode',
  '-owner',
  '-group',
  '-dest',
  '-content'
]);

var inheritableAttributes = Object.freeze([
  '-mode',
  '-owner',
  '-group'
]);

/**
 * Split up given object into children and valid attributes that are ready for
 * the File constructor.
 *
 * @param  {object} options
 * @param  {object} parentAttributes Normalized attributes of the parent.
 * @return {object}
 */
var normalizeOptions = function(options, parentAttributes) {
  var opts = {
    attributes: {},
    inheritedAttributes: [],
    children: {}
  };

  if (typeof options === 'object') {
    for (var i in options) {
      // If the starting character is a hyphen, the option is an attribute,
      // because having files prepended with a hyphen in Unix is a terrible
      // idea: http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html#dashes
      if (i.indexOf('-') === 0) {
        if (knownAttributes.indexOf(i) === -1) {
          throw new Error("Unknown attribute '" + i + "' in object.");
        }

        // Attributes can have objects as values, for attributes of the attributes,
        // such as inherit. In that case, the value attribute is taken as the value.
        if (typeof options[i] === 'object') {
          if (!('value' in options[i])) {
            throw new Error("Attribute object '" + i + "' needs 'value'.");
          }

          if ('inherit' in options[i] && options[i].inherit) {
            if (inheritableAttributes.indexOf(i) === -1) {
              throw new Error("Unknown inheritable attribute '" + i + "' in object.");
            }

            opts.inheritedAttributes.push(i);
          }

          opts.attributes[i.substring(1)] = options[i].value;
        }
        else {
          opts.attributes[i.substring(1)] = options[i];
        }
      }
      else {
        opts.children[i] = options[i];
      }
    }

    if ('owner' in opts.attributes && opts.attributes.owner !== process.env.USER && opts.attributes.owner !== 'root') {
      throw new Error("Must be run as root if owner differs from you.");
    }

    if (!('path' in opts.attributes)) {
      if (typeof parentAttributes === 'object') {
        opts.attributes.path = parentAttributes.path + File.DIRECTORY_SEPARATOR + opts.attributes.name;
      }
      else {
        opts.attributes.path = '.';
      }
    }

    if (!('type' in opts.attributes)) {
      if ('dest' in opts.attributes) {
        opts.attributes.type = 'l';
      }
      else if (Object.keys(opts.children).length > 0) {
        opts.attributes.type = 'd';
      }
      else {
        opts.attributes.type = '-';
      }
    }
  }

  return opts;
};

/**
 * Converts a formatted, structured object to a directory structure.
 *
 * @param  {object} json
 * @param  {object} options
 * @param  {Function} callback
 */
var json2dir = function(json, options, callback) {
  options = options || {};

  // Keeps track of the number of child keys in the object. When count
  // returns to 0, we know the object has been exhausted.
  var count = 0;

  /**
   * The handler for determining when everything is finished.
   *
   * @param  {Error} err
   */
  var finishCallback = function(err) {
    if (err) callback(err);

    if (count === 0) {
      callback();
    }
  };

  /**
   * Recursive function which recurses through the object and asynchronously
   * creates the directory structure based upon normalized options.
   *
   * @param  {object} json
   * @param  {object} parentAttributes
   */
  var _json2dir = function(json, parentAttributes) {
    if (typeof json === 'object') {
      // Validate and normalize the options into children and attributes.
      var options = normalizeOptions(json, parentAttributes),
          childKeys = Object.keys(options.children);

      // First count the number of children.
      count += childKeys.length;

      // Create the File object given the set of attributes parsed which
      // represents the file in question.
      var f = new File(options.attributes);

      f.create(function(err) {
        if (err) finishCallback(err);

        // When IO is finished for this file, we mark it as done.
        --count;

        // For each of the children parsed, call this function in parallel.
        ASYNC.each(childKeys, function(name, callback) {
          // normalizeOptions() needs the key of the child object, which is the name.
          options.children[name]['-name'] = name;

          // If there are any inherited attributes of the parent, we need to add
          // them to the child object.
          if (options.inheritedAttributes.length > 0) {
            for (var i in options.inheritedAttributes) {
              options.children[name][options.inheritedAttributes[i]] = { value: options.attributes[options.inheritedAttributes[i].substring(1)], inherit: true };
            }
          }

          // Recurse, given the unnormalized options of the child and normalized
          // attributes of the parent.
          _json2dir(options.children[name], options.attributes);

          // Async has us call callback() to know when this function is done.
          callback();
        }, function(err) {
          if (err) finishCallback(err);
          finishCallback();
        });
      });
    }
  };

  _json2dir(json);
};

/**
 * Converts a given directory structure to a formatted, structured object.
 *
 * @param  {string} path
 * @param  {object} options
 * @return {object}
 */
var dir2json = function(path, options) {
  options = options || {};

  var json = {
    "-path": path
  };

  var _dir2json = function(path) {
    FS.readdir(path, function(err, files) {
      if (err) throw err;

//      ASYNC.each(files, function()
    });
  };

  return _dir2json(path);
};

json2dir({
  "a": {
    "a1": {
      "a11": {
        "a111": {
          "a1111": {},
          "a1112": {},
          "a1113": {},
          "a1114": {},
        },
        "a112": {},
        "a113": {
          "a1131": {},
          "a1132": {},
          "a1133": {
            "a11331": {},
            "a11332": {}
          }
        }
      }
    },
    "a2": {
      "a21": {}
    }
  },
  "b": {},
  "c": {},
  "d": {
    "d1": {},
    "d2": {
      "d21": {},
      "d22": {}
    }
  },
  "e": {},
  "f": {},
  "g": {},
  "h": {},
  "i": {},
  "j": {},
  "k": {
    "k1": {},
    "k2": {
      "k21": {
        "k22": {},
        "k23": {
          "k231": {}
        }
      }
    }
  },
  "-path": "output"
}, {}, function(err) {
  if (err) throw err;
});

module.exports = {
  json2dir: json2dir,
  dir2json: dir2json
};
<|endoftext|>


<commit_before>function getUrlVars() {
    var vars = {};
    window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
        vars[key] = value;
    });
    return vars;
}
function showUserData(data) {

    alert("showUserData"); return;

    $(document).attr('title', 'Show Product #' + data.ProductCode);

    $('#ProductCode').attr('value', data.ProductCode);
    $('#ProductDescription').attr('value', data.ProductDescription);
    $('#UnitPrice').attr('value', data.UnitPrice);
}

function showEditableUserData(data) {

    alert("showEditableUserData"); return;

    $('input').filter(function (index) {
        return $(this).attr('id') !== 'ProductCode';
    }).removeAttr('readonly').attr('method', 'post').prop('required', true);

    $('div._header').text('Edit product');

    var submissionCallback = function (event) {
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;

        var jsonObj = {
            ProductCode: $('#ProductCode').val(),
            description: $("#ProductDescription").val(),
            unit_price: $("#UnitPrice").val()
        }

        var requestStr = JSON.stringify(jsonObj);

        $.ajax({
            url: "api/updateProduct.php",
            type: "POST",
            data: {
                product: requestStr
            },
            dataType: "JSON",
            success: function (jsonStr) {
                alert(JSON.stringify(jsonStr));
            }
        });
    };

    showProductData(data);

    $('form').attr('method', 'post').attr('action', 'api/updateProduct.php')
        .append('<input type="submit" id="submit" value="Submit">').submit(submissionCallback);

    $('#ProductDescription').focus();
}

function showBlankUserData(data) {

    alert("showBlankUserData"); return;

    $('div._product_code').remove();

    $('input').removeAttr('readonly').prop('required', true).val('');

    $('#ProductDescription').focus();

    var submissionCallback = function (event) {
        // prevent the default form behaviour
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;

        var jsonObj = {
            ProductCode: "",
            description: $("#ProductDescription").val(),
            unit_price: $("#UnitPrice").val()
        }

        var requestStr = JSON.stringify(jsonObj);

        $.ajax({
            url: "api/updateProduct.php",
            type: "POST",
            data: {
                product: requestStr
            },
            dataType: "JSON",
            success: function (jsonObj) {
                $.ajax({
                    url: "showProduct.php",
                    type: "GET",
                    data: {
                        ProductId: jsonObj
                    },
                    dataType: "text",
                    success: function (jsonObj) {
                    }
                });
            }
        });
    };

    $('form')
        .append('<input id="submit" type="submit" value="Submit">').submit(submissionCallback);

    $('div._header').text('Create new product');
}

function loadUser() {
    var urlVars = getUrlVars();
    var action = urlVars['action'];

    if (action !== 'create') {
        var id = urlVars['UserId'];
        if (id == undefined) {
            alert('No user id was detected');
            return;
        }
    }

    if (action == undefined)
        action = 'show';
    else if (action != 'show' && action != 'create' && action != 'edit')
        return;

    $.ajax({
        url: "api/user_is_admin.php",
        success: function (is_admin) {
            is_admin = JSON.parse(is_admin);

            if (!is_admin) {
                $.ajax({
                    url: "api/get_logged_id.php",
                    success: function(logged_id) {
                        logged_id = JSON.parse(logged_id);

                        var onSuccess = null;

                        if (id === logged_id) {
                            switch(action) {
                                case 'edit': {
                                    onSuccess = showEditableUserData;
                                    break;
                                }
                                case 'show' : {
                                    onSuccess = showUserData;
                                }
                            }
                        }

                        if (onSuccess == null)
                            return;

                        $.getJSON("api/getUser.php", {
                            UserId: decodeURI(id)
                        }).done(onSuccess);
                    }
                });
            } else {
                var onSuccess = null;
                switch(action) {
                    case 'edit': {
                        onSuccess = is_admin ? showEditableUserData : null;
                        break;
                    }
                    case 'create': {
                        onSuccess = is_admin ? showBlankUserData : null;
                        break;
                    }
                    case 'show' : {
                        onSuccess = showUserData;
                        break;
                    }
                }

                if (onSuccess == null)
                    return;

                $.getJSON("api/getUser.php", {
                    UserId: decodeURI(id)
                }).done(onSuccess);
            }
        }
    })
}<commit_msg>Update showUser.js.<commit_after>function getUrlVars() {
    var vars = {};
    window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
        vars[key] = value;
    });
    return vars;
}

function showUserData(data) {
    $('._header').text('Show User');
    $('#Username').attr('value', data.Username);
    loadRoles($('#role'), data.Role);
    $('#role').attr('disabled', true);
}

function loadRoles(target, toBeSelected) {
    $.getJSON("api/getAllRoles.php", {
    }).done(function (data) {
            for (var i = 0; i < data.length; i++) {
                var option = document.createElement("option");
                option.value = data[i].id;
                option.text = data[i].name;
                target.append(option);

                if (option.text == toBeSelected)
                    option.selected = true;
            }
        });
}

function showAdministratorEditableUserData(data) {
    $('._header').text('Edit User : Administrator');
    $('#Username').attr('value', data.Username);
    loadRoles($('#role'), data.Role);

    var passwordField = '
Password:<input type="password" id="PasswordField" required></input>
'
    $('form').append(passwordField);

    var checkBox = '<input type="checkbox" id="ChangePassword"> Change password </input>'
    $('form').append(checkBox);
    $('#ChangePassword').click(function() {
        if ($(this).is(':checked'))
            $('#Password').show().attr('disabled', false);
        else
            $('#Password').hide().attr('disabled', true);
    });

    var submitButton = '<input type="submit" id="submit" value="Submit"></input>';
    $('form').append(submitButton).submit(function(event) {
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;

        // ajax request
    });
}

function showEditableUserData(data) {
    $('._header').text('Edit User');
    $('#Username').attr('value', data.Username);
    loadRoles($('#role'), data.Role);
    $('#role').attr('disabled', true);

    var passwordField = '
Password:<input type="password" id="PasswordField" required></input>
'
    $('form').append(passwordField);

    var checkBox = '<input type="checkbox" id="ChangePassword"> Change password </input>'
    $('form').append(checkBox);
    $('#ChangePassword').click(function() {
        if ($(this).is(':checked'))
            $('#Password').show().attr('disabled', false);
        else
            $('#Password').hide().disable();
    });

    var submitButton = '<input type="submit" id="submit" value="Submit"></input>';
    $('form').append(submitButton).submit(function(event) {
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;

        // ajax request
    });
}

function showBlankUserData(data) {
    $('._header').text('Create User');
    $('#Username').attr('required', true).attr('value', '').attr('readonly', false);

    loadRoles($('#role'), '');

    var passwordField = '
Password:<input type="password" id="PasswordField" required></input>
'
    //$('form').append(passwordField);
    $('form ._user_role').before(passwordField);

    var submitButton = '<input type="submit" id="submit" value="Submit"></input>';
    $('form').append(submitButton).submit(function(event) {
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;

        var jsonObj = {
            username : $('#Username').val(),
            password : $('#passwordField').val(),
            role_id : $('#role').find(':selected').val()
        };

        $.ajax({
            url: "api/updateUser.php",
            type: "POST",
            data: {
                user: JSON.stringify(jsonObj)
            },
            dataType: "JSON",
            success: function (jsonObj) {
                alert('success');

            }
        });
    });

}

function loadUser() {
    var urlVars = getUrlVars();
    var action = urlVars['action'];

    if (action !== 'create') {
        var id = urlVars['UserId'];
        if (id == undefined) {
            alert('No user id was detected');
            return;
        }
    }

    if (action == undefined)
        action = 'show';
    else if (action != 'show' && action != 'create' && action != 'edit')
        return;

    $.ajax({
        url: "api/user_is_admin.php",
        success: function (is_admin) {
            is_admin = JSON.parse(is_admin);

            if (!is_admin) {
                $.ajax({
                    url: "api/get_logged_id.php",
                    success: function(logged_id) {
                        logged_id = JSON.parse(logged_id);

                        var onSuccess = null;

                        if (id === logged_id) {
                            switch(action) {
                                case 'edit': {
                                    onSuccess = showEditableUserData;
                                    break;
                                }
                                case 'show' : {
                                    onSuccess = showUserData;
                                }
                            }
                        }

                        if (onSuccess == null)
                            return;

                        $.getJSON("api/getUser.php", {
                            UserId: decodeURI(id)
                        }).done(onSuccess);
                    }
                });
            } else {
                var onSuccess = null;
                switch(action) {
                    case 'edit': {
                        onSuccess = is_admin ? showAdministratorEditableUserData : null;
                        break;
                    }
                    case 'create': {
                        onSuccess = is_admin ? showBlankUserData : null;
                        break;
                    }
                    case 'show' : {
                        onSuccess = showUserData;
                        break;
                    }
                }

                if (onSuccess == null)
                    return;

                $.getJSON("api/getUser.php", {
                    UserId: decodeURI(id)
                }).done(onSuccess);
            }
        }
    })
}<|endoftext|>


<commit_before>require('dotenv').config({path: '../../.env' });

var express    = require('express'),
    app        = express(),
    exphbs     = require('express-handlebars'),
    hbs        = require('hbs'),
    fs         = require('fs'),
    bodyParser = require('body-parser')

app.engine('hbs', exphbs({
  defaultLayout:  'main',
  partialsDir:    __dirname + '/views/partials',
  layoutsDir:     __dirname + '/views/layouts',
  extname:        '.hbs'
}));

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}));

app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');

app.use(express.static(__dirname + '/public'));

require('./models/db');
require('./models/user');

app.use('/', require('./controllers/home'));

//Start server listening on port 3000
var server = app.listen(process.env.PORT || 3000, function() {
  console.log('Server listening at http://localhost:' + server.address().port);
});
<commit_msg>require .env at top of server file<commit_after>require('dotenv').config();

var express    = require('express'),
    app        = express(),
    exphbs     = require('express-handlebars'),
    hbs        = require('hbs'),
    fs         = require('fs'),
    bodyParser = require('body-parser')

app.engine('hbs', exphbs({
  defaultLayout:  'main',
  partialsDir:    __dirname + '/views/partials',
  layoutsDir:     __dirname + '/views/layouts',
  extname:        '.hbs'
}));

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}));

app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');

app.use(express.static(__dirname + '/public'));

require('./models/db');
require('./models/user');

app.use('/', require('./controllers/home'));

//Start server listening on port 3000
var server = app.listen(process.env.PORT || 3000, function() {
  console.log('Server listening at http://localhost:' + server.address().port);
});
<|endoftext|>


<commit_before>(function ($) {
    $.fn.sideshow = function (options) {
        $.extend($.fn.sideshow.settings, $.fn.sideshow.defaults, options);

        return this.each(function () {
            $.fn.sideshow.init(this);
        });
    };

    $.fn.sideshow.settings = {},
    $.fn.sideshow.slides = [];
    $.fn.sideshow.current = 0;

    $.fn.sideshow.defaults = {
        duration: 0,
        help: true,
        bindings: {
            37: "prev", // left
            38: "prev", // up
            75: "prev", // k
            39: "next", // right
            40: "next", // down
            74: "next", // j
            32: "next", // space
            72: "help", // h
        },
    };

    $.fn.sideshow.init = function (element) {
        $.fn.sideshow.root = root = $(element);
        $.fn.sideshow.header = header = root.find("> header");
        $.fn.sideshow.footer = footer = root.find("> footer");
        var slides = $.fn.sideshow.slides;

        /* Hide header, footer and (slides > 1). */
        root.addClass("slides").children("section").each(function () {
            slides.push($(this));
        });
        $.each(slides.slice(1), function () {
            $(this).hide();
        });
        $.fn.sideshow.gotohash();

        var $document = $(document);
        $document.keydown(function (event) {
            var key = (event.keyCode ? event.keyCode : event.which);
            var fnname = $.fn.sideshow.settings.bindings[key],
                fn = $.fn.sideshow[fnname];
            if (fn) {
                fn();
                return false;
            };
        });

        if ("hashchange" in $(window)) {
            $(window).hashchange(function () {
                $.fn.sideshow.gotohash();
            });
        };

        if ($.fn.sideshow.settings.help)
            $.fn.sideshow.flash("This webpage is a presentation! Press h for help.");
    };

    $.fn.sideshow.goto = function (index) {
        var slides = $.fn.sideshow.slides,
            current = $.fn.sideshow.current,
            settings = $.fn.sideshow.settings;
        if (index >= slides.length || index < 0 || (index > 1 && index == current))
            return;
        $.fn.sideshow.hide(slides[current]);
        $.fn.sideshow.show(slides[index]);
        $.fn.sideshow.current = index;
        location.hash = "#slide" + (index + 1);
    };

    $.fn.sideshow.next = function () {
        $.fn.sideshow.goto($.fn.sideshow.current + 1);
    }

    $.fn.sideshow.prev = function () {
        $.fn.sideshow.goto($.fn.sideshow.current - 1);
    }

    $.fn.sideshow.show = function (slide) {
        slide.show($.fn.sideshow.settings.duration);
    };

    $.fn.sideshow.hide = function (slide) {
        slide.hide($.fn.sideshow.settings.duration);
    };

    $.fn.sideshow.gotohash = function (hash) {
        var hash = hash;
        if (typeof hash == "undefined")
            hash = location.hash || "#slide1";
        var slide = hash.replace(/^#slide/, "");
        $.fn.sideshow.goto(parseInt(slide, 10) - 1);
    };

    $.fn.sideshow.flash = function (message, duration) {
        var elem = $("#flash");
        var duration = duration >= 0 || 5000;
        if (elem.length != 0) {
            elem.remove();
        }

        $('
' + message + '
')
            .appendTo("body")
            .show()
            .fadeOut(duration, function () { $(this).remove(); });
    };

    $.fn.sideshow.help = function () {
        if (! $.fn.sideshow.settings.help)
            return;
        $.fn.sideshow.flash(
                "Keys: " +
                "↑, ←, k or space to go forward; " +
                "↓, →, or j to go backward.");
    };
})(jQuery);
<commit_msg>Removing trailing comma<commit_after>(function ($) {
    $.fn.sideshow = function (options) {
        $.extend($.fn.sideshow.settings, $.fn.sideshow.defaults, options);

        return this.each(function () {
            $.fn.sideshow.init(this);
        });
    };

    $.fn.sideshow.settings = {},
    $.fn.sideshow.slides = [];
    $.fn.sideshow.current = 0;

    $.fn.sideshow.defaults = {
        duration: 0,
        help: true,
        bindings: {
            37: "prev", // left
            38: "prev", // up
            75: "prev", // k
            39: "next", // right
            40: "next", // down
            74: "next", // j
            32: "next", // space
            72: "help", // h
        }
    };

    $.fn.sideshow.init = function (element) {
        $.fn.sideshow.root = root = $(element);
        $.fn.sideshow.header = header = root.find("> header");
        $.fn.sideshow.footer = footer = root.find("> footer");
        var slides = $.fn.sideshow.slides;

        /* Hide header, footer and (slides > 1). */
        root.addClass("slides").children("section").each(function () {
            slides.push($(this));
        });
        $.each(slides.slice(1), function () {
            $(this).hide();
        });
        $.fn.sideshow.gotohash();

        var $document = $(document);
        $document.keydown(function (event) {
            var key = (event.keyCode ? event.keyCode : event.which);
            var fnname = $.fn.sideshow.settings.bindings[key],
                fn = $.fn.sideshow[fnname];
            if (fn) {
                fn();
                return false;
            };
        });

        if ("hashchange" in $(window)) {
            $(window).hashchange(function () {
                $.fn.sideshow.gotohash();
            });
        };

        if ($.fn.sideshow.settings.help)
            $.fn.sideshow.flash("This webpage is a presentation! Press h for help.");
    };

    $.fn.sideshow.goto = function (index) {
        var slides = $.fn.sideshow.slides,
            current = $.fn.sideshow.current,
            settings = $.fn.sideshow.settings;
        if (index >= slides.length || index < 0 || (index > 1 && index == current))
            return;
        $.fn.sideshow.hide(slides[current]);
        $.fn.sideshow.show(slides[index]);
        $.fn.sideshow.current = index;
        location.hash = "#slide" + (index + 1);
    };

    $.fn.sideshow.next = function () {
        $.fn.sideshow.goto($.fn.sideshow.current + 1);
    }

    $.fn.sideshow.prev = function () {
        $.fn.sideshow.goto($.fn.sideshow.current - 1);
    }

    $.fn.sideshow.show = function (slide) {
        slide.show($.fn.sideshow.settings.duration);
    };

    $.fn.sideshow.hide = function (slide) {
        slide.hide($.fn.sideshow.settings.duration);
    };

    $.fn.sideshow.gotohash = function (hash) {
        var hash = hash;
        if (typeof hash == "undefined")
            hash = location.hash || "#slide1";
        var slide = hash.replace(/^#slide/, "");
        $.fn.sideshow.goto(parseInt(slide, 10) - 1);
    };

    $.fn.sideshow.flash = function (message, duration) {
        var elem = $("#flash");
        var duration = duration >= 0 || 5000;
        if (elem.length != 0) {
            elem.remove();
        }

        $('
' + message + '
')
            .appendTo("body")
            .show()
            .fadeOut(duration, function () { $(this).remove(); });
    };

    $.fn.sideshow.help = function () {
        if (! $.fn.sideshow.settings.help)
            return;
        $.fn.sideshow.flash(
                "Keys: " +
                "↑, ←, k or space to go forward; " +
                "↓, →, or j to go backward.");
    };
})(jQuery);
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import App from './components/app'
import store from './store'
import { AppContainer } from 'react-hot-loader'

ReactDOM.render(
  <Provider store={ store }>
    <App />
  </Provider>,
  document.getElementById('root')
)

if (module.hot) {
  module.hot.accept('./components/app', () => {
    ReactDOM.render(
      <Provider store={ store }>
        <AppContainer component = {require('./components/app').default} />
      </Provider>,
      document.getElementById('root')
    )
  })
}
<commit_msg>Updates for hot reloading.<commit_after>import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import App from './components/app'
import store from './store'
import { AppContainer } from 'react-hot-loader'

ReactDOM.render(
  <Provider store={ store }>
    <AppContainer>
      <App />
    </AppContainer>
  </Provider>,
  document.getElementById('root')
)

if (module.hot) {
  module.hot.accept('./components/app', () => {
    ReactDOM.render(
      <Provider store={ store }>
        <AppContainer component = {require('./components/app').default} />
      </Provider>,
      document.getElementById('root')
    )
  })
}
<|endoftext|>


<commit_before>(function() {
    "use strict";
    var ascClass = "order-asc";
    var descClass = "order-desc";

    /**
     * setEventToAllObject
     * 引数のエレメント全てに特定のイベントで発火する関数を定義する
     *
     * @param {HTMLElement} elements - 対象のエレメントの配列
     * @param {String} event - 対象のイベント
     * @param {Function} func - 発火する関数
     * @return なし
     */
    function setEventToAllObject(elements, event, func) {
        Object.keys(elements).forEach(function(key) {
            elements[key].addEventListener(event, func, false);
        });
    }

    /**
     * getTargetTable
     * 対象のテーブルのエレメントを取得
     *
     * @param {HTMLElement} elem - クリックしたth要素のエレメント
     * @return {HTMLElement} table - クリックした要素の属するテーブル
     */
    function getTargetTable(elem) {
        //操作対象のテーブルを特定する
        //TABLEタグが見つかるまでelemの親要素をたどる
        var closest = function(th) {
            var parent = th.parentNode;
            if (parent.tagName.toUpperCase() === "TABLE") {
                return parent;
            }
            return closest(parent);
        };
        return closest(elem);
    }

    /**
     * getTableData
     * テーブルのデータ取得
     *
     * @param {HTMLElement} tableElem - テーブル
     * @return {Array} data - tableElemのデータ配列
     */
    function getTableData(tableElem) {
        var data = [];
        //1行目を飛ばす
        for (var i = 1, l = tableElem.length; i < l; i++) {
            for (var j = 0, m = tableElem[i].cells.length; j < m; j++) {
                if (typeof data[i] === "undefined") {
                    data[i] = {};
                    data[i]["key"] = i; //ソート用のキー設定
                }
                data[i][j] = tableElem[i].cells[j].innerText;
            }
        }
        return data;
    }

    /**
     * sortTableData
     * テーブルのデータをソート
     *
     * @param {Array} tableData - tableElemのデータ配列
     * @param {Int} colNo - ソートする列番号
     * @param {Int} sortOrder - ソート順
     * @return {Array} tableData - ソート後配列
     */
    function sortTableData(tableData, colNo, sortOrder) {
        //クリックした列番号取得
        //ソート処理
        tableData.sort(function(a, b) {
                    if (a[colNo] < b[colNo]) {
                        return -1 * sortOrder;
                    } else if (a[colNo] > b[colNo]) {
                        return sortOrder;
                    }
                    return 0;
                });
        return tableData;
    }

    /**
     * rewriteTableHTML
     * テーブルのHTMLを書き換え
     *
     * @param {HTMLElement} table - クリックした要素の属するテーブル
     * @param {Array} tableData - tableElemのデータ配列
     * @return なし
     */
    function rewriteTableHTML(table, tableData) {
        //ソート後のHTMLを構築して書き換え
        var html = "";
        tableData.forEach(function(x) {
            html += table.querySelectorAll("tr")[x["key"]].outerHTML;
        });
        table.querySelector("tbody").innerHTML = html;
    }

    /**
     * removeTHClass
     * TH要素のクラスを削除する
     *
     * @param {HTMLElement} table - クリックした要素の属するテーブル
     * @param {Int} sortOrder - ソート順
     * @return なし
     */
    function removeTHClass(table, tableData) {
        //テーブルの昇順降順Classをクリア・設定する
        var tableElem = table.querySelectorAll("thead th");
        Object.keys(tableElem).forEach(function(key) {
            tableElem[key].classList.remove(descClass);
            tableElem[key].classList.remove(ascClass);
        });
    }

    /**
     * setTHClass
     * TH要素のクラスをリセットして、ソート対象のみ書き換え
     *
     * @param {HTMLElement} elem - クリックされたエレメント
     * @param {Int} sortOrder - ソート順
     * @return なし
     */
    function setTHClass(elem, sortOrder) {
        if (sortOrder === 1) {
            elem.classList.add(ascClass);
        }else {
            elem.classList.add(descClass);
        }
    }

    /**
     * sortEvent
     * ソート処理イベント
     *
     * @param {HTMLElement} elem - クリックされたエレメント
     * @return {boolean} true
     */
    function sortEvent(elem) {

        //操作対象のテーブルを特定する
        var table = getTargetTable(elem);
        if (!table) {
            return;
        }

        //テーブルデータ取得
        var tableData = getTableData(table.querySelectorAll("tr"));

        //ソート順取得
        //"order-asc"クラスを持っていなければ昇順・それ以外なら降順
        var sortOrder = !elem.classList.contains(ascClass) ? 1 : -1;

        //データソート処理
        tableData = sortTableData(tableData, elem.cellIndex, sortOrder);

        //ソート後のHTMLを構築して書き換え
        rewriteTableHTML(table, tableData);

        //テーブルの昇順降順Classをクリア・設定する
        removeTHClass(table, tableData);
        setTHClass(elem, sortOrder);
    }

    //ロード時にソート用イベントをバインドする
    window.addEventListener("load", function() {
        var elem = document.querySelectorAll("table.sortable thead th");
        setEventToAllObject(elem, "click", function(e) {sortEvent(e.target); });
    }, false);

})();
<commit_msg>config設定追加 ソート対象のテーブルを選べるように修正<commit_after>var sorTablejs = function (setting) {
    "use strict";

    //default
    var config = {
        //引数がある場合引数のクエリ、なければsortableクラスをソート対象に
        targetTable: "table.sortable",
        cssAsc: "order-asc",
        cssDesc: "order-desc",
        cssBg: "sortable",
        selectorHeaders: "thead th"
    };

    //クエリ文字列のときは対象をクエリ文字列に
    if(setting instanceof String || typeof setting === "string"){
        config.targetTable = setting;
    }else if(typeof setting === "object"){
    //オブジェクトの場合は設定値を上書き
        Object.keys(setting).forEach(function(key) {
            config[key] = setting[key];
        });
    }

    /** Unimplemented
        cssHeader: "header",
        cssChildRow: "expand-child",
        sortInitialOrder: "asc",
        sortMultiSortKey: "shiftKey",
        sortForce: null,
        sortAppend: null,
        sortLocaleCompare: true,
        textExtraction: "simple",
        parsers: {},
        widgets: [],
        widgetZebra: {
            css: ["even", "odd"]
        },
        headers: {},
        widthFixed: false,
        cancelSelection: true,
        sortList: [],
        headerList: [],
        dateFormat: "us",
        decimal: '/\.|\,/g',
        onRenderHeader: null,
    **/

    /**
     * setEventToAllObject
     * 引数のエレメント全てに特定のイベントで発火する関数を定義する
     *
     * @param {HTMLElement} elements - 対象のエレメントの配列
     * @param {String} event - 対象のイベント
     * @param {Function} func - 発火する関数
     * @return なし
     */
    function setEventToAllObject(elements, event, func) {
        Object.keys(elements).forEach(function(key) {
            elements[key].addEventListener(event, func, false);
        });
    }

    /**
     * getTableElement
     * 対象のテーブルのエレメントを取得
     *
     * @param {HTMLElement} elem - クリックしたth要素のエレメント
     * @return {HTMLElement} table - クリックした要素の属するテーブル
     */
    function getTableElement(elem) {
        //操作対象のテーブルを特定する
        //TABLEタグが見つかるまでelemの親要素をたどる
        var closest = function(th) {
            var parent = th.parentNode;
            if (parent.tagName.toUpperCase() === "TABLE") {
                return parent;
            }
            return closest(parent);
        };
        return closest(elem);
    }

    /**
     * getTableData
     * テーブルのデータ取得
     *
     * @param {HTMLElement} tableElem - テーブル
     * @return {Array} data - tableElemのデータ配列
     */
    function getTableData(tableElem) {
        var data = [];
        //1行目を飛ばす
        for (var i = 1, l = tableElem.length; i < l; i++) {
            for (var j = 0, m = tableElem[i].cells.length; j < m; j++) {
                if (typeof data[i] === "undefined") {
                    data[i] = {};
                    data[i]["key"] = i; //ソート用のキー設定
                }
                data[i][j] = tableElem[i].cells[j].innerText;
            }
        }
        return data;
    }

    /**
     * sortTableData
     * テーブルのデータをソート
     *
     * @param {Array} tableData - tableElemのデータ配列
     * @param {Int} colNo - ソートする列番号
     * @param {Int} sortOrder - ソート順
     * @return {Array} tableData - ソート後配列
     */
    function sortTableData(tableData, colNo, sortOrder) {
        //クリックした列番号取得
        //ソート処理
        tableData.sort(function(a, b) {
                    if (a[colNo] < b[colNo]) {
                        return -1 * sortOrder;
                    } else if (a[colNo] > b[colNo]) {
                        return sortOrder;
                    }
                    return 0;
                });
        return tableData;
    }

    /**
     * rewriteTableHTML
     * テーブルのHTMLを書き換え
     *
     * @param {HTMLElement} table - クリックした要素の属するテーブル
     * @param {Array} tableData - tableElemのデータ配列
     * @return なし
     */
    function rewriteTableHTML(table, tableData) {
        //ソート後のHTMLを構築して書き換え
        var html = "";
        tableData.forEach(function(x) {
            html += table.querySelectorAll("tr")[x["key"]].outerHTML;
        });
        table.querySelector("tbody").innerHTML = html;
    }

    /**
     * removeTHClass
     * TH要素のクラスを削除する
     *
     * @param {HTMLElement} table - クリックした要素の属するテーブル
     * @param {Int} sortOrder - ソート順
     * @return なし
     */
    function removeTHClass(table, tableData) {
        //テーブルの昇順降順Classをクリア・設定する
        var tableElem = table.querySelectorAll(config.selectorHeaders);
        Object.keys(tableElem).forEach(function(key) {
            tableElem[key].classList.remove(config.cssDesc);
            tableElem[key].classList.remove(config.cssAsc);
        });
    }

    /**
     * setTHClass
     * TH要素のクラスをリセットして、ソート対象のみ書き換え
     *
     * @param {HTMLElement} elem - クリックされたエレメント
     * @param {Int} sortOrder - ソート順
     * @return なし
     */
    function setTHClass(elem, sortOrder) {
        if (sortOrder === 1) {
            elem.classList.add(config.cssAsc);
        }else {
            elem.classList.add(config.cssDesc);
        }
    }

    /**
     * sortEvent
     * ソート処理イベント
     *
     * @param {HTMLElement} elem - クリックされたエレメント
     * @return {boolean} true
     */
    function sortEvent(elem) {

        //操作対象のテーブルを特定する
        var table = getTableElement(elem);
        if (!table) {
            return;
        }

        //テーブルデータ取得
        var tableData = getTableData(table.querySelectorAll("tr"));

        //ソート順取得
        //昇順クラスを持っていなければ昇順・それ以外なら降順
        var sortOrder = !elem.classList.contains(config.cssAsc) ? 1 : -1;

        //データソート処理
        tableData = sortTableData(tableData, elem.cellIndex, sortOrder);

        //ソート後のHTMLを構築して書き換え
        rewriteTableHTML(table, tableData);

        //テーブルの昇順降順Classをクリア・設定する
        removeTHClass(table, tableData);
        setTHClass(elem, sortOrder);
    }

    //ロード時にソート用イベントをバインドする
    window.addEventListener("load", function() {
        var elem = document.querySelector(config.targetTable).querySelectorAll(config.selectorHeaders);
        //カーソル表示用CSS追加
        document.querySelector(config.targetTable).classList.add(config.cssBg);
        setEventToAllObject(elem, "click", function(e) {sortEvent(e.target); });
    }, false);

    return this;
};

sorTablejs();
//sorTablejs("table#sortable");
//sorTablejs({targetTable: "table#sortable"});
<|endoftext|>


<commit_before>#!/usr/bin/env node
var argv = process.argv.splice(2)
var log = require('./helpers/log.js')
var whitelist = ['build', 'run', 'test', 'lint', 'setup']

if (argv.length === 0 || argv[0] === 'help') {
  console.log('abc [command]\n\nCommands:')
  console.log('  build            Compiles the source files from src/ into a build/ directory. ')
  console.log('  run src/file.js  Runs a specified file.')
  console.log('  test             Runs the test files in the tests/ directory.')
  console.log('  lint             Checks if your code is consistent and follows best practices. ')
  console.log('  setup            Creates the directories and files for the whole project to run.')
  console.log('  help             This help page you are looking at!')
  process.exit(0)
}

if (whitelist.indexOf(argv[0]) === -1) {
  log.error('Command `' + argv[0] + '` does not exist')
  process.exit(1)
}

var callback = require('./' + argv[0] + '.js')
callback.apply(null, argv.splice(1))
<commit_msg>Remove whitespace & use same order as in readme<commit_after>#!/usr/bin/env node
var argv = process.argv.splice(2)
var log = require('./helpers/log.js')
var whitelist = ['build', 'run', 'test', 'lint', 'setup']

if (argv.length === 0 || argv[0] === 'help') {
  console.log('abc [command]')
  console.log('')
  console.log('Commands:')
  console.log('  setup            Creates the directories and files for the whole project to run.')
  console.log('  build            Compiles the source files from src/ into a build/ directory.')
  console.log('  test             Runs the test files in the tests/ directory.')
  console.log('  lint             Checks if your code is consistent and follows best practices.')
  console.log('  run src/file.js  Runs a specified file.')
  console.log('  help             This help page you are looking at!')
  process.exit(0)
}

if (whitelist.indexOf(argv[0]) === -1) {
  log.error('Command `' + argv[0] + '` does not exist')
  process.exit(1)
}

var callback = require('./' + argv[0] + '.js')
callback.apply(null, argv.splice(1))
<|endoftext|>


<commit_before>
/* Define global variables */
//spacing definitions
var initX = 0; //px
var initY = 0; //px
var moveOneUnit = 100; //px
//size of gameboard (gameSize x gameSize)
var gameSize = 5;
//size of innerboard (goalSize x goalSize)
var goalSize = gameSize - 2; //a border of block (1 block thick)
//maximum number of the same color
var maxNumOfColors = gameSize-1;
//gameboard
var board;
//goal board to match to
var myGoalBoard;
//colors for blocks
var colors = ['blue','lime','darkviolet','red','yellow','hotpink']
//['#0000FF','#FF0000','#00FF00','#FF00FF','#FFFF00','DarkOrchid']

//constructor for block
function block(x,y,c) {
    this.posX = x;  //int
    this.posY = y;  //int
    this.color = c; //hex
    this.isBlank=false;
}

//constructor for gameboard
function gameboard(n) {
    this.gameSize = gameSize; //game grid size
    this.goalSize = goalSize; //goal grid size
    this.blocks = {};  //positions of blocks (block objects)
    this.blank;        //position of the blank block
}

/* Check if game has been won
 * Input: goalboard object, gameboard object
 * Output: Boolean
 */
function gameWon(goalBoard,board) {
    //get inner part of board
    var innerBoard = {}; var x; var y;
    //get thickness of the border (number of blocks)
    var borderSize = (gameSize-goalSize)/2 //should always be an integer
    //go over each part of the inner board
    //note we are ignoring the border completely
    for(x=borderSize; x<=board.goalSize; x++) {
        for(y=borderSize; y<=board.goalSize; y++) {
            innerBoard[x+'_'+y] = board.blocks[x+'_'+y];
        }
    }
    //check if any inner board and goal board blocks don't match
    for(b in innerBoard) {//b in innerBoard)
        if (innerBoard[b].color !== myGoalBoard[b].color)
            return false;
    }
    //game won since we never broke out of the loop
    return true;
}

/* Create goal for inner board
 * Input: none
 * Output: goalBoard object with the size of goalSize-by-goalSize
 */
function createGoalBoard(){
    //keep count of how many times a color was used (initialized to 0)
    var colorCounts = Array.apply(null, new Array(colors.length))
                           .map(Number.prototype.valueOf,0);
    var x; var y;
    var goalBoard = Array(goalSize*goalSize);
    //get thickness of the border (number of blocks)
    var borderSize = (gameSize-goalSize)/2; //should always be an integer
    //go over the goal board using the absolute position in the gameboard
    for(x=borderSize; x<(board.goalSize+borderSize); x++) {
        for(y=borderSize; y<(board.goalSize+borderSize); y++) {
            //randomly get a color
            var cn = Math.floor((Math.random() * colors.length));
            //check that the color hasn't been maxed out
            //not very efficient but should be no problem with small games
            while( colorCounts[cn] >= maxNumOfColors ) {
                //since color was maxed out, try randomly picking again
                cn = Math.floor((Math.random() * colors.length));
            }
            //color is usable so count it and assign it to new block
            colorCounts[cn] += 1;
            var blockColor = colors[cn];
            goalBoard[x+'_'+y] = new block(x,y,blockColor);
        }
    }
    return goalBoard;
}

//start game setup, return gameboard
function initGame(n) {
    //initiate gameboard
    var myBoard = new gameboard(n);
    //array of colors for blocks
    //['blue','red','green','purple','yellow']
    //color counts
    var colorCounts = Array.apply(null, new Array(colors.length))
                           .map(Number.prototype.valueOf,0);
    var max = 4;
    //construct board of blocks
    var x; var y;
    for(x=0; x<n; x++) {
        for(y=0; y<n; y++) {
            if(y===0 && x===n-1) { //top right
                tempBlock = new block(x,y,'white');
                tempBlock.isBlank = true;
                myBoard.blank = tempBlock;
            }
            else {
                //get a number (corresponding to color) randomly up to max number
                var cn = Math.floor((Math.random() * colors.length));
                while( colorCounts[cn] >= max ) {
                    cn = Math.floor((Math.random() * colors.length));
                }
                colorCounts[cn] += 1;
                var blockColor = colors[cn];
                tempBlock = new block(x,y,blockColor);//colors[(x+y)%6]);
            }
            var keyStr = x+'_'+y;
            myBoard.blocks[keyStr] = tempBlock;
        }
    }
    return myBoard;
}

function displayGame() {
    //
    var gameboardDiv = document.getElementById('gameboard');
    //set style for gameboard
    board = initGame(gameSize);
    //create goal board
    myGoalBoard = createGoalBoard();
    var goalDiv = document.getElementById("goal");
    var str = ''; var x; var y; var count=0;
    for(y=1; y<(4); y++) {
        for(x=1; x<(4); x++) {
            if (count%3 == 0)
                str += '
';
            str += "<float style='border-style:solid;border-width:1px;"
                +  "background:"+myGoalBoard[x+'_'+y].color+";'>"
                +  "&nbsp &nbsp &nbsp" + '</float>';
            count++;
        }
    }
    goalDiv.innerHTML = str;

    //square border thickness
    var squareThick = 1;
    //create inner board's  height and width be a square (not including the edge)
    var innerHeight = moveOneUnit*(gameSize-2);
    var innerWidth  = moveOneUnit*(gameSize-2);
    //inner board thickness
    var innerThick = 8;
    //inner board position (one block in)
    var innerPosX = initX + moveOneUnit-innerThick;
    var innerPosY = initY + moveOneUnit-innerThick;
    //one block into board
    gameboardDiv.innerHTML = "<div id='innerBoard' "
                           + "style='height:"+innerHeight+"px;width:"+innerWidth+"px;"
                           + "border-style:solid;border-color:black;"
                           + "border-width:"+(innerThick+squareThick)+"px;"
                           + "position:absolute;left:"+innerPosX+"px;top:"+innerPosY+"px;"
                           + "z-index:1;pointer-events:none;" //send to top (click under
                           + "border-radius: 15px;"
                           + "'>"
                           + "
";
    //add in tiles to display
    for (b in board.blocks) { //(myBlock in board.blocks)
        var myBlock = board.blocks[b];
        //left?
        var leftPos = initX + myBlock.posX * moveOneUnit;
        //top
        var topPos  = initY + myBlock.posY * moveOneUnit;
        //blank?
        var idStr   = (myBlock.isBlank) ? 'blank':myBlock.posX+'_'+myBlock.posY;
        var borderStyle = (myBlock.isBlank) ? 'none':'solid';
        //string for div to be inserted
        var divStr = '

';
        gameboardDiv.innerHTML += divStr;
    }
    //return board

    return board;
}

function moveBlockTo(blockId,toX,toY) {
    //move block square attributes
    document.getElementById(blockId).id = toX+'_'+toY;
    var selector = $('div#'+toX+'_'+toY);
    //change to positions
    toX = initX + moveOneUnit*toX;
    toY = initY + moveOneUnit*toY;
    //move block to new position
    selector.animate({left:toX+'px',top:toY+'px'},'fast')
}

function moveBlank(toX,toY) {
    //move blank square attributes
    board.blank.posX = toX;
    board.blank.posY = toY;
    //save blank position in game board
    //board.blocks[oldX+'_'+oldY] = board.blank;
    //convert to pixels
    toX = initX + moveOneUnit*toX;
    toY = initY + moveOneUnit*toY;
    //disappears blank
    return $('div#blank')                                //vanish blank
        .animate({left:toX+'px',top:toY+'px'},'fast')    //move blank to new position
        .animate({opacity:0},'fast')                     //show blank again
        .promise();                                      //allows methods to check if done
}

//switch blank with click (if applicable)
function moveToBlank(blockSelector) {
    //save old values
    var blockX = parseInt(blockSelector.attr('id')[0]); //first number in block
    var blockY = parseInt(blockSelector.attr('id')[2]); //last number in block
    var blankX = parseInt(board.blank.posX); //first number in blank
    var blankY = parseInt(board.blank.posY); //last number in blank
    //if possible: blank is touching piece

    //test if in left or right of blank
    if( ((blockX===(blankX-1)) && (blockY===blankY)) || //left of blank
        ((blockX===(blankX+1)) && (blockY===blankY)) || //right of blank
        ((blockY===(blankY-1)) && (blockX===blankX)) || //above of blank
        ((blockY===(blankY+1)) && (blockX===blankX))    //below of blank
    )
    {
        // save a temp of the block
        var tempB = board.blocks[blockX+'_'+blockY];
        //var myTempBlock = new block(tempB.posX,tempB.posY,tempB.color);
        board.blocks['temp'] = new block(tempB.posX,tempB.posY,tempB.color);

        //move piece
        moveBlockTo(blockX+'_'+blockY,blankX,blankY);
        //
        board.blocks[blankX+'_'+blankY] = board.blocks['temp'];

        //move blank
        moveBlank(blockX,blockY).done(
            //checks if the game is won and presents alert after animation finishes
            function() {
                if (gameWon(myGoalBoard,board))
                    alert("YOU WIN!!!\nClick \"Restart Game\" to play again");
            }
        );

        //
        board.blocks[blockX+'_'+blockY] = board.blank;

    }
}

$(document).ready(displayGame);
<commit_msg>Update squareup.js<commit_after>/* Define global variables */
//spacing definitions
var initX = 0; //px
var initY = 0; //px
var moveOneUnit = 100; //px
//number of blocks thick for border around goal(1 block thick)
var minBorderThickness = 1;
//size of gameboard (gameSize x gameSize)
var gameSize = 5;
//size of innerboard (goalSize x goalSize)
var goalSize = gameSize - 2*minBorderThickness; //goal must be within gameboard
//maximum number of the same color
var maxNumOfColors = gameSize-1;
//gameboard
var board;
//goal board to match to
var myGoalBoard;
//colors for blocks
var colors = ['blue','lime','darkviolet','red','yellow','hotpink']
//['#0000FF','#FF0000','#00FF00','#FF00FF','#FFFF00','DarkOrchid']

//set the gameboard size
function setGameSize(n) {
    //set the new gameSize
    gameSize = n;
    //check that the goalSize < gameSize (by at least minimum border thickness)
    while((gameSize-goalSize) < (2*minBorderThicknes)){
        //adjust goalSize to fit with newly assigned gameSize
        goalSize -= 1;
    }
}

//set the goal board size
function setGoalSize(n) {
    //set the new goalSize
    goalSize = n;
    //check that the goalSize < gameSize (by at least minimum border thickness)
    while((gameSize-goalSize) < (2*minBorderThicknes)){
        //adjust gameSize to fit with newly assigned goalSize
        gameSize += 1;
    }
}

//constructor for block
function block(x,y,c) {
    this.posX = x;  //int
    this.posY = y;  //int
    this.color = c; //hex
    this.isBlank=false;
}

//constructor for gameboard
function gameboard() {
    this.gameSize = gameSize; //game grid size
    this.goalSize = goalSize; //goal grid size
    this.blocks = {};  //positions of blocks (block objects)
    this.blank;        //position of the blank block
}

/* Check if game has been won
 * Input: goalboard object, gameboard object
 * Output: Boolean
 */
function gameWon(goalBoard,board) {
    //get inner part of board
    var innerBoard = {}; var x; var y;
    //get thickness of the border (number of blocks)
    var borderSize = (gameSize-goalSize)/2 //should always be an integer
    //go over each part of the inner board
    //note we are ignoring the border completely
    for(x=borderSize; x<=board.goalSize; x++) {
        for(y=borderSize; y<=board.goalSize; y++) {
            innerBoard[x+'_'+y] = board.blocks[x+'_'+y];
        }
    }
    //check if any inner board and goal board blocks don't match
    for(b in innerBoard) {//b in innerBoard)
        if (innerBoard[b].color !== myGoalBoard[b].color)
            return false;
    }
    //game won since we never broke out of the loop
    return true;
}

/* Create goal for inner board
 * Input: none
 * Output: goalBoard object with the size of goalSize-by-goalSize
 */
function createGoalBoard(){
    //keep count of how many times a color was used (initialized to 0)
    var colorCounts = Array.apply(null, new Array(colors.length))
                           .map(Number.prototype.valueOf,0);
    var x; var y;
    var goalBoard = Array(goalSize*goalSize);
    //get thickness of the border (number of blocks)
    var borderSize = (gameSize-goalSize)/2; //should always be an integer
    //go over the goal board using the absolute position in the gameboard
    for(x=borderSize; x<(board.goalSize+borderSize); x++) {
        for(y=borderSize; y<(board.goalSize+borderSize); y++) {
            //randomly get a color
            var cn = Math.floor((Math.random() * colors.length));
            //check that the color hasn't been maxed out
            //not very efficient but should be no problem with small games
            while( colorCounts[cn] >= maxNumOfColors ) {
                //since color was maxed out, try randomly picking again
                cn = Math.floor((Math.random() * colors.length));
            }
            //color is usable so count it and assign it to new block
            colorCounts[cn] += 1;
            var blockColor = colors[cn];
            goalBoard[x+'_'+y] = new block(x,y,blockColor);
        }
    }
    return goalBoard;
}

//start game setup, return gameboard
function initGame(n) {
    //initiate gameboard
    var myBoard = new gameboard();
    //array of colors for blocks
    //['blue','red','green','purple','yellow']
    //color counts
    var colorCounts = Array.apply(null, new Array(colors.length))
                           .map(Number.prototype.valueOf,0);
    var max = 4;
    //construct board of blocks
    var x; var y;
    for(x=0; x<n; x++) {
        for(y=0; y<n; y++) {
            if(y===0 && x===n-1) { //top right
                tempBlock = new block(x,y,'white');
                tempBlock.isBlank = true;
                myBoard.blank = tempBlock;
            }
            else {
                //get a number (corresponding to color) randomly up to max number
                var cn = Math.floor((Math.random() * colors.length));
                while( colorCounts[cn] >= max ) {
                    cn = Math.floor((Math.random() * colors.length));
                }
                colorCounts[cn] += 1;
                var blockColor = colors[cn];
                tempBlock = new block(x,y,blockColor);//colors[(x+y)%6]);
            }
            var keyStr = x+'_'+y;
            myBoard.blocks[keyStr] = tempBlock;
        }
    }
    return myBoard;
}

function displayGame() {
    //
    var gameboardDiv = document.getElementById('gameboard');
    //set style for gameboard
    board = initGame(gameSize);
    //create goal board
    myGoalBoard = createGoalBoard();
    var goalDiv = document.getElementById("goal");
    var str = ''; var x; var y; var count=0;
    for(y=1; y<(4); y++) {
        for(x=1; x<(4); x++) {
            if (count%3 == 0)
                str += '
';
            str += "<float style='border-style:solid;border-width:1px;"
                +  "background:"+myGoalBoard[x+'_'+y].color+";'>"
                +  "&nbsp &nbsp &nbsp" + '</float>';
            count++;
        }
    }
    goalDiv.innerHTML = str;

    //square border thickness
    var squareThick = 1;
    //create inner board's  height and width be a square (not including the edge)
    var innerHeight = moveOneUnit*(gameSize-2);
    var innerWidth  = moveOneUnit*(gameSize-2);
    //inner board thickness
    var innerThick = 8;
    //inner board position (one block in)
    var innerPosX = initX + moveOneUnit-innerThick;
    var innerPosY = initY + moveOneUnit-innerThick;
    //one block into board
    gameboardDiv.innerHTML = "<div id='innerBoard' "
                           + "style='height:"+innerHeight+"px;width:"+innerWidth+"px;"
                           + "border-style:solid;border-color:black;"
                           + "border-width:"+(innerThick+squareThick)+"px;"
                           + "position:absolute;left:"+innerPosX+"px;top:"+innerPosY+"px;"
                           + "z-index:1;pointer-events:none;" //send to top (click under
                           + "border-radius: 15px;"
                           + "'>"
                           + "
";
    //add in tiles to display
    for (b in board.blocks) { //(myBlock in board.blocks)
        var myBlock = board.blocks[b];
        //left?
        var leftPos = initX + myBlock.posX * moveOneUnit;
        //top
        var topPos  = initY + myBlock.posY * moveOneUnit;
        //blank?
        var idStr   = (myBlock.isBlank) ? 'blank':myBlock.posX+'_'+myBlock.posY;
        var borderStyle = (myBlock.isBlank) ? 'none':'solid';
        //string for div to be inserted
        var divStr = '

';
        gameboardDiv.innerHTML += divStr;
    }
    //return board

    return board;
}

function moveBlockTo(blockId,toX,toY) {
    //move block square attributes
    document.getElementById(blockId).id = toX+'_'+toY;
    var selector = $('div#'+toX+'_'+toY);
    //change to positions
    toX = initX + moveOneUnit*toX;
    toY = initY + moveOneUnit*toY;
    //move block to new position
    selector.animate({left:toX+'px',top:toY+'px'},'fast')
}

function moveBlank(toX,toY) {
    //move blank square attributes
    board.blank.posX = toX;
    board.blank.posY = toY;
    //save blank position in game board
    //board.blocks[oldX+'_'+oldY] = board.blank;
    //convert to pixels
    toX = initX + moveOneUnit*toX;
    toY = initY + moveOneUnit*toY;
    //disappears blank
    return $('div#blank')                                //vanish blank
        .animate({left:toX+'px',top:toY+'px'},'fast')    //move blank to new position
        .animate({opacity:0},'fast')                     //show blank again
        .promise();                                      //allows methods to check if done
}

//switch blank with click (if applicable)
function moveToBlank(blockSelector) {
    //save old values
    var blockX = parseInt(blockSelector.attr('id')[0]); //first number in block
    var blockY = parseInt(blockSelector.attr('id')[2]); //last number in block
    var blankX = parseInt(board.blank.posX); //first number in blank
    var blankY = parseInt(board.blank.posY); //last number in blank
    //if possible: blank is touching piece

    //test if in left or right of blank
    if( ((blockX===(blankX-1)) && (blockY===blankY)) || //left of blank
        ((blockX===(blankX+1)) && (blockY===blankY)) || //right of blank
        ((blockY===(blankY-1)) && (blockX===blankX)) || //above of blank
        ((blockY===(blankY+1)) && (blockX===blankX))    //below of blank
    )
    {
        // save a temp of the block
        var tempB = board.blocks[blockX+'_'+blockY];
        //var myTempBlock = new block(tempB.posX,tempB.posY,tempB.color);
        board.blocks['temp'] = new block(tempB.posX,tempB.posY,tempB.color);

        //move piece
        moveBlockTo(blockX+'_'+blockY,blankX,blankY);
        //
        board.blocks[blankX+'_'+blankY] = board.blocks['temp'];

        //move blank
        moveBlank(blockX,blockY).done(
            //checks if the game is won and presents alert after animation finishes
            function() {
                if (gameWon(myGoalBoard,board))
                    alert("YOU WIN!!!\nClick \"Restart Game\" to play again");
            }
        );

        //
        board.blocks[blockX+'_'+blockY] = board.blank;

    }
}

$(document).ready(displayGame);
<|endoftext|>


<commit_before>/**
 * Redux middleware for calling an API
 * @module apiMiddleware
 * @requires normalizr
 * @requires isomorphic-fetch
 * @exports {Symbol} CALL_API
 * @exports {ReduxMiddleWare} apiMiddleware
 */

/**
 * @typedef {function} ReduxMiddleware
 * @param {Object} store
 * @returns {ReduxNextHandler}
 *
 * @typedef {function} ReduxNextHandler
 * @param {function} next
 * @returns {ReduxActionHandler}
 *
 * @typedef {function} ReduxActionHandler
 * @param {object} action
 * @returns undefined
 */

import { normalize, Schema, arrayOf } from 'normalizr';
import fetch from 'isomorphic-fetch';
import isPlainObject from 'lodash.isplainobject';

/**
 * Fetches an API response and normalizes the resulting JSON according to schema.
 *
 * @function callApi
 * @access private
 * @param {string} endpoint - The URL endpoint for the request
 * @param {string} method - The HTTP method for the request
 * @param {boolean} [auth=false] - Whether to send authentication credentials or not
 * @param {Object} [body] - The body of the request
 * @param {Schema} [schema] - The normalizr schema with which to parse the response
 * @returns {Promise}
 */
function callApi(endpoint, method, headers, body, schema) {
  const requestOptions = { method, body, headers }

  return fetch(endpoint, requestOptions)
    .then((response) => {
      if (response.ok) {
        return Promise.resolve(response);
      } else {
        return Promise.reject(new Error(`${response.status} - ${response.statusText}`));
      }
    })
    .then(response => {
      const contentType = response.headers.get('Content-Type');
      if (contentType && ~contentType.indexOf('json')) {
        return response.json().then((json) => {
          if (schema) {
            return Promise.resolve(normalize(json, schema));
          } else {
            return Promise.resolve(json);
          }
        });
      } else {
        return Promise.resolve();
      }
    });
}

/**
 * Action key that carries API call info interpreted by this Redux middleware.
 *
 * @constant {Symbol}
 * @access public
 * @default
 */
export const CALL_API = Symbol('Call API');

/**
 * Is the given action a Redux Standard API-calling action?
 *
 * @function isRSAA
 * @access public
 * @param action - The action to check against the RSAA definition.
 * @returns {boolean}
 */
export function isRSAA(action) {
  const validRootKeys = [
    [CALL_API],
    'payload',
    'meta'
  ];
  const validCallAPIKeys = [
    'endpoint',
    'method',
    'types',
    'body',
    'headers',
    'schema',
    'bailout'
  ];
  const validMethods = [
    'GET',
    'HEAD',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS'
  ]

  const callAPI = action[CALL_API];
  if (!isPlainObject(action) || typeof callAPI === 'undefined') {
    return false;
  }

  const { endpoint, method, body, headers, schema, types, bailout } = callAPI;

  return Object.keys(action).every(key => ~validRootKeys.indexOf(key)) &&
    isPlainObject(callAPI) &&
    Object.keys(callAPI).every(key => ~validCallAPIKeys.indexOf(key)) &&
    (typeof endpoint === 'string' || typeof endpoint === 'function') &&
    ~validMethods.indexOf(method.toUpperCase()) &&
    (Array.isArray(types) && types.length === 3) &&
    (typeof headers === 'undefined' || isPlainObject(headers)) &&
    (typeof schema === 'undefined' || schema instanceof Schema || schema.hasOwnProperty('_itemSchema')) &&
    (typeof bailout === 'undefined' || typeof bailout === 'boolean' || typeof bailout === 'function');
}

/**
 * A Redux middleware that interprets actions with CALL_API info specified.
 * Performs the call and promises when such actions are dispatched.
 *
 * @type {ReduxMiddleware}
 * @access public
 */
export function apiMiddleware({ getState }) {
  return next => action => {
    const callAPI = action[CALL_API];
    if (!isRSAA(action)) {
      return next(action);
    }

    let { endpoint } = callAPI;
    const { method, body, headers, schema, types, bailout } = callAPI;
    if (typeof endpoint === 'function') {
      endpoint = endpoint(getState());
    }
    if ((typeof bailout === 'boolean' && bailout) ||
        (typeof bailout === 'function' && bailout(getState()))) {
      return Promise.resolve('Bailing out');
    }

    function actionWith(data, payload) {
      const finalPayload = { ...action.payload, ...payload };
      const finalAction = { ...action, payload: finalPayload, ...data };
      delete finalAction[CALL_API];
      return finalAction;
    }

    const [requestType, successType, failureType] = types;
    next(actionWith({ type: requestType }));

    return callApi(endpoint, method, headers, body, schema).then(
      response => next(actionWith({ type: successType }, response)),
      error => next(actionWith({
        type: failureType,
        payload: error,
        error: true
      }))
    );
  };
}
<commit_msg>Update index.js<commit_after>/**
 * Redux middleware for calling an API
 * @module apiMiddleware
 * @requires normalizr
 * @requires isomorphic-fetch
 * @exports {Symbol} CALL_API
 * @exports {ReduxMiddleWare} apiMiddleware
 */

/**
 * @typedef {function} ReduxMiddleware
 * @param {Object} store
 * @returns {ReduxNextHandler}
 *
 * @typedef {function} ReduxNextHandler
 * @param {function} next
 * @returns {ReduxActionHandler}
 *
 * @typedef {function} ReduxActionHandler
 * @param {object} action
 * @returns undefined
 */

import { normalize, Schema } from 'normalizr';
import fetch from 'isomorphic-fetch';
import isPlainObject from 'lodash.isplainobject';

/**
 * Fetches an API response and normalizes the resulting JSON according to schema.
 *
 * @function callApi
 * @access private
 * @param {string} endpoint - The URL endpoint for the request
 * @param {string} method - The HTTP method for the request
 * @param {boolean} [auth=false] - Whether to send authentication credentials or not
 * @param {Object} [body] - The body of the request
 * @param {Schema} [schema] - The normalizr schema with which to parse the response
 * @returns {Promise}
 */
function callApi(endpoint, method, headers, body, schema) {
  const requestOptions = { method, body, headers }

  return fetch(endpoint, requestOptions)
    .then((response) => {
      if (response.ok) {
        return Promise.resolve(response);
      } else {
        return Promise.reject(new Error(`${response.status} - ${response.statusText}`));
      }
    })
    .then(response => {
      const contentType = response.headers.get('Content-Type');
      if (contentType && ~contentType.indexOf('json')) {
        return response.json().then((json) => {
          if (schema) {
            return Promise.resolve(normalize(json, schema));
          } else {
            return Promise.resolve(json);
          }
        });
      } else {
        return Promise.resolve();
      }
    });
}

/**
 * Action key that carries API call info interpreted by this Redux middleware.
 *
 * @constant {Symbol}
 * @access public
 * @default
 */
export const CALL_API = Symbol('Call API');

/**
 * Is the given action a Redux Standard API-calling action?
 *
 * @function isRSAA
 * @access public
 * @param action - The action to check against the RSAA definition.
 * @returns {boolean}
 */
export function isRSAA(action) {
  const validRootKeys = [
    [CALL_API],
    'payload',
    'meta'
  ];
  const validCallAPIKeys = [
    'endpoint',
    'method',
    'types',
    'body',
    'headers',
    'schema',
    'bailout'
  ];
  const validMethods = [
    'GET',
    'HEAD',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS'
  ]

  const callAPI = action[CALL_API];
  if (!isPlainObject(action) || typeof callAPI === 'undefined') {
    return false;
  }

  const { endpoint, method, body, headers, schema, types, bailout } = callAPI;

  return Object.keys(action).every(key => ~validRootKeys.indexOf(key)) &&
    isPlainObject(callAPI) &&
    Object.keys(callAPI).every(key => ~validCallAPIKeys.indexOf(key)) &&
    (typeof endpoint === 'string' || typeof endpoint === 'function') &&
    ~validMethods.indexOf(method.toUpperCase()) &&
    (Array.isArray(types) && types.length === 3) &&
    (typeof headers === 'undefined' || isPlainObject(headers)) &&
    (typeof schema === 'undefined' || schema instanceof Schema || schema.hasOwnProperty('_itemSchema')) &&
    (typeof bailout === 'undefined' || typeof bailout === 'boolean' || typeof bailout === 'function');
}

/**
 * A Redux middleware that interprets actions with CALL_API info specified.
 * Performs the call and promises when such actions are dispatched.
 *
 * @type {ReduxMiddleware}
 * @access public
 */
export function apiMiddleware({ getState }) {
  return next => action => {
    const callAPI = action[CALL_API];
    if (!isRSAA(action)) {
      return next(action);
    }

    let { endpoint } = callAPI;
    const { method, body, headers, schema, types, bailout } = callAPI;
    if (typeof endpoint === 'function') {
      endpoint = endpoint(getState());
    }
    if ((typeof bailout === 'boolean' && bailout) ||
        (typeof bailout === 'function' && bailout(getState()))) {
      return Promise.resolve('Bailing out');
    }

    function actionWith(data, payload) {
      const finalPayload = { ...action.payload, ...payload };
      const finalAction = { ...action, payload: finalPayload, ...data };
      delete finalAction[CALL_API];
      return finalAction;
    }

    const [requestType, successType, failureType] = types;
    next(actionWith({ type: requestType }));

    return callApi(endpoint, method, headers, body, schema).then(
      response => next(actionWith({ type: successType }, response)),
      error => next(actionWith({
        type: failureType,
        payload: error,
        error: true
      }))
    );
  };
}
<|endoftext|>


<commit_before>var cameras = require('./cameras.js');
var render = require('./render.js');
var renderer = require('./renderer.js');
var skybox = require('./skybox.js');
var scenes = require('./scenes.js');
var controls = require('./controls.js');
var bodies = require('./bodies.js');
var animate = require('./animate.js');

$(document).ready(function(){
  animate();
});<commit_msg>added require statement for systemInfo.js<commit_after>var cameras = require('./cameras.js');
var render = require('./render.js');
var renderer = require('./renderer.js');
var skybox = require('./skybox.js');
var scenes = require('./scenes.js');
var controls = require('./controls.js');
var bodies = require('./bodies.js');
var systemInfo = require('./systemInfo.js');
var animate = require('./animate.js');

$(document).ready(function(){
  animate();
});<|endoftext|>


<commit_before>import * as types from './types';

import * as react from './react';
import * as refs from './refs';
import * as renderers from './renderers';
import RenderData from './renderers/renderData';
import Renderer from './renderers/renderer';
import * as template from './template';

import './theme';

const Formatron = {
  react,
  refs,
  renderers: renderers.default,
  template,
  types
};

Formatron.refs.parseRef = refs.default;
Formatron.template.parseTemplate = template.default;

Formatron.renderers.valueRenderers = renderers.valueRenderers;
Formatron.renderers.RenderData = RenderData;
Formatron.renderers.Renderer = Renderer;

export default Formatron;
<commit_msg>Fixed bug in index file.<commit_after>import * as types from './types';

import * as react from './react';
import * as refs from './refs';
import * as renderers from './renderers';
import RenderData from './renderers/renderData';
import Renderer from './renderers/renderer';
import * as template from './template';

import './theme';

const Formatron = {
  react,
  refs,
  renderers: renderers.default,
  template,
  types
};

Formatron.template.parseTemplate = template.default;

Formatron.renderers.valueRenderers = renderers.valueRenderers;
Formatron.renderers.RenderData = RenderData;
Formatron.renderers.Renderer = Renderer;

export default Formatron;
<|endoftext|>


<commit_before>import React from 'react';

const App = function() {
   return
Hi!
;
 }

React.render(App);
<commit_msg>Fixed bug<commit_after>import React from 'react';
import ReactDOM from 'react-dom';

// Create new component, should produce html
const App = function() {
   return
Hi!
;
 }

// Take component's HTML and put in DOM
ReactDOM.render(<App />, document.querySelector('.container'));
<|endoftext|>


<commit_before>module.exports = function mutableProxyFactory(defaultTarget) {
  let mutableHandler;
  let mutableTarget;

  function setTarget(target) {
    if (!(target instanceof Object)) {
      throw new Error(`Target "${target}" is not an object`);
    }
    mutableTarget = target;
  }

  function setHandler(handler) {
    Object.keys(handler).forEach(key => {
      const value = handler[key];

      if (typeof value !== 'function') {
        throw new Error(`Trap "${key}: ${value}" is not a function`);
      }

      if (!Reflect[key]) {
        throw new Error(`Trap "${key}: ${value}" is not a valid trap`);
      }
    });
    mutableHandler = handler;
  }

  if (defaultTarget) {
    setTarget(defaultTarget);
  }
  setHandler(Reflect);

  // Dynamically forward all the traps to the associated methods on the mutable handler
  const handler = new Proxy({}, {
    get(target, property) {
      return (...args) => {
        const patched = [mutableTarget].concat(...args.slice(1));
        return mutableHandler[property].apply(null, patched);
      };
    }
  });

  return {
    setTarget,
    setHandler,
    getTarget() {
      return mutableTarget;
    },
    getHandler() {
      return mutableHandler;
    },
    proxy: new Proxy(() => {}, handler)
  };
};
<commit_msg>Revert proxy handler change for coverage<commit_after>module.exports = function mutableProxyFactory(defaultTarget) {
  let mutableHandler;
  let mutableTarget;

  function setTarget(target) {
    if (!(target instanceof Object)) {
      throw new Error(`Target "${target}" is not an object`);
    }
    mutableTarget = target;
  }

  function setHandler(handler) {
    Object.keys(handler).forEach(key => {
      const value = handler[key];

      if (typeof value !== 'function') {
        throw new Error(`Trap "${key}: ${value}" is not a function`);
      }

      if (!Reflect[key]) {
        throw new Error(`Trap "${key}: ${value}" is not a valid trap`);
      }
    });
    mutableHandler = handler;
  }

  if (defaultTarget) {
    setTarget(defaultTarget);
  }
  setHandler(Reflect);

  // Dynamically forward all the traps to the associated methods on the mutable handler
  const handler = new Proxy({}, {
    get(target, property) {
      return (...args) => mutableHandler[property].apply(null, [mutableTarget, ...args.slice(1)]);
    }
  });

  return {
    setTarget,
    setHandler,
    getTarget() {
      return mutableTarget;
    },
    getHandler() {
      return mutableHandler;
    },
    proxy: new Proxy(() => {}, handler)
  };
};
<|endoftext|>


<commit_before>/* TODO:
- autocomplete search
- select indicateur:
 + min/max/mean/median + /time (week or month or year?)
 + histogram through time for mp
 + histogram deciles by time of all mps with bin highlighted
- handle current mps only?
- by group?
*/

var deputes = {},
  indicateurs = [
    ["semaines_presence", "Semaines d'activité"],
    ["commission_presences", "Commissions — réunions"],
    ["commission_interventions", "Commissions — interventions"],
    ["hemicycle_interventions", "Hémicycle — interventions longues"],
    ["hemicycle_interventions_courtes", "Hémicycle — interventions longues"],
    ["amendements_signes", "Amendements signés"],
    ["amendements_adoptes", "Amendements adoptés"],
    ["rapports", "Rapports"],
    ["propositions_ecrites", "Propositions de loi écrites"],
    ["propositions_signees", "Propositions de loi signées"],
    ["questions_orales", "Questions orales"],
    ["questions_ecrites", "Questions écrites"]
  ],
  start = [6, 12],
  end = [(new Date()).getMonth() + 1, (new Date()).getFullYear() - 2000];
  month = function(){
    return "20" + start[1] + (String(start[0]).length < 2 ? "0" : "") + start[0];
  },
  timeout = 0,
  download = function(m, last){
    setTimeout(function(){
      d3.json("http://www.nosdeputes.fr/synthese/" + m + "/json", function(error, data){
        data.deputes.forEach(function(d){
          if (deputes[d.depute.id] == undefined) deputes[d.depute.id] = {};
          Object.keys(d.depute).forEach(function(k){
            var i = parseInt(d.depute[k]);
            if (k != "id" && k != "nom" && k != "groupe") {
              if (deputes[d.depute.id][k] == undefined) deputes[d.depute.id][k] = 0;
              deputes[d.depute.id][k] += i;
            }
          });
        });
        if (last) {
          document.getElementById("loader").style.display = "none";
          document.getElementById("menu").style.display = "";
        }
      });
    }, timeout);
    timeout += 110;
  },
  displayTop = function(){
    var selec = document.getElementById("deputes"),
      sel = selec.options[selec.selectedIndex].value;
    d3.select("#data").html("").append("ul")
      .selectAll("li")
      .data(indicateurs)
      .enter().append("li")
      .html(function(d) {
        return d[1] + " : " + deputes[sel][d[0]] + "";
      });
    d3.select("#photo").html('');
  };

while (start[0] != end[0] || start[1] != end[1]) {
  download(month());
  if (start[0] == 12) {
    start = [1, start[1]+1];
  } else start[0]++;
}
download(month(), true);

d3.json("http://www.nosdeputes.fr/deputes/json", function(error, data){
  var select = d3.select("#menu").append("select")
    .attr("id", "deputes")
    .on("change", displayTop)
    .selectAll('option')
    .data(data.deputes.sort(function(a,b){
      return d3.ascending(a.depute.nom_de_famille, b.depute.nom_de_famille);
    }))
    .enter().append("option")
    .attr("value", function(d) {
      return d.depute.id;
    })
    .text(function(d) {
      return d.depute.nom_de_famille + ' ' + d.depute.prenom + ' (' + d.depute.groupe_sigle + ')';
    });
  data.deputes.forEach(function(d){
    if (deputes[d.depute.id] == undefined) deputes[d.depute.id] = d.depute;
    else for (var key in d.depute)
      deputes[d.depute.id][key] = d.depute[attrname];
    deputes[d.depute.id].photo = d.depute.url_nosdeputes.replace('.fr/', '.fr/depute/photo/') + '/110';
  });
});

<commit_msg>cleanup js<commit_after>/* TODO:
- autocomplete search
- select indicateur:
 + min/max/mean/median + /time (week or month or year?)
 + histogram through time for mp
 + histogram deciles by time of all mps with bin highlighted
- handle current mps only?
- by group?
*/
(function (ns) {

  ns.deputes = {};
  ns.indicateurs = [
    ["semaines_presence", "Semaines d'activité"],
    ["commission_presences", "Commissions — réunions"],
    ["commission_interventions", "Commissions — interventions"],
    ["hemicycle_interventions", "Hémicycle — interventions longues"],
    ["hemicycle_interventions_courtes", "Hémicycle — interventions longues"],
    ["amendements_signes", "Amendements signés"],
    ["amendements_adoptes", "Amendements adoptés"],
    ["rapports", "Rapports"],
    ["propositions_ecrites", "Propositions de loi écrites"],
    ["propositions_signees", "Propositions de loi signées"],
    ["questions_orales", "Questions orales"],
    ["questions_ecrites", "Questions écrites"]
  ];

  ns.start = [6, 12];
  ns.end = [(new Date()).getMonth() + 1, (new Date()).getFullYear() - 2000];
  ns.timeout = 0;
  ns.download = function(last) {
    var m = "20" + ns.start[1] +
            (String(ns.start[0]).length < 2 ? "0" : "") + ns.start[0];
    setTimeout(function(){
      d3.json("http://www.nosdeputes.fr/synthese/"+m+"/json", function(e, data){
        data.deputes.forEach(function(d){
          if (ns.deputes[d.depute.id] == undefined)
            ns.deputes[d.depute.id] = {};
          Object.keys(d.depute).forEach(function(k){
            if (k != "id" && k != "nom" && k != "groupe") {
              if (ns.deputes[d.depute.id][k] == undefined)
                ns.deputes[d.depute.id][k] = 0;
              ns.deputes[d.depute.id][k] += parseInt(d.depute[k]);
            }
          });
        });
        if (last) {
          document.getElementById("loader").style.display = "none";
          document.getElementById("menu").style.display = "";
        }
      });
    }, ns.timeout);
    ns.timeout += 110;
  };

  ns.displayTop = function() {
    var selec = document.getElementById("deputes"),
      sel = selec.options[selec.selectedIndex].value;
    d3.select("#data").html("").append("ul")
      .selectAll("li")
      .data(ns.indicateurs)
      .enter().append("li")
      .html(function(d) {
        return d[1] + " : " + ns.deputes[sel][d[0]] + "";
      });
    d3.select("#photo").html(
      ''
    );
  };

  ns.init = function() {

    while (ns.start[0] != ns.end[0] || ns.start[1] != ns.end[1]) {
      ns.download();
      if (ns.start[0] == 12) {
        ns.start = [1, ns.start[1]+1];
      } else ns.start[0]++;
    }
    ns.download(true);

    d3.json("http://www.nosdeputes.fr/deputes/json", function(error, data){
      var select = d3.select("#menu").append("select")
        .attr("id", "deputes")
        .on("change", ns.displayTop)
        .selectAll('option')
        .data(data.deputes.sort(function(a, b){
          return d3.ascending(a.depute.nom_de_famille, b.depute.nom_de_famille);
        }))
        .enter().append("option")
        .attr("value", function(d) {
          return d.depute.id;
        })
        .text(function(d) {
          return d.depute.nom_de_famille + ' ' + d.depute.prenom +
                 ' (' + d.depute.groupe_sigle + ')';
        });
      data.deputes.forEach(function(d){
        if (ns.deputes[d.depute.id] == undefined)
          ns.deputes[d.depute.id] = d.depute;
        else for (var key in d.depute)
          ns.deputes[d.depute.id][key] = d.depute[key];
        ns.deputes[d.depute.id].photo = (d.depute.url_nosdeputes + '/110')
          .replace('.fr/', '.fr/depute/photo/');
      });
    });

  }();

})(window.synthese = window.synthese || {});
<|endoftext|>