<commit_before>var Player = function(){
	return({
				id:"player", // Every object has an ID for being picked up every time (we've used the ID into newLife)
				group:"player", // ... and is put in a group (do you remember the setGroups command?)
				tileset:"player", // Uses this tileset, generated during loading phase...
				eyes:"peyes",
				killed:false, // and, for now, was not killed.
				scorecombo:1, // We'll keep also the score combo, while eating ghosts. at start is 0. Will increase while we're invincible.
				bugs:0,
				stilltimer:0,
				initialize:function() { // The "initialize" method is called the first frame the object spawns and never more.
					// We will use the topview toys, since player is... well... a top view game.
					toys.topview.initialize(this,{
						haspushing:true,
						shadow:{tileset:"shadows", tile:0},
						frames:{ // These are quite self explanatory
							standup:{ speed:1, frames:[0] },
							standdown:{ speed:1, frames:[3] },
							standleft:{ speed:1, frames:[6] },
							standright:{ speed:1, frames:[6] },
							movingup:{speed:3,frames:[0,1,0,2] },
							movingdown:{speed:3,frames:[3,4,3,5] },
							movingleft:{speed:3,frames:[6,7,6,8] },
							movingright:{speed:3,frames:[6,7,6,8] },
							pushingup:{speed:6,frames:[0,1,0,2] },
							pushingdown:{speed:6,frames:[3,4,3,5] },
							pushingleft:{speed:6,frames:[6,7,6,8] },
							pushingright:{speed:6,frames:[6,7,6,8] }
						}
						// What? Starting "x" and "y" are not here. That's because, when the first level starts, the "newLife" calls "spawn" over the player, setting the position.
					});
				},
				gotBug:function(){
					this.bugs++;
				},
attack:function() {
		gbox.hitAudio("swing");

		this.stilltimer=10; // Stay still for a while
		//this.frame=(this.facing==toys.FACE_UP?9:(this.facing==toys.FACE_DOWN?10:11));

		 // net
				toys.topview.fireBullet("playerbullets",null,{
					fullhit:true,
					collidegroup:"bug",
					undestructable:false, // Custom attribute. Is not destroyed by the hitted object.
					power:1, // Custom attribute. Is the damage value of this weapon.
					from:this,
					sidex:this.facing,
					sidey:this.facing,
					tileset:((this.facing==toys.FACE_LEFT)||(this.facing==toys.FACE_RIGHT)?"lefthit":"uphit"),
					frames:{speed:1,frames:[0,0,0,0]},
					duration:4,
					acc:5,
					fliph:(this.facing==toys.FACE_RIGHT),
					flipv:(this.facing==toys.FACE_DOWN),
					angle:toys.FACES_ANGLE[this.facing]
				});
	},

				first:function() { // Usually everyting involving interacton is into the "first" method.
					if (this.stilltimer) this.stilltimer--;

					this.counter=(this.counter+1)%60; // This line must be used in every object that uses animation. Is needed for getting the right frame (the "frames" block few lines up)

					if (!this.killed&&!maingame.gameIsHold()) { // If player is still alive and the game is not "hold" (level changing fadein/fadeouts etc.) and the "bullet timer" is not stopping the game.

						// First of all, let's move.
						// We want to move diagonally at the same speed as straight (default controlmaxacc is 4)
						if ((gbox.keyIsPressed("left") || gbox.keyIsPressed("right")) && (gbox.keyIsPressed("up") || gbox.keyIsPressed("down"))){
							this.controlmaxacc = Math.sqrt(8);//Math.sqrt((4*4)/2);
						} else {
							this.controlmaxacc = 4;
						}
						toys.topview.controlKeys(this,(this.stilltimer ? {} : {left:"left",right:"right",up:"up",down:"down"})); // Set player's horizontal and vertical speed.
						toys.topview.handleAccellerations(this);
						toys.topview.applyForces(this); // Moves player
						// Note that our player will keep going since we're not changing the speed given by controlKeys and applied by applyForces (i.e. toys.handleAccellerations)
						toys.topview.tileCollision(this,maze,"map",null); // check tile collisions.
																								  // tolerance indicates how "rounded" the corners are (for turning precision - in player have to be precise but not too much, for anticipated turnings)
																								  // Approximation is the distance in pixel of each check. Lower approximation is better but is slower. Usually using the lower between the tile size and the sprite height is enough.

						if (!this.stilltimer){
							toys.topview.setFrame(this); // setFrame sets the right frame checking the facing and the defined animations in "initialize"
							if(gbox.keyIsHit("a")){
								this.attack();
							}
						}
					}
				},

				// The blit phase is the very last method called every frame. It should only draw the object on the bufferContext (i.e. the screen)
				blit:function() {
					if (!this.killed) // If the player is alive, then draw it on the screen. Is a nice trick, since is not needed to destroy/recreate the player every life.
						var buf = gbox.getBufferContext();
						gbox.blitTile(buf,{tileset:this.tileset,tile:this.frame,dx:this.x,dy:this.y,fliph:this.fliph,flipv:this.flipv,camera:this.camera,alpha:1});
						gbox.blitTile(buf,{tileset:this.eyes,tile:this.frame,dx:this.x,dy:this.y,fliph:this.fliph,flipv:this.flipv,camera:this.camera,alpha:1});
						// That means: draw, from my tileset, a frame in position dx,dy flipping the sprite horizontally and/or vertcally, using the camera coords and with full opacity
						// All the arguments are taken from this: the "toys" values everything for doing something coherent from the genre of game you're using.
						// So, our "player" flips, moves and does animation automatically. Really nerds can code something more complex, skipping or integrating the
						// "toys" methods.
				},

				// And now, a custom method. This one will kill the player and will be called by ghosts, when colliding with player.
				sleep:function() {
					if (!this.killed) { // If we're alive...
						this.killed=true; // First of all, player is killed. As you've seen, that makes player invisible and on hold.
						gbox.hitAudio("die"); // Play the die sound
						maingame.playerDied({wait:50}); // Telling the main game cycle that the player died. The arguments sets a short delay after the last fadeout, for making visible the dead animation
						toys.generate.sparks.simple(this,"sparks",null,{tileset:this.tileset,frames:{speed:.1,frames:[8]}});
						// And here comes a common trick: the player is still where was killed and a "spark" (i.e. unuseful animation) starts in the same place.
						// This method allows many nice tricks, since avoid destruction/recreation of the player object, allow a respawn the player in the place it was killed very easily (switching
						// the killed attribute. The "spark.simple" method spawns a spark in the same position of the object in the first argument.
					}
				}

			  });}

<commit_msg>[Delivers #25161819] fixed grid lines when walking diagonal, the player speed was set to sqrt(8) = 2.83 which means the player was walking at most 2.83 px/frame in each of the x and y directions resulting in a movement of 4 pixel-sized units diagonally. This was handled nicely by Chrome but not well by Firefox and Safari. The speed was changed to the nearest whole number (3) for the best of both worlds.<commit_after>var Player = function(){
	return({
				id:"player", // Every object has an ID for being picked up every time (we've used the ID into newLife)
				group:"player", // ... and is put in a group (do you remember the setGroups command?)
				tileset:"player", // Uses this tileset, generated during loading phase...
				eyes:"peyes",
				killed:false, // and, for now, was not killed.
				scorecombo:1, // We'll keep also the score combo, while eating ghosts. at start is 0. Will increase while we're invincible.
				bugs:0,
				stilltimer:0,
				initialize:function() { // The "initialize" method is called the first frame the object spawns and never more.
					// We will use the topview toys, since player is... well... a top view game.
					toys.topview.initialize(this,{
						haspushing:true,
						shadow:{tileset:"shadows", tile:0},
						frames:{ // These are quite self explanatory
							standup:{ speed:1, frames:[0] },
							standdown:{ speed:1, frames:[3] },
							standleft:{ speed:1, frames:[6] },
							standright:{ speed:1, frames:[6] },
							movingup:{speed:3,frames:[0,1,0,2] },
							movingdown:{speed:3,frames:[3,4,3,5] },
							movingleft:{speed:3,frames:[6,7,6,8] },
							movingright:{speed:3,frames:[6,7,6,8] },
							pushingup:{speed:6,frames:[0,1,0,2] },
							pushingdown:{speed:6,frames:[3,4,3,5] },
							pushingleft:{speed:6,frames:[6,7,6,8] },
							pushingright:{speed:6,frames:[6,7,6,8] }
						}
						// What? Starting "x" and "y" are not here. That's because, when the first level starts, the "newLife" calls "spawn" over the player, setting the position.
					});
				},
				gotBug:function(){
					this.bugs++;
				},
attack:function() {
		gbox.hitAudio("swing");

		this.stilltimer=10; // Stay still for a while
		//this.frame=(this.facing==toys.FACE_UP?9:(this.facing==toys.FACE_DOWN?10:11));

		 // net
				toys.topview.fireBullet("playerbullets",null,{
					fullhit:true,
					collidegroup:"bug",
					undestructable:false, // Custom attribute. Is not destroyed by the hitted object.
					power:1, // Custom attribute. Is the damage value of this weapon.
					from:this,
					sidex:this.facing,
					sidey:this.facing,
					tileset:((this.facing==toys.FACE_LEFT)||(this.facing==toys.FACE_RIGHT)?"lefthit":"uphit"),
					frames:{speed:1,frames:[0,0,0,0]},
					duration:4,
					acc:5,
					fliph:(this.facing==toys.FACE_RIGHT),
					flipv:(this.facing==toys.FACE_DOWN),
					angle:toys.FACES_ANGLE[this.facing]
				});
	},

				first:function() { // Usually everyting involving interacton is into the "first" method.
					if (this.stilltimer) this.stilltimer--;

					this.counter=(this.counter+1)%60; // This line must be used in every object that uses animation. Is needed for getting the right frame (the "frames" block few lines up)

					if (!this.killed&&!maingame.gameIsHold()) { // If player is still alive and the game is not "hold" (level changing fadein/fadeouts etc.) and the "bullet timer" is not stopping the game.

						// First of all, let's move.
						// We want to move diagonally at the same speed as straight (default controlmaxacc is 4)
						if ((gbox.keyIsPressed("left") || gbox.keyIsPressed("right")) && (gbox.keyIsPressed("up") || gbox.keyIsPressed("down"))){
							this.controlmaxacc = 3;//changed to a whole number since decimals created problems with Firefox and Safari. Math.sqrt(8);//Math.sqrt((4*4)/2);
						} else {
							this.controlmaxacc = 4;
						}
						toys.topview.controlKeys(this,(this.stilltimer ? {} : {left:"left",right:"right",up:"up",down:"down"})); // Set player's horizontal and vertical speed.
						toys.topview.handleAccellerations(this);
						toys.topview.applyForces(this); // Moves player
						// Note that our player will keep going since we're not changing the speed given by controlKeys and applied by applyForces (i.e. toys.handleAccellerations)
						toys.topview.tileCollision(this,maze,"map",null); // check tile collisions.
																								  // tolerance indicates how "rounded" the corners are (for turning precision - in player have to be precise but not too much, for anticipated turnings)
																								  // Approximation is the distance in pixel of each check. Lower approximation is better but is slower. Usually using the lower between the tile size and the sprite height is enough.

						if (!this.stilltimer){
							toys.topview.setFrame(this); // setFrame sets the right frame checking the facing and the defined animations in "initialize"
							if(gbox.keyIsHit("a")){
								this.attack();
							}
						}
					}
				},

				// The blit phase is the very last method called every frame. It should only draw the object on the bufferContext (i.e. the screen)
				blit:function() {
					if (!this.killed) // If the player is alive, then draw it on the screen. Is a nice trick, since is not needed to destroy/recreate the player every life.
						var buf = gbox.getBufferContext();
						gbox.blitTile(buf,{tileset:this.tileset,tile:this.frame,dx:this.x,dy:this.y,fliph:this.fliph,flipv:this.flipv,camera:this.camera,alpha:1});
						gbox.blitTile(buf,{tileset:this.eyes,tile:this.frame,dx:this.x,dy:this.y,fliph:this.fliph,flipv:this.flipv,camera:this.camera,alpha:1});
						// That means: draw, from my tileset, a frame in position dx,dy flipping the sprite horizontally and/or vertcally, using the camera coords and with full opacity
						// All the arguments are taken from this: the "toys" values everything for doing something coherent from the genre of game you're using.
						// So, our "player" flips, moves and does animation automatically. Really nerds can code something more complex, skipping or integrating the
						// "toys" methods.
				},

				// And now, a custom method. This one will kill the player and will be called by ghosts, when colliding with player.
				sleep:function() {
					if (!this.killed) { // If we're alive...
						this.killed=true; // First of all, player is killed. As you've seen, that makes player invisible and on hold.
						gbox.hitAudio("die"); // Play the die sound
						maingame.playerDied({wait:50}); // Telling the main game cycle that the player died. The arguments sets a short delay after the last fadeout, for making visible the dead animation
						toys.generate.sparks.simple(this,"sparks",null,{tileset:this.tileset,frames:{speed:.1,frames:[8]}});
						// And here comes a common trick: the player is still where was killed and a "spark" (i.e. unuseful animation) starts in the same place.
						// This method allows many nice tricks, since avoid destruction/recreation of the player object, allow a respawn the player in the place it was killed very easily (switching
						// the killed attribute. The "spark.simple" method spawns a spark in the same position of the object in the first argument.
					}
				}

			  });}

<|endoftext|>


<commit_before>const normalDistribution = require("./normalDistribution");
const calculateArea = require("./calculateArea");

// Number -> Number -> (Number -> Time -> Seed -> Integer)
function occurrences(mean, sd) {
    const constant = 0.00245 / 1.23;
    const newConstant = constant * sd;

    return (eloDifference, timeLength, seed) => {
        const f = graph(mean, sd, newConstant, eloDifference, timeLength);
        const rand = updateSeed(seed, eloDifference, timeLength).decimal;

        return occurrences_(f, rand, mean, 0);
    };
}

function occurrences(mean, sd) {
    const constant = 0.00245 / 1.23;
    const newConstant = constant * sd;

    return (eloDifference, timeLength, seed) => {
        const decimal = timeLength.minutes / 90;
        const meanScaled = (mean + (newConstant * eloDifference)) * decimal;
        const sdScaled = sd * decimal
        const s = Math.sqrt((3 * Math.pow(sdScaled, 2)) / Math.pow(Math.PI, 2));
        const x = updateSeed(seed, eloDifference, timeLength).decimal;
        const output = meanScaled + (s * Math.log(x / (1 - x)));
        const goals = Math.round(output);

        return goals < 0 ? 0 : goals;
    };
}

// (Number -> Number) -> Number -> Number -> Number -> Number
function occurrences_(f, rand, mean, goalCount) {
    const area = calculateArea(f, mean - 20, goalCount + 0.5);

    if (rand > area) {
        return occurrences_(f, rand, mean, goalCount + 1);
    }

    return goalCount;
}

// Number -> Number -> Number -> Number -> Time -> (Number -> Number)
function graph(mean, standardDeviation, constant, eloDifference, timeLength) {
    mean = mean + (constant * eloDifference);

    const decimal = timeLength.minutes / 90;

    const meanScaled = mean * decimal;
    const sdScaled = standardDeviation * decimal;

    return x => normalDistribution(meanScaled, sdScaled, x);
}

// Seed -> Number -> Time -> Seed
function updateSeed(seed, eloDifference, timeLength) {
    return seed
        .append(eloDifference)
        .append(timeLength.milliseconds);
}

module.exports = occurrences;
<commit_msg>Tidies code, still needs work<commit_after>const normalDistribution = require("./normalDistribution");
const calculateArea = require("./calculateArea");
const logit = require("./logitFunction");

// Number -> Number -> (Number -> Time -> Seed -> Integer)
function occurrences(mean, sd) {
    const constant = 0.00245 / 1.23;
    const newConstant = constant * sd;

    return (eloDifference, timeLength, seed) => {
        const f = graph(mean, sd, newConstant, eloDifference, timeLength);
        const rand = updateSeed(seed, eloDifference, timeLength).decimal;

        return occurrences_(f, rand, mean, 0);
    };
}

function occurrences(mean, sd) {
    const constant = (0.00245 / 1.23) * sd;

    return (eloDifference, timeLength, seed) => {
        const meanScaled = scaleMean(constant, timeLength, eloDifference, mean);
        const sdScaled = scaleStandardDeviation(timeLength, sd);
        const x = updateSeed(seed, eloDifference, timeLength).decimal;
        const output = logit(sdScaled, meanScaled, x);
        const goals = Math.round(output);

        return goals < 0 ? 0 : goals;
    };
}

// Number -> Time -> Number -> Number -> Number
function scaleMean(constant, timeLength, eloDifference, mean) {
    const ratio = timeToRatio(timeLength);

    return (mean + (constant * eloDifference)) * ratio;
}

// Time -> Number -> Number
function scaleStandardDeviation(timeLength, standardDeviation) {
    const ratio = timeToRatio(timeLength);

    return ratio * standardDeviation;
}

// Time -> Number
function timeToRatio(timeLength) {
    return timeLength.minutes / 90;
}

// (Number -> Number) -> Number -> Number -> Number -> Number
function occurrences_(f, rand, mean, goalCount) {
    const area = calculateArea(f, mean - 20, goalCount + 0.5);

    if (rand > area) {
        return occurrences_(f, rand, mean, goalCount + 1);
    }

    return goalCount;
}

// Number -> Number -> Number -> Number -> Time -> (Number -> Number)
function graph(mean, standardDeviation, constant, eloDifference, timeLength) {
    mean = mean + (constant * eloDifference);

    const decimal = timeLength.minutes / 90;

    const meanScaled = mean * decimal;
    const sdScaled = standardDeviation * decimal;

    return x => normalDistribution(meanScaled, sdScaled, x);
}

// Seed -> Number -> Time -> Seed
function updateSeed(seed, eloDifference, timeLength) {
    return seed
        .append(eloDifference)
        .append(timeLength.milliseconds);
}

module.exports = occurrences;
<|endoftext|>


<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

export const BACKGROUND_COLOR = '#f8fbfe';
export const BLUE_WHITE = '#ecf3fc';
export const DARK_GREY = '#4a4a4a';
export const DARKER_GREY = '#333333';
export const FINALISE_GREEN = '#219d1b';
export const FINALISED_RED = '#f63b30';
export const GREY = '#909192';
export const LIGHT_GREY = '#c9cccd';
export const ROW_BLUE = 'rgba(73, 143, 226, 0.05)';
export const SHADOW_BORDER = 'rgba(0, 0, 0, 0.1)';
export const SOFT_RED = '#f63b3022';
export const SUSSOL_ORANGE = '#e95c30';
export const TRANSPARENT = 'rgba(0, 0, 0, 0)';
export const WARM_GREY = '#9b9b9b';
export const WARMER_GREY = '#a8aaac';
export const WHITE = '#FFFFFF';
export const COLD_BREACH_BLUE = '#70b4f0';
export const DANGER_RED = '#FA6400';
<commit_msg>Add misty charcoal colour<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

export const BACKGROUND_COLOR = '#f8fbfe';
export const BLUE_WHITE = '#ecf3fc';
export const DARK_GREY = '#4a4a4a';
export const DARKER_GREY = '#333333';
export const MISTY_CHARCOAL = 'rgba(51,51,51,0.2)';
export const FINALISE_GREEN = '#219d1b';
export const FINALISED_RED = '#f63b30';
export const GREY = '#909192';
export const LIGHT_GREY = '#c9cccd';
export const ROW_BLUE = 'rgba(73, 143, 226, 0.05)';
export const SHADOW_BORDER = 'rgba(0, 0, 0, 0.1)';
export const SOFT_RED = '#f63b3022';
export const SUSSOL_ORANGE = '#e95c30';
export const TRANSPARENT = 'rgba(0, 0, 0, 0)';
export const WARM_GREY = '#9b9b9b';
export const WARMER_GREY = '#a8aaac';
export const WHITE = '#FFFFFF';
export const COLD_BREACH_BLUE = '#70b4f0';
export const DANGER_RED = '#FA6400';
<|endoftext|>


<commit_before>Date.CultureInfo = {
    /* Culture Name */
    name: "ar-DJ",
    englishName: "Arabic (Djibouti)",
    nativeName: "العربية (جيبوتي)",

    /* Day Name Strings */
    dayNames: ["الأحد", "الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت"],
    abbreviatedDayNames: ["أحد", "إثنين", "ثلاثاء", "أربعاء", "خميس", "جمعة", "سبت"],
    shortestDayNames: ["حد", "ثن", "ثل", "رع", "خم", "جم", "سب"],
    firstLetterDayNames: ["ح", "ن", "ث", "ر", "خ", "ج", "س"],

    /* Month Name Strings */
    monthNames: ["يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"],
    abbreviatedMonthNames: ["ينا", "فبر", "مار", "أبر", "ماي", "يون", "يول", "أغس", "سبت", "أكت", "نوف", "ديس"],

    /* AM/PM Designators */
    amDesignator: "ص",
    pmDesignator: "م",

    firstDayOfWeek: 6,
    twoDigitYearMax: 2029,

    /**
     * The dateElementOrder is based on the order of the
     * format specifiers in the formatPatterns.DatePattern.
     *
     * Example:

     shortDatePattern    dateElementOrder
     ------------------  ----------------
     "M/d/yyyy"          "mdy"
     "dd/MM/yyyy"        "dmy"
     "yyyy-MM-dd"        "ymd"

     *
     * The correct dateElementOrder is required by the parser to
     * determine the expected order of the date elements in the
     * string being parsed.
     */
    dateElementOrder: "dmy",

    /* Standard date and time format patterns */
    formatPatterns: {
        shortDate: "dd/MM/yy",
        longDate: "dd/MMMM/yyyy",
        shortTime: "hh:mm tt",
        longTime: "hh:mm:ss tt",
        fullDateTime: "dd/MMMM/yyyy hh:mm:ss tt",
        sortableDateTime: "yyyy-MM-ddTHH:mm:ss",
        universalSortableDateTime: "yyyy-MM-dd HH:mm:ssZ",
        rfc1123: "ddd, dd MMM yyyy HH:mm:ss GMT",
        monthDay: "dd MMMM",
        yearMonth: "MMMM, yyyy"
    },

    /**
     * NOTE: If a string format is not parsing correctly, but
     * you would expect it parse, the problem likely lies below.
     *
     * The following regex patterns control most of the string matching
     * within the parser.
     *
     * The Month name and Day name patterns were automatically generated
     * and in general should be (mostly) correct.
     *
     * Beyond the month and day name patterns are natural language strings.
     * Example: "next", "today", "months"
     *
     * These natural language string may NOT be correct for this culture.
     * If they are not correct, please translate and edit this file
     * providing the correct regular expression pattern.
     *
     * If you modify this file, please post your revised CultureInfo file
     * to the Datejs Forum located at http://www.datejs.com/forums/.
     *
     * Please mark the subject of the post with [CultureInfo]. Example:
     *    Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)
     *
     * We will add the modified patterns to the master source files.
     *
     * As well, please review the list of "Future Strings" section below.
     */
    regexPatterns: {
        jan: /^يناير/i,
        feb: /^فبراير/i,
        mar: /^مارس/i,
        apr: /^أبريل/i,
        may: /^مايو/i,
        jun: /^يونيو/i,
        jul: /^يوليو/i,
        aug: /^أغسطس/i,
        sep: /^سبتمبر/i,
        oct: /^أكتوبر/i,
        nov: /^نوفمبر/i,
        dec: /^ديسمبر/i,

        sun: /^الأحد/i,
        mon: /^الإثنين/i,
        tue: /^الثلاثاء/i,
        wed: /^الأربعاء/i,
        thu: /^الخميس/i,
        fri: /^الجمعة/i,
        sat: /^السبت/i,

        future: /^القادم/i,
        past: /^الماضي/i,
        add: /^(\+|بعد|عقب)/i,
        subtract: /^(\-|قبل|منذ)/i,

        yesterday: /^((ال)?(ا|أ)مس|(ال)?بارح(ة)?)/i,
        today: /^اليوم/i,
        tomorrow: /^(الغد|غد(ا)?)/i,
        now: /^(ال)?آن/i,

        millisecond: /^(ال)?ج(زء(ا))?( من( ال(أ|ا)لف من)? |( )?.( )?)(ال)?ث(انية)?(.)?/i,
	second: /^(ال)?ث(انية|وان(ي)?)?(.)?/i,
	minute: /^(ال)?د(قيقة|قائق)?(.)?/i,
	hour: /^(ال)?س(اعة|اعات)?(.)?/i,
	week: /^(ال)?(إ|ا)س(بوع|ابيع)/i,
	month: /^(ال)?((أ|ا)?شهر|شهور)/i,
	day: /(ال)?(يوم|أيام)/i,
	year: /^(ال)?سن(ة|ين|ون|وات)/i,

	shortMeridian: /^(ص|م)/i,
	longMeridian: /^(صباح(ا)?|مساء(ا)?)/i,
  	timezone: /^(((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt|utc|((ب(ال)?)?توقيت )?((جمهورية )?|جيبوتي|شرق افريقيا|eat|ast|eastern africa? tim(e|ing)))/i,
  	ordinalSuffix: /^\s*(st|nd|rd|th)/i,
  	timeContext: /^\s*(\:|a(?!u|p)|p)/i
    },

	timezones: [{name:"UTC", offset:"+000"}, {name:"GMT", offset:"+000"}, {name:"EAT", offset:"+0300"}, {name:"AST", offset:"+0300"}]
};

/********************
 ** Future Strings **
 ********************
 *
 * The following list of strings may not be currently being used, but
 * may be incorporated into the Datejs library later.
 *
 * We would appreciate any help translating the strings below.
 *
 * If you modify this file, please post your revised CultureInfo file
 * to the Datejs Forum located at http://www.datejs.com/forums/.
 *
 * Please mark the subject of the post with [CultureInfo]. Example:
 *    Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)b
 *
 * English Name        Translated
 * ------------------  -----------------
 * about               قرابة
 * ago                 مضت
 * date                التاريخ
 * time                الوقت
 * calendar            التقويم
 * show                اظهار
 * hourly              كل ساعة
 * daily               يومياً
 * weekly              اسبوعياً
 * bi-weekly           مرتين بالإسبوع
 * fortnight           اسبوعان
 * monthly             شهرياً
 * bi-monthly          مرتين بالشهر
 * quarter             ربع
 * quarterly           كل ربع سنة
 * yearly              سنوياً
 * annual              سنوي
 * annually            سنوياً
 * annum               عام
 * again               مرة أخرى
 * between             بين
 * after               بعد
 * from now            من الآن
 * repeat              كرر
 * times               مرات
 * per                 كل
 * min (abbrev minute) د.
 * morning             صباح
 * noon                ظهيرة
 * night               ليل
 * midnight            نصف الليل
 * mid-night           نصف الليل
 * evening             مساء
 * final               ختامي
 * future              مستقبل
 * spring              ربيع
 * summer              صيف
 * fall                خريف
 * winter              شتاء
 * end of              نهاية
 * end                 نهاية
 * long                طويل
 * short               قصير
 */
<commit_msg>update regexPatterns<commit_after>Date.CultureInfo = {
    /* Culture Name */
    name: "ar-DJ",
    englishName: "Arabic (Djibouti)",
    nativeName: "العربية (جيبوتي)",

    /* Day Name Strings */
    dayNames: ["الأحد", "الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت"],
    abbreviatedDayNames: ["أحد", "إثنين", "ثلاثاء", "أربعاء", "خميس", "جمعة", "سبت"],
    shortestDayNames: ["حد", "ثن", "ثل", "رع", "خم", "جم", "سب"],
    firstLetterDayNames: ["ح", "ن", "ث", "ر", "خ", "ج", "س"],

    /* Month Name Strings */
    monthNames: ["يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"],
    abbreviatedMonthNames: ["ينا", "فبر", "مار", "أبر", "ماي", "يون", "يول", "أغس", "سبت", "أكت", "نوف", "ديس"],

    /* AM/PM Designators */
    amDesignator: "ص",
    pmDesignator: "م",

    firstDayOfWeek: 6,
    twoDigitYearMax: 2029,

    /**
     * The dateElementOrder is based on the order of the
     * format specifiers in the formatPatterns.DatePattern.
     *
     * Example:

     shortDatePattern    dateElementOrder
     ------------------  ----------------
     "M/d/yyyy"          "mdy"
     "dd/MM/yyyy"        "dmy"
     "yyyy-MM-dd"        "ymd"

     *
     * The correct dateElementOrder is required by the parser to
     * determine the expected order of the date elements in the
     * string being parsed.
     */
    dateElementOrder: "dmy",

    /* Standard date and time format patterns */
    formatPatterns: {
        shortDate: "dd/MM/yy",
        longDate: "dd/MMMM/yyyy",
        shortTime: "hh:mm tt",
        longTime: "hh:mm:ss tt",
        fullDateTime: "dd/MMMM/yyyy hh:mm:ss tt",
        sortableDateTime: "yyyy-MM-ddTHH:mm:ss",
        universalSortableDateTime: "yyyy-MM-dd HH:mm:ssZ",
        rfc1123: "ddd, dd MMM yyyy HH:mm:ss GMT",
        monthDay: "dd MMMM",
        yearMonth: "MMMM, yyyy"
    },

    /**
     * NOTE: If a string format is not parsing correctly, but
     * you would expect it parse, the problem likely lies below.
     *
     * The following regex patterns control most of the string matching
     * within the parser.
     *
     * The Month name and Day name patterns were automatically generated
     * and in general should be (mostly) correct.
     *
     * Beyond the month and day name patterns are natural language strings.
     * Example: "next", "today", "months"
     *
     * These natural language string may NOT be correct for this culture.
     * If they are not correct, please translate and edit this file
     * providing the correct regular expression pattern.
     *
     * If you modify this file, please post your revised CultureInfo file
     * to the Datejs Forum located at http://www.datejs.com/forums/.
     *
     * Please mark the subject of the post with [CultureInfo]. Example:
     *    Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)
     *
     * We will add the modified patterns to the master source files.
     *
     * As well, please review the list of "Future Strings" section below.
     */
    regexPatterns: {
        jan: /^ينا(ير)?/i,
        feb: /^فبر(اير)?/i,
        mar: /^مار(س)?/i,
        apr: /^أبر(يل)?/i,
        may: /^ماي(و)?/i,
        jun: /^يون(يو)?/i,
        jul: /^يول(يو)?/i,
        aug: /^أغس(طس)?/i,
        sep: /^سبت(مبر)?/i,
        oct: /^أكت(وبر)?/i,
        nov: /^نوف(مبر)?/i,
        dec: /^ديس(مبر)?/i,

	sun: /^الأحد|(أ|ا)حد|ح(د)?/i,
        mon: /^الإثنين|(إ|ا)ثنين|(ث)?ن/i,
        tue: /^الثلاثاء|ث(ل|لاثاء)?/i,
        wed: /^الأربعاء|(أ|ا)ربعاء|ر(ع)?/i,
        thu: /^الخميس|خ(م|ميس)?/i,
        fri: /^الجمعة|ج(م|معة)?/i,
        sat: /^السبت|س(ب|بت)?/i,

        future: /^القادم/i,
        past: /^الماضي/i,
        add: /^(\+|بعد|عقب)/i,
        subtract: /^(\-|قبل|منذ)/i,

        yesterday: /^((ال)?(ا|أ)مس|(ال)?بارح(ة)?)/i,
        today: /^اليوم/i,
        tomorrow: /^(الغد|غد(ا)?)/i,
        now: /^(ال)?آن/i,

        millisecond: /^(ال)?ج(زء(ا))?( من( ال(أ|ا)لف من)? |( )?.( )?)(ال)?ث(انية)?(.)?/i,
	second: /^(ال)?ث(انية|وان(ي)?)?(.)?/i,
	minute: /^(ال)?د(قيقة|قائق)?(.)?/i,
	hour: /^(ال)?س(اعة|اعات)?(.)?/i,
	week: /^(ال)?(إ|ا)س(بوع|ابيع)/i,
	month: /^(ال)?((أ|ا)?شهر|شهور)/i,
	day: /(ال)?(يوم|أيام)/i,
	year: /^(ال)?سن(ة|ين|ون|وات)/i,

	shortMeridian: /^(ص|م)/i,
	longMeridian: /^(صباح(ا)?|مساء(ا)?)/i,
  	timezone: /^(((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt|utc|((ب(ال)?)?توقيت )?((جمهورية )?|جيبوتي|شرق افريقيا|eat|ast|eastern africa? tim(e|ing)))/i,
  	ordinalSuffix: /^\s*(st|nd|rd|th)/i,
  	timeContext: /^\s*(\:|a(?!u|p)|p)/i
    },

	timezones: [{name:"UTC", offset:"+000"}, {name:"GMT", offset:"+000"}, {name:"EAT", offset:"+0300"}, {name:"AST", offset:"+0300"}]
};

/********************
 ** Future Strings **
 ********************
 *
 * The following list of strings may not be currently being used, but
 * may be incorporated into the Datejs library later.
 *
 * We would appreciate any help translating the strings below.
 *
 * If you modify this file, please post your revised CultureInfo file
 * to the Datejs Forum located at http://www.datejs.com/forums/.
 *
 * Please mark the subject of the post with [CultureInfo]. Example:
 *    Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)b
 *
 * English Name        Translated
 * ------------------  -----------------
 * about               قرابة
 * ago                 مضت
 * date                التاريخ
 * time                الوقت
 * calendar            التقويم
 * show                اظهار
 * hourly              كل ساعة
 * daily               يومياً
 * weekly              اسبوعياً
 * bi-weekly           مرتين بالإسبوع
 * fortnight           اسبوعان
 * monthly             شهرياً
 * bi-monthly          مرتين بالشهر
 * quarter             ربع
 * quarterly           كل ربع سنة
 * yearly              سنوياً
 * annual              سنوي
 * annually            سنوياً
 * annum               عام
 * again               مرة أخرى
 * between             بين
 * after               بعد
 * from now            من الآن
 * repeat              كرر
 * times               مرات
 * per                 كل
 * min (abbrev minute) د.
 * morning             صباح
 * noon                ظهيرة
 * night               ليل
 * midnight            نصف الليل
 * mid-night           نصف الليل
 * evening             مساء
 * final               ختامي
 * future              مستقبل
 * spring              ربيع
 * summer              صيف
 * fall                خريف
 * winter              شتاء
 * end of              نهاية
 * end                 نهاية
 * long                طويل
 * short               قصير
 */
<|endoftext|>


<commit_before>Date.CultureInfo = {
    /* Culture Name */
    name: "ar-MA",
    englishName: "Arabic (Morocco)",
    nativeName: "العربية (المملكة المغربية)",

    /* Day Name Strings */
    dayNames: ["الأحد", "الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت"],
    abbreviatedDayNames: ["أحد", "إثنين", "ثلاثاء", "أربعاء", "خميس", "جمعة", "سبت"],
    shortestDayNames: ["حد", "ثن", "ثل", "رع", "خم", "جم", "سب"],
    firstLetterDayNames: ["ح", "ن", "ث", "ر", "خ", "ج", "س"],

    /* Month Name Strings */
    monthNames: ["يناير", "فبراير", "مارس", "أبريل", "ماي", "يونيو", "يوليوز", "غشت", "شتنبر", "أكتوبر", "نونبر", "دجنبر"],
    abbreviatedMonthNames: ["ينا", "فبر", "مار", "أبر", "ماي", "يون", "يول", "غشت", "شتن", "أكت", "نون", "دجن"],

    /* AM/PM Designators */
    amDesignator: "ص",
    pmDesignator: "م",

    firstDayOfWeek: 1,
    twoDigitYearMax: 2029,

    /**
     * The dateElementOrder is based on the order of the
     * format specifiers in the formatPatterns.DatePattern.
     *
     * Example:

     shortDatePattern    dateElementOrder
     ------------------  ----------------
     "M/d/yyyy"          "mdy"
     "dd/MM/yyyy"        "dmy"
     "yyyy-MM-dd"        "ymd"

     *
     * The correct dateElementOrder is required by the parser to
     * determine the expected order of the date elements in the
     * string being parsed.
     */
    dateElementOrder: "dmy",

    /* Standard date and time format patterns */
    formatPatterns: {
        shortDate: "dd/MM/yy",
        longDate: "dd/MMMM/yyyy",
        shortTime: "hh:mm tt",
        longTime: "hh:mm:ss tt",
        fullDateTime: "dd/MMMM/yyyy hh:mm:ss tt",
        sortableDateTime: "yyyy-MM-ddTHH:mm:ss",
        universalSortableDateTime: "yyyy-MM-dd HH:mm:ssZ",
        rfc1123: "ddd, dd MMM yyyy HH:mm:ss GMT",
        monthDay: "dd MMMM",
        yearMonth: "MMMM, yyyy"
    },

    /**
     * NOTE: If a string format is not parsing correctly, but
     * you would expect it parse, the problem likely lies below.
     *
     * The following regex patterns control most of the string matching
     * within the parser.
     *
     * The Month name and Day name patterns were automatically generated
     * and in general should be (mostly) correct.
     *
     * Beyond the month and day name patterns are natural language strings.
     * Example: "next", "today", "months"
     *
     * These natural language string may NOT be correct for this culture.
     * If they are not correct, please translate and edit this file
     * providing the correct regular expression pattern.
     *
     * If you modify this file, please post your revised CultureInfo file
     * to the Datejs Forum located at http://www.datejs.com/forums/.
     *
     * Please mark the subject of the post with [CultureInfo]. Example:
     *    Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)
     *
     * We will add the modified patterns to the master source files.
     *
     * As well, please review the list of "Future Strings" section below.
     */
    regexPatterns: {
        jan: /^يناير/i,
        feb: /^فبراير/i,
        mar: /^مارس/i,
        apr: /^أبريل/i,
        may: /^ماي/i,
        jun: /^يونيو/i,
        jul: /^يوليوز/i,
        aug: /^غشت/i,
        sep: /^شتنبر/i,
        oct: /^أكتوبر/i,
        nov: /^نونبر/i,
        dec: /^دجنبر/i,

        sun: /^الأحد/i,
        mon: /^الإثنين/i,
        tue: /^الثلاثاء/i,
        wed: /^الأربعاء/i,
        thu: /^الخميس/i,
        fri: /^الجمعة/i,
        sat: /^السبت/i,

        future: /^القادم/i,
        past: /^الماضي/i,
        add: /^(\+|بعد|عقب)/i,
        subtract: /^(\-|قبل|منذ)/i,

        yesterday: /^((ال)?(ا|أ)مس|(ال)?بارح(ة)?)/i,
        today: /^اليوم/i,
        tomorrow: /^(الغد|غد(ا)?)/i,
        now: /^(ال)?آن/i,

        millisecond: /^(ال)?ج(زء(ا))?( من( ال(أ|ا)لف من)? |( )?.( )?)(ال)?ث(انية)?(.)?/i,
	second: /^(ال)?ث(انية|وان(ي)?)?(.)?/i,
	minute: /^(ال)?د(قيقة|قائق)?(.)?/i,
	hour: /^(ال)?س(اعة|اعات)?(.)?/i,
	week: /^(ال)?(إ|ا)س(بوع|ابيع)/i,
	month: /^(ال)?((أ|ا)?شهر|شهور)/i,
	day: /(ال)?(يوم|أيام)/i,
	year: /^(ال)?سن(ة|ين|ون|وات)/i,

	shortMeridian: /^(ص|م)/i,
	longMeridian: /^(صباح(ا)?|مساء(ا)?)/i,
	timezone: /^(((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt|utc|((ب(ال)?)?توقيت )?((ال)?(مملكة )?(ال)?مغرب(ية)?|الرباط|جرينتش|غرب أوروبا|wet|west|western europe (summer)? tim(e|ing))/i,
	ordinalSuffix: /^\s*(st|nd|rd|th)/i,
        timeContext: /^\s*(\:|a(?!u|p)|p)/i
    },

	timezones: [{name:"UTC", offset:"+000"}, {name:"GMT", offset:"+000"}, {name:"WET", offset:"+000"}, {name:"WEST", offset:"+0100"}]
};

/********************
 ** Future Strings **
 ********************
 *
 * The following list of strings may not be currently being used, but
 * may be incorporated into the Datejs library later.
 *
 * We would appreciate any help translating the strings below.
 *
 * If you modify this file, please post your revised CultureInfo file
 * to the Datejs Forum located at http://www.datejs.com/forums/.
 *
 * Please mark the subject of the post with [CultureInfo]. Example:
 *    Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)b
 *
 * English Name        Translated
 * ------------------  -----------------
 * about               قرابة
 * ago                 مضت
 * date                التاريخ
 * time                الوقت
 * calendar            التقويم
 * show                اظهار
 * hourly              كل ساعة
 * daily               يومياً
 * weekly              اسبوعياً
 * bi-weekly           مرتين بالإسبوع
 * fortnight           اسبوعان
 * monthly             شهرياً
 * bi-monthly          مرتين بالشهر
 * quarter             ربع
 * quarterly           كل ربع سنة
 * yearly              سنوياً
 * annual              سنوي
 * annually            سنوياً
 * annum               عام
 * again               مرة أخرى
 * between             بين
 * after               بعد
 * from now            من الآن
 * repeat              كرر
 * times               مرات
 * per                 كل
 * min (abbrev minute) د.
 * morning             صباح
 * noon                ظهيرة
 * night               ليل
 * midnight            نصف الليل
 * mid-night           نصف الليل
 * evening             مساء
 * final               ختامي
 * future              مستقبل
 * spring              ربيع
 * summer              صيف
 * fall                خريف
 * winter              شتاء
 * end of              نهاية
 * end                 نهاية
 * long                طويل
 * short               قصير
 */
<commit_msg>update regexPatterns<commit_after>Date.CultureInfo = {
    /* Culture Name */
    name: "ar-MA",
    englishName: "Arabic (Morocco)",
    nativeName: "العربية (المملكة المغربية)",

    /* Day Name Strings */
    dayNames: ["الأحد", "الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت"],
    abbreviatedDayNames: ["أحد", "إثنين", "ثلاثاء", "أربعاء", "خميس", "جمعة", "سبت"],
    shortestDayNames: ["حد", "ثن", "ثل", "رع", "خم", "جم", "سب"],
    firstLetterDayNames: ["ح", "ن", "ث", "ر", "خ", "ج", "س"],

    /* Month Name Strings */
    monthNames: ["يناير", "فبراير", "مارس", "أبريل", "ماي", "يونيو", "يوليوز", "غشت", "شتنبر", "أكتوبر", "نونبر", "دجنبر"],
    abbreviatedMonthNames: ["ينا", "فبر", "مار", "أبر", "ماي", "يون", "يول", "غشت", "شتن", "أكت", "نون", "دجن"],

    /* AM/PM Designators */
    amDesignator: "ص",
    pmDesignator: "م",

    firstDayOfWeek: 1,
    twoDigitYearMax: 2029,

    /**
     * The dateElementOrder is based on the order of the
     * format specifiers in the formatPatterns.DatePattern.
     *
     * Example:

     shortDatePattern    dateElementOrder
     ------------------  ----------------
     "M/d/yyyy"          "mdy"
     "dd/MM/yyyy"        "dmy"
     "yyyy-MM-dd"        "ymd"

     *
     * The correct dateElementOrder is required by the parser to
     * determine the expected order of the date elements in the
     * string being parsed.
     */
    dateElementOrder: "dmy",

    /* Standard date and time format patterns */
    formatPatterns: {
        shortDate: "dd/MM/yy",
        longDate: "dd/MMMM/yyyy",
        shortTime: "hh:mm tt",
        longTime: "hh:mm:ss tt",
        fullDateTime: "dd/MMMM/yyyy hh:mm:ss tt",
        sortableDateTime: "yyyy-MM-ddTHH:mm:ss",
        universalSortableDateTime: "yyyy-MM-dd HH:mm:ssZ",
        rfc1123: "ddd, dd MMM yyyy HH:mm:ss GMT",
        monthDay: "dd MMMM",
        yearMonth: "MMMM, yyyy"
    },

    /**
     * NOTE: If a string format is not parsing correctly, but
     * you would expect it parse, the problem likely lies below.
     *
     * The following regex patterns control most of the string matching
     * within the parser.
     *
     * The Month name and Day name patterns were automatically generated
     * and in general should be (mostly) correct.
     *
     * Beyond the month and day name patterns are natural language strings.
     * Example: "next", "today", "months"
     *
     * These natural language string may NOT be correct for this culture.
     * If they are not correct, please translate and edit this file
     * providing the correct regular expression pattern.
     *
     * If you modify this file, please post your revised CultureInfo file
     * to the Datejs Forum located at http://www.datejs.com/forums/.
     *
     * Please mark the subject of the post with [CultureInfo]. Example:
     *    Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)
     *
     * We will add the modified patterns to the master source files.
     *
     * As well, please review the list of "Future Strings" section below.
     */
    regexPatterns: {
        jan: /^ينا(ير)?/i,
        feb: /^فبر(اير)?/i,
        mar: /^مار(س)?/i,
        apr: /^أبر(يل)?/i,
        may: /^ماي/i,
        jun: /^يون(يو)?/i,
        jul: /^يول(يوز)?/i,
        aug: /^غشت/i,
        sep: /^شتن(بر)?/i,
        oct: /^أكت(وبر)?/i,
        nov: /^نون(بر)?/i,
        dec: /^دجن(بر)?/i,

	sun: /^الأحد|(أ|ا)حد|ح(د)?/i,
        mon: /^الإثنين|(إ|ا)ثنين|(ث)?ن/i,
        tue: /^الثلاثاء|ث(ل|لاثاء)?/i,
        wed: /^الأربعاء|(أ|ا)ربعاء|ر(ع)?/i,
        thu: /^الخميس|خ(م|ميس)?/i,
        fri: /^الجمعة|ج(م|معة)?/i,
        sat: /^السبت|س(ب|بت)?/i,

        future: /^القادم/i,
        past: /^الماضي/i,
        add: /^(\+|بعد|عقب)/i,
        subtract: /^(\-|قبل|منذ)/i,

        yesterday: /^((ال)?(ا|أ)مس|(ال)?بارح(ة)?)/i,
        today: /^اليوم/i,
        tomorrow: /^(الغد|غد(ا)?)/i,
        now: /^(ال)?آن/i,

        millisecond: /^(ال)?ج(زء(ا))?( من( ال(أ|ا)لف من)? |( )?.( )?)(ال)?ث(انية)?(.)?/i,
	second: /^(ال)?ث(انية|وان(ي)?)?(.)?/i,
	minute: /^(ال)?د(قيقة|قائق)?(.)?/i,
	hour: /^(ال)?س(اعة|اعات)?(.)?/i,
	week: /^(ال)?(إ|ا)س(بوع|ابيع)/i,
	month: /^(ال)?((أ|ا)?شهر|شهور)/i,
	day: /(ال)?(يوم|أيام)/i,
	year: /^(ال)?سن(ة|ين|ون|وات)/i,

	shortMeridian: /^(ص|م)/i,
	longMeridian: /^(صباح(ا)?|مساء(ا)?)/i,
	timezone: /^(((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt|utc|((ب(ال)?)?توقيت )?((ال)?(مملكة )?(ال)?مغرب(ية)?|الرباط|جرينتش|غرب أوروبا|wet|west|western europe (summer)? tim(e|ing))/i,
	ordinalSuffix: /^\s*(st|nd|rd|th)/i,
        timeContext: /^\s*(\:|a(?!u|p)|p)/i
    },

	timezones: [{name:"UTC", offset:"+000"}, {name:"GMT", offset:"+000"}, {name:"WET", offset:"+000"}, {name:"WEST", offset:"+0100"}]
};

/********************
 ** Future Strings **
 ********************
 *
 * The following list of strings may not be currently being used, but
 * may be incorporated into the Datejs library later.
 *
 * We would appreciate any help translating the strings below.
 *
 * If you modify this file, please post your revised CultureInfo file
 * to the Datejs Forum located at http://www.datejs.com/forums/.
 *
 * Please mark the subject of the post with [CultureInfo]. Example:
 *    Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)b
 *
 * English Name        Translated
 * ------------------  -----------------
 * about               قرابة
 * ago                 مضت
 * date                التاريخ
 * time                الوقت
 * calendar            التقويم
 * show                اظهار
 * hourly              كل ساعة
 * daily               يومياً
 * weekly              اسبوعياً
 * bi-weekly           مرتين بالإسبوع
 * fortnight           اسبوعان
 * monthly             شهرياً
 * bi-monthly          مرتين بالشهر
 * quarter             ربع
 * quarterly           كل ربع سنة
 * yearly              سنوياً
 * annual              سنوي
 * annually            سنوياً
 * annum               عام
 * again               مرة أخرى
 * between             بين
 * after               بعد
 * from now            من الآن
 * repeat              كرر
 * times               مرات
 * per                 كل
 * min (abbrev minute) د.
 * morning             صباح
 * noon                ظهيرة
 * night               ليل
 * midnight            نصف الليل
 * mid-night           نصف الليل
 * evening             مساء
 * final               ختامي
 * future              مستقبل
 * spring              ربيع
 * summer              صيف
 * fall                خريف
 * winter              شتاء
 * end of              نهاية
 * end                 نهاية
 * long                طويل
 * short               قصير
 */
<|endoftext|>


<commit_before>module.exports = {
    add: {
        dependencies: ['number'],
        code: 'function $add(a, b) { return $number(a) + $number(b); }'
    },
    array: {
        dependencies: ['slice'],
        code: [
            'function $array() { ',
            '   return Object.freeze($slice(arguments, 0));',
            '}'
        ].join("\n")
    },
    bool: {
        dependencies: [],
        code: [
            'function $bool(x) {',
            '    if (typeof x !== "boolean") {',
            '        throw new Error("not a boolean: " + x);',
            '    }',
            '    return x;',
            '}'
        ].join("\n")
    },
    concat: {
        dependencies: [],
        code: [
            'function $concat(a, b) {' +
            '    if (typeof a === "string" && typeof b === "string") {' +
            '        return a + b;' +
            '    }' +
            '    if (Array.isArray(a) && Array.isArray(b)) {' +
            '        return a.concat(b);' +
            '    }' +
            '    throw new Error("incorrect argument types for ++");' +
            '}'
        ].join("\n")
    },
    divide: {
        dependencies: ['number'],
        code: 'function $divide(a, b) { return $number(a) / $number(b); }'
    },
    eq: {
        dependencies: ['isObject'],
        code: [
            'function $eq(a, b) {',
            '    if (a === b) {',
            '        return true;',
            '    } else if (Array.isArray(a) && Array.isArray(b)) {',
            '        var n = a.length;',
            '        var m = b.length;',
            '        if (n !== m) {',
            '            return false;',
            '        } else {',
            '            for (var i = 0; i < n; i++) {',
            '                if (!$eq(a[i], b[i])) {',
            '                    return false;',
            '                }',
            '            }',
            '            return true;',
            '        }',
            '    } else if ($isObject(a) && $isObject(b)) {',
            '        // TODO: Remove duplicates.',
            '        var ks = Object.keys(a).concat(Object.keys(b)).sort();',
            '        return ks.every(function(k) {',
            '            return k in a && k in b && $eq(a[k], b[k]);',
            '        });',
            '    } else {',
            '        return false;',
            '    }',
            '}'
        ].join("\n")
    },
    get: {
        dependencies: [],
        code: [
            'function $get(obj, k) {',
            '    if (obj === null || obj === undefined) {',
            '        throw new Error("cannot get " + k + " of " + obj);',
            '    }',
            '    var v = obj[k];',
            '    if (v !== undefined) {',
            '        return v;',
            '    }',
            '    throw new Error("key " + k + " is undefined in " + obj);',
            '}'
        ].join("\n")
    },
    global: {
        dependencies: [],
        code: 'var $global = (1, eval)("this");'
    },
    gt: {
        // TODO: Make it work on strings too
        dependencies: ['number'],
        code: 'function $gt(a, b) { return $number(a) > $number(b); }'
    },
    gte: {
        dependencies: ['gt', 'eq'],
        code: 'function $gte(a, b) { return $gt(a, b) || $eq(a, b); }'
    },
    has: {
        dependencies: [],
        code: 'function $has(obj, key) { return obj[key] !== undefined; }'
    },
    is: {
        dependencies: [],
        code: [
            'function $is(x, y) {',
            '    if (x === y) {',
            '        return x !== 0 || 1 / x === 1 / y;',
            '    } else {',
            '        return x !== x && y !== y;',
            '    }',
            '}'
        ].join("\n")
    },
    isObject: {
        dependencies: [],
        code: 'function $isObject(x) { return x && typeof x === "object"; }'
    },
    isObjectish: {
        dependencies: [],
        code: [
            'function $isObjectish(x) {',
            '   return x !== undefined && x !== null;',
            '}'
        ].join("\n")
    },
    lt: {
        // TODO: Make it work on strings too
        dependencies: ['number'],
        code: 'function $lt(a, b) { return $number(a) < $number(b); }'
    },
    lte: {
        dependencies: ['lt', 'eq'],
        code: 'function $lte(a, b) { return $lt(a, b) || $eq(a, b); }'
    },
    method: {
        dependencies: [],
        code: 'function $method(obj, method) { return obj[method].bind(obj); }'
    },
    multiply: {
        dependencies: ['number'],
        code: 'function $multiply(a, b) { return $number(a) * $number(b); }'
    },
    negate: {
        dependencies: ['number'],
        code: 'function $negate(x) { return -$number(x); }'
    },
    neq: {
        dependencies: ['eq'],
        code: 'function $neq(a, b) { return !$eq(a, b); }'
    },
    not: {
        dependencies: ['bool'],
        code: 'function $not(x) { return !$bool(x); }'
    },
    number: {
        dependencies: [],
        code: [
            'function $number(x) {',
            '    if (typeof x !== "number") {',
            '        throw new Error("not a number: " + x);',
            '    }',
            '    return x;',
            '}'
        ].join("\n")
    },
    object: {
        dependencies: [],
        code: [
'function $object() {',
'    if (arguments.length % 2 !== 0) {',
'        throw new Error("objects must have an even number of items");',
'    }',
'    var obj = {};',
'    var i = 0;',
'    var n = arguments.length - 1;',
'    while (i < n) {',
'        if (typeof arguments[i] !== "string") {',
'            throw new Error("object keys must be strings: " + arguments[i]);',
'        }',
'        obj[arguments[i]] = arguments[i + 1];',
'        i += 2;',
'    }',
'    return Object.freeze(obj);',
'}'
].join("\n")
    },
    ref: {
        dependencies: ['undef'],
        code:
            'function $ref(x, name) {' +
            '    if (x === $undef) {' +
            '        throw new ReferenceError(' +
            'name + " used before initialization");' +
            '    }' +
            '    return x;' +
            '}'
    },
    set: {
        dependencies: [],
        code:
// TODO: Expose this in the language.
'function $set(obj, k, v) {' +
'    if (obj === null || typeof obj !== "object") {' +
'        throw new Error("cannot set " + k + " on " + obj);' +
'    }' +
'    if (Object.isFrozen(obj)) {' +
'        throw new Error("cannot set " + k + " on frozen object");' +
'    }' +
'    obj[k] = v;' +
'    return obj;' +
'}'
    },
    slice: {
        dependencies: [],
        code: 'function $slice(xs, i) { ' +
            'return Object.freeze(Array.prototype.slice.call(xs, i)); }'
    },
    subtract: {
        dependencies: ['number'],
        code: 'function $subtract(a, b) { return $number(a) - $number(b); }'
    },
    type: {
        dependencies: [],
        code:
            // TODO: Expose this in the language.
            'function $type(x) {' +
            '    if (x === null) {' +
            '        return "null"' +
            '    }' +
            '    if (Array.isArray(x)) {' +
            '        return "array";' +
            '    }' +
            '    return typeof x;' +
            '}'
    },
    undef: {
        dependencies: [],
        code: 'var $undef = {_: "SQUIGGLE_TEMPORAL_DEADZONE_VALUE"};'
    },
    update: {
        dependencies: [],
        code:
            'function $update(a, b) {' +
            '    var c = Object.create(Object.getPrototypeOf(a));' +
            '    Object.keys(a).forEach(function(k) { c[k] = a[k]; });' +
            '    Object.keys(b).forEach(function(k) { c[k] = b[k]; });' +
            '    return Object.freeze(c);' +
            '}'
    }
};
<commit_msg>Add type checking to `has`<commit_after>module.exports = {
    add: {
        dependencies: ['number'],
        code: 'function $add(a, b) { return $number(a) + $number(b); }'
    },
    array: {
        dependencies: ['slice'],
        code: [
            'function $array() { ',
            '   return Object.freeze($slice(arguments, 0));',
            '}'
        ].join("\n")
    },
    bool: {
        dependencies: [],
        code: [
            'function $bool(x) {',
            '    if (typeof x !== "boolean") {',
            '        throw new Error("not a boolean: " + x);',
            '    }',
            '    return x;',
            '}'
        ].join("\n")
    },
    concat: {
        dependencies: [],
        code: [
            'function $concat(a, b) {' +
            '    if (typeof a === "string" && typeof b === "string") {' +
            '        return a + b;' +
            '    }' +
            '    if (Array.isArray(a) && Array.isArray(b)) {' +
            '        return a.concat(b);' +
            '    }' +
            '    throw new Error("incorrect argument types for ++");' +
            '}'
        ].join("\n")
    },
    divide: {
        dependencies: ['number'],
        code: 'function $divide(a, b) { return $number(a) / $number(b); }'
    },
    eq: {
        dependencies: ['isObject'],
        code: [
            'function $eq(a, b) {',
            '    if (a === b) {',
            '        return true;',
            '    } else if (Array.isArray(a) && Array.isArray(b)) {',
            '        var n = a.length;',
            '        var m = b.length;',
            '        if (n !== m) {',
            '            return false;',
            '        } else {',
            '            for (var i = 0; i < n; i++) {',
            '                if (!$eq(a[i], b[i])) {',
            '                    return false;',
            '                }',
            '            }',
            '            return true;',
            '        }',
            '    } else if ($isObject(a) && $isObject(b)) {',
            '        // TODO: Remove duplicates.',
            '        var ks = Object.keys(a).concat(Object.keys(b)).sort();',
            '        return ks.every(function(k) {',
            '            return k in a && k in b && $eq(a[k], b[k]);',
            '        });',
            '    } else {',
            '        return false;',
            '    }',
            '}'
        ].join("\n")
    },
    get: {
        dependencies: [],
        code: [
            'function $get(obj, k) {',
            '    if (obj === null || obj === undefined) {',
            '        throw new Error("cannot get " + k + " of " + obj);',
            '    }',
            '    var v = obj[k];',
            '    if (v !== undefined) {',
            '        return v;',
            '    }',
            '    throw new Error("key " + k + " is undefined in " + obj);',
            '}'
        ].join("\n")
    },
    global: {
        dependencies: [],
        code: 'var $global = (1, eval)("this");'
    },
    gt: {
        // TODO: Make it work on strings too
        dependencies: ['number'],
        code: 'function $gt(a, b) { return $number(a) > $number(b); }'
    },
    gte: {
        dependencies: ['gt', 'eq'],
        code: 'function $gte(a, b) { return $gt(a, b) || $eq(a, b); }'
    },
    has: {
        dependencies: [],
        code: [
            'function $has(obj, key) {',
            '    if (typeof key !== "string" &&',
            '        typeof key !== "number") {',
            '       throw new Error("key must be a string or a number. " +',
            '                       "Key is a " + typeof key);',
            '    }',
            '    if (typeof key === "number" && !(key % 1 === 0)) {',
            '        throw new Error("Numerical keys cannot be floats");',
            '    }',
            '    return obj[key] !== undefined;',
            '}'
        ].join("\n")
    },
    is: {
        dependencies: [],
        code: [
            'function $is(x, y) {',
            '    if (x === y) {',
            '        return x !== 0 || 1 / x === 1 / y;',
            '    } else {',
            '        return x !== x && y !== y;',
            '    }',
            '}'
        ].join("\n")
    },
    isObject: {
        dependencies: [],
        code: 'function $isObject(x) { return x && typeof x === "object"; }'
    },
    isObjectish: {
        dependencies: [],
        code: [
            'function $isObjectish(x) {',
            '   return x !== undefined && x !== null;',
            '}'
        ].join("\n")
    },
    lt: {
        // TODO: Make it work on strings too
        dependencies: ['number'],
        code: 'function $lt(a, b) { return $number(a) < $number(b); }'
    },
    lte: {
        dependencies: ['lt', 'eq'],
        code: 'function $lte(a, b) { return $lt(a, b) || $eq(a, b); }'
    },
    method: {
        dependencies: [],
        code: 'function $method(obj, method) { return obj[method].bind(obj); }'
    },
    multiply: {
        dependencies: ['number'],
        code: 'function $multiply(a, b) { return $number(a) * $number(b); }'
    },
    negate: {
        dependencies: ['number'],
        code: 'function $negate(x) { return -$number(x); }'
    },
    neq: {
        dependencies: ['eq'],
        code: 'function $neq(a, b) { return !$eq(a, b); }'
    },
    not: {
        dependencies: ['bool'],
        code: 'function $not(x) { return !$bool(x); }'
    },
    number: {
        dependencies: [],
        code: [
            'function $number(x) {',
            '    if (typeof x !== "number") {',
            '        throw new Error("not a number: " + x);',
            '    }',
            '    return x;',
            '}'
        ].join("\n")
    },
    object: {
        dependencies: [],
        code: [
'function $object() {',
'    if (arguments.length % 2 !== 0) {',
'        throw new Error("objects must have an even number of items");',
'    }',
'    var obj = {};',
'    var i = 0;',
'    var n = arguments.length - 1;',
'    while (i < n) {',
'        if (typeof arguments[i] !== "string") {',
'            throw new Error("object keys must be strings: " + arguments[i]);',
'        }',
'        obj[arguments[i]] = arguments[i + 1];',
'        i += 2;',
'    }',
'    return Object.freeze(obj);',
'}'
].join("\n")
    },
    ref: {
        dependencies: ['undef'],
        code:
            'function $ref(x, name) {' +
            '    if (x === $undef) {' +
            '        throw new ReferenceError(' +
            'name + " used before initialization");' +
            '    }' +
            '    return x;' +
            '}'
    },
    set: {
        dependencies: [],
        code:
// TODO: Expose this in the language.
'function $set(obj, k, v) {' +
'    if (obj === null || typeof obj !== "object") {' +
'        throw new Error("cannot set " + k + " on " + obj);' +
'    }' +
'    if (Object.isFrozen(obj)) {' +
'        throw new Error("cannot set " + k + " on frozen object");' +
'    }' +
'    obj[k] = v;' +
'    return obj;' +
'}'
    },
    slice: {
        dependencies: [],
        code: 'function $slice(xs, i) { ' +
            'return Object.freeze(Array.prototype.slice.call(xs, i)); }'
    },
    subtract: {
        dependencies: ['number'],
        code: 'function $subtract(a, b) { return $number(a) - $number(b); }'
    },
    type: {
        dependencies: [],
        code:
            // TODO: Expose this in the language.
            'function $type(x) {' +
            '    if (x === null) {' +
            '        return "null"' +
            '    }' +
            '    if (Array.isArray(x)) {' +
            '        return "array";' +
            '    }' +
            '    return typeof x;' +
            '}'
    },
    undef: {
        dependencies: [],
        code: 'var $undef = {_: "SQUIGGLE_TEMPORAL_DEADZONE_VALUE"};'
    },
    update: {
        dependencies: [],
        code:
            'function $update(a, b) {' +
            '    var c = Object.create(Object.getPrototypeOf(a));' +
            '    Object.keys(a).forEach(function(k) { c[k] = a[k]; });' +
            '    Object.keys(b).forEach(function(k) { c[k] = b[k]; });' +
            '    return Object.freeze(c);' +
            '}'
    }
};
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Particle Swarm Optimization Visualization
//
// Author : Marc Gumowski
//
// Description : Function allowing to visualize a simple implementation of the  particle
//               swarm optimization algorithm (PSO), using a physical simulation of charged
//               particles.
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function psoViz(id, expr, options) {

  ////////////////////////////////////////////////////////
  // Initial options /////////////////////////////////////
  ////////////////////////////////////////////////////////

  var cfg = {
    margin: { top: 10, left: 5, right: 5, bottom: 10 },
    width: Math.min(640, window.innerWidth - 10),
    height: Math.min(480, window.innerHeight - 20),
    grid: { xMin: -2, xMax: 2, yMin: -2, yMax: 2 },
    radius: 3,
    number: 50,
    color: '#ce2525',
    colorBest: "#1b9e77"
  };

  //Put all of the options into a variable called cfg
	if('undefined' !== typeof options){
	  for(var p in options){
		if('undefined' !== typeof options[p]){ cfg[p] = options[p]; }
	  }
	}

	var scaleX = d3.scaleLinear()
	  .domain([cfg.grid.xMin, cfg.grid.xMax])
	  .range([0, cfg.width]);

	var scaleY = d3.scaleLinear()
	  .domain([cfg.grid.yMin, cfg.grid.yMax])
	  .range([0, cfg.height]);

	function randomize(min, max) {
    return Math.random() * (max - min) + min;
  }

  Array.prototype.getMin = function(attrib) {
    return this.reduce(function(prev, curr){
        return prev[attrib] < curr[attrib] ? prev : curr;
    });
  };

  function getgbest(data) {

    var best = [];
    best = data.getMin('pbestEval');
    best.color = cfg.colorBest;

    console.log(best.color);
    return best;
  }

  ////////////////////////////////////////////////////////
  // SVG /////////////////////////////////////////////////
  ////////////////////////////////////////////////////////

	d3.select(id).select("svg").remove();

	var svg = d3.select(id).append("svg")
	    .attr('id', 'psoVizSVG')
			.attr("width",  cfg.width)
			.attr("height", cfg.height);

  ////////////////////////////////////////////////////////
  // Contour /////////////////////////////////////////////
  ////////////////////////////////////////////////////////

  // Create a grid of value
 var n = 240, m = Math.round(240 * cfg.height / cfg.width), values = new Array(n * m);
  for (var j = 0.5, k = 0; j < m; ++j) {
    for (var i = 0.5; i < n; ++i, ++k) {
      values[k] = expr(cfg.grid.xMin + (cfg.grid.xMax - cfg.grid.xMin) * i / n,
                       cfg.grid.yMax - (cfg.grid.yMax - cfg.grid.yMin) * j / m);
    }
  }

  // Plot
  var thresholds = d3.range(1, 21)
      .map(function(p) { return Math.pow(2, p); });

  var contours = d3.contours()
      .size([n, m])
      .thresholds(thresholds);

  var color = d3.scaleLog()
      .domain(d3.extent(thresholds))
      .interpolate(function() { return d3.interpolateYlGnBu; });

  svg.append("g").selectAll("path")
    .data(contours(values))
    .enter().append("path")
      .attr("d", d3.geoPath(d3.geoIdentity().scale(cfg.width / n)))
      .attr("fill", function(d) { return color(d.value); })
      .style("stroke", "#fff")
      .style("stroke-width", 0.5);

  ////////////////////////////////////////////////////////
  // Particles ///////////////////////////////////////////
  ////////////////////////////////////////////////////////

  // Initialize data with best known position pbest and velocity
  var data = new Array(1 * cfg.number);
  for (var l = 0; l < cfg.number; ++l) {
    data[l] = {
      "value": cfg.radius,
      "color": cfg.color,
      "pbest": {
        "x": randomize(scaleX.domain()[0], scaleX.domain()[1]),
        "y": randomize(scaleY.domain()[0], scaleY.domain()[1])
      },
      "pbestEval": [],
      "velocity": {
        "x": 0,
        "y": 0
      }
    };
  }

  // Evaluate pbest
  var pbestEval = [];
  data.forEach(function(d) { d.pbestEval = expr(d.pbest.x, d.pbest.y); });

  // Update global best: gbest
  var gbest = getgbest(data);

  console.log(data);
  console.log(gbest);
  console.log(expr(0,-1));
  console.log(scaleX(0));
  console.log(scaleY(-1));

  // Create particle and initialize position with appropriate scale
  var particle = svg.selectAll('.particle')
      .data(data)
      .enter().append("g")
      .append('circle')
      .attr('class', 'particle')
      .attr('id', function(d,i) { return "particle" + i;})
      .attr('r', function(d) { return d.value; })
      .attr('cx', function(d) { return scaleX(d.pbest.x); })
      .attr('cy', function(d) { return cfg.height - scaleY(d.pbest.y); })
      .on("click", function(d) { console.log(d); })
      .style('fill', function(d) { return d.color; });

  ////////////////////////////////////////////////////////
  // Simulation //////////////////////////////////////////
  ////////////////////////////////////////////////////////

  // While Criteria
  // Do function Loop
  // else STOP

  // Function loop
  // For each particle
   // For each dimension
    // Update position
    // Evaluate pbest
    // reinitialize color everyone same color cfg.color
    // Update gbest -> getgbest

  var cxNew = cfg.width / 2,
      cyNew = cfg.height / 2;

/*  for (var z = 0; z < 0; z++) {

    particle = particle
      .transition()
      .duration(500)
      .attr('cx', function(d) { return cxNew *  randomize(0, 2); }) // d.cxNew
      .attr('cy', function(d) { return cyNew *  randomize(0, 2); }) // d.cyNew
      .style('fill', function(d) { return d.color; });

  } */

/*    particle.selectAll("circle")
      .transition()
      .duration(function(d) { return 2000 * randomize(1, 2)}) // d.vx * d.vy
      .on("start", function repeat() {
        d3.active(this)
          .attr('cx', function(d) { return cxNew *  randomize(0, 2); }) // d.cxNew
          .attr('cy', function(d) { return cyNew *  randomize(0, 2); }) // d.cyNew
          .transition()
            .on("start", repeat);
      });*/ // Random moves

  ////////////////////////////////////////////////////////
  // Legend and Buttons //////////////////////////////////
  ////////////////////////////////////////////////////////
}

<commit_msg>Update<commit_after>///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Particle Swarm Optimization Visualization
//
// Author : Marc Gumowski
//
// Description : Function allowing to visualize a simple implementation of the  particle
//               swarm optimization algorithm (PSO), using a physical simulation of charged
//               particles.
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function psoViz(id, expr, options) {

  ////////////////////////////////////////////////////////
  // Initial options /////////////////////////////////////
  ////////////////////////////////////////////////////////

  var cfg = {
    margin: { top: 10, left: 5, right: 5, bottom: 10 },
    width: Math.min(640, window.innerWidth - 10),
    height: Math.min(480, window.innerHeight - 20),
    grid: { xMin: -2, xMax: 2, yMin: -2, yMax: 2 },
    radius: 3,
    number: 50,
    color: '#ce2525',
    colorBest: "#1b9e77"
  };

  //Put all of the options into a variable called cfg
	if('undefined' !== typeof options){
	  for(var p in options){
		if('undefined' !== typeof options[p]){ cfg[p] = options[p]; }
	  }
	}

	var scaleX = d3.scaleLinear()
	  .domain([cfg.grid.xMin, cfg.grid.xMax])
	  .range([0, cfg.width]);

	var scaleY = d3.scaleLinear()
	  .domain([cfg.grid.yMin, cfg.grid.yMax])
	  .range([0, cfg.height]);

	function randomize(min, max) {
    return Math.random() * (max - min) + min;
  }

  Array.prototype.getMin = function(attrib) {
    return this.reduce(function(prev, curr){
        return prev[attrib] < curr[attrib] ? prev : curr;
    });
  };

  function getgbest(data) {

    var best = [];
    best = data.getMin('pbestEval');
    best.color = cfg.colorBest;

    console.log(best.color);
    return best;
  }

  ////////////////////////////////////////////////////////
  // SVG /////////////////////////////////////////////////
  ////////////////////////////////////////////////////////

	d3.select(id).select("svg").remove();

	var svg = d3.select(id).append("svg")
	    .attr('id', 'psoVizSVG')
			.attr("width",  cfg.width)
			.attr("height", cfg.height);

  ////////////////////////////////////////////////////////
  // Contour /////////////////////////////////////////////
  ////////////////////////////////////////////////////////

  // Create a grid of value
 var n = 240, m = Math.round(240 * cfg.height / cfg.width), values = new Array(n * m);
  for (var j = 0.5, k = 0; j < m; ++j) {
    for (var i = 0.5; i < n; ++i, ++k) {
      values[k] = expr(cfg.grid.xMin + (cfg.grid.xMax - cfg.grid.xMin) * i / n,
                       cfg.grid.yMax - (cfg.grid.yMax - cfg.grid.yMin) * j / m);
    }
  }

  // Plot
  var thresholds = d3.range(1, 21)
      .map(function(p) { return Math.pow(2, p); });

  var contours = d3.contours()
      .size([n, m])
      .thresholds(thresholds);

  var color = d3.scaleLog()
      .domain(d3.extent(thresholds))
      .interpolate(function() { return d3.interpolateYlGnBu; });

  svg.append("g").selectAll("path")
    .data(contours(values))
    .enter().append("path")
      .attr("d", d3.geoPath(d3.geoIdentity().scale(cfg.width / n)))
      .attr("fill", function(d) { return color(d.value); })
      .style("stroke", "#fff")
      .style("stroke-width", 0.5);

  ////////////////////////////////////////////////////////
  // Particles ///////////////////////////////////////////
  ////////////////////////////////////////////////////////

  // Initialize data with best known position pbest and velocity
  var data = new Array(1 * cfg.number);
  for (var l = 0; l < cfg.number; ++l) {
    data[l] = {
      "value": cfg.radius,
      "color": cfg.color,
      "pbest": {
        "x": randomize(scaleX.domain()[0], scaleX.domain()[1]),
        "y": randomize(scaleY.domain()[0], scaleY.domain()[1])
      },
      "pbestEval": [],
      "velocity": {
        "x": 0,
        "y": 0
      }
    };
  }

  // Evaluate pbest
  var pbestEval = [];
  data.forEach(function(d) { d.pbestEval = expr(d.pbest.x, d.pbest.y); });

  // Update global best: gbest
  var gbest = getgbest(data);

  console.log(data);
  console.log(gbest);
  console.log(expr(0,-1));
  console.log(scaleX(0));
  console.log(scaleY(-1));

  // Create particle and initialize position with appropriate scale
  var particle = svg.selectAll('.particle')
      .data(data)
      .enter().append("g")
      .append('circle')
      .attr('class', 'particle')
      .attr('id', function(d,i) { return "particle" + i;})
      .attr('r', function(d) { return d.value; })
      .attr('cx', function(d) { return scaleX(d.pbest.x); })
      .attr('cy', function(d) { return cfg.height - scaleY(d.pbest.y); })
      .on("click", function(d) { console.log(d); })
      .style('fill', function(d) { return d.color; });

  ////////////////////////////////////////////////////////
  // Simulation //////////////////////////////////////////
  ////////////////////////////////////////////////////////

  // While Criteria
  // Do function Loop
  // else STOP

  // Function loop
  // For each particle
   // For each dimension
    // Update position
    // Evaluate pbest
    // reinitialize color everyone same color cfg.color
    // Update gbest -> getgbest

  var cxNew = cfg.width / 2,
      cyNew = cfg.height / 2;

/*  for (var z = 0; z < 0; z++) {

    particle = particle
      .transition()
      .duration(500)
      .attr('cx', function(d) { return cxNew *  randomize(0, 2); }) // d.cxNew
      .attr('cy', function(d) { return cyNew *  randomize(0, 2); }) // d.cyNew
      .style('fill', function(d) { return d.color; });

  } */

/*    particle.selectAll("circle")
      .transition()
      .duration(function(d) { return 2000 * randomize(1, 2)}) // d.vx * d.vy
      .on("start", function repeat() {
        d3.active(this)
          .attr('cx', function(d) { return cxNew *  randomize(0, 2); }) // d.cxNew
          .attr('cy', function(d) { return cyNew *  randomize(0, 2); }) // d.cyNew
          .transition()
            .on("start", repeat);
      });*/ // Random moves

  ////////////////////////////////////////////////////////
  // Legend and Buttons //////////////////////////////////
  ////////////////////////////////////////////////////////
}

<|endoftext|>


<commit_before>var NODE_FOUND_EVENT = 'n',
    PATH_FOUND_EVENT = 'p';

function pubSub(){

   var listeners = {n:[], p:[]},
       errorListeners = [];

   /**
    * Test if something found in the json matches the pattern and, if it does,
    * calls the callback.
    *
    * After partial completion of the first three args, we are left with a function which when called with the details
    * of something called in the parsed json, calls the listener if it matches.
    *
    * @param test
    * @param callback
    * @param callbackContext
    */
   function callConditionally( test, callback, callbackContext, path, ancestors, nodeList ) {

      var foundNode = test( path, nodeList );

      // Possible values for foundNode are now:
      //
      //    false:
      //       we did not match
      //
      //    an object/array/string/number/null:
      //       that node is the one that matched. Because json can have nulls, this can
      //       be null.
      //
      //    undefined: like above, but we don't have the node yet. ie, we know there is a
      //       node that matches but we don't know if it is an array, object, string
      //       etc yet so we can't say anything about it. Null isn't used here because
      //       it would be indistinguishable from us finding a node with a value of
      //       null.
      //
      if( foundNode !== false ) {

         // change curNode to foundNode when it stops breaking tests
         try{
            callback.call(callbackContext, foundNode, path, ancestors );
         } catch(e) {
            errorHappened(Error('Error thrown by callback ' + e.message));
         }
      }
   }

   /**
    * Notify any of the listeners in a list that are interested in the path or node that was
    * just found.
    *
    * @param {Array} listenerList one of listenerMap[NODE_FOUND_EVENT] or
    *                listenerMap[PATH_FOUND_EVENT]
    */
   /**
    * @returns {*} an identifier that can later be used to de-register this listener
    */
   function pushListener(listenerList, pattern, callback, callbackContext) {

      listenerList.push(
         partialComplete(
            callConditionally,
            jsonPathCompiler(pattern),
            callback,
            callbackContext || window
         )
      );
   }

   /**
    * implementation behind .onPath() and .onNode(): add several listeners in one call
    * @param listenerMap
    */
   function pushListeners(listenerList, listenerMap) {

      // TODO: document this call style
      for( var pattern in listenerMap ) {
         pushListener(listenerList, pattern, listenerMap[pattern]);
      }
   }

   function errorHappened(error) {
      callAll( errorListeners, error );
   }

   return {
      notify:function ( eventId, node, path, ancestors ) {

         var nodeList = ancestors.concat([node]),
             listenerList = listeners[eventId];

         callAll( listenerList, path, ancestors, nodeList );
      },
      on:function( eventId, jsonPath, callback, callbackContext ) {

         var listenerList = listeners[eventId];

         if( isString(jsonPath) ) {
            pushListener(listenerList, jsonPath, callback, callbackContext);
         } else {
            pushListeners(listenerList, jsonPath);
         }
         return this; // chaining
      },

      /**
       *
       * @param error
       */
      notifyErr: errorHappened,

      /**
       * Add a new json path to the parser, which will be called when a value is found at the given path
       *
       * @param {Function} callback
       */
      onError: function (callback) {
         errorListeners.push(callback);
         return this; // chaining
      }

   };
}<commit_msg>actually, no it doesnt<commit_after>var NODE_FOUND_EVENT = 'n',
    PATH_FOUND_EVENT = 'p';

function pubSub(){

   var listeners = {n:[], p:[]},
       errorListeners = [];

   /**
    * Test if something found in the json matches the pattern and, if it does,
    * calls the callback.
    *
    * After partial completion of the first three args, we are left with a function which when called with the details
    * of something called in the parsed json, calls the listener if it matches.
    *
    * @param test
    * @param callback
    * @param callbackContext
    */
   function callConditionally( test, callback, callbackContext, path, ancestors, nodeList ) {

      var foundNode = test( path, nodeList );

      // Possible values for foundNode are now:
      //
      //    false:
      //       we did not match
      //
      //    an object/array/string/number/null:
      //       that node is the one that matched. Because json can have nulls, this can
      //       be null.
      //
      //    undefined: like above, but we don't have the node yet. ie, we know there is a
      //       node that matches but we don't know if it is an array, object, string
      //       etc yet so we can't say anything about it. Null isn't used here because
      //       it would be indistinguishable from us finding a node with a value of
      //       null.
      //
      if( foundNode !== false ) {

         // change curNode to foundNode when it stops breaking tests
         try{
            callback.call(callbackContext, foundNode, path, ancestors );
         } catch(e) {
            errorHappened(Error('Error thrown by callback ' + e.message));
         }
      }
   }

   /**
    * Notify any of the listeners in a list that are interested in the path or node that was
    * just found.
    *
    * @param {Array} listenerList one of listenerMap[NODE_FOUND_EVENT] or
    *                listenerMap[PATH_FOUND_EVENT]
    *
    */
   function pushListener(listenerList, pattern, callback, callbackContext) {

      listenerList.push(
         partialComplete(
            callConditionally,
            jsonPathCompiler(pattern),
            callback,
            callbackContext || window
         )
      );
   }

   /**
    * implementation behind .onPath() and .onNode(): add several listeners in one call
    * @param listenerMap
    */
   function pushListeners(listenerList, listenerMap) {

      // TODO: document this call style
      for( var pattern in listenerMap ) {
         pushListener(listenerList, pattern, listenerMap[pattern]);
      }
   }

   function errorHappened(error) {
      callAll( errorListeners, error );
   }

   return {
      notify:function ( eventId, node, path, ancestors ) {

         var nodeList = ancestors.concat([node]),
             listenerList = listeners[eventId];

         callAll( listenerList, path, ancestors, nodeList );
      },
      on:function( eventId, jsonPath, callback, callbackContext ) {

         var listenerList = listeners[eventId];

         if( isString(jsonPath) ) {
            pushListener(listenerList, jsonPath, callback, callbackContext);
         } else {
            pushListeners(listenerList, jsonPath);
         }
         return this; // chaining
      },

      /**
       *
       * @param error
       */
      notifyErr: errorHappened,

      /**
       * Add a new json path to the parser, which will be called when a value is found at the given path
       *
       * @param {Function} callback
       */
      onError: function (callback) {
         errorListeners.push(callback);
         return this; // chaining
      }

   };
}<|endoftext|>


<commit_before>var Utils = require("../utils");
var GroovyFunction = require("./groovyfunction");

var GroovyParser = (function() {

  function GroovyParser() {
  }

  /**
   * Parse a .groovy file and return an object mapping each groovy function
   * name to its definition.
   *
   * @param {String} fileContent - raw content of a .groovy file
   * @return {Object} - map of GroovyFunction
   */
  GroovyParser.prototype.scan = function(fileContent) {
    var line;
    var functionsContainer = {};

    fileContent = fileContent.split("\n");

    for (var i = 0; i < fileContent.length; i++) {
      line = fileContent[i];
      this.parseLine(fileContent, line, functionsContainer);
    }

    return functionsContainer;
  };

  /**
   * Parse a Groovy file line
   *
   * @param {Array} fileContent - array of Groovy lines
   * @param {String} line - Groovy file line
   * @param {Object} functionsContainer - Object to store all functions into
   */
  GroovyParser.prototype.parseLine = function(fileContent, line, functionsContainer) {
    var groovyFunction;

    if (this.isStartDefLine(line)) {
      groovyFunction = new GroovyFunction();
      groovyFunction.setSignature(line);
      groovyFunction.setDefinition(fileContent, line);

      functionsContainer[groovyFunction.getName()] = groovyFunction;
    }
  };

  /**
   * Check if line is the start of a function definition
   *
   * @param {String} line - Groovy file line
   * @return {Boolean} - Whether the line is a def starting line or not
   */
  GroovyParser.prototype.isStartDefLine = function(line) {
    var re = /^def( .*)/;
    return re.test(line);
  };

  return GroovyParser;

})();

module.exports = GroovyParser;<commit_msg>Fix an issue when parsing an undefined fileContent<commit_after>var Utils = require("../utils");
var GroovyFunction = require("./groovyfunction");

var GroovyParser = (function() {

  function GroovyParser() {
  }

  /**
   * Parse a .groovy file and return an object mapping each groovy function
   * name to its definition.
   *
   * @param {String} fileContent - raw content of a .groovy file
   * @return {Object} - map of GroovyFunction
   */
  GroovyParser.prototype.scan = function(fileContent) {
    var line;
    var functionsContainer = {};

    fileContent = fileContent ? fileContent.split("\n") : '';

    for (var i = 0; i < fileContent.length; i++) {
      line = fileContent[i];
      this.parseLine(fileContent, line, functionsContainer);
    }

    return functionsContainer;
  };

  /**
   * Parse a Groovy file line
   *
   * @param {Array} fileContent - array of Groovy lines
   * @param {String} line - Groovy file line
   * @param {Object} functionsContainer - Object to store all functions into
   */
  GroovyParser.prototype.parseLine = function(fileContent, line, functionsContainer) {
    var groovyFunction;

    if (this.isStartDefLine(line)) {
      groovyFunction = new GroovyFunction();
      groovyFunction.setSignature(line);
      groovyFunction.setDefinition(fileContent, line);

      functionsContainer[groovyFunction.getName()] = groovyFunction;
    }
  };

  /**
   * Check if line is the start of a function definition
   *
   * @param {String} line - Groovy file line
   * @return {Boolean} - Whether the line is a def starting line or not
   */
  GroovyParser.prototype.isStartDefLine = function(line) {
    var re = /^def( .*)/;
    return re.test(line);
  };

  return GroovyParser;

})();

module.exports = GroovyParser;<|endoftext|>


<commit_before>var windowElements = document.getElementsByTagName("*");
var angularDefaultDirectives = {
  'html': 'html',
  'head': 'head',
  'meta': 'meta',
  'title': 'title',
  'body': 'body',
  'script': 'script',
  'ng-app': 'ng-app',
  'ng-bind': 'ng-bind',
  'ng-bindhtml': 'ng-bindhtml',
  'ng-bindtemplate': 'ng-bindtemplate',
  'ng-blur': 'ng-blur',
  'ng-change': 'ng-change',
  'ng-checked': 'ng-checked',
  'ng-class': 'ng-class',
  'ng-classeven': 'ng-classeven',
  'ng-classodd': 'ng-classodd',
  'ng-click': 'ng-click',
  'ng-cloak': 'ng-cloak',
  'ng-controller': 'ng-controller',
  'ng-copy': 'ng-copy',
  'ng-csp': 'ng-csp',
  'ng-cut': 'ng-cut',
  'ng-dblclick': 'ng-dblclick',
  'ng-disabled': 'ng-disabled',
  'ng-focus': 'ng-focus',
  'ng-form': 'ng-form',
  'ng-hide': 'ng-hide',
  'ng-href': 'ng-href',
  'ng-if': 'ng-if',
  'ng-include': 'ng-include',
  'ng-init': 'ng-init',
  'ng-keydown': 'ng-keydown',
  'ng-keypress': 'ng-keypress',
  'ng-keyup': 'ng-keyup',
  'ng-list': 'ng-list',
  'ng-model': 'ng-model',
  'ng-modeloptions': 'ng-modeloptions',
  'ng-mousedown': 'ng-mousedown',
  'ng-mouseenter': 'ng-mouseenter',
  'ng-mouseleave': 'ng-mouseleave',
  'ng-mousemove': 'ng-mousemove',
  'ng-mouseover': 'ng-mouseover',
  'ng-mouseup': 'ng-mouseup',
  'ng-nonbindable': 'ng-nonbindable',
  'ng-open': 'ng-open',
  'ng-paste': 'ng-paste',
  'ng-pluralize': 'ng-pluralize',
  'ng-readonly': 'ng-readonly',
  'ng-repeat': 'ng-repeat',
  'ng-selected': 'ng-selected',
  'ng-show': 'ng-show',
  'ng-src': 'ng-src',
  'ng-srcset': 'ng-srcset',
  'ng-style': 'ng-style',
  'ng-submit': 'ng-submit',
  'ng-switch': 'ng-switch',
  'ng-transclude': 'ng-transclude',
  'ng-value': 'ng-value'};
var failedElements = [];
<commit_msg>feat(dd-app): implement checkDefaultDirs function<commit_after>var windowElements = document.getElementsByTagName("*");
var angularDefaultDirectives = {
  'html': 'html',
  'head': 'head',
  'meta': 'meta',
  'title': 'title',
  'body': 'body',
  'script': 'script',
  'ng-app': 'ng-app',
  'ng-bind': 'ng-bind',
  'ng-bindhtml': 'ng-bindhtml',
  'ng-bindtemplate': 'ng-bindtemplate',
  'ng-blur': 'ng-blur',
  'ng-change': 'ng-change',
  'ng-checked': 'ng-checked',
  'ng-class': 'ng-class',
  'ng-classeven': 'ng-classeven',
  'ng-classodd': 'ng-classodd',
  'ng-click': 'ng-click',
  'ng-cloak': 'ng-cloak',
  'ng-controller': 'ng-controller',
  'ng-copy': 'ng-copy',
  'ng-csp': 'ng-csp',
  'ng-cut': 'ng-cut',
  'ng-dblclick': 'ng-dblclick',
  'ng-disabled': 'ng-disabled',
  'ng-focus': 'ng-focus',
  'ng-form': 'ng-form',
  'ng-hide': 'ng-hide',
  'ng-href': 'ng-href',
  'ng-if': 'ng-if',
  'ng-include': 'ng-include',
  'ng-init': 'ng-init',
  'ng-keydown': 'ng-keydown',
  'ng-keypress': 'ng-keypress',
  'ng-keyup': 'ng-keyup',
  'ng-list': 'ng-list',
  'ng-model': 'ng-model',
  'ng-modeloptions': 'ng-modeloptions',
  'ng-mousedown': 'ng-mousedown',
  'ng-mouseenter': 'ng-mouseenter',
  'ng-mouseleave': 'ng-mouseleave',
  'ng-mousemove': 'ng-mousemove',
  'ng-mouseover': 'ng-mouseover',
  'ng-mouseup': 'ng-mouseup',
  'ng-nonbindable': 'ng-nonbindable',
  'ng-open': 'ng-open',
  'ng-paste': 'ng-paste',
  'ng-pluralize': 'ng-pluralize',
  'ng-readonly': 'ng-readonly',
  'ng-repeat': 'ng-repeat',
  'ng-selected': 'ng-selected',
  'ng-show': 'ng-show',
  'ng-src': 'ng-src',
  'ng-srcset': 'ng-srcset',
  'ng-style': 'ng-style',
  'ng-submit': 'ng-submit',
  'ng-switch': 'ng-switch',
  'ng-transclude': 'ng-transclude',
  'ng-value': 'ng-value'};
var failedElements = [];
var checkDefaultDirs = function() {
  for(elesIndex = 0; elesIndex < windowElements.length; elesIndex++) {
    var attrsOfEles = windowElements[elesIndex].attributes;
    var found = false;
    for(attrIndex = 0; attrIndex < attrsOfEles.length; attrIndex++) {
      var currentAttr = angularDefaultDirectives[attrsOfEles[attrIndex].nodeName];
      if(currentAttr) {
        found = true;
        break;
      }
    }
    if(!found) {
      failedElements.push(windowElements[elesIndex]);
    }
  }
}
checkDefaultDirs();
console.log(failedElements);<|endoftext|>


<commit_before>import exceptions from 'src/database/exceptions';
import SqlCommands from 'src/database/sql-related/sqlCommands';

const sqlCommands = new SqlCommands();

function updateFile(fileId, markdownFile) {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) =>
      sqlCommands.saveFile(fileId, markdownFile)
      .then(data => resolve(true))
      .catch(sqlError => sqlError)
    );
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

export default class dataUpdate {
  static constructor() {}

  static saveFile(fileId, markdownFile) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        updateFile(fileId, markdownFile)
        .then(data => resolve(data))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }
}
<commit_msg>Remove updateFile function in dataUpdate.js<commit_after>import exceptions from 'src/database/exceptions';
import SqlCommands from 'src/database/sql-related/sqlCommands';

const sqlCommands = new SqlCommands();

export default class dataUpdate {
  static constructor() {}

  static saveFile(fileId, markdownFile) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

const science = require('../scientist/console');

module.exports = {
  doSomething: doSomething,
	doSomethingElse: doSomethingElse
};

function doSomething(req, res) {
	var a = req.swagger.params.op1.value;
	var b = req.swagger.params.op2.value;
	var ab = [a, 0];

	var experimentResult = science('div-array', (experiment) => {
    experiment.context({ 'div':  a + '/' + b});
		experiment.use(() => divOld(a, b));
    experiment.try(() => divNew(ab));
  });

	return res.json({'result': experimentResult});
}

function divOld(a, b) {
	return a/b;
}

function divNew(arr) {
	return arr[0]/arr[1];
}

function doSomethingElse(req, res) {
	var params = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89];

	var experimentResult = science('multiply-forEach', (experiment) => {
    experiment.context({ 'multiply':  params});
		experiment.use(() => multiplyOld(params));
    experiment.try(() => multiplyNew(params));
  });

	return res.json({'result': experimentResult});
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

function multiplyOld(arr) {
	for(var d = 0; d < 100000; d++) {
		var result = 1;
		for(var index = 0; index < arr.length; index++) {
			result *= arr[index];
		}
	}
	return result;
}

function multiplyNew(arr) {
	for(var d = 0; d < 100000; d++) {
		var result = 1;
		arr.forEach( (item) => {
			result *= item;
		});
	}
	return result;
}
<commit_msg>comment to highlight scientist test<commit_after>'use strict';

const science = require('../scientist/console');

module.exports = {
  doSomething: doSomething,
	doSomethingElse: doSomethingElse
};

function doSomething(req, res) {
	var a = req.swagger.params.op1.value;
	var b = req.swagger.params.op2.value;
  // Awful bug!!!!!
	var ab = [a, 0];

	var experimentResult = science('div-array', (experiment) => {
    experiment.context({ 'div':  a + '/' + b});
		experiment.use(() => divOld(a, b));
    experiment.try(() => divNew(ab));
  });

	return res.json({'result': experimentResult});
}

function divOld(a, b) {
	return a/b;
}

function divNew(arr) {
	return arr[0]/arr[1];
}

function doSomethingElse(req, res) {
	var params = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89];

	var experimentResult = science('multiply-forEach', (experiment) => {
    experiment.context({ 'multiply':  params});
		experiment.use(() => multiplyOld(params));
    experiment.try(() => multiplyNew(params));
  });

	return res.json({'result': experimentResult});
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

function multiplyOld(arr) {
	for(var d = 0; d < 100000; d++) {
		var result = 1;
		for(var index = 0; index < arr.length; index++) {
			result *= arr[index];
		}
	}
	return result;
}

function multiplyNew(arr) {
	for(var d = 0; d < 100000; d++) {
		var result = 1;
		arr.forEach( (item) => {
			result *= item;
		});
	}
	return result;
}
<|endoftext|>