<commit_before>function Turtle(x = 0, y = 0, head = 0, step = 40, delta = Math.PI / 2, system) {
    var initVocab = {
        F: 'F,-,F,+,F,F,-,F,-,F,+,F',
        '-': '-',
        '+': '+'
    };
    DOL.call(this, initVocab, 'F,-,F,-,F,-,F');
    this.position = {
        x: x,
        y: y
    };
    this.heading = head;
    this.step = step;
    this.delta = delta;
    this.stepFactor = 0.25;
    this.points = new Array([this.position.x, this.position.y]);
    this.commands = {
        F: this.forward,
        f: this.blankForward,
        '-': this.clockwise,
        '+': this.counterClockwise
    };
    this.pLoc = new p5.Vector(x, y);
    this.startPosition = this.pLoc.copy();
    this.hVector = new p5.Vector.fromAngle(head).mult(step);
    console.log(this.hVector);
}
Turtle.prototype = Object.create(DOL.prototype);

Turtle.prototype.forward = function(draw = true) {
    this.pLoc.add(this.hVector);
    console.log(this.pLoc);
    var dx = Math.cos(this.heading) * this.step;
    var dy = Math.sin(this.heading) * this.step;
    this.position.x += dx;
    this.position.y += dy;
    this.points.push([this.position.x, this.position.y]);
    console.log('postion');
};

Turtle.prototype.blankForward = function() {
    this.forward(false);
};

Turtle.prototype.clockwise = function() {
    this.heading += this.delta;
    this.hVector.rotate(this.heading);
    console.log(this.heading);

};

Turtle.prototype.counterClockwise = function() {
    this.heading -= this.delta;
    this.hVector.rotate(-1 * (this.heading));
    console.log(this.heading);

};

Turtle.prototype.interpret = function() {
    var splitString = this.string.split(',');
    splitString.forEach(function(el) {
        if (this.commands[el] != false) {
            this.commands[el].call(this);
        }
    }, this);
};

Turtle.prototype.spawn = function(depth = 1) {
    for (var i = depth - 1; i >= 0; i--) {
        DOL.prototype.spawn.call(this);
        this.step *= this.stepFactor;
    }

};<commit_msg>refactors turtle position and heaing with p5 Vectors<commit_after>function Turtle(x = 0, y = 0, head = 0, step = 40, delta = Math.PI / 2, system) {
    var initVocab = {
        F: 'F,-,F,+,F,F,-,F,-,F,+,F',
        '-': '-',
        '+': '+'
    };
    DOL.call(this, initVocab, 'F,-,F,-,F,-,F');
    // this.position = {
    //     x: x,
    //     y: y
    // };
    this.position = new p5.Vector(x, y);
    this.startPosition = this.position.copy();
    this.hVector = new p5.Vector.fromAngle(head).mult(step);

    this.heading = this.hVector.heading();
    this.step = step;
    this.delta = delta;
    this.stepFactor = 0.25;
    this.points = new Array(this.position);
    this.commands = {
        F: this.forward,
        f: this.blankForward,
        '-': this.clockwise,
        '+': this.counterClockwise
    };
    console.log(this.hVector);
}
Turtle.prototype = Object.create(DOL.prototype);

Turtle.prototype.forward = function(draw = true) {
    this.position.add(this.hVector);
    console.log(this.position);
    // var dx = Math.cos(this.heading) * this.step;
    // var dy = Math.sin(this.heading) * this.step;
    // this.position.x += dx;
    // this.position.y += dy;
    this.points.push(this.position);
    console.log('postion');
};

Turtle.prototype.blankForward = function() {
    this.forward(false);
};

Turtle.prototype.clockwise = function() {
    // this.heading += this.delta;
    this.hVector.rotate(this.delta);
    this.heading = this.hVector.heading();
    console.log(this.heading);

};

Turtle.prototype.counterClockwise = function() {
    // this.heading -= this.delta;
    this.hVector.rotate(-1 * (this.delta));
    this.heading = this.hVector.heading();

    console.log(this.heading);

};

Turtle.prototype.interpret = function() {
    var splitString = this.string.split(',');
    splitString.forEach(function(el) {
        if (this.commands[el] != false) {
            this.commands[el].call(this);
        }
    }, this);
};

Turtle.prototype.spawn = function(depth = 1) {
    for (var i = depth - 1; i >= 0; i--) {
        DOL.prototype.spawn.call(this);
        this.step *= this.stepFactor;
    }

};<|endoftext|>


<commit_before>/*
 * Allow you smoothly surf on many websites blocking non-mainland visitors.
 * Copyright (C) 2012 - 2014  Bo Zhu  http://zhuzhu.org
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/*jshint devel:true, globalstrict: true */
/*global chrome: false, unblock_youku: false, new_sogou_proxy_addr: false, urls2pac: false, get_mode_name: false */
/*global ga_report_timeout: false, ga_report_error: false, ga_report_event: false */
"use strict";

function setup_pac_data(proxy_domain) {
    var pac_data = urls2pac([], unblock_youku.normal_url_list, proxy_domain, 'HTTPS');
    console.log(pac_data);
    var proxy_config = {
        mode: 'pac_script',
        pacScript: {
            data: pac_data
        }
    };
    chrome.proxy.settings.set(
        {
            value: proxy_config,
            scope: 'regular'
        },
        function() {
            return;
        }
    );
}

function setup_proxy(depth) {  // depth for recursion
    if (typeof depth === 'undefined') {
        depth = 0;  // recursion depth
        console.group('to set up proxy');
    }

    var test_server = 'proxy.mainland.io:993';
    // var test_server = 'proxy.uku.im:8888';
    setup_pac_data(test_server);
    console.log('using experimental server: ' + test_server);
    ga_report_event('Proxy Server Selection', test_server, 0.1);
    console.groupEnd();

    /*
    var proxy_addr = new_sogou_proxy_addr();
    console.log('using proxy: ' + proxy_addr);
    setup_pac_data(proxy_addr);  // should set up PAC already

    console.log('to check if the proxy server is avaiable: ' + proxy_addr);
    console.log((depth + 1) + '-th time to test proxy servers');
    var xhr = new XMLHttpRequest();

    // test timeout
    var xhr_timer = setTimeout(function() {
        xhr.abort();
        console.warn(proxy_addr + ' TIMEOUT!');
        ga_report_timeout('Proxy Server Timeout', proxy_addr);
        get_mode_name(function(current_mode_name) {
            if (current_mode_name === 'normal') {
                // if (depth < 31) {
                if (depth < 3) {
                    setup_proxy(depth + 1); // simply recursive
                } else {
                    console.warn('have reached the max retrial times of setup_proxy, so abort');

                    // experimental
                    var test_server = 'proxy.mainland.io:8888';
                    console.log('using experimental server: ' + test_server);
                    setup_pac_data(test_server);
                    ga_report_event('Proxy Server Selection', test_server, 0.1);

                    console.groupEnd();
                }
            } else {
                console.warn('not in normal mode anymore, so abort the retrial');
                console.groupEnd();
            }
        });
    }, 3000);  // 3s

    // http://goo.gl/ktYcx
    // but still can't get rid of the annoying message "Failed to load resource"
    xhr.onerror = function(e) {
        console.error('xhr error: ' + e.target.status);
    };

    // xhr.open('GET', 'http://httpbin.org/delay/13');
    // xhr.open('GET', 'http://fakedomainname');
    xhr.open('GET', 'http://' + proxy_addr);
    xhr.timeout = 4000; // 4s
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 400) {
            clearTimeout(xhr_timer);
            console.log('the proxy server seems to be working fine: ' + proxy_addr);
            ga_report_event('Proxy Server Selection', proxy_addr, 0.1);

            console.groupEnd();
        }
    };
    xhr.send();
    */
}

function clear_proxy() {
    var proxy_config = {
        mode: 'system'
    };

    chrome.proxy.settings.set(
        {
            value: proxy_config,
            scope: 'regular'
        },
        function() {
            return;
        }
    );

    console.log('proxy is removed (changed to system setting)');
}
<commit_msg>remove debug msg<commit_after>/*
 * Allow you smoothly surf on many websites blocking non-mainland visitors.
 * Copyright (C) 2012 - 2014  Bo Zhu  http://zhuzhu.org
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/*jshint devel:true, globalstrict: true */
/*global chrome: false, unblock_youku: false, new_sogou_proxy_addr: false, urls2pac: false, get_mode_name: false */
/*global ga_report_timeout: false, ga_report_error: false, ga_report_event: false */
"use strict";

function setup_pac_data(proxy_domain) {
    var pac_data = urls2pac([], unblock_youku.normal_url_list, proxy_domain, 'HTTPS');
    // console.log(pac_data);
    var proxy_config = {
        mode: 'pac_script',
        pacScript: {
            data: pac_data
        }
    };
    chrome.proxy.settings.set(
        {
            value: proxy_config,
            scope: 'regular'
        },
        function() {
            return;
        }
    );
}

function setup_proxy(depth) {  // depth for recursion
    if (typeof depth === 'undefined') {
        depth = 0;  // recursion depth
        console.group('to set up proxy');
    }

    var test_server = 'proxy.mainland.io:993';
    // var test_server = 'proxy.uku.im:8888';
    setup_pac_data(test_server);
    console.log('using experimental server: ' + test_server);
    ga_report_event('Proxy Server Selection', test_server, 0.1);
    console.groupEnd();

    /*
    var proxy_addr = new_sogou_proxy_addr();
    console.log('using proxy: ' + proxy_addr);
    setup_pac_data(proxy_addr);  // should set up PAC already

    console.log('to check if the proxy server is avaiable: ' + proxy_addr);
    console.log((depth + 1) + '-th time to test proxy servers');
    var xhr = new XMLHttpRequest();

    // test timeout
    var xhr_timer = setTimeout(function() {
        xhr.abort();
        console.warn(proxy_addr + ' TIMEOUT!');
        ga_report_timeout('Proxy Server Timeout', proxy_addr);
        get_mode_name(function(current_mode_name) {
            if (current_mode_name === 'normal') {
                // if (depth < 31) {
                if (depth < 3) {
                    setup_proxy(depth + 1); // simply recursive
                } else {
                    console.warn('have reached the max retrial times of setup_proxy, so abort');

                    // experimental
                    var test_server = 'proxy.mainland.io:8888';
                    console.log('using experimental server: ' + test_server);
                    setup_pac_data(test_server);
                    ga_report_event('Proxy Server Selection', test_server, 0.1);

                    console.groupEnd();
                }
            } else {
                console.warn('not in normal mode anymore, so abort the retrial');
                console.groupEnd();
            }
        });
    }, 3000);  // 3s

    // http://goo.gl/ktYcx
    // but still can't get rid of the annoying message "Failed to load resource"
    xhr.onerror = function(e) {
        console.error('xhr error: ' + e.target.status);
    };

    // xhr.open('GET', 'http://httpbin.org/delay/13');
    // xhr.open('GET', 'http://fakedomainname');
    xhr.open('GET', 'http://' + proxy_addr);
    xhr.timeout = 4000; // 4s
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 400) {
            clearTimeout(xhr_timer);
            console.log('the proxy server seems to be working fine: ' + proxy_addr);
            ga_report_event('Proxy Server Selection', proxy_addr, 0.1);

            console.groupEnd();
        }
    };
    xhr.send();
    */
}

function clear_proxy() {
    var proxy_config = {
        mode: 'system'
    };

    chrome.proxy.settings.set(
        {
            value: proxy_config,
            scope: 'regular'
        },
        function() {
            return;
        }
    );

    console.log('proxy is removed (changed to system setting)');
}
<|endoftext|>


<commit_before>/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */
var tiBinding = kroll.binding('Titanium'),
	Titanium = tiBinding.Titanium,
	Proxy = tiBinding.Proxy,
	assets = kroll.binding('assets'),
	Script = kroll.binding('evals').Script,
	bootstrap = require('bootstrap'),
	path = require('path'),
	url = require('url');

// the app entry point
Titanium.sourceUrl = "app://app.js";

// a list of java APIs that need an invocation-specific URL
// passed in as the first argument
Titanium.invocationAPIs = [];

function TiInclude(filename, baseUrl) {
	baseUrl = typeof(baseUrl) === 'undefined' ? "app://app.js" : baseUrl;
	var sourceUrl = url.resolve(baseUrl, filename);
	var source;

	if (!('protocol' in sourceUrl)) {
		source = assets.readResource(filename);

	} else if (sourceUrl.filePath) {
		var filepath = url.toFilePath(sourceUrl);
		source = assets.readFile(filepath);

	} else if (sourceUrl.assetPath) {
		var assetPath = url.toAssetPath(sourceUrl);
		source = assets.readResource(assetPath);
	}

	Titanium.runInContext(source, sourceUrl.href);
}
Titanium.include = TiInclude;

Titanium.runInContext = function(source, url) {
	// Use the prototype inheritance chain
	// to copy and maintain the Titanium dynamic
	// getters/setters
	function SandboxTitanium() {}
	SandboxTitanium.prototype = Titanium;

	var sandboxTi = new SandboxTitanium();
	sandbox = { Ti: sandboxTi, Titanium: sandboxTi };

	sandbox.Ti.sourceUrl = url;
	sandbox.Ti.include = function(filename, baseUrl) {
		baseUrl = typeof(baseUrl) === 'undefined' ? url : baseUrl;
		TiInclude(filename, baseUrl);
	}

	Titanium.bindInvocationAPIs(sandboxTi, url);

	var wrappedSource = "with(sandbox) { " + source + " }";
	return Script.runInThisContext(wrappedSource, url);
}

Titanium.bindInvocationAPIs = function(sandboxTi, url) {
	// This loops through all known APIs that require an
	// Invocation object and wraps them so we can pass a
	// source URL as the first argument
	var len = Titanium.invocationAPIs.length;
	for (var i = 0; i < len; ++i) {
		var invocationAPI = Titanium.invocationAPIs[i];
		var names = invocationAPI.namespace.split(".");
		var apiNamespace = sandboxTi;
		var realAPI = tiBinding.Titanium;

		for (var j = 0, namesLen = names.length; j < namesLen; ++j) {
			var name = names[j];
			function SandboxAPI() {}
			SandboxAPI.prototype = apiNamespace[name];

			var api = new SandboxAPI();
			apiNamespace[name] = api;
			apiNamespace = api;
			realAPI = realAPI[name];
		}

		var delegate = realAPI[invocationAPI.api];

		function invoker() {
			var args = Array.prototype.slice.call(arguments);
			args.splice(0, 0, url);
			return delegate.apply(this, args);
		}

		// These invokers form a call hierarchy so we need to
		// provide a way back to the actual root Titanium / actual impl.
		while ("__parent__" in delegate) {
			delegate = delegate.__parent__;
		}
		invoker.__parent__ = delegate;

		apiNamespace[invocationAPI.api] = invoker;
	}
}

Titanium.Proxy = Proxy;

Object.prototype.extend = function(other) {
	if (!other) return;

	for (var name in other) {
		if (other.hasOwnProperty(name)) {
			this[name] = other[name];
		}
	}
	return this;
}

Proxy.defineProperties = function(proxyPrototype, names) {
	var properties = {};
	var len = names.length;

	for (var i = 0; i < len; ++i) {
		var name = names[i];
		properties[name] = {
			get: function() { return this.getProperty(name); },
			set: function(value) { this.setPropertyAndFire(name, value); },
			enumerable: true
		};
	}

	Object.defineProperties(proxyPrototype, properties);
}

Proxy.prototype.getProperty = function(property) {
	return this._properties[property];
}

Proxy.prototype.setPropertyAndFire = function(property, value) {
	if (!property) return false;

	var oldValue = this._properties[property];
	this._properties[property] = value;

	kroll.log("setting " + property + " to " + value + ", oldValue = " + oldValue);
	if (oldValue != value) {
		kroll.log("calling onPropertyChanged = " + this.onPropertyChanged);
		this.onPropertyChanged(property, oldValue, value);
	}
}

Proxy.prototype.setPropertiesAndFire = function(properties) {
	var ownNames = Object.getOwnPropertyNames(properties);
	var len = ownNames.length;
	var changes = [];

	for (var i = 0; i < len; ++i) {
		var property = ownNames[i];
		var value = properties[property];

		if (!property) continue;

		var oldValue = this._properties[property];
		this._properties[property] = value;

		if (value != oldValue) {
			changes.push([property, oldValue, value]);
		}
	}

	if (changes.length > 0) {
		this.onPropertiesChanged(changes);
	}
}

// Custom native modules
bootstrap.defineLazyBinding(Titanium, "API");

// Custom JS extensions to Java modules
var Window;
bootstrap.defineLazyGetter("UI", "Window", function() {
	if (!Window) {
		Window = require("window").bootstrapWindow(Titanium);
	}
	return Window;
});

bootstrap.defineLazyGetter("UI", "createWindow", function() {
	if (!Window) {
		Window = require("window").bootstrapWindow(Titanium);
	}
	return this.createWindow;
});

// Define lazy initializers for all Titanium APIs
bootstrap.bootstrap(Titanium);
Titanium.bindInvocationAPIs(Titanium, Titanium.sourceUrl);

module.exports = Titanium;
<commit_msg>separate each invoker into it's own private scope to avoid sharing references in a loop<commit_after>/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */
var tiBinding = kroll.binding('Titanium'),
	Titanium = tiBinding.Titanium,
	Proxy = tiBinding.Proxy,
	assets = kroll.binding('assets'),
	Script = kroll.binding('evals').Script,
	bootstrap = require('bootstrap'),
	path = require('path'),
	url = require('url');

// the app entry point
Titanium.sourceUrl = "app://app.js";

// a list of java APIs that need an invocation-specific URL
// passed in as the first argument
Titanium.invocationAPIs = [];

function TiInclude(filename, baseUrl) {
	baseUrl = typeof(baseUrl) === 'undefined' ? "app://app.js" : baseUrl;
	var sourceUrl = url.resolve(baseUrl, filename);
	var source;

	if (!('protocol' in sourceUrl)) {
		source = assets.readResource(filename);

	} else if (sourceUrl.filePath) {
		var filepath = url.toFilePath(sourceUrl);
		source = assets.readFile(filepath);

	} else if (sourceUrl.assetPath) {
		var assetPath = url.toAssetPath(sourceUrl);
		source = assets.readResource(assetPath);
	}

	Titanium.runInContext(source, sourceUrl.href);
}
Titanium.include = TiInclude;

Titanium.runInContext = function(source, url) {
	// Use the prototype inheritance chain
	// to copy and maintain the Titanium dynamic
	// getters/setters
	function SandboxTitanium() {}
	SandboxTitanium.prototype = Titanium;

	var sandboxTi = new SandboxTitanium();
	sandbox = { Ti: sandboxTi, Titanium: sandboxTi };

	sandbox.Ti.sourceUrl = url;
	sandbox.Ti.include = function(filename, baseUrl) {
		baseUrl = typeof(baseUrl) === 'undefined' ? url : baseUrl;
		TiInclude(filename, baseUrl);
	}

	Titanium.bindInvocationAPIs(sandboxTi, url);

	var wrappedSource = "with(sandbox) { " + source + " }";
	return Script.runInThisContext(wrappedSource, url);
}

Titanium.bindInvocationAPIs = function(sandboxTi, url) {
	// This loops through all known APIs that require an
	// Invocation object and wraps them so we can pass a
	// source URL as the first argument

	function genInvoker(invocationAPI) {
		var names = invocationAPI.namespace.split(".");
		var apiNamespace = sandboxTi;
		var realAPI = tiBinding.Titanium;

		for (var j = 0, namesLen = names.length; j < namesLen; ++j) {
			var name = names[j];
			function SandboxAPI() {}
			SandboxAPI.prototype = apiNamespace[name];

			var api = new SandboxAPI();
			apiNamespace[name] = api;
			apiNamespace = api;
			realAPI = realAPI[name];
		}

		var delegate = realAPI[invocationAPI.api];

		function invoker() {
			var args = Array.prototype.slice.call(arguments);
			args.splice(0, 0, url);
			return delegate.apply(this, args);
		}

		// These invokers form a call hierarchy so we need to
		// provide a way back to the actual root Titanium / actual impl.
		while ("__parent__" in delegate) {
			delegate = delegate.__parent__;
		}
		invoker.__parent__ = delegate;

		apiNamespace[invocationAPI.api] = invoker;
	}

	var len = Titanium.invocationAPIs.length;
	for (var i = 0; i < len; ++i) {
		// separate each invoker into it's own private scope
		genInvoker(Titanium.invocationAPIs[i]);
	}
}

Titanium.Proxy = Proxy;

Object.prototype.extend = function(other) {
	if (!other) return;

	for (var name in other) {
		if (other.hasOwnProperty(name)) {
			this[name] = other[name];
		}
	}
	return this;
}

Proxy.defineProperties = function(proxyPrototype, names) {
	var properties = {};
	var len = names.length;

	for (var i = 0; i < len; ++i) {
		var name = names[i];
		properties[name] = {
			get: function() { return this.getProperty(name); },
			set: function(value) { this.setPropertyAndFire(name, value); },
			enumerable: true
		};
	}

	Object.defineProperties(proxyPrototype, properties);
}

Proxy.prototype.getProperty = function(property) {
	return this._properties[property];
}

Proxy.prototype.setPropertyAndFire = function(property, value) {
	if (!property) return false;

	var oldValue = this._properties[property];
	this._properties[property] = value;

	kroll.log("setting " + property + " to " + value + ", oldValue = " + oldValue);
	if (oldValue != value) {
		kroll.log("calling onPropertyChanged = " + this.onPropertyChanged);
		this.onPropertyChanged(property, oldValue, value);
	}
}

Proxy.prototype.setPropertiesAndFire = function(properties) {
	var ownNames = Object.getOwnPropertyNames(properties);
	var len = ownNames.length;
	var changes = [];

	for (var i = 0; i < len; ++i) {
		var property = ownNames[i];
		var value = properties[property];

		if (!property) continue;

		var oldValue = this._properties[property];
		this._properties[property] = value;

		if (value != oldValue) {
			changes.push([property, oldValue, value]);
		}
	}

	if (changes.length > 0) {
		this.onPropertiesChanged(changes);
	}
}

// Custom native modules
bootstrap.defineLazyBinding(Titanium, "API");

// Custom JS extensions to Java modules
var Window;
bootstrap.defineLazyGetter("UI", "Window", function() {
	if (!Window) {
		Window = require("window").bootstrapWindow(Titanium);
	}
	return Window;
});

bootstrap.defineLazyGetter("UI", "createWindow", function() {
	if (!Window) {
		Window = require("window").bootstrapWindow(Titanium);
	}
	return this.createWindow;
});

// Define lazy initializers for all Titanium APIs
bootstrap.bootstrap(Titanium);
Titanium.bindInvocationAPIs(Titanium, Titanium.sourceUrl);

module.exports = Titanium;
<|endoftext|>


<commit_before>function UndefinedValue() {}

exports.UndefinedValue = UndefinedValue;

UndefinedValue.prototype.is = function (Class) {
  return this instanceof Class;
};

UndefinedValue.prototype.context = Context.EMPTY;

UndefinedValue.prototype.toString = function () {
  return 'undefined';
};

UndefinedValue.prototype.clone = function (context) {
  var value = new UndefinedValue();
  value.context = context;
  return value;
};

UndefinedValue.DEFAULT = new UndefinedValue();

UndefinedValue.fromContext = function (context) {
  return UndefinedValue.DEFAULT.clone(context);
};

function ComplexValue(real, imaginary) {
  real = +real;
  imaginary = +imaginary;
  UndefinedValue.call(this);
  this.real = real;
  this.imaginary = imaginary;
}

exports.ComplexValue = ComplexValue;
extend(UndefinedValue, ComplexValue);

ComplexValue.prototype.toString = function () {
  if (this.imaginary < 0) {
    return this.real + '' + this.imaginary + 'i';
  } else {
    return this.real + '+' + this.imaginary + 'i';
  }
};

ComplexValue.prototype.clone = function (context) {
  var value = new ComplexValue(this.real, this.imaginary);
  value.context = context;
  return value;
};

function RealValue(value) {
  value = +value;
  ComplexValue.call(this, value, 0);
  this.value = value;
}

exports.RealValue = RealValue;
extend(ComplexValue, RealValue);

RealValue.prototype.toString = function () {
  return '' + this.value;
};

RealValue.prototype.clone = function (context) {
  var value = new RealValue(this.value);
  value.context = context;
  return value;
};

function IntegerValue(value) {
  RealValue.call(this, ~~value);
}

exports.IntegerValue = IntegerValue;
extend(RealValue, IntegerValue);

IntegerValue.prototype.toString = function () {
  return '' + this.value;
};

IntegerValue.prototype.clone = function (context) {
  var value = new IntegerValue(this.value);
  value.context = context;
  return value;
};

function NaturalValue(value) {
  value = ~~value;
  if (value < 0) {
    throw new LambdaInternalError();
  }
  IntegerValue.call(this, value);
}

exports.NaturalValue = NaturalValue;
extend(IntegerValue, NaturalValue);

NaturalValue.prototype.toString = function () {
  return '' + this.value;
};

NaturalValue.prototype.clone = function (context) {
  var value = new NaturalValue(this.value);
  value.context = context;
  return value;
};

function BooleanValue(value) {
  value = !!value;
  UndefinedValue.call(this);
  this.value = value;
}

exports.BooleanValue = BooleanValue;
extend(UndefinedValue, BooleanValue);

BooleanValue.prototype.toString = function () {
  if (this.value) {
    return 'true';
  } else {
    return 'false';
  }
};

BooleanValue.prototype.clone = function (context) {
  var value = new BooleanValue(this.value);
  value.context = context;
  return value;
};

BooleanValue.TRUE = new BooleanValue(true);
BooleanValue.FALSE = new BooleanValue(false);

function IndexedValue() {
  UndefinedValue.call(this);
}

exports.IndexedValue = IndexedValue;
extend(UndefinedValue, IndexedValue);

function StringValue(value) {
  value = '' + value;
  IndexedValue.call(this);
  this.value = value;
}

exports.StringValue = StringValue;
extend(IndexedValue, StringValue);

StringValue.prototype.toString = function () {
  return this.value;
};

StringValue.prototype.clone = function (context) {
  var value = new StringValue(this.value);
  value.context = context;
  return value;
};

StringValue.prototype.lookup = function (index) {
  if (index < 0 || index >= this.value.length) {
    throw new LambdaRuntimeError();
  }
  return new StringValue(this.value[index]);
};

function ListValue(values) {
  IndexedValue.call(this);
  this.values = values;
}

exports.ListValue = ListValue;
extend(IndexedValue, ListValue);

ListValue.prototype.toString = function () {
  return '{ ' + this.values.map(function (value) {
    return value.toString();
  }).join(', ') + ' }';
};

ListValue.prototype.clone = function (context) {
  var value = new ListValue(this.values);
  value.context = context;
  return value;
};

ListValue.prototype.lookup = function (index) {
  if (index < 0 || index >= this.values.length) {
    throw new LambdaRuntimeError();
  }
  return this.values[index];
};

function Closure(lambda, capture) {
  UndefinedValue.call(this);
  this.lambda = lambda;
  this.capture = capture;
}

exports.Closure = Closure;
extend(UndefinedValue, Closure);

Closure.prototype.toString = function () {
  return 'closure';
};

Closure.prototype.clone = function (context) {
  var value = new Closure(this.lambda, this.capture);
  value.context = context;
  return value;
};
<commit_msg>AbstractValue<commit_after>function AbstractValue() {}

exports.AbstractValue = AbstractValue;

AbstractValue.prototype.is = function (Class) {
  return this instanceof Class;
};

function UndefinedValue() {
  AbstractValue.call(this);
}

exports.UndefinedValue = UndefinedValue;
extend(AbstractValue, UndefinedValue);

UndefinedValue.prototype.context = Context.EMPTY;

UndefinedValue.prototype.toString = function () {
  return 'undefined';
};

UndefinedValue.prototype._clone = function () {
  return new UndefinedValue();
};

UndefinedValue.prototype.clone = function (context) {
  var value = this._clone();
  value.context = context;
  return value;
};

UndefinedValue.DEFAULT = new UndefinedValue();

UndefinedValue.fromContext = function (context) {
  return UndefinedValue.DEFAULT.clone(context);
};

function ComplexValue(real, imaginary) {
  real = +real;
  imaginary = +imaginary;
  UndefinedValue.call(this);
  this.real = real;
  this.imaginary = imaginary;
}

exports.ComplexValue = ComplexValue;
extend(UndefinedValue, ComplexValue);

ComplexValue.prototype.toString = function () {
  if (this.imaginary < 0) {
    return this.real + '' + this.imaginary + 'i';
  } else {
    return this.real + '+' + this.imaginary + 'i';
  }
};

ComplexValue.prototype._clone = function () {
  return new ComplexValue(this.real, this.imaginary);
};

function RealValue(value) {
  value = +value;
  ComplexValue.call(this, value, 0);
  this.value = value;
}

exports.RealValue = RealValue;
extend(ComplexValue, RealValue);

RealValue.prototype.toString = function () {
  return '' + this.value;
};

RealValue.prototype._clone = function () {
  return new RealValue(this.value);
};

function IntegerValue(value) {
  RealValue.call(this, ~~value);
}

exports.IntegerValue = IntegerValue;
extend(RealValue, IntegerValue);

IntegerValue.prototype.toString = function () {
  return '' + this.value;
};

IntegerValue.prototype._clone = function () {
  return new IntegerValue(this.value);
};

function NaturalValue(value) {
  value = ~~value;
  if (value < 0) {
    throw new LambdaInternalError();
  }
  IntegerValue.call(this, value);
}

exports.NaturalValue = NaturalValue;
extend(IntegerValue, NaturalValue);

NaturalValue.prototype.toString = function () {
  return '' + this.value;
};

NaturalValue.prototype._clone = function () {
  return new NaturalValue(this.value);
};

function BooleanValue(value) {
  value = !!value;
  UndefinedValue.call(this);
  this.value = value;
}

exports.BooleanValue = BooleanValue;
extend(UndefinedValue, BooleanValue);

BooleanValue.prototype.toString = function () {
  if (this.value) {
    return 'true';
  } else {
    return 'false';
  }
};

BooleanValue.prototype._clone = function () {
  return new BooleanValue(this.value);
};

BooleanValue.TRUE = new BooleanValue(true);
BooleanValue.FALSE = new BooleanValue(false);

function IndexedValue() {
  UndefinedValue.call(this);
}

exports.IndexedValue = IndexedValue;
extend(UndefinedValue, IndexedValue);

function StringValue(value) {
  value = '' + value;
  IndexedValue.call(this);
  this.value = value;
}

exports.StringValue = StringValue;
extend(IndexedValue, StringValue);

StringValue.prototype.toString = function () {
  return this.value;
};

StringValue.prototype._clone = function () {
  return new StringValue(this.value);
};

StringValue.prototype.lookup = function (index) {
  if (index < 0 || index >= this.value.length) {
    throw new LambdaRuntimeError();
  }
  return new StringValue(this.value[index]);
};

function ListValue(values) {
  IndexedValue.call(this);
  this.values = values;
}

exports.ListValue = ListValue;
extend(IndexedValue, ListValue);

ListValue.prototype.toString = function () {
  return '{ ' + this.values.map(function (value) {
    return value.toString();
  }).join(', ') + ' }';
};

ListValue.prototype._clone = function () {
  return new ListValue(this.values);
};

ListValue.prototype.lookup = function (index) {
  if (index < 0 || index >= this.values.length) {
    throw new LambdaRuntimeError();
  }
  return this.values[index];
};

function Closure(lambda, capture) {
  UndefinedValue.call(this);
  this.lambda = lambda;
  this.capture = capture;
}

exports.Closure = Closure;
extend(UndefinedValue, Closure);

Closure.prototype.toString = function () {
  return 'closure';
};

Closure.prototype._clone = function () {
  return new Closure(this.lambda, this.capture);
};
<|endoftext|>


<commit_before>this.Wire = (function(getUndefined, hasOwnProperty, Queue, Error, EventEmitter, extendClass){
  var WireConnectionIterator = (function(){
    var refresh = function(){

      this._connections = this._wire._bindings;
    };
    function WireConnectionIterator(wire){

      this._wire = wire;
      this._index = 0;
      refresh.call(this);
    }
    WireConnectionIterator.prototype = {};
    var P = WireConnectionIterator.prototype;
    P.reset = function(){

      // Reset iterator index
      this._index = 0;
    };
    P.next = function(){

      // Check if we are at the last connection
      if (this._index < this._connections.length){

        // Get current connection
        var connection = this._connections[this._index];

        // Increment index and return connection
        this._index = this._index + 1;
        return {
          done: false,
          value: {block: connection.block, pin: connection.pin}
        };
      }
      else
        return {done: true};
    };
    P.peek = function(){

      // Check if we are at the last connection
      if (this._index < this._connections.length){

        // Get current connection
        var connection = this._connections[this._index];

        // Return connection
        return {
          done: false,
          value: {block: connection.block, pin: connection.pin}
        };
      }
      else
        return {done: true};
    };
    P.has = function(connection){

      // Run through iterator and check for equivalent connection
      for (var i = 0; i < this._connections.length; i++){

        var con = this._connections[i];
        if (con.block === connection.block && con.pin === connection.pin)
          return true;
      }

      // Match not found
      return false;
    };
    return WireConnectionIterator;
  }());
  function Wire(hash){

    EventEmitter.call(this);

    this._bindings = [];
    this._updating = false;

    // Process argument
    if (typeof hash !== "undefined"){

      // Add equalTo function if supplied
      if (hasOwnProperty(hash, "equalTo"))
        this.equalTo = hash.equalTo;

      // Add queue if supplied
      if (hasOwnProperty(hash, "queue"))
        this._valueQueue = hash.queue;
    }

    // Set defaults
    if (!hasOwnProperty(this, "_valueQueue"))
      this._valueQueue = new Queue();
  }
  var maxIterations = 1000;
  Wire.setMaxIterations = function(iterations){

    maxIterations = iterations;
  };
  extendClass(EventEmitter, Wire);
  var P = Wire.prototype;
  P.duplicate = function(){

    var hash = {
      queue: this._valueQueue.duplicate()
    };

    if (hasOwnProperty(this, "equalTo"))
      hash.equalTo = this.equalTo;

    return new Wire(hash);
  };
  P.equalTo = function(value){

    // Compare with ===, but let NaN === NaN be true
    return value !== value ? this._value !== this._value : value === this._value;
  };
  P.bind = function(block, pin){

    // Get bindings list
    var bindings = this._bindings;

    // Iterate over bindings and copy to new bindings
    var newBindings = [], bindingExists;
    for (var i = 0; i < bindings.length; i++){
      newBindings.push(bindings[i]);
      if (bindings[i].block === block && bindings[i].pin === pin)
        bindingExists = true;
    }

    // Add new binding if not exists
    if (!bindingExists) {

      // Add binding
      newBindings.push({block: block, pin: pin});

      // Fire event
      this.fire("connect", {block: block, pin: pin});
    }

    // Replace existing bindings
    this._bindings = newBindings;
  };
  P.unbind = function(block, pin){

    // Get bindings list
    var bindings = this._bindings;

    // Iterate over bindings and copy to new bindings
    var newBindings = [];
    for (var i = 0; i < bindings.length; i++){
      if (bindings[i].block !== block || bindings[i].pin !== pin)
        newBindings.push(bindings[i]);
      else
        this.fire("disconnect", {block: bindings[i].block, pin: bindings[i].pin}); // Fire event
    }

    // Replace existing bindings
    this._bindings = newBindings;
  };
  P.notify = function(){

    // Get bindings list
    var bindings = this._bindings;

    // Update each bound block
    for (var i = 0; i < bindings.length; i++)
      bindings[i].block.update(bindings[i].pin);
  };
  P.value = function(newValue){

    if (!arguments.length)
      return this._value; // We are getting the value
    else {

      // We are setting a new value

      // Check updating flag
      if (this._updating){

        // Add new value to queue and return
        this._valueQueue.push(newValue);
        return;
      }
      else
        this._updating = true; // Set updating flag

      // Main loop
      var iterations = 1;
      while (true){

        // Check iteration count
        if (iterations++ > maxIterations){

          this._updating = false;
          throw new Error("Infinite loop detected: reached " + maxIterations + " iterations");
        }

        // Compare new value to current value
        if (!this.equalTo(newValue)){

          // Set new value
          this._value = newValue;

          // Fire event
          this.fire("value", newValue);

          // Notify bound blocks
          this.notify();
        }

        // Process value queue
        if (this._valueQueue.isEmpty()){

          // Unset updating flag and return
          this._updating = false;
          return;
        }
        else
          newValue = this._valueQueue.next(); // Get next value from queue

        // Restart loop
      }
    }
  };
  P.connections = function(){

    return new WireConnectionIterator(this);
  };
  return Wire;
}(this.getUndefined, this.hasOwnProperty, this.Queue, host.Error, this.EventEmitter, this.extendClass));

<commit_msg>Fix Wire class queue logic<commit_after>this.Wire = (function(getUndefined, hasOwnProperty, Queue, Error, EventEmitter, extendClass){
  var WireConnectionIterator = (function(){
    var refresh = function(){

      this._connections = this._wire._bindings;
    };
    function WireConnectionIterator(wire){

      this._wire = wire;
      this._index = 0;
      refresh.call(this);
    }
    WireConnectionIterator.prototype = {};
    var P = WireConnectionIterator.prototype;
    P.reset = function(){

      // Reset iterator index
      this._index = 0;
    };
    P.next = function(){

      // Check if we are at the last connection
      if (this._index < this._connections.length){

        // Get current connection
        var connection = this._connections[this._index];

        // Increment index and return connection
        this._index = this._index + 1;
        return {
          done: false,
          value: {block: connection.block, pin: connection.pin}
        };
      }
      else
        return {done: true};
    };
    P.peek = function(){

      // Check if we are at the last connection
      if (this._index < this._connections.length){

        // Get current connection
        var connection = this._connections[this._index];

        // Return connection
        return {
          done: false,
          value: {block: connection.block, pin: connection.pin}
        };
      }
      else
        return {done: true};
    };
    P.has = function(connection){

      // Run through iterator and check for equivalent connection
      for (var i = 0; i < this._connections.length; i++){

        var con = this._connections[i];
        if (con.block === connection.block && con.pin === connection.pin)
          return true;
      }

      // Match not found
      return false;
    };
    return WireConnectionIterator;
  }());
  function Wire(hash){

    EventEmitter.call(this);

    this._bindings = [];
    this._updating = false;

    // Process argument
    if (typeof hash !== "undefined"){

      // Add equalTo function if supplied
      if (hasOwnProperty(hash, "equalTo"))
        this.equalTo = hash.equalTo;

      // Add queue if supplied
      if (hasOwnProperty(hash, "queue"))
        this._valueQueue = hash.queue;
    }

    // Set defaults
    if (!hasOwnProperty(this, "_valueQueue"))
      this._valueQueue = new Queue();
  }
  var maxIterations = 1000;
  Wire.setMaxIterations = function(iterations){

    maxIterations = iterations;
  };
  extendClass(EventEmitter, Wire);
  var P = Wire.prototype;
  P.duplicate = function(){

    var hash = {
      queue: this._valueQueue.duplicate()
    };

    if (hasOwnProperty(this, "equalTo"))
      hash.equalTo = this.equalTo;

    return new Wire(hash);
  };
  P.equalTo = function(value){

    // Compare with ===, but let NaN === NaN be true
    return value !== value ? this._value !== this._value : value === this._value;
  };
  P.bind = function(block, pin){

    // Get bindings list
    var bindings = this._bindings;

    // Iterate over bindings and copy to new bindings
    var newBindings = [], bindingExists;
    for (var i = 0; i < bindings.length; i++){
      newBindings.push(bindings[i]);
      if (bindings[i].block === block && bindings[i].pin === pin)
        bindingExists = true;
    }

    // Add new binding if not exists
    if (!bindingExists) {

      // Add binding
      newBindings.push({block: block, pin: pin});

      // Fire event
      this.fire("connect", {block: block, pin: pin});
    }

    // Replace existing bindings
    this._bindings = newBindings;
  };
  P.unbind = function(block, pin){

    // Get bindings list
    var bindings = this._bindings;

    // Iterate over bindings and copy to new bindings
    var newBindings = [];
    for (var i = 0; i < bindings.length; i++){
      if (bindings[i].block !== block || bindings[i].pin !== pin)
        newBindings.push(bindings[i]);
      else
        this.fire("disconnect", {block: bindings[i].block, pin: bindings[i].pin}); // Fire event
    }

    // Replace existing bindings
    this._bindings = newBindings;
  };
  P.notify = function(){

    // Get bindings list
    var bindings = this._bindings;

    // Update each bound block
    for (var i = 0; i < bindings.length; i++)
      bindings[i].block.update(bindings[i].pin);
  };
  P.value = function(newValue){

    if (!arguments.length)
      return this._value; // We are getting the value
    else {

      // We are setting a new value

      // Check updating flag
      if (this._updating){

        // Add new value to queue and return

        // Don't add the same value to the queue
        if (!this.equalTo(newValue))
          this._valueQueue.push(newValue);

        // Return
        return;
      }
      else
        this._updating = true; // Set updating flag

      // Main loop
      var iterations = 1;
      while (true){

        // Check iteration count
        if (iterations++ > maxIterations){

          this._updating = false;
          throw new Error("Infinite loop detected: reached " + maxIterations + " iterations");
        }

        // Compare new value to current value
        if (!this.equalTo(newValue)){

          // Set new value
          this._value = newValue;

          // Fire event
          this.fire("value", newValue);

          // Notify bound blocks
          this.notify();
        }

        // Process value queue
        if (this._valueQueue.isEmpty()){

          // Unset updating flag and return
          this._updating = false;
          return;
        }
        else
          newValue = this._valueQueue.next(); // Get next value from queue

        // Restart loop
      }
    }
  };
  P.connections = function(){

    return new WireConnectionIterator(this);
  };
  return Wire;
}(this.getUndefined, this.hasOwnProperty, this.Queue, host.Error, this.EventEmitter, this.extendClass));

<|endoftext|>


<commit_before>// TODO : user validation.

module.exports = {
  /**
   * list() - list all docs
   */
  index: function(req, res) {

    var page=req.param('page',1);
    var limit=req.param('limit',null);

    // Use a promise to get both queries in parallel.
    Promise.all([
      Document.find().paginate({
        page: page,
        limit: limit
      }),
      Document.count()
    ]).spread(function(documents, count) {
      // Get all of our results.
      return res.json({
        error: false,
        page: page,
        limit: limit,
        count: count,
        documents: documents
      });
    }).catch(function(error) {
      // Handle any errors - this occurs on
      // the *first* error.
      return res.badRequest(error);
    });

  },
  find: function(req, res) {
    Document.findOne({slug: req.param('slug')}).exec(function(error, document) {
      return res.json({
        error: false,
        document: document
      });
    });
  },
  create: function(req, res) {
    var doc = req.param('document');
    if(!doc)
    {
      doc = {
        'title': 'Untitled Document'
      };
    }
    // We need a slug.
    if(!doc.slug){
        doc.slug = Uuid.v4();
    }

    Document.create(doc, function(error, document) {
      // Create the etherpad for this document.
      EtherpadService.createPad({padID: document.slug});

      return res.json({
        error: error,
        document: document
      });
    });
  },
  update: function(req, res) {
    Document.findOne({slug: req.param('slug')}).exec(function(error, document) {
      if(document){
        // Todo: error checking.
        var newDoc = req.param('document');
        for(param in newDoc) {
          document[param] = newDoc[param];
        }
        document.save();
      }
      else {
        return res.json({
          error: error,
          document: document
        });
      }
    });
  },
  destroy: function(req, res) {
    // Todo: error checking.
    Document.destroy({slug: req.param('slug')}).exec(function(error) {
        // Delete the etherpad for this document.
        EtherpadService.deletePad({padID: req.param('slug')});

        return res.json({
          error: error
        });
    });
  }

};
<commit_msg>Don't return an error if we don't need one.<commit_after>// TODO : user validation.

module.exports = {
  /**
   * list() - list all docs
   */
  index: function(req, res) {

    var page=req.param('page',1);
    var limit=req.param('limit',null);

    // Use a promise to get both queries in parallel.
    Promise.all([
      Document.find().paginate({
        page: page,
        limit: limit
      }),
      Document.count()
    ]).spread(function(documents, count) {
      // Get all of our results.
      return res.json({
        page: page,
        limit: limit,
        count: count,
        documents: documents
      });
    }).catch(function(error) {
      // Handle any errors - this occurs on
      // the *first* error.
      return res.badRequest(error);
    });

  },
  find: function(req, res) {
    Document.findOne({slug: req.param('slug')}).exec(function(error, document) {
      return res.json({
        error: false,
        document: document
      });
    });
  },
  create: function(req, res) {
    var doc = req.param('document');
    if(!doc)
    {
      doc = {
        'title': 'Untitled Document'
      };
    }
    // We need a slug.
    if(!doc.slug){
        doc.slug = Uuid.v4();
    }

    Document.create(doc, function(error, document) {
      // Create the etherpad for this document.
      EtherpadService.createPad({padID: document.slug});

      return res.json({
        error: error,
        document: document
      });
    });
  },
  update: function(req, res) {
    Document.findOne({slug: req.param('slug')}).exec(function(error, document) {
      if(document){
        // Todo: error checking.
        var newDoc = req.param('document');
        for(param in newDoc) {
          document[param] = newDoc[param];
        }
        document.save();
      }
      else {
        return res.json({
          error: error,
          document: document
        });
      }
    });
  },
  destroy: function(req, res) {
    // Todo: error checking.
    Document.destroy({slug: req.param('slug')}).exec(function(error) {
        // Delete the etherpad for this document.
        EtherpadService.deletePad({padID: req.param('slug')});

        return res.json({
          error: error
        });
    });
  }

};
<|endoftext|>


<commit_before>/**
 * NNewsController
 *
 * @description :: Server-side logic for managing nnews
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

var request = require('request');
var slack_config = sails.config.slack;
var counter = 0;

var slack_config = sails.config.slack;

module.exports = {

	newsRequest: function(req, res) {

		if (slack_config.slack_verification_token === req.body.token) {

			if (counter > 0) {
				counter = 0
			};

			var articleSource = req.body.text;

			articleSource = articleSource.toLowerCase()

			//handle empty request string coming from slack
			if (!articleSource) {
				articleSource = 'help'
			}

			// find whitespaces and delete them
			if (/\s/g.test(articleSource)) {
				articleSource = articleSource.trim();
			}

			sails.log(articleSource)

			if (articleSource === 'help') {
				var sendHelpMessage = HelpService.answerToUser({
					helpMessageFromUser: articleSource
				});
				return res.ok(sendHelpMessage);
			} else {

				DownloadArticleService.download({
					articleSource: articleSource

				}, function(articles, error) {

					if (articles === 'error') {
						var errorMessage = ErrorService.errorMessageToUser({
							falseStringFromUser: articleSource
						}, function(errorMessage, error) {
							return res.ok(errorMessage)
						});

						return;
					}

					var responseArticle = articles[0]
					var responseSource = articles[1]

					if (responseArticle && responseSource) {
						var articleQuery = ArticleService.articleQuery({
							articles: responseArticle,
							sources: responseSource,
							sourceName: articleSource,
							counter: counter
						})
					} else {
						var errorMessage = ErrorService.errorMessageToUser();
						return res.ok(errorMessage)
					}

					if (articleQuery && responseSource) {
						var article = ArticleService.buildArticleMessageForSlack({
							articleSource: articleSource,
							articleQuery: articleQuery,
							responseSource: responseSource
						})
					}
					return res.ok(article)
				})
			}
		} else {

			return res.badRequest({
				text: '`No valid token detected!`'
			})
		}
	},

	buttonAction: function(req, res) {

		counter++;

		var SlackclientId = slack_config.clientId;
		var button_payload = req.body.payload
		button_payload = JSON.parse(button_payload)

		var ask_for_permission = {
			text: 'Please give us your ' + '<https://slack.com/oauth/authorize?&client_id=' + SlackclientId + '&redirect_uri='+ process.env.REDIRECT_URI +
				'&team=' + button_payload.team.id + '&scope=chat:write:user| PERMISSION>' + ' to post as you into Slack'
		}

		// post as user into current channel
		if (button_payload.actions[0].name === 'post_article') {

			Newspipe.checkUser({
				user_id: button_payload.user.id,
				team_id: button_payload.team.id
			}, function(err, user) {
				if (err) return sails.log.error(err);
				if (!user || !user.length) {
					return res.ok(ask_for_permission)
				} else {
					for (var i = 0; i < user.length; i++) {
						var user_token = user[i].oauth_token
					}
					var post_article = button_payload.actions.shift().value

					post_article = JSON.parse(post_article)

					var article_to_post = ArticleService.postMessageInChannel({
						post_article: post_article
					})

					request({
						method: 'POST',
						json: true,
						url: 'https://slack.com/api/chat.postMessage',
						qs: {
							token: user_token,
							channel: button_payload.channel.id,
							as_user: true,
							text: 'Found at: :point_right: ' + post_article.id.toUpperCase() + ' :point_left:',
							attachments: article_to_post
						}

					}, function(err, responds, body) {

						if (!err && responds.statusCode === 200) {
							return res.ok();
						}
					});
				}
			})

		} else {

			var next_article = button_payload.actions.shift().value

			DownloadArticleService.download({
				articleSource: next_article
			}, function(articles, error) {

				if (articles === 'error') {
					var errorMessage = ErrorService.errorMessageToUser();
					return res.serverError(errorMessage)
					sails.log.info(error)
				}

				var responseArticle = articles[0]
				var responseSource = articles[1]
				var articleLength = responseArticle.length

				if (counter === articleLength) {
					counter = 0
				}

				if (responseArticle && responseSource) {
					var articleQuery = ArticleService.articleQuery({
						articles: responseArticle,
						sources: responseSource,
						sourceName: next_article,
						counter: counter
					})

				} else {
					var errorMessage = ErrorService.errorMessageToUser();
					return res.serverError(errorMessage)
				}

				if (articleQuery) {
					var article = ArticleService.buildArticleMessageForSlack({
						articleSource: next_article,
						articleQuery: articleQuery,
						responseSource: responseSource
					})
				}
				return res.ok(article)
			})
		}

	}
};
<commit_msg>Update NewspipeController.js<commit_after>/**
 * NNewsController
 *
 * @description :: Server-side logic for managing nnews
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

var request = require('request');
var slack_config = sails.config.slack;
var counter = 0;

var slack_config = sails.config.slack;

module.exports = {

	newsRequest: function(req, res) {

		if (slack_config.slack_verification_token === req.body.token) {

			if (counter > 0) {
				counter = 0
			};

			var articleSource = req.body.text;

			articleSource = articleSource.toLowerCase()

			//handle empty request string coming from slack
			if (!articleSource) {
				articleSource = 'help'
			}

			// find whitespaces and delete them
			if (/\s/g.test(articleSource)) {
				articleSource = articleSource.trim();
			}

			sails.log(articleSource)

			if (articleSource === 'help') {
				var sendHelpMessage = HelpService.answerToUser({
					helpMessageFromUser: articleSource
				});
				return res.ok(sendHelpMessage);
			} else {

				DownloadArticleService.download({
					articleSource: articleSource

				}, function(articles, error) {

					if (articles === 'error') {
						var errorMessage = ErrorService.errorMessageToUser({
							falseStringFromUser: articleSource
						}, function(errorMessage, error) {
							return res.ok(errorMessage)
						});

						return;
					}

					var responseArticle = articles[0]
					var responseSource = articles[1]

					if (responseArticle && responseSource) {
						var articleQuery = ArticleService.articleQuery({
							articles: responseArticle,
							sources: responseSource,
							sourceName: articleSource,
							counter: counter
						})
					} else {
						var errorMessage = ErrorService.errorMessageToUser();
						return res.ok(errorMessage)
					}

					if (articleQuery && responseSource) {
						var article = ArticleService.buildArticleMessageForSlack({
							articleSource: articleSource,
							articleQuery: articleQuery,
							responseSource: responseSource
						})
					}
					return res.ok(article)
				})
			}
		} else {

			return res.badRequest({
				text: '`No valid token detected!`'
			})
		}
	},

	buttonAction: function(req, res) {

		counter++;

		var SlackclientId = slack_config.clientId;
		var button_payload = req.body.payload
		button_payload = JSON.parse(button_payload)

		var ask_for_permission = {
			text: 'Please give us your ' + '<https://slack.com/oauth/authorize?&client_id=' + SlackclientId + '&redirect_uri='+ process.env.REDIRECT_URI +
				'&team=' + button_payload.team.id + '&scope=chat:write:user| PERMISSION>' + ' to post as you into Slack'
		}

		// post as user into current channel
		if (button_payload.actions[0].name === 'post_article') {

			Newspipe.checkUser({
				user_id: button_payload.user.id,
				team_id: button_payload.team.id
			}, function(err, user) {
				if (err) return sails.log.error(err);
				if (!user || !user.length) {
					return res.ok(ask_for_permission)
				} else {
					for (var i = 0; i < user.length; i++) {
						var user_token = user[i].oauth_token
					}
					var post_article = button_payload.actions.shift().value

					post_article = JSON.parse(post_article)

					var article_to_post = ArticleService.postMessageInChannel({
						post_article: post_article
					})

					request({
						method: 'POST',
						json: true,
						url: 'https://slack.com/api/chat.postMessage',
						qs: {
							token: user_token,
							channel: button_payload.channel.id,
							as_user: true,
							text: 'Found at: :point_right: ' + post_article.id.toUpperCase() + ' :point_left:',
							attachments: article_to_post
						}

					}, function(err, responds, body) {

						if (!err && responds.statusCode === 200) {
							return res.ok();
						}
					});
				}
			})

		} else { // if the button payload not 'post_article'

			var next_article = button_payload.actions.shift().value

			DownloadArticleService.download({
				articleSource: next_article
			}, function(articles, error) {

				if (articles === 'error') {
					var errorMessage = ErrorService.errorMessageToUser();
					return res.serverError(errorMessage)
					sails.log.info(error)
				}

				var responseArticle = articles[0]
				var responseSource = articles[1]
				var articleLength = responseArticle.length

				if (counter === articleLength) {
					counter = 0
				}

				if (responseArticle && responseSource) {
					var articleQuery = ArticleService.articleQuery({
						articles: responseArticle,
						sources: responseSource,
						sourceName: next_article,
						counter: counter
					})

				} else {
					var errorMessage = ErrorService.errorMessageToUser();
					return res.serverError(errorMessage)
				}

				if (articleQuery) {
					var article = ArticleService.buildArticleMessageForSlack({
						articleSource: next_article,
						articleQuery: articleQuery,
						responseSource: responseSource
					})
				}
				return res.ok(article)
			})
		}
	}
};
<|endoftext|>


<commit_before>
"use strict";

export default $http => {
    delete $http.defaults.headers.common['X-Requested-With'];
    $http.defaults.withCredentials = true;
    $http.defaults.headers.post["Content-Type"] = 'application/x-www-form-urlencoded;charset=utf-8';

    // http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
    // Note that the original function as referenced above silently drops empty
    // values (null or undefined). We actually want those to be posted, but as
    // an empty value, so lines 35 to 37 handle that.
    function param(obj) {
        var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
        for (name in obj) {
            value = obj[name];
            if (value instanceof Array) {
                for (i = 0; i < value.length; ++i) {
                    subValue = value[i];
                    fullSubName = name + '[' + i + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            } else if (value instanceof Date) {
                query += encodeURIComponent(name) + '=' + encodeURIComponent(value.toString()) + '&';
            } else if (value instanceof Object) {
                for (subName in value) {
                    subValue = value[subName];
                    fullSubName = name + '[' + subName + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            } else if (value !== undefined && value !== null) {
                query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
            } else {
                query += encodeURIComponent(name) + '=&';
            }
        }
        return query.length ? query.substr(0, query.length - 1) : query;
    };
    // Override $http service's default transformRequest
    $http.defaults.transformRequest = [function(data) {
        return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
    }];
};

<commit_msg>cleanup slightly<commit_after>
"use strict";

export default $http => {
    delete $http.defaults.headers.common['X-Requested-With'];
    $http.defaults.withCredentials = true;
    $http.defaults.headers.post["Content-Type"] = 'application/x-www-form-urlencoded;charset=utf-8';

    // http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
    // Note that the original function as referenced above silently drops empty
    // values (null or undefined). We actually want those to be posted, but as
    // an empty value, so lines 35 to 37 handle that.
    function param(obj) {
        let query = '', name, value, fullSubName, subValue, innerObj;
        for (name in obj) {
            value = obj[name];
            if (value instanceof Array) {
                for (let i = 0; i < value.length; ++i) {
                    subValue = value[i];
                    fullSubName = name + '[' + i + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            } else if (value instanceof Date) {
                query += encodeURIComponent(name) + '=' + encodeURIComponent(value.toString()) + '&';
            } else if (value instanceof Object) {
                for (let subName in value) {
                    subValue = value[subName];
                    fullSubName = name + '[' + subName + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            } else if (value !== undefined && value !== null) {
                query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
            } else {
                query += encodeURIComponent(name) + '=&';
            }
        }
        return query.length ? query.substr(0, query.length - 1) : query;
    };
    // Override $http service's default transformRequest
    $http.defaults.transformRequest = [function(data) {
        return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
    }];
};

<|endoftext|>


<commit_before>import { pick } from 'lodash'
import { map, uniq } from 'lodash/fp'
import { isFollowing } from '../group/queryUtils'

export function findThread (userIds) {
  const subquery = Group.havingExactMembers(userIds, Post)
  .query(isFollowing)
  .query().select('group_data_id')

  return Post.where({id: subquery, type: Post.Type.THREAD}).fetch()
}

export default function findOrCreateThread (userId, participantIds) {
  return findThread(uniq([userId].concat(participantIds)))
  .then(post => post || createThread(userId, uniq(participantIds)))
}

export async function createThread (userId, participantIds) {
  const attrs = await setupNewThreadAttrs(userId)
  let thread
  await bookshelf.transaction(async trx => {
    thread = await Post.create(attrs, {transacting: trx})
    await afterSavingThread(thread, {participantIds, transacting: trx})
  })
  return thread
}

export function validateThreadData (userId, data) {
  const { participantIds } = data
  if (!(participantIds && participantIds.length)) {
    throw new Error("participantIds can't be empty")
  }
  const checkForSharedCommunity = id =>
    Group.inSameGroup([userId, id], Community)
    .then(doesShare => {
      if (!doesShare) throw new Error(`no shared communities with user ${id}`)
    })
  return Promise.all(map(checkForSharedCommunity, participantIds))
}

function setupNewThreadAttrs (userId) {
  return Promise.resolve({
    type: Post.Type.THREAD,
    visibility: Post.Visibility.DEFAULT,
    user_id: userId,
    link_preview_id: null
  })
}

async function afterSavingThread (thread, opts) {
  const userId = thread.get('user_id')
  const participantIds = uniq([userId].concat(opts.participantIds))
  const trxOpts = pick(opts, 'transacting')

  const followers = await thread.addFollowers(participantIds, {}, trxOpts)
  return followers
}
<commit_msg>fixes issue with findOrCreate thread (#405)<commit_after>import { pick } from 'lodash'
import { map, uniq } from 'lodash/fp'
import { isFollowing } from '../group/queryUtils'

export function findThread (userIds) {
  const subquery = Group.havingExactMembers(userIds, Post)
  .query(isFollowing)
  .query().select('group_data_id')

  return Post.query(q => q.whereIn('id', subquery).where({type: Post.Type.THREAD})).fetch()
}

export default function findOrCreateThread (userId, participantIds) {
  return findThread(uniq([userId].concat(participantIds)))
  .then(post => post || createThread(userId, uniq(participantIds)))
}

export async function createThread (userId, participantIds) {
  const attrs = await setupNewThreadAttrs(userId)
  let thread
  await bookshelf.transaction(async trx => {
    thread = await Post.create(attrs, {transacting: trx})
    await afterSavingThread(thread, {participantIds, transacting: trx})
  })
  return thread
}

export function validateThreadData (userId, data) {
  const { participantIds } = data
  if (!(participantIds && participantIds.length)) {
    throw new Error("participantIds can't be empty")
  }
  const checkForSharedCommunity = id =>
    Group.inSameGroup([userId, id], Community)
    .then(doesShare => {
      if (!doesShare) throw new Error(`no shared communities with user ${id}`)
    })
  return Promise.all(map(checkForSharedCommunity, participantIds))
}

function setupNewThreadAttrs (userId) {
  return Promise.resolve({
    type: Post.Type.THREAD,
    visibility: Post.Visibility.DEFAULT,
    user_id: userId,
    link_preview_id: null
  })
}

async function afterSavingThread (thread, opts) {
  const userId = thread.get('user_id')
  const participantIds = uniq([userId].concat(opts.participantIds))
  const trxOpts = pick(opts, 'transacting')

  const followers = await thread.addFollowers(participantIds, {}, trxOpts)
  return followers
}
<|endoftext|>


<commit_before>
// Laddar...
function toggleClass() {
	$('#nextMeal').toggleClass('loading');
	$('#tips').toggleClass('loading');
}

// Service info
function serviceBusy() {
	$('#hide').slideUp('fast');
	$('#serviceBusy').slideDown('fast');
}

// Hjärtan
function generateHearts(percent) {
	if(percent >= 20) {
		$('.popular').html('');
	} else if(percent >= 15) {
		$('.popular').html('');
	} else if(percent >= 10) {
		$('.popular').html('');
	} else if(percent >= 5) {
		$('.popular').html('');
	} else {
		$('.popular').html('');
	}
}

$(window).load(function() {

	// Formulär
	$('#tip_form').submit(function(ev) {
		ev.preventDefault();
		$.post("/index.php/submit/tip", $( "#tip_form" ).serialize() )
		.done(function(data) {
			if(data == 1) {
				$('#thanksForTips').addClass('show');
				$('#tip_form').trigger("reset");
				setTimeout(function() {
					$('#thanksForTips').removeClass('show');
				}, 8000);
			} else {
				alert("Något vart fel. Kontrollera att samtliga fält är ifyllda");
			}
		});
	});

	// Tangentbordstryckningar
	$(document).keydown(function(e) {
		e.preventDefault();
		var key = e.which;
		if(key == 82 || key == 78 || key == 13) {
			getMeal();
		} else if(key == 32) {
			$('#supertips .tips').hide();
			$('#supertips .success').show();
			setTimeout(function() {
				$('#supertips .success').addClass('deactivate');
			}, 2500);
			getMeal();
		} else if(key == 76 || key == 83) {
			$('#meal_link').trigger('click');
		}
	});
});

// Printa ut data i HTML
var counts = 0;
function getMeal() {
	toggleClass();
	$.getJSON("/api/getmeal/", function (data) {

		if(data.error) {

			$('#meal_count').html("-");
			$('.actionTrigger').attr('data-id', 0);
			$('#meal_owner').html("-");
			$('#meal_ownerlink').attr('href', "#");
			$('#meal_link').attr('href', "#");
			$('#meal_link').attr('data-original-title', "0 personer har läst receptet");

			generateHearts(0);

			$('#meal_name').html(data.error.code+" "+data.error.title);
			toggleClass();
			return false;

		}
		else {
			var meal = data.data

			$('#meal_count').html("#"+meal.id);
			$('.actionTrigger').attr('data-id', meal.id);
			$('#meal_name').html(meal.name);
			$('#meal_owner').html(meal.owner);
			$('#meal_ownerlink').attr('href', meal.ownerlink);
			$('#meal_link').attr('href', meal.link);
			$('#meal_link').attr('data-original-title', meal.clicks + " personer har läst receptet");
			$('.count').show();
			generateHearts(meal.percentage);

			toggleClass();

			return true;
		}
	});
}

// "Se recept" & "Nästa"
$('.actionTrigger').click(function () {
	if($(this).attr('id') == "meal_link") {
		var id = $(this).attr('data-id');
		$.get("/index.php/main/add_up?id="+id, function (data) {
		});
	} else if($(this).attr('id') == "nextMeal") {
		var id = $(this).attr('data-id');
		getMeal();
	});
	} else {
		// fail silently
		return false;
	}
});<commit_msg>JS bug<commit_after>
// Laddar...
function toggleClass() {
	$('#nextMeal').toggleClass('loading');
	$('#tips').toggleClass('loading');
}

// Service info
function serviceBusy() {
	$('#hide').slideUp('fast');
	$('#serviceBusy').slideDown('fast');
}

// Hjärtan
function generateHearts(percent) {
	if(percent >= 20) {
		$('.popular').html('');
	} else if(percent >= 15) {
		$('.popular').html('');
	} else if(percent >= 10) {
		$('.popular').html('');
	} else if(percent >= 5) {
		$('.popular').html('');
	} else {
		$('.popular').html('');
	}
}

$(window).load(function() {

	// Formulär
	$('#tip_form').submit(function(ev) {
		ev.preventDefault();
		$.post("/index.php/submit/tip", $( "#tip_form" ).serialize() )
		.done(function(data) {
			if(data == 1) {
				$('#thanksForTips').addClass('show');
				$('#tip_form').trigger("reset");
				setTimeout(function() {
					$('#thanksForTips').removeClass('show');
				}, 8000);
			} else {
				alert("Något vart fel. Kontrollera att samtliga fält är ifyllda");
			}
		});
	});

	// Tangentbordstryckningar
	$(document).keydown(function(e) {
		e.preventDefault();
		var key = e.which;
		if(key == 82 || key == 78 || key == 13) {
			getMeal();
		} else if(key == 32) {
			$('#supertips .tips').hide();
			$('#supertips .success').show();
			setTimeout(function() {
				$('#supertips .success').addClass('deactivate');
			}, 2500);
			getMeal();
		} else if(key == 76 || key == 83) {
			$('#meal_link').trigger('click');
		}
	});
});

// Printa ut data i HTML
var counts = 0;
function getMeal() {
	toggleClass();
	$.getJSON("/api/getmeal/", function (data) {

		if(data.error) {

			$('#meal_count').html("-");
			$('.actionTrigger').attr('data-id', 0);
			$('#meal_owner').html("-");
			$('#meal_ownerlink').attr('href', "#");
			$('#meal_link').attr('href', "#");
			$('#meal_link').attr('data-original-title', "0 personer har läst receptet");

			generateHearts(0);

			$('#meal_name').html(data.error.code+" "+data.error.title);
			toggleClass();
			return false;

		}
		else {
			var meal = data.data

			$('#meal_count').html("#"+meal.id);
			$('.actionTrigger').attr('data-id', meal.id);
			$('#meal_name').html(meal.name);
			$('#meal_owner').html(meal.owner);
			$('#meal_ownerlink').attr('href', meal.ownerlink);
			$('#meal_link').attr('href', meal.link);
			$('#meal_link').attr('data-original-title', meal.clicks + " personer har läst receptet");
			$('.count').show();
			generateHearts(meal.percentage);

			toggleClass();

			return true;
		}
	});
}

// "Se recept" & "Nästa"
$('.actionTrigger').click(function () {
	if($(this).attr('id') == "meal_link") {
		var id = $(this).attr('data-id');
		$.get("/index.php/main/add_up?id="+id, function (data) {
		});
	} else if($(this).attr('id') == "nextMeal") {
		var id = $(this).attr('data-id');
		getMeal();
	} else {
		// fail silently
		return false;
	}
});<|endoftext|>


<commit_before>/*
 HTML5 Shiv v3.6.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
(function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag();
a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/\w+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}</style>";
c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode||
"undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup main mark meter nav output progress section summary time video",version:"3.6.2",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);if(g)return a.createDocumentFragment();
for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document);
<commit_msg>Update html5shiv to v3.7.0.<commit_after>/*
 HTML5 Shiv v3.7.0 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
(function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag();
a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/[\w\-]+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}</style>";
c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode||
"undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video",version:"3.7.0",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);
if(g)return a.createDocumentFragment();for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document);
<|endoftext|>


<commit_before>/**
 * @file Nashorn host adapter
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_HOST*/ // Host types
/*global _gpfBootImplByHost*/ // Boot host specific implementation per host
/*global _gpfJavaHostImpl*/ // Common implementation for Java hosts
/*#endif*/

_gpfBootImplByHost[_GPF_HOST.NASHORN] = _gpfJavaHostImpl;
<commit_msg>Documentation (#220)<commit_after>/**
 * @file Nashorn host adapter
 * @since 0.2.4
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_HOST*/ // Host types
/*global _gpfBootImplByHost*/ // Boot host specific implementation per host
/*global _gpfJavaHostImpl*/ // Common implementation for Java hosts
/*#endif*/

_gpfBootImplByHost[_GPF_HOST.NASHORN] = _gpfJavaHostImpl;
<|endoftext|>


<commit_before>/**
 * @fileOverview Chalk detail scene assistant
 * @author l.m.orchard@pobox.com
 * @version 0.1
 */
/*jslint laxbreak: true */
/*global Decafbad, BlockChalk, Mojo, Ajax, $, $L, $A, $H, SimpleDateFormat */
function ChalkAssistant(chalk) {
    this.chalk = chalk;
}

ChalkAssistant.prototype = (function () { /** @lends ChalkAssistant# */

    return {

        /**
         * Set up the whole card.
         */
        setup: function () {

            BlockChalk.setupGlobalMenu(this.controller);

            this.controller.get('contents').update(
                this.chalk.contents.escapeHTML()
            );

            this.controller.get('meta').update([
                BlockChalk.formatDate(this.chalk.datetime),
                this.chalk.distance
            ].join(' ').escapeHTML());

            if (['nearby','home'].indexOf(BlockChalk.service.getLocationContext()) === -1) {
                // User browsing another location, disallow chalkbacks.
                this.controller.get('chalkback-wrapper').remove();
                this.controller.get('reply-wrapper').width = "100%";
            } else {
                // Chalkbacks allowed here, so setup up the button.
                this.controller.setupWidget(
                    'chalk-chalkback-button', { label: $L('Chalkback') }, {}
                );
             }

            // Hide the location button, or set it up if a place is present.
            if (!this.chalk.place) {
                this.controller.get('chalk-view-location-button').remove();
            } else {
                this.controller.setupWidget(
                    'chalk-view-location-button',
                    { label: $L('View attached location') }, {}
                );
            }

            // Hide the view chalkback button, unless there's a chalkbackTo
            if (!this.chalk.chalkbackTo) {
                this.controller.get('chalk-view-chalkback-button').remove();
            } else {
                $$('.chalk-scene')[0].addClassName('chalkback');
                this.controller.setupWidget(
                    'chalk-view-chalkback-button',
                    { label: $L('See original chalk') }, {}
                );
            }

            this.controller.setupWidget(
                'chalk-reply-button', { label: $L('Reply privately') }, {}
            );
            this.controller.setupWidget(
                'chalk-bury-button', { label: $L('Report') }, {}
            );
            this.controller.setupWidget(
                'chalk-tweet-button', { label: $L('Tweet') }, {}
            );
            this.controller.setupWidget(
                'chalk-email-button', { label: $L('Email') }, {}
            );

        },

        /**
         * Hook up listeners on card activation.
         */
        activate: function (event) {
            var listeners = [
                ['chalk-reply-button', Mojo.Event.tap, this.handleReply],
                ['chalk-bury-button', Mojo.Event.tap, this.handleBury],
                ['chalk-tweet-button', Mojo.Event.tap, this.handleTweet],
                ['chalk-email-button', Mojo.Event.tap, this.handleEmail]
            ];
            if (['nearby','home'].indexOf(BlockChalk.service.getLocationContext()) === -1) {
                // Wire up the chalkback button if allowed.
                listeners.push([
                    'chalk-chalkback-button',
                    Mojo.Event.tap, this.handleChalkback
                ]);
            }
            if (this.chalk.place) {
                // Wire up the location button if necessary.
                listeners.push([
                    'chalk-view-location-button',
                    Mojo.Event.tap, this.handleViewLocation
                ]);
            }
            if (this.chalk.chalkbackTo) {
                // Wire up the view chalkback button if necessary.
                listeners.push([
                    'chalk-view-chalkback-button',
                    Mojo.Event.tap, this.handleViewChalkback
                ]);
            }

            Decafbad.Utils.setupListeners(listeners, this);
        },

        /**
         * Unhook listeners on card deactivation.
         */
        deactivate: function (event) {
            Decafbad.Utils.clearListeners(this);
        },

        /**
         * Clean everything up.
         */
        cleanup: function (event) {
        },

        /**
         * Handle tap on the reply button.
         */
        handleReply: function (ev) {
            this.chalk.kind = 'chalk';
            this.controller.stageController.pushScene('reply', this.chalk);
        },

        /**
         * Handle tap on the chalkback reply button.
         */
        handleChalkback: function (ev) {
            return this.controller.stageController.pushScene(
                'compose', this.chalk
            );
        },

        /**
         * Handle tap on the bury button
         */
        handleBury: function (ev) {
            this.controller.showAlertDialog({
                title: $L("Report this chalk?"),
                message: $L("Reporting a chalk hides it from your view and helps us fight abuse."),
                choices: [
                    {label:$L("Report"), value:"yes", type:"negative"},
                    {label:$L("Cancel"),  value:"no", type:"dismiss"}
                ],
                onChoose: function(value) {
                    if ('yes' == value) {
                        BlockChalk.service.buryChalk(
                            this.chalk.id, BlockChalk.user_id,
                            function (resp) {
                                this.controller.stageController
                                    .popScene({ refresh: true });
                            }.bind(this),
                            function (resp) {
                                Decafbad.Utils.showSimpleBanner($L('Report failed!'));
                            }.bind(this)
                        );
                    }
                }.bind(this)
            });
        },

        /**
         * Handle tap on the view attached location button
         */
        handleViewLocation: function (ev) {
            this.controller.serviceRequest('palm://com.palm.applicationManager', {
                method: 'launch',
                parameters: {
                    id: "com.palm.app.maps",
                    params: { "query": this.chalk.place }
                }
            });
        },

        /**
         * Handle tap on the view original chalkback button
         */
        handleViewChalkback: function (ev) {
            BlockChalk.service.getChalk(
                this.chalk.chalkbackTo,
                function (chalk) {
                    this.controller.stageController.pushScene('chalk', chalk);
                }.bind(this),
                function (resp) {
                    Decafbad.Utils.showSimpleBanner(
                        $L('Original chalk not found!')
                    );
                }.bind(this)
            );
        },

        /**
         * Handle tap on the tweet button
         */
        handleTweet: function (ev) {
            var url = "http://m.twitter.com/home?status=" +
                encodeURIComponent(
                    'Check out this chalk on my block ' +
                    'http://blockchalk.com/'+this.chalk.id+'#chalk'
                );
            Mojo.log("Tweet this URL: %s", url);
            this.controller.serviceRequest("palm://com.palm.applicationManager", {
                method: "open",
                parameters:  {
                    id: 'com.palm.app.browser',
                    params: { target: url }
                }
            });
        },

        /**
         * Handle tap on the email button
         */
        handleEmail: function (ev) {
            this.controller.serviceRequest('palm://com.palm.applicationManager', {
                method: 'open',
                parameters: {
                    id: 'com.palm.app.email',
                    params: {
                        summary: 'Check out this post from BlockChalk',
                        text: $L(
                            "Hey, I wanted you to see this post from BlockChalk:\n\n"+
                            "http://blockchalk.com/"
                        )+this.chalk.id,
                        recipients: [ ]
                    }
                }
            });
        },

        EOF: null
    };

}());
<commit_msg>Bugfix to chalkbacks<commit_after>/**
 * @fileOverview Chalk detail scene assistant
 * @author l.m.orchard@pobox.com
 * @version 0.1
 */
/*jslint laxbreak: true */
/*global Decafbad, BlockChalk, Mojo, Ajax, $, $L, $A, $H, SimpleDateFormat */
function ChalkAssistant(chalk) {
    this.chalk = chalk;
}

ChalkAssistant.prototype = (function () { /** @lends ChalkAssistant# */

    return {

        /**
         * Set up the whole card.
         */
        setup: function () {

            BlockChalk.setupGlobalMenu(this.controller);

            this.controller.get('contents').update(
                this.chalk.contents.escapeHTML()
            );

            this.controller.get('meta').update([
                BlockChalk.formatDate(this.chalk.datetime),
                this.chalk.distance
            ].join(' ').escapeHTML());

            if (['nearby','home'].indexOf(BlockChalk.service.getLocationContext()) === -1) {
                // User browsing another location, disallow chalkbacks.
                this.controller.get('chalkback-wrapper').remove();
                this.controller.get('reply-wrapper').width = "100%";
            } else {
                // Chalkbacks allowed here, so setup up the button.
                this.controller.setupWidget(
                    'chalk-chalkback-button', { label: $L('Chalkback') }, {}
                );
             }

            // Hide the location button, or set it up if a place is present.
            if (!this.chalk.place) {
                this.controller.get('chalk-view-location-button').remove();
            } else {
                this.controller.setupWidget(
                    'chalk-view-location-button',
                    { label: $L('View attached location') }, {}
                );
            }

            // Hide the view chalkback button, unless there's a chalkbackTo
            if (!this.chalk.chalkbackTo) {
                this.controller.get('chalk-view-chalkback-button').remove();
            } else {
                $$('.chalk-scene')[0].addClassName('chalkback');
                this.controller.setupWidget(
                    'chalk-view-chalkback-button',
                    { label: $L('See original chalk') }, {}
                );
            }

            this.controller.setupWidget(
                'chalk-reply-button', { label: $L('Reply privately') }, {}
            );
            this.controller.setupWidget(
                'chalk-bury-button', { label: $L('Report') }, {}
            );
            this.controller.setupWidget(
                'chalk-tweet-button', { label: $L('Tweet') }, {}
            );
            this.controller.setupWidget(
                'chalk-email-button', { label: $L('Email') }, {}
            );

        },

        /**
         * Hook up listeners on card activation.
         */
        activate: function (event) {
            var listeners = [
                ['chalk-reply-button', Mojo.Event.tap, this.handleReply],
                ['chalk-bury-button', Mojo.Event.tap, this.handleBury],
                ['chalk-tweet-button', Mojo.Event.tap, this.handleTweet],
                ['chalk-email-button', Mojo.Event.tap, this.handleEmail]
            ];
            if (['nearby','home'].indexOf(BlockChalk.service.getLocationContext()) !== -1) {
                // Wire up the chalkback button if allowed.
                listeners.push([
                    'chalk-chalkback-button',
                    Mojo.Event.tap, this.handleChalkback
                ]);
            }
            if (this.chalk.place) {
                // Wire up the location button if necessary.
                listeners.push([
                    'chalk-view-location-button',
                    Mojo.Event.tap, this.handleViewLocation
                ]);
            }
            if (this.chalk.chalkbackTo) {
                // Wire up the view chalkback button if necessary.
                listeners.push([
                    'chalk-view-chalkback-button',
                    Mojo.Event.tap, this.handleViewChalkback
                ]);
            }

            Decafbad.Utils.setupListeners(listeners, this);
        },

        /**
         * Unhook listeners on card deactivation.
         */
        deactivate: function (event) {
            Decafbad.Utils.clearListeners(this);
        },

        /**
         * Clean everything up.
         */
        cleanup: function (event) {
        },

        /**
         * Handle tap on the reply button.
         */
        handleReply: function (ev) {
            this.chalk.kind = 'chalk';
            this.controller.stageController.pushScene('reply', this.chalk);
        },

        /**
         * Handle tap on the chalkback reply button.
         */
        handleChalkback: function (ev) {
            return this.controller.stageController.pushScene(
                'compose', this.chalk
            );
        },

        /**
         * Handle tap on the bury button
         */
        handleBury: function (ev) {
            this.controller.showAlertDialog({
                title: $L("Report this chalk?"),
                message: $L("Reporting a chalk hides it from your view and helps us fight abuse."),
                choices: [
                    {label:$L("Report"), value:"yes", type:"negative"},
                    {label:$L("Cancel"),  value:"no", type:"dismiss"}
                ],
                onChoose: function(value) {
                    if ('yes' == value) {
                        BlockChalk.service.buryChalk(
                            this.chalk.id, BlockChalk.user_id,
                            function (resp) {
                                this.controller.stageController
                                    .popScene({ refresh: true });
                            }.bind(this),
                            function (resp) {
                                Decafbad.Utils.showSimpleBanner($L('Report failed!'));
                            }.bind(this)
                        );
                    }
                }.bind(this)
            });
        },

        /**
         * Handle tap on the view attached location button
         */
        handleViewLocation: function (ev) {
            this.controller.serviceRequest('palm://com.palm.applicationManager', {
                method: 'launch',
                parameters: {
                    id: "com.palm.app.maps",
                    params: { "query": this.chalk.place }
                }
            });
        },

        /**
         * Handle tap on the view original chalkback button
         */
        handleViewChalkback: function (ev) {
            BlockChalk.service.getChalk(
                this.chalk.chalkbackTo,
                function (chalk) {
                    this.controller.stageController.pushScene('chalk', chalk);
                }.bind(this),
                function (resp) {
                    Decafbad.Utils.showSimpleBanner(
                        $L('Original chalk not found!')
                    );
                }.bind(this)
            );
        },

        /**
         * Handle tap on the tweet button
         */
        handleTweet: function (ev) {
            var url = "http://m.twitter.com/home?status=" +
                encodeURIComponent(
                    'Check out this chalk on my block ' +
                    'http://blockchalk.com/'+this.chalk.id+'#chalk'
                );
            Mojo.log("Tweet this URL: %s", url);
            this.controller.serviceRequest("palm://com.palm.applicationManager", {
                method: "open",
                parameters:  {
                    id: 'com.palm.app.browser',
                    params: { target: url }
                }
            });
        },

        /**
         * Handle tap on the email button
         */
        handleEmail: function (ev) {
            this.controller.serviceRequest('palm://com.palm.applicationManager', {
                method: 'open',
                parameters: {
                    id: 'com.palm.app.email',
                    params: {
                        summary: 'Check out this post from BlockChalk',
                        text: $L(
                            "Hey, I wanted you to see this post from BlockChalk:\n\n"+
                            "http://blockchalk.com/"
                        )+this.chalk.id,
                        recipients: [ ]
                    }
                }
            });
        },

        EOF: null
    };

}());
<|endoftext|>