<commit_before>/*
* @Author: kuychaco
* @Date:   2015-06-10 16:19:56
* @Last Modified by:   justinwebb
* @Last Modified time: 2015-06-13 11:42:08
*/

'use strict';

var GitHubApi = require('github');

var github = new GitHubApi({
  // required
  version: '3.0.0',
  // optional
  // debug: true,
  protocol: 'https',
  host: 'api.github.com', // should be api.github.com for GitHub
  // pathPrefix: '/api/v3', // for some GHEs; none for GitHub
  timeout: 5000,
  headers: {
    'user-agent': 'My-Cool-GitHub-App' // GitHub is happy with a unique user agent
  }
});

// OAuth2
github.authenticate({
  type: 'oauth',
  token: '<INSERT_GITHUB_TOKEN_HERE>'
});

// Get all issues from specified repo
var getIssues = function(callback) {

  github.issues.repoIssues({
    user: 'relentlessbreakfast',
    repo: 'WebApp',
    state: 'open'
  }, function(err, res) {
    if (err) {
      return callback(err, null);
    }
    return callback(null, res);
  });

};

// Helper method to automate creation of issues
var createIssue = function(title, body, label) {
  github.issues.create({
    user: 'relentlessbreakfast',
    repo: 'WebApp',
    title: title,
    body: body,
    assignee: 'kuychaco',
    labels: [label]
  }, function(err, res) {
    console.log(res);
  });
};

module.exports.getIssues = getIssues;
module.exports.createIssue = createIssue;
<commit_msg>(feat) Add 'relentlessbreakfast' Github authentication parameters<commit_after><|endoftext|>


<commit_before>$(function() {
    window.Image = {
        memoryCanvas: [],
        usedColours: [],
        defaultValue: {
            'r':0,
            'g':0,
            'b':0,
            'a':1 // 0: fully transparent -> 1: not transparent
        },
        componentToHex: function(c) {
            var hex = c.toString(16);
            return hex.length == 1 ? "0" + hex : hex;
        },
        rgbToHex: function(r, g, b) {
            return "#" + this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b);
        },
        average: function(values) {
            var sum = values.reduceRight(function(x, total) {
                return total + x;
            }, 0);

            return sum/values.length;
        },
        hexToRgb: function(hex) {
            var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
            return result ? {
                r: parseInt(result[1], 16),
                g: parseInt(result[2], 16),
                b: parseInt(result[3], 16)
            } : null;
        },
        _originalMethod: function(surroundingSquares) {
            // surroundingSquares is an n x n grid (min n = 2, max n = 3)
            var reds = [];
            var greens = [];
            var blues = [];
            for (var i = 0; i < surroundingSquares.length; i++) {
                var row = surroundingSquares[i];
                for (var j = 0; j < row.length; j++) {
                    var colour = row[j];
                    if (colour !== this.defaultValue) {
                        var colours = this.hexToRgb(colour);
                        if (colours !== null) {
                            reds.push(colours.r);
                            greens.push(colours.g);
                            blues.push(colours.b);
                        }
                    }
                }
            }

            var redAvg = Math.floor(Math.random() * 256);
            if (reds.length > 0) {
                redAvg = Math.floor(this.average(reds));
            }

            var greenAvg = Math.floor(Math.random() * 256);
            if (greens.length > 0) {
                greenAvg = Math.floor(this.average(greens));
            }

            var blueAvg = Math.floor(Math.random() * 256);
            if (blues.length > 0) {
                blueAvg = Math.floor(this.average(blues));
            }

            var potential = {
                'r':redAvg,
                'g':greenAvg,
                'b':blueAvg,
                'a':1
            };

            var possible = this.rgbToHex(potential.r, potential.g, potential.b);

            if (this.usedColours.indexOf(possible) >= 0) {
                // Already used this colour
                found = false;
                var box = 2;
                while (!found) {
                    var minRed = redAvg - box < 0 ? 0 : redAvg - box;
                    var minGreen = greenAvg - box < 0 ? 0 : greenAvg - box;
                    var minBlue = blueAvg - box < 0 ? 0 : blueAvg - box;
                    var maxRed = redAvg + box > 255 ? 255 : redAvg + box;
                    var maxGreen = greenAvg + box > 255 ? 255 : greenAvg + box;
                    var maxBlue = blueAvg + box > 255 ? 255 : blueAvg + box;
                    for (i = minRed; i <= maxRed; i++) {
                        for (j = minGreen; j <= maxGreen; j++) {
                            for (k = minBlue; k <= maxBlue; k++) {
                                potential.r = i;
                                potential.g = j;
                                potential.b = k;
                                possible = this.rgbToHex(i, j, k);
                                if (this.usedColours.indexOf(possible) < 0) {
                                    found = true;
                                    break;
                                }
                            }
                            if (found) {
                                break;
                            }
                        }
                        if (found) {
                            break;
                        }
                    }
                    box = box * 2;
                    if (box > 4) {
                        console.log("Box became larger than 30");
                        found = true;
                    }
                }
            }

            return potential;
        },

        _iterationMethod: function(surroundingSquares) {
            var potential = {
                'r':0,
                'g':0,
                'b':0,
                'a':0
            };
            if (typeof(this.previousValue) !== "undefined") {
                // This obviously isn't a potential option, but used to
                // have a baseline to increment from
                potential = this.hexToRgb(this.previousValue);
            } else {
                // No previousValue has been defined - so we create on.
                // It's also no in the list of used colours, so it'll
                // go straight through.
                this.previousValue = this.rgbToHex(
                    this.defaultValue.r,
                    this.defaultValue.g,
                    this.defaultValue.b
                );
            }

            var possibleColour = this.previousValue;

            while (this.usedColours.indexOf(possibleColour) >= 0) {
                potential.r = potential.r + 1;
                if (potential.r > 255) {
                    potential.r = 0;
                    potential.g = potential.g + 1;
                    if (potential.g > 255) {
                        potential.b = potential.b + 1;
                    }
                }
                potential.a = Math.random();
                possibleColour = this.rgbToHex(
                    potential.r, potential.g, potential.b
                );
            }

            return potential;
        },

        setMethod: function(method) {
            switch(method){
                case "original":
                case "ORIGINAL":
                    this.generateColour = this._originalMethod;
                    break;
                case "iterate":
                case "ITERATE":
                    this.generateColour = this._iterationMethod
                    break;
            }
        },

        _getSurroundingColours: function(i, j) {
            var grid = [];

            var previousI = i - 1 < 0 ? 0 : i - 1;
            var previousJ = j - 1 < 0 ? 0 : j - 1;
            for (var x = previousI; x < i + 1; x++) {
                var row = [];
                for (var y = previousJ; y < j + 1; y++) {
                    row.push(this.memoryCanvas[x][y]);
                }
                grid.push(row);
            }

            return grid;
        },

        init: function() {
            var canvas = $(document).find("#area")[0];
            var context = canvas.getContext('2d');

            var width = canvas.width;
            var height = canvas.height;

            for (var i = 0; i < width; i++) {
                var row = [];
                for (var j = 0; j < height; j++) {
                    row.push(this.defaultValue);
                }
                this.memoryCanvas.push(row);
            }
            this.usedColours = [];
        },

        begin: function() {
            var method = $(document).find("#method option:selected").val();
            this.setMethod(method);

            var canvas = $(document).find("#area")[0];
            var context = canvas.getContext('2d');

            var width = canvas.width;
            var height = canvas.height;

            // Iterate over the canvas
            for (var i = 0; i < width; i++) {
                var row = [];
                for (var j = 0; j < height; j++) {
                    var colour = this.generateColour(
                        this._getSurroundingColours(i, j)
                    );
                    var hexColour = this.rgbToHex(colour.r, colour.g, colour.b);
                    this.usedColours.push(hexColour);
                    this.memoryCanvas[i][j] = colour;
                    console.log(
                        "generated colour " + hexColour + " for (" + i + "," + j + ")"
                    );
                }
            }

            for (var i = 0; i < width; i++) {
                for (j = 0; j < height; j++) {
                    context.globalAlpha(this.memoryCanvas[i][j].a)
                    context.fillStyle = this.rgbToHex(
                        this.memoryCanvas[i][j].r,
                        this.memoryCanvas[i][j].g,
                        this.memoryCanvas[i][j].b
                    );
                    context.fillRect(i, j, 1, 1);
                }
            }

            this.init();
        }
    }

    $(document).find("#start").on('click', function() {
        window.Image.begin();
    });

    window.Image.init();
});<commit_msg>Moved the image generators to their own objects. Moved any util functions to their own object too. Iterate works at 0.5 seconds per row. The original currently doesn't function<commit_after>$(function() {
    if (typeof(window.Methods) === 'undefined') {
        window.Methods = {};
    }

    window.Methods.Iterate = {
        usedColours:[],
        defaultValue:null,
        previousValue:undefined,

        init: function(canvas, defaultValue) {
            this.defaultValue = defaultValue;
        },

        generate: function(i, j) {
            var potential = {
                'r':0,
                'g':0,
                'b':0,
                'a':0
            };
            if (typeof(this.previousValue) !== "undefined") {
                // This obviously isn't a potential option, but used to
                // have a baseline to increment from
                potential = window.ImageUtils.hexToRgb(this.previousValue);
            } else {
                // No previousValue has been defined - so we create on.
                // It's also no in the list of used colours, so it'll
                // go straight through.
                this.previousValue = window.ImageUtils.rgbToHex(
                    this.defaultValue.r,
                    this.defaultValue.g,
                    this.defaultValue.b
                );
            }

            var possibleColour = this.previousValue;

            while (this.usedColours.indexOf(possibleColour) >= 0) {
                potential.r = potential.r + 1;
                if (potential.r > 255) {
                    potential.r = 0;
                    potential.g = potential.g + 1;
                    if (potential.g > 255) {
                        potential.b = potential.b + 1;
                    }
                }
                possibleColour = window.ImageUtils.rgbToHex(
                    potential.r, potential.g, potential.b
                );
            }

            this.previousValue = possibleColour;

            return potential;
        },

        record: function(colour) {
            var hexColour = window.ImageUtils.rgbToHex(colour.r, colour.g, colour.b);
            this.usedColours.push(hexColour);
        }
    },

    window.Methods.Original = {
        memoryCanvas: [],
        usedColours:[],

        init: function(canvas, defaultValue) {
            var width = canvas.width;
            var height = canvas.height;

            for (var i = 0; i < width; i++) {
                var row = [];
                for (var j = 0; j < height; j++) {
                    row.push(defaultValue);
                }
                this.memoryCanvas.push(row);
            }
        },

        average: function(values) {
            var sum = values.reduceRight(function(x, total) {
                return total + x;
            }, 0);

            return sum/values.length;
        },

        _getSurroundingColours: function(i, j) {
            var grid = [];

            var previousI = i - 1 < 0 ? 0 : i - 1;
            var previousJ = j - 1 < 0 ? 0 : j - 1;
            for (var x = previousI; x < i + 1; x++) {
                var row = [];
                for (var y = previousJ; y < j + 1; y++) {
                    row.push(this.memoryCanvas[x][y]);
                }
                grid.push(row);
            }

            return grid;
        },

        generate: function(i, j) {
            // surroundingSquares is an n x n grid (min n = 2, max n = 3)
            var surroundingSquares = [];
            var reds = [];
            var greens = [];
            var blues = [];
            for (var i = 0; i < surroundingSquares.length; i++) {
                var row = surroundingSquares[i];
                for (var j = 0; j < row.length; j++) {
                    var colour = row[j];
                    if (colour !== this.defaultValue) {
                        var colours = window.ImageUtils.hexToRgb(colour);
                        if (colours !== null) {
                            reds.push(colours.r);
                            greens.push(colours.g);
                            blues.push(colours.b);
                        }
                    }
                }
            }

            var redAvg = Math.floor(Math.random() * 256);
            if (reds.length > 0) {
                redAvg = Math.floor(this.average(reds));
            }

            var greenAvg = Math.floor(Math.random() * 256);
            if (greens.length > 0) {
                greenAvg = Math.floor(this.average(greens));
            }

            var blueAvg = Math.floor(Math.random() * 256);
            if (blues.length > 0) {
                blueAvg = Math.floor(this.average(blues));
            }

            var potential = {
                'r':redAvg,
                'g':greenAvg,
                'b':blueAvg,
                'a':1
            };

            var possible = window.ImageUtils.rgbToHex(potential.r, potential.g, potential.b);

            if (this.usedColours.indexOf(possible) >= 0) {
                // Already used this colour
                found = false;
                var box = 2;
                while (!found) {
                    var minRed = redAvg - box < 0 ? 0 : redAvg - box;
                    var minGreen = greenAvg - box < 0 ? 0 : greenAvg - box;
                    var minBlue = blueAvg - box < 0 ? 0 : blueAvg - box;
                    var maxRed = redAvg + box > 255 ? 255 : redAvg + box;
                    var maxGreen = greenAvg + box > 255 ? 255 : greenAvg + box;
                    var maxBlue = blueAvg + box > 255 ? 255 : blueAvg + box;
                    for (i = minRed; i <= maxRed; i++) {
                        for (j = minGreen; j <= maxGreen; j++) {
                            for (k = minBlue; k <= maxBlue; k++) {
                                potential.r = i;
                                potential.g = j;
                                potential.b = k;
                                possible = window.ImageUtils.rgbToHex(i, j, k);
                                if (this.usedColours.indexOf(possible) < 0) {
                                    found = true;
                                    break;
                                }
                            }
                            if (found) {
                                break;
                            }
                        }
                        if (found) {
                            break;
                        }
                    }
                    box = box * 2;
                    if (box > 4) {
                        console.log("Box became larger than 30");
                        found = true;
                    }
                }
            }

            return potential;
        },

        record: function(colour) {
            var hexColour = window.ImageUtils.rgbToHex(colour.r, colour.g, colour.b);
            this.usedColours.push(hexColour);
        }
    },

    window.ImageUtils = {
        componentToHex: function(c) {
            var hex = c.toString(16);
            return hex.length == 1 ? "0" + hex : hex;
        },
        rgbToHex: function(r, g, b) {
            return "#" + this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b);
        },

        hexToRgb: function(hex) {
            var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
            return result ? {
                r: parseInt(result[1], 16),
                g: parseInt(result[2], 16),
                b: parseInt(result[3], 16)
            } : null;
        },
        unique: function(values) {
            console.log(
                values.length + " of which unique: " + values.reduceRight(
                    function(memo, num){
                        if (memo.indexOf(num) === -1) {
                            memo.push(num);
                        }
                        return memo;
                    }, []
                ).length
            );
        }
    },

    window.Image = {
        uniqueCheck:false,
        canvas:null,
        context:null,

        defaultValue: {
            'r':0,
            'g':0,
            'b':0,
            'a':1 // 0: fully transparent -> 1: not transparent
        },
        method:null,

        setMethod: function(method) {
            switch(method){
                case "original":
                case "ORIGINAL":
                    this.method = window.Methods.Original;
                    break;
                case "iterate":
                case "ITERATE":
                    this.method = window.Methods.Iterate;
                    break;
            }
        },

        init: function() {
            this.canvas = $(document).find("#area")[0];
            this.context = this.canvas.getContext('2d');

            this.currentRow = 0;
            this.method = window.Methods.Original;
        },

        drawRow: function(row) {
            for (var i = 0; i < row.length; i++) {
                this.context.fillStyle = window.ImageUtils.rgbToHex(
                    row[i].r, row[i].g, row[i].b
                );
                this.context.fillRect(i, this.currentRow, 1, 1);
            }
            this.currentRow++;
        },

        begin: function() {
            this.currentRow = 0;

            var method = $(document).find("#method option:selected").val();
            this.setMethod(method);

            this.method.init(this.canvas, this.defaultValue);

            var width = this.canvas.width;
            var height = this.canvas.height;

            // Iterate over the canvas
            var now = Date.now();
            for (var i = 0; i < width; i++) {
                var row = [];
                for (var j = 0; j < height; j++) {
                    var colour = this.method.generate(i, j);
                    this.method.record(colour);

                    row.push(colour);
                }
                this.drawRow(row);
                console.log("finished row " + i + " in: " + (Date.now() - now));
                now = Date.now();
            }
            if (this.uniqueCheck === true) {
                this.unique();
            }
        }
    }

    $(document).find("#start").on('click', function() {
        window.Image.begin();
    });

    window.Image.init();
});<|endoftext|>


<commit_before>/**
 * jQuery Async Me
 * Un plug-in jQuery pour charger de manière asynchrone vos contenu multimédia.
 * http://github.com/Jok3rDev/async-me
 *
 * Licensed under the MIT license.
 * Copyright 2016 Fabrice Trimech
 * https://github.com/Jok3rDev/
 */

(function($) {
  $.fn.asyncMe = function() {
    'use strict';
    console.log('Le plug-in est exécuté');
    var $element = this;
    console.log($element);
    $element.each(function(){
      checkAttribute($element);
      defineElement($element);
    });
    return this;

    /**
     * Vérifie si l'attribut data-src est présent et non null
     * @param  $element L'élement du DOM sur lequel est exécuté AsyncMe
     * @return booléen
     */
    function checkAttribute($element) {
      console.log($element);
      var check = true;
      check &= Boolean($element.data('src') === undefined);
      check &= Boolean($element.data('src') != '');

      if (check) {
        console.error("L'attribut data-src n'est pas correctement formaté.");
      }
      return check;
    }

    function defineElement($element) {

    }
  }
})(window.jQuery);
<commit_msg>Ajout méthode prise en charge des elements du dom<commit_after>/**
 * jQuery Async Me
 * Un plug-in jQuery pour charger de manière asynchrone vos contenu multimédia.
 * http://github.com/Jok3rDev/async-me
 *
 * Licensed under the MIT license.
 * Copyright 2016 Fabrice Trimech
 * https://github.com/Jok3rDev/
 */

(function($) {
  $.fn.asyncMe = function() {
    'use strict';
    console.log('Le plug-in est exécuté');
    var $element = this;
    console.log($element);
    $element.each(function(key, value){
      checkAttribute($(this));
      defineElement(value.tagName);
    });
    return this;

    /**
     * Vérifie si l'attribut data-src est présent et non null
     * @param  $element L'élement du DOM sur lequel est exécuté AsyncMe
     * @return booléen
     */
    function checkAttribute($element) {
      var check = true;
      check &= Boolean($element.data('src') === undefined);
      check &= Boolean($element.data('src') != '');

      if (check) {
        console.error("L'attribut data-src n'est pas correctement formaté.");
      }
      return check;
    }

    function defineElement(tag) {
      var tag    = tag.toLowerCase();
      var result = [];

      switch (tag) {
        case 'img':
        case 'iframe':
          result['toChange'] = 'src';
          break;
        default:
        console.error("L'élement du DOM définit n'est pas géré par le plug-in.");
        result = false;
      }
      return result;
    }
  }
})(window.jQuery);
<|endoftext|>


<commit_before>/**
 * @file Reaction Roles Groups Handler
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

module.exports = async Bastion => {
  try {
    let reactionRolesGroupModels = await Bastion.database.models.reactionRolesGroup.findAll({
      attributes: [ 'messageID', 'channelID', 'guildID' ]
    });

    let reactionRolesGroups = reactionRolesGroupModels.map(model => model.dataValues);

    for (let group of reactionRolesGroups) {
      if (!Bastion.channels.has(group.channelID)) return;
      let channel = Bastion.channels.get(group.channelID);
      if (!channel.messages.has(group.messageID)) {
        await channel.fetchMessage(group.messageID);
      }
    }
  }
  catch (e) {
    Bastion.error.log(e);
  }
};
<commit_msg>handlers: fix error handler in reactionRolesGroupHandler<commit_after>/**
 * @file Reaction Roles Groups Handler
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

module.exports = async Bastion => {
  try {
    let reactionRolesGroupModels = await Bastion.database.models.reactionRolesGroup.findAll({
      attributes: [ 'messageID', 'channelID', 'guildID' ]
    });

    let reactionRolesGroups = reactionRolesGroupModels.map(model => model.dataValues);

    for (let group of reactionRolesGroups) {
      if (!Bastion.channels.has(group.channelID)) return;
      let channel = Bastion.channels.get(group.channelID);
      if (!channel.messages.has(group.messageID)) {
        await channel.fetchMessage(group.messageID);
      }
    }
  }
  catch (e) {
    Bastion.log.error(e);
  }
};
<|endoftext|>


<commit_before>function cloneObject(obj){
    if (obj === null){
        return null;
    }
    var o = obj.constructor === Array ? [] : {};
    for(var i in obj){
        if(obj.hasOwnProperty(i)){
            o[i] = typeof obj[i] === "object" ? cloneObject(obj[i]) : obj[i];
        }
    }
    return o;
}
function turn(car, o) {
    var _car = cloneObject(car);
    if(o == 'left') {
	_car.row -- ;
    } else {
	_car.row ++ ;
    }
    return _car;
}

function safe(a, b) {
    var ba = 1 << a.row;
    var bb = 1 << b.row;
    if(a.o == 'left') {
	ba |= 1 << (a.row - 1);
    } else if(a.o == 'right'){
	ba |= 1 << (a.row + 1);
    }
    if(b.o == 'left') {
	bb |= 1 << (b.row - 1);
    } else if(b.o == 'right'){
	bb |= 1 << (b.row + 1);
    }
    if((ba & bb) > 0) {
	if(a.x > b.x) {
	    if(a.speed > b.speed) {
		return 1; // ahead and faster
	    } else {
		if(a.x - backWarningRatio * Math.exp( - a.speed) - a.len * 1.3 < b.x + b.speed * frontWarningRatio) {
		    if(a.maxSpeed > b.maxSpeed) {
			return 2; // prior
		    } else {
			return 1.5; // should give place
		    }
		} else {
		    return 1; // too far
		}
	    }
	} else {
	    if(a.speed < b.speed) {
		return 1; // behind and slower
	    } else {
		if(a.x + a.speed * frontWarningRatio > b.x - backWarningRatio * Math.exp( - b.speed) - b.len * 1.3) {
		    if(a.maxSpeed > b.maxSpeed) {
			return 0.5; // prior
		    } else {
			return 0; // should give place
		    }
		} else {
		    return 1; // too for
		}
	    }
	}
    } else {
	return 1; // no conflict
    }
}

function strategyNon(car, carList){
    car.x += car.speed;
    car.speed = Math.min(car.maxSpeed, car.speed + car.maxSpeed / accelerateRatio);
}

function strategyWait(car, carList) {
    var flag = 0;
    for(var x in carList) {
	if(car != carList[x]) {
	    var safeStatus = safe(car, carList[x]);
	    if(safeStatus < 1) {
		flag = 1;
	    }
	}
    }
    if(flag == 1) {
	car.speed = Math.max(0, car.speed - car.maxSpeed / brakeRatio);
    } else {
	car.speed = Math.min(car.maxSpeed, car.speed + car.maxSpeed / accelerateRatio);
    }
}

function strategyA(car, carList){
    var flag = 0;
    for(var x in carList) {
	if(car != carList[x]) {
	    var safeStatus = safe(car, carList[x]);
	    if(safeStatus < 1) {
		flag = 1;
	    }
	}
    }
    if(flag == 1) {
	var _flag = 0;
	if(car.row == 0) {
	    _flag = 1;
	}
	for(var x in carList) {
	    if(car != carList[x]) {
		var safeStatus = safe(turn(car, 'left'), carList[x]);
		if(safeStatus < 1) {
		    _flag = 1;
		}
	    }
	}
	if(_flag == 1) {
	    var __flag = 0;
	    if(car.row == maxRow - 1) {
		__flag = 1;
	    }
	    for(var x in carList) {
		if(car != carList[x]) {
		    var safeStatus = safe(turn(car, 'right'), carList[x]);
		    if(safeStatus < 1) {
			__flag = 1;
		    }
		}
	    }
	    if(__flag == 1) {
		car.speed = Math.max(0, car.speed - car.maxSpeed / brakeRatio);
	    } else {
		if(car.offset == 0) {
		    car.o = 'right';
		    car.offset = 5.5;
		}
	    }
	} else {
	    if(car.offset == 0) {
		car.o = 'left';
		car.offset = 5.5;
	    }
	}
    } else {
	car.speed = Math.min(car.maxSpeed, car.speed + car.maxSpeed / accelerateRatio);
    }
}

function strategyB(car, carList) {
    var _speedRow = [];
    for(var i = 0; i < maxRow; i ++ ) {
	_speedRow[i] = i * 150.0 / maxRow;
    }
    var flag = 0;
    var _flag = 0;
    if(car.maxSpeed > _speedRow[maxRow - car.row] && car.offset == 0){
	flag = 0;
	for(var x in carList) {
	    if(car != carList[x]) {
		var safeStatus = safe(turn(car, 'left'), carList[x]);
		if(safeStatus < 1) {
		    flag = 1;
		    break;
		}
	    }
	}
	if(!flag) {
	    car.o='left';
	    car.offset = 1.5;
	}
    }
    if(car.maxSpeed < _speedRow[maxRow - car.row - 1] && car.offset == 0){
	flag = 0;
	for(var x in carList) {
	    if(car != carList[x]) {
		var safeStatus = safe(turn(car, 'right'), carList[x]);
		if(safeStatus < 1) {
		    flag = 1;
		    break;
		}
	    }
	}
	if(!flag) {
	    car.o='right';
	    car.offset = 1.5;
	}
    }
    flag = 0;
    for(var x in carList) {
	if(car != carList[x]) {
	    var safeStatus = safe(car, carList[x]);
	    if(safeStatus < 1) {
		flag = 1;
		break;
	    }
	}
    }
    if(!flag) {
	car.speed = Math.min(car.maxSpeed, car.speed + car.maxSpeed / accelerateRatio);
    }
    else {
	car.speed = Math.max(0, car.speed - car.maxSpeed / brakeRatio);
    }
}

function strategyC(car, carList) {
    var flag = 0;
    if(car.row == maxRow - 1) {
	flag = 1;
    }
    for(var x in carList) {
	if(car != carList[x]) {
	    var safeStatus = safe(turn(car, 'right'), carList[x]);
	    if(safeStatus != 1) {
		flag = 1;
	    }
	}
    }
    if(flag == 1) {
    } else {
	if(car.offset == 0) {
	    car.o = 'right';
	    car.offset = 5.5;
	}
    }
    strategyA(car, carList);
}

function strategyD(car, carList) {

}

function strategyE(car, carList) {

}
<commit_msg>push failed?<commit_after>function cloneObject(obj){
    if (obj === null){
        return null;
    }
    var o = obj.constructor === Array ? [] : {};
    for(var i in obj){
        if(obj.hasOwnProperty(i)){
            o[i] = typeof obj[i] === "object" ? cloneObject(obj[i]) : obj[i];
        }
    }
    return o;
}

function turn(car, o) {
    var _car = cloneObject(car);
    if(o == 'left') {
	_car.row -- ;
    } else {
	_car.row ++ ;
    }
    return _car;
}

function safe(a, b) {
    var ba = 1 << a.row;
    var bb = 1 << b.row;
    if(a.o == 'left') {
	ba |= 1 << (a.row - 1);
    } else if(a.o == 'right'){
	ba |= 1 << (a.row + 1);
    }
    if(b.o == 'left') {
	bb |= 1 << (b.row - 1);
    } else if(b.o == 'right'){
	bb |= 1 << (b.row + 1);
    }
    if((ba & bb) > 0) {
	if(a.x > b.x) {
	    if(a.speed > b.speed) {
		return 1; // ahead and faster
	    } else {
		if(a.x - backWarningRatio * Math.exp( - a.speed) - a.len * 1.3 < b.x + b.speed * frontWarningRatio) {
		    if(a.maxSpeed > b.maxSpeed) {
			return 2; // prior
		    } else {
			return 1.5; // should give place
		    }
		} else {
		    return 1; // too far
		}
	    }
	} else {
	    if(a.speed < b.speed) {
		return 1; // behind and slower
	    } else {
		if(a.x + a.speed * frontWarningRatio > b.x - backWarningRatio * Math.exp( - b.speed) - b.len * 1.3) {
		    if(a.maxSpeed > b.maxSpeed) {
			return 0.5; // prior
		    } else {
			return 0; // should give place
		    }
		} else {
		    return 1; // too for
		}
	    }
	}
    } else {
	return 1; // no conflict
    }
}

function strategyNon(car, carList){
    car.x += car.speed;
    car.speed = Math.min(car.maxSpeed, car.speed + car.maxSpeed / accelerateRatio);
}

function strategyWait(car, carList) {
    var flag = 0;
    for(var x in carList) {
	if(car != carList[x]) {
	    var safeStatus = safe(car, carList[x]);
	    if(safeStatus < 1) {
		flag = 1;
	    }
	}
    }
    if(flag == 1) {
	car.speed = Math.max(0, car.speed - car.maxSpeed / brakeRatio);
    } else {
	car.speed = Math.min(car.maxSpeed, car.speed + car.maxSpeed / accelerateRatio);
    }
}

function strategyA(car, carList){
    var flag = 0;
    for(var x in carList) {
	if(car != carList[x]) {
	    var safeStatus = safe(car, carList[x]);
	    if(safeStatus < 1) {
		flag = 1;
	    }
	}
    }
    if(flag == 1) {
	var _flag = 0;
	if(car.row == 0) {
	    _flag = 1;
	}
	for(var x in carList) {
	    if(car != carList[x]) {
		var safeStatus = safe(turn(car, 'left'), carList[x]);
		if(safeStatus < 1) {
		    _flag = 1;
		}
	    }
	}
	if(_flag == 1) {
	    var __flag = 0;
	    if(car.row == maxRow - 1) {
		__flag = 1;
	    }
	    for(var x in carList) {
		if(car != carList[x]) {
		    var safeStatus = safe(turn(car, 'right'), carList[x]);
		    if(safeStatus < 1) {
			__flag = 1;
		    }
		}
	    }
	    if(__flag == 1) {
		car.speed = Math.max(0, car.speed - car.maxSpeed / brakeRatio);
	    } else {
		if(car.offset == 0) {
		    car.o = 'right';
		    car.offset = 5.5;
		}
	    }
	} else {
	    if(car.offset == 0) {
		car.o = 'left';
		car.offset = 5.5;
	    }
	}
    } else {
	car.speed = Math.min(car.maxSpeed, car.speed + car.maxSpeed / accelerateRatio);
    }
}

function strategyB(car, carList) {
    var _speedRow = [];
    for(var i = 0; i < maxRow; i ++ ) {
	_speedRow[i] = i * 150.0 / maxRow;
    }
    var flag = 0;
    var _flag = 0;
    if(car.maxSpeed > _speedRow[maxRow - car.row] && car.offset == 0){
	flag = 0;
	for(var x in carList) {
	    if(car != carList[x]) {
		var safeStatus = safe(turn(car, 'left'), carList[x]);
		if(safeStatus < 1) {
		    flag = 1;
		    break;
		}
	    }
	}
	if(!flag) {
	    car.o='left';
	    car.offset = 1.5;
	}
    }
    if(car.maxSpeed < _speedRow[maxRow - car.row - 1] && car.offset == 0){
	flag = 0;
	for(var x in carList) {
	    if(car != carList[x]) {
		var safeStatus = safe(turn(car, 'right'), carList[x]);
		if(safeStatus < 1) {
		    flag = 1;
		    break;
		}
	    }
	}
	if(!flag) {
	    car.o='right';
	    car.offset = 1.5;
	}
    }
    flag = 0;
    for(var x in carList) {
	if(car != carList[x]) {
	    var safeStatus = safe(car, carList[x]);
	    if(safeStatus < 1) {
		flag = 1;
		break;
	    }
	}
    }
    if(!flag) {
	car.speed = Math.min(car.maxSpeed, car.speed + car.maxSpeed / accelerateRatio);
    }
    else {
	car.speed = Math.max(0, car.speed - car.maxSpeed / brakeRatio);
    }
}

function strategyC(car, carList) {
    var flag = 0;
    if(car.row == maxRow - 1) {
	flag = 1;
    }
    for(var x in carList) {
	if(car != carList[x]) {
	    var safeStatus = safe(turn(car, 'right'), carList[x]);
	    if(safeStatus != 1) {
		flag = 1;
	    }
	}
    }
    if(flag == 1) {
    } else {
	if(car.offset == 0) {
	    car.o = 'right';
	    car.offset = 5.5;
	}
    }
    strategyA(car, carList);
}

function strategyD(car, carList) {

}

function strategyE(car, carList) {

}
<|endoftext|>


<commit_before>/**
* This class handles LZW encoding
* Adapted from Jef Poskanzer's Java port by way of J. M. G. Elliott.
* @author Kevin Weiner (original Java version - kweiner@fmsware.com)
* @author Thibault Imbert (AS3 version - bytearray.org)
* @version 0.1 AS3 implementation
*/

LZWEncoder = function()
{
    var exports = {};
	var EOF = -1;
	var imgW;
	var imgH
	var pixAry;
	var initCodeSize;
	var remaining;
	var curPixel;

	// GIFCOMPR.C - GIF Image compression routines
	// Lempel-Ziv compression based on 'compress'. GIF modifications by
	// David Rowley (mgardi@watdcsu.waterloo.edu)
	// General DEFINEs

	var BITS = 12;
	var HSIZE = 5003; // 80% occupancy

	// GIF Image compression - modified 'compress'
	// Based on: compress.c - File compression ala IEEE Computer, June 1984.
	// By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
	// Jim McKie (decvax!mcvax!jim)
	// Steve Davies (decvax!vax135!petsd!peora!srd)
	// Ken Turkowski (decvax!decwrl!turtlevax!ken)
	// James A. Woods (decvax!ihnp4!ames!jaw)
	// Joe Orost (decvax!vax135!petsd!joe)

	var n_bits // number of bits/code
	var maxbits = BITS; // user settable max # bits/code
	var maxcode // maximum code, given n_bits
	var maxmaxcode = 1 << BITS; // should NEVER generate this code
	var htab = new Array;
	var codetab = new Array;
	var hsize = HSIZE; // for dynamic table sizing
	var free_ent = 0; // first unused entry

	// block compression parameters -- after all codes are used up,
	// and compression rate changes, start over.

	var clear_flg/*Boolean*/ = false;

	// Algorithm: use open addressing double hashing (no chaining) on the
	// prefix code / next character combination. We do a variant of Knuth's
	// algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
	// secondary probe. Here, the modular division first probe is gives way
	// to a faster exclusive-or manipulation. Also do block compression with
	// an adaptive reset, whereby the code table is cleared when the compression
	// ratio decreases, but after the table fills. The variable-length output
	// codes are re-sized at this point, and a special CLEAR code is generated
	// for the decompressor. Late addition: construct the table according to
	// file size for noticeable speed improvement on small files. Please direct
	// questions about this implementation to ames!jaw.

	var g_init_bits;
	var ClearCode;
	var EOFCode;

	// output
	// Output the given code.
	// Inputs:
	// code: A n_bits-bit integer. If == -1, then EOF. This assumes
	// that n_bits =< wordsize - 1.
	// Outputs:
	// Outputs code to the file.
	// Assumptions:
	// Chars are 8 bits long.
	// Algorithm:
	// Maintain a BITS character long buffer (so that 8 codes will
	// fit in it exactly). Use the VAX insv instruction to insert each
	// code in turn. When the buffer fills up empty it and start over.

	var cur_accum = 0;
	var cur_bits = 0;
	var masks = [ 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF ];

	// Number of characters so far in this 'packet'
	var a_count;

	// Define the storage for the packet accumulator
	var accum = [];

	var LZWEncoder = exports.LZWEncoder = function LZWEncoder (width, height, pixels, color_depth)
	{

		imgW = width;
		imgH = height;
		pixAry = pixels;
		initCodeSize = Math.max(2, color_depth);

	}

	// Add a character to the end of the current packet, and if it is 254
	// characters, flush the packet to disk.
	var char_out = function char_out(c/*Number*/, outs)/*void*/
	{
		accum[a_count++] = c;
		if (a_count >= 254) flush_char(outs);

	}

	// Clear out the hash table
	// table clear for block compress

	var cl_block = function cl_block(outs)/*void*/
	{

		cl_hash(hsize);
		free_ent = ClearCode + 2;
		clear_flg = true;
		output(ClearCode, outs);

	}

	// reset code table
	var cl_hash = function cl_hash(hsize)/*void*/
	{

		for (var i = 0; i < hsize; ++i) htab[i] = -1;

	}

	var compress = exports.compress = function compress(init_bits, outs)/*void*/

	{
		var fcode;
		var i /* = 0 */;
		var c;
		var ent;
		var disp;
		var hsize_reg;
		var hshift;

		// Set up the globals: g_init_bits - initial number of bits
		g_init_bits = init_bits;

		// Set up the necessary values
		clear_flg = false;
		n_bits = g_init_bits;
		maxcode = MAXCODE(n_bits);

		ClearCode = 1 << (init_bits - 1);
		EOFCode = ClearCode + 1;
		free_ent = ClearCode + 2;

		a_count = 0; // clear packet

		ent = nextPixel();

		hshift = 0;
		for (fcode = hsize; fcode < 65536; fcode *= 2)
		  ++hshift;
		hshift = 8 - hshift; // set hash code range bound

		hsize_reg = hsize;
		cl_hash(hsize_reg); // clear hash table

		output(ClearCode, outs);

		outer_loop: while ((c = nextPixel()) != EOF)

		{

			fcode = (c << maxbits) + ent;
			i = (c << hshift) ^ ent; // xor hashing

			if (htab[i] == fcode)
			{
			ent = codetab[i];
			continue;
			} else if (htab[i] >= 0) // non-empty slot
			{
				disp = hsize_reg - i; // secondary hash (after G. Knott)
				if (i == 0)
				disp = 1;
				do
				{

					if ((i -= disp) < 0) i += hsize_reg;

					if (htab[i] == fcode)
					{
					ent = codetab[i];
					continue outer_loop;
					}
				} while (htab[i] >= 0);
			}

			output(ent, outs);
			ent = c;
			if (free_ent < maxmaxcode)
			{
				codetab[i] = free_ent++; // code -> hashtable
				htab[i] = fcode;
			} else cl_block(outs);
		}

		// Put out the final code.
		output(ent, outs);
		output(EOFCode, outs);

	}

	// ----------------------------------------------------------------------------
	var encode = exports.encode = function encode(os)/*void*/
	{
		os.writeByte(initCodeSize); // write "initial code size" byte
		remaining = imgW * imgH; // reset navigation variables
		curPixel = 0;
		compress(initCodeSize + 1, os); // compress and write the pixel data
		os.writeByte(0); // write block terminator

	}

	// Flush the packet to disk, and reset the accumulator
	var flush_char = function flush_char(outs)/*void*/
	{

		if (a_count > 0)
		{
			outs.writeByte(a_count);
			outs.writeBytes(accum, 0, a_count);
			a_count = 0;
		}

	}

	var MAXCODE = function MAXCODE(n_bits)
	{

		return (1 << n_bits) - 1;

	}

	// ----------------------------------------------------------------------------
	// Return the next pixel from the image
	// ----------------------------------------------------------------------------

	var nextPixel = function nextPixel()
	{

		if (remaining == 0) return EOF;

		--remaining;

		var pix/*Number*/ = pixAry[curPixel++];

		return pix & 0xff;

	}

	var output = function output(code, outs)/*void*/

	{
		cur_accum &= masks[cur_bits];

		if (cur_bits > 0) cur_accum |= (code << cur_bits);
		else cur_accum = code;

		cur_bits += n_bits;

		while (cur_bits >= 8)

		{

			char_out((cur_accum & 0xff), outs);
			cur_accum >>= 8;
			cur_bits -= 8;

		}

		// If the next entry is going to be too big for the code size,
		// then increase it, if possible.

		if (free_ent > maxcode || clear_flg)
		{

			if (clear_flg)
			{

				maxcode = MAXCODE(n_bits = g_init_bits);
				clear_flg = false;

			} else
			{

				++n_bits;

				if (n_bits == maxbits) maxcode = maxmaxcode;

				else maxcode = MAXCODE(n_bits);

			}

		}

		if (code == EOFCode)
		{

			// At EOF, write the rest of the buffer.
			while (cur_bits > 0)
			{

				char_out((cur_accum & 0xff), outs);
				cur_accum >>= 8;
				cur_bits -= 8;
			}

			flush_char(outs);

		}

	}
	LZWEncoder.apply(this, arguments);
   return exports;
}
<commit_msg>Remove 'boolean' type comment.<commit_after>/**
* This class handles LZW encoding
* Adapted from Jef Poskanzer's Java port by way of J. M. G. Elliott.
* @author Kevin Weiner (original Java version - kweiner@fmsware.com)
* @author Thibault Imbert (AS3 version - bytearray.org)
* @version 0.1 AS3 implementation
*/

LZWEncoder = function()
{
    var exports = {};
	var EOF = -1;
	var imgW;
	var imgH
	var pixAry;
	var initCodeSize;
	var remaining;
	var curPixel;

	// GIFCOMPR.C - GIF Image compression routines
	// Lempel-Ziv compression based on 'compress'. GIF modifications by
	// David Rowley (mgardi@watdcsu.waterloo.edu)
	// General DEFINEs

	var BITS = 12;
	var HSIZE = 5003; // 80% occupancy

	// GIF Image compression - modified 'compress'
	// Based on: compress.c - File compression ala IEEE Computer, June 1984.
	// By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
	// Jim McKie (decvax!mcvax!jim)
	// Steve Davies (decvax!vax135!petsd!peora!srd)
	// Ken Turkowski (decvax!decwrl!turtlevax!ken)
	// James A. Woods (decvax!ihnp4!ames!jaw)
	// Joe Orost (decvax!vax135!petsd!joe)

	var n_bits // number of bits/code
	var maxbits = BITS; // user settable max # bits/code
	var maxcode // maximum code, given n_bits
	var maxmaxcode = 1 << BITS; // should NEVER generate this code
	var htab = new Array;
	var codetab = new Array;
	var hsize = HSIZE; // for dynamic table sizing
	var free_ent = 0; // first unused entry

	// block compression parameters -- after all codes are used up,
	// and compression rate changes, start over.

	var clear_flg = false;

	// Algorithm: use open addressing double hashing (no chaining) on the
	// prefix code / next character combination. We do a variant of Knuth's
	// algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
	// secondary probe. Here, the modular division first probe is gives way
	// to a faster exclusive-or manipulation. Also do block compression with
	// an adaptive reset, whereby the code table is cleared when the compression
	// ratio decreases, but after the table fills. The variable-length output
	// codes are re-sized at this point, and a special CLEAR code is generated
	// for the decompressor. Late addition: construct the table according to
	// file size for noticeable speed improvement on small files. Please direct
	// questions about this implementation to ames!jaw.

	var g_init_bits;
	var ClearCode;
	var EOFCode;

	// output
	// Output the given code.
	// Inputs:
	// code: A n_bits-bit integer. If == -1, then EOF. This assumes
	// that n_bits =< wordsize - 1.
	// Outputs:
	// Outputs code to the file.
	// Assumptions:
	// Chars are 8 bits long.
	// Algorithm:
	// Maintain a BITS character long buffer (so that 8 codes will
	// fit in it exactly). Use the VAX insv instruction to insert each
	// code in turn. When the buffer fills up empty it and start over.

	var cur_accum = 0;
	var cur_bits = 0;
	var masks = [ 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF ];

	// Number of characters so far in this 'packet'
	var a_count;

	// Define the storage for the packet accumulator
	var accum = [];

	var LZWEncoder = exports.LZWEncoder = function LZWEncoder (width, height, pixels, color_depth)
	{

		imgW = width;
		imgH = height;
		pixAry = pixels;
		initCodeSize = Math.max(2, color_depth);

	}

	// Add a character to the end of the current packet, and if it is 254
	// characters, flush the packet to disk.
	var char_out = function char_out(c/*Number*/, outs)/*void*/
	{
		accum[a_count++] = c;
		if (a_count >= 254) flush_char(outs);

	}

	// Clear out the hash table
	// table clear for block compress

	var cl_block = function cl_block(outs)/*void*/
	{

		cl_hash(hsize);
		free_ent = ClearCode + 2;
		clear_flg = true;
		output(ClearCode, outs);

	}

	// reset code table
	var cl_hash = function cl_hash(hsize)/*void*/
	{

		for (var i = 0; i < hsize; ++i) htab[i] = -1;

	}

	var compress = exports.compress = function compress(init_bits, outs)/*void*/

	{
		var fcode;
		var i /* = 0 */;
		var c;
		var ent;
		var disp;
		var hsize_reg;
		var hshift;

		// Set up the globals: g_init_bits - initial number of bits
		g_init_bits = init_bits;

		// Set up the necessary values
		clear_flg = false;
		n_bits = g_init_bits;
		maxcode = MAXCODE(n_bits);

		ClearCode = 1 << (init_bits - 1);
		EOFCode = ClearCode + 1;
		free_ent = ClearCode + 2;

		a_count = 0; // clear packet

		ent = nextPixel();

		hshift = 0;
		for (fcode = hsize; fcode < 65536; fcode *= 2)
		  ++hshift;
		hshift = 8 - hshift; // set hash code range bound

		hsize_reg = hsize;
		cl_hash(hsize_reg); // clear hash table

		output(ClearCode, outs);

		outer_loop: while ((c = nextPixel()) != EOF)

		{

			fcode = (c << maxbits) + ent;
			i = (c << hshift) ^ ent; // xor hashing

			if (htab[i] == fcode)
			{
			ent = codetab[i];
			continue;
			} else if (htab[i] >= 0) // non-empty slot
			{
				disp = hsize_reg - i; // secondary hash (after G. Knott)
				if (i == 0)
				disp = 1;
				do
				{

					if ((i -= disp) < 0) i += hsize_reg;

					if (htab[i] == fcode)
					{
					ent = codetab[i];
					continue outer_loop;
					}
				} while (htab[i] >= 0);
			}

			output(ent, outs);
			ent = c;
			if (free_ent < maxmaxcode)
			{
				codetab[i] = free_ent++; // code -> hashtable
				htab[i] = fcode;
			} else cl_block(outs);
		}

		// Put out the final code.
		output(ent, outs);
		output(EOFCode, outs);

	}

	// ----------------------------------------------------------------------------
	var encode = exports.encode = function encode(os)/*void*/
	{
		os.writeByte(initCodeSize); // write "initial code size" byte
		remaining = imgW * imgH; // reset navigation variables
		curPixel = 0;
		compress(initCodeSize + 1, os); // compress and write the pixel data
		os.writeByte(0); // write block terminator

	}

	// Flush the packet to disk, and reset the accumulator
	var flush_char = function flush_char(outs)/*void*/
	{

		if (a_count > 0)
		{
			outs.writeByte(a_count);
			outs.writeBytes(accum, 0, a_count);
			a_count = 0;
		}

	}

	var MAXCODE = function MAXCODE(n_bits)
	{

		return (1 << n_bits) - 1;

	}

	// ----------------------------------------------------------------------------
	// Return the next pixel from the image
	// ----------------------------------------------------------------------------

	var nextPixel = function nextPixel()
	{

		if (remaining == 0) return EOF;

		--remaining;

		var pix/*Number*/ = pixAry[curPixel++];

		return pix & 0xff;

	}

	var output = function output(code, outs)/*void*/

	{
		cur_accum &= masks[cur_bits];

		if (cur_bits > 0) cur_accum |= (code << cur_bits);
		else cur_accum = code;

		cur_bits += n_bits;

		while (cur_bits >= 8)

		{

			char_out((cur_accum & 0xff), outs);
			cur_accum >>= 8;
			cur_bits -= 8;

		}

		// If the next entry is going to be too big for the code size,
		// then increase it, if possible.

		if (free_ent > maxcode || clear_flg)
		{

			if (clear_flg)
			{

				maxcode = MAXCODE(n_bits = g_init_bits);
				clear_flg = false;

			} else
			{

				++n_bits;

				if (n_bits == maxbits) maxcode = maxmaxcode;

				else maxcode = MAXCODE(n_bits);

			}

		}

		if (code == EOFCode)
		{

			// At EOF, write the rest of the buffer.
			while (cur_bits > 0)
			{

				char_out((cur_accum & 0xff), outs);
				cur_accum >>= 8;
				cur_bits -= 8;
			}

			flush_char(outs);

		}

	}
	LZWEncoder.apply(this, arguments);
   return exports;
}
<|endoftext|>


<commit_before>var jsmin = require('jsmin-sourcemap'),
    path = require('path');
module.exports = function (grunt) {
  grunt.registerMultiTask('jsmin-sourcemap', 'Generate minified JavaScript and sourcemap from files', function () {
    // Grab the files to minify
    var file = this.file,
        data = this.data,
        cwd = data.cwd || '.',
        srcFile = file.src,
        srcFiles = grunt.file.expand({'cwd': cwd}, srcFile);

    // Map each file into a JSMin input
    var input = srcFiles.map(function (file) {
      var filepath = path.join(cwd, file),
          code = grunt.file.read(filepath),
          src = file;
      return {'code': code, 'src': src};
    });

    // Grab the destFile and destMap paths, if it does not exist fallback to destFile + '.map'
    var destFile = path.join(cwd, file.dest),
        destMap = data.destMap;
    if (destMap !== undefined) {
      // Interpolate the map via grunt.template
      destMap = grunt.template.process(destMap);

      // Join it together with the cwd
      destMap = path.join(cwd, destMap);
    } else {
      destMap = destFile + ".map";
    }

    // Determine the relative dest and relative map path (trim off the first ../ since URL's don't need that)
    var relDestPath = path.relative(destFile, destMap),
        relMapPath = path.relative(destFile, destMap);
    relDestPath = relDestPath.replace('../', '');
    relMapPath = relMapPath.replace('../', '');

    // Minify the input
    var retObj = jsmin({
          'input': input,
          'dest': relDestPath,
          'srcRoot': data.srcRoot
        });

    // Grab the minified code
    var code = retObj.code;

    // Append a sourceMappingURL to the code
    code = code + '\n//@ sourceMappingURL=' + relMapPath;

    // Write out the code and map
    grunt.file.write(destFile, code);
    grunt.file.write(destMap, retObj.sourcemap);
  });
};<commit_msg>Corrected the relative paths for destFile and Map<commit_after>var jsmin = require('jsmin-sourcemap'),
    path = require('path');
module.exports = function (grunt) {
  grunt.registerMultiTask('jsmin-sourcemap', 'Generate minified JavaScript and sourcemap from files', function () {
    // Grab the files to minify
    var file = this.file,
        data = this.data,
        cwd = data.cwd || '.',
        srcFile = file.src,
        srcFiles = grunt.file.expand({'cwd': cwd}, srcFile);

    // Map each file into a JSMin input
    var input = srcFiles.map(function (file) {
      var filepath = path.join(cwd, file),
          code = grunt.file.read(filepath),
          src = file;
      return {'code': code, 'src': src};
    });

    // Grab the destFile and destMap paths, if it does not exist fallback to destFile + '.map'
    var destFile = path.join(cwd, file.dest),
        destMap = data.destMap;
    if (destMap !== undefined) {
      // Interpolate the map via grunt.template
      destMap = grunt.template.process(destMap);

      // Join it together with the cwd
      destMap = path.join(cwd, destMap);
    } else {
      destMap = destFile + ".map";
    }

    // Determine the relative dest and relative map path (trim off the first ../ since URL's don't need that)
    var relDestPath = path.relative(path.dirname(destMap), path.dirname(destFile)),
        relMapPath = path.relative(path.dirname(destFile), path.dirname(destMap));

    // Minify the input
    var retObj = jsmin({
          'input': input,
          'dest': path.join(relDestPath, path.basename(destFile)),
          'srcRoot': data.srcRoot
        });

    // Grab the minified code
    var code = retObj.code;

    // Append a sourceMappingURL to the code
    code = code + '\n//@ sourceMappingURL=' + path.join(relMapPath, path.basename(destMap));

    // Write out the code and map
    grunt.file.write(destFile, code);
    grunt.file.write(destMap, retObj.sourcemap);
  });
};<|endoftext|>


<commit_before>/* @flow */
'use strict';

import React from 'react';
import {View, Platform} from 'react-native';
import NativeBaseComponent from '../Base/NativeBaseComponent';
import computeProps from '../../Utils/computeProps';
import Button from "./Button";
import Title from "./Title";
import InputGroup from "./InputGroup";
import Subtitle from "./Subtitle";
import _ from 'lodash';

export default class Header extends NativeBaseComponent {

    getInitialStyle() {
        return {
            navbar: {
                backgroundColor: this.getTheme().toolbarDefaultBg,
                justifyContent: (!Array.isArray(this.props.children)) ? 'center' : 'space-between',
                flexDirection: 'row',
                alignItems: 'center',
                paddingHorizontal: 15,
                paddingTop: (Platform.OS === 'ios' ) ? 15 : 0,
                shadowColor: '#000',
                shadowOffset: {width: 0, height: 2},
                shadowOpacity: 0.1,
                shadowRadius: 1.5,
                height: this.getTheme().toolbarHeight,
                elevation: 2
            },
            iosToolbarSearch: {
                backgroundColor: this.getTheme().toolbarInputColor,
                borderRadius: this.props.rounded ? 25 : 2,
                height: 30,
                borderColor: 'transparent'
            },
            androidToolbarSearch: {
                backgroundColor: "#fff",
                borderRadius: 2,
                borderColor: 'transparent',
                elevation: 2
            }
        }
    }

    prepareRootProps() {

        var defaultProps = {
            style: this.getInitialStyle().navbar
        };

        return computeProps(this.props, defaultProps);

    }
    renderChildren() {
        if(!Array.isArray(this.props.children)) {
            return this.props.children;
        }

        else if (Array.isArray(this.props.children)) {
            var newChildren = [];
            var childrenArray = React.Children.toArray(this.props.children);

            var buttons = [];
            buttons = _.remove(childrenArray, function(item) {
                if(item.type == Button) {
                    return true;
                }
            });

            var title = [];
            title = _.remove(childrenArray, function(item) {
                if(item.type == Title) {
                    return true;
                }
            });

            var subtitle = [];
            subtitle = _.remove(childrenArray, function(item) {
                if(item.type == Subtitle) {
                    return true;
                }
            });

            var input = [];
            input = _.remove(childrenArray, function(item) {
                if(item.type == InputGroup) {
                    return true;
                }
            });

            if (this.props.searchBar) {
                if (Platform.OS === 'ios') {
                    newChildren.push(<View key='search' style={{flex: 1, alignSelf: 'stretch', alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -7}}>
                                        {React.cloneElement(input[0],{style: this.getInitialStyle().iosToolbarSearch, toolbar : true, key : 'inp'})}
                                    </View>)
                    newChildren.push(<View key='searchBtn' style={{alignItems: 'center', justifyContent: 'center', flexDirection: 'row', marginRight: -14}}>
                                        {React.cloneElement(buttons[0], {color: this.getTheme().iosToolbarBtnColor})}
                                    </View>)
                } else {
                    newChildren.push(<View key='search' style={{flex: 1,alignItems: 'center', paddingBottom: 4, justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -8, marginRight: -8}}>
                                        {React.cloneElement(input[0],{style: this.getInitialStyle().androidToolbarSearch, atoolbar : true})}
                                    </View>)
                }
            }
            else {
                if (Platform.OS === 'ios') {
                    newChildren.push(<View key='btn1' style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -14}}>
                                        {React.cloneElement(buttons[0], {color: this.getTheme().iosToolbarBtnColor})}
                                    </View>)
                    newChildren.push(<View key='title' style={{flex: 3, alignSelf: 'center', justifyContent: 'space-between'}}>
                                        {[title[0],subtitle[0]]}
                                    </View>)
                    for (let i = 1; i < buttons.length; i++) {
                        newChildren.push(<View key={'btn' + (i+1)} style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginRight: -14}}>
                                            {React.cloneElement(buttons[i], {color: this.getTheme().iosToolbarBtnColor})}
                                        </View>)
                    }
                } else {
                    newChildren.push(<View key='btn1' style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -10, marginRight: 12}}>
                                        {buttons[0]}
                                    </View>)
                    newChildren.push(<View key='title' style={{flex: 3, alignSelf: 'stretch'}}>
                                        {[title[0]]}
                                    </View>)
                    for (let i = 1; i < buttons.length; i++) {
                        newChildren.push(<View key={'btn' + (i+1)} style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginRight: -7}}>
                                            {buttons[i]}
                                        </View>)

                    }
                }

            }
          return newChildren;
        }
    }

    render() {
        return(
            <View {...this.prepareRootProps()} >
                {this.renderChildren()}
            </View>
        );
    }
}
<commit_msg>header fix<commit_after>/* @flow */
'use strict';

import React from 'react';
import {View, Platform} from 'react-native';
import NativeBaseComponent from '../Base/NativeBaseComponent';
import computeProps from '../../Utils/computeProps';
import Button from "./Button";
import Title from "./Title";
import InputGroup from "./InputGroup";
import Subtitle from "./Subtitle";
import _ from 'lodash';

export default class Header extends NativeBaseComponent {

    getInitialStyle() {
        return {
            navbar: {
                backgroundColor: this.getTheme().toolbarDefaultBg,
                justifyContent: (!Array.isArray(this.props.children)) ? 'center' : 'space-between',
                flexDirection: 'row',
                alignItems: 'center',
                paddingHorizontal: 15,
                paddingTop: (Platform.OS === 'ios' ) ? 15 : 0,
                shadowColor: '#000',
                shadowOffset: {width: 0, height: 2},
                shadowOpacity: 0.1,
                shadowRadius: 1.5,
                height: this.getTheme().toolbarHeight,
                elevation: 2
            },
            iosToolbarSearch: {
                backgroundColor: this.getTheme().toolbarInputColor,
                borderRadius: this.props.rounded ? 25 : 2,
                height: 30,
                borderColor: 'transparent'
            },
            androidToolbarSearch: {
                backgroundColor: "#fff",
                borderRadius: 2,
                borderColor: 'transparent',
                elevation: 2
            }
        }
    }

    prepareRootProps() {

        var defaultProps = {
            style: this.getInitialStyle().navbar
        };

        return computeProps(this.props, defaultProps);

    }
    renderChildren() {
        if(!Array.isArray(this.props.children)) {
            return this.props.children;
        }

        else if (Array.isArray(this.props.children)) {
            var newChildren = [];
            var childrenArray = React.Children.toArray(this.props.children);

            var buttons = [];
            buttons = _.remove(childrenArray, function(item) {
                if(item.type == Button) {
                    return true;
                }
            });

            var title = [];
            title = _.remove(childrenArray, function(item) {
                if(item.type == Title) {
                    return true;
                }
            });

            var subtitle = [];
            subtitle = _.remove(childrenArray, function(item) {
                if(item.type == Subtitle) {
                    return true;
                }
            });

            var input = [];
            input = _.remove(childrenArray, function(item) {
                if(item.type == InputGroup) {
                    return true;
                }
            });

            if (this.props.searchBar) {
                if (Platform.OS === 'ios') {
                    newChildren.push(<View key='search' style={{flex: 1, alignSelf: 'stretch', alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -7}}>
                                        {React.cloneElement(input[0],{style: this.getInitialStyle().iosToolbarSearch, toolbar : true, key : 'inp'})}
                                    </View>)
                    newChildren.push(<View key='searchBtn' style={{alignItems: 'center', justifyContent: 'center', flexDirection: 'row', marginRight: -14}}>
                                        {React.cloneElement(buttons[0], {color: this.getTheme().iosToolbarBtnColor})}
                                    </View>)
                } else {
                    newChildren.push(<View key='search' style={{flex: 1,alignItems: 'center', paddingBottom: 4, justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -8, marginRight: -8}}>
                                        {React.cloneElement(input[0],{style: this.getInitialStyle().androidToolbarSearch, atoolbar : true})}
                                    </View>)
                }
            }
            else {
                if (Platform.OS === 'ios') {
                    newChildren.push(<View key='btn1' style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -14}}>
                                        {React.cloneElement(buttons[0], {color: this.getTheme().iosToolbarBtnColor})}
                                    </View>)
                    newChildren.push(<View key='title' style={{flex: 3, alignSelf: 'center', justifyContent: 'space-between'}}>
                                        {[title[0],subtitle[0]]}
                                    </View>)
                    for (let i = 1; i < buttons.length; i++) {
                        newChildren.push(<View key={'btn' + (i+1)} style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginRight: -14}}>
                                            {React.cloneElement(buttons[i], {color: this.getTheme().iosToolbarBtnColor})}
                                        </View>)
                    }
                } else {
                    newChildren.push(<View key='btn1' style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -10, marginRight: 12}}>
                                        {buttons[0]}
                                    </View>)
                    newChildren.push(<View key='title' style={{flex: 3, alignSelf: 'stretch', justifyContent: 'center'}}>
                                        {[title[0]]}
                                    </View>)
                    for (let i = 1; i < buttons.length; i++) {
                        newChildren.push(<View key={'btn' + (i+1)} style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginRight: -7}}>
                                            {buttons[i]}
                                        </View>)

                    }
                }

            }
          return newChildren;
        }
    }

    render() {
        return(
            <View {...this.prepareRootProps()} >
                {this.renderChildren()}
            </View>
        );
    }
}
<|endoftext|>


<commit_before>(function (factory){
  // CommonJS Module
  if (typeof module !== 'undefined' && module.exports){
    module.exports = factory(require('jquery'), require('queue-async'));
  // AMD module
  } else if ( typeof define === 'function' && define.amd ) {
    define(['jquery', 'queue'], factory);
  // Browser globals
  } else {
    factory(jQuery, queue)
  }
})(function ($, queue) {

    $.fn.canvid = function(_opts) {
        var el = $(this),
            images = {},
            firstPlay = true,
            control = {
                play: function() { console.log('cannot play before images are loaded'); }
            };

        _opts = $.extend(el.data(), _opts || {});

        if (hasCanvas()) {
            // preload videos images
            var q = queue(4);

            for(var key in _opts.videos){
                var video = _opts.videos[key];
                q.defer(loadImage, key, video.src);
            }

            q.awaitAll(function(err) {
                if (err) return console.warn('error while loading video sources', err);

                var ctx = initCanvas(),
                    requestAnimationFrame = reqAnimFrame();

                control.play = function(key, reverse) {
                    if (control.pause) control.pause(); // pause current vid

                    var img = images[key],
                        opts = _opts.videos[key];

                    var curFrame = reverse ? opts.frames-1 : 0,
                        wait = 0,
                        playing = true,
                        loops = 0,
                        delay = 4;

                    requestAnimationFrame(frame);

                    control.resume = function() {
                        playing = true;
                        requestAnimationFrame(frame);
                    };

                    control.pause = function() {
                        playing = false;
                        requestAnimationFrame(frame);
                    };

                    if (firstPlay) {
                        firstPlay = false;
                        $(':not(canvas.canvid)', el).hide();
                    }

                    function frame() {
                        if (!wait) {
                            drawFrame(curFrame);
                            curFrame = (+curFrame + (reverse ? -1 : 1));
                            if (curFrame < 0) curFrame += +opts.frames;
                            if (curFrame >= opts.frames) curFrame -= opts.frames;
                            if (reverse ? curFrame == opts.frames-1 : !curFrame) loops++;
                            if (opts.loops && loops >= opts.loops) playing = false;
                        }
                        wait = (wait+1) % ((reverse ? 0.5 : 1) * delay);
                        if (playing && opts.frames > 1) requestAnimationFrame(frame);
                    }

                    function drawFrame(f) {
                        var fx = Math.floor(f % opts.cols) * _opts.width,
                            fy = Math.floor(f / opts.cols) * _opts.height;
                        ctx.clearRect(0, 0, _opts.width, _opts.height); // clear frame
                        ctx.drawImage(img, fx, fy, _opts.width, _opts.height, 0,0, _opts.width, _opts.height);
                    }

                }; // end control.play

                if ($.isFunction(_opts.loaded)) _opts.loaded(control);

            }); // end awaitAll

        } else if (opts.srcGif) {
            el.append('');
        }

        function loadImage(key, url, callback) {
            var img = images[key] = new Image();
            img.onload = function() { callback(null); };
            img.src = url;
        }

        function initCanvas() {
            var canvas = $('<canvas />')
                .attr('width', _opts.width)
                .attr('class', 'canvid')
                .attr('height', _opts.height)
                .appendTo(el);
            return canvas.get(0).getContext('2d');
        }

        function reqAnimFrame() {
            return window.requestAnimationFrame
                || window.webkitRequestAnimationFrame
                || window.mozRequestAnimationFrame
                || window.msRequestAnimationFrame
                || function(callback) { return setTimeout(callback, 1000 / 60); };
        }

        function hasCanvas() {
            // taken from Modernizr
            var elem = document.createElement('canvas');
            return !!(elem.getContext && elem.getContext('2d'));
        }

        return control;
    };

});
<commit_msg>add framewidth and frameheight options<commit_after>(function (factory){
  // CommonJS Module
  if (typeof module !== 'undefined' && module.exports){
    module.exports = factory(require('jquery'), require('queue-async'));
  // AMD module
  } else if ( typeof define === 'function' && define.amd ) {
    define(['jquery', 'queue'], factory);
  // Browser globals
  } else {
    factory(jQuery, queue)
  }
})(function ($, queue) {

    $.fn.canvid = function(_opts) {
        var el = $(this),
            images = {},
            firstPlay = true,
            control = {
                play: function() { console.log('cannot play before images are loaded'); }
            };

        _opts = $.extend(el.data(), _opts || {});

        if (hasCanvas()) {
            // preload videos images
            var q = queue(4);

            for(var key in _opts.videos){
                var video = _opts.videos[key];
                q.defer(loadImage, key, video.src);
            }

            q.awaitAll(function(err) {
                if (err) return console.warn('error while loading video sources', err);

                var ctx = initCanvas(),
                    requestAnimationFrame = reqAnimFrame();

                control.play = function(key, reverse) {
                    if (control.pause) control.pause(); // pause current vid

                    var img = images[key],
                        opts = _opts.videos[key],
                        frameWidth = opts.frameWidth || _opts.width,
                        frameHeight = opts.frameHeight || _opts.height;

                    var curFrame = reverse ? opts.frames-1 : 0,
                        wait = 0,
                        playing = true,
                        loops = 0,
                        delay = 4;

                    requestAnimationFrame(frame);

                    control.resume = function() {
                        playing = true;
                        requestAnimationFrame(frame);
                    };

                    control.pause = function() {
                        playing = false;
                        requestAnimationFrame(frame);
                    };

                    if (firstPlay) {
                        firstPlay = false;
                        $(':not(canvas.canvid)', el).hide();
                    }

                    function frame() {
                        if (!wait) {
                            drawFrame(curFrame);
                            curFrame = (+curFrame + (reverse ? -1 : 1));
                            if (curFrame < 0) curFrame += +opts.frames;
                            if (curFrame >= opts.frames) curFrame -= opts.frames;
                            if (reverse ? curFrame == opts.frames-1 : !curFrame) loops++;
                            if (opts.loops && loops >= opts.loops) playing = false;
                        }
                        wait = (wait+1) % ((reverse ? 0.5 : 1) * delay);
                        if (playing && opts.frames > 1) requestAnimationFrame(frame);
                    }

                    function drawFrame(f) {
                        var fx = Math.floor(f % opts.cols) * frameWidth,
                            fy = Math.floor(f / opts.cols) * frameHeight;
                        ctx.clearRect(0, 0, _opts.width, _opts.height); // clear frame
                        ctx.drawImage(img, fx, fy, frameWidth, frameHeight, 0,0, _opts.width, _opts.height);
                    }

                }; // end control.play

                if ($.isFunction(_opts.loaded)) _opts.loaded(control);

            }); // end awaitAll

        } else if (opts.srcGif) {
            el.append('');
        }

        function loadImage(key, url, callback) {
            var img = images[key] = new Image();
            img.onload = function() { callback(null); };
            img.src = url;
        }

        function initCanvas() {
            var canvas = $('<canvas />')
                .attr('width', _opts.width)
                .attr('class', 'canvid')
                .attr('height', _opts.height)
                .appendTo(el);
            return canvas.get(0).getContext('2d');
        }

        function reqAnimFrame() {
            return window.requestAnimationFrame
                || window.webkitRequestAnimationFrame
                || window.mozRequestAnimationFrame
                || window.msRequestAnimationFrame
                || function(callback) { return setTimeout(callback, 1000 / 60); };
        }

        function hasCanvas() {
            // taken from Modernizr
            var elem = document.createElement('canvas');
            return !!(elem.getContext && elem.getContext('2d'));
        }

        return control;
    };
});<|endoftext|>


<commit_before>/**
 * @module ember-flexberry
 */

import Ember from 'ember';

const { getOwner } = Ember;

/**
 * Base component for Flexberry Ember UI Components.
 *
 * @class FlexberryBaseComponent
 */
export default Ember.Component.extend({
  /**
   * Flag: indicates whether component is readonly.
   *
   * @property readonly
   * @type Boolean
   * @default false
   */
  readonly: false,

  /**
   * Flag: indicates whether component is required.
   *
   * @property required
   * @type Boolean
   * @default false
   */
  required: false,

  /**
   * Unique name of the component.
   * TODO: use guidFor from 'ember-metal/utils'
   *
   * @property componentName
   * @type String
   * @default undefined
   */
  componentName: undefined,

  /**
   * Component dynamic properties ({ componentPropertyName: value }).
   * Used when component renderes dynamicly with ember {{component}} helper:
   * {{component 'my-component' value=value dynamicProperties=myConponentProperties}}.
   * In the end of component initializetion its properties values will be replaced with values from this object.
   *
   * @property dynamicProperties
   * @type Object
   * @default null
   */
  dynamicProperties: null,

  /**
   * Model to which current component's value is related.
   *
   * @property relatedModel
   * @type DS.Model
   * @default null
   */
  relatedModel: null,

  /**
   * Path to component's settings in application configuration (JSON from ./config/environment.js).
   *
   * @property appConfigSettingsPath
   * @type String
   * @default 'APP.components.flexberryBaseComponent'
   */
  appConfigSettingsPath: 'APP.components.flexberryBaseComponent',

  /**
   * Application configuration (JSON from ./config/environment.js).
   *
   * @property appConfig
   * @type Object
   */
  appConfig: null,

  /**
   * Component settings object from application configuration (part of JSON from ./config/environment.js).
   * Part of appConfig related to appConfigSettingsPath.
   *
   * @property appConfigSettings
   * @type Object
   */
  appConfigSettings: null,

  /**
   * Current controller.
   * @property currentController
   * @type Ember.Controller
   */
  currentController: null,

  /**
   * Initializes component properties.
   */
  init: function() {
    this._super(...arguments);

    // Get and remember current controller.
    var currentController = this.getTargetObjectByCondition(function(targetObject) {
      return targetObject instanceof Ember.Controller;
    });
    this.set('currentController', currentController);

    // Set related model.
    var relatedModel = this.get('relatedModel');
    if (Ember.isNone(relatedModel) && !Ember.isNone(currentController)) {
      relatedModel = currentController.get('model');
      this.set('relatedModel', relatedModel);
    }

    // Import application config\environment.
    var appConfig = getOwner(this)._lookupFactory('config:environment');
    if (!Ember.isNone(appConfig)) {
      this.set('appConfig', appConfig);
    }

    var appConfigSettingsPath = this.get('appConfigSettingsPath');
    if (Ember.typeOf(appConfigSettingsPath) === 'string') {
      var appConfigSettings = Ember.get(appConfig, appConfigSettingsPath);
      if (!Ember.isNone(appConfigSettings)) {
        this.set('appConfigSettings', appConfigSettings);
      }
    }

    var dynamicProperties = this.get('dynamicProperties');
    if (Ember.typeOf(dynamicProperties) !== 'object') {
      return;
    }

    // Initialize properties for dynamicly-rendered component.
    for (var propertyName in dynamicProperties) {
      if (dynamicProperties.hasOwnProperty(propertyName)) {
        this.set(propertyName, dynamicProperties[propertyName]);
      }
    }
  },

  /**
   * Initializes DOM-related component properties.
   */
  didInsertElement: function() {
    this._super(...arguments);
  },

  /**
   * Cleanup component.
   */
  willDestroy: function() {
    this._super(...arguments);
  },

  /**
   * Cleanup DOM-related component stuff.
   */
  willDestroyElement: function() {
    this._super(...arguments);
  },

  /**
   * Initializes component's property with recpect to following priority:
   * 1 - template-defined parameters,
   * 2 - applicaion configuration-defined parameters (JSON from ./config/environment by path defined in 'appConfigSettingsPath' property),
   * 3 - component-defined defaults.
   * Note! It is important to be declared as undefined for those component properties, which will be initialized through 'initProperty' call.
   *
   * ```javascript
   * // Possible ./config/environment.js.
   * module.exports = function(environment) {
   *   APP: {
   *     components: {
   *       myComponent: {
   *         myComponentProperty: 'myComponentProperty config-defined default value'
   *       }
   *     }
   *   }
   }
   * });
   *
   * var myComponent = FlexberryBaseComponent.extend({
   *   appConfigSettingsPath: 'APP.components.myComponent',
   *
   *   myComponentProperty: undefined,
   *
   *   init: function() {
   *     this._super.apply(this, arguments);
   *     this.initProperty({ propertyName: 'myComponentProperty', defaultValue: 'myComponentProperty default value' });
   *   }
   * });
   * ```
   *
   * @param {Object} options Method options.
   * @param {String} options.propertyName Component's property name.
   * @param {*} options.defaultValue Component's property default value (from component defined default's).
   */
  initProperty: function(options) {
    options = options || {};
    if (Ember.typeOf(options.propertyName) !== 'string') {
      return;
    }

    // If property value is already defined in template,
    // then we should break property initialization.
    var componentDefinedPropertyValue = this.get(options.propertyName);
    if (Ember.typeOf(componentDefinedPropertyValue) !== 'undefined') {
      return;
    }

    // Property value is not defined in template,
    // then we should set configuration-defined value or default.
    var configDefinedPropertyValue;
    var appConfigSettings = this.get('appConfigSettings');
    if (!Ember.isNone(appConfigSettings)) {
      configDefinedPropertyValue = Ember.get(appConfigSettings, options.propertyName);
    }

    if (Ember.typeOf(configDefinedPropertyValue) !== 'undefined') {
      this.set(options.propertyName, configDefinedPropertyValue);
    } else {
      this.set(options.propertyName, options.defaultValue);
    }
  },

  /**
   * Returns that 'targetObject' (from 'targetObject's hierarchy) which satisfies a given condition.
   *
   * ```javascript
   * var controller = this.getTargetObjectByCondition(function(targetObject) {
   *   return targetObject instanceof Ember.Controller;
   * });
   * ```
   *
   * @method getTargetObjectByCondition.
   * @param {Function} condition Callback-function, which will be called for each 'targetObject' in 'targetObject's hierarchy,
   * until callback return true for one of them.
   * @return {null|Ember.Component|Ember.Controller} Target object which satisfies a given condition or null.
   */
  getTargetObjectByCondition: function(condition) {
    if (Ember.typeOf(condition) !== 'function') {
      return null;
    }

    // Component's 'targetObject' is parent component or a controller (in the end of components hierarchy).
    // Search until 'targetObject' is none or condition is true.
    var targetObject = this.get('targetObject');
    while (!(Ember.isNone(targetObject) || condition(targetObject))) {
      targetObject = targetObject.get('targetObject');
    }

    return targetObject;
  }
});
<commit_msg>Fix typos<commit_after>/**
 * @module ember-flexberry
 */

import Ember from 'ember';

const { getOwner } = Ember;

/**
 * Base component for Flexberry Ember UI Components.
 *
 * @class FlexberryBaseComponent
 */
export default Ember.Component.extend({
  /**
   * Flag: indicates whether component is readonly.
   *
   * @property readonly
   * @type Boolean
   * @default false
   */
  readonly: false,

  /**
   * Flag: indicates whether component is required.
   *
   * @property required
   * @type Boolean
   * @default false
   */
  required: false,

  /**
   * Unique name of the component.
   * TODO: use guidFor from 'ember-metal/utils'
   *
   * @property componentName
   * @type String
   * @default undefined
   */
  componentName: undefined,

  /**
   * Component dynamic properties ({ componentPropertyName: value }).
   * Used when component renders dynamically with ember {{component}} helper:
   * {{component 'my-component' value=value dynamicProperties=myConponentProperties}}.
   * In the end of component initialization its properties values will be replaced with values from this object.
   *
   * @property dynamicProperties
   * @type Object
   * @default null
   */
  dynamicProperties: null,

  /**
   * Model to which current component's value is related.
   *
   * @property relatedModel
   * @type DS.Model
   * @default null
   */
  relatedModel: null,

  /**
   * Path to component's settings in application configuration (JSON from ./config/environment.js).
   *
   * @property appConfigSettingsPath
   * @type String
   * @default 'APP.components.flexberryBaseComponent'
   */
  appConfigSettingsPath: 'APP.components.flexberryBaseComponent',

  /**
   * Application configuration (JSON from ./config/environment.js).
   *
   * @property appConfig
   * @type Object
   */
  appConfig: null,

  /**
   * Component settings object from application configuration (part of JSON from ./config/environment.js).
   * Part of appConfig related to appConfigSettingsPath.
   *
   * @property appConfigSettings
   * @type Object
   */
  appConfigSettings: null,

  /**
   * Current controller.
   * @property currentController
   * @type Ember.Controller
   */
  currentController: null,

  /**
   * Initializes component properties.
   */
  init: function() {
    this._super(...arguments);

    // Get and remember current controller.
    var currentController = this.getTargetObjectByCondition(function(targetObject) {
      return targetObject instanceof Ember.Controller;
    });
    this.set('currentController', currentController);

    // Set related model.
    var relatedModel = this.get('relatedModel');
    if (Ember.isNone(relatedModel) && !Ember.isNone(currentController)) {
      relatedModel = currentController.get('model');
      this.set('relatedModel', relatedModel);
    }

    // Import application config\environment.
    var appConfig = getOwner(this)._lookupFactory('config:environment');
    if (!Ember.isNone(appConfig)) {
      this.set('appConfig', appConfig);
    }

    var appConfigSettingsPath = this.get('appConfigSettingsPath');
    if (Ember.typeOf(appConfigSettingsPath) === 'string') {
      var appConfigSettings = Ember.get(appConfig, appConfigSettingsPath);
      if (!Ember.isNone(appConfigSettings)) {
        this.set('appConfigSettings', appConfigSettings);
      }
    }

    var dynamicProperties = this.get('dynamicProperties');
    if (Ember.typeOf(dynamicProperties) !== 'object') {
      return;
    }

    // Initialize properties for dynamicly-rendered component.
    for (var propertyName in dynamicProperties) {
      if (dynamicProperties.hasOwnProperty(propertyName)) {
        this.set(propertyName, dynamicProperties[propertyName]);
      }
    }
  },

  /**
   * Initializes DOM-related component properties.
   */
  didInsertElement: function() {
    this._super(...arguments);
  },

  /**
   * Cleanup component.
   */
  willDestroy: function() {
    this._super(...arguments);
  },

  /**
   * Cleanup DOM-related component stuff.
   */
  willDestroyElement: function() {
    this._super(...arguments);
  },

  /**
   * Initializes component's property with recpect to following priority:
   * 1 - template-defined parameters,
   * 2 - applicaion configuration-defined parameters (JSON from ./config/environment by path defined in 'appConfigSettingsPath' property),
   * 3 - component-defined defaults.
   * Note! It is important to be declared as undefined for those component properties, which will be initialized through 'initProperty' call.
   *
   * ```javascript
   * // Possible ./config/environment.js.
   * module.exports = function(environment) {
   *   APP: {
   *     components: {
   *       myComponent: {
   *         myComponentProperty: 'myComponentProperty config-defined default value'
   *       }
   *     }
   *   }
   }
   * });
   *
   * var myComponent = FlexberryBaseComponent.extend({
   *   appConfigSettingsPath: 'APP.components.myComponent',
   *
   *   myComponentProperty: undefined,
   *
   *   init: function() {
   *     this._super.apply(this, arguments);
   *     this.initProperty({ propertyName: 'myComponentProperty', defaultValue: 'myComponentProperty default value' });
   *   }
   * });
   * ```
   *
   * @param {Object} options Method options.
   * @param {String} options.propertyName Component's property name.
   * @param {*} options.defaultValue Component's property default value (from component defined default's).
   */
  initProperty: function(options) {
    options = options || {};
    if (Ember.typeOf(options.propertyName) !== 'string') {
      return;
    }

    // If property value is already defined in template,
    // then we should break property initialization.
    var componentDefinedPropertyValue = this.get(options.propertyName);
    if (Ember.typeOf(componentDefinedPropertyValue) !== 'undefined') {
      return;
    }

    // Property value is not defined in template,
    // then we should set configuration-defined value or default.
    var configDefinedPropertyValue;
    var appConfigSettings = this.get('appConfigSettings');
    if (!Ember.isNone(appConfigSettings)) {
      configDefinedPropertyValue = Ember.get(appConfigSettings, options.propertyName);
    }

    if (Ember.typeOf(configDefinedPropertyValue) !== 'undefined') {
      this.set(options.propertyName, configDefinedPropertyValue);
    } else {
      this.set(options.propertyName, options.defaultValue);
    }
  },

  /**
   * Returns that 'targetObject' (from 'targetObject's hierarchy) which satisfies a given condition.
   *
   * ```javascript
   * var controller = this.getTargetObjectByCondition(function(targetObject) {
   *   return targetObject instanceof Ember.Controller;
   * });
   * ```
   *
   * @method getTargetObjectByCondition.
   * @param {Function} condition Callback-function, which will be called for each 'targetObject' in 'targetObject's hierarchy,
   * until callback return true for one of them.
   * @return {null|Ember.Component|Ember.Controller} Target object which satisfies a given condition or null.
   */
  getTargetObjectByCondition: function(condition) {
    if (Ember.typeOf(condition) !== 'function') {
      return null;
    }

    // Component's 'targetObject' is parent component or a controller (in the end of components hierarchy).
    // Search until 'targetObject' is none or condition is true.
    var targetObject = this.get('targetObject');
    while (!(Ember.isNone(targetObject) || condition(targetObject))) {
      targetObject = targetObject.get('targetObject');
    }

    return targetObject;
  }
});
<|endoftext|>