<commit_before>/**
 * Created by anthony on 24/01/2017.
 */

function registerGlobal(moduleName, asName) {

    if (!global[asName]) {
        console.info('reistered global', moduleName, 'as', asName);
        global[asName] = require(moduleName);
    }
}

/*** A-START ***/
/*** T-END ***/

var preGlobals = [
    ['Path', 'path'],
    ['Url', 'url'],
    ['Promise', 'bluebird'],
    ['Enum', 'enum'],
    ['FS', 'fs']
];

var util = require('util');

function crspr(startTag, endTag, replaceMent) {

    replaceMent = replaceMent || preGlobals.map(function (pair) {
            var asName = pair[0], moduleName = pair[1];
            return util.format('global[\'%s\'] = require(\'%s\');', asName, moduleName);
        });

    startTag = startTag || "/*** A-START ***/";
    endTag = endTag || "/*** T-END ***/";

    console.log('REPLACEMENT:', replaceMent.join('\n'));

    var fs = require('fs');
    var lineReader = require('readline').createInterface({
        input: fs.createReadStream(__filename)
    });

    var newFileLines = [];

    var startMarkerSeen = false, endMarkerSeen = false, unmodified = true;
    lineReader.on('line', function (line) {
        //console.log('Line from file:', line);

        var trimmedLine = line.trim();
        endMarkerSeen = trimmedLine === endTag;

        if(!startMarkerSeen && !endMarkerSeen){
            newFileLines.push(line);
        }

        if(startMarkerSeen && endMarkerSeen && unmodified){
            replaceMent.forEach(function(newLine){
                console.log('adding repcement:', newLine);
                newFileLines.push(newLine);
            });
            unmodified = false;
        }

        if(startMarkerSeen && !endMarkerSeen){
            //skip
        }

        if(endMarkerSeen && !unmodified){
            newFileLines.push(line);
        }

        startMarkerSeen = trimmedLine === startTag;
    });

    lineReader.on('close', function () {
        fs.writeFileSync(__filename, newFileLines.join('\n'));
        console.log('wrote file');
    });

}

if(!module.parent){
    crspr();
}

module.exports = crspr;<commit_msg>- fixed __filename bug<commit_after>/**
 * Created by anthony on 24/01/2017.
 */

/*** A-START ***/
/*** T-END ***/

var preGlobals = [
    ['Path', 'path'],
    ['Url', 'url'],
    ['Promise', 'bluebird'],
    ['Enum', 'enum'],
    ['FS', 'fs']
];

var util = require('util');
var path = require('path');

function crspr(startTag, endTag, replaceMent) {

    replaceMent = replaceMent || preGlobals.map(function (pair) {
            var asName = pair[0], moduleName = pair[1];
            return util.format('global[\'%s\'] = require(\'%s\');', asName, moduleName);
        });

    startTag = startTag || "/*** A-START ***/";
    endTag = endTag || "/*** T-END ***/";

    console.log('REPLACEMENT:', replaceMent.join('\n'));

    var mePath = process.argv[1];

    console.log('me file:', mePath);

    var fs = require('fs');

    var lineReader = require('readline').createInterface({
        input: fs.createReadStream(mePath)
    });

    var newFileLines = [];

    var startMarkerSeen = false, endMarkerSeen = false, unmodified = true;
    lineReader.on('line', function (line) {
        //console.log('Line from file:', line);

        var trimmedLine = line.trim();
        endMarkerSeen = trimmedLine === endTag;

        if(!startMarkerSeen && !endMarkerSeen){
            newFileLines.push(line);
        }

        if(startMarkerSeen && endMarkerSeen && unmodified){
            replaceMent.forEach(function(newLine){
                console.log('adding repcement:', newLine);
                newFileLines.push(newLine);
            });
            unmodified = false;
        }

        if(startMarkerSeen && !endMarkerSeen){
            //skip
        }

        if(endMarkerSeen && !unmodified){
            newFileLines.push(line);
        }

        startMarkerSeen = trimmedLine === startTag;
    });

    lineReader.on('close', function () {
        fs.writeFileSync(mePath, newFileLines.join('\n'));
        console.log('wrote file');
    });

}

if(!module.parent){
    crspr();
}

module.exports = crspr;<|endoftext|>


<commit_before>(function() {
  var base64map
      = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',

  crypt = {
    // Bit-wise rotation left
    rotl: function(n, b) {
      return (n << b) | (n >>> (32 - b));
    },

    // Bit-wise rotation right
    rotr: function(n, b) {
      return (n << (32 - b)) | (n >>> b);
    },

    // Swap big-endian to little-endian and vice versa
    endian: function(n) {
      // If number given, swap endian
      if (n.constructor == Number) {
        return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;
      }

      // Else, assume array and swap all items
      for (var i = 0; i < n.length; i++)
        n[i] = crypt.endian(n[i]);
      return n;
    },

    // Generate an array of any length of random bytes
    randomBytes: function(n) {
      for (var bytes = []; n > 0; n--)
        bytes.push(Math.floor(Math.random() * 256));
      return bytes;
    },

    // Convert a byte array to big-endian 32-bit words
    bytesToWords: function(bytes) {
      for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)
        words[b >>> 5] |= bytes[i] << (24 - b % 32);
      return words;
    },

    // Convert big-endian 32-bit words to a byte array
    wordsToBytes: function(words) {
      for (var bytes = [], b = 0; b < words.length * 32; b += 8)
        bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
    },

    // Convert a byte array to a hex string
    bytesToHex: function(bytes) {
      for (var hex = [], i = 0; i < bytes.length; i++) {
        hex.push((bytes[i] >>> 4).toString(16));
        hex.push((bytes[i] & 0xF).toString(16));
      }
      return hex.join('');
    },

    // Convert a hex string to a byte array
    hexToBytes: function(hex) {
      for (var bytes = [], c = 0; c < hex.length; c += 2)
        bytes.push(parseInt(hex.substr(c, 2), 16));
      return bytes;
    },

    // Convert a byte array to a base-64 string
    bytesToBase64: function(bytes) {
      for (var base64 = [], i = 0; i < bytes.length; i += 3) {
        var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
        for (var j = 0; j < 4; j++)
          if (i * 8 + j * 6 <= bytes.length * 8)
            base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));
          else
            base64.push('=');
      }
      return base64.join('');
    },

    // Convert a base-64 string to a byte array
    base64ToBytes: function(base64) {
      // Remove non-base-64 characters
      base64 = base64.replace(/[^A-Z0-9+\/]/ig, '');

      for (var bytes = [], i = 0, imod4 = 0; i < base64.length;
          imod4 = ++i % 4) {
        if (imod4 == 0) continue;
        bytes.push(((base64map.indexOf(base64.charAt(i - 1))
            & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))
            | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))));
      }
      return bytes;
    }
  };
})();
<commit_msg>Fix bracket and return statement<commit_after>(function() {
  var base64map
      = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',

  crypt = {
    // Bit-wise rotation left
    rotl: function(n, b) {
      return (n << b) | (n >>> (32 - b));
    },

    // Bit-wise rotation right
    rotr: function(n, b) {
      return (n << (32 - b)) | (n >>> b);
    },

    // Swap big-endian to little-endian and vice versa
    endian: function(n) {
      // If number given, swap endian
      if (n.constructor == Number) {
        return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;
      }

      // Else, assume array and swap all items
      for (var i = 0; i < n.length; i++)
        n[i] = crypt.endian(n[i]);
      return n;
    },

    // Generate an array of any length of random bytes
    randomBytes: function(n) {
      for (var bytes = []; n > 0; n--)
        bytes.push(Math.floor(Math.random() * 256));
      return bytes;
    },

    // Convert a byte array to big-endian 32-bit words
    bytesToWords: function(bytes) {
      for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)
        words[b >>> 5] |= bytes[i] << (24 - b % 32);
      return words;
    },

    // Convert big-endian 32-bit words to a byte array
    wordsToBytes: function(words) {
      for (var bytes = [], b = 0; b < words.length * 32; b += 8)
        bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
      return bytes;
    },

    // Convert a byte array to a hex string
    bytesToHex: function(bytes) {
      for (var hex = [], i = 0; i < bytes.length; i++) {
        hex.push((bytes[i] >>> 4).toString(16));
        hex.push((bytes[i] & 0xF).toString(16));
      }
      return hex.join('');
    },

    // Convert a hex string to a byte array
    hexToBytes: function(hex) {
      for (var bytes = [], c = 0; c < hex.length; c += 2)
        bytes.push(parseInt(hex.substr(c, 2), 16));
      return bytes;
    },

    // Convert a byte array to a base-64 string
    bytesToBase64: function(bytes) {
      for (var base64 = [], i = 0; i < bytes.length; i += 3) {
        var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
        for (var j = 0; j < 4; j++)
          if (i * 8 + j * 6 <= bytes.length * 8)
            base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));
          else
            base64.push('=');
      }
      return base64.join('');
    },

    // Convert a base-64 string to a byte array
    base64ToBytes: function(base64) {
      // Remove non-base-64 characters
      base64 = base64.replace(/[^A-Z0-9+\/]/ig, '');

      for (var bytes = [], i = 0, imod4 = 0; i < base64.length;
          imod4 = ++i % 4) {
        if (imod4 == 0) continue;
        bytes.push(((base64map.indexOf(base64.charAt(i - 1))
            & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))
            | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));
      }
      return bytes;
    }
  };

  module.exports = crypt;
})();
<|endoftext|>


<commit_before>describe("$.set", function() {
	it("exists", function() {
		expect($.set).to.exist;
	});

	it("sets options on the provided subject", function() {
		var element = $.set(document.createElement("nav"), {
			style: {
				color: "red"
			}
		});

		expect(element).to.exist;
		expect(element.style.color).to.equal("red");
	});

	it("can be called on elements", function() {
		var element = document.createElement("nav");
		element._.set({className: "main-navigation"});

		expect(element.className).to.equal("main-navigation");
	});

	it("sets other options as properties or attributes on the subject", function() {
		var element = $.set(document.createElement("input"), {
			id: "the-main-one",
			type: "text",
			disabled: true
		});

		expect(element.id).to.equal("the-main-one");
		expect(element.disabled).to.be.true;
		expect(element.type).to.equal("text");
	});
});
<commit_msg>Add failing test for calling set on arrays<commit_after>describe("$.set", function() {
	it("exists", function() {
		expect($.set).to.exist;
	});

	it("sets options on the provided subject", function() {
		var element = $.set(document.createElement("nav"), {
			style: {
				color: "red"
			}
		});

		expect(element).to.exist;
		expect(element.style.color).to.equal("red");
	});

	it("can be called on elements", function() {
		var element = document.createElement("nav");
		element._.set({className: "main-navigation"});

		expect(element.className).to.equal("main-navigation");
	});

	xit("can be called on arrays", function() {
		var list = [
			document.createElement("li"),
			document.createElement("li"),
			document.createElement("li")
		];

		list._.set({className: "list-part"});

		list.forEach(function(item) {
			expect(item.className).to.equal("list-part");
		});
	});

	it("sets other options as properties or attributes on the subject", function() {
		var element = $.set(document.createElement("input"), {
			id: "the-main-one",
			type: "text",
			disabled: true
		});

		expect(element.id).to.equal("the-main-one");
		expect(element.disabled).to.be.true;
		expect(element.type).to.equal("text");
	});
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013 Christopher Schäpers <christopher@schaepers.it>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

/**
 * This plugin inserts the right avatar for the user, depending on, whether a
 * custom avatar is uploaded - which it uses then - or not, and display a
 * placeholder with the first letter of the users name instead.
 * For this it queries the core_avatar_get route, thus this plugin is fit very
 * tightly for owncloud, and it may not work anywhere else.
 *
 * You may use this on any

 * Here I'm using

 as an example.
 *
 * There are 5 ways to call this:
 *
 * 1. $('.avatardiv').avatar('jdoe', 128);
 * This will make the div to jdoe's fitting avatar, with a size of 128px.
 *
 * 2. $('.avatardiv').avatar('jdoe');
 * This will make the div to jdoe's fitting avatar. If the div already has a
 * height, it will be used for the avatars size. Otherwise this plugin will
 * search for 'size' DOM data, to use for avatar size. If neither are available
 * it will default to 64px.
 *
 * 3. $('.avatardiv').avatar();
 * This will search the DOM for 'user' data, to use as the username. If there
 * is no username available it will default to a placeholder with the value of
 * "x". The size will be determined the same way, as the second example.
 *
 * 4. $('.avatardiv').avatar('jdoe', 128, true);
 * This will behave like the first example, except it will also append random
 * hashes to the custom avatar images, to force image reloading in IE8.
 *
 * 5. $('.avatardiv').avatar('jdoe', 128, undefined, true);
 * This will behave like the first example, but it will hide the avatardiv, if
 * it will display the default placeholder. undefined is the ie8fix from
 * example 4 and can be either true, or false/undefined, to be ignored.
 *
 * 6. $('.avatardiv').avatar('jdoe', 128, undefined, true, callback);
 * This will behave like the above example, but it will call the function
 * defined in callback after the avatar is placed into the DOM.
 *
 */

(function ($) {
	$.fn.avatar = function(user, size, ie8fix, hidedefault, callback, displayname) {
		if (typeof(size) === 'undefined') {
			if (this.height() > 0) {
				size = this.height();
			} else if (this.data('size') > 0) {
				size = this.data('size');
			} else {
				size = 64;
			}
		}

		this.height(size);
		this.width(size);

		if (typeof(user) === 'undefined') {
			if (typeof(this.data('user')) !== 'undefined') {
				user = this.data('user');
			} else {
				this.imageplaceholder('x');
				return;
			}
		}

		// sanitize
		user = String(user).replace(/\//g,'');

		var $div = this;
		var url;

		// If this is our own avatar we have to use the version attribute
		if (user === OC.getCurrentUser().uid) {
			url = OC.generateUrl(
				'/avatar/{user}/{size}?v={version}',
				{
					user: user,
					size: Math.ceil(size * window.devicePixelRatio),
					version: oc_userconfig.avatar.version
				});
		} else {
			url = OC.generateUrl(
				'/avatar/{user}/{size}',
				{
					user: user,
					size: Math.ceil(size * window.devicePixelRatio)
				});
		}

		// If the displayname is not defined we use the old code path
		if (typeof(displayname) === 'undefined') {
			$.get(url).always(function(result, status) {
				// if there is an error or an object returned (contains user information):
				// -> show the fallback placeholder
				if (typeof(result) === 'object' || status === 'error') {
					if (!hidedefault) {
						if (result.data && result.data.displayname) {
							$div.imageplaceholder(user, result.data.displayname);
						} else {
							// User does not exist
							$div.imageplaceholder(user, 'X');
							$div.css('background-color', '#b9b9b9');
						}
					} else {
						$div.hide();
					}
				// else an image is transferred and should be shown
				} else {
					$div.show();
					if (ie8fix === true) {
						$div.html('');
					} else {
						$div.html('');
					}
				}
				if(typeof callback === 'function') {
					callback();
				}
			});
		} else {
			// We already have the displayname so set the placeholder (to show at least something)
			if (!hidedefault) {
				$div.imageplaceholder(displayname);
			}

			var img = new Image();

			// If the new image loads successfully set it.
			img.onload = function() {
				$div.show();
				$div.text('');
				$div.append(img);
			};

			img.width = size;
			img.height = size;
			img.src = url;
		}
	};
}(jQuery));
<commit_msg>use ? instead of X for avatar name fallback<commit_after>/**
 * Copyright (c) 2013 Christopher Schäpers <christopher@schaepers.it>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

/**
 * This plugin inserts the right avatar for the user, depending on, whether a
 * custom avatar is uploaded - which it uses then - or not, and display a
 * placeholder with the first letter of the users name instead.
 * For this it queries the core_avatar_get route, thus this plugin is fit very
 * tightly for owncloud, and it may not work anywhere else.
 *
 * You may use this on any

 * Here I'm using

 as an example.
 *
 * There are 5 ways to call this:
 *
 * 1. $('.avatardiv').avatar('jdoe', 128);
 * This will make the div to jdoe's fitting avatar, with a size of 128px.
 *
 * 2. $('.avatardiv').avatar('jdoe');
 * This will make the div to jdoe's fitting avatar. If the div already has a
 * height, it will be used for the avatars size. Otherwise this plugin will
 * search for 'size' DOM data, to use for avatar size. If neither are available
 * it will default to 64px.
 *
 * 3. $('.avatardiv').avatar();
 * This will search the DOM for 'user' data, to use as the username. If there
 * is no username available it will default to a placeholder with the value of
 * "?". The size will be determined the same way, as the second example.
 *
 * 4. $('.avatardiv').avatar('jdoe', 128, true);
 * This will behave like the first example, except it will also append random
 * hashes to the custom avatar images, to force image reloading in IE8.
 *
 * 5. $('.avatardiv').avatar('jdoe', 128, undefined, true);
 * This will behave like the first example, but it will hide the avatardiv, if
 * it will display the default placeholder. undefined is the ie8fix from
 * example 4 and can be either true, or false/undefined, to be ignored.
 *
 * 6. $('.avatardiv').avatar('jdoe', 128, undefined, true, callback);
 * This will behave like the above example, but it will call the function
 * defined in callback after the avatar is placed into the DOM.
 *
 */

(function ($) {
	$.fn.avatar = function(user, size, ie8fix, hidedefault, callback, displayname) {
		if (typeof(size) === 'undefined') {
			if (this.height() > 0) {
				size = this.height();
			} else if (this.data('size') > 0) {
				size = this.data('size');
			} else {
				size = 64;
			}
		}

		this.height(size);
		this.width(size);

		if (typeof(user) === 'undefined') {
			if (typeof(this.data('user')) !== 'undefined') {
				user = this.data('user');
			} else {
				this.imageplaceholder('?');
				return;
			}
		}

		// sanitize
		user = String(user).replace(/\//g,'');

		var $div = this;
		var url;

		// If this is our own avatar we have to use the version attribute
		if (user === OC.getCurrentUser().uid) {
			url = OC.generateUrl(
				'/avatar/{user}/{size}?v={version}',
				{
					user: user,
					size: Math.ceil(size * window.devicePixelRatio),
					version: oc_userconfig.avatar.version
				});
		} else {
			url = OC.generateUrl(
				'/avatar/{user}/{size}',
				{
					user: user,
					size: Math.ceil(size * window.devicePixelRatio)
				});
		}

		// If the displayname is not defined we use the old code path
		if (typeof(displayname) === 'undefined') {
			$.get(url).always(function(result, status) {
				// if there is an error or an object returned (contains user information):
				// -> show the fallback placeholder
				if (typeof(result) === 'object' || status === 'error') {
					if (!hidedefault) {
						if (result.data && result.data.displayname) {
							$div.imageplaceholder(user, result.data.displayname);
						} else {
							// User does not exist
							$div.imageplaceholder(user, '?');
							$div.css('background-color', '#b9b9b9');
						}
					} else {
						$div.hide();
					}
				// else an image is transferred and should be shown
				} else {
					$div.show();
					if (ie8fix === true) {
						$div.html('');
					} else {
						$div.html('');
					}
				}
				if(typeof callback === 'function') {
					callback();
				}
			});
		} else {
			// We already have the displayname so set the placeholder (to show at least something)
			if (!hidedefault) {
				$div.imageplaceholder(displayname);
			}

			var img = new Image();

			// If the new image loads successfully set it.
			img.onload = function() {
				$div.show();
				$div.text('');
				$div.append(img);
			};

			img.width = size;
			img.height = size;
			img.src = url;
		}
	};
}(jQuery));
<|endoftext|>


<commit_before>// with migrationLevel 3
if (LivelyMigrationSupport.documentMigrationLevel < 3) {
    LivelyMigrationSupport.addModuleRename(
        'lively.morphic.BindingsExtension',
        'lively.bindings.GeometryBindings', 3);
    LivelyMigrationSupport.addModuleRename(
        'lively.morphic.BindingsTests',
        'lively.bindings.GeometryBindingsTest', 3);
}

if (LivelyMigrationSupport.documentMigrationLevel < 7) {
    LivelyMigrationSupport.addWorldJsoTransform(function(jso) {
        for (var id in jso.registry) {
            var obj = jso.registry[id];
            if (!obj || !obj.__LivelyClassName__ || obj.__LivelyClassName__ !== "ChangeSet") continue;
            jso.registry[id] = {
                isChangeSetReplacement: true,
                toString: function() {
                    return "This is a replacement of a lkml ChangeSet object."
                         + "ChangeSets are no longer used."
                }
            }
        }
        return jso;
    });
}
<commit_msg>core: module rename migrations for old (noew non-existant) modules<commit_after>// with migrationLevel 3
if (LivelyMigrationSupport.documentMigrationLevel < 3) {
    LivelyMigrationSupport.addModuleRename(
        'lively.morphic.BindingsExtension',
        'lively.bindings.GeometryBindings', 3);
    LivelyMigrationSupport.addModuleRename(
        'lively.morphic.BindingsTests',
        'lively.bindings.GeometryBindingsTest', 3);
}

LivelyMigrationSupport.addModuleRename('lively.ide.LocalBrowser', 'lively.ide', 7);
LivelyMigrationSupport.addModuleRename('lively.ide.ChangeSet', 'lively.ide', 7);

if (LivelyMigrationSupport.documentMigrationLevel < 7) {
    LivelyMigrationSupport.addWorldJsoTransform(function(jso) {
        for (var id in jso.registry) {
            var obj = jso.registry[id];
            if (!obj || !obj.__LivelyClassName__ || obj.__LivelyClassName__ !== "ChangeSet") continue;
            jso.registry[id] = {
                isChangeSetReplacement: true,
                toString: function() {
                    return "This is a replacement of a lkml ChangeSet object."
                         + "ChangeSets are no longer used."
                }
            }
        }
        return jso;
    });
}
<|endoftext|>


<commit_before>import {inject} from 'aurelia-framework';
import {App} from '../app';
import {json} from 'aurelia-fetch-client';
import { ValidationControllerFactory, ValidationRules, Validator, validateTrigger } from 'aurelia-validation';
import {FormValidator} from '../classes/FormValidator';
@inject(App, ValidationControllerFactory, Validator)
export class Charity {
  controller = null;
  validator = null;
  constructor(app, controllerFactory, validator){
    this.app = app;
    this.newCharity = {
      'charityName': '',
      'charityCity': '',
      'charityState': '',
      'charityZipCode': 0,
      //'charityPhoneNumber': 2,
      //'charityEmail': '',
      'charityTypes': [],
      'charityManagers': [],
      'charityMngIds': [],
      'charityTypeOther': '',
      'charityTypesHtml': ''
    };
    this.validator = new FormValidator(validator, (results) => this.updateCanSubmit(results)); //if the form is valid then set to true.
    this.controller = controllerFactory.createForCurrentScope(this.validator);
    this.controller.validateTrigger = validateTrigger.changeOrBlur;
    this.validator2 = new FormValidator(validator, (results) => this.updateCanSubmit2(results));
    this.controller2 = controllerFactory.createForCurrentScope(this.validator2);
    this.controller2.validateTrigger = validateTrigger.changeOrBlur;
    this.canSubmit = false;  //the button on the form
    this.canSubmit2 = true;
    this.validType = false;
    this.validType2 = true;
    this.charities = {};
    //this.updateCharityDisplay = false;
  }

  //pretty much just copy and pasted the 'causes' array from user-account.js
  //types = ['Christian', 'Environmental', 'Hunger', 'Animal Rights', 'Homeless', 'Veterans', 'Elderly'];
  states = [ 'Alabama', 'Alaska', 'American Samoa', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Federated States of Micronesia', 'Florida', 'Georgia', 'Guam', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Marshall Islands', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Northern Mariana Islands', 'Ohio', 'Oklahoma', 'Oregon', 'Palau', 'Pennsylvania', 'Puerto Rico', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virgin Island', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']

  async activate(){
    this.uid = this.app.auth.getTokenPayload().sub;
    this.user = await this.app.appState.getUser(this.uid);
    const res = await this.app.httpClient.fetch('/charity/' + this.uid);
    this.charities = await res.json();
    console.log(this.charities);
    if (this.charities.length !== 0){
      this.buildTypes();
      console.log(this.charities[0].charityTypes);
    }
    this.types = ['Christian', 'Environmental', 'Hunger', 'Animal Rights', 'Homeless', 'Veterans', 'Elderly'];
    this.types.sort();
    this.types.push('other');
    this.states.sort();
    this.setupValidation();
  }

  showUpdateCharity(charity){
    //this.updateCharityDisplay = true;
    let updateDiv = document.getElementById('updateCharitySection');
    updateDiv.style.display = 'block';
    this.charityName = charity.charityName;
    this.updateCharity = charity;
    this.setupValidation2();
    if (this.updateCharity.charityTypes.includes('other')){
      this.typeOther = true;
    } else {
      this.typeOther = false;
      this.updateCharity.charitytypeOther = '';
    }
    document.getElementById('updateCharitySection').scrollIntoView();
  }

  showCheckboxes(id){
    const checkboxes = document.getElementById(id);
    if (!this.expanded) {
      checkboxes.opened = true;
      this.expanded = true;
    } else {
      checkboxes.opened = false;
      this.expanded = false;
    }
  }

  typePicked(){
    this.validType = false;
    let nub = document.getElementById('newCharityButton');
    nub.style.display = 'none';
    for (let i = 0; i < this.types.length; i++) {
      if (this.newCharity.charityTypes.indexOf(this.types[i]) > -1){
        this.validType = true;
        if (this.canSubmit){
          nub.style.display = 'block';
        }
      }
    }
    if (this.newCharity.charityTypes.includes('other')){
      this.typeOther = true;
    } else {
      this.typeOther = false;
      this.newCharity.charityTypeOther = '';
    }
  }

  updateTypePicked(){
    this.validType2 = false;
    let nub = document.getElementById('updateCharityButton');
    nub.style.display = 'none';
    for (let i = 0; i < this.types.length; i++) {
      if (this.updateCharity.charityTypes.indexOf(this.types[i]) > -1){
        this.validType2 = true;
        if (this.canSubmit2){
          nub.style.display = 'block';
        }
      }
    }
    console.log('the charity types picked are: ' + this.updateCharity.charityTypes);
    if (this.updateCharity.charityTypes.includes('other')){
      this.typeOther = true;
    } else {
      this.typeOther = false;
      this.updateCharity.charityTypeOther = '';
    }
  }

  setupValidation() {
    ValidationRules
    .ensure('charityPhoneNumber').matches(/[2-9]\d{9}/).maxLength(10).withMessage('10 digit phone number')
    .ensure('charityZipCode').required().matches(/\d{5}/).maxLength(5).withMessage('5-digit zipcode')
    .ensure('charityCity').required().matches(/[^0-9]+/).maxLength(30).withMessage('City name please')
    .ensure('charityName').required().maxLength(40).withMessage('Charity name please')
    .ensure('charityState').required().withMessage('Charity state please')
    .on(this.newCharity);
  }

  setupValidation2() {
    ValidationRules
    .ensure('charityPhoneNumber').matches(/[2-9]\d{9}/).maxLength(10).withMessage('10 digit phone number')
    .ensure('charityZipCode').required().matches(/\d{5}/).maxLength(5).withMessage('5-digit zipcode')
    .ensure('charityCity').required().matches(/[^0-9]+/).maxLength(30).withMessage('City name please')
    .ensure('charityName').required().maxLength(40).withMessage('Charity name please')
    .ensure('charityState').required().withMessage('Charity state please')
    .on(this.updateCharity);
  }

  validate() {
    return this.validator.validateObject(this.newCharity);
  }

  //validate2() {
  //  return this.validator2.validateObject(this.updateCharity);
  //}

  updateCanSubmit(validationResults) {
    let valid = true;
    let nub = document.getElementById('newCharityButton');
    nub.style.display = 'none';
    for (let result of validationResults) {
      if (result.valid === false){
        valid = false;
        break;
      }
    }
    this.canSubmit = valid;
    if (this.canSubmit && this.validType){
      nub.style.display = 'block';
    }
    return this.canSubmit;
  }

  updateCanSubmit2(validationResults) {
    let valid = true;
    console.log('Running update funcitronfswd');
    let nub = document.getElementById('updateCharityButton');
    if (nub !== null) {
      nub.style.display = 'none';
      for (let result of validationResults) {
        if (result.valid === false){
          console.log('Something is not valid');
          valid = false;
          break;
        }
      }
      this.canSubmit2 = valid;
      if (this.canSubmit2 && this.validType2){
        nub.style.display = 'block';
      }
      return this.canSubmit2;
    }
  }

  createCharity(){
    this.newCharity.charityManagers[0] = this.user.name;
    this.newCharity.charityMngIds[0] = this.user._id;
    //the selection menu sets this to the index of the state array, not the actual value of the state in the array.
    //so the selected index is used to get the correct state
    //this.newCharity.charityState = this.states[this.newCharity.charityState - 1];
    this.app.httpClient.fetch('/charity/create', {
      method: 'post',
      body: json(this.newCharity)
    })
    .then((data) => {
      console.log(data);
      this.newCharity = {};
      this.activate();
    });
  }

  buildTypes(){
    for (let l = 0; l < this.charities.length; l++){
      let typeHtml = '';
      for (let i = 0; i < this.charities[l].charityTypes.length; i++) {
        if (this.charities[l].charityTypes[i] !== ''){
          if (this.charities[l].charityTypes[i] !== 'other'){
            typeHtml = typeHtml + '
' + this.charities[l].charityTypes[i] + '
';
          } else {
            typeHtml = typeHtml + '
' + this.charities[l].charityTypeOther + '
';
          }
        }
      }
      if (typeHtml === ''){
        typeHtml = '
not specified
';
      }
      this.charities[l].charityTypesHtml = typeHtml;
    }
  }

  async deleteCharity(charityId){
    await fetch;
    this.app.httpClient.fetch('/charity/' + charityId, {
      method: 'delete'
    })
    .then((data) => {
      console.log('your charity has been deleted');
      this.activate();
    });
  }

  async updateCharityFunct(){
    await fetch;
    this.app.httpClient.fetch('/charity/' +   this.updateCharity._id, {
      method: 'put',
      body: json(this.updateCharity)
    })
    .then((response) => response.json())
    .then((data) => {
      let updateDiv = document.getElementById('updateCharitySection');
      updateDiv.style.display = 'none';
      this.updateCharity = {};
      document.getElementById('charityDash').scrollIntoView();
      this.activate();
    });
  }

  // attached(){
  //   if (this.updateCharityDisplay === true){
  //
  //   }
  // }

}
<commit_msg>fixed validation<commit_after>import {inject} from 'aurelia-framework';
import {App} from '../app';
import {json} from 'aurelia-fetch-client';
import { ValidationControllerFactory, ValidationRules, Validator, validateTrigger } from 'aurelia-validation';
import {FormValidator} from '../classes/FormValidator';
@inject(App, ValidationControllerFactory, Validator)
export class Charity {
  controller = null;
  validator = null;
  constructor(app, controllerFactory, validator){
    this.app = app;
    this.newCharity = {
      'charityName': '',
      'charityCity': '',
      'charityState': '',
      'charityZipCode': 0,
      //'charityPhoneNumber': 2,
      //'charityEmail': '',
      'charityTypes': [],
      'charityManagers': [],
      'charityMngIds': [],
      'charityTypeOther': '',
      'charityTypesHtml': ''
    };
    this.validator = new FormValidator(validator, (results) => this.updateCanSubmit(results)); //if the form is valid then set to true.
    this.controller = controllerFactory.createForCurrentScope(this.validator);
    this.controller.validateTrigger = validateTrigger.changeOrBlur;
    this.validator2 = new FormValidator(validator, (results) => this.updateCanSubmit2(results));
    this.controller2 = controllerFactory.createForCurrentScope(this.validator2);
    this.controller2.validateTrigger = validateTrigger.changeOrBlur;
    this.canSubmit = false;  //the button on the form
    this.canSubmit2 = true;
    this.validType = false;
    this.validType2 = true;
    this.charities = {};
    //this.updateCharityDisplay = false;
  }

  //pretty much just copy and pasted the 'causes' array from user-account.js
  //types = ['Christian', 'Environmental', 'Hunger', 'Animal Rights', 'Homeless', 'Veterans', 'Elderly'];
  states = [ 'Alabama', 'Alaska', 'American Samoa', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Federated States of Micronesia', 'Florida', 'Georgia', 'Guam', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Marshall Islands', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Northern Mariana Islands', 'Ohio', 'Oklahoma', 'Oregon', 'Palau', 'Pennsylvania', 'Puerto Rico', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virgin Island', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']

  async activate(){
    this.uid = this.app.auth.getTokenPayload().sub;
    this.user = await this.app.appState.getUser(this.uid);
    const res = await this.app.httpClient.fetch('/charity/' + this.uid);
    this.charities = await res.json();
    console.log(this.charities);
    if (this.charities.length !== 0){
      this.buildTypes();
      console.log(this.charities[0].charityTypes);
    }
    this.types = ['Christian', 'Environmental', 'Hunger', 'Animal Rights', 'Homeless', 'Veterans', 'Elderly'];
    this.types.sort();
    this.types.push('other');
    this.states.sort();
    this.setupValidation();
  }

  showUpdateCharity(charity){
    //this.updateCharityDisplay = true;
    let updateDiv = document.getElementById('updateCharitySection');
    updateDiv.style.display = 'block';
    this.charityName = charity.charityName;
    this.updateCharity = charity;
    this.setupValidation2();
    if (this.updateCharity.charityTypes.includes('other')){
      this.typeOther = true;
    } else {
      this.typeOther = false;
      this.updateCharity.charitytypeOther = '';
    }
    document.getElementById('updateCharitySection').scrollIntoView();
  }

  showCheckboxes(id){
    const checkboxes = document.getElementById(id);
    if (!this.expanded) {
      checkboxes.opened = true;
      this.expanded = true;
    } else {
      checkboxes.opened = false;
      this.expanded = false;
    }
  }

  typePicked(){
    this.validType = false;
    let nub = document.getElementById('newCharityButton');
    nub.style.display = 'none';
    for (let i = 0; i < this.types.length; i++) {
      if (this.newCharity.charityTypes.indexOf(this.types[i]) > -1){
        this.validType = true;
        if (this.canSubmit){
          nub.style.display = 'block';
        }
      }
    }
    if (this.newCharity.charityTypes.includes('other')){
      this.typeOther = true;
    } else {
      this.typeOther = false;
      this.newCharity.charityTypeOther = '';
    }
  }

  updateTypePicked(){
    this.validType2 = false;
    let nub = document.getElementById('updateCharityButton');
    nub.style.display = 'none';
    for (let i = 0; i < this.types.length; i++) {
      if (this.updateCharity.charityTypes.indexOf(this.types[i]) > -1){
        this.validType2 = true;
        if (this.canSubmit2){
          nub.style.display = 'block';
        }
      }
    }
    console.log('the charity types picked are: ' + this.updateCharity.charityTypes);
    if (this.updateCharity.charityTypes.includes('other')){
      this.typeOther = true;
    } else {
      this.typeOther = false;
      this.updateCharity.charityTypeOther = '';
    }
  }

  setupValidation() {
    ValidationRules
    .ensure('charityPhoneNumber').matches(/[2-9]\d{9}/).maxLength(10).withMessage('10 digit phone number')
    .ensure('charityZipCode').required().matches(/\d{5}/).withMessage('5-digit zipcode')
    .ensure('charityCity').required().matches(/[^0-9]+/).maxLength(30).withMessage('City name please')
    .ensure('charityName').required().maxLength(40).withMessage('Charity name please')
    .ensure('charityState').required().withMessage('Charity state please')
    .on(this.newCharity);
  }

  setupValidation2() {
    ValidationRules
    .ensure('charityPhoneNumber').matches(/[2-9]\d{9}/).maxLength(10).withMessage('10 digit phone number')
    .ensure('charityZipCode').required().matches(/\d{5}/).withMessage('5-digit zipcode')
    .ensure('charityCity').required().matches(/[^0-9]+/).maxLength(30).withMessage('City name please')
    .ensure('charityName').required().maxLength(40).withMessage('Charity name please')
    .ensure('charityState').required().withMessage('Charity state please')
    .on(this.updateCharity);
  }

  validate() {
    return this.validator.validateObject(this.newCharity);
  }

  validate2() {
    return this.validator2.validateObject(this.updateCharity);
  }

  updateCanSubmit(validationResults) {
    let valid = true;
    let nub = document.getElementById('newCharityButton');
    nub.style.display = 'none';
    for (let result of validationResults) {
      if (result.valid === false){
        valid = false;
        break;
      }
    }
    this.canSubmit = valid;
    if (this.canSubmit && this.validType){
      nub.style.display = 'block';
    }
    return this.canSubmit;
  }

  updateCanSubmit2(validationResults) {
    let valid = true;
    console.log('Running update funcitronfswd');
    let nub = document.getElementById('updateCharityButton');
    if (nub !== null) {
      //nub.style.display = 'none';
      for (let result of validationResults) {
        if (result.valid === false){
          console.log('Something is not valid');
          nub.style.display = 'none';
          valid = false;
          break;
        }
      }
      this.canSubmit2 = valid;
      if (this.canSubmit2 && this.validType2){
        nub.style.display = 'block';
      }
      return this.canSubmit2;
    }
  }

  createCharity(){
    this.newCharity.charityManagers[0] = this.user.name;
    this.newCharity.charityMngIds[0] = this.user._id;
    //the selection menu sets this to the index of the state array, not the actual value of the state in the array.
    //so the selected index is used to get the correct state
    //this.newCharity.charityState = this.states[this.newCharity.charityState - 1];
    this.app.httpClient.fetch('/charity/create', {
      method: 'post',
      body: json(this.newCharity)
    })
    .then((data) => {
      console.log(data);
      this.newCharity = {};
      this.activate();
    });
  }

  buildTypes(){
    for (let l = 0; l < this.charities.length; l++){
      let typeHtml = '';
      for (let i = 0; i < this.charities[l].charityTypes.length; i++) {
        if (this.charities[l].charityTypes[i] !== ''){
          if (this.charities[l].charityTypes[i] !== 'other'){
            typeHtml = typeHtml + '
' + this.charities[l].charityTypes[i] + '
';
          } else {
            typeHtml = typeHtml + '
' + this.charities[l].charityTypeOther + '
';
          }
        }
      }
      if (typeHtml === ''){
        typeHtml = '
not specified
';
      }
      this.charities[l].charityTypesHtml = typeHtml;
    }
  }

  async deleteCharity(charityId){
    await fetch;
    this.app.httpClient.fetch('/charity/' + charityId, {
      method: 'delete'
    })
    .then((data) => {
      console.log('your charity has been deleted');
      this.activate();
    });
  }

  async updateCharityFunct(){
    await fetch;
    this.app.httpClient.fetch('/charity/' +   this.updateCharity._id, {
      method: 'put',
      body: json(this.updateCharity)
    })
    .then((response) => response.json())
    .then((data) => {
      let updateDiv = document.getElementById('updateCharitySection');
      updateDiv.style.display = 'none';
      this.updateCharity = {};
      document.getElementById('charityDash').scrollIntoView();
      this.activate();
    });
  }

  // attached(){
  //   if (this.updateCharityDisplay === true){
  //
  //   }
  // }

}
<|endoftext|>


<commit_before>var namespaceMap = {
    "s": "http://schema.org/"
}

var dataUrl = "http://localhost:8088/data/sheldon.ttl";
var subject = "http://localhost:8080/data/person/sheldon-cooper";

var app = angular.module('AngularRDF', []);

app.directive("myDirective", function () {
    return {
        restrict: "A",
        scope: {
            two: "="
        }
    };
});

// controller here
app.controller('rdfController', ['$scope', '$attrs', '$q', '$log',
    function ($scope, $attrs, $q, $log) {

        $log.info("PROPERTY = " + $attrs.property);

        //  .controller('LogController', ['$scope', '$log', function($scope, $log) {
        $scope.$log = $log;

        console.log("controller called");

        $scope.store = new rdf.LdpStore();

        $scope.data = {
            message: "Helloo"
        };

        // Angular has its own $http, see http://stackoverflow.com/questions/21667613/in-angular-how-to-pass-json-object-array-into-directive

        /**
         * Represents a book.
         * @constructor
         * @param {string} title - The title of the book.
         * @param {string} author - The author of the book.
         * @returns {Number}
         */
        $scope.store.graph(dataUrl, function (graph, error) {
            $scope.graph = graph;
            if (error) {
                console.log(error);
            } else {

                console.log("Successfully fetched %d triples", graph.length);

                // render data
                $scope.turtleString = graph.toArray().join("\n").toString();
                $scope.$apply(); // trigger sync

                $scope.node = {};

                $scope.node.x = function (value) {

                    var name = $attrs.property;
                    $log.info("value  in node.x = " + value);

                    var split = name.split(":");
                    if (split.length > 1) {
                        name = namespaceMap[split[0]] + split[1];
                    }

                    $log.info("name = " + name);
                    // $log.info("cf = " + $scope.cf);
                    $log.info("calling setLiteral with " + subject + "  " + name + "  " + value);
                    if (value) { // angular.isDefined(value) &&

                        setLiteral(subject, name, value);
                        // return "r";
                    } else {
                        var objectNode = getLiteral(subject, name);
                        console.log("returning name = " + objectNode);

                        return objectNode;
                    }
                }

                $scope.node.object = function (name, value) {
                    var name = $attrs.property;
                    $log.info("value in node.object = " + value + " name = " + name);

                    var split = name.split(":");
                    if (split.length > 1) {
                        name = namespaceMap[split[0]] + split[1];
                    }

                    $log.info("name = " + name);
                    // $log.info("cf = " + $scope.cf);

                    if (value && (typeof (value) != "undefined") && ("" + value) != "undefined") { // angular.isDefined(value) &&
                        $log.info("calling setLiteral with " + subject + "  " + name + "  " + value);
                        setLiteral(subject, name, value);
                        // return "r";
                    } else {
                        var objectNode = getLiteral(subject, name);
                        console.log("returning name = " + objectNode);
                        return objectNode;
                    }
                }

            }
        });

        function getLiteral(s, p) {
            $log.info("getLiteral called with s=" + s + " p=" + p);

            var matches = $scope.graph.match(s, p, null);
            //            console.log("matches = " + matches.length);
            matches = matches.toArray();
            var o = matches[0].object.toString();
            console.log("getLiteral o = " + o);
            return o;

            // clownface lookup
            // .out should search subject->object', function () {
            //  $log.info("getLiteral $scope.cf = " + $scope.cf);
            /*
            $scope.cf.node(s, null, function (result) {
                var resultArray = result.out(p).nodes();
                return resultArray[0].toString();
            });
            */
        }

        // test it clears multiple values in graph
        function setLiteral(sString, pString, oString) {
            $log.info("setLiteral called with s=" + sString + " p=" + pString + " o=" + oString);
            // todo : check o is a string
            var s = rdf.createNamedNode(sString)
            var p = rdf.createNamedNode(pString);
            var o = rdf.createLiteral(oString, null, null);

            $scope.graph.removeMatches(s, p, null);
            $scope.store.add(s, p, o);
        }
}]);<commit_msg>nearly there...<commit_after>var namespaceMap = {
    "s": "http://schema.org/"
}

var dataUrl = "http://localhost:8088/data/sheldon.ttl";
var subject = "http://localhost:8080/data/person/sheldon-cooper";

var app = angular.module('AngularRDF', []);

app.directive("myDirective", function () {
    return {
        restrict: "A",
        scope: {
            two: "="
        }
    };
});

// controller here
app.controller('rdfController', ['$scope', '$attrs', '$q', '$log',
    function ($scope, $attrs, $q, $log) {

        $log.info("PROPERTY = " + $attrs.property);

        //  .controller('LogController', ['$scope', '$log', function($scope, $log) {
        $scope.$log = $log;

        console.log("controller called");

        $scope.store = new rdf.LdpStore();

        $scope.data = {
            message: "Helloo"
        };

        // Angular has its own $http, see http://stackoverflow.com/questions/21667613/in-angular-how-to-pass-json-object-array-into-directive

        /**
         * Represents a book.
         * @constructor
         * @param {string} title - The title of the book.
         * @param {string} author - The author of the book.
         * @returns {Number}
         */
        $scope.store.graph(dataUrl, function (graph, error) {
            $scope.graph = graph;
            if (error) {
                console.log(error);
            } else {

                console.log("Successfully fetched %d triples", graph.length);

                // render data
                $scope.turtleString = graph.toArray().join("\n").toString();
                $scope.$apply(); // trigger sync

                $scope.node = {};

                // two slightly different versions, both fairly close

                $scope.node.x = function (value) {

                    var name = $attrs.property; // sometimes it works, sometimes it doesn't !??
                    $log.info("value  in node.x = " + value);

                    var split = name.split(":");
                    if (split.length > 1) {
                        name = namespaceMap[split[0]] + split[1];
                    }

                    $log.info("name = " + name);
                    // $log.info("cf = " + $scope.cf);

                    if (value && (typeof (value) != "undefined") && ("" + value) != "undefined") {
                        $log.info("calling setLiteral with " + subject + "  " + name + "  " + value);
                        setLiteral(subject, name, value);
                        // return "r";
                    } else {
                        var objectNode = getLiteral(subject, name);
                        console.log("returning name = " + objectNode);

                        return objectNode;
                    }
                }

                $scope.node.object = function (name, value) {
                    var name = $attrs.property; // sometimes it works, sometimes it doesn't !??
                    if (!name || (typeof (name) == "undefined") || ("" + name) == "undefined") {
                        return "waiting";
                    }
                    $log.info("value in node.object = " + value + " name = " + name);

                    var split = name.split(":");
                    if (split.length > 1) {
                        name = namespaceMap[split[0]] + split[1];
                    }

                    $log.info("name = " + name);
                    // $log.info("cf = " + $scope.cf);

                    if (value && (typeof (value) != "undefined") && ("" + value) != "undefined") {
                        $log.info("calling setLiteral with " + subject + "  " + name + "  " + value);
                        setLiteral(subject, name, value);
                        // return "r";
                    } else {
                        var objectNode = getLiteral(subject, name);
                        console.log("returning name = " + objectNode);
                        return objectNode;
                    }
                }

            }
        });

        function getLiteral(s, p) {
            $log.info("getLiteral called with s=" + s + " p=" + p);

            var matches = $scope.graph.match(s, p, null);
            console.log("matches = " + matches.length);
            matches = matches.toArray();

            var o = matches[0].object.toString();
            console.log("getLiteral o = " + o);
            return o;

            // clownface lookup
            // .out should search subject->object', function () {
            //  $log.info("getLiteral $scope.cf = " + $scope.cf);
            /*
            $scope.cf.node(s, null, function (result) {
                var resultArray = result.out(p).nodes();
                return resultArray[0].toString();
            });
            */
        }

        // test it clears multiple values in graph
        function setLiteral(sString, pString, oString) {
            $log.info("setLiteral called with s=" + sString + " p=" + pString + " o=" + oString);
            // todo : check o is a string
            var s = rdf.createNamedNode(sString)
            var p = rdf.createNamedNode(pString);
            var o = rdf.createLiteral(oString, null, null);

            $scope.graph.removeMatches(s, p, null);
            $scope.store.add(s, p, o);
        }
}]);<|endoftext|>


<commit_before>import {
  GraphQLObjectType,
  GraphQLInputObjectType,
  GraphQLString,
  GraphQLID,
  GraphQLNonNull,
} from 'graphql';

import jwt from 'jsonwebtoken';
import { auth } from '../../config';

import { User, UserClaim, UserProfile } from '../models';

const RegisterOrLogin = {
  type: new GraphQLObjectType({
    name: 'RegisterOrLogin',
    fields: {
      jwtToken: { type: GraphQLString },
    }
  }),
  args: {
    id: { type: new GraphQLNonNull(GraphQLID) },
    email: { type: GraphQLString },
    claim: {
      type: new GraphQLInputObjectType({
        name: 'InputUserClaim',
        fields: {
          accessToken: { type: GraphQLString },
        }
      })
    },
    profile: {
      type: new GraphQLInputObjectType({
        name: 'InputUserProfile',
        fields: {
          phone: { type: GraphQLString },
          displayName: { type: GraphQLString },
          gender: { type: GraphQLString },
        }
      })
    },
  },
  async resolve(obj, { id, email, claim, profile }) {
    const claimType = 'urn:facebook:access_token';
    await User.upsert({
      id: id,
      email: email,
      emailConfirmed: true,
    });

    await UserClaim.findOrCreate({
      where: {
        userId: id,
        type: claimType,
        value: claim.accessToken
      },
      defaults: {
        userId: id,
        type: claimType,
        value: claim.accessToken
      }
    });

    await UserProfile.upsert({
      userId: id,
      displayName: profile.displayName,
      gender: profile.gender,
      picture: `https://graph.facebook.com/${id}/picture?type=large`,
    });

    const user = await User.findByPrimary(id, {
      include: [
        { model: UserClaim, as: 'claims' },
        { model: UserProfile, as: 'profile' },
      ]
    });

    const expiresIn = 60 * 60 * 24 * 180; // 180 days
    let jwtToken = null;

    if (user != null) {
      jwtToken = jwt.sign(user.toJSON(), auth.jwt.secret, { expiresIn });
    }

    return { jwtToken: jwtToken };
  }
};

export default RegisterOrLogin;<commit_msg>Only retrieve 1 claim in relationship.<commit_after>import {
  GraphQLObjectType,
  GraphQLInputObjectType,
  GraphQLString,
  GraphQLID,
  GraphQLNonNull,
} from 'graphql';

import jwt from 'jsonwebtoken';
import { auth } from '../../config';

import { User, UserClaim, UserProfile } from '../models';

const RegisterOrLogin = {
  type: new GraphQLObjectType({
    name: 'RegisterOrLogin',
    fields: {
      jwtToken: { type: GraphQLString },
    }
  }),
  args: {
    id: { type: new GraphQLNonNull(GraphQLID) },
    email: { type: GraphQLString },
    claim: {
      type: new GraphQLInputObjectType({
        name: 'InputUserClaim',
        fields: {
          accessToken: { type: GraphQLString },
        }
      })
    },
    profile: {
      type: new GraphQLInputObjectType({
        name: 'InputUserProfile',
        fields: {
          phone: { type: GraphQLString },
          displayName: { type: GraphQLString },
          gender: { type: GraphQLString },
        }
      })
    },
  },
  async resolve(obj, { id, email, claim, profile }) {
    const claimType = 'urn:facebook:access_token';
    await User.upsert({
      id: id,
      email: email,
      emailConfirmed: true,
    });

    await UserClaim.findOrCreate({
      where: {
        userId: id,
        type: claimType,
        value: claim.accessToken
      },
      defaults: {
        userId: id,
        type: claimType,
        value: claim.accessToken
      }
    });

    await UserProfile.upsert({
      userId: id,
      displayName: profile.displayName,
      gender: profile.gender,
      picture: `https://graph.facebook.com/${id}/picture?type=large`,
    });

    const user = await User.findByPrimary(id, {
      include: [
        { model: UserClaim, as: 'claims', order: [['id', 'DESC']], limit: 1 },
        { model: UserProfile, as: 'profile' },
      ]
    });

    const expiresIn = 60 * 60 * 24 * 180; // 180 days
    let jwtToken = null;

    if (user != null) {
      jwtToken = jwt.sign(user.toJSON(), auth.jwt.secret, { expiresIn });
    }

    return { jwtToken: jwtToken };
  }
};

export default RegisterOrLogin;<|endoftext|>


<commit_before>$(document).ready(function() {
  // This is called after the document has loaded in its entirety
  // This guarantees that any elements we bind to will exist on the page
  // when we try to bind to them

  // See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

$('.ask-question-form').on('submit', '.new-question', function(event){
  event.preventDefault();

    var url = $(this).attr('action')

    var data =$('.new-question').serialize()

    $.ajax({
      url: url,
      type: 'POST',
      data: data
    })

    .done(function(response){
      $('.question-container').prepend(response);
    })
})

});
<commit_msg>resets form to be blank<commit_after>$(document).ready(function() {
  // This is called after the document has loaded in its entirety
  // This guarantees that any elements we bind to will exist on the page
  // when we try to bind to them

  // See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

$('.ask-question-form').on('submit', '.new-question', function(event){
  event.preventDefault();

    var url = $(this).attr('action')

    var data =$('.new-question').serialize()

    $.ajax({
      url: url,
      type: 'POST',
      data: data
    })

    .done(function(response){
      $('.question-container').prepend(response);
      $('.new-question').trigger('reset');
    })
})

});
<|endoftext|>


<commit_before>function autocomplete_source(elem) {
  return $('#search form').attr('action') + '?type=' + $('#search_type').val();
}

function add_header_field() {
  var name = prompt('Name:');

  if (!name || name.trim().length < 1) {
    return;
  }

  var key = name.trim().replace(/\s+/, '_').toLowerCase();
  var id  = '_header_' + key;

  $('#header_fields').append('
' +
    '' + name + ':
' +
    '<input type="text" id="' + id + '" name="header[' + key + ']" size="50" />' +
  '
');
}

$(document).ready(function() {
  var i = $('#main input[type=text]').first();
  if (i) {
    var v = i.val();
    if (v.trim().length < 1) {
      i.focus();
    }
  }

  $('#spinner')
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    });

  $('#search_query').autocomplete({
    source: autocomplete_source(),
    focus:  function(event, ui) {
      return false;
    },
    select: function(event, ui) {
      window.location.href = $(ui.item).val();
      return false;
    }
  });

  $('#search_type').change(function() {
    $('#search_query').autocomplete(
      'option', 'source', autocomplete_source()
    );
  });

  $('<input type="button" value="Add header field" />')
    .insertAfter('#header_fields')
    .click(add_header_field);
});
<commit_msg>Prevent adding duplicated header fields.<commit_after>function autocomplete_source(elem) {
  return $('#search form').attr('action') + '?type=' + $('#search_type').val();
}

function add_header_field() {
  var name = prompt('Name:');

  var names = $('#header_fields input').map(function() {
    return this.name;
  });

  if (jQuery.inArray('header[' + name + ']', names) > -1) {
    alert('A field named "' + name + '" already exists.');
    return;
  } else if (!name || name.trim().length < 1) {
    return;
  }

  var key = name.trim().replace(/\s+/, '_').toLowerCase();
  var id  = '_header_' + key;

  $('#header_fields').append('
' +
    '' + name + ':
' +
    '<input type="text" id="' + id + '" name="header[' + key + ']" size="50" />' +
  '
');
}

$(document).ready(function() {
  var i = $('#main input[type=text]').first();
  if (i) {
    var v = i.val();
    if (v.trim().length < 1) {
      i.focus();
    }
  }

  $('#spinner')
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    });

  $('#search_query').autocomplete({
    source: autocomplete_source(),
    focus:  function(event, ui) {
      return false;
    },
    select: function(event, ui) {
      window.location.href = $(ui.item).val();
      return false;
    }
  });

  $('#search_type').change(function() {
    $('#search_query').autocomplete(
      'option', 'source', autocomplete_source()
    );
  });

  $('<input type="button" value="Add header field" />')
    .insertAfter('#header_fields')
    .click(add_header_field);
});
<|endoftext|>


<commit_before>var prices = new Array();

var stageWidth;
var stageHeight;

var highest;
var lowest;
var onePixelPrice;
var candleWidth;
var candleMargin = 10;

var stage;
var candleStickContainer;
var initialScaling = 0;

var days = 20;

var movingAverageContainers = new Array();

function init() {

	// stage initialisieren
	stage = new createjs.Stage("chartCanvas");

	stageWidth = $("#chartCanvas").width();
	stageHeight = $("#chartCanvas").height();

	candleStickContainerWidth = stageWidth - 200;
	candleStickContainerHeight = stageHeight - 100;
	candleStickContainerLeft = 100;
	candleStickContainerTop = 50;

	// text einfügen
	var text = new createjs.Text(stock.symbol, '13px Arial', '#000000');
	text.x = 6;
	text.y = 7;
	stage.addChild(text);

	// button erstellen
	// sprite = new Image();
    // sprite.src = '/img/button.png';
    // sprite.onload = addButton;

	loadPrices(20);
}

function loadPrices(daysToGet) {
	days = daysToGet;
	$.ajax({
        type: "GET",
        crossDomain: false,
        url: "/stock/loadPrices/" + stock.id + "/" + days,
        dataType: "json",
        success: drawPrices
    });
}

function drawPrices(data, textStatus, jqXHR) {

	prices = data.prices;

	// remove old stuff
	stage.removeChild(candleStickContainer);
	for (i=0; i<movingAverageContainers.length; i++) {
		if (typeof movingAverageContainers[i] !== 'undefined') {
			stage.removeChild(movingAverageContainers[i]);
		}
	}
	stage.update();

	// add candlestickcontainer
	candleStickContainer = createCandleStickContainer(prices.slice(0, days));
	stage.addChild(candleStickContainer);

	// redraw moving averages if necessary
	for (i=0; i<movingAverageContainers.length; i++) {
		if (typeof movingAverageContainers[i] !== 'undefined') {
			var movingAverageData = calculateMovingAverage(i);
			movingAverageContainers[i] = drawMovingAverage(i, movingAverageData);
			stage.addChild(movingAverageContainers[i]);
		}
	}
}

function drawMovingAverage(period, movingAverageData) {

	var color = null;
	switch (period) {
		case 10: color = createjs.Graphics.getRGB(0,0,200); break;
		case 20: color = createjs.Graphics.getRGB(51,153,0); break;
		case 30: color = createjs.Graphics.getRGB(255,153,0); break;
	}

	// calculate coordinates
	var coordinates = new Array();
	for (var i=0; i<days; i++) {
		coordinates[i] = new Object();
		coordinates[i]['x'] = candleStickContainerWidth - (candleWidth * (i + 1)) + (candleWidth / 2);
		coordinates[i]['x'] = coordinates[i]['x'] - ((i + 1) * candleMargin);
		coordinates[i]['y'] = calculateTopInPixelsFromPrice(movingAverageData[i].value);
	}

	var movingAverageContainer = new createjs.Container();

	for (var i=0; i<days; i++) {

		var g = new createjs.Graphics();
		g.setStrokeStyle(1);
		g.beginStroke(color);
		g.beginFill(color);
		g.drawCircle(0,0,2);

		// create shape
		var s = new createjs.Shape(g);
		s.x = coordinates[i]['x'];
		s.y = coordinates[i]['y'];

		//candleStickContainer.addChild(s);
		movingAverageContainer.addChild(s);
	}

	movingAverageContainer.x = candleStickContainerLeft;
	movingAverageContainer.y = candleStickContainerTop;

	return movingAverageContainer;

	//	g.moveTo(0, 0);
	//	g.lineTo(100, 100);
	//	g.bezierCurveTo (0, 50, 50, 50, 100, 100);
}

function calculateMovingAverage(movingAveragePeriod) {

	// generate moving average of each price
	var movingAverage = new Array();

	for (var i=0; i<prices.length; i++) {

		if (prices.length - i < movingAveragePeriod) {
			break;
		}

		var tmp = 0.00;
		for (j = i; j < i + movingAveragePeriod; j++) {
			tmp += prices[j]['close'];
		}

		movingAverage[i] = new Object();
		movingAverage[i]['date'] = prices[i]['date'];
		movingAverage[i]['value'] = Math.round(tmp / movingAveragePeriod * 100) / 100;
	}

	return movingAverage;
}<commit_msg>chart now shown an error msg when no prices are found.<commit_after>var prices = new Array();

var stageWidth;
var stageHeight;

var highest;
var lowest;
var onePixelPrice;
var candleWidth;
var candleMargin = 10;

var stage;
var candleStickContainer;
var initialScaling = 0;

var days = 20;

var movingAverageContainers = new Array();

function init() {

	// stage initialisieren
	stage = new createjs.Stage("chartCanvas");

	stageWidth = $("#chartCanvas").width();
	stageHeight = $("#chartCanvas").height();

	candleStickContainerWidth = stageWidth - 200;
	candleStickContainerHeight = stageHeight - 100;
	candleStickContainerLeft = 100;
	candleStickContainerTop = 50;

	// text einfügen
	var text = new createjs.Text(stock.symbol, '13px Arial', '#000000');
	text.x = 6;
	text.y = 7;
	stage.addChild(text);

	// button erstellen
	// sprite = new Image();
    // sprite.src = '/img/button.png';
    // sprite.onload = addButton;

	loadPrices(20);
}

function loadPrices(daysToGet) {
	days = daysToGet;
	$.ajax({
        type: "GET",
        crossDomain: false,
        url: "/stock/loadPrices/" + stock.id + "/" + days,
        dataType: "json",
        success: drawPrices
    });
}

function drawPrices(data, textStatus, jqXHR) {

	prices = data.prices;

	// remove old stuff
	stage.removeChild(candleStickContainer);
	for (i=0; i<movingAverageContainers.length; i++) {
		if (typeof movingAverageContainers[i] !== 'undefined') {
			stage.removeChild(movingAverageContainers[i]);
		}
	}
	stage.update();

	if (prices.length < 1) {
		var text = new createjs.Text('Für diese Aktie sind noch keine Kurse in der Datenbank vorhanden.', '13px Arial', '#000000');
		text.x = 6;
		text.y = 25;
		stage.addChild(text);
		stage.update();
		return;
	}

	// add candlestickcontainer
	candleStickContainer = createCandleStickContainer(prices.slice(0, days));
	stage.addChild(candleStickContainer);

	// redraw moving averages if necessary
	for (i=0; i<movingAverageContainers.length; i++) {
		if (typeof movingAverageContainers[i] !== 'undefined') {
			var movingAverageData = calculateMovingAverage(i);
			movingAverageContainers[i] = drawMovingAverage(i, movingAverageData);
			stage.addChild(movingAverageContainers[i]);
		}
	}
}

function drawMovingAverage(period, movingAverageData) {

	var color = null;
	switch (period) {
		case 10: color = createjs.Graphics.getRGB(0,0,200); break;
		case 20: color = createjs.Graphics.getRGB(51,153,0); break;
		case 30: color = createjs.Graphics.getRGB(255,153,0); break;
	}

	// calculate coordinates
	var coordinates = new Array();
	for (var i=0; i<days; i++) {
		coordinates[i] = new Object();
		coordinates[i]['x'] = candleStickContainerWidth - (candleWidth * (i + 1)) + (candleWidth / 2);
		coordinates[i]['x'] = coordinates[i]['x'] - ((i + 1) * candleMargin);
		coordinates[i]['y'] = calculateTopInPixelsFromPrice(movingAverageData[i].value);
	}

	var movingAverageContainer = new createjs.Container();

	for (var i=0; i<days; i++) {

		var g = new createjs.Graphics();
		g.setStrokeStyle(1);
		g.beginStroke(color);
		g.beginFill(color);
		g.drawCircle(0,0,2);

		// create shape
		var s = new createjs.Shape(g);
		s.x = coordinates[i]['x'];
		s.y = coordinates[i]['y'];

		//candleStickContainer.addChild(s);
		movingAverageContainer.addChild(s);
	}

	movingAverageContainer.x = candleStickContainerLeft;
	movingAverageContainer.y = candleStickContainerTop;

	return movingAverageContainer;

	//	g.moveTo(0, 0);
	//	g.lineTo(100, 100);
	//	g.bezierCurveTo (0, 50, 50, 50, 100, 100);
}

function calculateMovingAverage(movingAveragePeriod) {

	// generate moving average of each price
	var movingAverage = new Array();

	for (var i=0; i<prices.length; i++) {

		if (prices.length - i < movingAveragePeriod) {
			break;
		}

		var tmp = 0.00;
		for (j = i; j < i + movingAveragePeriod; j++) {
			tmp += prices[j]['close'];
		}

		movingAverage[i] = new Object();
		movingAverage[i]['date'] = prices[i]['date'];
		movingAverage[i]['value'] = Math.round(tmp / movingAveragePeriod * 100) / 100;
	}

	return movingAverage;
}<|endoftext|>


<commit_before>var saving = {
  todo: {
    html: false,
    css: false,
    javascript: false
  },
  _inprogress: false,
  inprogress: function (inprogress) {
    if (typeof inprogress === 'undefined') {
      return saving._inprogress;
    }

    saving._inprogress = inprogress;
    if (inprogress === false) {
      var panels = ['html','css','javascript'],
          todo;

      var save = function () {
        var todo = panels.pop();
        if (todo && saving.todo[todo]) {
          saving._inprogress = true;
          updateCode(todo, save);
          saving.todo[todo] = false;
        } else if (todo) {
          save();
        }
      };

      save();
    }
  }
};

// to allow for download button to be introduced via beta feature
$('a.save').click(function (event) {
  event.preventDefault();

  analytics.milestone();
  // if save is disabled, hitting save will trigger a reload
  var ajax = true;
  if (jsbin.saveDisabled === true) {
    ajax = false;
  }
  saveCode('save', ajax);

  return false;
});

var $shareLinks = $('#share .link');

$panelCheckboxes = $('#sharemenu #sharepanels input');

function updateSavedState() {
  var mapping = {
    live: 'output',
    javascript: 'js',
    css: 'css',
    html: 'html',
    console: 'console'
  };
  var query = $panelCheckboxes.filter(':checked').map(function () {
    return mapping[this.getAttribute('data-panel')];
  }).get().join(',');
  $shareLinks.each(function () {
    var path = this.getAttribute('data-path');
    var url = jsbin.getURL(false, path === '/') + path + (query && this.id !== 'livepreview' ? '?' + query : ''),
        nodeName = this.nodeName;
    if (nodeName === 'A') {
      this.href = url;
    } else if (nodeName === 'INPUT') {
      this.value = url;
    } else if (nodeName === 'TEXTAREA') {
      this.value = ('' + documentTitle + '<' + 'script src="' + jsbin.static + '/js/embed.js"><' + '/script>').replace(/<>"&/g, function (m) {
          return {
            '<': '<',
            '>': '>',
            '"': '"',
            '&': '&'
          }[m];
        });
    }
  });
}

$('#sharemenu').bind('open', function () {
  updateSavedState();
});

$document.on('saved', function () {
  updateSavedState();
  $shareLinks.closest('.menu').removeClass('hidden');

  $('#jsbinurl').attr('href', jsbin.getURL()).removeClass('hidden');
  $('#clone').removeClass('hidden');
});

var saveChecksum = jsbin.state.checksum || sessionStorage.getItem('checksum') || false;

// store it back on state
jsbin.state.checksum = saveChecksum;

if (saveChecksum) {
  // remove the disabled class, but also remove the cancelling event handlers
  $('#share div.disabled').removeClass('disabled').unbind('click mousedown mouseup');
} else {
  $('#share div.disabled').one('click', function (event) {
    event.preventDefault();
    $('a.save').click();
  });
}

$document.one('saved', function () {
  $('#share div.disabled').removeClass('disabled').unbind('click mousedown mouseup');
});

function onSaveError(jqXHR, panelId) {
  if (jqXHR.status === 413) {
    // Hijack the tip label to show an error message.
    $('#tip p').html('Sorry this bin is too large for us to save');
    $(document.documentElement).addClass('showtip');
  } else if (jqXHR.status === 403) {
    $document.trigger('tip', {
      type: 'error',
      content: 'I think there\'s something wrong with your session and I\'m unable to save. Refresh to fix this, you will not lose your code.'
    });
  } else if (panelId) {
    if (panelId) savingLabels[panelId].text('Saving...').animate({ opacity: 1 }, 100);
    window._console.error({message: 'Warning: Something went wrong while saving. Your most recent work is not saved.'});
  }
}

// only start live saving it they're allowed to (whereas save is disabled if they're following)
if (!jsbin.saveDisabled) {
  $('.code.panel .label .name').append('Saved');

  var savingLabels = {
    html: $('.panel.html .name span'),
    javascript: $('.panel.javascript .name span'),
    css: $('.panel.css .name span')
  };

  $document.bind('jsbinReady', function () {
    jsbin.panels.allEditors(function (panel) {
      panel.on('processor', function () {
        // if the url doesn't match the root - i.e. they've actually saved something then save on processor change
        if (jsbin.root !== jsbin.getURL()) {
          $document.trigger('codeChange', [{ panelId: panel.id }]);
        }
      });
    });

    $document.bind('codeChange', function (event, data) {
      // savingLabels[data.panelId].text('Saving');
      if (savingLabels[data.panelId]) {
        savingLabels[data.panelId].css({ 'opacity': 0 }).stop(true, true);
      }
    });

    $document.bind('saveComplete', throttle(function (event, data) {
      // show saved, then revert out animation
      savingLabels[data.panelId]
        .text('Saved')
        .stop(true, true)
        .animate({ opacity: 1 }, 100)
        .delay(1200)
        .animate({ opacity: 0 }, 500);
    }, 500));

    $document.bind('codeChange', throttle(function (event, data) {
      if (!data.panelId) {
        return;
      }

      if (jsbin.state.deleted) {
        return;
      }

      var panelId = data.panelId;

      jsbin.panels.savecontent();

      if (saving.inprogress()) {
        // queue up the request and wait
        saving.todo[panelId] = true;
        return;
      }

      saving.inprogress(true);

      // We force a full save if there's no checksum OR if there's no bin code/url
      if (!saveChecksum || !jsbin.state.code) {
        // create the bin and when the response comes back update the url
        saveCode('save', true);
      } else {
        updateCode(panelId);
      }
    }, 250));
  });
} else {
  $document.one('jsbinReady', function () {
    var shown = false;
    if (!jsbin.embed && !jsbin.sandbox) {
      $document.on('codeChange', function (event, data) {
        if (!data.onload && !shown && data.origin !== 'setValue') {
          shown = true;
          var ismac = navigator.userAgent.indexOf(' Mac ') !== -1;
          var cmd = ismac ? '⌘' : 'ctrl';
          var shift = ismac ? '⇧' : 'shift';
          var plus = ismac ? '' : '+';

          $document.trigger('tip', {
            type: 'notification',
            content: 'You\'re currently viewing someone else\'s live stream, but you can clone your own copy (' + cmd + plus + shift + plus + 'S) at any time to save your edits'
          });
        }
      });
    }
  });
}

function updateCode(panelId, callback) {
  var panelSettings = {};

  if (jsbin.state.processors) {
    panelSettings.processors = jsbin.state.processors;
  }

  $.ajax({
    url: jsbin.getURL() + '/save',
    data: {
      code: jsbin.state.code,
      revision: jsbin.state.revision,
      method: 'update',
      panel: panelId,
      content: editors[panelId].getCode(),
      checksum: saveChecksum,
      settings: JSON.stringify(panelSettings)
    },
    type: 'post',
    dataType: 'json',
    headers: {'Accept': 'application/json'},
    success: function (data) {
      $document.trigger('saveComplete', { panelId: panelId });
      if (data.error) {
        saveCode('save', true, function (data) {
          // savedAlready = data.checksum;
        });
      }
    },
    error: function (jqXHR) {
      onSaveError(jqXHR, panelId);
    },
    complete: function () {
      saving.inprogress(false);
      callback && callback();
    }
  });
}

$('a.clone').click(function (event) {
  event.preventDefault();

  // save our panel layout - assumes our user is happy with this layout
  jsbin.panels.save();
  analytics.clone();

  var $form = setupform('save,new');
  $form.submit();

  return false;
});

function setupform(method) {
var $form = $('form#saveform').empty()
    .append('<input type="hidden" name="javascript" />')
    .append('<input type="hidden" name="html" />')
    .append('<input type="hidden" name="css" />')
    .append('<input type="hidden" name="method" />')
    .append('<input type="hidden" name="_csrf" value="' + jsbin.state.token + '" />')
    .append('<input type="hidden" name="settings" />');

  var settings = {};

  if (jsbin.state.processors) {
    settings.processors = jsbin.state.processors;
  }

  // this prevents new revisions forking off the welcome bin
  // because it's looking silly!
  if (jsbin.state.code === 'welcome') {
    $form.attr('action', '/save');
  }

  $form.find('input[name=settings]').val(JSON.stringify(settings));
  $form.find('input[name=javascript]').val(editors.javascript.getCode());
  $form.find('input[name=css]').val(editors.css.getCode());
  $form.find('input[name=html]').val(editors.html.getCode());
  $form.find('input[name=method]').val(method);

  return $form;
}

function pad(n){
  return n<10 ? '0'+n : n
}

function ISODateString(d){
  return d.getFullYear()+'-'
    + pad(d.getMonth()+1)+'-'
    + pad(d.getDate())+'T'
    + pad(d.getHours())+':'
    + pad(d.getMinutes())+':'
    + pad(d.getSeconds())+'Z'
}

function saveCode(method, ajax, ajaxCallback) {
  // create form and post to it
  var $form = setupform(method);
  // save our panel layout - assumes our user is happy with this layout
  jsbin.panels.save();
  jsbin.panels.saveOnExit = true;

  if (ajax) {
    $.ajax({
      url: $form.attr('action'),
      data: $form.serialize(),
      dataType: 'json',
      type: 'post',
      headers: {'Accept': 'application/json'},
      success: function (data) {
        var $binGroup,
            edit;

        $form.attr('action', data.url + '/save');
        if (ajaxCallback) {
          ajaxCallback(data);
        }

        sessionStorage.setItem('checksum', data.checksum);
        saveChecksum = data.checksum;

        jsbin.state.checksum = saveChecksum;
        jsbin.state.code = data.code;
        jsbin.state.revision = data.revision;
        jsbin.state.metadata = { name: jsbin.user.name };

        // getURL(true) gets the jsbin without the root attached
        // $binGroup = $('#history tr[data-url="' + jsbin.getURL(true) + '"]');
        // edit = data.edit.replace(location.protocol + '//' + window.location.host, '') + window.location.search;
        // $binGroup.find('td.url a span.first').removeClass('first');
        // $binGroup.before('
' + data.code + '/' + data.revision + '/	Just now	' + data.title + '
');

        if (window.history && window.history.pushState) {
          // updateURL(edit);
          window.history.pushState(null, '', jsbin.getURL() + '/edit');
          sessionStorage.setItem('url', jsbin.getURL());
        } else {
          window.location.hash = data.edit;
        }

        $document.trigger('saved');
      },
      error: function (jqXHR) {
        onSaveError(jqXHR, null);
      },
      complete: function () {
        saving.inprogress(false);
      }
    });
  } else {
    $form.submit();
  }
}

/**
 * Returns the similar part of two strings
 * @param  {String} a first string
 * @param  {String} b second string
 * @return {String}   common substring
 */
function sameStart(a, b) {
  if (a == b) return a;

  var tmp = b.slice(0, 1);
  while (a.indexOf(b.slice(0, tmp.length + 1)) === 0) {
    tmp = b.slice(0, tmp.length + 1);
  }

  return tmp;
}

/*

// refresh the window when we popstate, because for now we don't do an xhr to
// inject the panel content...yet.
window.onpopstate = function onpopstate(event) {
  // ignore the first popstate event, because that comes from the browser...
  if (!onpopstate.first) window.location.reload();
  else onpopstate.first = false;
};

onpopstate.first = true;

function updateURL(path) {
  var old = location.pathname,
      back = true,
      same = sameStart(old, path);
      sameAt = same.length;

  if (updateURL.timer) window.cancelAnimationFrame(updateURL.timer);

  var run = function () {
    if (location.pathname !== path) {
      updateURL.timer = window.requestAnimationFrame(run);
    }

    if (location.pathname !== same) {
      if (back) {
        history.replaceState({ path: path }, '', location.pathname.slice(0, -1));
      } else {
        history.replaceState({ path: path }, '', path.slice(0, location.pathname.length + 1));
      }
    } else {
      back = false;
      history.replaceState({ path: path }, '', path.slice(0, sameAt + 2));
    }
  };

  history.pushState({ path: path }, '', location.pathname.slice(0, -1));

  run();
}

*/
<commit_msg>Compress the content for each POST to /<url>/save<commit_after>var saving = {
  todo: {
    html: false,
    css: false,
    javascript: false
  },
  _inprogress: false,
  inprogress: function (inprogress) {
    if (typeof inprogress === 'undefined') {
      return saving._inprogress;
    }

    saving._inprogress = inprogress;
    if (inprogress === false) {
      var panels = ['html','css','javascript'],
          todo;

      var save = function () {
        var todo = panels.pop();
        if (todo && saving.todo[todo]) {
          saving._inprogress = true;
          updateCode(todo, save);
          saving.todo[todo] = false;
        } else if (todo) {
          save();
        }
      };

      save();
    }
  }
};

// to allow for download button to be introduced via beta feature
$('a.save').click(function (event) {
  event.preventDefault();

  analytics.milestone();
  // if save is disabled, hitting save will trigger a reload
  var ajax = true;
  if (jsbin.saveDisabled === true) {
    ajax = false;
  }
  saveCode('save', ajax);

  return false;
});

var $shareLinks = $('#share .link');

$panelCheckboxes = $('#sharemenu #sharepanels input');

function updateSavedState() {
  var mapping = {
    live: 'output',
    javascript: 'js',
    css: 'css',
    html: 'html',
    console: 'console'
  };
  var query = $panelCheckboxes.filter(':checked').map(function () {
    return mapping[this.getAttribute('data-panel')];
  }).get().join(',');
  $shareLinks.each(function () {
    var path = this.getAttribute('data-path');
    var url = jsbin.getURL(false, path === '/') + path + (query && this.id !== 'livepreview' ? '?' + query : ''),
        nodeName = this.nodeName;
    if (nodeName === 'A') {
      this.href = url;
    } else if (nodeName === 'INPUT') {
      this.value = url;
    } else if (nodeName === 'TEXTAREA') {
      this.value = ('' + documentTitle + '<' + 'script src="' + jsbin.static + '/js/embed.js"><' + '/script>').replace(/<>"&/g, function (m) {
          return {
            '<': '<',
            '>': '>',
            '"': '"',
            '&': '&'
          }[m];
        });
    }
  });
}

$('#sharemenu').bind('open', function () {
  updateSavedState();
});

$document.on('saved', function () {
  updateSavedState();
  $shareLinks.closest('.menu').removeClass('hidden');

  $('#jsbinurl').attr('href', jsbin.getURL()).removeClass('hidden');
  $('#clone').removeClass('hidden');
});

var saveChecksum = jsbin.state.checksum || sessionStorage.getItem('checksum') || false;

// store it back on state
jsbin.state.checksum = saveChecksum;

if (saveChecksum) {
  // remove the disabled class, but also remove the cancelling event handlers
  $('#share div.disabled').removeClass('disabled').unbind('click mousedown mouseup');
} else {
  $('#share div.disabled').one('click', function (event) {
    event.preventDefault();
    $('a.save').click();
  });
}

$document.one('saved', function () {
  $('#share div.disabled').removeClass('disabled').unbind('click mousedown mouseup');
});

function onSaveError(jqXHR, panelId) {
  if (jqXHR.status === 413) {
    // Hijack the tip label to show an error message.
    $('#tip p').html('Sorry this bin is too large for us to save');
    $(document.documentElement).addClass('showtip');
  } else if (jqXHR.status === 403) {
    $document.trigger('tip', {
      type: 'error',
      content: 'I think there\'s something wrong with your session and I\'m unable to save. Refresh to fix this, you will not lose your code.'
    });
  } else if (panelId) {
    if (panelId) savingLabels[panelId].text('Saving...').animate({ opacity: 1 }, 100);
    window._console.error({message: 'Warning: Something went wrong while saving. Your most recent work is not saved.'});
  }
}

// only start live saving it they're allowed to (whereas save is disabled if they're following)
if (!jsbin.saveDisabled) {
  $('.code.panel .label .name').append('Saved');

  var savingLabels = {
    html: $('.panel.html .name span'),
    javascript: $('.panel.javascript .name span'),
    css: $('.panel.css .name span')
  };

  $document.bind('jsbinReady', function () {
    jsbin.panels.allEditors(function (panel) {
      panel.on('processor', function () {
        // if the url doesn't match the root - i.e. they've actually saved something then save on processor change
        if (jsbin.root !== jsbin.getURL()) {
          $document.trigger('codeChange', [{ panelId: panel.id }]);
        }
      });
    });

    $document.bind('codeChange', function (event, data) {
      // savingLabels[data.panelId].text('Saving');
      if (savingLabels[data.panelId]) {
        savingLabels[data.panelId].css({ 'opacity': 0 }).stop(true, true);
      }
    });

    $document.bind('saveComplete', throttle(function (event, data) {
      // show saved, then revert out animation
      savingLabels[data.panelId]
        .text('Saved')
        .stop(true, true)
        .animate({ opacity: 1 }, 100)
        .delay(1200)
        .animate({ opacity: 0 }, 500);
    }, 500));

    $document.bind('codeChange', throttle(function (event, data) {
      if (!data.panelId) {
        return;
      }

      if (jsbin.state.deleted) {
        return;
      }

      var panelId = data.panelId;

      jsbin.panels.savecontent();

      if (saving.inprogress()) {
        // queue up the request and wait
        saving.todo[panelId] = true;
        return;
      }

      saving.inprogress(true);

      // We force a full save if there's no checksum OR if there's no bin code/url
      if (!saveChecksum || !jsbin.state.code) {
        // create the bin and when the response comes back update the url
        saveCode('save', true);
      } else {
        updateCode(panelId);
      }
    }, 250));
  });
} else {
  $document.one('jsbinReady', function () {
    var shown = false;
    if (!jsbin.embed && !jsbin.sandbox) {
      $document.on('codeChange', function (event, data) {
        if (!data.onload && !shown && data.origin !== 'setValue') {
          shown = true;
          var ismac = navigator.userAgent.indexOf(' Mac ') !== -1;
          var cmd = ismac ? '⌘' : 'ctrl';
          var shift = ismac ? '⇧' : 'shift';
          var plus = ismac ? '' : '+';

          $document.trigger('tip', {
            type: 'notification',
            content: 'You\'re currently viewing someone else\'s live stream, but you can clone your own copy (' + cmd + plus + shift + plus + 'S) at any time to save your edits'
          });
        }
      });
    }
  });
}

function updateCode(panelId, callback) {
  var panelSettings = {};

  if (jsbin.state.processors) {
    panelSettings.processors = jsbin.state.processors;
  }

  $.ajax({
    url: jsbin.getURL() + '/save',
    data: {
      code: jsbin.state.code,
      revision: jsbin.state.revision,
      method: 'update',
      panel: panelId,
      content: LZString.compress(editors[panelId].getCode()),
      checksum: saveChecksum,
      settings: JSON.stringify(panelSettings),
      compressed: 'content'
    },
    type: 'post',
    dataType: 'json',
    headers: {'Accept': 'application/json'},
    success: function (data) {
      $document.trigger('saveComplete', { panelId: panelId });
      if (data.error) {
        saveCode('save', true, function (data) {
          // savedAlready = data.checksum;
        });
      }
    },
    error: function (jqXHR) {
      onSaveError(jqXHR, panelId);
    },
    complete: function () {
      saving.inprogress(false);
      callback && callback();
    }
  });
}

$('a.clone').click(function (event) {
  event.preventDefault();

  // save our panel layout - assumes our user is happy with this layout
  jsbin.panels.save();
  analytics.clone();

  var $form = setupform('save,new');
  $form.submit();

  return false;
});

function setupform(method) {
var $form = $('form#saveform').empty()
    .append('<input type="hidden" name="javascript" />')
    .append('<input type="hidden" name="html" />')
    .append('<input type="hidden" name="css" />')
    .append('<input type="hidden" name="method" />')
    .append('<input type="hidden" name="_csrf" value="' + jsbin.state.token + '" />')
    .append('<input type="hidden" name="settings" />');

  var settings = {};

  if (jsbin.state.processors) {
    settings.processors = jsbin.state.processors;
  }

  // this prevents new revisions forking off the welcome bin
  // because it's looking silly!
  if (jsbin.state.code === 'welcome') {
    $form.attr('action', '/save');
  }

  $form.find('input[name=settings]').val(JSON.stringify(settings));
  $form.find('input[name=javascript]').val(editors.javascript.getCode());
  $form.find('input[name=css]').val(editors.css.getCode());
  $form.find('input[name=html]').val(editors.html.getCode());
  $form.find('input[name=method]').val(method);

  return $form;
}

function pad(n){
  return n<10 ? '0'+n : n
}

function ISODateString(d){
  return d.getFullYear()+'-'
    + pad(d.getMonth()+1)+'-'
    + pad(d.getDate())+'T'
    + pad(d.getHours())+':'
    + pad(d.getMinutes())+':'
    + pad(d.getSeconds())+'Z'
}

function saveCode(method, ajax, ajaxCallback) {
  // create form and post to it
  var $form = setupform(method);
  // save our panel layout - assumes our user is happy with this layout
  jsbin.panels.save();
  jsbin.panels.saveOnExit = true;

  if (ajax) {
    $.ajax({
      url: $form.attr('action'),
      data: $form.serialize(),
      dataType: 'json',
      type: 'post',
      headers: {'Accept': 'application/json'},
      success: function (data) {
        var $binGroup,
            edit;

        $form.attr('action', data.url + '/save');
        if (ajaxCallback) {
          ajaxCallback(data);
        }

        sessionStorage.setItem('checksum', data.checksum);
        saveChecksum = data.checksum;

        jsbin.state.checksum = saveChecksum;
        jsbin.state.code = data.code;
        jsbin.state.revision = data.revision;
        jsbin.state.metadata = { name: jsbin.user.name };

        // getURL(true) gets the jsbin without the root attached
        // $binGroup = $('#history tr[data-url="' + jsbin.getURL(true) + '"]');
        // edit = data.edit.replace(location.protocol + '//' + window.location.host, '') + window.location.search;
        // $binGroup.find('td.url a span.first').removeClass('first');
        // $binGroup.before('
' + data.code + '/' + data.revision + '/	Just now	' + data.title + '
');

        if (window.history && window.history.pushState) {
          // updateURL(edit);
          window.history.pushState(null, '', jsbin.getURL() + '/edit');
          sessionStorage.setItem('url', jsbin.getURL());
        } else {
          window.location.hash = data.edit;
        }

        $document.trigger('saved');
      },
      error: function (jqXHR) {
        onSaveError(jqXHR, null);
      },
      complete: function () {
        saving.inprogress(false);
      }
    });
  } else {
    $form.submit();
  }
}

/**
 * Returns the similar part of two strings
 * @param  {String} a first string
 * @param  {String} b second string
 * @return {String}   common substring
 */
function sameStart(a, b) {
  if (a == b) return a;

  var tmp = b.slice(0, 1);
  while (a.indexOf(b.slice(0, tmp.length + 1)) === 0) {
    tmp = b.slice(0, tmp.length + 1);
  }

  return tmp;
}

/*

// refresh the window when we popstate, because for now we don't do an xhr to
// inject the panel content...yet.
window.onpopstate = function onpopstate(event) {
  // ignore the first popstate event, because that comes from the browser...
  if (!onpopstate.first) window.location.reload();
  else onpopstate.first = false;
};

onpopstate.first = true;

function updateURL(path) {
  var old = location.pathname,
      back = true,
      same = sameStart(old, path);
      sameAt = same.length;

  if (updateURL.timer) window.cancelAnimationFrame(updateURL.timer);

  var run = function () {
    if (location.pathname !== path) {
      updateURL.timer = window.requestAnimationFrame(run);
    }

    if (location.pathname !== same) {
      if (back) {
        history.replaceState({ path: path }, '', location.pathname.slice(0, -1));
      } else {
        history.replaceState({ path: path }, '', path.slice(0, location.pathname.length + 1));
      }
    } else {
      back = false;
      history.replaceState({ path: path }, '', path.slice(0, sameAt + 2));
    }
  };

  history.pushState({ path: path }, '', location.pathname.slice(0, -1));

  run();
}

*/
<|endoftext|>