prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>test_lagrange_polynomials.py<|end_file_name|><|fim▁begin|>import chaospy
import numpy
import pytest
@pytest.fixture
def samples(joint):
return joint.sample(10, rule="sobol")
@pytest.fixture
def evaluations(model_solver, samples):
return numpy.array([model_solver(sample) for sample in samples.T])
@pytest.fixture
def expansion(samples):
return chaospy.lagrange_polynomial(samples)
<|fim▁hole|> return chaospy.sum(evaluations.T*expansion, axis=-1).T
def test_lagrange_mean(lagrange_approximation, joint, true_mean):
assert numpy.allclose(chaospy.E(lagrange_approximation, joint), true_mean, rtol=1e-3)
def test_lagrange_variance(lagrange_approximation, joint, true_variance):
assert numpy.allclose(chaospy.Var(lagrange_approximation, joint), true_variance, rtol=1e-2)<|fim▁end|>
|
@pytest.fixture
def lagrange_approximation(evaluations, expansion):
|
<|file_name|>jquery-ui.js<|end_file_name|><|fim▁begin|>/*! jQuery UI - v1.10.3 - 2013-05-03
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.effect.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js, jquery.ui.menu.js, jquery.ui.position.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js
* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
(function($, undefined) {
var uuid = 0,
runiqueId = /^ui-id-\d+$/;
// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};
$.extend($.ui, {
version: "1.10.3",
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
});
// plugins
$.fn.extend({
focus: (function(orig) {
return function(delay, fn) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(function() {
$(elem).focus();
if (fn) {
fn.call(elem);
}
}, delay);
}) :
orig.apply(this, arguments);
};
})($.fn.focus),
scrollParent: function() {
var scrollParent;
if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) {
scrollParent = this.parents().filter(function() {
return (/(relative|absolute|fixed)/).test($.css(this, "position")) && (/(auto|scroll)/).test($.css(this, "overflow") + $.css(this, "overflow-y") + $.css(this, "overflow-x"));
}).eq(0);
} else {
scrollParent = this.parents().filter(function() {
return (/(auto|scroll)/).test($.css(this, "overflow") + $.css(this, "overflow-y") + $.css(this, "overflow-x"));
}).eq(0);
}
return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent;
},
zIndex: function(zIndex) {
if (zIndex !== undefined) {
return this.css("zIndex", zIndex);
}
if (this.length) {
var elem = $(this[ 0 ]), position, value;
while (elem.length && elem[ 0 ] !== document) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css("position");
if (position === "absolute" || position === "relative" || position === "fixed") {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt(elem.css("zIndex"), 10);
if (!isNaN(value) && value !== 0) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
},
uniqueId: function() {
return this.each(function() {
if (!this.id) {
this.id = "ui-id-" + (++uuid);
}
});
},
removeUniqueId: function() {
return this.each(function() {
if (runiqueId.test(this.id)) {
$(this).removeAttr("id");
}
});
}
});
// selectors
function focusable(element, isTabIndexNotNaN) {
var map, mapName, img,
nodeName = element.nodeName.toLowerCase();
if ("area" === nodeName) {
map = element.parentNode;
mapName = map.name;
if (!element.href || !mapName || map.nodeName.toLowerCase() !== "map") {
return false;
}
img = $("img[usemap=#" + mapName + "]")[0];
return !!img && visible(img);
}
return (/input|select|textarea|button|object/.test(nodeName) ?
!element.disabled :
"a" === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) &&
// the element and all of its ancestors must be visible
visible(element);
}
function visible(element) {
return $.expr.filters.visible(element) &&
!$(element).parents().addBack().filter(function() {
return $.css(this, "visibility") === "hidden";
}).length;
}
$.extend($.expr[ ":" ], {
data: $.expr.createPseudo ?
$.expr.createPseudo(function(dataName) {
return function(elem) {
return !!$.data(elem, dataName);
};
}) :
// support: jQuery <1.8
function(elem, i, match) {
return !!$.data(elem, match[ 3 ]);
},
focusable: function(element) {
return focusable(element, !isNaN($.attr(element, "tabindex")));
},
tabbable: function(element) {
var tabIndex = $.attr(element, "tabindex"),
isTabIndexNaN = isNaN(tabIndex);
return (isTabIndexNaN || tabIndex >= 0) && focusable(element, !isTabIndexNaN);
}
});
// support: jQuery <1.8
if (!$("<a>").outerWidth(1).jquery) {
$.each(["Width", "Height"], function(i, name) {
var side = name === "Width" ? ["Left", "Right"] : ["Top", "Bottom"],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};
function reduce(elem, size, border, margin) {
$.each(side, function() {
size -= parseFloat($.css(elem, "padding" + this)) || 0;
if (border) {
size -= parseFloat($.css(elem, "border" + this + "Width")) || 0;
}
if (margin) {
size -= parseFloat($.css(elem, "margin" + this)) || 0;
}
});
return size;
}
$.fn[ "inner" + name ] = function(size) {
if (size === undefined) {
return orig[ "inner" + name ].call(this);
}
return this.each(function() {
$(this).css(type, reduce(this, size) + "px");
});
};
$.fn[ "outer" + name] = function(size, margin) {
if (typeof size !== "number") {
return orig[ "outer" + name ].call(this, size);
}
return this.each(function() {
$(this).css(type, reduce(this, size, true, margin) + "px");
});
};
});
}
// support: jQuery <1.8
if (!$.fn.addBack) {
$.fn.addBack = function(selector) {
return this.add(selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
};
}
// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ($("<a>").data("a-b", "a").removeData("a-b").data("a-b")) {
$.fn.removeData = (function(removeData) {
return function(key) {
if (arguments.length) {
return removeData.call(this, $.camelCase(key));
} else {
return removeData.call(this);
}
};
})($.fn.removeData);
}
// deprecated
$.ui.ie = !!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());
$.support.selectstart = "onselectstart" in document.createElement("div");
$.fn.extend({
disableSelection: function() {
return this.bind(($.support.selectstart ? "selectstart" : "mousedown") +
".ui-disableSelection", function(event) {
event.preventDefault();
});
},
enableSelection: function() {
return this.unbind(".ui-disableSelection");
}
});
$.extend($.ui, {
// $.ui.plugin is deprecated. Use $.widget() extensions instead.
plugin: {
add: function(module, option, set) {
var i,
proto = $.ui[ module ].prototype;
for (i in set) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push([option, set[ i ]]);
}
},
call: function(instance, name, args) {
var i,
set = instance.plugins[ name ];
if (!set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11) {
return;
}
for (i = 0; i < set.length; i++) {
if (instance.options[ set[ i ][ 0 ] ]) {
set[ i ][ 1 ].apply(instance.element, args);
}
}
}
},
// only used by resizable
hasScroll: function(el, a) {
//If overflow is hidden, the element might have extra content, but the user wants to hide it
if ($(el).css("overflow") === "hidden") {
return false;
}
var scroll = (a && a === "left") ? "scrollLeft" : "scrollTop",
has = false;
if (el[ scroll ] > 0) {
return true;
}
// TODO: determine which cases actually cause this to happen
// if the element doesn't have the scroll set, see if it's possible to
// set the scroll
el[ scroll ] = 1;
has = (el[ scroll ] > 0);
el[ scroll ] = 0;
return has;
}
});
})(jQuery);
(function($, undefined) {
var uuid = 0,
slice = Array.prototype.slice,
_cleanData = $.cleanData;
$.cleanData = function(elems) {
for (var i = 0, elem; (elem = elems[i]) != null; i++) {
try {
$(elem).triggerHandler("remove");
// http://bugs.jquery.com/ticket/8235
} catch (e) {
}
}
_cleanData(elems);
};
$.widget = function(name, base, prototype) {
var fullName, existingConstructor, constructor, basePrototype,
// proxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
proxiedPrototype = {},
namespace = name.split(".")[ 0 ];
name = name.split(".")[ 1 ];
fullName = namespace + "-" + name;
if (!prototype) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function(elem) {
return !!$.data(elem, fullName);
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function(options, element) {
// allow instantiation without "new" keyword
if (!this._createWidget) {
return new constructor(options, element);
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if (arguments.length) {
this._createWidget(options, element);
}
};
// extend with the existing constructor to carry over any static properties
$.extend(constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend({}, prototype),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend({}, basePrototype.options);
$.each(prototype, function(prop, value) {
if (!$.isFunction(value)) {
proxiedPrototype[ prop ] = value;
return;
}
proxiedPrototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply(this, arguments);
},
_superApply = function(args) {
return base.prototype[ prop ].apply(this, args);
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply(this, arguments);
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
});
constructor.prototype = $.widget.extend(basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if (existingConstructor) {
$.each(existingConstructor._childConstructors, function(i, child) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget(childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto);
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push(constructor);
}
$.widget.bridge(name, constructor);
};
$.widget.extend = function(target) {
var input = slice.call(arguments, 1),
inputIndex = 0,
inputLength = input.length,
key,
value;
for (; inputIndex < inputLength; inputIndex++) {
for (key in input[ inputIndex ]) {
value = input[ inputIndex ][ key ];
if (input[ inputIndex ].hasOwnProperty(key) && value !== undefined) {
// Clone objects
if ($.isPlainObject(value)) {
target[ key ] = $.isPlainObject(target[ key ]) ?
$.widget.extend({}, target[ key ], value) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend({}, value);
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function(name, object) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function(options) {
var isMethodCall = typeof options === "string",
args = slice.call(arguments, 1),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply(null, [options].concat(args)) :
options;
if (isMethodCall) {
this.each(function() {
var methodValue,
instance = $.data(this, fullName);
if (!instance) {
return $.error("cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'");
}
if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
return $.error("no such method '" + options + "' for " + name + " widget instance");
}
methodValue = instance[ options ].apply(instance, args);
if (methodValue !== instance && methodValue !== undefined) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack(methodValue.get()) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data(this, fullName);
if (instance) {
instance.option(options || {})._init();
} else {
$.data(this, fullName, new object(options, this));
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {
};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function(options, element) {
element = $(element || this.defaultElement || this)[ 0 ];
this.element = $(element);
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend({},
this.options,
this._getCreateOptions(),
options);
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if (element !== this) {
$.data(element, this.widgetFullName, this);
this._on(true, this.element, {
remove: function(event) {
if (event.target === element) {
this.destroy();
}
}
});
this.document = $(element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element);
this.window = $(this.document[0].defaultView || this.document[0].parentWindow);
}
this._create();
this._trigger("create", null, this._getCreateEventData());
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind(this.eventNamespace)
// 1.9 BC for #7810
// TODO remove dual storage
.removeData(this.widgetName)
.removeData(this.widgetFullName)
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData($.camelCase(this.widgetFullName));
this.widget()
.unbind(this.eventNamespace)
.removeAttr("aria-disabled")
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled");
// clean up events and states
this.bindings.unbind(this.eventNamespace);
this.hoverable.removeClass("ui-state-hover");
this.focusable.removeClass("ui-state-focus");
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function(key, value) {
var options = key,
parts,
curOption,
i;
if (arguments.length === 0) {
// don't return a reference to the internal hash
return $.widget.extend({}, this.options);
}
if (typeof key === "string") {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split(".");
key = parts.shift();
if (parts.length) {
curOption = options[ key ] = $.widget.extend({}, this.options[ key ]);
for (i = 0; i < parts.length - 1; i++) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if (value === undefined) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if (value === undefined) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions(options);
return this;
},
_setOptions: function(options) {
var key;
for (key in options) {
this._setOption(key, options[ key ]);
}
return this;
},
_setOption: function(key, value) {
this.options[ key ] = value;
if (key === "disabled") {
this.widget()
.toggleClass(this.widgetFullName + "-disabled ui-state-disabled", !!value)
.attr("aria-disabled", value);
this.hoverable.removeClass("ui-state-hover");
this.focusable.removeClass("ui-state-focus");
}
return this;
},
enable: function() {
return this._setOption("disabled", false);
},
disable: function() {
return this._setOption("disabled", true);
},
_on: function(suppressDisabledCheck, element, handlers) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if (typeof suppressDisabledCheck !== "boolean") {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if (!handlers) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
// accept selectors, DOM elements
element = delegateElement = $(element);
this.bindings = this.bindings.add(element);
}
$.each(handlers, function(event, handler) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if (!suppressDisabledCheck &&
(instance.options.disabled === true ||
$(this).hasClass("ui-state-disabled"))) {
return;
}
return (typeof handler === "string" ? instance[ handler ] : handler)
.apply(instance, arguments);
}
// copy the guid so direct unbinding works
if (typeof handler !== "string") {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match(/^(\w+)\s*(.*)$/),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if (selector) {
delegateElement.delegate(selector, eventName, handlerProxy);
} else {
element.bind(eventName, handlerProxy);
}
});
},
_off: function(element, eventName) {
eventName = (eventName || "").split(" ").join(this.eventNamespace + " ") + this.eventNamespace;
element.unbind(eventName).undelegate(eventName);
},
_delay: function(handler, delay) {
function handlerProxy() {
return (typeof handler === "string" ? instance[ handler ] : handler)
.apply(instance, arguments);
}
var instance = this;
return setTimeout(handlerProxy, delay || 0);
},
_hoverable: function(element) {
this.hoverable = this.hoverable.add(element);
this._on(element, {
mouseenter: function(event) {
$(event.currentTarget).addClass("ui-state-hover");
},
mouseleave: function(event) {
$(event.currentTarget).removeClass("ui-state-hover");
}
});
},
_focusable: function(element) {
this.focusable = this.focusable.add(element);
this._on(element, {
focusin: function(event) {
$(event.currentTarget).addClass("ui-state-focus");
},
focusout: function(event) {
$(event.currentTarget).removeClass("ui-state-focus");
}
});
},
_trigger: function(type, event, data) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event(event);
event.type = (type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if (orig) {
for (prop in orig) {
if (!(prop in event)) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger(event, data);
return !($.isFunction(callback) &&
callback.apply(this.element[0], [event].concat(data)) === false ||
event.isDefaultPrevented());
}
};
$.each({show: "fadeIn", hide: "fadeOut"}, function(method, defaultEffect) {
$.Widget.prototype[ "_" + method ] = function(element, options, callback) {
if (typeof options === "string") {
options = {effect: options};
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if (typeof options === "number") {
options = {duration: options};
}
hasOptions = !$.isEmptyObject(options);
options.complete = callback;
if (options.delay) {
element.delay(options.delay);
}
if (hasOptions && $.effects && $.effects.effect[ effectName ]) {
element[ method ](options);
} else if (effectName !== method && element[ effectName ]) {
element[ effectName ](options.duration, options.easing, callback);
} else {
element.queue(function(next) {
$(this)[ method ]();
if (callback) {
callback.call(element[ 0 ]);
}
next();
});
}
};
});
})(jQuery);
(function($, undefined) {
var mouseHandled = false;
$(document).mouseup(function() {
mouseHandled = false;
});
$.widget("ui.mouse", {
version: "1.10.3",
options: {
cancel: "input,textarea,button,select,option",
distance: 1,
delay: 0
},
_mouseInit: function() {
var that = this;
this.element
.bind("mousedown." + this.widgetName, function(event) {
return that._mouseDown(event);
})
.bind("click." + this.widgetName, function(event) {
if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
$.removeData(event.target, that.widgetName + ".preventClickEvent");
event.stopImmediatePropagation();
return false;
}
});
this.started = false;
},
// TODO: make sure destroying one instance of mouse doesn't mess with
// other instances of mouse
_mouseDestroy: function() {
this.element.unbind("." + this.widgetName);
if (this._mouseMoveDelegate) {
$(document)
.unbind("mousemove." + this.widgetName, this._mouseMoveDelegate)
.unbind("mouseup." + this.widgetName, this._mouseUpDelegate);
}
},
_mouseDown: function(event) {
// don't let more than one widget handle mouseStart
if (mouseHandled) {
return;
}
// we may have missed mouseup (out of window)
(this._mouseStarted && this._mouseUp(event));
this._mouseDownEvent = event;
var that = this,
btnIsLeft = (event.which === 1),
// event.target.nodeName works around a bug in IE 8 with
// disabled inputs (#7620)
elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
return true;
}
this.mouseDelayMet = !this.options.delay;
if (!this.mouseDelayMet) {
this._mouseDelayTimer = setTimeout(function() {
that.mouseDelayMet = true;
}, this.options.delay);
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted = (this._mouseStart(event) !== false);
if (!this._mouseStarted) {
event.preventDefault();
return true;
}
}
// Click event may never have fired (Gecko & Opera)
if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
$.removeData(event.target, this.widgetName + ".preventClickEvent");
}
// these delegates are required to keep context
this._mouseMoveDelegate = function(event) {
return that._mouseMove(event);
};
this._mouseUpDelegate = function(event) {
return that._mouseUp(event);
};
$(document)
.bind("mousemove." + this.widgetName, this._mouseMoveDelegate)
.bind("mouseup." + this.widgetName, this._mouseUpDelegate);
event.preventDefault();
mouseHandled = true;
return true;
},
_mouseMove: function(event) {
// IE mouseup check - mouseup happened when mouse was out of window
if ($.ui.ie && (!document.documentMode || document.documentMode < 9) && !event.button) {
return this._mouseUp(event);
}
if (this._mouseStarted) {
this._mouseDrag(event);
return event.preventDefault();
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted =
(this._mouseStart(this._mouseDownEvent, event) !== false);
(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
}
return !this._mouseStarted;
},
_mouseUp: function(event) {
$(document)
.unbind("mousemove." + this.widgetName, this._mouseMoveDelegate)
.unbind("mouseup." + this.widgetName, this._mouseUpDelegate);
if (this._mouseStarted) {
this._mouseStarted = false;
if (event.target === this._mouseDownEvent.target) {
$.data(event.target, this.widgetName + ".preventClickEvent", true);
}
this._mouseStop(event);
}
return false;
},
_mouseDistanceMet: function(event) {
return (Math.max(
Math.abs(this._mouseDownEvent.pageX - event.pageX),
Math.abs(this._mouseDownEvent.pageY - event.pageY)
) >= this.options.distance
);
},
_mouseDelayMet: function(/* event */) {
return this.mouseDelayMet;
},
// These are placeholder methods, to be overriden by extending plugin
_mouseStart: function(/* event */) {
},
_mouseDrag: function(/* event */) {
},
_mouseStop: function(/* event */) {
},
_mouseCapture: function(/* event */) {
return true;
}
});
})(jQuery);
(function($, undefined) {
$.widget("ui.draggable", $.ui.mouse, {
version: "1.10.3",
widgetEventPrefix: "drag",
options: {
addClasses: true,
appendTo: "parent",
axis: false,
connectToSortable: false,
containment: false,
cursor: "auto",
cursorAt: false,
grid: false,
handle: false,
helper: "original",
iframeFix: false,
opacity: false,
refreshPositions: false,
revert: false,
revertDuration: 500,
scope: "default",
scroll: true,
scrollSensitivity: 20,
scrollSpeed: 20,
snap: false,
snapMode: "both",
snapTolerance: 20,
stack: false,
zIndex: false,
// callbacks
drag: null,
start: null,
stop: null
},
_create: function() {
if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) {
this.element[0].style.position = "relative";
}
if (this.options.addClasses) {
this.element.addClass("ui-draggable");
}
if (this.options.disabled) {
this.element.addClass("ui-draggable-disabled");
}
this._mouseInit();
},
_destroy: function() {
this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");
this._mouseDestroy();
},
_mouseCapture: function(event) {
var o = this.options;
// among others, prevent a drag on a resizable-handle
if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) {
return false;
}
//Quit if we're not on a valid handle
this.handle = this._getHandle(event);
if (!this.handle) {
return false;
}
$(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
$("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>")
.css({
width: this.offsetWidth + "px", height: this.offsetHeight + "px",
position: "absolute", opacity: "0.001", zIndex: 1000
})
.css($(this).offset())
.appendTo("body");
});
return true;
},
_mouseStart: function(event) {
var o = this.options;
//Create and append the visible helper
this.helper = this._createHelper(event);
this.helper.addClass("ui-draggable-dragging");
//Cache the helper size
this._cacheHelperProportions();
//If ddmanager is used for droppables, set the global draggable
if ($.ui.ddmanager) {
$.ui.ddmanager.current = this;
}
/*
* - Position generation -
* This block generates everything position related - it's the core of draggables.
*/
//Cache the margins of the original element
this._cacheMargins();
//Store the helper's css position
this.cssPosition = this.helper.css("position");
this.scrollParent = this.helper.scrollParent();
this.offsetParent = this.helper.offsetParent();
this.offsetParentCssPosition = this.offsetParent.css("position");
//The element's absolute position on the page minus margins
this.offset = this.positionAbs = this.element.offset();
this.offset = {
top: this.offset.top - this.margins.top,
left: this.offset.left - this.margins.left
};
//Reset scroll cache
this.offset.scroll = false;
$.extend(this.offset, {
click: {//Where the click happened, relative to the element
left: event.pageX - this.offset.left,
top: event.pageY - this.offset.top
},
parent: this._getParentOffset(),
relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
});
//Generate the original position
this.originalPosition = this.position = this._generatePosition(event);
this.originalPageX = event.pageX;
this.originalPageY = event.pageY;
//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
//Set a containment if given in the options
this._setContainment();
//Trigger event + callbacks
if (this._trigger("start", event) === false) {
this._clear();
return false;
}
//Recache the helper size
this._cacheHelperProportions();
//Prepare the droppable offsets
if ($.ui.ddmanager && !o.dropBehaviour) {
$.ui.ddmanager.prepareOffsets(this, event);
}
this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
//If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
if ($.ui.ddmanager) {
$.ui.ddmanager.dragStart(this, event);
}
return true;
},
_mouseDrag: function(event, noPropagation) {
// reset any necessary cached properties (see #5009)
if (this.offsetParentCssPosition === "fixed") {
this.offset.parent = this._getParentOffset();
}
//Compute the helpers position
this.position = this._generatePosition(event);
this.positionAbs = this._convertPositionTo("absolute");
//Call plugins and callbacks and use the resulting position if something is returned
if (!noPropagation) {
var ui = this._uiHash();
if (this._trigger("drag", event, ui) === false) {
this._mouseUp({});
return false;
}
this.position = ui.position;
}
if (!this.options.axis || this.options.axis !== "y") {
this.helper[0].style.left = this.position.left + "px";
}
if (!this.options.axis || this.options.axis !== "x") {
this.helper[0].style.top = this.position.top + "px";
}
if ($.ui.ddmanager) {
$.ui.ddmanager.drag(this, event);
}
return false;
},
_mouseStop: function(event) {
//If we are using droppables, inform the manager about the drop
var that = this,
dropped = false;
if ($.ui.ddmanager && !this.options.dropBehaviour) {
dropped = $.ui.ddmanager.drop(this, event);
}
//if a drop comes from outside (a sortable)
if (this.dropped) {
dropped = this.dropped;
this.dropped = false;
}
//if the original element is no longer in the DOM don't bother to continue (see #8269)
if (this.options.helper === "original" && !$.contains(this.element[ 0 ].ownerDocument, this.element[ 0 ])) {
return false;
}
if ((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
if (that._trigger("stop", event) !== false) {
that._clear();
}
});
} else {
if (this._trigger("stop", event) !== false) {
this._clear();
}
}
return false;
},
_mouseUp: function(event) {
//Remove frame helpers
$("div.ui-draggable-iframeFix").each(function() {
this.parentNode.removeChild(this);
});
//If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
if ($.ui.ddmanager) {
$.ui.ddmanager.dragStop(this, event);
}
return $.ui.mouse.prototype._mouseUp.call(this, event);
},
cancel: function() {
if (this.helper.is(".ui-draggable-dragging")) {
this._mouseUp({});
} else {
this._clear();
}
return this;
},
_getHandle: function(event) {
return this.options.handle ?
!!$(event.target).closest(this.element.find(this.options.handle)).length :
true;
},
_createHelper: function(event) {
var o = this.options,
helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element);
if (!helper.parents("body").length) {
helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo));
}
if (helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) {
helper.css("position", "absolute");
}
return helper;
},
_adjustOffsetFromHelper: function(obj) {
if (typeof obj === "string") {
obj = obj.split(" ");
}
if ($.isArray(obj)) {
obj = {left: +obj[0], top: +obj[1] || 0};
}
if ("left" in obj) {
this.offset.click.left = obj.left + this.margins.left;
}
if ("right" in obj) {
this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
}
if ("top" in obj) {
this.offset.click.top = obj.top + this.margins.top;
}
if ("bottom" in obj) {
this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
}
},
_getParentOffset: function() {
//Get the offsetParent and cache its position
var po = this.offsetParent.offset();
// This is a special case where we need to modify a offset calculated on start, since the following happened:
// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
// the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
po.left += this.scrollParent.scrollLeft();
po.top += this.scrollParent.scrollTop();
}
//This needs to be actually done for all browsers, since pageX/pageY includes this information
//Ugly IE fix
if ((this.offsetParent[0] === document.body) ||
(this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
po = {top: 0, left: 0};
}
return {
top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0),
left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0)
};
},
_getRelativeOffset: function() {
if (this.cssPosition === "relative") {
var p = this.element.position();
return {
top: p.top - (parseInt(this.helper.css("top"), 10) || 0) + this.scrollParent.scrollTop(),
left: p.left - (parseInt(this.helper.css("left"), 10) || 0) + this.scrollParent.scrollLeft()
};
} else {
return {top: 0, left: 0};
}
},
_cacheMargins: function() {
this.margins = {
left: (parseInt(this.element.css("marginLeft"), 10) || 0),
top: (parseInt(this.element.css("marginTop"), 10) || 0),
right: (parseInt(this.element.css("marginRight"), 10) || 0),
bottom: (parseInt(this.element.css("marginBottom"), 10) || 0)
};
},
_cacheHelperProportions: function() {
this.helperProportions = {
width: this.helper.outerWidth(),
height: this.helper.outerHeight()
};
},
_setContainment: function() {
var over, c, ce,
o = this.options;
if (!o.containment) {
this.containment = null;
return;
}
if (o.containment === "window") {
this.containment = [
$(window).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
$(window).scrollTop() - this.offset.relative.top - this.offset.parent.top,
$(window).scrollLeft() + $(window).width() - this.helperProportions.width - this.margins.left,
$(window).scrollTop() + ($(window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
];
return;
}
if (o.containment === "document") {
this.containment = [
0,
0,
$(document).width() - this.helperProportions.width - this.margins.left,
($(document).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
];
return;
}
if (o.containment.constructor === Array) {
this.containment = o.containment;
return;
}
if (o.containment === "parent") {
o.containment = this.helper[ 0 ].parentNode;
}
c = $(o.containment);
ce = c[ 0 ];
if (!ce) {
return;
}
over = c.css("overflow") !== "hidden";
this.containment = [
(parseInt(c.css("borderLeftWidth"), 10) || 0) + (parseInt(c.css("paddingLeft"), 10) || 0),
(parseInt(c.css("borderTopWidth"), 10) || 0) + (parseInt(c.css("paddingTop"), 10) || 0),
(over ? Math.max(ce.scrollWidth, ce.offsetWidth) : ce.offsetWidth) - (parseInt(c.css("borderRightWidth"), 10) || 0) - (parseInt(c.css("paddingRight"), 10) || 0) - this.helperProportions.width - this.margins.left - this.margins.right,
(over ? Math.max(ce.scrollHeight, ce.offsetHeight) : ce.offsetHeight) - (parseInt(c.css("borderBottomWidth"), 10) || 0) - (parseInt(c.css("paddingBottom"), 10) || 0) - this.helperProportions.height - this.margins.top - this.margins.bottom
];
this.relative_container = c;
},
_convertPositionTo: function(d, pos) {
if (!pos) {
pos = this.position;
}
var mod = d === "absolute" ? 1 : -1,
scroll = this.cssPosition === "absolute" && !(this.scrollParent[ 0 ] !== document && $.contains(this.scrollParent[ 0 ], this.offsetParent[ 0 ])) ? this.offsetParent : this.scrollParent;
//Cache the scroll
if (!this.offset.scroll) {
this.offset.scroll = {top: scroll.scrollTop(), left: scroll.scrollLeft()};
}
return {
top: (
pos.top + // The absolute mouse position
this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
((this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top) * mod)
),
left: (
pos.left + // The absolute mouse position
this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
((this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left) * mod)
)
};
},
_generatePosition: function(event) {
var containment, co, top, left,
o = this.options,
scroll = this.cssPosition === "absolute" && !(this.scrollParent[ 0 ] !== document && $.contains(this.scrollParent[ 0 ], this.offsetParent[ 0 ])) ? this.offsetParent : this.scrollParent,
pageX = event.pageX,
pageY = event.pageY;
//Cache the scroll
if (!this.offset.scroll) {
this.offset.scroll = {top: scroll.scrollTop(), left: scroll.scrollLeft()};
}
/*
* - Position constraining -
* Constrain the position to a mix of grid, containment.
*/
// If we are not dragging yet, we won't check for options
if (this.originalPosition) {
if (this.containment) {
if (this.relative_container) {
co = this.relative_container.offset();
containment = [
this.containment[ 0 ] + co.left,
this.containment[ 1 ] + co.top,
this.containment[ 2 ] + co.left,
this.containment[ 3 ] + co.top
];
}
else {
containment = this.containment;
}
if (event.pageX - this.offset.click.left < containment[0]) {
pageX = containment[0] + this.offset.click.left;
}
if (event.pageY - this.offset.click.top < containment[1]) {
pageY = containment[1] + this.offset.click.top;
}
if (event.pageX - this.offset.click.left > containment[2]) {
pageX = containment[2] + this.offset.click.left;
}
if (event.pageY - this.offset.click.top > containment[3]) {
pageY = containment[3] + this.offset.click.top;
}
}
if (o.grid) {
//Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950)
top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX;
pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
}
}
return {
top: (
pageY - // The absolute mouse position
this.offset.click.top - // Click offset (relative to the element)
this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
(this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top)
),
left: (
pageX - // The absolute mouse position
this.offset.click.left - // Click offset (relative to the element)
this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
(this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left)
)
};
},
_clear: function() {
this.helper.removeClass("ui-draggable-dragging");
if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
this.helper.remove();
}
this.helper = null;
this.cancelHelperRemoval = false;
},
// From now on bulk stuff - mainly helpers
_trigger: function(type, event, ui) {
ui = ui || this._uiHash();
$.ui.plugin.call(this, type, [event, ui]);
//The absolute position has to be recalculated after plugins
if (type === "drag") {
this.positionAbs = this._convertPositionTo("absolute");
}
return $.Widget.prototype._trigger.call(this, type, event, ui);
},
plugins: {},
_uiHash: function() {
return {
helper: this.helper,
position: this.position,
originalPosition: this.originalPosition,
offset: this.positionAbs
};
}
});
$.ui.plugin.add("draggable", "connectToSortable", {
start: function(event, ui) {
var inst = $(this).data("ui-draggable"), o = inst.options,
uiSortable = $.extend({}, ui, {item: inst.element});
inst.sortables = [];
$(o.connectToSortable).each(function() {
var sortable = $.data(this, "ui-sortable");
if (sortable && !sortable.options.disabled) {
inst.sortables.push({
instance: sortable,
shouldRevert: sortable.options.revert
});
sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page).
sortable._trigger("activate", event, uiSortable);
}
});
},
stop: function(event, ui) {
//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
var inst = $(this).data("ui-draggable"),
uiSortable = $.extend({}, ui, {item: inst.element});
$.each(inst.sortables, function() {
if (this.instance.isOver) {
this.instance.isOver = 0;
inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid"
if (this.shouldRevert) {
this.instance.options.revert = this.shouldRevert;
}
//Trigger the stop of the sortable
this.instance._mouseStop(event);
this.instance.options.helper = this.instance.options._helper;
//If the helper has been the original item, restore properties in the sortable
if (inst.options.helper === "original") {
this.instance.currentItem.css({top: "auto", left: "auto"});
}
} else {
this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
this.instance._trigger("deactivate", event, uiSortable);
}
});
},
drag: function(event, ui) {
var inst = $(this).data("ui-draggable"), that = this;
$.each(inst.sortables, function() {
var innermostIntersecting = false,
thisSortable = this;
//Copy over some variables to allow calling the sortable's native _intersectsWith
this.instance.positionAbs = inst.positionAbs;
this.instance.helperProportions = inst.helperProportions;
this.instance.offset.click = inst.offset.click;
if (this.instance._intersectsWith(this.instance.containerCache)) {
innermostIntersecting = true;
$.each(inst.sortables, function() {
this.instance.positionAbs = inst.positionAbs;
this.instance.helperProportions = inst.helperProportions;
this.instance.offset.click = inst.offset.click;
if (this !== thisSortable &&
this.instance._intersectsWith(this.instance.containerCache) &&
$.contains(thisSortable.instance.element[0], this.instance.element[0])
) {
innermostIntersecting = false;
}
return innermostIntersecting;
});
}
if (innermostIntersecting) {
//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
if (!this.instance.isOver) {
this.instance.isOver = 1;
//Now we fake the start of dragging for the sortable instance,
//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true);
this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
this.instance.options.helper = function() {
return ui.helper[0];
};
event.target = this.instance.currentItem[0];
this.instance._mouseCapture(event, true);
this.instance._mouseStart(event, true, true);
//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
this.instance.offset.click.top = inst.offset.click.top;
this.instance.offset.click.left = inst.offset.click.left;
this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
inst._trigger("toSortable", event);
inst.dropped = this.instance.element; //draggable revert needs that
//hack so receive/update callbacks work (mostly)
inst.currentItem = inst.element;
this.instance.fromOutside = inst;
}
//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
if (this.instance.currentItem) {
this.instance._mouseDrag(event);
}
} else {
//If it doesn't intersect with the sortable, and it intersected before,
//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
if (this.instance.isOver) {
this.instance.isOver = 0;
this.instance.cancelHelperRemoval = true;
//Prevent reverting on this forced stop
this.instance.options.revert = false;
// The out event needs to be triggered independently
this.instance._trigger("out", event, this.instance._uiHash(this.instance));
this.instance._mouseStop(event, true);
this.instance.options.helper = this.instance.options._helper;
//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
this.instance.currentItem.remove();
if (this.instance.placeholder) {
this.instance.placeholder.remove();
}
inst._trigger("fromSortable", event);
inst.dropped = false; //draggable revert needs that
}
}
});
}
});
$.ui.plugin.add("draggable", "cursor", {
start: function() {
var t = $("body"), o = $(this).data("ui-draggable").options;
if (t.css("cursor")) {
o._cursor = t.css("cursor");
}
t.css("cursor", o.cursor);
},
stop: function() {
var o = $(this).data("ui-draggable").options;
if (o._cursor) {
$("body").css("cursor", o._cursor);
}
}
});
$.ui.plugin.add("draggable", "opacity", {
start: function(event, ui) {
var t = $(ui.helper), o = $(this).data("ui-draggable").options;
if (t.css("opacity")) {
o._opacity = t.css("opacity");
}
t.css("opacity", o.opacity);
},
stop: function(event, ui) {
var o = $(this).data("ui-draggable").options;
if (o._opacity) {
$(ui.helper).css("opacity", o._opacity);
}
}
});
$.ui.plugin.add("draggable", "scroll", {
start: function() {
var i = $(this).data("ui-draggable");
if (i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
i.overflowOffset = i.scrollParent.offset();
}
},
drag: function(event) {
var i = $(this).data("ui-draggable"), o = i.options, scrolled = false;
if (i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
if (!o.axis || o.axis !== "x") {
if ((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
} else if (event.pageY - i.overflowOffset.top < o.scrollSensitivity) {
i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
}
}
if (!o.axis || o.axis !== "y") {
if ((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
} else if (event.pageX - i.overflowOffset.left < o.scrollSensitivity) {
i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
}
}
} else {
if (!o.axis || o.axis !== "x") {
if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
} else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
}
}
if (!o.axis || o.axis !== "y") {
if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
} else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
}
}
}
if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
$.ui.ddmanager.prepareOffsets(i, event);
}
}
});
$.ui.plugin.add("draggable", "snap", {
start: function() {
var i = $(this).data("ui-draggable"),
o = i.options;
i.snapElements = [];
$(o.snap.constructor !== String ? (o.snap.items || ":data(ui-draggable)") : o.snap).each(function() {
var $t = $(this),
$o = $t.offset();
if (this !== i.element[0]) {
i.snapElements.push({
item: this,
width: $t.outerWidth(), height: $t.outerHeight(),
top: $o.top, left: $o.left
});
}
});
},
drag: function(event, ui) {
var ts, bs, ls, rs, l, r, t, b, i, first,
inst = $(this).data("ui-draggable"),
o = inst.options,
d = o.snapTolerance,
x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;
for (i = inst.snapElements.length - 1; i >= 0; i--) {
l = inst.snapElements[i].left;
r = l + inst.snapElements[i].width;
t = inst.snapElements[i].top;
b = t + inst.snapElements[i].height;
if (x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains(inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item)) {
if (inst.snapElements[i].snapping) {
(inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), {snapItem: inst.snapElements[i].item})));
}
inst.snapElements[i].snapping = false;
continue;
}
if (o.snapMode !== "inner") {
ts = Math.abs(t - y2) <= d;
bs = Math.abs(b - y1) <= d;
ls = Math.abs(l - x2) <= d;
rs = Math.abs(r - x1) <= d;
if (ts) {
ui.position.top = inst._convertPositionTo("relative", {top: t - inst.helperProportions.height, left: 0}).top - inst.margins.top;
}
if (bs) {
ui.position.top = inst._convertPositionTo("relative", {top: b, left: 0}).top - inst.margins.top;
}
if (ls) {
ui.position.left = inst._convertPositionTo("relative", {top: 0, left: l - inst.helperProportions.width}).left - inst.margins.left;
}
if (rs) {
ui.position.left = inst._convertPositionTo("relative", {top: 0, left: r}).left - inst.margins.left;
}
}
first = (ts || bs || ls || rs);
if (o.snapMode !== "outer") {
ts = Math.abs(t - y1) <= d;
bs = Math.abs(b - y2) <= d;
ls = Math.abs(l - x1) <= d;
rs = Math.abs(r - x2) <= d;
if (ts) {
ui.position.top = inst._convertPositionTo("relative", {top: t, left: 0}).top - inst.margins.top;
}
if (bs) {
ui.position.top = inst._convertPositionTo("relative", {top: b - inst.helperProportions.height, left: 0}).top - inst.margins.top;
}
if (ls) {
ui.position.left = inst._convertPositionTo("relative", {top: 0, left: l}).left - inst.margins.left;
}
if (rs) {
ui.position.left = inst._convertPositionTo("relative", {top: 0, left: r - inst.helperProportions.width}).left - inst.margins.left;
}
}
if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), {snapItem: inst.snapElements[i].item})));
}
inst.snapElements[i].snapping = (ts || bs || ls || rs || first);
}
}
});
$.ui.plugin.add("draggable", "stack", {
start: function() {
var min,
o = this.data("ui-draggable").options,
group = $.makeArray($(o.stack)).sort(function(a, b) {
return (parseInt($(a).css("zIndex"), 10) || 0) - (parseInt($(b).css("zIndex"), 10) || 0);
});
if (!group.length) {
return;
}
min = parseInt($(group[0]).css("zIndex"), 10) || 0;
$(group).each(function(i) {
$(this).css("zIndex", min + i);
});
this.css("zIndex", (min + group.length));
}
});
$.ui.plugin.add("draggable", "zIndex", {
start: function(event, ui) {
var t = $(ui.helper), o = $(this).data("ui-draggable").options;
if (t.css("zIndex")) {
o._zIndex = t.css("zIndex");
}
t.css("zIndex", o.zIndex);
},
stop: function(event, ui) {
var o = $(this).data("ui-draggable").options;
if (o._zIndex) {
$(ui.helper).css("zIndex", o._zIndex);
}
}
});
})(jQuery);
(function($, undefined) {
function isOverAxis(x, reference, size) {
return (x > reference) && (x < (reference + size));
}
$.widget("ui.droppable", {
version: "1.10.3",
widgetEventPrefix: "drop",
options: {
accept: "*",
activeClass: false,
addClasses: true,
greedy: false,
hoverClass: false,
scope: "default",
tolerance: "intersect",
// callbacks
activate: null,
deactivate: null,
drop: null,
out: null,
over: null
},
_create: function() {
var o = this.options,
accept = o.accept;
this.isover = false;
this.isout = true;
this.accept = $.isFunction(accept) ? accept : function(d) {
return d.is(accept);
};
//Store the droppable's proportions
this.proportions = {width: this.element[0].offsetWidth, height: this.element[0].offsetHeight};
// Add the reference and positions to the manager
$.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || [];
$.ui.ddmanager.droppables[o.scope].push(this);
(o.addClasses && this.element.addClass("ui-droppable"));
},
_destroy: function() {
var i = 0,
drop = $.ui.ddmanager.droppables[this.options.scope];
for (; i < drop.length; i++) {
if (drop[i] === this) {
drop.splice(i, 1);
}
}
this.element.removeClass("ui-droppable ui-droppable-disabled");
},
_setOption: function(key, value) {
if (key === "accept") {
this.accept = $.isFunction(value) ? value : function(d) {
return d.is(value);
};
}
$.Widget.prototype._setOption.apply(this, arguments);
},
_activate: function(event) {
var draggable = $.ui.ddmanager.current;
if (this.options.activeClass) {
this.element.addClass(this.options.activeClass);
}
if (draggable) {
this._trigger("activate", event, this.ui(draggable));
}
},
_deactivate: function(event) {
var draggable = $.ui.ddmanager.current;
if (this.options.activeClass) {
this.element.removeClass(this.options.activeClass);
}
if (draggable) {
this._trigger("deactivate", event, this.ui(draggable));
}
},
_over: function(event) {
var draggable = $.ui.ddmanager.current;
// Bail if draggable and droppable are same element
if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
return;
}
if (this.accept.call(this.element[0], (draggable.currentItem || draggable.element))) {
if (this.options.hoverClass) {
this.element.addClass(this.options.hoverClass);
}
this._trigger("over", event, this.ui(draggable));
}
},
_out: function(event) {
var draggable = $.ui.ddmanager.current;
// Bail if draggable and droppable are same element
if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
return;
}
if (this.accept.call(this.element[0], (draggable.currentItem || draggable.element))) {
if (this.options.hoverClass) {
this.element.removeClass(this.options.hoverClass);
}
this._trigger("out", event, this.ui(draggable));
}
},
_drop: function(event, custom) {
var draggable = custom || $.ui.ddmanager.current,
childrenIntersection = false;
// Bail if draggable and droppable are same element
if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
return false;
}
this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function() {
var inst = $.data(this, "ui-droppable");
if (
inst.options.greedy &&
!inst.options.disabled &&
inst.options.scope === draggable.options.scope &&
inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) &&
$.ui.intersect(draggable, $.extend(inst, {offset: inst.element.offset()}), inst.options.tolerance)
) {
childrenIntersection = true;
return false;
}
});
if (childrenIntersection) {
return false;
}
if (this.accept.call(this.element[0], (draggable.currentItem || draggable.element))) {
if (this.options.activeClass) {
this.element.removeClass(this.options.activeClass);
}
if (this.options.hoverClass) {
this.element.removeClass(this.options.hoverClass);
}
this._trigger("drop", event, this.ui(draggable));
return this.element;
}
return false;
},
ui: function(c) {
return {
draggable: (c.currentItem || c.element),
helper: c.helper,
position: c.position,
offset: c.positionAbs
};
}
});
$.ui.intersect = function(draggable, droppable, toleranceMode) {
if (!droppable.offset) {
return false;
}
var draggableLeft, draggableTop,
x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width,
y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height,
l = droppable.offset.left, r = l + droppable.proportions.width,
t = droppable.offset.top, b = t + droppable.proportions.height;
switch (toleranceMode) {
case "fit":
return (l <= x1 && x2 <= r && t <= y1 && y2 <= b);
case "intersect":
return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half
x2 - (draggable.helperProportions.width / 2) < r && // Left Half
t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half
y2 - (draggable.helperProportions.height / 2) < b); // Top Half
case "pointer":
draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left);
draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top);
return isOverAxis(draggableTop, t, droppable.proportions.height) && isOverAxis(draggableLeft, l, droppable.proportions.width);
case "touch":
return (
(y1 >= t && y1 <= b) || // Top edge touching
(y2 >= t && y2 <= b) || // Bottom edge touching
(y1 < t && y2 > b) // Surrounded vertically
) && (
(x1 >= l && x1 <= r) || // Left edge touching
(x2 >= l && x2 <= r) || // Right edge touching
(x1 < l && x2 > r) // Surrounded horizontally
);
default:
return false;
}
};
/*
This manager tracks offsets of draggables and droppables
*/
$.ui.ddmanager = {
current: null,
droppables: {"default": []},
prepareOffsets: function(t, event) {
var i, j,
m = $.ui.ddmanager.droppables[t.options.scope] || [],
type = event ? event.type : null, // workaround for #2317
list = (t.currentItem || t.element).find(":data(ui-droppable)").addBack();
droppablesLoop: for (i = 0; i < m.length; i++) {
//No disabled and non-accepted
if (m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0], (t.currentItem || t.element)))) {
continue;
}
// Filter out elements in the current dragged item
for (j = 0; j < list.length; j++) {
if (list[j] === m[i].element[0]) {
m[i].proportions.height = 0;
continue droppablesLoop;
}
}
m[i].visible = m[i].element.css("display") !== "none";
if (!m[i].visible) {
continue;
}
//Activate the droppable if used directly from draggables
if (type === "mousedown") {
m[i]._activate.call(m[i], event);
}
m[i].offset = m[i].element.offset();
m[i].proportions = {width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight};
}
},
drop: function(draggable, event) {
var dropped = false;
// Create a copy of the droppables in case the list changes during the drop (#9116)
$.each(($.ui.ddmanager.droppables[draggable.options.scope] || []).slice(), function() {
if (!this.options) {
return;
}
if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance)) {
dropped = this._drop.call(this, event) || dropped;
}
if (!this.options.disabled && this.visible && this.accept.call(this.element[0], (draggable.currentItem || draggable.element))) {
this.isout = true;
this.isover = false;
this._deactivate.call(this, event);
}
});
return dropped;
},
dragStart: function(draggable, event) {
//Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003)
draggable.element.parentsUntil("body").bind("scroll.droppable", function() {
if (!draggable.options.refreshPositions) {
$.ui.ddmanager.prepareOffsets(draggable, event);
}
});
},
drag: function(draggable, event) {
//If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
if (draggable.options.refreshPositions) {
$.ui.ddmanager.prepareOffsets(draggable, event);
}
//Run through all droppables and check their positions based on specific tolerance options
$.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() {
if (this.options.disabled || this.greedyChild || !this.visible) {
return;
}
var parentInstance, scope, parent,
intersects = $.ui.intersect(draggable, this, this.options.tolerance),
c = !intersects && this.isover ? "isout" : (intersects && !this.isover ? "isover" : null);
if (!c) {
return;
}
if (this.options.greedy) {
// find droppable parents with same scope
scope = this.options.scope;
parent = this.element.parents(":data(ui-droppable)").filter(function() {
return $.data(this, "ui-droppable").options.scope === scope;
});
if (parent.length) {
parentInstance = $.data(parent[0], "ui-droppable");
parentInstance.greedyChild = (c === "isover");
}
}
// we just moved into a greedy child
if (parentInstance && c === "isover") {
parentInstance.isover = false;
parentInstance.isout = true;
parentInstance._out.call(parentInstance, event);
}
this[c] = true;
this[c === "isout" ? "isover" : "isout"] = false;
this[c === "isover" ? "_over" : "_out"].call(this, event);
// we just moved out of a greedy child
if (parentInstance && c === "isout") {
parentInstance.isout = false;
parentInstance.isover = true;
parentInstance._over.call(parentInstance, event);
}
});
},
dragStop: function(draggable, event) {
draggable.element.parentsUntil("body").unbind("scroll.droppable");
//Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003)
if (!draggable.options.refreshPositions) {
$.ui.ddmanager.prepareOffsets(draggable, event);
}
}
};
})(jQuery);
(function($, undefined) {
function num(v) {
return parseInt(v, 10) || 0;
}
function isNumber(value) {
return !isNaN(parseInt(value, 10));
}
$.widget("ui.resizable", $.ui.mouse, {
version: "1.10.3",
widgetEventPrefix: "resize",
options: {
alsoResize: false,
animate: false,
animateDuration: "slow",
animateEasing: "swing",
aspectRatio: false,
autoHide: false,
containment: false,
ghost: false,
grid: false,
handles: "e,s,se",
helper: false,
maxHeight: null,
maxWidth: null,
minHeight: 10,
minWidth: 10,
// See #7960
zIndex: 90,
// callbacks
resize: null,
start: null,
stop: null
},
_create: function() {
var n, i, handle, axis, hname,
that = this,
o = this.options;
this.element.addClass("ui-resizable");
$.extend(this, {
_aspectRatio: !!(o.aspectRatio),
aspectRatio: o.aspectRatio,
originalElement: this.element,
_proportionallyResizeElements: [],
_helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
});
//Wrap the element if it cannot hold child nodes
if (this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) {
//Create a wrapper element and set the wrapper to the new current internal element
this.element.wrap(
$("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({
position: this.element.css("position"),
width: this.element.outerWidth(),
height: this.element.outerHeight(),
top: this.element.css("top"),
left: this.element.css("left")
})
);
//Overwrite the original this.element
this.element = this.element.parent().data(
"ui-resizable", this.element.data("ui-resizable")
);
this.elementIsWrapper = true;
//Move margins to the wrapper
this.element.css({marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom")});
this.originalElement.css({marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});
//Prevent Safari textarea resize
this.originalResizeStyle = this.originalElement.css("resize");
this.originalElement.css("resize", "none");
//Push the actual element to our proportionallyResize internal array
this._proportionallyResizeElements.push(this.originalElement.css({position: "static", zoom: 1, display: "block"}));
// avoid IE jump (hard set the margin)
this.originalElement.css({margin: this.originalElement.css("margin")});
// fix handlers offset
this._proportionallyResize();
}
this.handles = o.handles || (!$(".ui-resizable-handle", this.element).length ? "e,s,se" : {n: ".ui-resizable-n", e: ".ui-resizable-e", s: ".ui-resizable-s", w: ".ui-resizable-w", se: ".ui-resizable-se", sw: ".ui-resizable-sw", ne: ".ui-resizable-ne", nw: ".ui-resizable-nw"});
if (this.handles.constructor === String) {
if (this.handles === "all") {
this.handles = "n,e,s,w,se,sw,ne,nw";
}
n = this.handles.split(",");
this.handles = {};
for (i = 0; i < n.length; i++) {
handle = $.trim(n[i]);
hname = "ui-resizable-" + handle;
axis = $("<div class='ui-resizable-handle " + hname + "'></div>");
// Apply zIndex to all handles - see #7960
axis.css({zIndex: o.zIndex});
//TODO : What's going on here?
if ("se" === handle) {
axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se");
}
//Insert into internal handles object and append to element
this.handles[handle] = ".ui-resizable-" + handle;
this.element.append(axis);
}
}
this._renderAxis = function(target) {
var i, axis, padPos, padWrapper;
target = target || this.element;
for (i in this.handles) {
if (this.handles[i].constructor === String) {
this.handles[i] = $(this.handles[i], this.element).show();
}
//Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {
axis = $(this.handles[i], this.element);
//Checking the correct pad and border
padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();
//The padding type i have to apply...
padPos = ["padding",
/ne|nw|n/.test(i) ? "Top" :
/se|sw|s/.test(i) ? "Bottom" :
/^e$/.test(i) ? "Right" : "Left"].join("");
target.css(padPos, padWrapper);
this._proportionallyResize();
}
//TODO: What's that good for? There's not anything to be executed left
if (!$(this.handles[i]).length) {
continue;
}
}
};
//TODO: make renderAxis a prototype function
this._renderAxis(this.element);
this._handles = $(".ui-resizable-handle", this.element)
.disableSelection();
//Matching axis name
this._handles.mouseover(function() {
if (!that.resizing) {
if (this.className) {
axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
}
//Axis, default = se
that.axis = axis && axis[1] ? axis[1] : "se";
}
});
//If we want to auto hide the elements
if (o.autoHide) {
this._handles.hide();
$(this.element)
.addClass("ui-resizable-autohide")
.mouseenter(function() {
if (o.disabled) {
return;
}
$(this).removeClass("ui-resizable-autohide");
that._handles.show();
})
.mouseleave(function() {
if (o.disabled) {
return;
}
if (!that.resizing) {
$(this).addClass("ui-resizable-autohide");
that._handles.hide();
}
});
}
//Initialize the mouse interaction
this._mouseInit();
},
_destroy: function() {
this._mouseDestroy();
var wrapper,
_destroy = function(exp) {
$(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
.removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove();
};
//TODO: Unwrap at same DOM position
if (this.elementIsWrapper) {
_destroy(this.element);
wrapper = this.element;
this.originalElement.css({
position: wrapper.css("position"),
width: wrapper.outerWidth(),
height: wrapper.outerHeight(),
top: wrapper.css("top"),
left: wrapper.css("left")
}).insertAfter(wrapper);
wrapper.remove();
}
this.originalElement.css("resize", this.originalResizeStyle);
_destroy(this.originalElement);
return this;
},
_mouseCapture: function(event) {
var i, handle,
capture = false;
for (i in this.handles) {
handle = $(this.handles[i])[0];
if (handle === event.target || $.contains(handle, event.target)) {
capture = true;
}
}
return !this.options.disabled && capture;
},
_mouseStart: function(event) {
var curleft, curtop, cursor,
o = this.options,
iniPos = this.element.position(),
el = this.element;
this.resizing = true;
// bugfix for http://dev.jquery.com/ticket/1749
if ((/absolute/).test(el.css("position"))) {
el.css({position: "absolute", top: el.css("top"), left: el.css("left")});
} else if (el.is(".ui-draggable")) {
el.css({position: "absolute", top: iniPos.top, left: iniPos.left});
}
this._renderProxy();
curleft = num(this.helper.css("left"));
curtop = num(this.helper.css("top"));
if (o.containment) {
curleft += $(o.containment).scrollLeft() || 0;
curtop += $(o.containment).scrollTop() || 0;
}
//Store needed variables
this.offset = this.helper.offset();
this.position = {left: curleft, top: curtop};
this.size = this._helper ? {width: el.outerWidth(), height: el.outerHeight()} : {width: el.width(), height: el.height()};
this.originalSize = this._helper ? {width: el.outerWidth(), height: el.outerHeight()} : {width: el.width(), height: el.height()};
this.originalPosition = {left: curleft, top: curtop};
this.sizeDiff = {width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height()};
this.originalMousePosition = {left: event.pageX, top: event.pageY};
//Aspect Ratio
this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1);
cursor = $(".ui-resizable-" + this.axis).css("cursor");
$("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor);
el.addClass("ui-resizable-resizing");
this._propagate("start", event);
return true;
},
_mouseDrag: function(event) {
//Increase performance, avoid regex
var data,
el = this.helper, props = {},
smp = this.originalMousePosition,
a = this.axis,
prevTop = this.position.top,
prevLeft = this.position.left,
prevWidth = this.size.width,
prevHeight = this.size.height,
dx = (event.pageX - smp.left) || 0,
dy = (event.pageY - smp.top) || 0,
trigger = this._change[a];
if (!trigger) {
return false;
}
// Calculate the attrs that will be change
data = trigger.apply(this, [event, dx, dy]);
// Put this in the mouseDrag handler since the user can start pressing shift while resizing
this._updateVirtualBoundaries(event.shiftKey);
if (this._aspectRatio || event.shiftKey) {
data = this._updateRatio(data, event);
}
data = this._respectSize(data, event);
this._updateCache(data);
// plugins callbacks need to be called first
this._propagate("resize", event);
if (this.position.top !== prevTop) {
props.top = this.position.top + "px";
}
if (this.position.left !== prevLeft) {
props.left = this.position.left + "px";
}
if (this.size.width !== prevWidth) {
props.width = this.size.width + "px";
}
if (this.size.height !== prevHeight) {
props.height = this.size.height + "px";
}
el.css(props);
if (!this._helper && this._proportionallyResizeElements.length) {
this._proportionallyResize();
}
// Call the user callback if the element was resized
if (!$.isEmptyObject(props)) {
this._trigger("resize", event, this.ui());
}
return false;
},
_mouseStop: function(event) {
this.resizing = false;
var pr, ista, soffseth, soffsetw, s, left, top,
o = this.options, that = this;
if (this._helper) {
pr = this._proportionallyResizeElements;
ista = pr.length && (/textarea/i).test(pr[0].nodeName);
soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height;
soffsetw = ista ? 0 : that.sizeDiff.width;
s = {width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth)};
left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null;
top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null;
if (!o.animate) {
this.element.css($.extend(s, {top: top, left: left}));
}
that.helper.height(that.size.height);
that.helper.width(that.size.width);
if (this._helper && !o.animate) {
this._proportionallyResize();
}
}
$("body").css("cursor", "auto");
this.element.removeClass("ui-resizable-resizing");
this._propagate("stop", event);
if (this._helper) {
this.helper.remove();
}
return false;
},
_updateVirtualBoundaries: function(forceAspectRatio) {
var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
o = this.options;
b = {
minWidth: isNumber(o.minWidth) ? o.minWidth : 0,
maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity,
minHeight: isNumber(o.minHeight) ? o.minHeight : 0,
maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity
};
if (this._aspectRatio || forceAspectRatio) {
// We want to create an enclosing box whose aspect ration is the requested one
// First, compute the "projected" size for each dimension based on the aspect ratio and other dimension
pMinWidth = b.minHeight * this.aspectRatio;
pMinHeight = b.minWidth / this.aspectRatio;
pMaxWidth = b.maxHeight * this.aspectRatio;
pMaxHeight = b.maxWidth / this.aspectRatio;
if (pMinWidth > b.minWidth) {
b.minWidth = pMinWidth;
}
if (pMinHeight > b.minHeight) {
b.minHeight = pMinHeight;
}
if (pMaxWidth < b.maxWidth) {
b.maxWidth = pMaxWidth;
}
if (pMaxHeight < b.maxHeight) {
b.maxHeight = pMaxHeight;
}
}
this._vBoundaries = b;
},
_updateCache: function(data) {
this.offset = this.helper.offset();
if (isNumber(data.left)) {
this.position.left = data.left;
}
if (isNumber(data.top)) {
this.position.top = data.top;
}
if (isNumber(data.height)) {
this.size.height = data.height;
}
if (isNumber(data.width)) {
this.size.width = data.width;
}
},
_updateRatio: function(data) {
var cpos = this.position,
csize = this.size,
a = this.axis;
if (isNumber(data.height)) {
data.width = (data.height * this.aspectRatio);
} else if (isNumber(data.width)) {
data.height = (data.width / this.aspectRatio);
}
if (a === "sw") {
data.left = cpos.left + (csize.width - data.width);
data.top = null;
}
if (a === "nw") {
data.top = cpos.top + (csize.height - data.height);
data.left = cpos.left + (csize.width - data.width);
}
return data;
},
_respectSize: function(data) {
var o = this._vBoundaries,
a = this.axis,
ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height),
dw = this.originalPosition.left + this.originalSize.width,
dh = this.position.top + this.size.height,
cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);
if (isminw) {
data.width = o.minWidth;
}
if (isminh) {
data.height = o.minHeight;
}
if (ismaxw) {
data.width = o.maxWidth;
}
if (ismaxh) {
data.height = o.maxHeight;
}
if (isminw && cw) {
data.left = dw - o.minWidth;
}
if (ismaxw && cw) {
data.left = dw - o.maxWidth;
}
if (isminh && ch) {
data.top = dh - o.minHeight;
}
if (ismaxh && ch) {
data.top = dh - o.maxHeight;
}
// fixing jump error on top/left - bug #2330
if (!data.width && !data.height && !data.left && data.top) {
data.top = null;
} else if (!data.width && !data.height && !data.top && data.left) {
data.left = null;
}
return data;
},
_proportionallyResize: function() {
if (!this._proportionallyResizeElements.length) {
return;
}
var i, j, borders, paddings, prel,
element = this.helper || this.element;
for (i = 0; i < this._proportionallyResizeElements.length; i++) {
prel = this._proportionallyResizeElements[i];
if (!this.borderDif) {
this.borderDif = [];
borders = [prel.css("borderTopWidth"), prel.css("borderRightWidth"), prel.css("borderBottomWidth"), prel.css("borderLeftWidth")];
paddings = [prel.css("paddingTop"), prel.css("paddingRight"), prel.css("paddingBottom"), prel.css("paddingLeft")];
for (j = 0; j < borders.length; j++) {
this.borderDif[ j ] = (parseInt(borders[ j ], 10) || 0) + (parseInt(paddings[ j ], 10) || 0);
}
}
prel.css({
height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0,
width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0
});
}
},
_renderProxy: function() {
var el = this.element, o = this.options;
this.elementOffset = el.offset();
if (this._helper) {
this.helper = this.helper || $("<div style='overflow:hidden;'></div>");
this.helper.addClass(this._helper).css({
width: this.element.outerWidth() - 1,
height: this.element.outerHeight() - 1,
position: "absolute",
left: this.elementOffset.left + "px",
top: this.elementOffset.top + "px",
zIndex: ++o.zIndex //TODO: Don't modify option
});
this.helper
.appendTo("body")
.disableSelection();
} else {
this.helper = this.element;
}
},
_change: {
e: function(event, dx) {
return {width: this.originalSize.width + dx};
},
w: function(event, dx) {
var cs = this.originalSize, sp = this.originalPosition;
return {left: sp.left + dx, width: cs.width - dx};
},
n: function(event, dx, dy) {
var cs = this.originalSize, sp = this.originalPosition;
return {top: sp.top + dy, height: cs.height - dy};
},
s: function(event, dx, dy) {
return {height: this.originalSize.height + dy};
},
se: function(event, dx, dy) {
return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
},
sw: function(event, dx, dy) {
return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
},
ne: function(event, dx, dy) {
return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
},
nw: function(event, dx, dy) {
return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
}
},
_propagate: function(n, event) {
$.ui.plugin.call(this, n, [event, this.ui()]);
(n !== "resize" && this._trigger(n, event, this.ui()));
},
plugins: {},
ui: function() {
return {
originalElement: this.originalElement,
element: this.element,
helper: this.helper,
position: this.position,
size: this.size,
originalSize: this.originalSize,
originalPosition: this.originalPosition
};
}
});
/*
* Resizable Extensions
*/
$.ui.plugin.add("resizable", "animate", {
stop: function(event) {
var that = $(this).data("ui-resizable"),
o = that.options,
pr = that._proportionallyResizeElements,
ista = pr.length && (/textarea/i).test(pr[0].nodeName),
soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height,
soffsetw = ista ? 0 : that.sizeDiff.width,
style = {width: (that.size.width - soffsetw), height: (that.size.height - soffseth)},
left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null,
top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null;
that.element.animate(
$.extend(style, top && left ? {top: top, left: left} : {}), {
duration: o.animateDuration,
easing: o.animateEasing,
step: function() {
var data = {
width: parseInt(that.element.css("width"), 10),
height: parseInt(that.element.css("height"), 10),
top: parseInt(that.element.css("top"), 10),
left: parseInt(that.element.css("left"), 10)
};
if (pr && pr.length) {
$(pr[0]).css({width: data.width, height: data.height});
}
// propagating resize, and updating values for each animation step
that._updateCache(data);
that._propagate("resize", event);
}
}
);
}
});
$.ui.plugin.add("resizable", "containment", {
start: function() {
var element, p, co, ch, cw, width, height,
that = $(this).data("ui-resizable"),
o = that.options,
el = that.element,
oc = o.containment,
ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
if (!ce) {
return;
}
that.containerElement = $(ce);
if (/document/.test(oc) || oc === document) {
that.containerOffset = {left: 0, top: 0};
that.containerPosition = {left: 0, top: 0};
that.parentData = {
element: $(document), left: 0, top: 0,
width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
};
}
// i'm a node, so compute top, left, right, bottom
else {
element = $(ce);
p = [];
$(["Top", "Right", "Left", "Bottom"]).each(function(i, name) {
p[i] = num(element.css("padding" + name));
});
that.containerOffset = element.offset();
that.containerPosition = element.position();
that.containerSize = {height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1])};
co = that.containerOffset;
ch = that.containerSize.height;
cw = that.containerSize.width;
width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw);
height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);
that.parentData = {
element: ce, left: co.left, top: co.top, width: width, height: height
};
}
},
resize: function(event) {
var woset, hoset, isParent, isOffsetRelative,
that = $(this).data("ui-resizable"),
o = that.options,
co = that.containerOffset, cp = that.position,
pRatio = that._aspectRatio || event.shiftKey,
cop = {top: 0, left: 0}, ce = that.containerElement;
if (ce[0] !== document && (/static/).test(ce.css("position"))) {
cop = co;
}
if (cp.left < (that._helper ? co.left : 0)) {
that.size.width = that.size.width + (that._helper ? (that.position.left - co.left) : (that.position.left - cop.left));
if (pRatio) {
that.size.height = that.size.width / that.aspectRatio;
}
that.position.left = o.helper ? co.left : 0;
}
if (cp.top < (that._helper ? co.top : 0)) {
that.size.height = that.size.height + (that._helper ? (that.position.top - co.top) : that.position.top);
if (pRatio) {
that.size.width = that.size.height * that.aspectRatio;
}
that.position.top = that._helper ? co.top : 0;
}
that.offset.left = that.parentData.left + that.position.left;
that.offset.top = that.parentData.top + that.position.top;
woset = Math.abs((that._helper ? that.offset.left - cop.left : (that.offset.left - cop.left)) + that.sizeDiff.width);
hoset = Math.abs((that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) + that.sizeDiff.height);
isParent = that.containerElement.get(0) === that.element.parent().get(0);
isOffsetRelative = /relative|absolute/.test(that.containerElement.css("position"));
if (isParent && isOffsetRelative) {
woset -= that.parentData.left;
}
if (woset + that.size.width >= that.parentData.width) {
that.size.width = that.parentData.width - woset;
if (pRatio) {
that.size.height = that.size.width / that.aspectRatio;
}
}
if (hoset + that.size.height >= that.parentData.height) {
that.size.height = that.parentData.height - hoset;
if (pRatio) {
that.size.width = that.size.height * that.aspectRatio;
}
}
},
stop: function() {
var that = $(this).data("ui-resizable"),
o = that.options,
co = that.containerOffset,
cop = that.containerPosition,
ce = that.containerElement,
helper = $(that.helper),
ho = helper.offset(),
w = helper.outerWidth() - that.sizeDiff.width,
h = helper.outerHeight() - that.sizeDiff.height;
if (that._helper && !o.animate && (/relative/).test(ce.css("position"))) {
$(this).css({left: ho.left - cop.left - co.left, width: w, height: h});
}
if (that._helper && !o.animate && (/static/).test(ce.css("position"))) {
$(this).css({left: ho.left - cop.left - co.left, width: w, height: h});
}
}
});
$.ui.plugin.add("resizable", "alsoResize", {
start: function() {
var that = $(this).data("ui-resizable"),
o = that.options,
_store = function(exp) {
$(exp).each(function() {
var el = $(this);
el.data("ui-resizable-alsoresize", {
width: parseInt(el.width(), 10), height: parseInt(el.height(), 10),
left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10)
});
});
};
if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) {
if (o.alsoResize.length) {
o.alsoResize = o.alsoResize[0];
_store(o.alsoResize);
}
else {
$.each(o.alsoResize, function(exp) {
_store(exp);
});
}
} else {
_store(o.alsoResize);
}
},
resize: function(event, ui) {
var that = $(this).data("ui-resizable"),
o = that.options,
os = that.originalSize,
op = that.originalPosition,
delta = {
height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0,
top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0
},
_alsoResize = function(exp, c) {
$(exp).each(function() {
var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {},
css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"];
$.each(css, function(i, prop) {
var sum = (start[prop] || 0) + (delta[prop] || 0);
if (sum && sum >= 0) {
style[prop] = sum || null;
}
});
el.css(style);
});
};
if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) {
$.each(o.alsoResize, function(exp, c) {
_alsoResize(exp, c);
});
} else {
_alsoResize(o.alsoResize);
}
},
stop: function() {
$(this).removeData("resizable-alsoresize");
}
});
$.ui.plugin.add("resizable", "ghost", {
start: function() {
var that = $(this).data("ui-resizable"), o = that.options, cs = that.size;
that.ghost = that.originalElement.clone();
that.ghost
.css({opacity: 0.25, display: "block", position: "relative", height: cs.height, width: cs.width, margin: 0, left: 0, top: 0})
.addClass("ui-resizable-ghost")
.addClass(typeof o.ghost === "string" ? o.ghost : "");
that.ghost.appendTo(that.helper);
},
resize: function() {
var that = $(this).data("ui-resizable");
if (that.ghost) {
that.ghost.css({position: "relative", height: that.size.height, width: that.size.width});
}
},
stop: function() {
var that = $(this).data("ui-resizable");
if (that.ghost && that.helper) {
that.helper.get(0).removeChild(that.ghost.get(0));
}
}
});
$.ui.plugin.add("resizable", "grid", {
resize: function() {
var that = $(this).data("ui-resizable"),
o = that.options,
cs = that.size,
os = that.originalSize,
op = that.originalPosition,
a = that.axis,
grid = typeof o.grid === "number" ? [o.grid, o.grid] : o.grid,
gridX = (grid[0] || 1),
gridY = (grid[1] || 1),
ox = Math.round((cs.width - os.width) / gridX) * gridX,
oy = Math.round((cs.height - os.height) / gridY) * gridY,
newWidth = os.width + ox,
newHeight = os.height + oy,
isMaxWidth = o.maxWidth && (o.maxWidth < newWidth),
isMaxHeight = o.maxHeight && (o.maxHeight < newHeight),
isMinWidth = o.minWidth && (o.minWidth > newWidth),
isMinHeight = o.minHeight && (o.minHeight > newHeight);
o.grid = grid;
if (isMinWidth) {
newWidth = newWidth + gridX;
}
if (isMinHeight) {
newHeight = newHeight + gridY;
}
if (isMaxWidth) {
newWidth = newWidth - gridX;
}
if (isMaxHeight) {
newHeight = newHeight - gridY;
}
if (/^(se|s|e)$/.test(a)) {
that.size.width = newWidth;
that.size.height = newHeight;
} else if (/^(ne)$/.test(a)) {
that.size.width = newWidth;
that.size.height = newHeight;
that.position.top = op.top - oy;
} else if (/^(sw)$/.test(a)) {
that.size.width = newWidth;
that.size.height = newHeight;
that.position.left = op.left - ox;
} else {
that.size.width = newWidth;
that.size.height = newHeight;
that.position.top = op.top - oy;
that.position.left = op.left - ox;
}
}
});
})(jQuery);
(function($, undefined) {
$.widget("ui.selectable", $.ui.mouse, {
version: "1.10.3",
options: {
appendTo: "body",
autoRefresh: true,
distance: 0,
filter: "*",
tolerance: "touch",
// callbacks
selected: null,
selecting: null,
start: null,
stop: null,
unselected: null,
unselecting: null
},
_create: function() {
var selectees,
that = this;
this.element.addClass("ui-selectable");
this.dragged = false;
// cache selectee children based on filter
this.refresh = function() {
selectees = $(that.options.filter, that.element[0]);
selectees.addClass("ui-selectee");
selectees.each(function() {
var $this = $(this),
pos = $this.offset();
$.data(this, "selectable-item", {
element: this,
$element: $this,
left: pos.left,
top: pos.top,
right: pos.left + $this.outerWidth(),
bottom: pos.top + $this.outerHeight(),
startselected: false,
selected: $this.hasClass("ui-selected"),
selecting: $this.hasClass("ui-selecting"),
unselecting: $this.hasClass("ui-unselecting")
});
});
};
this.refresh();
this.selectees = selectees.addClass("ui-selectee");
this._mouseInit();
this.helper = $("<div class='ui-selectable-helper'></div>");
},
_destroy: function() {
this.selectees
.removeClass("ui-selectee")
.removeData("selectable-item");
this.element
.removeClass("ui-selectable ui-selectable-disabled");
this._mouseDestroy();
},
_mouseStart: function(event) {
var that = this,
options = this.options;
this.opos = [event.pageX, event.pageY];
if (this.options.disabled) {
return;
}
this.selectees = $(options.filter, this.element[0]);
this._trigger("start", event);
$(options.appendTo).append(this.helper);
// position helper (lasso)
this.helper.css({
"left": event.pageX,
"top": event.pageY,
"width": 0,
"height": 0
});
if (options.autoRefresh) {
this.refresh();
}
this.selectees.filter(".ui-selected").each(function() {
var selectee = $.data(this, "selectable-item");
selectee.startselected = true;
if (!event.metaKey && !event.ctrlKey) {
selectee.$element.removeClass("ui-selected");
selectee.selected = false;
selectee.$element.addClass("ui-unselecting");
selectee.unselecting = true;
// selectable UNSELECTING callback
that._trigger("unselecting", event, {
unselecting: selectee.element
});
}
});
$(event.target).parents().addBack().each(function() {
var doSelect,
selectee = $.data(this, "selectable-item");
if (selectee) {
doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected");
selectee.$element
.removeClass(doSelect ? "ui-unselecting" : "ui-selected")
.addClass(doSelect ? "ui-selecting" : "ui-unselecting");
selectee.unselecting = !doSelect;
selectee.selecting = doSelect;
selectee.selected = doSelect;
// selectable (UN)SELECTING callback
if (doSelect) {
that._trigger("selecting", event, {
selecting: selectee.element
});
} else {
that._trigger("unselecting", event, {
unselecting: selectee.element
});
}
return false;
}
});
},
_mouseDrag: function(event) {
this.dragged = true;
if (this.options.disabled) {
return;
}
var tmp,
that = this,
options = this.options,
x1 = this.opos[0],
y1 = this.opos[1],
x2 = event.pageX,
y2 = event.pageY;
if (x1 > x2) {
tmp = x2;
x2 = x1;
x1 = tmp;
}
if (y1 > y2) {
tmp = y2;
y2 = y1;
y1 = tmp;
}
this.helper.css({left: x1, top: y1, width: x2 - x1, height: y2 - y1});
this.selectees.each(function() {
var selectee = $.data(this, "selectable-item"),
hit = false;
//prevent helper from being selected if appendTo: selectable
if (!selectee || selectee.element === that.element[0]) {
return;
}
if (options.tolerance === "touch") {
hit = (!(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1));
} else if (options.tolerance === "fit") {
hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
}
if (hit) {
// SELECT
if (selectee.selected) {
selectee.$element.removeClass("ui-selected");
selectee.selected = false;
}
if (selectee.unselecting) {
selectee.$element.removeClass("ui-unselecting");
selectee.unselecting = false;
}
if (!selectee.selecting) {
selectee.$element.addClass("ui-selecting");
selectee.selecting = true;
// selectable SELECTING callback
that._trigger("selecting", event, {
selecting: selectee.element
});
}
} else {
// UNSELECT
if (selectee.selecting) {
if ((event.metaKey || event.ctrlKey) && selectee.startselected) {
selectee.$element.removeClass("ui-selecting");
selectee.selecting = false;
selectee.$element.addClass("ui-selected");
selectee.selected = true;
} else {
selectee.$element.removeClass("ui-selecting");
selectee.selecting = false;
if (selectee.startselected) {
selectee.$element.addClass("ui-unselecting");
selectee.unselecting = true;
}
// selectable UNSELECTING callback
that._trigger("unselecting", event, {
unselecting: selectee.element
});
}
}
if (selectee.selected) {
if (!event.metaKey && !event.ctrlKey && !selectee.startselected) {
selectee.$element.removeClass("ui-selected");
selectee.selected = false;
selectee.$element.addClass("ui-unselecting");
selectee.unselecting = true;
// selectable UNSELECTING callback
that._trigger("unselecting", event, {
unselecting: selectee.element
});
}
}
}
});
return false;
},
_mouseStop: function(event) {
var that = this;
this.dragged = false;
$(".ui-unselecting", this.element[0]).each(function() {
var selectee = $.data(this, "selectable-item");
selectee.$element.removeClass("ui-unselecting");
selectee.unselecting = false;
selectee.startselected = false;
that._trigger("unselected", event, {
unselected: selectee.element
});
});
$(".ui-selecting", this.element[0]).each(function() {
var selectee = $.data(this, "selectable-item");
selectee.$element.removeClass("ui-selecting").addClass("ui-selected");
selectee.selecting = false;
selectee.selected = true;
selectee.startselected = true;
that._trigger("selected", event, {
selected: selectee.element
});
});
this._trigger("stop", event);
this.helper.remove();
return false;
}
});
})(jQuery);
(function($, undefined) {
/*jshint loopfunc: true */
function isOverAxis(x, reference, size) {
return (x > reference) && (x < (reference + size));
}
function isFloating(item) {
return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display"));
}
$.widget("ui.sortable", $.ui.mouse, {
version: "1.10.3",
widgetEventPrefix: "sort",
ready: false,
options: {
appendTo: "parent",
axis: false,
connectWith: false,
containment: false,
cursor: "auto",
cursorAt: false,
dropOnEmpty: true,
forcePlaceholderSize: false,
forceHelperSize: false,
grid: false,
handle: false,
helper: "original",
items: "> *",
opacity: false,
placeholder: false,
revert: false,
scroll: true,
scrollSensitivity: 20,
scrollSpeed: 20,
scope: "default",
tolerance: "intersect",
zIndex: 1000,
// callbacks
activate: null,
beforeStop: null,
change: null,
deactivate: null,
out: null,
over: null,
receive: null,
remove: null,
sort: null,
start: null,
stop: null,
update: null
},
_create: function() {
var o = this.options;
this.containerCache = {};
this.element.addClass("ui-sortable");
//Get the items
this.refresh();
//Let's determine if the items are being displayed horizontally
this.floating = this.items.length ? o.axis === "x" || isFloating(this.items[0].item) : false;
//Let's determine the parent's offset
this.offset = this.element.offset();
//Initialize mouse events for interaction
this._mouseInit();
//We're ready to go
this.ready = true;
},
_destroy: function() {
this.element
.removeClass("ui-sortable ui-sortable-disabled");
this._mouseDestroy();
for (var i = this.items.length - 1; i >= 0; i--) {
this.items[i].item.removeData(this.widgetName + "-item");
}
return this;
},
_setOption: function(key, value) {
if (key === "disabled") {
this.options[ key ] = value;
this.widget().toggleClass("ui-sortable-disabled", !!value);
} else {
// Don't call widget base _setOption for disable as it adds ui-state-disabled class
$.Widget.prototype._setOption.apply(this, arguments);
}
},
_mouseCapture: function(event, overrideHandle) {
var currentItem = null,
validHandle = false,
that = this;
if (this.reverting) {
return false;
}
if (this.options.disabled || this.options.type === "static") {
return false;
}
//We have to refresh the items data once first
this._refreshItems(event);
//Find out if the clicked node (or one of its parents) is a actual item in this.items
$(event.target).parents().each(function() {
if ($.data(this, that.widgetName + "-item") === that) {
currentItem = $(this);
return false;
}
});
if ($.data(event.target, that.widgetName + "-item") === that) {
currentItem = $(event.target);
}
if (!currentItem) {
return false;
}
if (this.options.handle && !overrideHandle) {
$(this.options.handle, currentItem).find("*").addBack().each(function() {
if (this === event.target) {
validHandle = true;
}
});
if (!validHandle) {
return false;
}
}
this.currentItem = currentItem;
this._removeCurrentsFromItems();
return true;
},
_mouseStart: function(event, overrideHandle, noActivation) {
var i, body,
o = this.options;
this.currentContainer = this;
//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
this.refreshPositions();
//Create and append the visible helper
this.helper = this._createHelper(event);
//Cache the helper size
this._cacheHelperProportions();
/*
* - Position generation -
* This block generates everything position related - it's the core of draggables.
*/
//Cache the margins of the original element
this._cacheMargins();
//Get the next scrolling parent
this.scrollParent = this.helper.scrollParent();
//The element's absolute position on the page minus margins
this.offset = this.currentItem.offset();
this.offset = {
top: this.offset.top - this.margins.top,
left: this.offset.left - this.margins.left
};
$.extend(this.offset, {
click: {//Where the click happened, relative to the element
left: event.pageX - this.offset.left,
top: event.pageY - this.offset.top
},
parent: this._getParentOffset(),
relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
});
// Only after we got the offset, we can change the helper's position to absolute
// TODO: Still need to figure out a way to make relative sorting possible
this.helper.css("position", "absolute");
this.cssPosition = this.helper.css("position");
//Generate the original position
this.originalPosition = this._generatePosition(event);
this.originalPageX = event.pageX;
this.originalPageY = event.pageY;
//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
//Cache the former DOM position
this.domPosition = {prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0]};
//If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
if (this.helper[0] !== this.currentItem[0]) {
this.currentItem.hide();
}
//Create the placeholder
this._createPlaceholder();
//Set a containment if given in the options
if (o.containment) {
this._setContainment();
}
if (o.cursor && o.cursor !== "auto") { // cursor option
body = this.document.find("body");
// support: IE
this.storedCursor = body.css("cursor");
body.css("cursor", o.cursor);
this.storedStylesheet = $("<style>*{ cursor: " + o.cursor + " !important; }</style>").appendTo(body);
}
if (o.opacity) { // opacity option
if (this.helper.css("opacity")) {
this._storedOpacity = this.helper.css("opacity");
}
this.helper.css("opacity", o.opacity);
}
if (o.zIndex) { // zIndex option
if (this.helper.css("zIndex")) {
this._storedZIndex = this.helper.css("zIndex");
}
this.helper.css("zIndex", o.zIndex);
}
//Prepare scrolling
if (this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
this.overflowOffset = this.scrollParent.offset();
}
//Call callbacks
this._trigger("start", event, this._uiHash());
//Recache the helper size
if (!this._preserveHelperProportions) {
this._cacheHelperProportions();
}
//Post "activate" events to possible containers
if (!noActivation) {
for (i = this.containers.length - 1; i >= 0; i--) {
this.containers[ i ]._trigger("activate", event, this._uiHash(this));
}
}
//Prepare possible droppables
if ($.ui.ddmanager) {
$.ui.ddmanager.current = this;
}
if ($.ui.ddmanager && !o.dropBehaviour) {
$.ui.ddmanager.prepareOffsets(this, event);
}
this.dragging = true;
this.helper.addClass("ui-sortable-helper");
this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
return true;
},
_mouseDrag: function(event) {
var i, item, itemElement, intersection,
o = this.options,
scrolled = false;
//Compute the helpers position
this.position = this._generatePosition(event);
this.positionAbs = this._convertPositionTo("absolute");
if (!this.lastPositionAbs) {
this.lastPositionAbs = this.positionAbs;
}
//Do scrolling
if (this.options.scroll) {
if (this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
if ((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
} else if (event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
}
if ((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
} else if (event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
}
} else {
if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
} else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
}
if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
} else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
}
}
if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
$.ui.ddmanager.prepareOffsets(this, event);
}
}
//Regenerate the absolute position used for position checks
this.positionAbs = this._convertPositionTo("absolute");
//Set the helper position
if (!this.options.axis || this.options.axis !== "y") {
this.helper[0].style.left = this.position.left + "px";
}
if (!this.options.axis || this.options.axis !== "x") {
this.helper[0].style.top = this.position.top + "px";
}
//Rearrange
for (i = this.items.length - 1; i >= 0; i--) {
//Cache variables and intersection, continue if no intersection
item = this.items[i];
itemElement = item.item[0];
intersection = this._intersectsWithPointer(item);
if (!intersection) {
continue;
}
// Only put the placeholder inside the current Container, skip all
// items form other containers. This works because when moving
// an item from one container to another the
// currentContainer is switched before the placeholder is moved.
//
// Without this moving items in "sub-sortables" can cause the placeholder to jitter
// beetween the outer and inner container.
if (item.instance !== this.currentContainer) {
continue;
}
// cannot intersect with itself
// no useless actions that have been done before
// no action if the item moved is the parent of the item checked
if (itemElement !== this.currentItem[0] &&
this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
!$.contains(this.placeholder[0], itemElement) &&
(this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true)
) {
this.direction = intersection === 1 ? "down" : "up";
if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) {
this._rearrange(event, item);
} else {
break;
}
this._trigger("change", event, this._uiHash());
break;
}
}
//Post events to containers
this._contactContainers(event);
//Interconnect with droppables
if ($.ui.ddmanager) {
$.ui.ddmanager.drag(this, event);
}
//Call callbacks
this._trigger("sort", event, this._uiHash());
this.lastPositionAbs = this.positionAbs;
return false;
},
_mouseStop: function(event, noPropagation) {
if (!event) {
return;
}
//If we are using droppables, inform the manager about the drop
if ($.ui.ddmanager && !this.options.dropBehaviour) {
$.ui.ddmanager.drop(this, event);
}
if (this.options.revert) {
var that = this,
cur = this.placeholder.offset(),
axis = this.options.axis,
animation = {};
if (!axis || axis === "x") {
animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft);
}
if (!axis || axis === "y") {
animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop);
}
this.reverting = true;
$(this.helper).animate(animation, parseInt(this.options.revert, 10) || 500, function() {
that._clear(event);
});
} else {
this._clear(event, noPropagation);
}
return false;
},
cancel: function() {
if (this.dragging) {
this._mouseUp({target: null});
if (this.options.helper === "original") {
this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
} else {
this.currentItem.show();
}
//Post deactivating events to containers
for (var i = this.containers.length - 1; i >= 0; i--) {
this.containers[i]._trigger("deactivate", null, this._uiHash(this));
if (this.containers[i].containerCache.over) {
this.containers[i]._trigger("out", null, this._uiHash(this));
this.containers[i].containerCache.over = 0;
}
}
}
if (this.placeholder) {
//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
if (this.placeholder[0].parentNode) {
this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
}
if (this.options.helper !== "original" && this.helper && this.helper[0].parentNode) {
this.helper.remove();
}
$.extend(this, {
helper: null,
dragging: false,
reverting: false,
_noFinalSort: null
});
if (this.domPosition.prev) {
$(this.domPosition.prev).after(this.currentItem);
} else {
$(this.domPosition.parent).prepend(this.currentItem);
}
}
return this;
},
serialize: function(o) {
var items = this._getItemsAsjQuery(o && o.connected),
str = [];
o = o || {};
$(items).each(function() {
var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/));
if (res) {
str.push((o.key || res[1] + "[]") + "=" + (o.key && o.expression ? res[1] : res[2]));
}
});
if (!str.length && o.key) {
str.push(o.key + "=");
}
return str.join("&");
},
toArray: function(o) {
var items = this._getItemsAsjQuery(o && o.connected),
ret = [];
o = o || {};
items.each(function() {
ret.push($(o.item || this).attr(o.attribute || "id") || "");
});
return ret;
},
/* Be careful with the following core functions */
_intersectsWith: function(item) {
var x1 = this.positionAbs.left,
x2 = x1 + this.helperProportions.width,
y1 = this.positionAbs.top,
y2 = y1 + this.helperProportions.height,
l = item.left,
r = l + item.width,
t = item.top,
b = t + item.height,
dyClick = this.offset.click.top,
dxClick = this.offset.click.left,
isOverElementHeight = (this.options.axis === "x") || ((y1 + dyClick) > t && (y1 + dyClick) < b),
isOverElementWidth = (this.options.axis === "y") || ((x1 + dxClick) > l && (x1 + dxClick) < r),
isOverElement = isOverElementHeight && isOverElementWidth;
if (this.options.tolerance === "pointer" ||
this.options.forcePointerForContainers ||
(this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"])
) {
return isOverElement;
} else {
return (l < x1 + (this.helperProportions.width / 2) && // Right Half
x2 - (this.helperProportions.width / 2) < r && // Left Half
t < y1 + (this.helperProportions.height / 2) && // Bottom Half
y2 - (this.helperProportions.height / 2) < b); // Top Half
}
},
_intersectsWithPointer: function(item) {
var isOverElementHeight = (this.options.axis === "x") || isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
isOverElementWidth = (this.options.axis === "y") || isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
isOverElement = isOverElementHeight && isOverElementWidth,
verticalDirection = this._getDragVerticalDirection(),
horizontalDirection = this._getDragHorizontalDirection();
if (!isOverElement) {
return false;
}
return this.floating ?
(((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1)
: (verticalDirection && (verticalDirection === "down" ? 2 : 1));
},
_intersectsWithSides: function(item) {
var isOverBottomHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height / 2), item.height),
isOverRightHalf = isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width / 2), item.width),
verticalDirection = this._getDragVerticalDirection(),
horizontalDirection = this._getDragHorizontalDirection();
if (this.floating && horizontalDirection) {
return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf));
} else {
return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf));
}
},
_getDragVerticalDirection: function() {
var delta = this.positionAbs.top - this.lastPositionAbs.top;
return delta !== 0 && (delta > 0 ? "down" : "up");
},
_getDragHorizontalDirection: function() {
var delta = this.positionAbs.left - this.lastPositionAbs.left;
return delta !== 0 && (delta > 0 ? "right" : "left");
},
refresh: function(event) {
this._refreshItems(event);
this.refreshPositions();
return this;
},
_connectWith: function() {
var options = this.options;
return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith;
},
_getItemsAsjQuery: function(connected) {
var i, j, cur, inst,
items = [],
queries = [],
connectWith = this._connectWith();
if (connectWith && connected) {
for (i = connectWith.length - 1; i >= 0; i--) {
cur = $(connectWith[i]);
for (j = cur.length - 1; j >= 0; j--) {
inst = $.data(cur[j], this.widgetFullName);
if (inst && inst !== this && !inst.options.disabled) {
queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]);
}
}
}
}
queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, {options: this.options, item: this.currentItem}) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]);
for (i = queries.length - 1; i >= 0; i--) {
queries[i][0].each(function() {
items.push(this);
});
}
return $(items);
},
_removeCurrentsFromItems: function() {
var list = this.currentItem.find(":data(" + this.widgetName + "-item)");
this.items = $.grep(this.items, function(item) {
for (var j = 0; j < list.length; j++) {
if (list[j] === item.item[0]) {
return false;
}
}
return true;
});
},
_refreshItems: function(event) {
this.items = [];
this.containers = [this];
var i, j, cur, inst, targetData, _queries, item, queriesLength,
items = this.items,
queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, {item: this.currentItem}) : $(this.options.items, this.element), this]],
connectWith = this._connectWith();
if (connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
for (i = connectWith.length - 1; i >= 0; i--) {
cur = $(connectWith[i]);
for (j = cur.length - 1; j >= 0; j--) {
inst = $.data(cur[j], this.widgetFullName);
if (inst && inst !== this && !inst.options.disabled) {
queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, {item: this.currentItem}) : $(inst.options.items, inst.element), inst]);
this.containers.push(inst);
}
}
}
}
for (i = queries.length - 1; i >= 0; i--) {
targetData = queries[i][1];
_queries = queries[i][0];
for (j = 0, queriesLength = _queries.length; j < queriesLength; j++) {
item = $(_queries[j]);
item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager)
items.push({
item: item,
instance: targetData,
width: 0, height: 0,
left: 0, top: 0
});
}
}
},
refreshPositions: function(fast) {
//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
if (this.offsetParent && this.helper) {
this.offset.parent = this._getParentOffset();
}
var i, item, t, p;
for (i = this.items.length - 1; i >= 0; i--) {
item = this.items[i];
//We ignore calculating positions of all connected containers when we're not over them
if (item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) {
continue;
}
t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
if (!fast) {
item.width = t.outerWidth();
item.height = t.outerHeight();
}
p = t.offset();
item.left = p.left;
item.top = p.top;
}
if (this.options.custom && this.options.custom.refreshContainers) {
this.options.custom.refreshContainers.call(this);
} else {
for (i = this.containers.length - 1; i >= 0; i--) {
p = this.containers[i].element.offset();
this.containers[i].containerCache.left = p.left;
this.containers[i].containerCache.top = p.top;
this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
}
}
return this;
},
_createPlaceholder: function(that) {
that = that || this;
var className,
o = that.options;
if (!o.placeholder || o.placeholder.constructor === String) {
className = o.placeholder;
o.placeholder = {
element: function() {
var nodeName = that.currentItem[0].nodeName.toLowerCase(),
element = $("<" + nodeName + ">", that.document[0])
.addClass(className || that.currentItem[0].className + " ui-sortable-placeholder")
.removeClass("ui-sortable-helper");
if (nodeName === "tr") {
that.currentItem.children().each(function() {
$("<td> </td>", that.document[0])
.attr("colspan", $(this).attr("colspan") || 1)
.appendTo(element);
});
} else if (nodeName === "img") {
element.attr("src", that.currentItem.attr("src"));
}
if (!className) {
element.css("visibility", "hidden");
}
return element;
},
update: function(container, p) {
// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
if (className && !o.forcePlaceholderSize) {
return;
}
//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
if (!p.height()) {
p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop") || 0, 10) - parseInt(that.currentItem.css("paddingBottom") || 0, 10));
}
if (!p.width()) {
p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft") || 0, 10) - parseInt(that.currentItem.css("paddingRight") || 0, 10));
}
}
};
}
//Create the placeholder
that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));
//Append it after the actual current item
that.currentItem.after(that.placeholder);
//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
o.placeholder.update(that, that.placeholder);
},
_contactContainers: function(event) {
var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, base, cur, nearBottom, floating,
innermostContainer = null,
innermostIndex = null;
// get innermost container that intersects with item
for (i = this.containers.length - 1; i >= 0; i--) {
// never consider a container that's located within the item itself
if ($.contains(this.currentItem[0], this.containers[i].element[0])) {
continue;
}
if (this._intersectsWith(this.containers[i].containerCache)) {
// if we've already found a container and it's more "inner" than this, then continue
if (innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) {
continue;
}
innermostContainer = this.containers[i];
innermostIndex = i;
} else {
// container doesn't intersect. trigger "out" event if necessary
if (this.containers[i].containerCache.over) {
this.containers[i]._trigger("out", event, this._uiHash(this));
this.containers[i].containerCache.over = 0;
}
}
}
// if no intersecting containers found, return
if (!innermostContainer) {
return;
}
// move the item into the container if it's not there already
if (this.containers.length === 1) {
if (!this.containers[innermostIndex].containerCache.over) {
this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
this.containers[innermostIndex].containerCache.over = 1;
}
} else {
//When entering a new container, we will find the item with the least distance and append our item near it
dist = 10000;
itemWithLeastDistance = null;
floating = innermostContainer.floating || isFloating(this.currentItem);
posProperty = floating ? "left" : "top";
sizeProperty = floating ? "width" : "height";
base = this.positionAbs[posProperty] + this.offset.click[posProperty];
for (j = this.items.length - 1; j >= 0; j--) {
if (!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) {
continue;
}
if (this.items[j].item[0] === this.currentItem[0]) {
continue;
}
if (floating && !isOverAxis(this.positionAbs.top + this.offset.click.top, this.items[j].top, this.items[j].height)) {
continue;
}
cur = this.items[j].item.offset()[posProperty];
nearBottom = false;
if (Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)) {
nearBottom = true;
cur += this.items[j][sizeProperty];
}
if (Math.abs(cur - base) < dist) {
dist = Math.abs(cur - base);
itemWithLeastDistance = this.items[j];
this.direction = nearBottom ? "up" : "down";
}
}
//Check if dropOnEmpty is enabled
if (!itemWithLeastDistance && !this.options.dropOnEmpty) {
return;
}
if (this.currentContainer === this.containers[innermostIndex]) {
return;
}
itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
this._trigger("change", event, this._uiHash());
this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
this.currentContainer = this.containers[innermostIndex];
//Update the placeholder
this.options.placeholder.update(this.currentContainer, this.placeholder);
this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
this.containers[innermostIndex].containerCache.over = 1;
}
},
_createHelper: function(event) {
var o = this.options,
helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem);
//Add the helper to the DOM if that didn't happen already
if (!helper.parents("body").length) {
$(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
}
if (helper[0] === this.currentItem[0]) {
this._storedCSS = {width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left")};
}
if (!helper[0].style.width || o.forceHelperSize) {
helper.width(this.currentItem.width());
}
if (!helper[0].style.height || o.forceHelperSize) {
helper.height(this.currentItem.height());
}
return helper;
},
_adjustOffsetFromHelper: function(obj) {
if (typeof obj === "string") {
obj = obj.split(" ");
}
if ($.isArray(obj)) {
obj = {left: +obj[0], top: +obj[1] || 0};
}
if ("left" in obj) {
this.offset.click.left = obj.left + this.margins.left;
}
if ("right" in obj) {
this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
}
if ("top" in obj) {
this.offset.click.top = obj.top + this.margins.top;
}
if ("bottom" in obj) {
this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
}
},
_getParentOffset: function() {
//Get the offsetParent and cache its position
this.offsetParent = this.helper.offsetParent();
var po = this.offsetParent.offset();
// This is a special case where we need to modify a offset calculated on start, since the following happened:
// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
// the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
po.left += this.scrollParent.scrollLeft();
po.top += this.scrollParent.scrollTop();
}
// This needs to be actually done for all browsers, since pageX/pageY includes this information
// with an ugly IE fix
if (this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
po = {top: 0, left: 0};
}
return {
top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0),
left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0)
};
},
_getRelativeOffset: function() {
if (this.cssPosition === "relative") {
var p = this.currentItem.position();
return {
top: p.top - (parseInt(this.helper.css("top"), 10) || 0) + this.scrollParent.scrollTop(),
left: p.left - (parseInt(this.helper.css("left"), 10) || 0) + this.scrollParent.scrollLeft()
};
} else {
return {top: 0, left: 0};
}
},
_cacheMargins: function() {
this.margins = {
left: (parseInt(this.currentItem.css("marginLeft"), 10) || 0),
top: (parseInt(this.currentItem.css("marginTop"), 10) || 0)
};
},
_cacheHelperProportions: function() {
this.helperProportions = {
width: this.helper.outerWidth(),
height: this.helper.outerHeight()
};
},
_setContainment: function() {
var ce, co, over,
o = this.options;
if (o.containment === "parent") {
o.containment = this.helper[0].parentNode;
}
if (o.containment === "document" || o.containment === "window") {
this.containment = [
0 - this.offset.relative.left - this.offset.parent.left,
0 - this.offset.relative.top - this.offset.parent.top,
$(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left,
($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
];
}
if (!(/^(document|window|parent)$/).test(o.containment)) {
ce = $(o.containment)[0];
co = $(o.containment).offset();
over = ($(ce).css("overflow") !== "hidden");
this.containment = [
co.left + (parseInt($(ce).css("borderLeftWidth"), 10) || 0) + (parseInt($(ce).css("paddingLeft"), 10) || 0) - this.margins.left,
co.top + (parseInt($(ce).css("borderTopWidth"), 10) || 0) + (parseInt($(ce).css("paddingTop"), 10) || 0) - this.margins.top,
co.left + (over ? Math.max(ce.scrollWidth, ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"), 10) || 0) - (parseInt($(ce).css("paddingRight"), 10) || 0) - this.helperProportions.width - this.margins.left,
co.top + (over ? Math.max(ce.scrollHeight, ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"), 10) || 0) - (parseInt($(ce).css("paddingBottom"), 10) || 0) - this.helperProportions.height - this.margins.top
];
}
},
_convertPositionTo: function(d, pos) {
if (!pos) {
pos = this.position;
}
var mod = d === "absolute" ? 1 : -1,
scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
return {
top: (
pos.top + // The absolute mouse position
this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
((this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : (scrollIsRootNode ? 0 : scroll.scrollTop())) * mod)
),
left: (
pos.left + // The absolute mouse position
this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
((this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft()) * mod)
)
};
},
_generatePosition: function(event) {
var top, left,
o = this.options,
pageX = event.pageX,
pageY = event.pageY,
scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
// This is another very weird special case that only happens for relative elements:
// 1. If the css position is relative
// 2. and the scroll parent is the document or similar to the offset parent
// we have to refresh the relative offset during the scroll so there are no jumps
if (this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) {
this.offset.relative = this._getRelativeOffset();
}
/*
* - Position constraining -
* Constrain the position to a mix of grid, containment.
*/
if (this.originalPosition) { //If we are not dragging yet, we won't check for options
if (this.containment) {
if (event.pageX - this.offset.click.left < this.containment[0]) {
pageX = this.containment[0] + this.offset.click.left;
}
if (event.pageY - this.offset.click.top < this.containment[1]) {
pageY = this.containment[1] + this.offset.click.top;
}
if (event.pageX - this.offset.click.left > this.containment[2]) {
pageX = this.containment[2] + this.offset.click.left;
}
if (event.pageY - this.offset.click.top > this.containment[3]) {
pageY = this.containment[3] + this.offset.click.top;
}
}
if (o.grid) {
top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
pageY = this.containment ? ((top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
pageX = this.containment ? ((left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
}
}
return {
top: (
pageY - // The absolute mouse position
this.offset.click.top - // Click offset (relative to the element)
this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
((this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : (scrollIsRootNode ? 0 : scroll.scrollTop())))
),
left: (
pageX - // The absolute mouse position
this.offset.click.left - // Click offset (relative to the element)
this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
((this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft()))
)
};
},
_rearrange: function(event, i, a, hardRefresh) {
a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling));
//Various things done here to improve the performance:
// 1. we create a setTimeout, that calls refreshPositions
// 2. on the instance, we have a counter variable, that get's higher after every append
// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
// 4. this lets only the last addition to the timeout stack through
this.counter = this.counter ? ++this.counter : 1;
var counter = this.counter;
this._delay(function() {
if (counter === this.counter) {
this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
}
});
},
_clear: function(event, noPropagation) {
this.reverting = false;
// We delay all events that have to be triggered to after the point where the placeholder has been removed and
// everything else normalized again
var i,
delayedTriggers = [];
// We first have to update the dom position of the actual currentItem
// Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
if (!this._noFinalSort && this.currentItem.parent().length) {
this.placeholder.before(this.currentItem);
}
this._noFinalSort = null;
if (this.helper[0] === this.currentItem[0]) {
for (i in this._storedCSS) {
if (this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") {
this._storedCSS[i] = "";
}
}
this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
} else {
this.currentItem.show();
}
if (this.fromOutside && !noPropagation) {
delayedTriggers.push(function(event) {
this._trigger("receive", event, this._uiHash(this.fromOutside));
});
}
if ((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) {
delayedTriggers.push(function(event) {
this._trigger("update", event, this._uiHash());
}); //Trigger update callback if the DOM position has changed
}
// Check if the items Container has Changed and trigger appropriate
// events.
if (this !== this.currentContainer) {
if (!noPropagation) {
delayedTriggers.push(function(event) {
this._trigger("remove", event, this._uiHash());
});
delayedTriggers.push((function(c) {
return function(event) {
c._trigger("receive", event, this._uiHash(this));
};
}).call(this, this.currentContainer));
delayedTriggers.push((function(c) {
return function(event) {
c._trigger("update", event, this._uiHash(this));
};
}).call(this, this.currentContainer));
}
}
//Post events to containers
for (i = this.containers.length - 1; i >= 0; i--) {
if (!noPropagation) {
delayedTriggers.push((function(c) {
return function(event) {
c._trigger("deactivate", event, this._uiHash(this));
};
}).call(this, this.containers[i]));
}
if (this.containers[i].containerCache.over) {
delayedTriggers.push((function(c) {
return function(event) {
c._trigger("out", event, this._uiHash(this));
};
}).call(this, this.containers[i]));
this.containers[i].containerCache.over = 0;
}
}
//Do what was originally in plugins
if (this.storedCursor) {
this.document.find("body").css("cursor", this.storedCursor);
this.storedStylesheet.remove();
}
if (this._storedOpacity) {
this.helper.css("opacity", this._storedOpacity);
}
if (this._storedZIndex) {
this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex);
}
this.dragging = false;
if (this.cancelHelperRemoval) {
if (!noPropagation) {
this._trigger("beforeStop", event, this._uiHash());
for (i = 0; i < delayedTriggers.length; i++) {
delayedTriggers[i].call(this, event);
} //Trigger all delayed events
this._trigger("stop", event, this._uiHash());
}
this.fromOutside = false;
return false;
}
if (!noPropagation) {
this._trigger("beforeStop", event, this._uiHash());
}
//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
if (this.helper[0] !== this.currentItem[0]) {
this.helper.remove();
}
this.helper = null;
if (!noPropagation) {
for (i = 0; i < delayedTriggers.length; i++) {
delayedTriggers[i].call(this, event);
} //Trigger all delayed events
this._trigger("stop", event, this._uiHash());
}
this.fromOutside = false;
return true;
},
_trigger: function() {
if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
this.cancel();
}
},
_uiHash: function(_inst) {
var inst = _inst || this;
return {
helper: inst.helper,
placeholder: inst.placeholder || $([]),
position: inst.position,
originalPosition: inst.originalPosition,
offset: inst.positionAbs,
item: inst.currentItem,
sender: _inst ? _inst.element : null
};
}
});
})(jQuery);
(function($, undefined) {
var dataSpace = "ui-effects-";
$.effects = {
effect: {}
};
/*!
* jQuery Color Animations v2.1.2
* https://github.com/jquery/jquery-color
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* Date: Wed Jan 16 08:47:09 2013 -0600
*/
(function(jQuery, undefined) {
var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",
// plusequals test for += 100 -= 100
rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
// a set of RE's that can match strings and generate color tuples.
stringParsers = [{
re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
parse: function(execResult) {
return [
execResult[ 1 ],
execResult[ 2 ],
execResult[ 3 ],
execResult[ 4 ]
];
}
}, {
re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
parse: function(execResult) {
return [
execResult[ 1 ] * 2.55,
execResult[ 2 ] * 2.55,
execResult[ 3 ] * 2.55,
execResult[ 4 ]
];
}
}, {
// this regex ignores A-F because it's compared against an already lowercased string
re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
parse: function(execResult) {
return [
parseInt(execResult[ 1 ], 16),
parseInt(execResult[ 2 ], 16),
parseInt(execResult[ 3 ], 16)
];
}
}, {
// this regex ignores A-F because it's compared against an already lowercased string
re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
parse: function(execResult) {
return [
parseInt(execResult[ 1 ] + execResult[ 1 ], 16),
parseInt(execResult[ 2 ] + execResult[ 2 ], 16),
parseInt(execResult[ 3 ] + execResult[ 3 ], 16)
];
}
}, {
re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
space: "hsla",
parse: function(execResult) {
return [
execResult[ 1 ],
execResult[ 2 ] / 100,
execResult[ 3 ] / 100,
execResult[ 4 ]
];
}
}],
// jQuery.Color( )
color = jQuery.Color = function(color, green, blue, alpha) {
return new jQuery.Color.fn.parse(color, green, blue, alpha);
},
spaces = {
rgba: {
props: {
red: {
idx: 0,
type: "byte"
},
green: {
idx: 1,
type: "byte"
},
blue: {
idx: 2,
type: "byte"
}
}
},
hsla: {
props: {
hue: {
idx: 0,
type: "degrees"
},
saturation: {
idx: 1,
type: "percent"
},
lightness: {
idx: 2,
type: "percent"
}
}
}
},
propTypes = {
"byte": {
floor: true,
max: 255
},
"percent": {
max: 1
},
"degrees": {
mod: 360,
floor: true
}
},
support = color.support = {},
// element for support tests
supportElem = jQuery("<p>")[ 0 ],
// colors = jQuery.Color.names
colors,
// local aliases of functions called often
each = jQuery.each;
// determine rgba support immediately
supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
support.rgba = supportElem.style.backgroundColor.indexOf("rgba") > -1;
// define cache name and alpha properties
// for rgba and hsla spaces
each(spaces, function(spaceName, space) {
space.cache = "_" + spaceName;
space.props.alpha = {
idx: 3,
type: "percent",
def: 1
};
});
function clamp(value, prop, allowEmpty) {
var type = propTypes[ prop.type ] || {};
if (value == null) {
return (allowEmpty || !prop.def) ? null : prop.def;
}
// ~~ is an short way of doing floor for positive numbers
value = type.floor ? ~~value : parseFloat(value);
// IE will pass in empty strings as value for alpha,
// which will hit this case
if (isNaN(value)) {
return prop.def;
}
if (type.mod) {
// we add mod before modding to make sure that negatives values
// get converted properly: -10 -> 350
return (value + type.mod) % type.mod;
}
// for now all property types without mod have min and max
return 0 > value ? 0 : type.max < value ? type.max : value;
}
function stringParse(string) {
var inst = color(),
rgba = inst._rgba = [];
string = string.toLowerCase();
each(stringParsers, function(i, parser) {
var parsed,
match = parser.re.exec(string),
values = match && parser.parse(match),
spaceName = parser.space || "rgba";
if (values) {
parsed = inst[ spaceName ](values);
// if this was an rgba parse the assignment might happen twice
// oh well....
inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
rgba = inst._rgba = parsed._rgba;
// exit each( stringParsers ) here because we matched
return false;
}
});
// Found a stringParser that handled it
if (rgba.length) {
// if this came from a parsed string, force "transparent" when alpha is 0
// chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
if (rgba.join() === "0,0,0,0") {
jQuery.extend(rgba, colors.transparent);
}
return inst;
}
// named colors
return colors[ string ];
}
color.fn = jQuery.extend(color.prototype, {
parse: function(red, green, blue, alpha) {
if (red === undefined) {
this._rgba = [null, null, null, null];
return this;
}
if (red.jquery || red.nodeType) {
red = jQuery(red).css(green);
green = undefined;
}
var inst = this,
type = jQuery.type(red),
rgba = this._rgba = [];
// more than 1 argument specified - assume ( red, green, blue, alpha )
if (green !== undefined) {
red = [red, green, blue, alpha];
type = "array";
}
if (type === "string") {
return this.parse(stringParse(red) || colors._default);
}
if (type === "array") {
each(spaces.rgba.props, function(key, prop) {
rgba[ prop.idx ] = clamp(red[ prop.idx ], prop);
});
return this;
}
if (type === "object") {
if (red instanceof color) {
each(spaces, function(spaceName, space) {
if (red[ space.cache ]) {
inst[ space.cache ] = red[ space.cache ].slice();
}
});
} else {
each(spaces, function(spaceName, space) {
var cache = space.cache;
each(space.props, function(key, prop) {
// if the cache doesn't exist, and we know how to convert
if (!inst[ cache ] && space.to) {
// if the value was null, we don't need to copy it
// if the key was alpha, we don't need to copy it either
if (key === "alpha" || red[ key ] == null) {
return;
}
inst[ cache ] = space.to(inst._rgba);
}
// this is the only case where we allow nulls for ALL properties.
// call clamp with alwaysAllowEmpty
inst[ cache ][ prop.idx ] = clamp(red[ key ], prop, true);
});
// everything defined but alpha?
if (inst[ cache ] && jQuery.inArray(null, inst[ cache ].slice(0, 3)) < 0) {
// use the default of 1
inst[ cache ][ 3 ] = 1;
if (space.from) {
inst._rgba = space.from(inst[ cache ]);
}
}
});
}
return this;
}
},
is: function(compare) {
var is = color(compare),
same = true,
inst = this;
each(spaces, function(_, space) {
var localCache,
isCache = is[ space.cache ];
if (isCache) {
localCache = inst[ space.cache ] || space.to && space.to(inst._rgba) || [];
each(space.props, function(_, prop) {
if (isCache[ prop.idx ] != null) {
same = (isCache[ prop.idx ] === localCache[ prop.idx ]);
return same;
}
});
}
return same;
});
return same;
},
_space: function() {
var used = [],
inst = this;
each(spaces, function(spaceName, space) {
if (inst[ space.cache ]) {
used.push(spaceName);
}
});
return used.pop();
},
transition: function(other, distance) {
var end = color(other),
spaceName = end._space(),
space = spaces[ spaceName ],
startColor = this.alpha() === 0 ? color("transparent") : this,
start = startColor[ space.cache ] || space.to(startColor._rgba),
result = start.slice();
end = end[ space.cache ];
each(space.props, function(key, prop) {
var index = prop.idx,
startValue = start[ index ],
endValue = end[ index ],
type = propTypes[ prop.type ] || {};
// if null, don't override start value
if (endValue === null) {
return;
}
// if null - use end
if (startValue === null) {
result[ index ] = endValue;
} else {
if (type.mod) {
if (endValue - startValue > type.mod / 2) {
startValue += type.mod;
} else if (startValue - endValue > type.mod / 2) {
startValue -= type.mod;
}
}
result[ index ] = clamp((endValue - startValue) * distance + startValue, prop);
}
});
return this[ spaceName ](result);
},
blend: function(opaque) {
// if we are already opaque - return ourself
if (this._rgba[ 3 ] === 1) {
return this;
}
var rgb = this._rgba.slice(),
a = rgb.pop(),
blend = color(opaque)._rgba;
return color(jQuery.map(rgb, function(v, i) {
return (1 - a) * blend[ i ] + a * v;
}));
},
toRgbaString: function() {
var prefix = "rgba(",
rgba = jQuery.map(this._rgba, function(v, i) {
return v == null ? (i > 2 ? 1 : 0) : v;
});
if (rgba[ 3 ] === 1) {
rgba.pop();
prefix = "rgb(";
}
return prefix + rgba.join() + ")";
},
toHslaString: function() {
var prefix = "hsla(",
hsla = jQuery.map(this.hsla(), function(v, i) {
if (v == null) {
v = i > 2 ? 1 : 0;
}
// catch 1 and 2
if (i && i < 3) {
v = Math.round(v * 100) + "%";
}
return v;
});
if (hsla[ 3 ] === 1) {
hsla.pop();
prefix = "hsl(";
}
return prefix + hsla.join() + ")";
},
toHexString: function(includeAlpha) {
var rgba = this._rgba.slice(),
alpha = rgba.pop();
if (includeAlpha) {
rgba.push(~~(alpha * 255));
}
return "#" + jQuery.map(rgba, function(v) {
// default to 0 when nulls exist
v = (v || 0).toString(16);
return v.length === 1 ? "0" + v : v;
}).join("");
},
toString: function() {
return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
}
});
color.fn.parse.prototype = color.fn;
// hsla conversions adapted from:
// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021
function hue2rgb(p, q, h) {
h = (h + 1) % 1;
if (h * 6 < 1) {
return p + (q - p) * h * 6;
}
if (h * 2 < 1) {
return q;
}
if (h * 3 < 2) {
return p + (q - p) * ((2 / 3) - h) * 6;
}
return p;
}
spaces.hsla.to = function(rgba) {
if (rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null) {
return [null, null, null, rgba[ 3 ]];
}
var r = rgba[ 0 ] / 255,
g = rgba[ 1 ] / 255,
b = rgba[ 2 ] / 255,
a = rgba[ 3 ],
max = Math.max(r, g, b),
min = Math.min(r, g, b),
diff = max - min,
add = max + min,
l = add * 0.5,
h, s;
if (min === max) {
h = 0;
} else if (r === max) {
h = (60 * (g - b) / diff) + 360;
} else if (g === max) {
h = (60 * (b - r) / diff) + 120;
} else {
h = (60 * (r - g) / diff) + 240;
}
// chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
// otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
if (diff === 0) {
s = 0;
} else if (l <= 0.5) {
s = diff / add;
} else {
s = diff / (2 - add);
}
return [Math.round(h) % 360, s, l, a == null ? 1 : a];
};
spaces.hsla.from = function(hsla) {
if (hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null) {
return [null, null, null, hsla[ 3 ]];
}
var h = hsla[ 0 ] / 360,
s = hsla[ 1 ],
l = hsla[ 2 ],
a = hsla[ 3 ],
q = l <= 0.5 ? l * (1 + s) : l + s - l * s,
p = 2 * l - q;
return [
Math.round(hue2rgb(p, q, h + (1 / 3)) * 255),
Math.round(hue2rgb(p, q, h) * 255),
Math.round(hue2rgb(p, q, h - (1 / 3)) * 255),
a
];
};
each(spaces, function(spaceName, space) {
var props = space.props,
cache = space.cache,
to = space.to,
from = space.from;
// makes rgba() and hsla()
color.fn[ spaceName ] = function(value) {
// generate a cache for this space if it doesn't exist
if (to && !this[ cache ]) {
this[ cache ] = to(this._rgba);
}
if (value === undefined) {
return this[ cache ].slice();
}
var ret,
type = jQuery.type(value),
arr = (type === "array" || type === "object") ? value : arguments,
local = this[ cache ].slice();
each(props, function(key, prop) {
var val = arr[ type === "object" ? key : prop.idx ];
if (val == null) {
val = local[ prop.idx ];
}
local[ prop.idx ] = clamp(val, prop);
});
if (from) {
ret = color(from(local));
ret[ cache ] = local;
return ret;
} else {
return color(local);
}
};
// makes red() green() blue() alpha() hue() saturation() lightness()
each(props, function(key, prop) {
// alpha is included in more than one space
if (color.fn[ key ]) {
return;
}
color.fn[ key ] = function(value) {
var vtype = jQuery.type(value),
fn = (key === "alpha" ? (this._hsla ? "hsla" : "rgba") : spaceName),
local = this[ fn ](),
cur = local[ prop.idx ],
match;
if (vtype === "undefined") {
return cur;
}
if (vtype === "function") {
value = value.call(this, cur);
vtype = jQuery.type(value);
}
if (value == null && prop.empty) {
return this;
}
if (vtype === "string") {
match = rplusequals.exec(value);
if (match) {
value = cur + parseFloat(match[ 2 ]) * (match[ 1 ] === "+" ? 1 : -1);
}
}
local[ prop.idx ] = value;
return this[ fn ](local);
};
});
});
// add cssHook and .fx.step function for each named hook.
// accept a space separated string of properties
color.hook = function(hook) {
var hooks = hook.split(" ");
each(hooks, function(i, hook) {
jQuery.cssHooks[ hook ] = {
set: function(elem, value) {
var parsed, curElem,
backgroundColor = "";
if (value !== "transparent" && (jQuery.type(value) !== "string" || (parsed = stringParse(value)))) {
value = color(parsed || value);
if (!support.rgba && value._rgba[ 3 ] !== 1) {
curElem = hook === "backgroundColor" ? elem.parentNode : elem;
while (
(backgroundColor === "" || backgroundColor === "transparent") &&
curElem && curElem.style
) {
try {
backgroundColor = jQuery.css(curElem, "backgroundColor");
curElem = curElem.parentNode;
} catch (e) {
}
}
value = value.blend(backgroundColor && backgroundColor !== "transparent" ?
backgroundColor :
"_default");
}
value = value.toRgbaString();
}
try {
elem.style[ hook ] = value;
} catch (e) {
// wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit'
}
}
};
jQuery.fx.step[ hook ] = function(fx) {
if (!fx.colorInit) {
fx.start = color(fx.elem, hook);
fx.end = color(fx.end);
fx.colorInit = true;
}
jQuery.cssHooks[ hook ].set(fx.elem, fx.start.transition(fx.end, fx.pos));
};
});
};
color.hook(stepHooks);
jQuery.cssHooks.borderColor = {
expand: function(value) {
var expanded = {};
each(["Top", "Right", "Bottom", "Left"], function(i, part) {
expanded[ "border" + part + "Color" ] = value;
});
return expanded;
}
};
// Basic color names only.
// Usage of any of the other color names requires adding yourself or including
// jquery.color.svg-names.js.
colors = jQuery.Color.names = {
// 4.1. Basic color keywords
aqua: "#00ffff",
black: "#000000",
blue: "#0000ff",
fuchsia: "#ff00ff",
gray: "#808080",
green: "#008000",
lime: "#00ff00",
maroon: "#800000",
navy: "#000080",
olive: "#808000",
purple: "#800080",
red: "#ff0000",
silver: "#c0c0c0",
teal: "#008080",
white: "#ffffff",
yellow: "#ffff00",
// 4.2.3. "transparent" color keyword
transparent: [null, null, null, 0],
_default: "#ffffff"
};
})(jQuery);
/******************************************************************************/
/****************************** CLASS ANIMATIONS ******************************/
/******************************************************************************/
(function() {
var classAnimationActions = ["add", "remove", "toggle"],
shorthandStyles = {
border: 1,
borderBottom: 1,
borderColor: 1,
borderLeft: 1,
borderRight: 1,
borderTop: 1,
borderWidth: 1,
margin: 1,
padding: 1
};
$.each(["borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle"], function(_, prop) {
$.fx.step[ prop ] = function(fx) {
if (fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr) {
jQuery.style(fx.elem, prop, fx.end);
fx.setAttr = true;
}
};
});
function getElementStyles(elem) {
var key, len,
style = elem.ownerDocument.defaultView ?
elem.ownerDocument.defaultView.getComputedStyle(elem, null) :
elem.currentStyle,
styles = {};
if (style && style.length && style[ 0 ] && style[ style[ 0 ] ]) {
len = style.length;
while (len--) {
key = style[ len ];
if (typeof style[ key ] === "string") {
styles[ $.camelCase(key) ] = style[ key ];
}
}
// support: Opera, IE <9
} else {
for (key in style) {
if (typeof style[ key ] === "string") {
styles[ key ] = style[ key ];
}
}
}
return styles;
}
function styleDifference(oldStyle, newStyle) {
var diff = {},
name, value;
for (name in newStyle) {
value = newStyle[ name ];
if (oldStyle[ name ] !== value) {
if (!shorthandStyles[ name ]) {
if ($.fx.step[ name ] || !isNaN(parseFloat(value))) {
diff[ name ] = value;
}
}
}
}
return diff;
}
// support: jQuery <1.8
if (!$.fn.addBack) {
$.fn.addBack = function(selector) {
return this.add(selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
};
}
$.effects.animateClass = function(value, duration, easing, callback) {
var o = $.speed(duration, easing, callback);
return this.queue(function() {
var animated = $(this),
baseClass = animated.attr("class") || "",
applyClassChange,
allAnimations = o.children ? animated.find("*").addBack() : animated;
// map the animated objects to store the original styles.
allAnimations = allAnimations.map(function() {
var el = $(this);
return {
el: el,
start: getElementStyles(this)
};
});
// apply class change
applyClassChange = function() {
$.each(classAnimationActions, function(i, action) {
if (value[ action ]) {
animated[ action + "Class" ](value[ action ]);
}
});
};
applyClassChange();
// map all animated objects again - calculate new styles and diff
allAnimations = allAnimations.map(function() {
this.end = getElementStyles(this.el[ 0 ]);
this.diff = styleDifference(this.start, this.end);
return this;
});
// apply original class
animated.attr("class", baseClass);
// map all animated objects again - this time collecting a promise
allAnimations = allAnimations.map(function() {
var styleInfo = this,
dfd = $.Deferred(),
opts = $.extend({}, o, {
queue: false,
complete: function() {
dfd.resolve(styleInfo);
}
});
this.el.animate(this.diff, opts);
return dfd.promise();
});
// once all animations have completed:
$.when.apply($, allAnimations.get()).done(function() {
// set the final class
applyClassChange();
// for each animated element,
// clear all css properties that were animated
$.each(arguments, function() {
var el = this.el;
$.each(this.diff, function(key) {
el.css(key, "");
});
});
// this is guarnteed to be there if you use jQuery.speed()
// it also handles dequeuing the next anim...
o.complete.call(animated[ 0 ]);
});
});
};
$.fn.extend({
addClass: (function(orig) {
return function(classNames, speed, easing, callback) {
return speed ?
$.effects.animateClass.call(this,
{add: classNames}, speed, easing, callback) :
orig.apply(this, arguments);
};
})($.fn.addClass),
removeClass: (function(orig) {
return function(classNames, speed, easing, callback) {
return arguments.length > 1 ?
$.effects.animateClass.call(this,
{remove: classNames}, speed, easing, callback) :
orig.apply(this, arguments);
};
})($.fn.removeClass),
toggleClass: (function(orig) {
return function(classNames, force, speed, easing, callback) {
if (typeof force === "boolean" || force === undefined) {
if (!speed) {
// without speed parameter
return orig.apply(this, arguments);
} else {
return $.effects.animateClass.call(this,
(force ? {add: classNames} : {remove: classNames}),
speed, easing, callback);
}
} else {
// without force parameter
return $.effects.animateClass.call(this,
{toggle: classNames}, force, speed, easing);
}
};
})($.fn.toggleClass),
switchClass: function(remove, add, speed, easing, callback) {
return $.effects.animateClass.call(this, {
add: add,
remove: remove
}, speed, easing, callback);
}
});
})();
/******************************************************************************/
/*********************************** EFFECTS **********************************/
/******************************************************************************/
(function() {
$.extend($.effects, {
version: "1.10.3",
// Saves a set of properties in a data storage
save: function(element, set) {
for (var i = 0; i < set.length; i++) {
if (set[ i ] !== null) {
element.data(dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ]);
}
}
},
// Restores a set of previously saved properties from a data storage
restore: function(element, set) {
var val, i;
for (i = 0; i < set.length; i++) {
if (set[ i ] !== null) {
val = element.data(dataSpace + set[ i ]);
// support: jQuery 1.6.2
// http://bugs.jquery.com/ticket/9917
// jQuery 1.6.2 incorrectly returns undefined for any falsy value.
// We can't differentiate between "" and 0 here, so we just assume
// empty string since it's likely to be a more common value...
if (val === undefined) {
val = "";
}
element.css(set[ i ], val);
}
}
},
setMode: function(el, mode) {
if (mode === "toggle") {
mode = el.is(":hidden") ? "show" : "hide";
}
return mode;
},
// Translates a [top,left] array into a baseline value
// this should be a little more flexible in the future to handle a string & hash
getBaseline: function(origin, original) {
var y, x;
switch (origin[ 0 ]) {
case "top":
y = 0;
break;
case "middle":
y = 0.5;
break;
case "bottom":
y = 1;
break;
default:
y = origin[ 0 ] / original.height;
}
switch (origin[ 1 ]) {
case "left":
x = 0;
break;
case "center":
x = 0.5;
break;
case "right":
x = 1;
break;
default:
x = origin[ 1 ] / original.width;
}
return {
x: x,
y: y
};
},
// Wraps the element around a wrapper that copies position properties
createWrapper: function(element) {
// if the element is already wrapped, return it
if (element.parent().is(".ui-effects-wrapper")) {
return element.parent();
}
// wrap the element
var props = {
width: element.outerWidth(true),
height: element.outerHeight(true),
"float": element.css("float")
},
wrapper = $("<div></div>")
.addClass("ui-effects-wrapper")
.css({
fontSize: "100%",
background: "transparent",
border: "none",
margin: 0,
padding: 0
}),
// Store the size in case width/height are defined in % - Fixes #5245
size = {
width: element.width(),
height: element.height()
},
active = document.activeElement;
// support: Firefox
// Firefox incorrectly exposes anonymous content
// https://bugzilla.mozilla.org/show_bug.cgi?id=561664
try {
active.id;
} catch (e) {
active = document.body;
}
element.wrap(wrapper);
// Fixes #7595 - Elements lose focus when wrapped.
if (element[ 0 ] === active || $.contains(element[ 0 ], active)) {
$(active).focus();
}
wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element
// transfer positioning properties to the wrapper
if (element.css("position") === "static") {
wrapper.css({position: "relative"});
element.css({position: "relative"});
} else {
$.extend(props, {
position: element.css("position"),
zIndex: element.css("z-index")
});
$.each(["top", "left", "bottom", "right"], function(i, pos) {
props[ pos ] = element.css(pos);
if (isNaN(parseInt(props[ pos ], 10))) {
props[ pos ] = "auto";
}
});
element.css({
position: "relative",
top: 0,
left: 0,
right: "auto",
bottom: "auto"
});
}
element.css(size);
return wrapper.css(props).show();
},
removeWrapper: function(element) {
var active = document.activeElement;
if (element.parent().is(".ui-effects-wrapper")) {
element.parent().replaceWith(element);
// Fixes #7595 - Elements lose focus when wrapped.
if (element[ 0 ] === active || $.contains(element[ 0 ], active)) {
$(active).focus();
}
}
return element;
},
setTransition: function(element, list, factor, value) {
value = value || {};
$.each(list, function(i, x) {
var unit = element.cssUnit(x);
if (unit[ 0 ] > 0) {
value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
}
});
return value;
}
});
// return an effect options object for the given parameters:
function _normalizeArguments(effect, options, speed, callback) {
// allow passing all options as the first parameter
if ($.isPlainObject(effect)) {
options = effect;
effect = effect.effect;
}
// convert to an object
effect = {effect: effect};
// catch (effect, null, ...)
if (options == null) {
options = {};
}
// catch (effect, callback)
if ($.isFunction(options)) {
callback = options;
speed = null;
options = {};
}
// catch (effect, speed, ?)
if (typeof options === "number" || $.fx.speeds[ options ]) {
callback = speed;
speed = options;
options = {};
}
// catch (effect, options, callback)
if ($.isFunction(speed)) {
callback = speed;
speed = null;
}
// add options to effect
if (options) {
$.extend(effect, options);
}
speed = speed || options.duration;
effect.duration = $.fx.off ? 0 :
typeof speed === "number" ? speed :
speed in $.fx.speeds ? $.fx.speeds[ speed ] :
$.fx.speeds._default;
effect.complete = callback || options.complete;
return effect;
}
function standardAnimationOption(option) {
// Valid standard speeds (nothing, number, named speed)
if (!option || typeof option === "number" || $.fx.speeds[ option ]) {
return true;
}
// Invalid strings - treat as "normal" speed
if (typeof option === "string" && !$.effects.effect[ option ]) {
return true;
}
// Complete callback
if ($.isFunction(option)) {
return true;
}
// Options hash (but not naming an effect)
if (typeof option === "object" && !option.effect) {
return true;
}
// Didn't match any standard API
return false;
}
$.fn.extend({
effect: function( /* effect, options, speed, callback */ ) {
var args = _normalizeArguments.apply(this, arguments),
mode = args.mode,
queue = args.queue,
effectMethod = $.effects.effect[ args.effect ];
if ($.fx.off || !effectMethod) {
// delegate to the original method (e.g., .show()) if possible
if (mode) {
return this[ mode ](args.duration, args.complete);
} else {
return this.each(function() {
if (args.complete) {
args.complete.call(this);
}
});
}
}
function run(next) {
var elem = $(this),
complete = args.complete,
mode = args.mode;
function done() {
if ($.isFunction(complete)) {
complete.call(elem[0]);
}
if ($.isFunction(next)) {
next();
}
}
// If the element already has the correct final state, delegate to
// the core methods so the internal tracking of "olddisplay" works.
if (elem.is(":hidden") ? mode === "hide" : mode === "show") {
elem[ mode ]();
done();
} else {
effectMethod.call(elem[0], args, done);
}
}
return queue === false ? this.each(run) : this.queue(queue || "fx", run);
},
show: (function(orig) {
return function(option) {
if (standardAnimationOption(option)) {
return orig.apply(this, arguments);
} else {
var args = _normalizeArguments.apply(this, arguments);
args.mode = "show";
return this.effect.call(this, args);
}
};
})($.fn.show),
hide: (function(orig) {
return function(option) {
if (standardAnimationOption(option)) {
return orig.apply(this, arguments);
} else {
var args = _normalizeArguments.apply(this, arguments);
args.mode = "hide";
return this.effect.call(this, args);
}
};
})($.fn.hide),
toggle: (function(orig) {
return function(option) {
if (standardAnimationOption(option) || typeof option === "boolean") {
return orig.apply(this, arguments);
} else {
var args = _normalizeArguments.apply(this, arguments);
args.mode = "toggle";
return this.effect.call(this, args);
}
};
})($.fn.toggle),
// helper functions
cssUnit: function(key) {
var style = this.css(key),
val = [];
$.each(["em", "px", "%", "pt"], function(i, unit) {
if (style.indexOf(unit) > 0) {
val = [parseFloat(style), unit];
}
});
return val;
}
});
})();
/******************************************************************************/
/*********************************** EASING ***********************************/
/******************************************************************************/
(function() {
// based on easing equations from Robert Penner (http://www.robertpenner.com/easing)
var baseEasings = {};
$.each(["Quad", "Cubic", "Quart", "Quint", "Expo"], function(i, name) {
baseEasings[ name ] = function(p) {
return Math.pow(p, i + 2);
};
});
$.extend(baseEasings, {
Sine: function(p) {
return 1 - Math.cos(p * Math.PI / 2);
},
Circ: function(p) {
return 1 - Math.sqrt(1 - p * p);
},
Elastic: function(p) {
return p === 0 || p === 1 ? p :
-Math.pow(2, 8 * (p - 1)) * Math.sin(((p - 1) * 80 - 7.5) * Math.PI / 15);
},
Back: function(p) {
return p * p * (3 * p - 2);
},
Bounce: function(p) {
var pow2,
bounce = 4;
while (p < ((pow2 = Math.pow(2, --bounce)) - 1) / 11) {
}
return 1 / Math.pow(4, 3 - bounce) - 7.5625 * Math.pow((pow2 * 3 - 2) / 22 - p, 2);
}
});
$.each(baseEasings, function(name, easeIn) {
$.easing[ "easeIn" + name ] = easeIn;
$.easing[ "easeOut" + name ] = function(p) {
return 1 - easeIn(1 - p);
};
$.easing[ "easeInOut" + name ] = function(p) {
return p < 0.5 ?
easeIn(p * 2) / 2 :
1 - easeIn(p * -2 + 2) / 2;
};
});
})();
})(jQuery);
(function($, undefined) {
var uid = 0,
hideProps = {},
showProps = {};
hideProps.height = hideProps.paddingTop = hideProps.paddingBottom =
hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide";
showProps.height = showProps.paddingTop = showProps.paddingBottom =
showProps.borderTopWidth = showProps.borderBottomWidth = "show";
$.widget("ui.accordion", {
version: "1.10.3",
options: {
active: 0,
animate: {},
collapsible: false,
event: "click",
header: "> li > :first-child,> :not(li):even",
heightStyle: "auto",
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
},
// callbacks
activate: null,
beforeActivate: null
},
_create: function() {
var options = this.options;
this.prevShow = this.prevHide = $();
this.element.addClass("ui-accordion ui-widget ui-helper-reset")
// ARIA
.attr("role", "tablist");
// don't allow collapsible: false and active: false / null
if (!options.collapsible && (options.active === false || options.active == null)) {
options.active = 0;
}
this._processPanels();
// handle negative values
if (options.active < 0) {
options.active += this.headers.length;
}
this._refresh();
},
_getCreateEventData: function() {
return {
header: this.active,
panel: !this.active.length ? $() : this.active.next(),
content: !this.active.length ? $() : this.active.next()
};
},
_createIcons: function() {
var icons = this.options.icons;
if (icons) {
$("<span>")
.addClass("ui-accordion-header-icon ui-icon " + icons.header)
.prependTo(this.headers);
this.active.children(".ui-accordion-header-icon")
.removeClass(icons.header)
.addClass(icons.activeHeader);
this.headers.addClass("ui-accordion-icons");
}
},
_destroyIcons: function() {
this.headers
.removeClass("ui-accordion-icons")
.children(".ui-accordion-header-icon")
.remove();
},
_destroy: function() {
var contents;
// clean up main element
this.element
.removeClass("ui-accordion ui-widget ui-helper-reset")
.removeAttr("role");
// clean up headers
this.headers
.removeClass("ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top")
.removeAttr("role")
.removeAttr("aria-selected")
.removeAttr("aria-controls")
.removeAttr("tabIndex")
.each(function() {
if (/^ui-accordion/.test(this.id)) {
this.removeAttribute("id");
}
});
this._destroyIcons();
// clean up content panels
contents = this.headers.next()
.css("display", "")
.removeAttr("role")
.removeAttr("aria-expanded")
.removeAttr("aria-hidden")
.removeAttr("aria-labelledby")
.removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled")
.each(function() {
if (/^ui-accordion/.test(this.id)) {
this.removeAttribute("id");
}
});
if (this.options.heightStyle !== "content") {
contents.css("height", "");
}
},
_setOption: function(key, value) {
if (key === "active") {
// _activate() will handle invalid values and update this.options
this._activate(value);
return;
}
if (key === "event") {
if (this.options.event) {
this._off(this.headers, this.options.event);
}
this._setupEvents(value);
}
this._super(key, value);
// setting collapsible: false while collapsed; open first panel
if (key === "collapsible" && !value && this.options.active === false) {
this._activate(0);
}
if (key === "icons") {
this._destroyIcons();
if (value) {
this._createIcons();
}
}
// #5332 - opacity doesn't cascade to positioned elements in IE
// so we need to add the disabled class to the headers and panels
if (key === "disabled") {
this.headers.add(this.headers.next())
.toggleClass("ui-state-disabled", !!value);
}
},
_keydown: function(event) {
/*jshint maxcomplexity:15*/
if (event.altKey || event.ctrlKey) {
return;
}
var keyCode = $.ui.keyCode,
length = this.headers.length,
currentIndex = this.headers.index(event.target),
toFocus = false;
switch (event.keyCode) {
case keyCode.RIGHT:
case keyCode.DOWN:
toFocus = this.headers[ (currentIndex + 1) % length ];
break;
case keyCode.LEFT:
case keyCode.UP:
toFocus = this.headers[ (currentIndex - 1 + length) % length ];
break;
case keyCode.SPACE:
case keyCode.ENTER:
this._eventHandler(event);
break;
case keyCode.HOME:
toFocus = this.headers[ 0 ];
break;
case keyCode.END:
toFocus = this.headers[ length - 1 ];
break;
}
if (toFocus) {
$(event.target).attr("tabIndex", -1);
$(toFocus).attr("tabIndex", 0);
toFocus.focus();
event.preventDefault();
}
},
_panelKeyDown: function(event) {
if (event.keyCode === $.ui.keyCode.UP && event.ctrlKey) {
$(event.currentTarget).prev().focus();
}
},
refresh: function() {
var options = this.options;
this._processPanels();
// was collapsed or no panel
if ((options.active === false && options.collapsible === true) || !this.headers.length) {
options.active = false;
this.active = $();
// active false only when collapsible is true
} else if (options.active === false) {
this._activate(0);
// was active, but active panel is gone
} else if (this.active.length && !$.contains(this.element[ 0 ], this.active[ 0 ])) {
// all remaining panel are disabled
if (this.headers.length === this.headers.find(".ui-state-disabled").length) {
options.active = false;
this.active = $();
// activate previous panel
} else {
this._activate(Math.max(0, options.active - 1));
}
// was active, active panel still exists
} else {
// make sure active index is correct
options.active = this.headers.index(this.active);
}
this._destroyIcons();
this._refresh();
},
_processPanels: function() {
this.headers = this.element.find(this.options.header)
.addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all");
this.headers.next()
.addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom")
.filter(":not(.ui-accordion-content-active)")
.hide();
},
_refresh: function() {
var maxHeight,
options = this.options,
heightStyle = options.heightStyle,
parent = this.element.parent(),
accordionId = this.accordionId = "ui-accordion-" +
(this.element.attr("id") || ++uid);
this.active = this._findActive(options.active)
.addClass("ui-accordion-header-active ui-state-active ui-corner-top")
.removeClass("ui-corner-all");
this.active.next()
.addClass("ui-accordion-content-active")
.show();
this.headers
.attr("role", "tab")
.each(function(i) {
var header = $(this),
headerId = header.attr("id"),
panel = header.next(),
panelId = panel.attr("id");
if (!headerId) {
headerId = accordionId + "-header-" + i;
header.attr("id", headerId);
}
if (!panelId) {
panelId = accordionId + "-panel-" + i;
panel.attr("id", panelId);
}
header.attr("aria-controls", panelId);
panel.attr("aria-labelledby", headerId);
})
.next()
.attr("role", "tabpanel");
this.headers
.not(this.active)
.attr({
"aria-selected": "false",
tabIndex: -1
})
.next()
.attr({
"aria-expanded": "false",
"aria-hidden": "true"
})
.hide();
// make sure at least one header is in the tab order
if (!this.active.length) {
this.headers.eq(0).attr("tabIndex", 0);
} else {
this.active.attr({
"aria-selected": "true",
tabIndex: 0
})
.next()
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
});
}
this._createIcons();
this._setupEvents(options.event);
if (heightStyle === "fill") {
maxHeight = parent.height();
this.element.siblings(":visible").each(function() {
var elem = $(this),
position = elem.css("position");
if (position === "absolute" || position === "fixed") {
return;
}
maxHeight -= elem.outerHeight(true);
});
this.headers.each(function() {
maxHeight -= $(this).outerHeight(true);
});
this.headers.next()
.each(function() {
$(this).height(Math.max(0, maxHeight -
$(this).innerHeight() + $(this).height()));
})
.css("overflow", "auto");
} else if (heightStyle === "auto") {
maxHeight = 0;
this.headers.next()
.each(function() {
maxHeight = Math.max(maxHeight, $(this).css("height", "").height());
})
.height(maxHeight);
}
},
_activate: function(index) {
var active = this._findActive(index)[ 0 ];
// trying to activate the already active panel
if (active === this.active[ 0 ]) {
return;
}
// trying to collapse, simulate a click on the currently active header
active = active || this.active[ 0 ];
this._eventHandler({
target: active,
currentTarget: active,
preventDefault: $.noop
});
},
_findActive: function(selector) {
return typeof selector === "number" ? this.headers.eq(selector) : $();
},
_setupEvents: function(event) {
var events = {
keydown: "_keydown"
};
if (event) {
$.each(event.split(" "), function(index, eventName) {
events[ eventName ] = "_eventHandler";
});
}
this._off(this.headers.add(this.headers.next()));
this._on(this.headers, events);
this._on(this.headers.next(), {keydown: "_panelKeyDown"});
this._hoverable(this.headers);
this._focusable(this.headers);
},
_eventHandler: function(event) {
var options = this.options,
active = this.active,
clicked = $(event.currentTarget),
clickedIsActive = clicked[ 0 ] === active[ 0 ],
collapsing = clickedIsActive && options.collapsible,
toShow = collapsing ? $() : clicked.next(),
toHide = active.next(),
eventData = {
oldHeader: active,
oldPanel: toHide,
newHeader: collapsing ? $() : clicked,
newPanel: toShow
};
event.preventDefault();
if (
// click on active header, but not collapsible
(clickedIsActive && !options.collapsible) ||
// allow canceling activation
(this._trigger("beforeActivate", event, eventData) === false)) {
return;
}
options.active = collapsing ? false : this.headers.index(clicked);
// when the call to ._toggle() comes after the class changes
// it causes a very odd bug in IE 8 (see #6720)
this.active = clickedIsActive ? $() : clicked;
this._toggle(eventData);
// switch classes
// corner classes on the previously active header stay after the animation
active.removeClass("ui-accordion-header-active ui-state-active");
if (options.icons) {
active.children(".ui-accordion-header-icon")
.removeClass(options.icons.activeHeader)
.addClass(options.icons.header);
}
if (!clickedIsActive) {
clicked
.removeClass("ui-corner-all")
.addClass("ui-accordion-header-active ui-state-active ui-corner-top");
if (options.icons) {
clicked.children(".ui-accordion-header-icon")
.removeClass(options.icons.header)
.addClass(options.icons.activeHeader);
}
clicked
.next()
.addClass("ui-accordion-content-active");
}
},
_toggle: function(data) {
var toShow = data.newPanel,
toHide = this.prevShow.length ? this.prevShow : data.oldPanel;
// handle activating a panel during the animation for another activation
this.prevShow.add(this.prevHide).stop(true, true);
this.prevShow = toShow;
this.prevHide = toHide;
if (this.options.animate) {
this._animate(toShow, toHide, data);
} else {
toHide.hide();
toShow.show();
this._toggleComplete(data);
}
toHide.attr({
"aria-expanded": "false",
"aria-hidden": "true"
});
toHide.prev().attr("aria-selected", "false");
// if we're switching panels, remove the old header from the tab order
// if we're opening from collapsed state, remove the previous header from the tab order
// if we're collapsing, then keep the collapsing header in the tab order
if (toShow.length && toHide.length) {
toHide.prev().attr("tabIndex", -1);
} else if (toShow.length) {
this.headers.filter(function() {
return $(this).attr("tabIndex") === 0;
})
.attr("tabIndex", -1);
}
toShow
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
})
.prev()
.attr({
"aria-selected": "true",
tabIndex: 0
});
},
_animate: function(toShow, toHide, data) {
var total, easing, duration,
that = this,
adjust = 0,
down = toShow.length &&
(!toHide.length || (toShow.index() < toHide.index())),
animate = this.options.animate || {},
options = down && animate.down || animate,
complete = function() {
that._toggleComplete(data);
};
if (typeof options === "number") {
duration = options;
}
if (typeof options === "string") {
easing = options;
}
// fall back from options to animation in case of partial down settings
easing = easing || options.easing || animate.easing;
duration = duration || options.duration || animate.duration;
if (!toHide.length) {
return toShow.animate(showProps, duration, easing, complete);
}
if (!toShow.length) {
return toHide.animate(hideProps, duration, easing, complete);
}
total = toShow.show().outerHeight();
toHide.animate(hideProps, {
duration: duration,
easing: easing,
step: function(now, fx) {
fx.now = Math.round(now);
}
});
toShow
.hide()
.animate(showProps, {
duration: duration,
easing: easing,
complete: complete,
step: function(now, fx) {
fx.now = Math.round(now);
if (fx.prop !== "height") {
adjust += fx.now;
} else if (that.options.heightStyle !== "content") {
fx.now = Math.round(total - toHide.outerHeight() - adjust);
adjust = 0;
}
}
});
},
_toggleComplete: function(data) {
var toHide = data.oldPanel;
toHide
.removeClass("ui-accordion-content-active")
.prev()
.removeClass("ui-corner-top")
.addClass("ui-corner-all");
// Work around for rendering bug in IE (#5421)
if (toHide.length) {
toHide.parent()[0].className = toHide.parent()[0].className;
}
this._trigger("activate", null, data);
}
});
})(jQuery);
(function($, undefined) {
// used to prevent race conditions with remote data sources
var requestIndex = 0;
$.widget("ui.autocomplete", {
version: "1.10.3",
defaultElement: "<input>",
options: {
appendTo: null,
autoFocus: false,
delay: 300,
minLength: 1,
position: {
my: "left top",
at: "left bottom",
collision: "none"
},
source: null,
// callbacks
change: null,
close: null,
focus: null,
open: null,
response: null,
search: null,
select: null
},
pending: 0,
_create: function() {
// Some browsers only repeat keydown events, not keypress events,
// so we use the suppressKeyPress flag to determine if we've already
// handled the keydown event. #7269
// Unfortunately the code for & in keypress is the same as the up arrow,
// so we use the suppressKeyPressRepeat flag to avoid handling keypress
// events when we know the keydown event was used to modify the
// search term. #7799
var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
nodeName = this.element[0].nodeName.toLowerCase(),
isTextarea = nodeName === "textarea",
isInput = nodeName === "input";
this.isMultiLine =
// Textareas are always multi-line
isTextarea ? true :
// Inputs are always single-line, even if inside a contentEditable element
// IE also treats inputs as contentEditable
isInput ? false :
// All other element types are determined by whether or not they're contentEditable
this.element.prop("isContentEditable");
this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
this.isNewMenu = true;
this.element
.addClass("ui-autocomplete-input")
.attr("autocomplete", "off");
this._on(this.element, {
keydown: function(event) {
/*jshint maxcomplexity:15*/
if (this.element.prop("readOnly")) {
suppressKeyPress = true;
suppressInput = true;
suppressKeyPressRepeat = true;
return;
}
suppressKeyPress = false;
suppressInput = false;
suppressKeyPressRepeat = false;
var keyCode = $.ui.keyCode;
switch (event.keyCode) {
case keyCode.PAGE_UP:
suppressKeyPress = true;
this._move("previousPage", event);
break;
case keyCode.PAGE_DOWN:
suppressKeyPress = true;
this._move("nextPage", event);
break;
case keyCode.UP:
suppressKeyPress = true;
this._keyEvent("previous", event);
break;
case keyCode.DOWN:
suppressKeyPress = true;
this._keyEvent("next", event);
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
// when menu is open and has focus
if (this.menu.active) {
// #6055 - Opera still allows the keypress to occur
// which causes forms to submit
suppressKeyPress = true;
event.preventDefault();
this.menu.select(event);
}
break;
case keyCode.TAB:
if (this.menu.active) {
this.menu.select(event);
}
break;
case keyCode.ESCAPE:
if (this.menu.element.is(":visible")) {
this._value(this.term);
this.close(event);
// Different browsers have different default behavior for escape
// Single press can mean undo or clear
// Double press in IE means clear the whole form
event.preventDefault();
}
break;
default:
suppressKeyPressRepeat = true;
// search timeout should be triggered before the input value is changed
this._searchTimeout(event);
break;
}
},
keypress: function(event) {
if (suppressKeyPress) {
suppressKeyPress = false;
if (!this.isMultiLine || this.menu.element.is(":visible")) {
event.preventDefault();
}
return;
}
if (suppressKeyPressRepeat) {
return;
}
// replicate some key handlers to allow them to repeat in Firefox and Opera
var keyCode = $.ui.keyCode;
switch (event.keyCode) {
case keyCode.PAGE_UP:
this._move("previousPage", event);
break;
case keyCode.PAGE_DOWN:
this._move("nextPage", event);
break;
case keyCode.UP:
this._keyEvent("previous", event);
break;
case keyCode.DOWN:
this._keyEvent("next", event);
break;
}
},
input: function(event) {
if (suppressInput) {
suppressInput = false;
event.preventDefault();
return;
}
this._searchTimeout(event);
},
focus: function() {
this.selectedItem = null;
this.previous = this._value();
},
blur: function(event) {
if (this.cancelBlur) {
delete this.cancelBlur;
return;
}
clearTimeout(this.searching);
this.close(event);
this._change(event);
}
});
this._initSource();
this.menu = $("<ul>")
.addClass("ui-autocomplete ui-front")
.appendTo(this._appendTo())
.menu({
// disable ARIA support, the live region takes care of that
role: null
})
.hide()
.data("ui-menu");
this._on(this.menu.element, {
mousedown: function(event) {
// prevent moving focus out of the text field
event.preventDefault();
// IE doesn't prevent moving focus even with event.preventDefault()
// so we set a flag to know when we should ignore the blur event
this.cancelBlur = true;
this._delay(function() {
delete this.cancelBlur;
});
// clicking on the scrollbar causes focus to shift to the body
// but we can't detect a mouseup or a click immediately afterward
// so we have to track the next mousedown and close the menu if
// the user clicks somewhere outside of the autocomplete
var menuElement = this.menu.element[ 0 ];
if (!$(event.target).closest(".ui-menu-item").length) {
this._delay(function() {
var that = this;
this.document.one("mousedown", function(event) {
if (event.target !== that.element[ 0 ] &&
event.target !== menuElement &&
!$.contains(menuElement, event.target)) {
that.close();
}
});
});
}
},
menufocus: function(event, ui) {
// support: Firefox
// Prevent accidental activation of menu items in Firefox (#7024 #9118)
if (this.isNewMenu) {
this.isNewMenu = false;
if (event.originalEvent && /^mouse/.test(event.originalEvent.type)) {
this.menu.blur();
this.document.one("mousemove", function() {
$(event.target).trigger(event.originalEvent);
});
return;
}
}
var item = ui.item.data("ui-autocomplete-item");
if (false !== this._trigger("focus", event, {item: item})) {
// use value to match what will end up in the input, if it was a key event
if (event.originalEvent && /^key/.test(event.originalEvent.type)) {
this._value(item.value);
}
} else {
// Normally the input is populated with the item's value as the
// menu is navigated, causing screen readers to notice a change and
// announce the item. Since the focus event was canceled, this doesn't
// happen, so we update the live region so that screen readers can
// still notice the change and announce it.
this.liveRegion.text(item.value);
}
},
menuselect: function(event, ui) {
var item = ui.item.data("ui-autocomplete-item"),
previous = this.previous;
// only trigger when focus was lost (click on menu)
if (this.element[0] !== this.document[0].activeElement) {
this.element.focus();
this.previous = previous;
// #6109 - IE triggers two focus events and the second
// is asynchronous, so we need to reset the previous
// term synchronously and asynchronously :-(
this._delay(function() {
this.previous = previous;
this.selectedItem = item;
});
}
if (false !== this._trigger("select", event, {item: item})) {
this._value(item.value);
}
// reset the term after the select event
// this allows custom select handling to work properly
this.term = this._value();
this.close(event);
this.selectedItem = item;
}
});
this.liveRegion = $("<span>", {
role: "status",
"aria-live": "polite"
})
.addClass("ui-helper-hidden-accessible")
.insertBefore(this.element);
// turning off autocomplete prevents the browser from remembering the
// value when navigating through history, so we re-enable autocomplete
// if the page is unloaded before the widget is destroyed. #7790
this._on(this.window, {
beforeunload: function() {
this.element.removeAttr("autocomplete");
}
});
},
_destroy: function() {
clearTimeout(this.searching);
this.element
.removeClass("ui-autocomplete-input")
.removeAttr("autocomplete");
this.menu.element.remove();
this.liveRegion.remove();
},
_setOption: function(key, value) {
this._super(key, value);
if (key === "source") {
this._initSource();
}
if (key === "appendTo") {
this.menu.element.appendTo(this._appendTo());
}
if (key === "disabled" && value && this.xhr) {
this.xhr.abort();
}
},
_appendTo: function() {
var element = this.options.appendTo;
if (element) {
element = element.jquery || element.nodeType ?
$(element) :
this.document.find(element).eq(0);
}
if (!element) {
element = this.element.closest(".ui-front");
}
if (!element.length) {
element = this.document[0].body;
}
return element;
},
_initSource: function() {
var array, url,
that = this;
if ($.isArray(this.options.source)) {
array = this.options.source;
this.source = function(request, response) {
response($.ui.autocomplete.filter(array, request.term));
};
} else if (typeof this.options.source === "string") {
url = this.options.source;
this.source = function(request, response) {
if (that.xhr) {
that.xhr.abort();
}
that.xhr = $.ajax({
url: url,
data: request,
dataType: "json",
success: function(data) {
response(data);
},
error: function() {
response([]);
}
});
};
} else {
this.source = this.options.source;
}
},
_searchTimeout: function(event) {
clearTimeout(this.searching);
this.searching = this._delay(function() {
// only search if the value has changed
if (this.term !== this._value()) {
this.selectedItem = null;
this.search(null, event);
}
}, this.options.delay);
},
search: function(value, event) {
value = value != null ? value : this._value();
// always save the actual value, not the one passed as an argument
this.term = this._value();
if (value.length < this.options.minLength) {
return this.close(event);
}
if (this._trigger("search", event) === false) {
return;
}
return this._search(value);
},
_search: function(value) {
this.pending++;
this.element.addClass("ui-autocomplete-loading");
this.cancelSearch = false;
this.source({term: value}, this._response());
},
_response: function() {
var that = this,
index = ++requestIndex;
return function(content) {
if (index === requestIndex) {
that.__response(content);
}
that.pending--;
if (!that.pending) {
that.element.removeClass("ui-autocomplete-loading");
}
};
},
__response: function(content) {
if (content) {
content = this._normalize(content);
}
this._trigger("response", null, {content: content});
if (!this.options.disabled && content && content.length && !this.cancelSearch) {
this._suggest(content);
this._trigger("open");
} else {
// use ._close() instead of .close() so we don't cancel future searches
this._close();
}
},
close: function(event) {
this.cancelSearch = true;
this._close(event);
},
_close: function(event) {
if (this.menu.element.is(":visible")) {
this.menu.element.hide();
this.menu.blur();
this.isNewMenu = true;
this._trigger("close", event);
}
},
_change: function(event) {
if (this.previous !== this._value()) {
this._trigger("change", event, {item: this.selectedItem});
}
},
_normalize: function(items) {
// assume all items have the right format when the first item is complete
if (items.length && items[0].label && items[0].value) {
return items;
}
return $.map(items, function(item) {
if (typeof item === "string") {
return {
label: item,
value: item
};
}
return $.extend({
label: item.label || item.value,
value: item.value || item.label
}, item);
});
},
_suggest: function(items) {
var ul = this.menu.element.empty();
this._renderMenu(ul, items);
this.isNewMenu = true;
this.menu.refresh();
// size and position menu
ul.show();
this._resizeMenu();
ul.position($.extend({
of: this.element
}, this.options.position));
if (this.options.autoFocus) {
this.menu.next();
}
},
_resizeMenu: function() {
var ul = this.menu.element;
ul.outerWidth(Math.max(
// Firefox wraps long text (possibly a rounding bug)
// so we add 1px to avoid the wrapping (#7513)
ul.width("").outerWidth() + 1,
this.element.outerWidth()
));
},
_renderMenu: function(ul, items) {
var that = this;
$.each(items, function(index, item) {
that._renderItemData(ul, item);
});
},
_renderItemData: function(ul, item) {
return this._renderItem(ul, item).data("ui-autocomplete-item", item);
},
_renderItem: function(ul, item) {
return $("<li>")
.append($("<a>").text(item.label))
.appendTo(ul);
},
_move: function(direction, event) {
if (!this.menu.element.is(":visible")) {
this.search(null, event);
return;
}
if (this.menu.isFirstItem() && /^previous/.test(direction) ||
this.menu.isLastItem() && /^next/.test(direction)) {
this._value(this.term);
this.menu.blur();
return;
}
this.menu[ direction ](event);
},
widget: function() {
return this.menu.element;
},
_value: function() {
return this.valueMethod.apply(this.element, arguments);
},
_keyEvent: function(keyEvent, event) {
if (!this.isMultiLine || this.menu.element.is(":visible")) {
this._move(keyEvent, event);
// prevents moving cursor to beginning/end of the text field in some browsers
event.preventDefault();
}
}
});
$.extend($.ui.autocomplete, {
escapeRegex: function(value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
},
filter: function(array, term) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), "i");
return $.grep(array, function(value) {
return matcher.test(value.label || value.value || value);
});
}
});
// live region extension, adding a `messages` option
// NOTE: This is an experimental API. We are still investigating
// a full solution for string manipulation and internationalization.
$.widget("ui.autocomplete", $.ui.autocomplete, {
options: {
messages: {
noResults: "No search results.",
results: function(amount) {
return amount + (amount > 1 ? " results are" : " result is") +
" available, use up and down arrow keys to navigate.";
}
}
},
__response: function(content) {
var message;
this._superApply(arguments);
if (this.options.disabled || this.cancelSearch) {
return;
}
if (content && content.length) {
message = this.options.messages.results(content.length);
} else {
message = this.options.messages.noResults;
}
this.liveRegion.text(message);
}
});
}(jQuery));
(function($, undefined) {
var lastActive, startXPos, startYPos, clickDragged,
baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
stateClasses = "ui-state-hover ui-state-active ",
typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",
formResetHandler = function() {
var form = $(this);
setTimeout(function() {
form.find(":ui-button").button("refresh");
}, 1);
},
radioGroup = function(radio) {
var name = radio.name,
form = radio.form,
radios = $([]);
if (name) {
name = name.replace(/'/g, "\\'");
if (form) {
radios = $(form).find("[name='" + name + "']");
} else {
radios = $("[name='" + name + "']", radio.ownerDocument)
.filter(function() {
return !this.form;
});
}
}
return radios;
};
$.widget("ui.button", {
version: "1.10.3",
defaultElement: "<button>",
options: {
disabled: null,
text: true,
label: null,
icons: {
primary: null,
secondary: null
}
},
_create: function() {
this.element.closest("form")
.unbind("reset" + this.eventNamespace)
.bind("reset" + this.eventNamespace, formResetHandler);
if (typeof this.options.disabled !== "boolean") {
this.options.disabled = !!this.element.prop("disabled");
} else {
this.element.prop("disabled", this.options.disabled);
}
this._determineButtonType();
this.hasTitle = !!this.buttonElement.attr("title");
var that = this,
options = this.options,
toggleButton = this.type === "checkbox" || this.type === "radio",
activeClass = !toggleButton ? "ui-state-active" : "",
focusClass = "ui-state-focus";
if (options.label === null) {
options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html());
}
this._hoverable(this.buttonElement);
this.buttonElement
.addClass(baseClasses)
.attr("role", "button")
.bind("mouseenter" + this.eventNamespace, function() {
if (options.disabled) {
return;
}
if (this === lastActive) {
$(this).addClass("ui-state-active");
}
})
.bind("mouseleave" + this.eventNamespace, function() {
if (options.disabled) {
return;
}
$(this).removeClass(activeClass);
})
.bind("click" + this.eventNamespace, function(event) {
if (options.disabled) {
event.preventDefault();
event.stopImmediatePropagation();
}
});
this.element
.bind("focus" + this.eventNamespace, function() {
// no need to check disabled, focus won't be triggered anyway
that.buttonElement.addClass(focusClass);
})
.bind("blur" + this.eventNamespace, function() {
that.buttonElement.removeClass(focusClass);
});
if (toggleButton) {
this.element.bind("change" + this.eventNamespace, function() {
if (clickDragged) {
return;
}
that.refresh();
});
// if mouse moves between mousedown and mouseup (drag) set clickDragged flag
// prevents issue where button state changes but checkbox/radio checked state
// does not in Firefox (see ticket #6970)
this.buttonElement
.bind("mousedown" + this.eventNamespace, function(event) {
if (options.disabled) {
return;
}
clickDragged = false;
startXPos = event.pageX;
startYPos = event.pageY;
})
.bind("mouseup" + this.eventNamespace, function(event) {
if (options.disabled) {
return;
}
if (startXPos !== event.pageX || startYPos !== event.pageY) {
clickDragged = true;
}
});
}
if (this.type === "checkbox") {
this.buttonElement.bind("click" + this.eventNamespace, function() {
if (options.disabled || clickDragged) {
return false;
}
});
} else if (this.type === "radio") {
this.buttonElement.bind("click" + this.eventNamespace, function() {
if (options.disabled || clickDragged) {
return false;
}
$(this).addClass("ui-state-active");
that.buttonElement.attr("aria-pressed", "true");
var radio = that.element[ 0 ];
radioGroup(radio)
.not(radio)
.map(function() {
return $(this).button("widget")[ 0 ];
})
.removeClass("ui-state-active")
.attr("aria-pressed", "false");
});
} else {
this.buttonElement
.bind("mousedown" + this.eventNamespace, function() {
if (options.disabled) {
return false;
}
$(this).addClass("ui-state-active");
lastActive = this;
that.document.one("mouseup", function() {
lastActive = null;
});
})
.bind("mouseup" + this.eventNamespace, function() {
if (options.disabled) {
return false;
}
$(this).removeClass("ui-state-active");
})
.bind("keydown" + this.eventNamespace, function(event) {
if (options.disabled) {
return false;
}
if (event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER) {
$(this).addClass("ui-state-active");
}
})
// see #8559, we bind to blur here in case the button element loses
// focus between keydown and keyup, it would be left in an "active" state
.bind("keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() {
$(this).removeClass("ui-state-active");
});
if (this.buttonElement.is("a")) {
this.buttonElement.keyup(function(event) {
if (event.keyCode === $.ui.keyCode.SPACE) {
// TODO pass through original event correctly (just as 2nd argument doesn't work)
$(this).click();
}
});
}
}
// TODO: pull out $.Widget's handling for the disabled option into
// $.Widget.prototype._setOptionDisabled so it's easy to proxy and can
// be overridden by individual plugins
this._setOption("disabled", options.disabled);
this._resetButton();
},
_determineButtonType: function() {
var ancestor, labelSelector, checked;
if (this.element.is("[type=checkbox]")) {
this.type = "checkbox";
} else if (this.element.is("[type=radio]")) {
this.type = "radio";
} else if (this.element.is("input")) {
this.type = "input";
} else {
this.type = "button";
}
if (this.type === "checkbox" || this.type === "radio") {
// we don't search against the document in case the element
// is disconnected from the DOM
ancestor = this.element.parents().last();
labelSelector = "label[for='" + this.element.attr("id") + "']";
this.buttonElement = ancestor.find(labelSelector);
if (!this.buttonElement.length) {
ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings();
this.buttonElement = ancestor.filter(labelSelector);
if (!this.buttonElement.length) {
this.buttonElement = ancestor.find(labelSelector);
}
}
this.element.addClass("ui-helper-hidden-accessible");
checked = this.element.is(":checked");
if (checked) {
this.buttonElement.addClass("ui-state-active");
}
this.buttonElement.prop("aria-pressed", checked);
} else {
this.buttonElement = this.element;
}
},
widget: function() {
return this.buttonElement;
},
_destroy: function() {
this.element
.removeClass("ui-helper-hidden-accessible");
this.buttonElement
.removeClass(baseClasses + " " + stateClasses + " " + typeClasses)
.removeAttr("role")
.removeAttr("aria-pressed")
.html(this.buttonElement.find(".ui-button-text").html());
if (!this.hasTitle) {
this.buttonElement.removeAttr("title");
}
},
_setOption: function(key, value) {
this._super(key, value);
if (key === "disabled") {
if (value) {
this.element.prop("disabled", true);
} else {
this.element.prop("disabled", false);
}
return;
}
this._resetButton();
},
refresh: function() {
//See #8237 & #8828
var isDisabled = this.element.is("input, button") ? this.element.is(":disabled") : this.element.hasClass("ui-button-disabled");
if (isDisabled !== this.options.disabled) {
this._setOption("disabled", isDisabled);
}
if (this.type === "radio") {
radioGroup(this.element[0]).each(function() {
if ($(this).is(":checked")) {
$(this).button("widget")
.addClass("ui-state-active")
.attr("aria-pressed", "true");
} else {
$(this).button("widget")
.removeClass("ui-state-active")
.attr("aria-pressed", "false");
}
});
} else if (this.type === "checkbox") {
if (this.element.is(":checked")) {
this.buttonElement
.addClass("ui-state-active")
.attr("aria-pressed", "true");
} else {
this.buttonElement
.removeClass("ui-state-active")
.attr("aria-pressed", "false");
}
}
},
_resetButton: function() {
if (this.type === "input") {
if (this.options.label) {
this.element.val(this.options.label);
}
return;
}
var buttonElement = this.buttonElement.removeClass(typeClasses),
buttonText = $("<span></span>", this.document[0])
.addClass("ui-button-text")
.html(this.options.label)
.appendTo(buttonElement.empty())
.text(),
icons = this.options.icons,
multipleIcons = icons.primary && icons.secondary,
buttonClasses = [];
if (icons.primary || icons.secondary) {
if (this.options.text) {
buttonClasses.push("ui-button-text-icon" + (multipleIcons ? "s" : (icons.primary ? "-primary" : "-secondary")));
}
if (icons.primary) {
buttonElement.prepend("<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>");
}
if (icons.secondary) {
buttonElement.append("<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>");
}
if (!this.options.text) {
buttonClasses.push(multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only");
if (!this.hasTitle) {
buttonElement.attr("title", $.trim(buttonText));
}
}
} else {
buttonClasses.push("ui-button-text-only");
}
buttonElement.addClass(buttonClasses.join(" "));
}
});
$.widget("ui.buttonset", {
version: "1.10.3",
options: {
items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"
},
_create: function() {
this.element.addClass("ui-buttonset");
},
_init: function() {
this.refresh();
},
_setOption: function(key, value) {
if (key === "disabled") {
this.buttons.button("option", key, value);
}
this._super(key, value);
},
refresh: function() {
var rtl = this.element.css("direction") === "rtl";
this.buttons = this.element.find(this.options.items)
.filter(":ui-button")
.button("refresh")
.end()
.not(":ui-button")
.button()
.end()
.map(function() {
return $(this).button("widget")[ 0 ];
})
.removeClass("ui-corner-all ui-corner-left ui-corner-right")
.filter(":first")
.addClass(rtl ? "ui-corner-right" : "ui-corner-left")
.end()
.filter(":last")
.addClass(rtl ? "ui-corner-left" : "ui-corner-right")
.end()
.end();
},
_destroy: function() {
this.element.removeClass("ui-buttonset");
this.buttons
.map(function() {
return $(this).button("widget")[ 0 ];
})
.removeClass("ui-corner-left ui-corner-right")
.end()
.button("destroy");
}
});
}(jQuery));
(function($, undefined) {
$.extend($.ui, {datepicker: {version: "1.10.3"}});
var PROP_NAME = "datepicker",
instActive;
/* Date picker manager.
Use the singleton instance of this class, $.datepicker, to interact with the date picker.
Settings for (groups of) date pickers are maintained in an instance object,
allowing multiple different settings on the same page. */
function Datepicker() {
this._curInst = null; // The current instance in use
this._keyEvent = false; // If the last event was a key event
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
this._appendClass = "ui-datepicker-append"; // The name of the append marker class
this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[""] = {// Default regional settings
closeText: "Done", // Display text for close link
prevText: "Prev", // Display text for previous month link
nextText: "Next", // Display text for next month link
currentText: "Today", // Display text for current month link
monthNames: ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"], // Names of months for drop-down and formatting
monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting
dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting
dayNamesMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], // Column headings for days starting at Sunday
weekHeader: "Wk", // Column header for week of the year
dateFormat: "mm/dd/yy", // See format options on parseDate
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
isRTL: false, // True if right-to-left language, false if left-to-right
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearSuffix: "" // Additional text to append to the year in the month headers
};
this._defaults = {// Global defaults for all the date picker instances
showOn: "focus", // "focus" for popup on focus,
// "button" for trigger button, or "both" for either
showAnim: "fadeIn", // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
appendText: "", // Display text following the input box, e.g. showing the format
buttonText: "...", // Text for trigger button
buttonImage: "", // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
gotoCurrent: false, // True if today link goes back to current selection instead
changeMonth: false, // True if month can be selected directly, false if only prev/next
changeYear: false, // True if year can be selected directly, false if only prev/next
yearRange: "c-10:c+10", // Range of years to display in drop-down,
// either relative to today's year (-nn:+nn), relative to currently displayed year
// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
showOtherMonths: false, // True to show dates in other months, false to leave blank
selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
showWeek: false, // True to show week of the year, false to not show it
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: "+10", // Short year values < this are in the current century,
// > this are in the previous century,
// string value starting with "+" for current year + value
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
duration: "fast", // Duration of display/closure
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
// [2] = cell title (optional), e.g. $.datepicker.noWeekends
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onChangeMonthYear: null, // Define a callback function when the month or year is changed
onClose: null, // Define a callback function when the datepicker is closed
numberOfMonths: 1, // Number of months to show at a time
showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
stepMonths: 1, // Number of months to step back/forward
stepBigMonths: 12, // Number of months to step back/forward for the big links
altField: "", // Selector for an alternate field to store selected dates into
altFormat: "", // The date format to use for the alternate field
constrainInput: true, // The input is constrained by the current date format
showButtonPanel: false, // True to show button panel, false to not show it
autoSize: false, // True to size the input for the date format, false to leave as is
disabled: false // The initial disabled state
};
$.extend(this._defaults, this.regional[""]);
this.dpDiv = bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));
}
$.extend(Datepicker.prototype, {
/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: "hasDatepicker",
//Keep track of the maximum number of rows displayed (see #7043)
maxRows: 4,
// TODO rename to "widget" when switching to widget factory
_widgetDatepicker: function() {
return this.dpDiv;
},
/* Override the default settings for all instances of the date picker.
* @param settings object - the new settings to use as defaults (anonymous object)
* @return the manager object
*/
setDefaults: function(settings) {
extendRemove(this._defaults, settings || {});
return this;
},
/* Attach the date picker to a jQuery selection.
* @param target element - the target input field or division or span
* @param settings object - the new settings to use for this date picker instance (anonymous)
*/
_attachDatepicker: function(target, settings) {
var nodeName, inline, inst;
nodeName = target.nodeName.toLowerCase();
inline = (nodeName === "div" || nodeName === "span");
if (!target.id) {
this.uuid += 1;
target.id = "dp" + this.uuid;
}
inst = this._newInst($(target), inline);
inst.settings = $.extend({}, settings || {});
if (nodeName === "input") {
this._connectDatepicker(target, inst);
} else if (inline) {
this._inlineDatepicker(target, inst);
}
},
/* Create a new instance object. */
_newInst: function(target, inline) {
var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars
return {id: id, input: target, // associated target
selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
drawMonth: 0, drawYear: 0, // month being drawn
inline: inline, // is datepicker inline or not
dpDiv: (!inline ? this.dpDiv : // presentation div
bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))};
},
/* Attach the date picker to an input field. */
_connectDatepicker: function(target, inst) {
var input = $(target);
inst.append = $([]);
inst.trigger = $([]);
if (input.hasClass(this.markerClassName)) {
return;
}
this._attachments(input, inst);
input.addClass(this.markerClassName).keydown(this._doKeyDown).
keypress(this._doKeyPress).keyup(this._doKeyUp);
this._autoSize(inst);
$.data(target, PROP_NAME, inst);
//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
if (inst.settings.disabled) {
this._disableDatepicker(target);
}
},
/* Make attachments based on settings. */
_attachments: function(input, inst) {
var showOn, buttonText, buttonImage,
appendText = this._get(inst, "appendText"),
isRTL = this._get(inst, "isRTL");
if (inst.append) {
inst.append.remove();
}
if (appendText) {
inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
input[isRTL ? "before" : "after"](inst.append);
}
input.unbind("focus", this._showDatepicker);
if (inst.trigger) {
inst.trigger.remove();
}
showOn = this._get(inst, "showOn");
if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field
input.focus(this._showDatepicker);
}
if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked
buttonText = this._get(inst, "buttonText");
buttonImage = this._get(inst, "buttonImage");
inst.trigger = $(this._get(inst, "buttonImageOnly") ?
$("<img/>").addClass(this._triggerClass).
attr({src: buttonImage, alt: buttonText, title: buttonText}) :
$("<button type='button'></button>").addClass(this._triggerClass).
html(!buttonImage ? buttonText : $("<img/>").attr(
{src: buttonImage, alt: buttonText, title: buttonText})));
input[isRTL ? "before" : "after"](inst.trigger);
inst.trigger.click(function() {
if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) {
$.datepicker._hideDatepicker();
} else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) {
$.datepicker._hideDatepicker();
$.datepicker._showDatepicker(input[0]);
} else {
$.datepicker._showDatepicker(input[0]);
}
return false;
});
}
},
/* Apply the maximum length for the date format. */
_autoSize: function(inst) {
if (this._get(inst, "autoSize") && !inst.inline) {
var findMax, max, maxI, i,
date = new Date(2009, 12 - 1, 20), // Ensure double digits
dateFormat = this._get(inst, "dateFormat");
if (dateFormat.match(/[DM]/)) {
findMax = function(names) {
max = 0;
maxI = 0;
for (i = 0; i < names.length; i++) {
if (names[i].length > max) {
max = names[i].length;
maxI = i;
}
}
return maxI;
};
date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
"monthNames" : "monthNamesShort"))));
date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
"dayNames" : "dayNamesShort"))) + 20 - date.getDay());
}
inst.input.attr("size", this._formatDate(inst, date).length);
}
},
/* Attach an inline date picker to a div. */
_inlineDatepicker: function(target, inst) {
var divSpan = $(target);
if (divSpan.hasClass(this.markerClassName)) {
return;
}
divSpan.addClass(this.markerClassName).append(inst.dpDiv);
$.data(target, PROP_NAME, inst);
this._setDate(inst, this._getDefaultDate(inst), true);
this._updateDatepicker(inst);
this._updateAlternate(inst);
//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
if (inst.settings.disabled) {
this._disableDatepicker(target);
}
// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
inst.dpDiv.css("display", "block");
},
/* Pop-up the date picker in a "dialog" box.
* @param input element - ignored
* @param date string or Date - the initial date to display
* @param onSelect function - the function to call when a date is selected
* @param settings object - update the dialog date picker instance's settings (anonymous object)
* @param pos int[2] - coordinates for the dialog's position within the screen or
* event - with x/y coordinates or
* leave empty for default (screen centre)
* @return the manager object
*/
_dialogDatepicker: function(input, date, onSelect, settings, pos) {
var id, browserWidth, browserHeight, scrollX, scrollY,
inst = this._dialogInst; // internal instance
if (!inst) {
this.uuid += 1;
id = "dp" + this.uuid;
this._dialogInput = $("<input type='text' id='" + id +
"' style='position: absolute; top: -100px; width: 0px;'/>");
this._dialogInput.keydown(this._doKeyDown);
$("body").append(this._dialogInput);
inst = this._dialogInst = this._newInst(this._dialogInput, false);
inst.settings = {};
$.data(this._dialogInput[0], PROP_NAME, inst);
}
extendRemove(inst.settings, settings || {});
date = (date && date.constructor === Date ? this._formatDate(inst, date) : date);
this._dialogInput.val(date);
this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
if (!this._pos) {
browserWidth = document.documentElement.clientWidth;
browserHeight = document.documentElement.clientHeight;
scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
scrollY = document.documentElement.scrollTop || document.body.scrollTop;
this._pos = // should use actual width/height below
[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
}
// move input on screen for focus, but hidden behind dialog
this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px");
inst.settings.onSelect = onSelect;
this._inDialog = true;
this.dpDiv.addClass(this._dialogClass);
this._showDatepicker(this._dialogInput[0]);
if ($.blockUI) {
$.blockUI(this.dpDiv);
}
$.data(this._dialogInput[0], PROP_NAME, inst);
return this;
},
/* Detach a datepicker from its control.
* @param target element - the target input field or division or span
*/
_destroyDatepicker: function(target) {
var nodeName,
$target = $(target),
inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
$.removeData(target, PROP_NAME);
if (nodeName === "input") {
inst.append.remove();
inst.trigger.remove();
$target.removeClass(this.markerClassName).
unbind("focus", this._showDatepicker).
unbind("keydown", this._doKeyDown).
unbind("keypress", this._doKeyPress).
unbind("keyup", this._doKeyUp);
} else if (nodeName === "div" || nodeName === "span") {
$target.removeClass(this.markerClassName).empty();
}
},
/* Enable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_enableDatepicker: function(target) {
var nodeName, inline,
$target = $(target),
inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
if (nodeName === "input") {
target.disabled = false;
inst.trigger.filter("button").
each(function() {
this.disabled = false;
}).end().
filter("img").css({opacity: "1.0", cursor: ""});
} else if (nodeName === "div" || nodeName === "span") {
inline = $target.children("." + this._inlineClass);
inline.children().removeClass("ui-state-disabled");
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
prop("disabled", false);
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) {
return (value === target ? null : value);
}); // delete entry
},
/* Disable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_disableDatepicker: function(target) {
var nodeName, inline,
$target = $(target),
inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
if (nodeName === "input") {
target.disabled = true;
inst.trigger.filter("button").
each(function() {
this.disabled = true;
}).end().
filter("img").css({opacity: "0.5", cursor: "default"});
} else if (nodeName === "div" || nodeName === "span") {
inline = $target.children("." + this._inlineClass);
inline.children().addClass("ui-state-disabled");
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
prop("disabled", true);
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) {
return (value === target ? null : value);
}); // delete entry
this._disabledInputs[this._disabledInputs.length] = target;
},
/* Is the first field in a jQuery collection disabled as a datepicker?
* @param target element - the target input field or division or span
* @return boolean - true if disabled, false if enabled
*/
_isDisabledDatepicker: function(target) {
if (!target) {
return false;
}
for (var i = 0; i < this._disabledInputs.length; i++) {
if (this._disabledInputs[i] === target) {
return true;
}
}
return false;
},
/* Retrieve the instance data for the target control.
* @param target element - the target input field or division or span
* @return object - the associated instance data
* @throws error if a jQuery problem getting data
*/
_getInst: function(target) {
try {
return $.data(target, PROP_NAME);
}
catch (err) {
throw "Missing instance data for this datepicker";
}
},
/* Update or retrieve the settings for a date picker attached to an input field or division.
* @param target element - the target input field or division or span
* @param name object - the new settings to update or
* string - the name of the setting to change or retrieve,
* when retrieving also "all" for all instance settings or
* "defaults" for all global defaults
* @param value any - the new value for the setting
* (omit if above is an object or to retrieve a value)
*/
_optionDatepicker: function(target, name, value) {
var settings, date, minDate, maxDate,
inst = this._getInst(target);
if (arguments.length === 2 && typeof name === "string") {
return (name === "defaults" ? $.extend({}, $.datepicker._defaults) :
(inst ? (name === "all" ? $.extend({}, inst.settings) :
this._get(inst, name)) : null));
}
settings = name || {};
if (typeof name === "string") {
settings = {};
settings[name] = value;
}
if (inst) {
if (this._curInst === inst) {
this._hideDatepicker();
}
date = this._getDateDatepicker(target, true);
minDate = this._getMinMaxDate(inst, "min");
maxDate = this._getMinMaxDate(inst, "max");
extendRemove(inst.settings, settings);
// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) {
inst.settings.minDate = this._formatDate(inst, minDate);
}
if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) {
inst.settings.maxDate = this._formatDate(inst, maxDate);
}
if ("disabled" in settings) {
if (settings.disabled) {
this._disableDatepicker(target);
} else {
this._enableDatepicker(target);
}
}
this._attachments($(target), inst);
this._autoSize(inst);
this._setDate(inst, date);
this._updateAlternate(inst);
this._updateDatepicker(inst);
}
},
// change method deprecated
_changeDatepicker: function(target, name, value) {
this._optionDatepicker(target, name, value);
},
/* Redraw the date picker attached to an input field or division.
* @param target element - the target input field or division or span
*/
_refreshDatepicker: function(target) {
var inst = this._getInst(target);
if (inst) {
this._updateDatepicker(inst);
}
},
/* Set the dates for a jQuery selection.
* @param target element - the target input field or division or span
* @param date Date - the new date
*/
_setDateDatepicker: function(target, date) {
var inst = this._getInst(target);
if (inst) {
this._setDate(inst, date);
this._updateDatepicker(inst);
this._updateAlternate(inst);
}
},
/* Get the date(s) for the first entry in a jQuery selection.
* @param target element - the target input field or division or span
* @param noDefault boolean - true if no default date is to be used
* @return Date - the current date
*/
_getDateDatepicker: function(target, noDefault) {
var inst = this._getInst(target);
if (inst && !inst.inline) {
this._setDateFromField(inst, noDefault);
}
return (inst ? this._getDate(inst) : null);
},
/* Handle keystrokes. */
_doKeyDown: function(event) {
var onSelect, dateStr, sel,
inst = $.datepicker._getInst(event.target),
handled = true,
isRTL = inst.dpDiv.is(".ui-datepicker-rtl");
inst._keyEvent = true;
if ($.datepicker._datepickerShowing) {
switch (event.keyCode) {
case 9:
$.datepicker._hideDatepicker();
handled = false;
break; // hide on tab out
case 13:
sel = $("td." + $.datepicker._dayOverClass + ":not(." +
$.datepicker._currentClass + ")", inst.dpDiv);
if (sel[0]) {
$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
}
onSelect = $.datepicker._get(inst, "onSelect");
if (onSelect) {
dateStr = $.datepicker._formatDate(inst);
// trigger custom callback
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
} else {
$.datepicker._hideDatepicker();
}
return false; // don't submit the form
case 27:
$.datepicker._hideDatepicker();
break; // hide on escape
case 33:
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, "stepBigMonths") :
-$.datepicker._get(inst, "stepMonths")), "M");
break; // previous month/year on page up/+ ctrl
case 34:
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, "stepBigMonths") :
+$.datepicker._get(inst, "stepMonths")), "M");
break; // next month/year on page down/+ ctrl
case 35:
if (event.ctrlKey || event.metaKey) {
$.datepicker._clearDate(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // clear on ctrl or command +end
case 36:
if (event.ctrlKey || event.metaKey) {
$.datepicker._gotoToday(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // current on ctrl or command +home
case 37:
if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
}
handled = event.ctrlKey || event.metaKey;
// -1 day on ctrl or command +left
if (event.originalEvent.altKey) {
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, "stepBigMonths") :
-$.datepicker._get(inst, "stepMonths")), "M");
}
// next month/year on alt +left on Mac
break;
case 38:
if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, -7, "D");
}
handled = event.ctrlKey || event.metaKey;
break; // -1 week on ctrl or command +up
case 39:
if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
}
handled = event.ctrlKey || event.metaKey;
// +1 day on ctrl or command +right
if (event.originalEvent.altKey) {
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, "stepBigMonths") :
+$.datepicker._get(inst, "stepMonths")), "M");
}
// next month/year on alt +right
break;
case 40:
if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, +7, "D");
}
handled = event.ctrlKey || event.metaKey;
break; // +1 week on ctrl or command +down
default:
handled = false;
}
} else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
$.datepicker._showDatepicker(this);
} else {
handled = false;
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
},
/* Filter entered characters - based on date format. */
_doKeyPress: function(event) {
var chars, chr,
inst = $.datepicker._getInst(event.target);
if ($.datepicker._get(inst, "constrainInput")) {
chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat"));
chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode);
return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1);
}
},
/* Synchronise manual entry and field/alternate field. */
_doKeyUp: function(event) {
var date,
inst = $.datepicker._getInst(event.target);
if (inst.input.val() !== inst.lastVal) {
try {
date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
(inst.input ? inst.input.val() : null),
$.datepicker._getFormatConfig(inst));
if (date) { // only if valid
$.datepicker._setDateFromField(inst);
$.datepicker._updateAlternate(inst);
$.datepicker._updateDatepicker(inst);
}
}
catch (err) {
}
}
return true;
},
/* Pop-up the date picker for a given input field.
* If false returned from beforeShow event handler do not show.
* @param input element - the input field attached to the date picker or
* event - if triggered by focus
*/
_showDatepicker: function(input) {
input = input.target || input;
if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger
input = $("input", input.parentNode)[0];
}
if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here
return;
}
var inst, beforeShow, beforeShowSettings, isFixed,
offset, showAnim, duration;
inst = $.datepicker._getInst(input);
if ($.datepicker._curInst && $.datepicker._curInst !== inst) {
$.datepicker._curInst.dpDiv.stop(true, true);
if (inst && $.datepicker._datepickerShowing) {
$.datepicker._hideDatepicker($.datepicker._curInst.input[0]);
}
}
beforeShow = $.datepicker._get(inst, "beforeShow");
beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
if (beforeShowSettings === false) {
return;
}
extendRemove(inst.settings, beforeShowSettings);
inst.lastVal = null;
$.datepicker._lastInput = input;
$.datepicker._setDateFromField(inst);
if ($.datepicker._inDialog) { // hide cursor
input.value = "";
}
if (!$.datepicker._pos) { // position below input
$.datepicker._pos = $.datepicker._findPos(input);
$.datepicker._pos[1] += input.offsetHeight; // add the height
}
isFixed = false;
$(input).parents().each(function() {
isFixed |= $(this).css("position") === "fixed";
return !isFixed;
});
offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
$.datepicker._pos = null;
//to avoid flashes on Firefox
inst.dpDiv.empty();
// determine sizing offscreen
inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"});
$.datepicker._updateDatepicker(inst);
// fix width for dynamic number of date pickers
// and adjust position before showing
offset = $.datepicker._checkOffset(inst, offset, isFixed);
inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
"static" : (isFixed ? "fixed" : "absolute")), display: "none",
left: offset.left + "px", top: offset.top + "px"});
if (!inst.inline) {
showAnim = $.datepicker._get(inst, "showAnim");
duration = $.datepicker._get(inst, "duration");
inst.dpDiv.zIndex($(input).zIndex() + 1);
$.datepicker._datepickerShowing = true;
if ($.effects && $.effects.effect[ showAnim ]) {
inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration);
} else {
inst.dpDiv[showAnim || "show"](showAnim ? duration : null);
}
if ($.datepicker._shouldFocusInput(inst)) {
inst.input.focus();
}
$.datepicker._curInst = inst;
}
},
/* Generate the date picker content. */
_updateDatepicker: function(inst) {
this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
instActive = inst; // for delegate hover events
inst.dpDiv.empty().append(this._generateHTML(inst));
this._attachHandlers(inst);
inst.dpDiv.find("." + this._dayOverClass + " a").mouseover();
var origyearshtml,
numMonths = this._getNumberOfMonths(inst),
cols = numMonths[1],
width = 17;
inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");
if (cols > 1) {
inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");
}
inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") +
"Class"]("ui-datepicker-multi");
inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") +
"Class"]("ui-datepicker-rtl");
if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput(inst)) {
inst.input.focus();
}
// deffered render of the years select (to avoid flashes on Firefox)
if (inst.yearshtml) {
origyearshtml = inst.yearshtml;
setTimeout(function() {
//assure that inst.yearshtml didn't change.
if (origyearshtml === inst.yearshtml && inst.yearshtml) {
inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml);
}
origyearshtml = inst.yearshtml = null;
}, 0);
}
},
// #6694 - don't focus the input if it's already focused
// this breaks the change event in IE
// Support: IE and jQuery <1.9
_shouldFocusInput: function(inst) {
return inst.input && inst.input.is(":visible") && !inst.input.is(":disabled") && !inst.input.is(":focus");
},
/* Check positioning to remain on screen. */
_checkOffset: function(inst, offset, isFixed) {
var dpWidth = inst.dpDiv.outerWidth(),
dpHeight = inst.dpDiv.outerHeight(),
inputWidth = inst.input ? inst.input.outerWidth() : 0,
inputHeight = inst.input ? inst.input.outerHeight() : 0,
viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());
offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
// now check if datepicker is showing outside window viewport - move to a better place if so.
offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
Math.abs(offset.left + dpWidth - viewWidth) : 0);
offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
Math.abs(dpHeight + inputHeight) : 0);
return offset;
},
/* Find an object's position on the screen. */
_findPos: function(obj) {
var position,
inst = this._getInst(obj),
isRTL = this._get(inst, "isRTL");
while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
obj = obj[isRTL ? "previousSibling" : "nextSibling"];
}
position = $(obj).offset();
return [position.left, position.top];
},
/* Hide the date picker from view.
* @param input element - the input field attached to the date picker
*/
_hideDatepicker: function(input) {
var showAnim, duration, postProcess, onClose,
inst = this._curInst;
if (!inst || (input && inst !== $.data(input, PROP_NAME))) {
return;
}
if (this._datepickerShowing) {
showAnim = this._get(inst, "showAnim");
duration = this._get(inst, "duration");
postProcess = function() {
$.datepicker._tidyDialog(inst);
};
// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
if ($.effects && ($.effects.effect[ showAnim ] || $.effects[ showAnim ])) {
inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess);
} else {
inst.dpDiv[(showAnim === "slideDown" ? "slideUp" :
(showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess);
}
if (!showAnim) {
postProcess();
}
this._datepickerShowing = false;
onClose = this._get(inst, "onClose");
if (onClose) {
onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]);
}
this._lastInput = null;
if (this._inDialog) {
this._dialogInput.css({position: "absolute", left: "0", top: "-100px"});
if ($.blockUI) {
$.unblockUI();
$("body").append(this.dpDiv);
}
}
this._inDialog = false;
}
},
/* Tidy up after a dialog display. */
_tidyDialog: function(inst) {
inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar");
},
/* Close date picker if clicked elsewhere. */
_checkExternalClick: function(event) {
if (!$.datepicker._curInst) {
return;
}
var $target = $(event.target),
inst = $.datepicker._getInst($target[0]);
if ((($target[0].id !== $.datepicker._mainDivId &&
$target.parents("#" + $.datepicker._mainDivId).length === 0 &&
!$target.hasClass($.datepicker.markerClassName) &&
!$target.closest("." + $.datepicker._triggerClass).length &&
$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))) ||
($target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst)) {
$.datepicker._hideDatepicker();
}
},
/* Adjust one of the date sub-fields. */
_adjustDate: function(id, offset, period) {
var target = $(id),
inst = this._getInst(target[0]);
if (this._isDisabledDatepicker(target[0])) {
return;
}
this._adjustInstDate(inst, offset +
(period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
period);
this._updateDatepicker(inst);
},
/* Action for current link. */
_gotoToday: function(id) {
var date,
target = $(id),
inst = this._getInst(target[0]);
if (this._get(inst, "gotoCurrent") && inst.currentDay) {
inst.selectedDay = inst.currentDay;
inst.drawMonth = inst.selectedMonth = inst.currentMonth;
inst.drawYear = inst.selectedYear = inst.currentYear;
} else {
date = new Date();
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
}
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a new month/year. */
_selectMonthYear: function(id, select, period) {
var target = $(id),
inst = this._getInst(target[0]);
inst["selected" + (period === "M" ? "Month" : "Year")] =
inst["draw" + (period === "M" ? "Month" : "Year")] =
parseInt(select.options[select.selectedIndex].value, 10);
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a day. */
_selectDay: function(id, month, year, td) {
var inst,
target = $(id);
if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
return;
}
inst = this._getInst(target[0]);
inst.selectedDay = inst.currentDay = $("a", td).html();
inst.selectedMonth = inst.currentMonth = month;
inst.selectedYear = inst.currentYear = year;
this._selectDate(id, this._formatDate(inst,
inst.currentDay, inst.currentMonth, inst.currentYear));
},
/* Erase the input field and hide the date picker. */
_clearDate: function(id) {
var target = $(id);
this._selectDate(target, "");
},
/* Update the input field with the selected date. */
_selectDate: function(id, dateStr) {
var onSelect,
target = $(id),
inst = this._getInst(target[0]);
dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
if (inst.input) {
inst.input.val(dateStr);
}
this._updateAlternate(inst);
onSelect = this._get(inst, "onSelect");
if (onSelect) {
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
} else if (inst.input) {
inst.input.trigger("change"); // fire the change event
}
if (inst.inline) {
this._updateDatepicker(inst);
} else {
this._hideDatepicker();
this._lastInput = inst.input[0];
if (typeof(inst.input[0]) !== "object") {
inst.input.focus(); // restore focus
}
this._lastInput = null;
}
},
/* Update any alternate field to synchronise with the main field. */
_updateAlternate: function(inst) {
var altFormat, date, dateStr,
altField = this._get(inst, "altField");
if (altField) { // update alternate field too
altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
date = this._getDate(inst);
dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
$(altField).each(function() {
$(this).val(dateStr);
});
}
},
/* Set as beforeShowDay function to prevent selection of weekends.
* @param date Date - the date to customise
* @return [boolean, string] - is this date selectable?, what is its CSS class?
*/
noWeekends: function(date) {
var day = date.getDay();
return [(day > 0 && day < 6), ""];
},
/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
* @param date Date - the date to get the week for
* @return number - the number of the week within the year that contains this date
*/
iso8601Week: function(date) {
var time,
checkDate = new Date(date.getTime());
// Find Thursday of this week starting on Monday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
},
/* Parse a string value into a date object.
* See formatDate below for the possible formats.
*
* @param format string - the expected format of the date
* @param value string - the date in the above format
* @param settings Object - attributes include:
* shortYearCutoff number - the cutoff year for determining the century (optional)
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return Date - the extracted date value or null if value is blank
*/
parseDate: function(format, value, settings) {
if (format == null || value == null) {
throw "Invalid arguments";
}
value = (typeof value === "object" ? value.toString() : value + "");
if (value === "") {
return null;
}
var iFormat, dim, extra,
iValue = 0,
shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff,
shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)),
dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
year = -1,
month = -1,
day = -1,
doy = -1,
literal = false,
date,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
},
// Extract a number from the string value
getNumber = function(match) {
var isDoubled = lookAhead(match),
size = (match === "@" ? 14 : (match === "!" ? 20 :
(match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))),
digits = new RegExp("^\\d{1," + size + "}"),
num = value.substring(iValue).match(digits);
if (!num) {
throw "Missing number at position " + iValue;
}
iValue += num[0].length;
return parseInt(num[0], 10);
},
// Extract a name from the string value and convert to an index
getName = function(match, shortNames, longNames) {
var index = -1,
names = $.map(lookAhead(match) ? longNames : shortNames, function(v, k) {
return [[k, v]];
}).sort(function(a, b) {
return -(a[1].length - b[1].length);
});
$.each(names, function(i, pair) {
var name = pair[1];
if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) {
index = pair[0];
iValue += name.length;
return false;
}
});
if (index !== -1) {
return index + 1;
} else {
throw "Unknown name at position " + iValue;
}
},
// Confirm that a literal character matches the string value
checkLiteral = function() {
if (value.charAt(iValue) !== format.charAt(iFormat)) {
throw "Unexpected literal at position " + iValue;
}
iValue++;
};
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
checkLiteral();
}
} else {
switch (format.charAt(iFormat)) {
case "d":
day = getNumber("d");
break;
case "D":
getName("D", dayNamesShort, dayNames);
break;
case "o":
doy = getNumber("o");
break;
case "m":
month = getNumber("m");
break;
case "M":
month = getName("M", monthNamesShort, monthNames);
break;
case "y":
year = getNumber("y");
break;
case "@":
date = new Date(getNumber("@"));
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "!":
date = new Date((getNumber("!") - this._ticksTo1970) / 10000);
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "'":
if (lookAhead("'")) {
checkLiteral();
} else {
literal = true;
}
break;
default:
checkLiteral();
}
}
}
if (iValue < value.length) {
extra = value.substr(iValue);
if (!/^\s+/.test(extra)) {
throw "Extra/unparsed characters found in date: " + extra;
}
}
if (year === -1) {
year = new Date().getFullYear();
} else if (year < 100) {
year += new Date().getFullYear() - new Date().getFullYear() % 100 +
(year <= shortYearCutoff ? 0 : -100);
}
if (doy > -1) {
month = 1;
day = doy;
do {
dim = this._getDaysInMonth(year, month - 1);
if (day <= dim) {
break;
}
month++;
day -= dim;
} while (true);
}
date = this._daylightSavingAdjust(new Date(year, month - 1, day));
if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
throw "Invalid date"; // E.g. 31/02/00
}
return date;
},
/* Standard date formats. */
ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
COOKIE: "D, dd M yy",
ISO_8601: "yy-mm-dd",
RFC_822: "D, d M y",
RFC_850: "DD, dd-M-y",
RFC_1036: "D, d M y",
RFC_1123: "D, d M yy",
RFC_2822: "D, d M yy",
RSS: "D, d M y", // RFC 822
TICKS: "!",
TIMESTAMP: "@",
W3C: "yy-mm-dd", // ISO 8601
_ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
/* Format a date object into a string value.
* The format can be combinations of the following:
* d - day of month (no leading zero)
* dd - day of month (two digit)
* o - day of year (no leading zeros)
* oo - day of year (three digit)
* D - day name short
* DD - day name long
* m - month of year (no leading zero)
* mm - month of year (two digit)
* M - month name short
* MM - month name long
* y - year (two digit)
* yy - year (four digit)
* @ - Unix timestamp (ms since 01/01/1970)
* ! - Windows ticks (100ns since 01/01/0001)
* "..." - literal text
* '' - single quote
*
* @param format string - the desired format of the date
* @param date Date - the date value to format
* @param settings Object - attributes include:
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return string - the date in the above format
*/
formatDate: function(format, date, settings) {
if (!date) {
return "";
}
var iFormat,
dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
},
// Format a number, with leading zero if necessary
formatNumber = function(match, value, len) {
var num = "" + value;
if (lookAhead(match)) {
while (num.length < len) {
num = "0" + num;
}
}
return num;
},
// Format a name, short or long as requested
formatName = function(match, value, shortNames, longNames) {
return (lookAhead(match) ? longNames[value] : shortNames[value]);
},
output = "",
literal = false;
if (date) {
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
output += format.charAt(iFormat);
}
} else {
switch (format.charAt(iFormat)) {
case "d":
output += formatNumber("d", date.getDate(), 2);
break;
case "D":
output += formatName("D", date.getDay(), dayNamesShort, dayNames);
break;
case "o":
output += formatNumber("o",
Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
break;
case "m":
output += formatNumber("m", date.getMonth() + 1, 2);
break;
case "M":
output += formatName("M", date.getMonth(), monthNamesShort, monthNames);
break;
case "y":
output += (lookAhead("y") ? date.getFullYear() :
(date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100);
break;
case "@":
output += date.getTime();
break;
case "!":
output += date.getTime() * 10000 + this._ticksTo1970;
break;
case "'":
if (lookAhead("'")) {
output += "'";
} else {
literal = true;
}
break;
default:
output += format.charAt(iFormat);
}
}
}
}
return output;
},
/* Extract all possible characters from the date format. */
_possibleChars: function(format) {
var iFormat,
chars = "",
literal = false,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
};
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
chars += format.charAt(iFormat);
}
} else {
switch (format.charAt(iFormat)) {
case "d":
case "m":
case "y":
case "@":
chars += "0123456789";
break;
case "D":
case "M":
return null; // Accept anything
case "'":
if (lookAhead("'")) {
chars += "'";
} else {
literal = true;
}
break;
default:
chars += format.charAt(iFormat);
}
}
}
return chars;
},
/* Get a setting value, defaulting if necessary. */
_get: function(inst, name) {
return inst.settings[name] !== undefined ?
inst.settings[name] : this._defaults[name];
},
/* Parse existing date and initialise date picker. */
_setDateFromField: function(inst, noDefault) {
if (inst.input.val() === inst.lastVal) {
return;
}
var dateFormat = this._get(inst, "dateFormat"),
dates = inst.lastVal = inst.input ? inst.input.val() : null,
defaultDate = this._getDefaultDate(inst),
date = defaultDate,
settings = this._getFormatConfig(inst);
try {
date = this.parseDate(dateFormat, dates, settings) || defaultDate;
} catch (event) {
dates = (noDefault ? "" : dates);
}
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentDay = (dates ? date.getDate() : 0);
inst.currentMonth = (dates ? date.getMonth() : 0);
inst.currentYear = (dates ? date.getFullYear() : 0);
this._adjustInstDate(inst);
},
/* Retrieve the default date shown on opening. */
_getDefaultDate: function(inst) {
return this._restrictMinMax(inst,
this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
},
/* A date may be specified as an exact value or a relative one. */
_determineDate: function(inst, date, defaultDate) {
var offsetNumeric = function(offset) {
var date = new Date();
date.setDate(date.getDate() + offset);
return date;
},
offsetString = function(offset) {
try {
return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
offset, $.datepicker._getFormatConfig(inst));
}
catch (e) {
// Ignore
}
var date = (offset.toLowerCase().match(/^c/) ?
$.datepicker._getDate(inst) : null) || new Date(),
year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
matches = pattern.exec(offset);
while (matches) {
switch (matches[2] || "d") {
case "d" :
case "D" :
day += parseInt(matches[1], 10);
break;
case "w" :
case "W" :
day += parseInt(matches[1], 10) * 7;
break;
case "m" :
case "M" :
month += parseInt(matches[1], 10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
case "y":
case "Y" :
year += parseInt(matches[1], 10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
}
matches = pattern.exec(offset);
}
return new Date(year, month, day);
},
newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
(typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
if (newDate) {
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
}
return this._daylightSavingAdjust(newDate);
},
/* Handle switch to/from daylight saving.
* Hours may be non-zero on daylight saving cut-over:
* > 12 when midnight changeover, but then cannot generate
* midnight datetime, so jump to 1AM, otherwise reset.
* @param date (Date) the date to check
* @return (Date) the corrected date
*/
_daylightSavingAdjust: function(date) {
if (!date) {
return null;
}
date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
return date;
},
/* Set the date(s) directly. */
_setDate: function(inst, date, noChange) {
var clear = !date,
origMonth = inst.selectedMonth,
origYear = inst.selectedYear,
newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
inst.selectedDay = inst.currentDay = newDate.getDate();
inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
this._notifyChange(inst);
}
this._adjustInstDate(inst);
if (inst.input) {
inst.input.val(clear ? "" : this._formatDate(inst));
}
},
/* Retrieve the date(s) directly. */
_getDate: function(inst) {
var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null :
this._daylightSavingAdjust(new Date(
inst.currentYear, inst.currentMonth, inst.currentDay)));
return startDate;
},
/* Attach the onxxx handlers. These are declared statically so
* they work with static code transformers like Caja.
*/
_attachHandlers: function(inst) {
var stepMonths = this._get(inst, "stepMonths"),
id = "#" + inst.id.replace(/\\\\/g, "\\");
inst.dpDiv.find("[data-handler]").map(function() {
var handler = {
prev: function() {
$.datepicker._adjustDate(id, -stepMonths, "M");
},
next: function() {
$.datepicker._adjustDate(id, +stepMonths, "M");
},
hide: function() {
$.datepicker._hideDatepicker();
},
today: function() {
$.datepicker._gotoToday(id);
},
selectDay: function() {
$.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this);
return false;
},
selectMonth: function() {
$.datepicker._selectMonthYear(id, this, "M");
return false;
},
selectYear: function() {
$.datepicker._selectMonthYear(id, this, "Y");
return false;
}
};
$(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]);
});
},
/* Generate the HTML for the current state of the date picker. */
_generateHTML: function(inst) {
var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
printDate, dRow, tbody, daySettings, otherMonth, unselectable,
tempDate = new Date(),
today = this._daylightSavingAdjust(
new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time
isRTL = this._get(inst, "isRTL"),
showButtonPanel = this._get(inst, "showButtonPanel"),
hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"),
navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"),
numMonths = this._getNumberOfMonths(inst),
showCurrentAtPos = this._get(inst, "showCurrentAtPos"),
stepMonths = this._get(inst, "stepMonths"),
isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1),
currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
new Date(inst.currentYear, inst.currentMonth, inst.currentDay))),
minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
drawMonth = inst.drawMonth - showCurrentAtPos,
drawYear = inst.drawYear;
if (drawMonth < 0) {
drawMonth += 12;
drawYear--;
}
if (maxDate) {
maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
drawMonth--;
if (drawMonth < 0) {
drawMonth = 11;
drawYear--;
}
}
}
inst.drawMonth = drawMonth;
inst.drawYear = drawYear;
prevText = this._get(inst, "prevText");
prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
this._getFormatConfig(inst)));
prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
" title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + (isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + (isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));
nextText = this._get(inst, "nextText");
nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
this._getFormatConfig(inst)));
next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
" title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + (isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + (isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));
currentText = this._get(inst, "currentText");
gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today);
currentText = (!navigationAsDateFormat ? currentText :
this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
this._get(inst, "closeText") + "</button>" : "");
buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
(this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";
firstDay = parseInt(this._get(inst, "firstDay"), 10);
firstDay = (isNaN(firstDay) ? 0 : firstDay);
showWeek = this._get(inst, "showWeek");
dayNames = this._get(inst, "dayNames");
dayNamesMin = this._get(inst, "dayNamesMin");
monthNames = this._get(inst, "monthNames");
monthNamesShort = this._get(inst, "monthNamesShort");
beforeShowDay = this._get(inst, "beforeShowDay");
showOtherMonths = this._get(inst, "showOtherMonths");
selectOtherMonths = this._get(inst, "selectOtherMonths");
defaultDate = this._getDefaultDate(inst);
html = "";
dow;
for (row = 0; row < numMonths[0]; row++) {
group = "";
this.maxRows = 4;
for (col = 0; col < numMonths[1]; col++) {
selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
cornerClass = " ui-corner-all";
calender = "";
if (isMultiMonth) {
calender += "<div class='ui-datepicker-group";
if (numMonths[1] > 1) {
switch (col) {
case 0:
calender += " ui-datepicker-group-first";
cornerClass = " ui-corner-" + (isRTL ? "right" : "left");
break;
case numMonths[1] - 1:
calender += " ui-datepicker-group-last";
cornerClass = " ui-corner-" + (isRTL ? "left" : "right");
break;
default:
calender += " ui-datepicker-group-middle";
cornerClass = "";
break;
}
}
calender += "'>";
}
calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
(/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
(/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
"</div><table class='ui-datepicker-calendar'><thead>" +
"<tr>";
thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : "");
for (dow = 0; dow < 7; dow++) { // days of the week
day = (dow + firstDay) % 7;
thead += "<th" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" +
"<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>";
}
calender += thead + "</tr></thead><tbody>";
daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) {
inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
}
leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
this.maxRows = numRows;
printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows
calender += "<tr>";
tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
this._get(inst, "calculateWeek")(printDate) + "</td>");
for (dow = 0; dow < 7; dow++) { // create date picker days
daySettings = (beforeShowDay ?
beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]);
otherMonth = (printDate.getMonth() !== drawMonth);
unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
tbody += "<td class='" +
((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends
(otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months
((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key
(defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?
// or defaultDate is current printedDate and defaultDate is selectedDate
" " + this._dayOverClass : "") + // highlight selected day
(unselectable ? " " + this._unselectableClass + " ui-state-disabled" : "") + // highlight unselectable days
(otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates
(printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day
(printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different)
((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "'") + "'" : "") + // cell title
(unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions
(otherMonth && !showOtherMonths ? " " : // display for other months
(unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
(printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") +
(printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day
(otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months
"' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date
printDate.setDate(printDate.getDate() + 1);
printDate = this._daylightSavingAdjust(printDate);
}
calender += tbody + "</tr>";
}
drawMonth++;
if (drawMonth > 11) {
drawMonth = 0;
drawYear++;
}
calender += "</tbody></table>" + (isMultiMonth ? "</div>" +
((numMonths[0] > 0 && col === numMonths[1] - 1) ? "<div class='ui-datepicker-row-break'></div>" : "") : "");
group += calender;
}
html += group;
}
html += buttonPanel;
inst._keyEvent = false;
return html;
},
/* Generate the month and year header. */
_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort) {
var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
changeMonth = this._get(inst, "changeMonth"),
changeYear = this._get(inst, "changeYear"),
showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
html = "<div class='ui-datepicker-title'>",
monthHtml = "";
// month selection
if (secondary || !changeMonth) {
monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
} else {
inMinYear = (minDate && minDate.getFullYear() === drawYear);
inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
for (month = 0; month < 12; month++) {
if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
monthHtml += "<option value='" + month + "'" +
(month === drawMonth ? " selected='selected'" : "") +
">" + monthNamesShort[month] + "</option>";
}
}
monthHtml += "</select>";
}
if (!showMonthAfterYear) {
html += monthHtml + (secondary || !(changeMonth && changeYear) ? " " : "");
}
// year selection
if (!inst.yearshtml) {
inst.yearshtml = "";
if (secondary || !changeYear) {
html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
} else {
// determine range of years to display
years = this._get(inst, "yearRange").split(":");
thisYear = new Date().getFullYear();
determineYear = function(value) {
var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
(value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
parseInt(value, 10)));
return (isNaN(year) ? thisYear : year);
};
year = determineYear(years[0]);
endYear = Math.max(year, determineYear(years[1] || ""));
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
for (; year <= endYear; year++) {
inst.yearshtml += "<option value='" + year + "'" +
(year === drawYear ? " selected='selected'" : "") +
">" + year + "</option>";
}
inst.yearshtml += "</select>";
html += inst.yearshtml;
inst.yearshtml = null;
}
}
html += this._get(inst, "yearSuffix");
if (showMonthAfterYear) {
html += (secondary || !(changeMonth && changeYear) ? " " : "") + monthHtml;
}
html += "</div>"; // Close datepicker_header
return html;
},
/* Adjust one of the date sub-fields. */
_adjustInstDate: function(inst, offset, period) {
var year = inst.drawYear + (period === "Y" ? offset : 0),
month = inst.drawMonth + (period === "M" ? offset : 0),
day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0),
date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
if (period === "M" || period === "Y") {
this._notifyChange(inst);
}
},
/* Ensure a date is within any min/max bounds. */
_restrictMinMax: function(inst, date) {
var minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
newDate = (minDate && date < minDate ? minDate : date);
return (maxDate && newDate > maxDate ? maxDate : newDate);
},
/* Notify change of month/year. */
_notifyChange: function(inst) {
var onChange = this._get(inst, "onChangeMonthYear");
if (onChange) {
onChange.apply((inst.input ? inst.input[0] : null),
[inst.selectedYear, inst.selectedMonth + 1, inst]);
}
},
/* Determine the number of months to show. */
_getNumberOfMonths: function(inst) {
var numMonths = this._get(inst, "numberOfMonths");
return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths));
},
/* Determine the current maximum date - ensure no time components are set. */
_getMinMaxDate: function(inst, minMax) {
return this._determineDate(inst, this._get(inst, minMax + "Date"), null);
},
/* Find the number of days in a given month. */
_getDaysInMonth: function(year, month) {
return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
},
/* Find the day of the week of the first of a month. */
_getFirstDayOfMonth: function(year, month) {
return new Date(year, month, 1).getDay();
},
/* Determines if we should allow a "next/prev" month display change. */
_canAdjustMonth: function(inst, offset, curYear, curMonth) {
var numMonths = this._getNumberOfMonths(inst),
date = this._daylightSavingAdjust(new Date(curYear,
curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
if (offset < 0) {
date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
}
return this._isInRange(inst, date);
},
/* Is the given date in the accepted range? */
_isInRange: function(inst, date) {
var yearSplit, currentYear,
minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
minYear = null,
maxYear = null,
years = this._get(inst, "yearRange");
if (years) {
yearSplit = years.split(":");
currentYear = new Date().getFullYear();
minYear = parseInt(yearSplit[0], 10);
maxYear = parseInt(yearSplit[1], 10);
if (yearSplit[0].match(/[+\-].*/)) {
minYear += currentYear;
}
if (yearSplit[1].match(/[+\-].*/)) {
maxYear += currentYear;
}
}
return ((!minDate || date.getTime() >= minDate.getTime()) &&
(!maxDate || date.getTime() <= maxDate.getTime()) &&
(!minYear || date.getFullYear() >= minYear) &&
(!maxYear || date.getFullYear() <= maxYear));
},
/* Provide the configuration settings for formatting/parsing. */
_getFormatConfig: function(inst) {
var shortYearCutoff = this._get(inst, "shortYearCutoff");
shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff :
new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
return {shortYearCutoff: shortYearCutoff,
dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"),
monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")};
},
/* Format the given date for display. */
_formatDate: function(inst, day, month, year) {
if (!day) {
inst.currentDay = inst.selectedDay;
inst.currentMonth = inst.selectedMonth;
inst.currentYear = inst.selectedYear;
}
var date = (day ? (typeof day === "object" ? day :
this._daylightSavingAdjust(new Date(year, month, day))) :
this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst));
}
});
/*
* Bind hover events for datepicker elements.
* Done via delegate so the binding only occurs once in the lifetime of the parent div.
* Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
*/
function bindHover(dpDiv) {
var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
return dpDiv.delegate(selector, "mouseout", function() {
$(this).removeClass("ui-state-hover");
if (this.className.indexOf("ui-datepicker-prev") !== -1) {
$(this).removeClass("ui-datepicker-prev-hover");
}
if (this.className.indexOf("ui-datepicker-next") !== -1) {
$(this).removeClass("ui-datepicker-next-hover");
}
})
.delegate(selector, "mouseover", function() {
if (!$.datepicker._isDisabledDatepicker(instActive.inline ? dpDiv.parent()[0] : instActive.input[0])) {
$(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");
$(this).addClass("ui-state-hover");
if (this.className.indexOf("ui-datepicker-prev") !== -1) {
$(this).addClass("ui-datepicker-prev-hover");
}
if (this.className.indexOf("ui-datepicker-next") !== -1) {
$(this).addClass("ui-datepicker-next-hover");
}
}
});
}
/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
$.extend(target, props);
for (var name in props) {
if (props[name] == null) {
target[name] = props[name];
}
}
return target;
}
/* Invoke the datepicker functionality.
@param options string - a command, optionally followed by additional parameters or
Object - settings for attaching new datepicker functionality
@return jQuery object */
$.fn.datepicker = function(options) {
/* Verify an empty collection wasn't passed - Fixes #6976 */
if (!this.length) {
return this;
}
/* Initialise the date picker. */
if (!$.datepicker.initialized) {
$(document).mousedown($.datepicker._checkExternalClick);
$.datepicker.initialized = true;
}
/* Append datepicker main container to body if not exist. */
if ($("#" + $.datepicker._mainDivId).length === 0) {
$("body").append($.datepicker.dpDiv);
}
var otherArgs = Array.prototype.slice.call(arguments, 1);
if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) {
return $.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this[0]].concat(otherArgs));
}
if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") {
return $.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this[0]].concat(otherArgs));
}
return this.each(function() {
typeof options === "string" ?
$.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this].concat(otherArgs)) :
$.datepicker._attachDatepicker(this, options);
});
};
$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.10.3";
})(jQuery);
(function($, undefined) {
var sizeRelatedOptions = {
buttons: true,
height: true,
maxHeight: true,
maxWidth: true,
minHeight: true,
minWidth: true,
width: true
},
resizableRelatedOptions = {
maxHeight: true,
maxWidth: true,
minHeight: true,
minWidth: true
};
$.widget("ui.dialog", {
version: "1.10.3",
options: {
appendTo: "body",
autoOpen: true,
buttons: [],
closeOnEscape: true,
closeText: "close",
dialogClass: "",
draggable: true,
hide: null,
height: "auto",
maxHeight: null,
maxWidth: null,
minHeight: 150,
minWidth: 150,
modal: false,
position: {
my: "center",
at: "center",
of: window,
collision: "fit",
// Ensure the titlebar is always visible
using: function(pos) {
var topOffset = $(this).css(pos).offset().top;
if (topOffset < 0) {
$(this).css("top", pos.top - topOffset);
}
}
},
resizable: true,
show: null,
title: null,
width: 300,
// callbacks
beforeClose: null,
close: null,
drag: null,
dragStart: null,
dragStop: null,
focus: null,
open: null,
resize: null,
resizeStart: null,
resizeStop: null
},
_create: function() {
this.originalCss = {
display: this.element[0].style.display,
width: this.element[0].style.width,
minHeight: this.element[0].style.minHeight,
maxHeight: this.element[0].style.maxHeight,
height: this.element[0].style.height
};
this.originalPosition = {
parent: this.element.parent(),
index: this.element.parent().children().index(this.element)
};
this.originalTitle = this.element.attr("title");
this.options.title = this.options.title || this.originalTitle;
this._createWrapper();
this.element
.show()
.removeAttr("title")
.addClass("ui-dialog-content ui-widget-content")
.appendTo(this.uiDialog);
this._createTitlebar();
this._createButtonPane();
if (this.options.draggable && $.fn.draggable) {
this._makeDraggable();
}
if (this.options.resizable && $.fn.resizable) {
this._makeResizable();
}
this._isOpen = false;
},
_init: function() {
if (this.options.autoOpen) {
this.open();
}
},
_appendTo: function() {
var element = this.options.appendTo;
if (element && (element.jquery || element.nodeType)) {
return $(element);
}
return this.document.find(element || "body").eq(0);
},
_destroy: function() {
var next,
originalPosition = this.originalPosition;
this._destroyOverlay();
this.element
.removeUniqueId()
.removeClass("ui-dialog-content ui-widget-content")
.css(this.originalCss)
// Without detaching first, the following becomes really slow
.detach();
this.uiDialog.stop(true, true).remove();
if (this.originalTitle) {
this.element.attr("title", this.originalTitle);
}
next = originalPosition.parent.children().eq(originalPosition.index);
// Don't try to place the dialog next to itself (#8613)
if (next.length && next[0] !== this.element[0]) {
next.before(this.element);
} else {
originalPosition.parent.append(this.element);
}
},
widget: function() {
return this.uiDialog;
},
disable: $.noop,
enable: $.noop,
close: function(event) {
var that = this;
if (!this._isOpen || this._trigger("beforeClose", event) === false) {
return;
}
this._isOpen = false;
this._destroyOverlay();
if (!this.opener.filter(":focusable").focus().length) {
// Hiding a focused element doesn't trigger blur in WebKit
// so in case we have nothing to focus on, explicitly blur the active element
// https://bugs.webkit.org/show_bug.cgi?id=47182
$(this.document[0].activeElement).blur();
}
this._hide(this.uiDialog, this.options.hide, function() {
that._trigger("close", event);
});
},
isOpen: function() {
return this._isOpen;
},
moveToTop: function() {
this._moveToTop();
},
_moveToTop: function(event, silent) {
var moved = !!this.uiDialog.nextAll(":visible").insertBefore(this.uiDialog).length;
if (moved && !silent) {
this._trigger("focus", event);
}
return moved;
},
open: function() {
var that = this;
if (this._isOpen) {
if (this._moveToTop()) {
this._focusTabbable();
}
return;
}
this._isOpen = true;
this.opener = $(this.document[0].activeElement);
this._size();
this._position();
this._createOverlay();
this._moveToTop(null, true);
this._show(this.uiDialog, this.options.show, function() {
that._focusTabbable();
that._trigger("focus");
});
this._trigger("open");
},
_focusTabbable: function() {
// Set focus to the first match:
// 1. First element inside the dialog matching [autofocus]
// 2. Tabbable element inside the content element
// 3. Tabbable element inside the buttonpane
// 4. The close button
// 5. The dialog itself
var hasFocus = this.element.find("[autofocus]");
if (!hasFocus.length) {
hasFocus = this.element.find(":tabbable");
}
if (!hasFocus.length) {
hasFocus = this.uiDialogButtonPane.find(":tabbable");
}
if (!hasFocus.length) {
hasFocus = this.uiDialogTitlebarClose.filter(":tabbable");
}
if (!hasFocus.length) {
hasFocus = this.uiDialog;
}
hasFocus.eq(0).focus();
},
_keepFocus: function(event) {
function checkFocus() {
var activeElement = this.document[0].activeElement,
isActive = this.uiDialog[0] === activeElement ||
$.contains(this.uiDialog[0], activeElement);
if (!isActive) {
this._focusTabbable();
}
}
event.preventDefault();
checkFocus.call(this);
// support: IE
// IE <= 8 doesn't prevent moving focus even with event.preventDefault()
// so we check again later
this._delay(checkFocus);
},
_createWrapper: function() {
this.uiDialog = $("<div>")
.addClass("ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " +
this.options.dialogClass)
.hide()
.attr({
// Setting tabIndex makes the div focusable
tabIndex: -1,
role: "dialog"
})
.appendTo(this._appendTo());
this._on(this.uiDialog, {
keydown: function(event) {
if (this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
event.keyCode === $.ui.keyCode.ESCAPE) {
event.preventDefault();
this.close(event);
return;
}
// prevent tabbing out of dialogs
if (event.keyCode !== $.ui.keyCode.TAB) {
return;
}
var tabbables = this.uiDialog.find(":tabbable"),
first = tabbables.filter(":first"),
last = tabbables.filter(":last");
if ((event.target === last[0] || event.target === this.uiDialog[0]) && !event.shiftKey) {
first.focus(1);
event.preventDefault();
} else if ((event.target === first[0] || event.target === this.uiDialog[0]) && event.shiftKey) {
last.focus(1);
event.preventDefault();
}
},
mousedown: function(event) {
if (this._moveToTop(event)) {
this._focusTabbable();
}
}
});
// We assume that any existing aria-describedby attribute means
// that the dialog content is marked up properly
// otherwise we brute force the content as the description
if (!this.element.find("[aria-describedby]").length) {
this.uiDialog.attr({
"aria-describedby": this.element.uniqueId().attr("id")
});
}
},
_createTitlebar: function() {
var uiDialogTitle;
this.uiDialogTitlebar = $("<div>")
.addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix")
.prependTo(this.uiDialog);
this._on(this.uiDialogTitlebar, {
mousedown: function(event) {
// Don't prevent click on close button (#8838)
// Focusing a dialog that is partially scrolled out of view
// causes the browser to scroll it into view, preventing the click event
if (!$(event.target).closest(".ui-dialog-titlebar-close")) {
// Dialog isn't getting focus when dragging (#8063)
this.uiDialog.focus();
}
}
});
this.uiDialogTitlebarClose = $("<button></button>")
.button({
label: this.options.closeText,
icons: {
primary: "ui-icon-closethick"
},
text: false
})
.addClass("ui-dialog-titlebar-close")
.appendTo(this.uiDialogTitlebar);
this._on(this.uiDialogTitlebarClose, {
click: function(event) {
event.preventDefault();
this.close(event);
}
});
uiDialogTitle = $("<span>")
.uniqueId()
.addClass("ui-dialog-title")
.prependTo(this.uiDialogTitlebar);
this._title(uiDialogTitle);
this.uiDialog.attr({
"aria-labelledby": uiDialogTitle.attr("id")
});
},
_title: function(title) {
if (!this.options.title) {
title.html(" ");
}
title.text(this.options.title);
},
_createButtonPane: function() {
this.uiDialogButtonPane = $("<div>")
.addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");
this.uiButtonSet = $("<div>")
.addClass("ui-dialog-buttonset")
.appendTo(this.uiDialogButtonPane);
this._createButtons();
},
_createButtons: function() {
var that = this,
buttons = this.options.buttons;
// if we already have a button pane, remove it
this.uiDialogButtonPane.remove();
this.uiButtonSet.empty();
if ($.isEmptyObject(buttons) || ($.isArray(buttons) && !buttons.length)) {
this.uiDialog.removeClass("ui-dialog-buttons");
return;
}
$.each(buttons, function(name, props) {
var click, buttonOptions;
props = $.isFunction(props) ?
{click: props, text: name} :
props;
// Default to a non-submitting button
props = $.extend({type: "button"}, props);
// Change the context for the click callback to be the main element
click = props.click;
props.click = function() {
click.apply(that.element[0], arguments);
};
buttonOptions = {
icons: props.icons,
text: props.showText
};
delete props.icons;
delete props.showText;
$("<button></button>", props)
.button(buttonOptions)
.appendTo(that.uiButtonSet);
});
this.uiDialog.addClass("ui-dialog-buttons");
this.uiDialogButtonPane.appendTo(this.uiDialog);
},
_makeDraggable: function() {
var that = this,
options = this.options;
function filteredUi(ui) {
return {
position: ui.position,
offset: ui.offset
};
}
this.uiDialog.draggable({
cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
handle: ".ui-dialog-titlebar",
containment: "document",
start: function(event, ui) {
$(this).addClass("ui-dialog-dragging");
that._blockFrames();
that._trigger("dragStart", event, filteredUi(ui));
},
drag: function(event, ui) {
that._trigger("drag", event, filteredUi(ui));
},
stop: function(event, ui) {
options.position = [
ui.position.left - that.document.scrollLeft(),
ui.position.top - that.document.scrollTop()
];
$(this).removeClass("ui-dialog-dragging");
that._unblockFrames();
that._trigger("dragStop", event, filteredUi(ui));
}
});
},
_makeResizable: function() {
var that = this,
options = this.options,
handles = options.resizable,
// .ui-resizable has position: relative defined in the stylesheet
// but dialogs have to use absolute or fixed positioning
position = this.uiDialog.css("position"),
resizeHandles = typeof handles === "string" ?
handles :
"n,e,s,w,se,sw,ne,nw";
function filteredUi(ui) {
return {<|fim▁hole|> originalSize: ui.originalSize,
position: ui.position,
size: ui.size
};
}
this.uiDialog.resizable({
cancel: ".ui-dialog-content",
containment: "document",
alsoResize: this.element,
maxWidth: options.maxWidth,
maxHeight: options.maxHeight,
minWidth: options.minWidth,
minHeight: this._minHeight(),
handles: resizeHandles,
start: function(event, ui) {
$(this).addClass("ui-dialog-resizing");
that._blockFrames();
that._trigger("resizeStart", event, filteredUi(ui));
},
resize: function(event, ui) {
that._trigger("resize", event, filteredUi(ui));
},
stop: function(event, ui) {
options.height = $(this).height();
options.width = $(this).width();
$(this).removeClass("ui-dialog-resizing");
that._unblockFrames();
that._trigger("resizeStop", event, filteredUi(ui));
}
})
.css("position", position);
},
_minHeight: function() {
var options = this.options;
return options.height === "auto" ?
options.minHeight :
Math.min(options.minHeight, options.height);
},
_position: function() {
// Need to show the dialog to get the actual offset in the position plugin
var isVisible = this.uiDialog.is(":visible");
if (!isVisible) {
this.uiDialog.show();
}
this.uiDialog.position(this.options.position);
if (!isVisible) {
this.uiDialog.hide();
}
},
_setOptions: function(options) {
var that = this,
resize = false,
resizableOptions = {};
$.each(options, function(key, value) {
that._setOption(key, value);
if (key in sizeRelatedOptions) {
resize = true;
}
if (key in resizableRelatedOptions) {
resizableOptions[ key ] = value;
}
});
if (resize) {
this._size();
this._position();
}
if (this.uiDialog.is(":data(ui-resizable)")) {
this.uiDialog.resizable("option", resizableOptions);
}
},
_setOption: function(key, value) {
/*jshint maxcomplexity:15*/
var isDraggable, isResizable,
uiDialog = this.uiDialog;
if (key === "dialogClass") {
uiDialog
.removeClass(this.options.dialogClass)
.addClass(value);
}
if (key === "disabled") {
return;
}
this._super(key, value);
if (key === "appendTo") {
this.uiDialog.appendTo(this._appendTo());
}
if (key === "buttons") {
this._createButtons();
}
if (key === "closeText") {
this.uiDialogTitlebarClose.button({
// Ensure that we always pass a string
label: "" + value
});
}
if (key === "draggable") {
isDraggable = uiDialog.is(":data(ui-draggable)");
if (isDraggable && !value) {
uiDialog.draggable("destroy");
}
if (!isDraggable && value) {
this._makeDraggable();
}
}
if (key === "position") {
this._position();
}
if (key === "resizable") {
// currently resizable, becoming non-resizable
isResizable = uiDialog.is(":data(ui-resizable)");
if (isResizable && !value) {
uiDialog.resizable("destroy");
}
// currently resizable, changing handles
if (isResizable && typeof value === "string") {
uiDialog.resizable("option", "handles", value);
}
// currently non-resizable, becoming resizable
if (!isResizable && value !== false) {
this._makeResizable();
}
}
if (key === "title") {
this._title(this.uiDialogTitlebar.find(".ui-dialog-title"));
}
},
_size: function() {
// If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
// divs will both have width and height set, so we need to reset them
var nonContentHeight, minContentHeight, maxContentHeight,
options = this.options;
// Reset content sizing
this.element.show().css({
width: "auto",
minHeight: 0,
maxHeight: "none",
height: 0
});
if (options.minWidth > options.width) {
options.width = options.minWidth;
}
// reset wrapper sizing
// determine the height of all the non-content elements
nonContentHeight = this.uiDialog.css({
height: "auto",
width: options.width
})
.outerHeight();
minContentHeight = Math.max(0, options.minHeight - nonContentHeight);
maxContentHeight = typeof options.maxHeight === "number" ?
Math.max(0, options.maxHeight - nonContentHeight) :
"none";
if (options.height === "auto") {
this.element.css({
minHeight: minContentHeight,
maxHeight: maxContentHeight,
height: "auto"
});
} else {
this.element.height(Math.max(0, options.height - nonContentHeight));
}
if (this.uiDialog.is(":data(ui-resizable)")) {
this.uiDialog.resizable("option", "minHeight", this._minHeight());
}
},
_blockFrames: function() {
this.iframeBlocks = this.document.find("iframe").map(function() {
var iframe = $(this);
return $("<div>")
.css({
position: "absolute",
width: iframe.outerWidth(),
height: iframe.outerHeight()
})
.appendTo(iframe.parent())
.offset(iframe.offset())[0];
});
},
_unblockFrames: function() {
if (this.iframeBlocks) {
this.iframeBlocks.remove();
delete this.iframeBlocks;
}
},
_allowInteraction: function(event) {
if ($(event.target).closest(".ui-dialog").length) {
return true;
}
// TODO: Remove hack when datepicker implements
// the .ui-front logic (#8989)
return !!$(event.target).closest(".ui-datepicker").length;
},
_createOverlay: function() {
if (!this.options.modal) {
return;
}
var that = this,
widgetFullName = this.widgetFullName;
if (!$.ui.dialog.overlayInstances) {
// Prevent use of anchors and inputs.
// We use a delay in case the overlay is created from an
// event that we're going to be cancelling. (#2804)
this._delay(function() {
// Handle .dialog().dialog("close") (#4065)
if ($.ui.dialog.overlayInstances) {
this.document.bind("focusin.dialog", function(event) {
if (!that._allowInteraction(event)) {
event.preventDefault();
$(".ui-dialog:visible:last .ui-dialog-content")
.data(widgetFullName)._focusTabbable();
}
});
}
});
}
this.overlay = $("<div>")
.addClass("ui-widget-overlay ui-front")
.appendTo(this._appendTo());
this._on(this.overlay, {
mousedown: "_keepFocus"
});
$.ui.dialog.overlayInstances++;
},
_destroyOverlay: function() {
if (!this.options.modal) {
return;
}
if (this.overlay) {
$.ui.dialog.overlayInstances--;
if (!$.ui.dialog.overlayInstances) {
this.document.unbind("focusin.dialog");
}
this.overlay.remove();
this.overlay = null;
}
}
});
$.ui.dialog.overlayInstances = 0;
// DEPRECATED
if ($.uiBackCompat !== false) {
// position option with array notation
// just override with old implementation
$.widget("ui.dialog", $.ui.dialog, {
_position: function() {
var position = this.options.position,
myAt = [],
offset = [0, 0],
isVisible;
if (position) {
if (typeof position === "string" || (typeof position === "object" && "0" in position)) {
myAt = position.split ? position.split(" ") : [position[0], position[1]];
if (myAt.length === 1) {
myAt[1] = myAt[0];
}
$.each(["left", "top"], function(i, offsetPosition) {
if (+myAt[ i ] === myAt[ i ]) {
offset[ i ] = myAt[ i ];
myAt[ i ] = offsetPosition;
}
});
position = {
my: myAt[0] + (offset[0] < 0 ? offset[0] : "+" + offset[0]) + " " +
myAt[1] + (offset[1] < 0 ? offset[1] : "+" + offset[1]),
at: myAt.join(" ")
};
}
position = $.extend({}, $.ui.dialog.prototype.options.position, position);
} else {
position = $.ui.dialog.prototype.options.position;
}
// need to show the dialog to get the actual offset in the position plugin
isVisible = this.uiDialog.is(":visible");
if (!isVisible) {
this.uiDialog.show();
}
this.uiDialog.position(position);
if (!isVisible) {
this.uiDialog.hide();
}
}
});
}
}(jQuery));
(function($, undefined) {
var rvertical = /up|down|vertical/,
rpositivemotion = /up|left|vertical|horizontal/;
$.effects.effect.blind = function(o, done) {
// Create element
var el = $(this),
props = ["position", "top", "bottom", "left", "right", "height", "width"],
mode = $.effects.setMode(el, o.mode || "hide"),
direction = o.direction || "up",
vertical = rvertical.test(direction),
ref = vertical ? "height" : "width",
ref2 = vertical ? "top" : "left",
motion = rpositivemotion.test(direction),
animation = {},
show = mode === "show",
wrapper, distance, margin;
// if already wrapped, the wrapper's properties are my property. #6245
if (el.parent().is(".ui-effects-wrapper")) {
$.effects.save(el.parent(), props);
} else {
$.effects.save(el, props);
}
el.show();
wrapper = $.effects.createWrapper(el).css({
overflow: "hidden"
});
distance = wrapper[ ref ]();
margin = parseFloat(wrapper.css(ref2)) || 0;
animation[ ref ] = show ? distance : 0;
if (!motion) {
el
.css(vertical ? "bottom" : "right", 0)
.css(vertical ? "top" : "left", "auto")
.css({position: "absolute"});
animation[ ref2 ] = show ? margin : distance + margin;
}
// start at 0 if we are showing
if (show) {
wrapper.css(ref, 0);
if (!motion) {
wrapper.css(ref2, margin + distance);
}
}
// Animate
wrapper.animate(animation, {
duration: o.duration,
easing: o.easing,
queue: false,
complete: function() {
if (mode === "hide") {
el.hide();
}
$.effects.restore(el, props);
$.effects.removeWrapper(el);
done();
}
});
};
})(jQuery);
(function($, undefined) {
$.effects.effect.bounce = function(o, done) {
var el = $(this),
props = ["position", "top", "bottom", "left", "right", "height", "width"],
// defaults:
mode = $.effects.setMode(el, o.mode || "effect"),
hide = mode === "hide",
show = mode === "show",
direction = o.direction || "up",
distance = o.distance,
times = o.times || 5,
// number of internal animations
anims = times * 2 + (show || hide ? 1 : 0),
speed = o.duration / anims,
easing = o.easing,
// utility:
ref = (direction === "up" || direction === "down") ? "top" : "left",
motion = (direction === "up" || direction === "left"),
i,
upAnim,
downAnim,
// we will need to re-assemble the queue to stack our animations in place
queue = el.queue(),
queuelen = queue.length;
// Avoid touching opacity to prevent clearType and PNG issues in IE
if (show || hide) {
props.push("opacity");
}
$.effects.save(el, props);
el.show();
$.effects.createWrapper(el); // Create Wrapper
// default distance for the BIGGEST bounce is the outer Distance / 3
if (!distance) {
distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
}
if (show) {
downAnim = {opacity: 1};
downAnim[ ref ] = 0;
// if we are showing, force opacity 0 and set the initial position
// then do the "first" animation
el.css("opacity", 0)
.css(ref, motion ? -distance * 2 : distance * 2)
.animate(downAnim, speed, easing);
}
// start at the smallest distance if we are hiding
if (hide) {
distance = distance / Math.pow(2, times - 1);
}
downAnim = {};
downAnim[ ref ] = 0;
// Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
for (i = 0; i < times; i++) {
upAnim = {};
upAnim[ ref ] = (motion ? "-=" : "+=") + distance;
el.animate(upAnim, speed, easing)
.animate(downAnim, speed, easing);
distance = hide ? distance * 2 : distance / 2;
}
// Last Bounce when Hiding
if (hide) {
upAnim = {opacity: 0};
upAnim[ ref ] = (motion ? "-=" : "+=") + distance;
el.animate(upAnim, speed, easing);
}
el.queue(function() {
if (hide) {
el.hide();
}
$.effects.restore(el, props);
$.effects.removeWrapper(el);
done();
});
// inject all the animations we just queued to be first in line (after "inprogress")
if (queuelen > 1) {
queue.splice.apply(queue,
[1, 0].concat(queue.splice(queuelen, anims + 1)));
}
el.dequeue();
};
})(jQuery);
(function($, undefined) {
$.effects.effect.clip = function(o, done) {
// Create element
var el = $(this),
props = ["position", "top", "bottom", "left", "right", "height", "width"],
mode = $.effects.setMode(el, o.mode || "hide"),
show = mode === "show",
direction = o.direction || "vertical",
vert = direction === "vertical",
size = vert ? "height" : "width",
position = vert ? "top" : "left",
animation = {},
wrapper, animate, distance;
// Save & Show
$.effects.save(el, props);
el.show();
// Create Wrapper
wrapper = $.effects.createWrapper(el).css({
overflow: "hidden"
});
animate = (el[0].tagName === "IMG") ? wrapper : el;
distance = animate[ size ]();
// Shift
if (show) {
animate.css(size, 0);
animate.css(position, distance / 2);
}
// Create Animation Object:
animation[ size ] = show ? distance : 0;
animation[ position ] = show ? 0 : distance / 2;
// Animate
animate.animate(animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if (!show) {
el.hide();
}
$.effects.restore(el, props);
$.effects.removeWrapper(el);
done();
}
});
};
})(jQuery);
(function($, undefined) {
$.effects.effect.drop = function(o, done) {
var el = $(this),
props = ["position", "top", "bottom", "left", "right", "opacity", "height", "width"],
mode = $.effects.setMode(el, o.mode || "hide"),
show = mode === "show",
direction = o.direction || "left",
ref = (direction === "up" || direction === "down") ? "top" : "left",
motion = (direction === "up" || direction === "left") ? "pos" : "neg",
animation = {
opacity: show ? 1 : 0
},
distance;
// Adjust
$.effects.save(el, props);
el.show();
$.effects.createWrapper(el);
distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ](true) / 2;
if (show) {
el
.css("opacity", 0)
.css(ref, motion === "pos" ? -distance : distance);
}
// Animation
animation[ ref ] = (show ?
(motion === "pos" ? "+=" : "-=") :
(motion === "pos" ? "-=" : "+=")) +
distance;
// Animate
el.animate(animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if (mode === "hide") {
el.hide();
}
$.effects.restore(el, props);
$.effects.removeWrapper(el);
done();
}
});
};
})(jQuery);
(function($, undefined) {
$.effects.effect.explode = function(o, done) {
var rows = o.pieces ? Math.round(Math.sqrt(o.pieces)) : 3,
cells = rows,
el = $(this),
mode = $.effects.setMode(el, o.mode || "hide"),
show = mode === "show",
// show and then visibility:hidden the element before calculating offset
offset = el.show().css("visibility", "hidden").offset(),
// width and height of a piece
width = Math.ceil(el.outerWidth() / cells),
height = Math.ceil(el.outerHeight() / rows),
pieces = [],
// loop
i, j, left, top, mx, my;
// children animate complete:
function childComplete() {
pieces.push(this);
if (pieces.length === rows * cells) {
animComplete();
}
}
// clone the element for each row and cell.
for (i = 0; i < rows; i++) { // ===>
top = offset.top + i * height;
my = i - (rows - 1) / 2;
for (j = 0; j < cells; j++) { // |||
left = offset.left + j * width;
mx = j - (cells - 1) / 2;
// Create a clone of the now hidden main element that will be absolute positioned
// within a wrapper div off the -left and -top equal to size of our pieces
el
.clone()
.appendTo("body")
.wrap("<div></div>")
.css({
position: "absolute",
visibility: "visible",
left: -j * width,
top: -i * height
})
// select the wrapper - make it overflow: hidden and absolute positioned based on
// where the original was located +left and +top equal to the size of pieces
.parent()
.addClass("ui-effects-explode")
.css({
position: "absolute",
overflow: "hidden",
width: width,
height: height,
left: left + (show ? mx * width : 0),
top: top + (show ? my * height : 0),
opacity: show ? 0 : 1
}).animate({
left: left + (show ? 0 : mx * width),
top: top + (show ? 0 : my * height),
opacity: show ? 1 : 0
}, o.duration || 500, o.easing, childComplete);
}
}
function animComplete() {
el.css({
visibility: "visible"
});
$(pieces).remove();
if (!show) {
el.hide();
}
done();
}
};
})(jQuery);
(function($, undefined) {
$.effects.effect.fade = function(o, done) {
var el = $(this),
mode = $.effects.setMode(el, o.mode || "toggle");
el.animate({
opacity: mode
}, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: done
});
};
})(jQuery);
(function($, undefined) {
$.effects.effect.fold = function(o, done) {
// Create element
var el = $(this),
props = ["position", "top", "bottom", "left", "right", "height", "width"],
mode = $.effects.setMode(el, o.mode || "hide"),
show = mode === "show",
hide = mode === "hide",
size = o.size || 15,
percent = /([0-9]+)%/.exec(size),
horizFirst = !!o.horizFirst,
widthFirst = show !== horizFirst,
ref = widthFirst ? ["width", "height"] : ["height", "width"],
duration = o.duration / 2,
wrapper, distance,
animation1 = {},
animation2 = {};
$.effects.save(el, props);
el.show();
// Create Wrapper
wrapper = $.effects.createWrapper(el).css({
overflow: "hidden"
});
distance = widthFirst ?
[wrapper.width(), wrapper.height()] :
[wrapper.height(), wrapper.width()];
if (percent) {
size = parseInt(percent[ 1 ], 10) / 100 * distance[ hide ? 0 : 1 ];
}
if (show) {
wrapper.css(horizFirst ? {
height: 0,
width: size
} : {
height: size,
width: 0
});
}
// Animation
animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size;
animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0;
// Animate
wrapper
.animate(animation1, duration, o.easing)
.animate(animation2, duration, o.easing, function() {
if (hide) {
el.hide();
}
$.effects.restore(el, props);
$.effects.removeWrapper(el);
done();
});
};
})(jQuery);
(function($, undefined) {
$.effects.effect.highlight = function(o, done) {
var elem = $(this),
props = ["backgroundImage", "backgroundColor", "opacity"],
mode = $.effects.setMode(elem, o.mode || "show"),
animation = {
backgroundColor: elem.css("backgroundColor")
};
if (mode === "hide") {
animation.opacity = 0;
}
$.effects.save(elem, props);
elem
.show()
.css({
backgroundImage: "none",
backgroundColor: o.color || "#ffff99"
})
.animate(animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if (mode === "hide") {
elem.hide();
}
$.effects.restore(elem, props);
done();
}
});
};
})(jQuery);
(function($, undefined) {
$.effects.effect.pulsate = function(o, done) {
var elem = $(this),
mode = $.effects.setMode(elem, o.mode || "show"),
show = mode === "show",
hide = mode === "hide",
showhide = (show || mode === "hide"),
// showing or hiding leaves of the "last" animation
anims = ((o.times || 5) * 2) + (showhide ? 1 : 0),
duration = o.duration / anims,
animateTo = 0,
queue = elem.queue(),
queuelen = queue.length,
i;
if (show || !elem.is(":visible")) {
elem.css("opacity", 0).show();
animateTo = 1;
}
// anims - 1 opacity "toggles"
for (i = 1; i < anims; i++) {
elem.animate({
opacity: animateTo
}, duration, o.easing);
animateTo = 1 - animateTo;
}
elem.animate({
opacity: animateTo
}, duration, o.easing);
elem.queue(function() {
if (hide) {
elem.hide();
}
done();
});
// We just queued up "anims" animations, we need to put them next in the queue
if (queuelen > 1) {
queue.splice.apply(queue,
[1, 0].concat(queue.splice(queuelen, anims + 1)));
}
elem.dequeue();
};
})(jQuery);
(function($, undefined) {
$.effects.effect.puff = function(o, done) {
var elem = $(this),
mode = $.effects.setMode(elem, o.mode || "hide"),
hide = mode === "hide",
percent = parseInt(o.percent, 10) || 150,
factor = percent / 100,
original = {
height: elem.height(),
width: elem.width(),
outerHeight: elem.outerHeight(),
outerWidth: elem.outerWidth()
};
$.extend(o, {
effect: "scale",
queue: false,
fade: true,
mode: mode,
complete: done,
percent: hide ? percent : 100,
from: hide ?
original :
{
height: original.height * factor,
width: original.width * factor,
outerHeight: original.outerHeight * factor,
outerWidth: original.outerWidth * factor
}
});
elem.effect(o);
};
$.effects.effect.scale = function(o, done) {
// Create element
var el = $(this),
options = $.extend(true, {}, o),
mode = $.effects.setMode(el, o.mode || "effect"),
percent = parseInt(o.percent, 10) ||
(parseInt(o.percent, 10) === 0 ? 0 : (mode === "hide" ? 0 : 100)),
direction = o.direction || "both",
origin = o.origin,
original = {
height: el.height(),
width: el.width(),
outerHeight: el.outerHeight(),
outerWidth: el.outerWidth()
},
factor = {
y: direction !== "horizontal" ? (percent / 100) : 1,
x: direction !== "vertical" ? (percent / 100) : 1
};
// We are going to pass this effect to the size effect:
options.effect = "size";
options.queue = false;
options.complete = done;
// Set default origin and restore for show/hide
if (mode !== "effect") {
options.origin = origin || ["middle", "center"];
options.restore = true;
}
options.from = o.from || (mode === "show" ? {
height: 0,
width: 0,
outerHeight: 0,
outerWidth: 0
} : original);
options.to = {
height: original.height * factor.y,
width: original.width * factor.x,
outerHeight: original.outerHeight * factor.y,
outerWidth: original.outerWidth * factor.x
};
// Fade option to support puff
if (options.fade) {
if (mode === "show") {
options.from.opacity = 0;
options.to.opacity = 1;
}
if (mode === "hide") {
options.from.opacity = 1;
options.to.opacity = 0;
}
}
// Animate
el.effect(options);
};
$.effects.effect.size = function(o, done) {
// Create element
var original, baseline, factor,
el = $(this),
props0 = ["position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity"],
// Always restore
props1 = ["position", "top", "bottom", "left", "right", "overflow", "opacity"],
// Copy for children
props2 = ["width", "height", "overflow"],
cProps = ["fontSize"],
vProps = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"],
hProps = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"],
// Set options
mode = $.effects.setMode(el, o.mode || "effect"),
restore = o.restore || mode !== "effect",
scale = o.scale || "both",
origin = o.origin || ["middle", "center"],
position = el.css("position"),
props = restore ? props0 : props1,
zero = {
height: 0,
width: 0,
outerHeight: 0,
outerWidth: 0
};
if (mode === "show") {
el.show();
}
original = {
height: el.height(),
width: el.width(),
outerHeight: el.outerHeight(),
outerWidth: el.outerWidth()
};
if (o.mode === "toggle" && mode === "show") {
el.from = o.to || zero;
el.to = o.from || original;
} else {
el.from = o.from || (mode === "show" ? zero : original);
el.to = o.to || (mode === "hide" ? zero : original);
}
// Set scaling factor
factor = {
from: {
y: el.from.height / original.height,
x: el.from.width / original.width
},
to: {
y: el.to.height / original.height,
x: el.to.width / original.width
}
};
// Scale the css box
if (scale === "box" || scale === "both") {
// Vertical props scaling
if (factor.from.y !== factor.to.y) {
props = props.concat(vProps);
el.from = $.effects.setTransition(el, vProps, factor.from.y, el.from);
el.to = $.effects.setTransition(el, vProps, factor.to.y, el.to);
}
// Horizontal props scaling
if (factor.from.x !== factor.to.x) {
props = props.concat(hProps);
el.from = $.effects.setTransition(el, hProps, factor.from.x, el.from);
el.to = $.effects.setTransition(el, hProps, factor.to.x, el.to);
}
}
// Scale the content
if (scale === "content" || scale === "both") {
// Vertical props scaling
if (factor.from.y !== factor.to.y) {
props = props.concat(cProps).concat(props2);
el.from = $.effects.setTransition(el, cProps, factor.from.y, el.from);
el.to = $.effects.setTransition(el, cProps, factor.to.y, el.to);
}
}
$.effects.save(el, props);
el.show();
$.effects.createWrapper(el);
el.css("overflow", "hidden").css(el.from);
// Adjust
if (origin) { // Calculate baseline shifts
baseline = $.effects.getBaseline(origin, original);
el.from.top = (original.outerHeight - el.outerHeight()) * baseline.y;
el.from.left = (original.outerWidth - el.outerWidth()) * baseline.x;
el.to.top = (original.outerHeight - el.to.outerHeight) * baseline.y;
el.to.left = (original.outerWidth - el.to.outerWidth) * baseline.x;
}
el.css(el.from); // set top & left
// Animate
if (scale === "content" || scale === "both") { // Scale the children
// Add margins/font-size
vProps = vProps.concat(["marginTop", "marginBottom"]).concat(cProps);
hProps = hProps.concat(["marginLeft", "marginRight"]);
props2 = props0.concat(vProps).concat(hProps);
el.find("*[width]").each(function() {
var child = $(this),
c_original = {
height: child.height(),
width: child.width(),
outerHeight: child.outerHeight(),
outerWidth: child.outerWidth()
};
if (restore) {
$.effects.save(child, props2);
}
child.from = {
height: c_original.height * factor.from.y,
width: c_original.width * factor.from.x,
outerHeight: c_original.outerHeight * factor.from.y,
outerWidth: c_original.outerWidth * factor.from.x
};
child.to = {
height: c_original.height * factor.to.y,
width: c_original.width * factor.to.x,
outerHeight: c_original.height * factor.to.y,
outerWidth: c_original.width * factor.to.x
};
// Vertical props scaling
if (factor.from.y !== factor.to.y) {
child.from = $.effects.setTransition(child, vProps, factor.from.y, child.from);
child.to = $.effects.setTransition(child, vProps, factor.to.y, child.to);
}
// Horizontal props scaling
if (factor.from.x !== factor.to.x) {
child.from = $.effects.setTransition(child, hProps, factor.from.x, child.from);
child.to = $.effects.setTransition(child, hProps, factor.to.x, child.to);
}
// Animate children
child.css(child.from);
child.animate(child.to, o.duration, o.easing, function() {
// Restore children
if (restore) {
$.effects.restore(child, props2);
}
});
});
}
// Animate
el.animate(el.to, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if (el.to.opacity === 0) {
el.css("opacity", el.from.opacity);
}
if (mode === "hide") {
el.hide();
}
$.effects.restore(el, props);
if (!restore) {
// we need to calculate our new positioning based on the scaling
if (position === "static") {
el.css({
position: "relative",
top: el.to.top,
left: el.to.left
});
} else {
$.each(["top", "left"], function(idx, pos) {
el.css(pos, function(_, str) {
var val = parseInt(str, 10),
toRef = idx ? el.to.left : el.to.top;
// if original was "auto", recalculate the new value from wrapper
if (str === "auto") {
return toRef + "px";
}
return val + toRef + "px";
});
});
}
}
$.effects.removeWrapper(el);
done();
}
});
};
})(jQuery);
(function($, undefined) {
$.effects.effect.shake = function(o, done) {
var el = $(this),
props = ["position", "top", "bottom", "left", "right", "height", "width"],
mode = $.effects.setMode(el, o.mode || "effect"),
direction = o.direction || "left",
distance = o.distance || 20,
times = o.times || 3,
anims = times * 2 + 1,
speed = Math.round(o.duration / anims),
ref = (direction === "up" || direction === "down") ? "top" : "left",
positiveMotion = (direction === "up" || direction === "left"),
animation = {},
animation1 = {},
animation2 = {},
i,
// we will need to re-assemble the queue to stack our animations in place
queue = el.queue(),
queuelen = queue.length;
$.effects.save(el, props);
el.show();
$.effects.createWrapper(el);
// Animation
animation[ ref ] = (positiveMotion ? "-=" : "+=") + distance;
animation1[ ref ] = (positiveMotion ? "+=" : "-=") + distance * 2;
animation2[ ref ] = (positiveMotion ? "-=" : "+=") + distance * 2;
// Animate
el.animate(animation, speed, o.easing);
// Shakes
for (i = 1; i < times; i++) {
el.animate(animation1, speed, o.easing).animate(animation2, speed, o.easing);
}
el
.animate(animation1, speed, o.easing)
.animate(animation, speed / 2, o.easing)
.queue(function() {
if (mode === "hide") {
el.hide();
}
$.effects.restore(el, props);
$.effects.removeWrapper(el);
done();
});
// inject all the animations we just queued to be first in line (after "inprogress")
if (queuelen > 1) {
queue.splice.apply(queue,
[1, 0].concat(queue.splice(queuelen, anims + 1)));
}
el.dequeue();
};
})(jQuery);
(function($, undefined) {
$.effects.effect.slide = function(o, done) {
// Create element
var el = $(this),
props = ["position", "top", "bottom", "left", "right", "width", "height"],
mode = $.effects.setMode(el, o.mode || "show"),
show = mode === "show",
direction = o.direction || "left",
ref = (direction === "up" || direction === "down") ? "top" : "left",
positiveMotion = (direction === "up" || direction === "left"),
distance,
animation = {};
// Adjust
$.effects.save(el, props);
el.show();
distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ](true);
$.effects.createWrapper(el).css({
overflow: "hidden"
});
if (show) {
el.css(ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance);
}
// Animation
animation[ ref ] = (show ?
(positiveMotion ? "+=" : "-=") :
(positiveMotion ? "-=" : "+=")) +
distance;
// Animate
el.animate(animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if (mode === "hide") {
el.hide();
}
$.effects.restore(el, props);
$.effects.removeWrapper(el);
done();
}
});
};
})(jQuery);
(function($, undefined) {
$.effects.effect.transfer = function(o, done) {
var elem = $(this),
target = $(o.to),
targetFixed = target.css("position") === "fixed",
body = $("body"),
fixTop = targetFixed ? body.scrollTop() : 0,
fixLeft = targetFixed ? body.scrollLeft() : 0,
endPosition = target.offset(),
animation = {
top: endPosition.top - fixTop,
left: endPosition.left - fixLeft,
height: target.innerHeight(),
width: target.innerWidth()
},
startPosition = elem.offset(),
transfer = $("<div class='ui-effects-transfer'></div>")
.appendTo(document.body)
.addClass(o.className)
.css({
top: startPosition.top - fixTop,
left: startPosition.left - fixLeft,
height: elem.innerHeight(),
width: elem.innerWidth(),
position: targetFixed ? "fixed" : "absolute"
})
.animate(animation, o.duration, o.easing, function() {
transfer.remove();
done();
});
};
})(jQuery);
(function($, undefined) {
$.widget("ui.menu", {
version: "1.10.3",
defaultElement: "<ul>",
delay: 300,
options: {
icons: {
submenu: "ui-icon-carat-1-e"
},
menus: "ul",
position: {
my: "left top",
at: "right top"
},
role: "menu",
// callbacks
blur: null,
focus: null,
select: null
},
_create: function() {
this.activeMenu = this.element;
// flag used to prevent firing of the click handler
// as the event bubbles up through nested menus
this.mouseHandled = false;
this.element
.uniqueId()
.addClass("ui-menu ui-widget ui-widget-content ui-corner-all")
.toggleClass("ui-menu-icons", !!this.element.find(".ui-icon").length)
.attr({
role: this.options.role,
tabIndex: 0
})
// need to catch all clicks on disabled menu
// not possible through _on
.bind("click" + this.eventNamespace, $.proxy(function(event) {
if (this.options.disabled) {
event.preventDefault();
}
}, this));
if (this.options.disabled) {
this.element
.addClass("ui-state-disabled")
.attr("aria-disabled", "true");
}
this._on({
// Prevent focus from sticking to links inside menu after clicking
// them (focus should always stay on UL during navigation).
"mousedown .ui-menu-item > a": function(event) {
event.preventDefault();
},
"click .ui-state-disabled > a": function(event) {
event.preventDefault();
},
"click .ui-menu-item:has(a)": function(event) {
var target = $(event.target).closest(".ui-menu-item");
if (!this.mouseHandled && target.not(".ui-state-disabled").length) {
this.mouseHandled = true;
this.select(event);
// Open submenu on click
if (target.has(".ui-menu").length) {
this.expand(event);
} else if (!this.element.is(":focus")) {
// Redirect focus to the menu
this.element.trigger("focus", [true]);
// If the active item is on the top level, let it stay active.
// Otherwise, blur the active item since it is no longer visible.
if (this.active && this.active.parents(".ui-menu").length === 1) {
clearTimeout(this.timer);
}
}
}
},
"mouseenter .ui-menu-item": function(event) {
var target = $(event.currentTarget);
// Remove ui-state-active class from siblings of the newly focused menu item
// to avoid a jump caused by adjacent elements both having a class with a border
target.siblings().children(".ui-state-active").removeClass("ui-state-active");
this.focus(event, target);
},
mouseleave: "collapseAll",
"mouseleave .ui-menu": "collapseAll",
focus: function(event, keepActiveItem) {
// If there's already an active item, keep it active
// If not, activate the first item
var item = this.active || this.element.children(".ui-menu-item").eq(0);
if (!keepActiveItem) {
this.focus(event, item);
}
},
blur: function(event) {
this._delay(function() {
if (!$.contains(this.element[0], this.document[0].activeElement)) {
this.collapseAll(event);
}
});
},
keydown: "_keydown"
});
this.refresh();
// Clicks outside of a menu collapse any open menus
this._on(this.document, {
click: function(event) {
if (!$(event.target).closest(".ui-menu").length) {
this.collapseAll(event);
}
// Reset the mouseHandled flag
this.mouseHandled = false;
}
});
},
_destroy: function() {
// Destroy (sub)menus
this.element
.removeAttr("aria-activedescendant")
.find(".ui-menu").addBack()
.removeClass("ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons")
.removeAttr("role")
.removeAttr("tabIndex")
.removeAttr("aria-labelledby")
.removeAttr("aria-expanded")
.removeAttr("aria-hidden")
.removeAttr("aria-disabled")
.removeUniqueId()
.show();
// Destroy menu items
this.element.find(".ui-menu-item")
.removeClass("ui-menu-item")
.removeAttr("role")
.removeAttr("aria-disabled")
.children("a")
.removeUniqueId()
.removeClass("ui-corner-all ui-state-hover")
.removeAttr("tabIndex")
.removeAttr("role")
.removeAttr("aria-haspopup")
.children().each(function() {
var elem = $(this);
if (elem.data("ui-menu-submenu-carat")) {
elem.remove();
}
});
// Destroy menu dividers
this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content");
},
_keydown: function(event) {
/*jshint maxcomplexity:20*/
var match, prev, character, skip, regex,
preventDefault = true;
function escape(value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
switch (event.keyCode) {
case $.ui.keyCode.PAGE_UP:
this.previousPage(event);
break;
case $.ui.keyCode.PAGE_DOWN:
this.nextPage(event);
break;
case $.ui.keyCode.HOME:
this._move("first", "first", event);
break;
case $.ui.keyCode.END:
this._move("last", "last", event);
break;
case $.ui.keyCode.UP:
this.previous(event);
break;
case $.ui.keyCode.DOWN:
this.next(event);
break;
case $.ui.keyCode.LEFT:
this.collapse(event);
break;
case $.ui.keyCode.RIGHT:
if (this.active && !this.active.is(".ui-state-disabled")) {
this.expand(event);
}
break;
case $.ui.keyCode.ENTER:
case $.ui.keyCode.SPACE:
this._activate(event);
break;
case $.ui.keyCode.ESCAPE:
this.collapse(event);
break;
default:
preventDefault = false;
prev = this.previousFilter || "";
character = String.fromCharCode(event.keyCode);
skip = false;
clearTimeout(this.filterTimer);
if (character === prev) {
skip = true;
} else {
character = prev + character;
}
regex = new RegExp("^" + escape(character), "i");
match = this.activeMenu.children(".ui-menu-item").filter(function() {
return regex.test($(this).children("a").text());
});
match = skip && match.index(this.active.next()) !== -1 ?
this.active.nextAll(".ui-menu-item") :
match;
// If no matches on the current filter, reset to the last character pressed
// to move down the menu to the first item that starts with that character
if (!match.length) {
character = String.fromCharCode(event.keyCode);
regex = new RegExp("^" + escape(character), "i");
match = this.activeMenu.children(".ui-menu-item").filter(function() {
return regex.test($(this).children("a").text());
});
}
if (match.length) {
this.focus(event, match);
if (match.length > 1) {
this.previousFilter = character;
this.filterTimer = this._delay(function() {
delete this.previousFilter;
}, 1000);
} else {
delete this.previousFilter;
}
} else {
delete this.previousFilter;
}
}
if (preventDefault) {
event.preventDefault();
}
},
_activate: function(event) {
if (!this.active.is(".ui-state-disabled")) {
if (this.active.children("a[aria-haspopup='true']").length) {
this.expand(event);
} else {
this.select(event);
}
}
},
refresh: function() {
var menus,
icon = this.options.icons.submenu,
submenus = this.element.find(this.options.menus);
// Initialize nested menus
submenus.filter(":not(.ui-menu)")
.addClass("ui-menu ui-widget ui-widget-content ui-corner-all")
.hide()
.attr({
role: this.options.role,
"aria-hidden": "true",
"aria-expanded": "false"
})
.each(function() {
var menu = $(this),
item = menu.prev("a"),
submenuCarat = $("<span>")
.addClass("ui-menu-icon ui-icon " + icon)
.data("ui-menu-submenu-carat", true);
item
.attr("aria-haspopup", "true")
.prepend(submenuCarat);
menu.attr("aria-labelledby", item.attr("id"));
});
menus = submenus.add(this.element);
// Don't refresh list items that are already adapted
menus.children(":not(.ui-menu-item):has(a)")
.addClass("ui-menu-item")
.attr("role", "presentation")
.children("a")
.uniqueId()
.addClass("ui-corner-all")
.attr({
tabIndex: -1,
role: this._itemRole()
});
// Initialize unlinked menu-items containing spaces and/or dashes only as dividers
menus.children(":not(.ui-menu-item)").each(function() {
var item = $(this);
// hyphen, em dash, en dash
if (!/[^\-\u2014\u2013\s]/.test(item.text())) {
item.addClass("ui-widget-content ui-menu-divider");
}
});
// Add aria-disabled attribute to any disabled menu item
menus.children(".ui-state-disabled").attr("aria-disabled", "true");
// If the active item has been removed, blur the menu
if (this.active && !$.contains(this.element[ 0 ], this.active[ 0 ])) {
this.blur();
}
},
_itemRole: function() {
return {
menu: "menuitem",
listbox: "option"
}[ this.options.role ];
},
_setOption: function(key, value) {
if (key === "icons") {
this.element.find(".ui-menu-icon")
.removeClass(this.options.icons.submenu)
.addClass(value.submenu);
}
this._super(key, value);
},
focus: function(event, item) {
var nested, focused;
this.blur(event, event && event.type === "focus");
this._scrollIntoView(item);
this.active = item.first();
focused = this.active.children("a").addClass("ui-state-focus");
// Only update aria-activedescendant if there's a role
// otherwise we assume focus is managed elsewhere
if (this.options.role) {
this.element.attr("aria-activedescendant", focused.attr("id"));
}
// Highlight active parent menu item, if any
this.active
.parent()
.closest(".ui-menu-item")
.children("a:first")
.addClass("ui-state-active");
if (event && event.type === "keydown") {
this._close();
} else {
this.timer = this._delay(function() {
this._close();
}, this.delay);
}
nested = item.children(".ui-menu");
if (nested.length && (/^mouse/.test(event.type))) {
this._startOpening(nested);
}
this.activeMenu = item.parent();
this._trigger("focus", event, {item: item});
},
_scrollIntoView: function(item) {
var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
if (this._hasScroll()) {
borderTop = parseFloat($.css(this.activeMenu[0], "borderTopWidth")) || 0;
paddingTop = parseFloat($.css(this.activeMenu[0], "paddingTop")) || 0;
offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
scroll = this.activeMenu.scrollTop();
elementHeight = this.activeMenu.height();
itemHeight = item.height();
if (offset < 0) {
this.activeMenu.scrollTop(scroll + offset);
} else if (offset + itemHeight > elementHeight) {
this.activeMenu.scrollTop(scroll + offset - elementHeight + itemHeight);
}
}
},
blur: function(event, fromFocus) {
if (!fromFocus) {
clearTimeout(this.timer);
}
if (!this.active) {
return;
}
this.active.children("a").removeClass("ui-state-focus");
this.active = null;
this._trigger("blur", event, {item: this.active});
},
_startOpening: function(submenu) {
clearTimeout(this.timer);
// Don't open if already open fixes a Firefox bug that caused a .5 pixel
// shift in the submenu position when mousing over the carat icon
if (submenu.attr("aria-hidden") !== "true") {
return;
}
this.timer = this._delay(function() {
this._close();
this._open(submenu);
}, this.delay);
},
_open: function(submenu) {
var position = $.extend({
of: this.active
}, this.options.position);
clearTimeout(this.timer);
this.element.find(".ui-menu").not(submenu.parents(".ui-menu"))
.hide()
.attr("aria-hidden", "true");
submenu
.show()
.removeAttr("aria-hidden")
.attr("aria-expanded", "true")
.position(position);
},
collapseAll: function(event, all) {
clearTimeout(this.timer);
this.timer = this._delay(function() {
// If we were passed an event, look for the submenu that contains the event
var currentMenu = all ? this.element :
$(event && event.target).closest(this.element.find(".ui-menu"));
// If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
if (!currentMenu.length) {
currentMenu = this.element;
}
this._close(currentMenu);
this.blur(event);
this.activeMenu = currentMenu;
}, this.delay);
},
// With no arguments, closes the currently active menu - if nothing is active
// it closes all menus. If passed an argument, it will search for menus BELOW
_close: function(startMenu) {
if (!startMenu) {
startMenu = this.active ? this.active.parent() : this.element;
}
startMenu
.find(".ui-menu")
.hide()
.attr("aria-hidden", "true")
.attr("aria-expanded", "false")
.end()
.find("a.ui-state-active")
.removeClass("ui-state-active");
},
collapse: function(event) {
var newItem = this.active &&
this.active.parent().closest(".ui-menu-item", this.element);
if (newItem && newItem.length) {
this._close();
this.focus(event, newItem);
}
},
expand: function(event) {
var newItem = this.active &&
this.active
.children(".ui-menu ")
.children(".ui-menu-item")
.first();
if (newItem && newItem.length) {
this._open(newItem.parent());
// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
this._delay(function() {
this.focus(event, newItem);
});
}
},
next: function(event) {
this._move("next", "first", event);
},
previous: function(event) {
this._move("prev", "last", event);
},
isFirstItem: function() {
return this.active && !this.active.prevAll(".ui-menu-item").length;
},
isLastItem: function() {
return this.active && !this.active.nextAll(".ui-menu-item").length;
},
_move: function(direction, filter, event) {
var next;
if (this.active) {
if (direction === "first" || direction === "last") {
next = this.active
[ direction === "first" ? "prevAll" : "nextAll" ](".ui-menu-item")
.eq(-1);
} else {
next = this.active
[ direction + "All" ](".ui-menu-item")
.eq(0);
}
}
if (!next || !next.length || !this.active) {
next = this.activeMenu.children(".ui-menu-item")[ filter ]();
}
this.focus(event, next);
},
nextPage: function(event) {
var item, base, height;
if (!this.active) {
this.next(event);
return;
}
if (this.isLastItem()) {
return;
}
if (this._hasScroll()) {
base = this.active.offset().top;
height = this.element.height();
this.active.nextAll(".ui-menu-item").each(function() {
item = $(this);
return item.offset().top - base - height < 0;
});
this.focus(event, item);
} else {
this.focus(event, this.activeMenu.children(".ui-menu-item")
[ !this.active ? "first" : "last" ]());
}
},
previousPage: function(event) {
var item, base, height;
if (!this.active) {
this.next(event);
return;
}
if (this.isFirstItem()) {
return;
}
if (this._hasScroll()) {
base = this.active.offset().top;
height = this.element.height();
this.active.prevAll(".ui-menu-item").each(function() {
item = $(this);
return item.offset().top - base + height > 0;
});
this.focus(event, item);
} else {
this.focus(event, this.activeMenu.children(".ui-menu-item").first());
}
},
_hasScroll: function() {
return this.element.outerHeight() < this.element.prop("scrollHeight");
},
select: function(event) {
// TODO: It should never be possible to not have an active item at this
// point, but the tests don't trigger mouseenter before click.
this.active = this.active || $(event.target).closest(".ui-menu-item");
var ui = {item: this.active};
if (!this.active.has(".ui-menu").length) {
this.collapseAll(event, true);
}
this._trigger("select", event, ui);
}
});
}(jQuery));
(function($, undefined) {
$.ui = $.ui || {};
var cachedScrollbarWidth,
max = Math.max,
abs = Math.abs,
round = Math.round,
rhorizontal = /left|center|right/,
rvertical = /top|center|bottom/,
roffset = /[\+\-]\d+(\.[\d]+)?%?/,
rposition = /^\w+/,
rpercent = /%$/,
_position = $.fn.position;
function getOffsets(offsets, width, height) {
return [
parseFloat(offsets[ 0 ]) * (rpercent.test(offsets[ 0 ]) ? width / 100 : 1),
parseFloat(offsets[ 1 ]) * (rpercent.test(offsets[ 1 ]) ? height / 100 : 1)
];
}
function parseCss(element, property) {
return parseInt($.css(element, property), 10) || 0;
}
function getDimensions(elem) {
var raw = elem[0];
if (raw.nodeType === 9) {
return {
width: elem.width(),
height: elem.height(),
offset: {top: 0, left: 0}
};
}
if ($.isWindow(raw)) {
return {
width: elem.width(),
height: elem.height(),
offset: {top: elem.scrollTop(), left: elem.scrollLeft()}
};
}
if (raw.preventDefault) {
return {
width: 0,
height: 0,
offset: {top: raw.pageY, left: raw.pageX}
};
}
return {
width: elem.outerWidth(),
height: elem.outerHeight(),
offset: elem.offset()
};
}
$.position = {
scrollbarWidth: function() {
if (cachedScrollbarWidth !== undefined) {
return cachedScrollbarWidth;
}
var w1, w2,
div = $("<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),
innerDiv = div.children()[0];
$("body").append(div);
w1 = innerDiv.offsetWidth;
div.css("overflow", "scroll");
w2 = innerDiv.offsetWidth;
if (w1 === w2) {
w2 = div[0].clientWidth;
}
div.remove();
return (cachedScrollbarWidth = w1 - w2);
},
getScrollInfo: function(within) {
var overflowX = within.isWindow ? "" : within.element.css("overflow-x"),
overflowY = within.isWindow ? "" : within.element.css("overflow-y"),
hasOverflowX = overflowX === "scroll" ||
(overflowX === "auto" && within.width < within.element[0].scrollWidth),
hasOverflowY = overflowY === "scroll" ||
(overflowY === "auto" && within.height < within.element[0].scrollHeight);
return {
width: hasOverflowY ? $.position.scrollbarWidth() : 0,
height: hasOverflowX ? $.position.scrollbarWidth() : 0
};
},
getWithinInfo: function(element) {
var withinElement = $(element || window),
isWindow = $.isWindow(withinElement[0]);
return {
element: withinElement,
isWindow: isWindow,
offset: withinElement.offset() || {left: 0, top: 0},
scrollLeft: withinElement.scrollLeft(),
scrollTop: withinElement.scrollTop(),
width: isWindow ? withinElement.width() : withinElement.outerWidth(),
height: isWindow ? withinElement.height() : withinElement.outerHeight()
};
}
};
$.fn.position = function(options) {
if (!options || !options.of) {
return _position.apply(this, arguments);
}
// make a copy, we don't want to modify arguments
options = $.extend({}, options);
var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
target = $(options.of),
within = $.position.getWithinInfo(options.within),
scrollInfo = $.position.getScrollInfo(within),
collision = (options.collision || "flip").split(" "),
offsets = {};
dimensions = getDimensions(target);
if (target[0].preventDefault) {
// force left top to allow flipping
options.at = "left top";
}
targetWidth = dimensions.width;
targetHeight = dimensions.height;
targetOffset = dimensions.offset;
// clone to reuse original targetOffset later
basePosition = $.extend({}, targetOffset);
// force my and at to have valid horizontal and vertical positions
// if a value is missing or invalid, it will be converted to center
$.each(["my", "at"], function() {
var pos = (options[ this ] || "").split(" "),
horizontalOffset,
verticalOffset;
if (pos.length === 1) {
pos = rhorizontal.test(pos[ 0 ]) ?
pos.concat(["center"]) :
rvertical.test(pos[ 0 ]) ?
["center"].concat(pos) :
["center", "center"];
}
pos[ 0 ] = rhorizontal.test(pos[ 0 ]) ? pos[ 0 ] : "center";
pos[ 1 ] = rvertical.test(pos[ 1 ]) ? pos[ 1 ] : "center";
// calculate offsets
horizontalOffset = roffset.exec(pos[ 0 ]);
verticalOffset = roffset.exec(pos[ 1 ]);
offsets[ this ] = [
horizontalOffset ? horizontalOffset[ 0 ] : 0,
verticalOffset ? verticalOffset[ 0 ] : 0
];
// reduce to just the positions without the offsets
options[ this ] = [
rposition.exec(pos[ 0 ])[ 0 ],
rposition.exec(pos[ 1 ])[ 0 ]
];
});
// normalize collision option
if (collision.length === 1) {
collision[ 1 ] = collision[ 0 ];
}
if (options.at[ 0 ] === "right") {
basePosition.left += targetWidth;
} else if (options.at[ 0 ] === "center") {
basePosition.left += targetWidth / 2;
}
if (options.at[ 1 ] === "bottom") {
basePosition.top += targetHeight;
} else if (options.at[ 1 ] === "center") {
basePosition.top += targetHeight / 2;
}
atOffset = getOffsets(offsets.at, targetWidth, targetHeight);
basePosition.left += atOffset[ 0 ];
basePosition.top += atOffset[ 1 ];
return this.each(function() {
var collisionPosition, using,
elem = $(this),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseCss(this, "marginLeft"),
marginTop = parseCss(this, "marginTop"),
collisionWidth = elemWidth + marginLeft + parseCss(this, "marginRight") + scrollInfo.width,
collisionHeight = elemHeight + marginTop + parseCss(this, "marginBottom") + scrollInfo.height,
position = $.extend({}, basePosition),
myOffset = getOffsets(offsets.my, elem.outerWidth(), elem.outerHeight());
if (options.my[ 0 ] === "right") {
position.left -= elemWidth;
} else if (options.my[ 0 ] === "center") {
position.left -= elemWidth / 2;
}
if (options.my[ 1 ] === "bottom") {
position.top -= elemHeight;
} else if (options.my[ 1 ] === "center") {
position.top -= elemHeight / 2;
}
position.left += myOffset[ 0 ];
position.top += myOffset[ 1 ];
// if the browser doesn't support fractions, then round for consistent results
if (!$.support.offsetFractions) {
position.left = round(position.left);
position.top = round(position.top);
}
collisionPosition = {
marginLeft: marginLeft,
marginTop: marginTop
};
$.each(["left", "top"], function(i, dir) {
if ($.ui.position[ collision[ i ] ]) {
$.ui.position[ collision[ i ] ][ dir ](position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: [atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ]],
my: options.my,
at: options.at,
within: within,
elem: elem
});
}
});
if (options.using) {
// adds feedback as second argument to using callback, if present
using = function(props) {
var left = targetOffset.left - position.left,
right = left + targetWidth - elemWidth,
top = targetOffset.top - position.top,
bottom = top + targetHeight - elemHeight,
feedback = {
target: {
element: target,
left: targetOffset.left,
top: targetOffset.top,
width: targetWidth,
height: targetHeight
},
element: {
element: elem,
left: position.left,
top: position.top,
width: elemWidth,
height: elemHeight
},
horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
};
if (targetWidth < elemWidth && abs(left + right) < targetWidth) {
feedback.horizontal = "center";
}
if (targetHeight < elemHeight && abs(top + bottom) < targetHeight) {
feedback.vertical = "middle";
}
if (max(abs(left), abs(right)) > max(abs(top), abs(bottom))) {
feedback.important = "horizontal";
} else {
feedback.important = "vertical";
}
options.using.call(this, props, feedback);
};
}
elem.offset($.extend(position, {using: using}));
});
};
$.ui.position = {
fit: {
left: function(position, data) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
outerWidth = within.width,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = withinOffset - collisionPosLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
newOverRight;
// element is wider than within
if (data.collisionWidth > outerWidth) {
// element is initially over the left side of within
if (overLeft > 0 && overRight <= 0) {
newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
position.left += overLeft - newOverRight;
// element is initially over right side of within
} else if (overRight > 0 && overLeft <= 0) {
position.left = withinOffset;
// element is initially over both left and right sides of within
} else {
if (overLeft > overRight) {
position.left = withinOffset + outerWidth - data.collisionWidth;
} else {
position.left = withinOffset;
}
}
// too far left -> align with left edge
} else if (overLeft > 0) {
position.left += overLeft;
// too far right -> align with right edge
} else if (overRight > 0) {
position.left -= overRight;
// adjust based on position and margin
} else {
position.left = max(position.left - collisionPosLeft, position.left);
}
},
top: function(position, data) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
outerHeight = data.within.height,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = withinOffset - collisionPosTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
newOverBottom;
// element is taller than within
if (data.collisionHeight > outerHeight) {
// element is initially over the top of within
if (overTop > 0 && overBottom <= 0) {
newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
position.top += overTop - newOverBottom;
// element is initially over bottom of within
} else if (overBottom > 0 && overTop <= 0) {
position.top = withinOffset;
// element is initially over both top and bottom of within
} else {
if (overTop > overBottom) {
position.top = withinOffset + outerHeight - data.collisionHeight;
} else {
position.top = withinOffset;
}
}
// too far up -> align with top
} else if (overTop > 0) {
position.top += overTop;
// too far down -> align with bottom edge
} else if (overBottom > 0) {
position.top -= overBottom;
// adjust based on position and margin
} else {
position.top = max(position.top - collisionPosTop, position.top);
}
}
},
flip: {
left: function(position, data) {
var within = data.within,
withinOffset = within.offset.left + within.scrollLeft,
outerWidth = within.width,
offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = collisionPosLeft - offsetLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
data.at[ 0 ] === "right" ?
-data.targetWidth :
0,
offset = -2 * data.offset[ 0 ],
newOverRight,
newOverLeft;
if (overLeft < 0) {
newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
if (newOverRight < 0 || newOverRight < abs(overLeft)) {
position.left += myOffset + atOffset + offset;
}
}
else if (overRight > 0) {
newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
if (newOverLeft > 0 || abs(newOverLeft) < overRight) {
position.left += myOffset + atOffset + offset;
}
}
},
top: function(position, data) {
var within = data.within,
withinOffset = within.offset.top + within.scrollTop,
outerHeight = within.height,
offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = collisionPosTop - offsetTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
top = data.my[ 1 ] === "top",
myOffset = top ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
data.at[ 1 ] === "bottom" ?
-data.targetHeight :
0,
offset = -2 * data.offset[ 1 ],
newOverTop,
newOverBottom;
if (overTop < 0) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
if ((position.top + myOffset + atOffset + offset) > overTop && (newOverBottom < 0 || newOverBottom < abs(overTop))) {
position.top += myOffset + atOffset + offset;
}
}
else if (overBottom > 0) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
if ((position.top + myOffset + atOffset + offset) > overBottom && (newOverTop > 0 || abs(newOverTop) < overBottom)) {
position.top += myOffset + atOffset + offset;
}
}
}
},
flipfit: {
left: function() {
$.ui.position.flip.left.apply(this, arguments);
$.ui.position.fit.left.apply(this, arguments);
},
top: function() {
$.ui.position.flip.top.apply(this, arguments);
$.ui.position.fit.top.apply(this, arguments);
}
}
};
// fraction support test
(function() {
var testElement, testElementParent, testElementStyle, offsetLeft, i,
body = document.getElementsByTagName("body")[ 0 ],
div = document.createElement("div");
//Create a "fake body" for testing based on method used in jQuery.support
testElement = document.createElement(body ? "div" : "body");
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
};
if (body) {
$.extend(testElementStyle, {
position: "absolute",
left: "-1000px",
top: "-1000px"
});
}
for (i in testElementStyle) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild(div);
testElementParent = body || document.documentElement;
testElementParent.insertBefore(testElement, testElementParent.firstChild);
div.style.cssText = "position: absolute; left: 10.7432222px;";
offsetLeft = $(div).offset().left;
$.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;
testElement.innerHTML = "";
testElementParent.removeChild(testElement);
})();
}(jQuery));
(function($, undefined) {
$.widget("ui.progressbar", {
version: "1.10.3",
options: {
max: 100,
value: 0,
change: null,
complete: null
},
min: 0,
_create: function() {
// Constrain initial value
this.oldValue = this.options.value = this._constrainedValue();
this.element
.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all")
.attr({
// Only set static values, aria-valuenow and aria-valuemax are
// set inside _refreshValue()
role: "progressbar",
"aria-valuemin": this.min
});
this.valueDiv = $("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>")
.appendTo(this.element);
this._refreshValue();
},
_destroy: function() {
this.element
.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all")
.removeAttr("role")
.removeAttr("aria-valuemin")
.removeAttr("aria-valuemax")
.removeAttr("aria-valuenow");
this.valueDiv.remove();
},
value: function(newValue) {
if (newValue === undefined) {
return this.options.value;
}
this.options.value = this._constrainedValue(newValue);
this._refreshValue();
},
_constrainedValue: function(newValue) {
if (newValue === undefined) {
newValue = this.options.value;
}
this.indeterminate = newValue === false;
// sanitize value
if (typeof newValue !== "number") {
newValue = 0;
}
return this.indeterminate ? false :
Math.min(this.options.max, Math.max(this.min, newValue));
},
_setOptions: function(options) {
// Ensure "value" option is set after other values (like max)
var value = options.value;
delete options.value;
this._super(options);
this.options.value = this._constrainedValue(value);
this._refreshValue();
},
_setOption: function(key, value) {
if (key === "max") {
// Don't allow a max less than min
value = Math.max(this.min, value);
}
this._super(key, value);
},
_percentage: function() {
return this.indeterminate ? 100 : 100 * (this.options.value - this.min) / (this.options.max - this.min);
},
_refreshValue: function() {
var value = this.options.value,
percentage = this._percentage();
this.valueDiv
.toggle(this.indeterminate || value > this.min)
.toggleClass("ui-corner-right", value === this.options.max)
.width(percentage.toFixed(0) + "%");
this.element.toggleClass("ui-progressbar-indeterminate", this.indeterminate);
if (this.indeterminate) {
this.element.removeAttr("aria-valuenow");
if (!this.overlayDiv) {
this.overlayDiv = $("<div class='ui-progressbar-overlay'></div>").appendTo(this.valueDiv);
}
} else {
this.element.attr({
"aria-valuemax": this.options.max,
"aria-valuenow": value
});
if (this.overlayDiv) {
this.overlayDiv.remove();
this.overlayDiv = null;
}
}
if (this.oldValue !== value) {
this.oldValue = value;
this._trigger("change");
}
if (value === this.options.max) {
this._trigger("complete");
}
}
});
})(jQuery);
(function($, undefined) {
// number of pages in a slider
// (how many times can you page up/down to go through the whole range)
var numPages = 5;
$.widget("ui.slider", $.ui.mouse, {
version: "1.10.3",
widgetEventPrefix: "slide",
options: {
animate: false,
distance: 0,
max: 100,
min: 0,
orientation: "horizontal",
range: false,
step: 1,
value: 0,
values: null,
// callbacks
change: null,
slide: null,
start: null,
stop: null
},
_create: function() {
this._keySliding = false;
this._mouseSliding = false;
this._animateOff = true;
this._handleIndex = null;
this._detectOrientation();
this._mouseInit();
this.element
.addClass("ui-slider" +
" ui-slider-" + this.orientation +
" ui-widget" +
" ui-widget-content" +
" ui-corner-all");
this._refresh();
this._setOption("disabled", this.options.disabled);
this._animateOff = false;
},
_refresh: function() {
this._createRange();
this._createHandles();
this._setupEvents();
this._refreshValue();
},
_createHandles: function() {
var i, handleCount,
options = this.options,
existingHandles = this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),
handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
handles = [];
handleCount = (options.values && options.values.length) || 1;
if (existingHandles.length > handleCount) {
existingHandles.slice(handleCount).remove();
existingHandles = existingHandles.slice(0, handleCount);
}
for (i = existingHandles.length; i < handleCount; i++) {
handles.push(handle);
}
this.handles = existingHandles.add($(handles.join("")).appendTo(this.element));
this.handle = this.handles.eq(0);
this.handles.each(function(i) {
$(this).data("ui-slider-handle-index", i);
});
},
_createRange: function() {
var options = this.options,
classes = "";
if (options.range) {
if (options.range === true) {
if (!options.values) {
options.values = [this._valueMin(), this._valueMin()];
} else if (options.values.length && options.values.length !== 2) {
options.values = [options.values[0], options.values[0]];
} else if ($.isArray(options.values)) {
options.values = options.values.slice(0);
}
}
if (!this.range || !this.range.length) {
this.range = $("<div></div>")
.appendTo(this.element);
classes = "ui-slider-range" +
// note: this isn't the most fittingly semantic framework class for this element,
// but worked best visually with a variety of themes
" ui-widget-header ui-corner-all";
} else {
this.range.removeClass("ui-slider-range-min ui-slider-range-max")
// Handle range switching from true to min/max
.css({
"left": "",
"bottom": ""
});
}
this.range.addClass(classes +
((options.range === "min" || options.range === "max") ? " ui-slider-range-" + options.range : ""));
} else {
this.range = $([]);
}
},
_setupEvents: function() {
var elements = this.handles.add(this.range).filter("a");
this._off(elements);
this._on(elements, this._handleEvents);
this._hoverable(elements);
this._focusable(elements);
},
_destroy: function() {
this.handles.remove();
this.range.remove();
this.element
.removeClass("ui-slider" +
" ui-slider-horizontal" +
" ui-slider-vertical" +
" ui-widget" +
" ui-widget-content" +
" ui-corner-all");
this._mouseDestroy();
},
_mouseCapture: function(event) {
var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
that = this,
o = this.options;
if (o.disabled) {
return false;
}
this.elementSize = {
width: this.element.outerWidth(),
height: this.element.outerHeight()
};
this.elementOffset = this.element.offset();
position = {x: event.pageX, y: event.pageY};
normValue = this._normValueFromMouse(position);
distance = this._valueMax() - this._valueMin() + 1;
this.handles.each(function(i) {
var thisDistance = Math.abs(normValue - that.values(i));
if ((distance > thisDistance) ||
(distance === thisDistance &&
(i === that._lastChangedValue || that.values(i) === o.min))) {
distance = thisDistance;
closestHandle = $(this);
index = i;
}
});
allowed = this._start(event, index);
if (allowed === false) {
return false;
}
this._mouseSliding = true;
this._handleIndex = index;
closestHandle
.addClass("ui-state-active")
.focus();
offset = closestHandle.offset();
mouseOverHandle = !$(event.target).parents().addBack().is(".ui-slider-handle");
this._clickOffset = mouseOverHandle ? {left: 0, top: 0} : {
left: event.pageX - offset.left - (closestHandle.width() / 2),
top: event.pageY - offset.top -
(closestHandle.height() / 2) -
(parseInt(closestHandle.css("borderTopWidth"), 10) || 0) -
(parseInt(closestHandle.css("borderBottomWidth"), 10) || 0) +
(parseInt(closestHandle.css("marginTop"), 10) || 0)
};
if (!this.handles.hasClass("ui-state-hover")) {
this._slide(event, index, normValue);
}
this._animateOff = true;
return true;
},
_mouseStart: function() {
return true;
},
_mouseDrag: function(event) {
var position = {x: event.pageX, y: event.pageY},
normValue = this._normValueFromMouse(position);
this._slide(event, this._handleIndex, normValue);
return false;
},
_mouseStop: function(event) {
this.handles.removeClass("ui-state-active");
this._mouseSliding = false;
this._stop(event, this._handleIndex);
this._change(event, this._handleIndex);
this._handleIndex = null;
this._clickOffset = null;
this._animateOff = false;
return false;
},
_detectOrientation: function() {
this.orientation = (this.options.orientation === "vertical") ? "vertical" : "horizontal";
},
_normValueFromMouse: function(position) {
var pixelTotal,
pixelMouse,
percentMouse,
valueTotal,
valueMouse;
if (this.orientation === "horizontal") {
pixelTotal = this.elementSize.width;
pixelMouse = position.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0);
} else {
pixelTotal = this.elementSize.height;
pixelMouse = position.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0);
}
percentMouse = (pixelMouse / pixelTotal);
if (percentMouse > 1) {
percentMouse = 1;
}
if (percentMouse < 0) {
percentMouse = 0;
}
if (this.orientation === "vertical") {
percentMouse = 1 - percentMouse;
}
valueTotal = this._valueMax() - this._valueMin();
valueMouse = this._valueMin() + percentMouse * valueTotal;
return this._trimAlignValue(valueMouse);
},
_start: function(event, index) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if (this.options.values && this.options.values.length) {
uiHash.value = this.values(index);
uiHash.values = this.values();
}
return this._trigger("start", event, uiHash);
},
_slide: function(event, index, newVal) {
var otherVal,
newValues,
allowed;
if (this.options.values && this.options.values.length) {
otherVal = this.values(index ? 0 : 1);
if ((this.options.values.length === 2 && this.options.range === true) &&
((index === 0 && newVal > otherVal) || (index === 1 && newVal < otherVal))
) {
newVal = otherVal;
}
if (newVal !== this.values(index)) {
newValues = this.values();
newValues[ index ] = newVal;
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger("slide", event, {
handle: this.handles[ index ],
value: newVal,
values: newValues
});
otherVal = this.values(index ? 0 : 1);
if (allowed !== false) {
this.values(index, newVal, true);
}
}
} else {
if (newVal !== this.value()) {
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger("slide", event, {
handle: this.handles[ index ],
value: newVal
});
if (allowed !== false) {
this.value(newVal);
}
}
}
},
_stop: function(event, index) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if (this.options.values && this.options.values.length) {
uiHash.value = this.values(index);
uiHash.values = this.values();
}
this._trigger("stop", event, uiHash);
},
_change: function(event, index) {
if (!this._keySliding && !this._mouseSliding) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if (this.options.values && this.options.values.length) {
uiHash.value = this.values(index);
uiHash.values = this.values();
}
//store the last changed value index for reference when handles overlap
this._lastChangedValue = index;
this._trigger("change", event, uiHash);
}
},
value: function(newValue) {
if (arguments.length) {
this.options.value = this._trimAlignValue(newValue);
this._refreshValue();
this._change(null, 0);
return;
}
return this._value();
},
values: function(index, newValue) {
var vals,
newValues,
i;
if (arguments.length > 1) {
this.options.values[ index ] = this._trimAlignValue(newValue);
this._refreshValue();
this._change(null, index);
return;
}
if (arguments.length) {
if ($.isArray(arguments[ 0 ])) {
vals = this.options.values;
newValues = arguments[ 0 ];
for (i = 0; i < vals.length; i += 1) {
vals[ i ] = this._trimAlignValue(newValues[ i ]);
this._change(null, i);
}
this._refreshValue();
} else {
if (this.options.values && this.options.values.length) {
return this._values(index);
} else {
return this.value();
}
}
} else {
return this._values();
}
},
_setOption: function(key, value) {
var i,
valsLength = 0;
if (key === "range" && this.options.range === true) {
if (value === "min") {
this.options.value = this._values(0);
this.options.values = null;
} else if (value === "max") {
this.options.value = this._values(this.options.values.length - 1);
this.options.values = null;
}
}
if ($.isArray(this.options.values)) {
valsLength = this.options.values.length;
}
$.Widget.prototype._setOption.apply(this, arguments);
switch (key) {
case "orientation":
this._detectOrientation();
this.element
.removeClass("ui-slider-horizontal ui-slider-vertical")
.addClass("ui-slider-" + this.orientation);
this._refreshValue();
break;
case "value":
this._animateOff = true;
this._refreshValue();
this._change(null, 0);
this._animateOff = false;
break;
case "values":
this._animateOff = true;
this._refreshValue();
for (i = 0; i < valsLength; i += 1) {
this._change(null, i);
}
this._animateOff = false;
break;
case "min":
case "max":
this._animateOff = true;
this._refreshValue();
this._animateOff = false;
break;
case "range":
this._animateOff = true;
this._refresh();
this._animateOff = false;
break;
}
},
//internal value getter
// _value() returns value trimmed by min and max, aligned by step
_value: function() {
var val = this.options.value;
val = this._trimAlignValue(val);
return val;
},
//internal values getter
// _values() returns array of values trimmed by min and max, aligned by step
// _values( index ) returns single value trimmed by min and max, aligned by step
_values: function(index) {
var val,
vals,
i;
if (arguments.length) {
val = this.options.values[ index ];
val = this._trimAlignValue(val);
return val;
} else if (this.options.values && this.options.values.length) {
// .slice() creates a copy of the array
// this copy gets trimmed by min and max and then returned
vals = this.options.values.slice();
for (i = 0; i < vals.length; i += 1) {
vals[ i ] = this._trimAlignValue(vals[ i ]);
}
return vals;
} else {
return [];
}
},
// returns the step-aligned value that val is closest to, between (inclusive) min and max
_trimAlignValue: function(val) {
if (val <= this._valueMin()) {
return this._valueMin();
}
if (val >= this._valueMax()) {
return this._valueMax();
}
var step = (this.options.step > 0) ? this.options.step : 1,
valModStep = (val - this._valueMin()) % step,
alignValue = val - valModStep;
if (Math.abs(valModStep) * 2 >= step) {
alignValue += (valModStep > 0) ? step : (-step);
}
// Since JavaScript has problems with large floats, round
// the final value to 5 digits after the decimal point (see #4124)
return parseFloat(alignValue.toFixed(5));
},
_valueMin: function() {
return this.options.min;
},
_valueMax: function() {
return this.options.max;
},
_refreshValue: function() {
var lastValPercent, valPercent, value, valueMin, valueMax,
oRange = this.options.range,
o = this.options,
that = this,
animate = (!this._animateOff) ? o.animate : false,
_set = {};
if (this.options.values && this.options.values.length) {
this.handles.each(function(i) {
valPercent = (that.values(i) - that._valueMin()) / (that._valueMax() - that._valueMin()) * 100;
_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
$(this).stop(1, 1)[ animate ? "animate" : "css" ](_set, o.animate);
if (that.options.range === true) {
if (that.orientation === "horizontal") {
if (i === 0) {
that.range.stop(1, 1)[ animate ? "animate" : "css" ]({left: valPercent + "%"}, o.animate);
}
if (i === 1) {
that.range[ animate ? "animate" : "css" ]({width: (valPercent - lastValPercent) + "%"}, {queue: false, duration: o.animate});
}
} else {
if (i === 0) {
that.range.stop(1, 1)[ animate ? "animate" : "css" ]({bottom: (valPercent) + "%"}, o.animate);
}
if (i === 1) {
that.range[ animate ? "animate" : "css" ]({height: (valPercent - lastValPercent) + "%"}, {queue: false, duration: o.animate});
}
}
}
lastValPercent = valPercent;
});
} else {
value = this.value();
valueMin = this._valueMin();
valueMax = this._valueMax();
valPercent = (valueMax !== valueMin) ?
(value - valueMin) / (valueMax - valueMin) * 100 :
0;
_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
this.handle.stop(1, 1)[ animate ? "animate" : "css" ](_set, o.animate);
if (oRange === "min" && this.orientation === "horizontal") {
this.range.stop(1, 1)[ animate ? "animate" : "css" ]({width: valPercent + "%"}, o.animate);
}
if (oRange === "max" && this.orientation === "horizontal") {
this.range[ animate ? "animate" : "css" ]({width: (100 - valPercent) + "%"}, {queue: false, duration: o.animate});
}
if (oRange === "min" && this.orientation === "vertical") {
this.range.stop(1, 1)[ animate ? "animate" : "css" ]({height: valPercent + "%"}, o.animate);
}
if (oRange === "max" && this.orientation === "vertical") {
this.range[ animate ? "animate" : "css" ]({height: (100 - valPercent) + "%"}, {queue: false, duration: o.animate});
}
}
},
_handleEvents: {
keydown: function(event) {
/*jshint maxcomplexity:25*/
var allowed, curVal, newVal, step,
index = $(event.target).data("ui-slider-handle-index");
switch (event.keyCode) {
case $.ui.keyCode.HOME:
case $.ui.keyCode.END:
case $.ui.keyCode.PAGE_UP:
case $.ui.keyCode.PAGE_DOWN:
case $.ui.keyCode.UP:
case $.ui.keyCode.RIGHT:
case $.ui.keyCode.DOWN:
case $.ui.keyCode.LEFT:
event.preventDefault();
if (!this._keySliding) {
this._keySliding = true;
$(event.target).addClass("ui-state-active");
allowed = this._start(event, index);
if (allowed === false) {
return;
}
}
break;
}
step = this.options.step;
if (this.options.values && this.options.values.length) {
curVal = newVal = this.values(index);
} else {
curVal = newVal = this.value();
}
switch (event.keyCode) {
case $.ui.keyCode.HOME:
newVal = this._valueMin();
break;
case $.ui.keyCode.END:
newVal = this._valueMax();
break;
case $.ui.keyCode.PAGE_UP:
newVal = this._trimAlignValue(curVal + ((this._valueMax() - this._valueMin()) / numPages));
break;
case $.ui.keyCode.PAGE_DOWN:
newVal = this._trimAlignValue(curVal - ((this._valueMax() - this._valueMin()) / numPages));
break;
case $.ui.keyCode.UP:
case $.ui.keyCode.RIGHT:
if (curVal === this._valueMax()) {
return;
}
newVal = this._trimAlignValue(curVal + step);
break;
case $.ui.keyCode.DOWN:
case $.ui.keyCode.LEFT:
if (curVal === this._valueMin()) {
return;
}
newVal = this._trimAlignValue(curVal - step);
break;
}
this._slide(event, index, newVal);
},
click: function(event) {
event.preventDefault();
},
keyup: function(event) {
var index = $(event.target).data("ui-slider-handle-index");
if (this._keySliding) {
this._keySliding = false;
this._stop(event, index);
this._change(event, index);
$(event.target).removeClass("ui-state-active");
}
}
}
});
}(jQuery));
(function($) {
function modifier(fn) {
return function() {
var previous = this.element.val();
fn.apply(this, arguments);
this._refresh();
if (previous !== this.element.val()) {
this._trigger("change");
}
};
}
$.widget("ui.spinner", {
version: "1.10.3",
defaultElement: "<input>",
widgetEventPrefix: "spin",
options: {
culture: null,
icons: {
down: "ui-icon-triangle-1-s",
up: "ui-icon-triangle-1-n"
},
incremental: true,
max: null,
min: null,
numberFormat: null,
page: 10,
step: 1,
change: null,
spin: null,
start: null,
stop: null
},
_create: function() {
// handle string values that need to be parsed
this._setOption("max", this.options.max);
this._setOption("min", this.options.min);
this._setOption("step", this.options.step);
// format the value, but don't constrain
this._value(this.element.val(), true);
this._draw();
this._on(this._events);
this._refresh();
// turning off autocomplete prevents the browser from remembering the
// value when navigating through history, so we re-enable autocomplete
// if the page is unloaded before the widget is destroyed. #7790
this._on(this.window, {
beforeunload: function() {
this.element.removeAttr("autocomplete");
}
});
},
_getCreateOptions: function() {
var options = {},
element = this.element;
$.each(["min", "max", "step"], function(i, option) {
var value = element.attr(option);
if (value !== undefined && value.length) {
options[ option ] = value;
}
});
return options;
},
_events: {
keydown: function(event) {
if (this._start(event) && this._keydown(event)) {
event.preventDefault();
}
},
keyup: "_stop",
focus: function() {
this.previous = this.element.val();
},
blur: function(event) {
if (this.cancelBlur) {
delete this.cancelBlur;
return;
}
this._stop();
this._refresh();
if (this.previous !== this.element.val()) {
this._trigger("change", event);
}
},
mousewheel: function(event, delta) {
if (!delta) {
return;
}
if (!this.spinning && !this._start(event)) {
return false;
}
this._spin((delta > 0 ? 1 : -1) * this.options.step, event);
clearTimeout(this.mousewheelTimer);
this.mousewheelTimer = this._delay(function() {
if (this.spinning) {
this._stop(event);
}
}, 100);
event.preventDefault();
},
"mousedown .ui-spinner-button": function(event) {
var previous;
// We never want the buttons to have focus; whenever the user is
// interacting with the spinner, the focus should be on the input.
// If the input is focused then this.previous is properly set from
// when the input first received focus. If the input is not focused
// then we need to set this.previous based on the value before spinning.
previous = this.element[0] === this.document[0].activeElement ?
this.previous : this.element.val();
function checkFocus() {
var isActive = this.element[0] === this.document[0].activeElement;
if (!isActive) {
this.element.focus();
this.previous = previous;
// support: IE
// IE sets focus asynchronously, so we need to check if focus
// moved off of the input because the user clicked on the button.
this._delay(function() {
this.previous = previous;
});
}
}
// ensure focus is on (or stays on) the text field
event.preventDefault();
checkFocus.call(this);
// support: IE
// IE doesn't prevent moving focus even with event.preventDefault()
// so we set a flag to know when we should ignore the blur event
// and check (again) if focus moved off of the input.
this.cancelBlur = true;
this._delay(function() {
delete this.cancelBlur;
checkFocus.call(this);
});
if (this._start(event) === false) {
return;
}
this._repeat(null, $(event.currentTarget).hasClass("ui-spinner-up") ? 1 : -1, event);
},
"mouseup .ui-spinner-button": "_stop",
"mouseenter .ui-spinner-button": function(event) {
// button will add ui-state-active if mouse was down while mouseleave and kept down
if (!$(event.currentTarget).hasClass("ui-state-active")) {
return;
}
if (this._start(event) === false) {
return false;
}
this._repeat(null, $(event.currentTarget).hasClass("ui-spinner-up") ? 1 : -1, event);
},
// TODO: do we really want to consider this a stop?
// shouldn't we just stop the repeater and wait until mouseup before
// we trigger the stop event?
"mouseleave .ui-spinner-button": "_stop"
},
_draw: function() {
var uiSpinner = this.uiSpinner = this.element
.addClass("ui-spinner-input")
.attr("autocomplete", "off")
.wrap(this._uiSpinnerHtml())
.parent()
// add buttons
.append(this._buttonHtml());
this.element.attr("role", "spinbutton");
// button bindings
this.buttons = uiSpinner.find(".ui-spinner-button")
.attr("tabIndex", -1)
.button()
.removeClass("ui-corner-all");
// IE 6 doesn't understand height: 50% for the buttons
// unless the wrapper has an explicit height
if (this.buttons.height() > Math.ceil(uiSpinner.height() * 0.5) &&
uiSpinner.height() > 0) {
uiSpinner.height(uiSpinner.height());
}
// disable spinner if element was already disabled
if (this.options.disabled) {
this.disable();
}
},
_keydown: function(event) {
var options = this.options,
keyCode = $.ui.keyCode;
switch (event.keyCode) {
case keyCode.UP:
this._repeat(null, 1, event);
return true;
case keyCode.DOWN:
this._repeat(null, -1, event);
return true;
case keyCode.PAGE_UP:
this._repeat(null, options.page, event);
return true;
case keyCode.PAGE_DOWN:
this._repeat(null, -options.page, event);
return true;
}
return false;
},
_uiSpinnerHtml: function() {
return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>";
},
_buttonHtml: function() {
return "" +
"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" +
"<span class='ui-icon " + this.options.icons.up + "'>▲</span>" +
"</a>" +
"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" +
"<span class='ui-icon " + this.options.icons.down + "'>▼</span>" +
"</a>";
},
_start: function(event) {
if (!this.spinning && this._trigger("start", event) === false) {
return false;
}
if (!this.counter) {
this.counter = 1;
}
this.spinning = true;
return true;
},
_repeat: function(i, steps, event) {
i = i || 500;
clearTimeout(this.timer);
this.timer = this._delay(function() {
this._repeat(40, steps, event);
}, i);
this._spin(steps * this.options.step, event);
},
_spin: function(step, event) {
var value = this.value() || 0;
if (!this.counter) {
this.counter = 1;
}
value = this._adjustValue(value + step * this._increment(this.counter));
if (!this.spinning || this._trigger("spin", event, {value: value}) !== false) {
this._value(value);
this.counter++;
}
},
_increment: function(i) {
var incremental = this.options.incremental;
if (incremental) {
return $.isFunction(incremental) ?
incremental(i) :
Math.floor(i * i * i / 50000 - i * i / 500 + 17 * i / 200 + 1);
}
return 1;
},
_precision: function() {
var precision = this._precisionOf(this.options.step);
if (this.options.min !== null) {
precision = Math.max(precision, this._precisionOf(this.options.min));
}
return precision;
},
_precisionOf: function(num) {
var str = num.toString(),
decimal = str.indexOf(".");
return decimal === -1 ? 0 : str.length - decimal - 1;
},
_adjustValue: function(value) {
var base, aboveMin,
options = this.options;
// make sure we're at a valid step
// - find out where we are relative to the base (min or 0)
base = options.min !== null ? options.min : 0;
aboveMin = value - base;
// - round to the nearest step
aboveMin = Math.round(aboveMin / options.step) * options.step;
// - rounding is based on 0, so adjust back to our base
value = base + aboveMin;
// fix precision from bad JS floating point math
value = parseFloat(value.toFixed(this._precision()));
// clamp the value
if (options.max !== null && value > options.max) {
return options.max;
}
if (options.min !== null && value < options.min) {
return options.min;
}
return value;
},
_stop: function(event) {
if (!this.spinning) {
return;
}
clearTimeout(this.timer);
clearTimeout(this.mousewheelTimer);
this.counter = 0;
this.spinning = false;
this._trigger("stop", event);
},
_setOption: function(key, value) {
if (key === "culture" || key === "numberFormat") {
var prevValue = this._parse(this.element.val());
this.options[ key ] = value;
this.element.val(this._format(prevValue));
return;
}
if (key === "max" || key === "min" || key === "step") {
if (typeof value === "string") {
value = this._parse(value);
}
}
if (key === "icons") {
this.buttons.first().find(".ui-icon")
.removeClass(this.options.icons.up)
.addClass(value.up);
this.buttons.last().find(".ui-icon")
.removeClass(this.options.icons.down)
.addClass(value.down);
}
this._super(key, value);
if (key === "disabled") {
if (value) {
this.element.prop("disabled", true);
this.buttons.button("disable");
} else {
this.element.prop("disabled", false);
this.buttons.button("enable");
}
}
},
_setOptions: modifier(function(options) {
this._super(options);
this._value(this.element.val());
}),
_parse: function(val) {
if (typeof val === "string" && val !== "") {
val = window.Globalize && this.options.numberFormat ?
Globalize.parseFloat(val, 10, this.options.culture) : +val;
}
return val === "" || isNaN(val) ? null : val;
},
_format: function(value) {
if (value === "") {
return "";
}
return window.Globalize && this.options.numberFormat ?
Globalize.format(value, this.options.numberFormat, this.options.culture) :
value;
},
_refresh: function() {
this.element.attr({
"aria-valuemin": this.options.min,
"aria-valuemax": this.options.max,
// TODO: what should we do with values that can't be parsed?
"aria-valuenow": this._parse(this.element.val())
});
},
// update the value without triggering change
_value: function(value, allowAny) {
var parsed;
if (value !== "") {
parsed = this._parse(value);
if (parsed !== null) {
if (!allowAny) {
parsed = this._adjustValue(parsed);
}
value = this._format(parsed);
}
}
this.element.val(value);
this._refresh();
},
_destroy: function() {
this.element
.removeClass("ui-spinner-input")
.prop("disabled", false)
.removeAttr("autocomplete")
.removeAttr("role")
.removeAttr("aria-valuemin")
.removeAttr("aria-valuemax")
.removeAttr("aria-valuenow");
this.uiSpinner.replaceWith(this.element);
},
stepUp: modifier(function(steps) {
this._stepUp(steps);
}),
_stepUp: function(steps) {
if (this._start()) {
this._spin((steps || 1) * this.options.step);
this._stop();
}
},
stepDown: modifier(function(steps) {
this._stepDown(steps);
}),
_stepDown: function(steps) {
if (this._start()) {
this._spin((steps || 1) * -this.options.step);
this._stop();
}
},
pageUp: modifier(function(pages) {
this._stepUp((pages || 1) * this.options.page);
}),
pageDown: modifier(function(pages) {
this._stepDown((pages || 1) * this.options.page);
}),
value: function(newVal) {
if (!arguments.length) {
return this._parse(this.element.val());
}
modifier(this._value).call(this, newVal);
},
widget: function() {
return this.uiSpinner;
}
});
}(jQuery));
(function($, undefined) {
var tabId = 0,
rhash = /#.*$/;
function getNextTabId() {
return ++tabId;
}
function isLocal(anchor) {
return anchor.hash.length > 1 &&
decodeURIComponent(anchor.href.replace(rhash, "")) ===
decodeURIComponent(location.href.replace(rhash, ""));
}
$.widget("ui.tabs", {
version: "1.10.3",
delay: 300,
options: {
active: null,
collapsible: false,
event: "click",
heightStyle: "content",
hide: null,
show: null,
// callbacks
activate: null,
beforeActivate: null,
beforeLoad: null,
load: null
},
_create: function() {
var that = this,
options = this.options;
this.running = false;
this.element
.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all")
.toggleClass("ui-tabs-collapsible", options.collapsible)
// Prevent users from focusing disabled tabs via click
.delegate(".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function(event) {
if ($(this).is(".ui-state-disabled")) {
event.preventDefault();
}
})
// support: IE <9
// Preventing the default action in mousedown doesn't prevent IE
// from focusing the element, so if the anchor gets focused, blur.
// We don't have to worry about focusing the previously focused
// element since clicking on a non-focusable element should focus
// the body anyway.
.delegate(".ui-tabs-anchor", "focus" + this.eventNamespace, function() {
if ($(this).closest("li").is(".ui-state-disabled")) {
this.blur();
}
});
this._processTabs();
options.active = this._initialActive();
// Take disabling tabs via class attribute from HTML
// into account and update option properly.
if ($.isArray(options.disabled)) {
options.disabled = $.unique(options.disabled.concat(
$.map(this.tabs.filter(".ui-state-disabled"), function(li) {
return that.tabs.index(li);
})
)).sort();
}
// check for length avoids error when initializing empty list
if (this.options.active !== false && this.anchors.length) {
this.active = this._findActive(options.active);
} else {
this.active = $();
}
this._refresh();
if (this.active.length) {
this.load(options.active);
}
},
_initialActive: function() {
var active = this.options.active,
collapsible = this.options.collapsible,
locationHash = location.hash.substring(1);
if (active === null) {
// check the fragment identifier in the URL
if (locationHash) {
this.tabs.each(function(i, tab) {
if ($(tab).attr("aria-controls") === locationHash) {
active = i;
return false;
}
});
}
// check for a tab marked active via a class
if (active === null) {
active = this.tabs.index(this.tabs.filter(".ui-tabs-active"));
}
// no active tab, set to false
if (active === null || active === -1) {
active = this.tabs.length ? 0 : false;
}
}
// handle numbers: negative, out of range
if (active !== false) {
active = this.tabs.index(this.tabs.eq(active));
if (active === -1) {
active = collapsible ? false : 0;
}
}
// don't allow collapsible: false and active: false
if (!collapsible && active === false && this.anchors.length) {
active = 0;
}
return active;
},
_getCreateEventData: function() {
return {
tab: this.active,
panel: !this.active.length ? $() : this._getPanelForTab(this.active)
};
},
_tabKeydown: function(event) {
/*jshint maxcomplexity:15*/
var focusedTab = $(this.document[0].activeElement).closest("li"),
selectedIndex = this.tabs.index(focusedTab),
goingForward = true;
if (this._handlePageNav(event)) {
return;
}
switch (event.keyCode) {
case $.ui.keyCode.RIGHT:
case $.ui.keyCode.DOWN:
selectedIndex++;
break;
case $.ui.keyCode.UP:
case $.ui.keyCode.LEFT:
goingForward = false;
selectedIndex--;
break;
case $.ui.keyCode.END:
selectedIndex = this.anchors.length - 1;
break;
case $.ui.keyCode.HOME:
selectedIndex = 0;
break;
case $.ui.keyCode.SPACE:
// Activate only, no collapsing
event.preventDefault();
clearTimeout(this.activating);
this._activate(selectedIndex);
return;
case $.ui.keyCode.ENTER:
// Toggle (cancel delayed activation, allow collapsing)
event.preventDefault();
clearTimeout(this.activating);
// Determine if we should collapse or activate
this._activate(selectedIndex === this.options.active ? false : selectedIndex);
return;
default:
return;
}
// Focus the appropriate tab, based on which key was pressed
event.preventDefault();
clearTimeout(this.activating);
selectedIndex = this._focusNextTab(selectedIndex, goingForward);
// Navigating with control key will prevent automatic activation
if (!event.ctrlKey) {
// Update aria-selected immediately so that AT think the tab is already selected.
// Otherwise AT may confuse the user by stating that they need to activate the tab,
// but the tab will already be activated by the time the announcement finishes.
focusedTab.attr("aria-selected", "false");
this.tabs.eq(selectedIndex).attr("aria-selected", "true");
this.activating = this._delay(function() {
this.option("active", selectedIndex);
}, this.delay);
}
},
_panelKeydown: function(event) {
if (this._handlePageNav(event)) {
return;
}
// Ctrl+up moves focus to the current tab
if (event.ctrlKey && event.keyCode === $.ui.keyCode.UP) {
event.preventDefault();
this.active.focus();
}
},
// Alt+page up/down moves focus to the previous/next tab (and activates)
_handlePageNav: function(event) {
if (event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP) {
this._activate(this._focusNextTab(this.options.active - 1, false));
return true;
}
if (event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN) {
this._activate(this._focusNextTab(this.options.active + 1, true));
return true;
}
},
_findNextTab: function(index, goingForward) {
var lastTabIndex = this.tabs.length - 1;
function constrain() {
if (index > lastTabIndex) {
index = 0;
}
if (index < 0) {
index = lastTabIndex;
}
return index;
}
while ($.inArray(constrain(), this.options.disabled) !== -1) {
index = goingForward ? index + 1 : index - 1;
}
return index;
},
_focusNextTab: function(index, goingForward) {
index = this._findNextTab(index, goingForward);
this.tabs.eq(index).focus();
return index;
},
_setOption: function(key, value) {
if (key === "active") {
// _activate() will handle invalid values and update this.options
this._activate(value);
return;
}
if (key === "disabled") {
// don't use the widget factory's disabled handling
this._setupDisabled(value);
return;
}
this._super(key, value);
if (key === "collapsible") {
this.element.toggleClass("ui-tabs-collapsible", value);
// Setting collapsible: false while collapsed; open first panel
if (!value && this.options.active === false) {
this._activate(0);
}
}
if (key === "event") {
this._setupEvents(value);
}
if (key === "heightStyle") {
this._setupHeightStyle(value);
}
},
_tabId: function(tab) {
return tab.attr("aria-controls") || "ui-tabs-" + getNextTabId();
},
_sanitizeSelector: function(hash) {
return hash ? hash.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&") : "";
},
refresh: function() {
var options = this.options,
lis = this.tablist.children(":has(a[href])");
// get disabled tabs from class attribute from HTML
// this will get converted to a boolean if needed in _refresh()
options.disabled = $.map(lis.filter(".ui-state-disabled"), function(tab) {
return lis.index(tab);
});
this._processTabs();
// was collapsed or no tabs
if (options.active === false || !this.anchors.length) {
options.active = false;
this.active = $();
// was active, but active tab is gone
} else if (this.active.length && !$.contains(this.tablist[ 0 ], this.active[ 0 ])) {
// all remaining tabs are disabled
if (this.tabs.length === options.disabled.length) {
options.active = false;
this.active = $();
// activate previous tab
} else {
this._activate(this._findNextTab(Math.max(0, options.active - 1), false));
}
// was active, active tab still exists
} else {
// make sure active index is correct
options.active = this.tabs.index(this.active);
}
this._refresh();
},
_refresh: function() {
this._setupDisabled(this.options.disabled);
this._setupEvents(this.options.event);
this._setupHeightStyle(this.options.heightStyle);
this.tabs.not(this.active).attr({
"aria-selected": "false",
tabIndex: -1
});
this.panels.not(this._getPanelForTab(this.active))
.hide()
.attr({
"aria-expanded": "false",
"aria-hidden": "true"
});
// Make sure one tab is in the tab order
if (!this.active.length) {
this.tabs.eq(0).attr("tabIndex", 0);
} else {
this.active
.addClass("ui-tabs-active ui-state-active")
.attr({
"aria-selected": "true",
tabIndex: 0
});
this._getPanelForTab(this.active)
.show()
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
});
}
},
_processTabs: function() {
var that = this;
this.tablist = this._getList()
.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all")
.attr("role", "tablist");
this.tabs = this.tablist.find("> li:has(a[href])")
.addClass("ui-state-default ui-corner-top")
.attr({
role: "tab",
tabIndex: -1
});
this.anchors = this.tabs.map(function() {
return $("a", this)[ 0 ];
})
.addClass("ui-tabs-anchor")
.attr({
role: "presentation",
tabIndex: -1
});
this.panels = $();
this.anchors.each(function(i, anchor) {
var selector, panel, panelId,
anchorId = $(anchor).uniqueId().attr("id"),
tab = $(anchor).closest("li"),
originalAriaControls = tab.attr("aria-controls");
// inline tab
if (isLocal(anchor)) {
selector = anchor.hash;
panel = that.element.find(that._sanitizeSelector(selector));
// remote tab
} else {
panelId = that._tabId(tab);
selector = "#" + panelId;
panel = that.element.find(selector);
if (!panel.length) {
panel = that._createPanel(panelId);
panel.insertAfter(that.panels[ i - 1 ] || that.tablist);
}
panel.attr("aria-live", "polite");
}
if (panel.length) {
that.panels = that.panels.add(panel);
}
if (originalAriaControls) {
tab.data("ui-tabs-aria-controls", originalAriaControls);
}
tab.attr({
"aria-controls": selector.substring(1),
"aria-labelledby": anchorId
});
panel.attr("aria-labelledby", anchorId);
});
this.panels
.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom")
.attr("role", "tabpanel");
},
// allow overriding how to find the list for rare usage scenarios (#7715)
_getList: function() {
return this.element.find("ol,ul").eq(0);
},
_createPanel: function(id) {
return $("<div>")
.attr("id", id)
.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom")
.data("ui-tabs-destroy", true);
},
_setupDisabled: function(disabled) {
if ($.isArray(disabled)) {
if (!disabled.length) {
disabled = false;
} else if (disabled.length === this.anchors.length) {
disabled = true;
}
}
// disable tabs
for (var i = 0, li; (li = this.tabs[ i ]); i++) {
if (disabled === true || $.inArray(i, disabled) !== -1) {
$(li)
.addClass("ui-state-disabled")
.attr("aria-disabled", "true");
} else {
$(li)
.removeClass("ui-state-disabled")
.removeAttr("aria-disabled");
}
}
this.options.disabled = disabled;
},
_setupEvents: function(event) {
var events = {
click: function(event) {
event.preventDefault();
}
};
if (event) {
$.each(event.split(" "), function(index, eventName) {
events[ eventName ] = "_eventHandler";
});
}
this._off(this.anchors.add(this.tabs).add(this.panels));
this._on(this.anchors, events);
this._on(this.tabs, {keydown: "_tabKeydown"});
this._on(this.panels, {keydown: "_panelKeydown"});
this._focusable(this.tabs);
this._hoverable(this.tabs);
},
_setupHeightStyle: function(heightStyle) {
var maxHeight,
parent = this.element.parent();
if (heightStyle === "fill") {
maxHeight = parent.height();
maxHeight -= this.element.outerHeight() - this.element.height();
this.element.siblings(":visible").each(function() {
var elem = $(this),
position = elem.css("position");
if (position === "absolute" || position === "fixed") {
return;
}
maxHeight -= elem.outerHeight(true);
});
this.element.children().not(this.panels).each(function() {
maxHeight -= $(this).outerHeight(true);
});
this.panels.each(function() {
$(this).height(Math.max(0, maxHeight -
$(this).innerHeight() + $(this).height()));
})
.css("overflow", "auto");
} else if (heightStyle === "auto") {
maxHeight = 0;
this.panels.each(function() {
maxHeight = Math.max(maxHeight, $(this).height("").height());
}).height(maxHeight);
}
},
_eventHandler: function(event) {
var options = this.options,
active = this.active,
anchor = $(event.currentTarget),
tab = anchor.closest("li"),
clickedIsActive = tab[ 0 ] === active[ 0 ],
collapsing = clickedIsActive && options.collapsible,
toShow = collapsing ? $() : this._getPanelForTab(tab),
toHide = !active.length ? $() : this._getPanelForTab(active),
eventData = {
oldTab: active,
oldPanel: toHide,
newTab: collapsing ? $() : tab,
newPanel: toShow
};
event.preventDefault();
if (tab.hasClass("ui-state-disabled") ||
// tab is already loading
tab.hasClass("ui-tabs-loading") ||
// can't switch durning an animation
this.running ||
// click on active header, but not collapsible
(clickedIsActive && !options.collapsible) ||
// allow canceling activation
(this._trigger("beforeActivate", event, eventData) === false)) {
return;
}
options.active = collapsing ? false : this.tabs.index(tab);
this.active = clickedIsActive ? $() : tab;
if (this.xhr) {
this.xhr.abort();
}
if (!toHide.length && !toShow.length) {
$.error("jQuery UI Tabs: Mismatching fragment identifier.");
}
if (toShow.length) {
this.load(this.tabs.index(tab), event);
}
this._toggle(event, eventData);
},
// handles show/hide for selecting tabs
_toggle: function(event, eventData) {
var that = this,
toShow = eventData.newPanel,
toHide = eventData.oldPanel;
this.running = true;
function complete() {
that.running = false;
that._trigger("activate", event, eventData);
}
function show() {
eventData.newTab.closest("li").addClass("ui-tabs-active ui-state-active");
if (toShow.length && that.options.show) {
that._show(toShow, that.options.show, complete);
} else {
toShow.show();
complete();
}
}
// start out by hiding, then showing, then completing
if (toHide.length && this.options.hide) {
this._hide(toHide, this.options.hide, function() {
eventData.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active");
show();
});
} else {
eventData.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active");
toHide.hide();
show();
}
toHide.attr({
"aria-expanded": "false",
"aria-hidden": "true"
});
eventData.oldTab.attr("aria-selected", "false");
// If we're switching tabs, remove the old tab from the tab order.
// If we're opening from collapsed state, remove the previous tab from the tab order.
// If we're collapsing, then keep the collapsing tab in the tab order.
if (toShow.length && toHide.length) {
eventData.oldTab.attr("tabIndex", -1);
} else if (toShow.length) {
this.tabs.filter(function() {
return $(this).attr("tabIndex") === 0;
})
.attr("tabIndex", -1);
}
toShow.attr({
"aria-expanded": "true",
"aria-hidden": "false"
});
eventData.newTab.attr({
"aria-selected": "true",
tabIndex: 0
});
},
_activate: function(index) {
var anchor,
active = this._findActive(index);
// trying to activate the already active panel
if (active[ 0 ] === this.active[ 0 ]) {
return;
}
// trying to collapse, simulate a click on the current active header
if (!active.length) {
active = this.active;
}
anchor = active.find(".ui-tabs-anchor")[ 0 ];
this._eventHandler({
target: anchor,
currentTarget: anchor,
preventDefault: $.noop
});
},
_findActive: function(index) {
return index === false ? $() : this.tabs.eq(index);
},
_getIndex: function(index) {
// meta-function to give users option to provide a href string instead of a numerical index.
if (typeof index === "string") {
index = this.anchors.index(this.anchors.filter("[href$='" + index + "']"));
}
return index;
},
_destroy: function() {
if (this.xhr) {
this.xhr.abort();
}
this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible");
this.tablist
.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all")
.removeAttr("role");
this.anchors
.removeClass("ui-tabs-anchor")
.removeAttr("role")
.removeAttr("tabIndex")
.removeUniqueId();
this.tabs.add(this.panels).each(function() {
if ($.data(this, "ui-tabs-destroy")) {
$(this).remove();
} else {
$(this)
.removeClass("ui-state-default ui-state-active ui-state-disabled " +
"ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel")
.removeAttr("tabIndex")
.removeAttr("aria-live")
.removeAttr("aria-busy")
.removeAttr("aria-selected")
.removeAttr("aria-labelledby")
.removeAttr("aria-hidden")
.removeAttr("aria-expanded")
.removeAttr("role");
}
});
this.tabs.each(function() {
var li = $(this),
prev = li.data("ui-tabs-aria-controls");
if (prev) {
li
.attr("aria-controls", prev)
.removeData("ui-tabs-aria-controls");
} else {
li.removeAttr("aria-controls");
}
});
this.panels.show();
if (this.options.heightStyle !== "content") {
this.panels.css("height", "");
}
},
enable: function(index) {
var disabled = this.options.disabled;
if (disabled === false) {
return;
}
if (index === undefined) {
disabled = false;
} else {
index = this._getIndex(index);
if ($.isArray(disabled)) {
disabled = $.map(disabled, function(num) {
return num !== index ? num : null;
});
} else {
disabled = $.map(this.tabs, function(li, num) {
return num !== index ? num : null;
});
}
}
this._setupDisabled(disabled);
},
disable: function(index) {
var disabled = this.options.disabled;
if (disabled === true) {
return;
}
if (index === undefined) {
disabled = true;
} else {
index = this._getIndex(index);
if ($.inArray(index, disabled) !== -1) {
return;
}
if ($.isArray(disabled)) {
disabled = $.merge([index], disabled).sort();
} else {
disabled = [index];
}
}
this._setupDisabled(disabled);
},
load: function(index, event) {
index = this._getIndex(index);
var that = this,
tab = this.tabs.eq(index),
anchor = tab.find(".ui-tabs-anchor"),
panel = this._getPanelForTab(tab),
eventData = {
tab: tab,
panel: panel
};
// not remote
if (isLocal(anchor[ 0 ])) {
return;
}
this.xhr = $.ajax(this._ajaxSettings(anchor, event, eventData));
// support: jQuery <1.8
// jQuery <1.8 returns false if the request is canceled in beforeSend,
// but as of 1.8, $.ajax() always returns a jqXHR object.
if (this.xhr && this.xhr.statusText !== "canceled") {
tab.addClass("ui-tabs-loading");
panel.attr("aria-busy", "true");
this.xhr
.success(function(response) {
// support: jQuery <1.8
// http://bugs.jquery.com/ticket/11778
setTimeout(function() {
panel.html(response);
that._trigger("load", event, eventData);
}, 1);
})
.complete(function(jqXHR, status) {
// support: jQuery <1.8
// http://bugs.jquery.com/ticket/11778
setTimeout(function() {
if (status === "abort") {
that.panels.stop(false, true);
}
tab.removeClass("ui-tabs-loading");
panel.removeAttr("aria-busy");
if (jqXHR === that.xhr) {
delete that.xhr;
}
}, 1);
});
}
},
_ajaxSettings: function(anchor, event, eventData) {
var that = this;
return {
url: anchor.attr("href"),
beforeSend: function(jqXHR, settings) {
return that._trigger("beforeLoad", event,
$.extend({jqXHR: jqXHR, ajaxSettings: settings}, eventData));
}
};
},
_getPanelForTab: function(tab) {
var id = $(tab).attr("aria-controls");
return this.element.find(this._sanitizeSelector("#" + id));
}
});
})(jQuery);
(function($) {
var increments = 0;
function addDescribedBy(elem, id) {
var describedby = (elem.attr("aria-describedby") || "").split(/\s+/);
describedby.push(id);
elem
.data("ui-tooltip-id", id)
.attr("aria-describedby", $.trim(describedby.join(" ")));
}
function removeDescribedBy(elem) {
var id = elem.data("ui-tooltip-id"),
describedby = (elem.attr("aria-describedby") || "").split(/\s+/),
index = $.inArray(id, describedby);
if (index !== -1) {
describedby.splice(index, 1);
}
elem.removeData("ui-tooltip-id");
describedby = $.trim(describedby.join(" "));
if (describedby) {
elem.attr("aria-describedby", describedby);
} else {
elem.removeAttr("aria-describedby");
}
}
$.widget("ui.tooltip", {
version: "1.10.3",
options: {
content: function() {
// support: IE<9, Opera in jQuery <1.7
// .text() can't accept undefined, so coerce to a string
var title = $(this).attr("title") || "";
// Escape title, since we're going from an attribute to raw HTML
return $("<a>").text(title).html();
},
hide: true,
// Disabled elements have inconsistent behavior across browsers (#8661)
items: "[title]:not([disabled])",
position: {
my: "left top+15",
at: "left bottom",
collision: "flipfit flip"
},
show: true,
tooltipClass: null,
track: false,
// callbacks
close: null,
open: null
},
_create: function() {
this._on({
mouseover: "open",
focusin: "open"
});
// IDs of generated tooltips, needed for destroy
this.tooltips = {};
// IDs of parent tooltips where we removed the title attribute
this.parents = {};
if (this.options.disabled) {
this._disable();
}
},
_setOption: function(key, value) {
var that = this;
if (key === "disabled") {
this[ value ? "_disable" : "_enable" ]();
this.options[ key ] = value;
// disable element style changes
return;
}
this._super(key, value);
if (key === "content") {
$.each(this.tooltips, function(id, element) {
that._updateContent(element);
});
}
},
_disable: function() {
var that = this;
// close open tooltips
$.each(this.tooltips, function(id, element) {
var event = $.Event("blur");
event.target = event.currentTarget = element[0];
that.close(event, true);
});
// remove title attributes to prevent native tooltips
this.element.find(this.options.items).addBack().each(function() {
var element = $(this);
if (element.is("[title]")) {
element
.data("ui-tooltip-title", element.attr("title"))
.attr("title", "");
}
});
},
_enable: function() {
// restore title attributes
this.element.find(this.options.items).addBack().each(function() {
var element = $(this);
if (element.data("ui-tooltip-title")) {
element.attr("title", element.data("ui-tooltip-title"));
}
});
},
open: function(event) {
var that = this,
target = $(event ? event.target : this.element)
// we need closest here due to mouseover bubbling,
// but always pointing at the same event target
.closest(this.options.items);
// No element to show a tooltip for or the tooltip is already open
if (!target.length || target.data("ui-tooltip-id")) {
return;
}
if (target.attr("title")) {
target.data("ui-tooltip-title", target.attr("title"));
}
target.data("ui-tooltip-open", true);
// kill parent tooltips, custom or native, for hover
if (event && event.type === "mouseover") {
target.parents().each(function() {
var parent = $(this),
blurEvent;
if (parent.data("ui-tooltip-open")) {
blurEvent = $.Event("blur");
blurEvent.target = blurEvent.currentTarget = this;
that.close(blurEvent, true);
}
if (parent.attr("title")) {
parent.uniqueId();
that.parents[ this.id ] = {
element: this,
title: parent.attr("title")
};
parent.attr("title", "");
}
});
}
this._updateContent(target, event);
},
_updateContent: function(target, event) {
var content,
contentOption = this.options.content,
that = this,
eventType = event ? event.type : null;
if (typeof contentOption === "string") {
return this._open(event, target, contentOption);
}
content = contentOption.call(target[0], function(response) {
// ignore async response if tooltip was closed already
if (!target.data("ui-tooltip-open")) {
return;
}
// IE may instantly serve a cached response for ajax requests
// delay this call to _open so the other call to _open runs first
that._delay(function() {
// jQuery creates a special event for focusin when it doesn't
// exist natively. To improve performance, the native event
// object is reused and the type is changed. Therefore, we can't
// rely on the type being correct after the event finished
// bubbling, so we set it back to the previous value. (#8740)
if (event) {
event.type = eventType;
}
this._open(event, target, response);
});
});
if (content) {
this._open(event, target, content);
}
},
_open: function(event, target, content) {
var tooltip, events, delayedShow,
positionOption = $.extend({}, this.options.position);
if (!content) {
return;
}
// Content can be updated multiple times. If the tooltip already
// exists, then just update the content and bail.
tooltip = this._find(target);
if (tooltip.length) {
tooltip.find(".ui-tooltip-content").html(content);
return;
}
// if we have a title, clear it to prevent the native tooltip
// we have to check first to avoid defining a title if none exists
// (we don't want to cause an element to start matching [title])
//
// We use removeAttr only for key events, to allow IE to export the correct
// accessible attributes. For mouse events, set to empty string to avoid
// native tooltip showing up (happens only when removing inside mouseover).
if (target.is("[title]")) {
if (event && event.type === "mouseover") {
target.attr("title", "");
} else {
target.removeAttr("title");
}
}
tooltip = this._tooltip(target);
addDescribedBy(target, tooltip.attr("id"));
tooltip.find(".ui-tooltip-content").html(content);
function position(event) {
positionOption.of = event;
if (tooltip.is(":hidden")) {
return;
}
tooltip.position(positionOption);
}
if (this.options.track && event && /^mouse/.test(event.type)) {
this._on(this.document, {
mousemove: position
});
// trigger once to override element-relative positioning
position(event);
} else {
tooltip.position($.extend({
of: target
}, this.options.position));
}
tooltip.hide();
this._show(tooltip, this.options.show);
// Handle tracking tooltips that are shown with a delay (#8644). As soon
// as the tooltip is visible, position the tooltip using the most recent
// event.
if (this.options.show && this.options.show.delay) {
delayedShow = this.delayedShow = setInterval(function() {
if (tooltip.is(":visible")) {
position(positionOption.of);
clearInterval(delayedShow);
}
}, $.fx.interval);
}
this._trigger("open", event, {tooltip: tooltip});
events = {
keyup: function(event) {
if (event.keyCode === $.ui.keyCode.ESCAPE) {
var fakeEvent = $.Event(event);
fakeEvent.currentTarget = target[0];
this.close(fakeEvent, true);
}
},
remove: function() {
this._removeTooltip(tooltip);
}
};
if (!event || event.type === "mouseover") {
events.mouseleave = "close";
}
if (!event || event.type === "focusin") {
events.focusout = "close";
}
this._on(true, target, events);
},
close: function(event) {
var that = this,
target = $(event ? event.currentTarget : this.element),
tooltip = this._find(target);
// disabling closes the tooltip, so we need to track when we're closing
// to avoid an infinite loop in case the tooltip becomes disabled on close
if (this.closing) {
return;
}
// Clear the interval for delayed tracking tooltips
clearInterval(this.delayedShow);
// only set title if we had one before (see comment in _open())
if (target.data("ui-tooltip-title")) {
target.attr("title", target.data("ui-tooltip-title"));
}
removeDescribedBy(target);
tooltip.stop(true);
this._hide(tooltip, this.options.hide, function() {
that._removeTooltip($(this));
});
target.removeData("ui-tooltip-open");
this._off(target, "mouseleave focusout keyup");
// Remove 'remove' binding only on delegated targets
if (target[0] !== this.element[0]) {
this._off(target, "remove");
}
this._off(this.document, "mousemove");
if (event && event.type === "mouseleave") {
$.each(this.parents, function(id, parent) {
$(parent.element).attr("title", parent.title);
delete that.parents[ id ];
});
}
this.closing = true;
this._trigger("close", event, {tooltip: tooltip});
this.closing = false;
},
_tooltip: function(element) {
var id = "ui-tooltip-" + increments++,
tooltip = $("<div>")
.attr({
id: id,
role: "tooltip"
})
.addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content " +
(this.options.tooltipClass || ""));
$("<div>")
.addClass("ui-tooltip-content")
.appendTo(tooltip);
tooltip.appendTo(this.document[0].body);
this.tooltips[ id ] = element;
return tooltip;
},
_find: function(target) {
var id = target.data("ui-tooltip-id");
return id ? $("#" + id) : $();
},
_removeTooltip: function(tooltip) {
tooltip.remove();
delete this.tooltips[ tooltip.attr("id") ];
},
_destroy: function() {
var that = this;
// close open tooltips
$.each(this.tooltips, function(id, element) {
// Delegate to close method to handle common cleanup
var event = $.Event("blur");
event.target = event.currentTarget = element[0];
that.close(event, true);
// Remove immediately; destroying an open tooltip doesn't use the
// hide animation
$("#" + id).remove();
// Restore the title
if (element.data("ui-tooltip-title")) {
element.attr("title", element.data("ui-tooltip-title"));
element.removeData("ui-tooltip-title");
}
});
}
});
}(jQuery));<|fim▁end|>
|
originalPosition: ui.originalPosition,
|
<|file_name|>comparator.rs<|end_file_name|><|fim▁begin|>// rust way of ord
use std::cmp::Ordering;
pub trait Comparator<T> {
fn compare(&self, v: &T, w: &T) -> Ordering;
fn less(&self, v: &T, w: &T) -> bool {
self.compare(v, w) == Ordering::Less
}<|fim▁hole|> (*self)(v, w)
}
}
pub fn insertion_sort<T: PartialOrd, C: Comparator<T>>(a: &mut [T], comparator: C) {
let n = a.len();
for i in 0 .. n {
for j in (1 .. i + 1).rev() {
if comparator.less(&a[j], &a[j-1]) {
a.swap(j, j-1);
}
}
}
}
#[test]
fn test_insertion_sort_using_a_comparator() {
use rand::{thread_rng, Rng};
fn is_reverse_sorted<T: PartialOrd>(a: &[T]) -> bool {
for i in 1 .. a.len() {
if a[i] > a[i-1] {
return false;
}
}
true
}
let mut array = thread_rng().gen_iter().take(10).collect::<Vec<u32>>();
// FIXME: due to https://github.com/rust-lang/rust/issues/24680
// the Comparator closure's type can't be inferred!
insertion_sort(&mut array, |v: &u32, w: &u32| w.cmp(v) );
assert!(is_reverse_sorted(&array));
}<|fim▁end|>
|
}
impl<T, F> Comparator<T> for F where F: Send + Sync + Fn(&T, &T) -> Ordering {
fn compare(&self, v: &T, w: &T) -> Ordering {
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>from django.test import TestCase
from django import forms
from django.forms.models import ModelForm
import unittest
from employee.forms import *
from django.test import Client
class TestBasic(unittest.TestCase):
"Basic tests"
def test_basic(self):
a = 1
self.assertEqual(1, a)
class Modelforms_test(TestCase):
def test_report(self):
form = DailyReportForm(data = {'employee': '[email protected]', 'project': 'ravi', 'report':'Sample report'})
self.assertTrue(form.is_valid())
class Views_test(TestCase):
<|fim▁hole|>
resp = c.get('/portal/staff/reports/new/')
self.assertEqual(resp.status_code, 302)
resp = c.get('/portal/staff/reports/edit/1/')
self.assertEqual(resp.status_code, 302)
resp = c.get('/portal/staff/reports/delete/1/')
self.assertEqual(resp.status_code, 302)<|fim▁end|>
|
def test_employee_report(self):
c = Client()
resp = c.get('/portal/staff/')
self.assertEqual(resp.status_code, 302)
|
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import errno, socket, select, os
from Cookie import SimpleCookie
from contextlib import closing
from urlparse import parse_qs
import repr as reprlib
from email.utils import formatdate
from operator import itemgetter
from future_builtins import map
from urllib import quote as urlquote
from binascii import hexlify, unhexlify
from calibre import prints
from calibre.constants import iswindows
from calibre.utils.config_base import tweaks
from calibre.utils.localization import get_translator
from calibre.utils.socket_inheritance import set_socket_inherit
from calibre.utils.logging import ThreadSafeLog
from calibre.utils.shared_file import share_open, raise_winerror
HTTP1 = 'HTTP/1.0'
HTTP11 = 'HTTP/1.1'
DESIRED_SEND_BUFFER_SIZE = 16 * 1024 # windows 7 uses an 8KB sndbuf
def http_date(timeval=None):
return type('')(formatdate(timeval=timeval, usegmt=True))
class MultiDict(dict): # {{{
def __setitem__(self, key, val):
vals = dict.get(self, key, [])
vals.append(val)
dict.__setitem__(self, key, vals)
def __getitem__(self, key):
return dict.__getitem__(self, key)[-1]
@staticmethod
def create_from_query_string(qs):
ans = MultiDict()
for k, v in parse_qs(qs, keep_blank_values=True).iteritems():
dict.__setitem__(ans, k.decode('utf-8'), [x.decode('utf-8') for x in v])
return ans
def update_from_listdict(self, ld):
for key, values in ld.iteritems():
for val in values:
self[key] = val
def items(self, duplicates=True):
for k, v in dict.iteritems(self):
if duplicates:
for x in v:
yield k, x
else:
yield k, v[-1]
iteritems = items
def values(self, duplicates=True):
for v in dict.itervalues(self):
if duplicates:
for x in v:
yield x
else:
yield v[-1]
itervalues = values
def set(self, key, val, replace_all=False):
if replace_all:
dict.__setitem__(self, key, [val])
else:
self[key] = val
def get(self, key, default=None, all=False):
if all:
try:
return dict.__getitem__(self, key)
except KeyError:
return []
try:
return self.__getitem__(key)
except KeyError:
return default
def pop(self, key, default=None, all=False):
ans = dict.pop(self, key, default)
if ans is default:
return [] if all else default
return ans if all else ans[-1]
def __repr__(self):
return '{' + ', '.join('%s: %s' % (reprlib.repr(k), reprlib.repr(v)) for k, v in self.iteritems()) + '}'
__str__ = __unicode__ = __repr__
def pretty(self, leading_whitespace=''):
return leading_whitespace + ('\n' + leading_whitespace).join(
'%s: %s' % (k, (repr(v) if isinstance(v, bytes) else v)) for k, v in sorted(self.items(), key=itemgetter(0)))
# }}}
def error_codes(*errnames):
''' Return error numbers for error names, ignoring non-existent names '''
ans = {getattr(errno, x, None) for x in errnames}
ans.discard(None)
return ans
socket_errors_eintr = error_codes("EINTR", "WSAEINTR")
socket_errors_socket_closed = error_codes( # errors indicating a disconnected connection
"EPIPE",
"EBADF", "WSAEBADF",
"ENOTSOCK", "WSAENOTSOCK",
"ENOTCONN", "WSAENOTCONN",
"ESHUTDOWN", "WSAESHUTDOWN",
"ETIMEDOUT", "WSAETIMEDOUT",
"ECONNREFUSED", "WSAECONNREFUSED",
"ECONNRESET", "WSAECONNRESET",
"ECONNABORTED", "WSAECONNABORTED",
"ENETRESET", "WSAENETRESET",
"EHOSTDOWN", "EHOSTUNREACH",
)
socket_errors_nonblocking = error_codes(
'EAGAIN', 'EWOULDBLOCK', 'WSAEWOULDBLOCK')
def start_cork(sock):
if hasattr(socket, 'TCP_CORK'):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 1)
def stop_cork(sock):
if hasattr(socket, 'TCP_CORK'):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 0)
def create_sock_pair(port=0):
'''Create socket pair. Works also on windows by using an ephemeral TCP port.'''
if hasattr(socket, 'socketpair'):
client_sock, srv_sock = socket.socketpair()
set_socket_inherit(client_sock, False), set_socket_inherit(srv_sock, False)
return client_sock, srv_sock
# Create a non-blocking temporary server socket
temp_srv_sock = socket.socket()
set_socket_inherit(temp_srv_sock, False)
temp_srv_sock.setblocking(False)
temp_srv_sock.bind(('127.0.0.1', port))
port = temp_srv_sock.getsockname()[1]
temp_srv_sock.listen(1)
with closing(temp_srv_sock):
# Create non-blocking client socket
client_sock = socket.socket()
client_sock.setblocking(False)
set_socket_inherit(client_sock, False)
try:
client_sock.connect(('127.0.0.1', port))
except socket.error as err:
# EWOULDBLOCK is not an error, as the socket is non-blocking
if err.errno not in socket_errors_nonblocking:
raise
# Use select to wait for connect() to succeed.
timeout = 1
readable = select.select([temp_srv_sock], [], [], timeout)[0]
if temp_srv_sock not in readable:
raise Exception('Client socket not connected in {} second(s)'.format(timeout))
srv_sock = temp_srv_sock.accept()[0]
set_socket_inherit(srv_sock, False)
client_sock.setblocking(True)
return client_sock, srv_sock
def parse_http_list(header_val):
"""Parse lists as described by RFC 2068 Section 2.
In particular, parse comma-separated lists where the elements of
the list may include quoted-strings. A quoted-string could
contain a comma. A non-quoted string could have quotes in the
middle. Neither commas nor quotes count if they are escaped.
Only double-quotes count, not single-quotes.
"""
if isinstance(header_val, bytes):
slash, dquote, comma = b'\\",'
empty = b''
else:
slash, dquote, comma = '\\",'
empty = ''
part = empty
escape = quote = False
for cur in header_val:
if escape:<|fim▁hole|> if cur == slash:
escape = True
continue
elif cur == dquote:
quote = False
part += cur
continue
if cur == comma:
yield part.strip()
part = empty
continue
if cur == dquote:
quote = True
part += cur
if part:
yield part.strip()
def parse_http_dict(header_val):
'Parse an HTTP comma separated header with items of the form a=1, b="xxx" into a dictionary'
if not header_val:
return {}
ans = {}
sep, dquote = b'="' if isinstance(header_val, bytes) else '="'
for item in parse_http_list(header_val):
k, v = item.partition(sep)[::2]
if k:
if v.startswith(dquote) and v.endswith(dquote):
v = v[1:-1]
ans[k] = v
return ans
def sort_q_values(header_val):
'Get sorted items from an HTTP header of type: a;q=0.5, b;q=0.7...'
if not header_val:
return []
def item(x):
e, r = x.partition(';')[::2]
p, v = r.partition('=')[::2]
q = 1.0
if p == 'q' and v:
try:
q = max(0.0, min(1.0, float(v.strip())))
except Exception:
pass
return e.strip(), q
return tuple(map(itemgetter(0), sorted(map(item, parse_http_list(header_val)), key=itemgetter(1), reverse=True)))
def eintr_retry_call(func, *args, **kwargs):
while True:
try:
return func(*args, **kwargs)
except EnvironmentError as e:
if getattr(e, 'errno', None) in socket_errors_eintr:
continue
raise
def get_translator_for_lang(cache, bcp_47_code):
try:
return cache[bcp_47_code]
except KeyError:
pass
cache[bcp_47_code] = ans = get_translator(bcp_47_code)
return ans
def encode_path(*components):
'Encode the path specified as a list of path components using URL encoding'
return '/' + '/'.join(urlquote(x.encode('utf-8'), '').decode('ascii') for x in components)
def encode_name(name):
'Encode a name (arbitrary string) as URL safe characters. See decode_name() also.'
if isinstance(name, unicode):
name = name.encode('utf-8')
return hexlify(name)
def decode_name(name):
return unhexlify(name).decode('utf-8')
class Cookie(SimpleCookie):
def _BaseCookie__set(self, key, real_value, coded_value):
if not isinstance(key, bytes):
key = key.encode('ascii') # Python 2.x cannot handle unicode keys
return SimpleCookie._BaseCookie__set(self, key, real_value, coded_value)
def custom_fields_to_display(db):
ckeys = set(db.field_metadata.ignorable_field_keys())
yes_fields = set(tweaks['content_server_will_display'])
no_fields = set(tweaks['content_server_wont_display'])
if '*' in yes_fields:
yes_fields = ckeys
if '*' in no_fields:
no_fields = ckeys
return frozenset(ckeys & (yes_fields - no_fields))
# Logging {{{
class ServerLog(ThreadSafeLog):
exception_traceback_level = ThreadSafeLog.WARN
class RotatingStream(object):
def __init__(self, filename, max_size=None, history=5):
self.filename, self.history, self.max_size = filename, history, max_size
if iswindows:
self.filename = '\\\\?\\' + os.path.abspath(self.filename)
self.set_output()
def set_output(self):
self.stream = share_open(self.filename, 'ab', -1 if iswindows else 1) # line buffered
try:
self.current_pos = self.stream.tell()
except EnvironmentError:
# Happens if filename is /dev/stdout for example
self.current_pos = 0
self.max_size = None
def flush(self):
self.stream.flush()
def prints(self, level, *args, **kwargs):
kwargs['safe_encode'] = True
kwargs['file'] = self.stream
self.current_pos += prints(*args, **kwargs)
if iswindows:
# For some reason line buffering does not work on windows
end = kwargs.get('end', b'\n')
if b'\n' in end:
self.flush()
self.rollover()
def rename(self, src, dest):
try:
if iswindows:
import win32file, pywintypes
try:
win32file.MoveFileEx(src, dest, win32file.MOVEFILE_REPLACE_EXISTING|win32file.MOVEFILE_WRITE_THROUGH)
except pywintypes.error as e:
raise_winerror(e)
else:
os.rename(src, dest)
except EnvironmentError as e:
if e.errno != errno.ENOENT: # the source of the rename does not exist
raise
def rollover(self):
if self.max_size is None or self.current_pos <= self.max_size:
return
self.stream.close()
for i in xrange(self.history - 1, 0, -1):
src, dest = '%s.%d' % (self.filename, i), '%s.%d' % (self.filename, i+1)
self.rename(src, dest)
self.rename(self.filename, '%s.%d' % (self.filename, 1))
self.set_output()
class RotatingLog(ServerLog):
def __init__(self, filename, max_size=None, history=5):
ServerLog.__init__(self)
self.outputs = [RotatingStream(filename, max_size, history)]
def flush(self):
for o in self.outputs:
o.flush()
# }}}
class HandleInterrupt(object): # {{{
# On windows socket functions like accept(), recv(), send() are not
# interrupted by a Ctrl-C in the console. So to make Ctrl-C work we have to
# use this special context manager. See the echo server example at the
# bottom of this file for how to use it.
def __init__(self, action):
if not iswindows:
return # Interrupts work fine on POSIX
self.action = action
from ctypes import WINFUNCTYPE, windll
from ctypes.wintypes import BOOL, DWORD
kernel32 = windll.LoadLibrary('kernel32')
# <http://msdn.microsoft.com/en-us/library/ms686016.aspx>
PHANDLER_ROUTINE = WINFUNCTYPE(BOOL, DWORD)
self.SetConsoleCtrlHandler = kernel32.SetConsoleCtrlHandler
self.SetConsoleCtrlHandler.argtypes = (PHANDLER_ROUTINE, BOOL)
self.SetConsoleCtrlHandler.restype = BOOL
@PHANDLER_ROUTINE
def handle(event):
if event == 0: # CTRL_C_EVENT
if self.action is not None:
self.action()
self.action = None
# Typical C implementations would return 1 to indicate that
# the event was processed and other control handlers in the
# stack should not be executed. However, that would
# prevent the Python interpreter's handler from translating
# CTRL-C to a `KeyboardInterrupt` exception, so we pretend
# that we didn't handle it.
return 0
self.handle = handle
def __enter__(self):
if iswindows:
if self.SetConsoleCtrlHandler(self.handle, 1) == 0:
raise WindowsError()
def __exit__(self, *args):
if iswindows:
if self.SetConsoleCtrlHandler(self.handle, 0) == 0:
raise WindowsError()
# }}}
class Accumulator(object): # {{{
'Optimized replacement for BytesIO when the usage pattern is many writes followed by a single getvalue()'
def __init__(self):
self._buf = []
self.total_length = 0
def append(self, b):
self._buf.append(b)
self.total_length += len(b)
def getvalue(self):
ans = b''.join(self._buf)
self._buf = []
self.total_length = 0
return ans
# }}}
class ReadOnlyFileBuffer(object):
''' A zero copy implementation of a file like object. Uses memoryviews for efficiency. '''
def __init__(self, raw):
self.sz, self.mv = len(raw), (raw if isinstance(raw, memoryview) else memoryview(raw))
self.pos = 0
def tell(self):
return self.pos
def read(self, n=None):
if n is None:
ans = self.mv[self.pos:]
self.pos = self.sz
return ans
ans = self.mv[self.pos:self.pos+n]
self.pos = min(self.pos + n, self.sz)
return ans
def seek(self, pos, whence=os.SEEK_SET):
if whence == os.SEEK_SET:
self.pos = pos
elif whence == os.SEEK_END:
self.pos = self.sz + pos
else:
self.pos += pos
self.pos = max(0, min(self.pos, self.sz))
return self.pos
def getvalue(self):
return self.mv
def close(self):
pass<|fim▁end|>
|
part += cur
escape = False
continue
if quote:
|
<|file_name|>shell_options.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# encoding: UTF-8
"""
This file is part of Commix Project (http://commixproject.com).
Copyright (c) 2014-2017 Anastasios Stasinopoulos (@ancst).
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
For more see the file 'readme/COPYING' for copying permission.
"""
import re
import os
import sys
import time
import urllib
import urlparse
from src.utils import menu
from src.utils import settings
from src.core.injections.controller import checks
from src.thirdparty.colorama import Fore, Back, Style, init
from src.core.shells import bind_tcp
from src.core.shells import reverse_tcp
from src.core.injections.results_based.techniques.classic import cb_injector
from src.core.injections.results_based.techniques.eval_based import eb_injector
from src.core.injections.semiblind.techniques.file_based import fb_injector
"""
Check for established connection
"""
def check_established_connection():
while True:
if settings.VERBOSITY_LEVEL == 1:
print ""
warn_msg = "Something went wrong with the reverse TCP connection."
warn_msg += " Please wait while checking state."
print settings.print_warning_msg(warn_msg)
time.sleep(10)
lines = os.popen('netstat -anta').read().split("\n")
found = False
for line in lines:
if "ESTABLISHED" in line and settings.LPORT in line.split():
found = True
pass
if not found:
return
"""
Execute the bind / reverse TCP shell
"""
def execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, payload, OUTPUT_TEXTFILE):
if settings.EVAL_BASED_STATE != False:
# Command execution results.
start = time.time()
response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename)
end = time.time()
diff = end - start
# Evaluate injection results.
shell = eb_injector.injection_results(response, TAG, cmd)
else:
# Command execution results.
start = time.time()
if settings.FILE_BASED_STATE == True:
response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
else:
whitespace = settings.WHITESPACE[0]
if whitespace == " ":
whitespace = urllib.quote(whitespace)
response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename)
end = time.time()
diff = end - start
# Evaluate injection results.
shell = cb_injector.injection_results(response, TAG, cmd)
if settings.REVERSE_TCP and (int(diff) > 0 and int(diff) < 6):
check_established_connection()
else:
if settings.VERBOSITY_LEVEL == 1:
print ""
err_msg = "The " + os_shell_option.split("_")[0] + " "
err_msg += os_shell_option.split("_")[1].upper() + " connection has failed!"
print settings.print_critical_msg(err_msg)
"""
Configure the bind TCP shell
"""
def bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE):
settings.BIND_TCP = True
# Set up RHOST / LPORT for the bind TCP connection.
bind_tcp.configure_bind_tcp()
if settings.BIND_TCP == False:
if settings.REVERSE_TCP == True:
os_shell_option = "reverse_tcp"<|fim▁hole|>
while True:
if settings.RHOST and settings.LPORT in settings.SHELL_OPTIONS:
result = checks.check_bind_tcp_options(settings.RHOST)
else:
cmd = bind_tcp.bind_tcp_options()
result = checks.check_bind_tcp_options(cmd)
if result != None:
if result == 0:
go_back_again = False
elif result == 1 or result == 2:
go_back_again = True
settings.BIND_TCP = False
elif result == 3:
settings.BIND_TCP = False
reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE)
return go_back, go_back_again
# execute bind TCP shell
execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, payload, OUTPUT_TEXTFILE)
"""
Configure the reverse TCP shell
"""
def reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE):
settings.REVERSE_TCP = True
# Set up LHOST / LPORT for the reverse TCP connection.
reverse_tcp.configure_reverse_tcp()
if settings.REVERSE_TCP == False:
if settings.BIND_TCP == True:
os_shell_option = "bind_tcp"
bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE)
return go_back, go_back_again
while True:
if settings.LHOST and settings.LPORT in settings.SHELL_OPTIONS:
result = checks.check_reverse_tcp_options(settings.LHOST)
else:
cmd = reverse_tcp.reverse_tcp_options()
result = checks.check_reverse_tcp_options(cmd)
if result != None:
if result == 0:
go_back_again = False
elif result == 1 or result == 2:
go_back_again = True
settings.REVERSE_TCP = False
elif result == 3:
settings.REVERSE_TCP = False
bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE)
#reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again)
return go_back, go_back_again
# execute reverse TCP shell
execute_shell(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, payload, OUTPUT_TEXTFILE)
"""
Check commix shell options
"""
def check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE):
os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result)
if os_shell_option == "back" or os_shell_option == True or os_shell_option == False:
go_back = True
if os_shell_option == False:
go_back_again = True
return go_back, go_back_again
# The "os_shell" option
elif os_shell_option == "os_shell":
warn_msg = "You are already into the '" + os_shell_option + "' mode."
print settings.print_warning_msg(warn_msg)
return go_back, go_back_again
# The "bind_tcp" option
elif os_shell_option == "bind_tcp":
go_back, go_back_again = bind_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE)
return go_back, go_back_again
# The "reverse_tcp" option
elif os_shell_option == "reverse_tcp":
go_back, go_back_again = reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE)
return go_back, go_back_again
# The "quit" option
elif os_shell_option == "quit":
sys.exit(0)
else:
return go_back, go_back_again<|fim▁end|>
|
reverse_tcp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE)
return go_back, go_back_again
|
<|file_name|>stat.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::io::fs::PathExtensions;
use std::io::{File, TempDir};
pub fn main() {
let dir = TempDir::new_in(&Path::new("."), "").unwrap();<|fim▁hole|>
{
match File::create(&path) {
Err(..) => unreachable!(),
Ok(f) => {
let mut f = f;
for _ in range(0u, 1000) {
f.write(&[0]);
}
}
}
}
assert!(path.exists());
assert_eq!(path.stat().unwrap().size, 1000);
}<|fim▁end|>
|
let path = dir.path().join("file");
|
<|file_name|>test_air_quality.py<|end_file_name|><|fim▁begin|>"""Test the Dyson air quality component."""
import json
from unittest import mock
import asynctest
from libpurecool.dyson_pure_cool import DysonPureCool
from libpurecool.dyson_pure_state_v2 import DysonEnvironmentalSensorV2State
import homeassistant.components.dyson.air_quality as dyson
from homeassistant.components import dyson as dyson_parent
from homeassistant.components.air_quality import DOMAIN as AIQ_DOMAIN, \
ATTR_PM_2_5, ATTR_PM_10, ATTR_NO2
from homeassistant.helpers import discovery
from homeassistant.setup import async_setup_component
def _get_dyson_purecool_device():
"""Return a valid device as provided by the Dyson web services."""
device = mock.Mock(spec=DysonPureCool)
device.serial = 'XX-XXXXX-XX'
device.name = 'Living room'
device.connect = mock.Mock(return_value=True)
device.auto_connect = mock.Mock(return_value=True)
device.environmental_state.particulate_matter_25 = '0014'
device.environmental_state.particulate_matter_10 = '0025'
device.environmental_state.nitrogen_dioxide = '0042'
device.environmental_state.volatile_organic_compounds = '0035'
return device
def _get_config():
"""Return a config dictionary."""<|fim▁hole|> dyson_parent.CONF_USERNAME: 'email',
dyson_parent.CONF_PASSWORD: 'password',
dyson_parent.CONF_LANGUAGE: 'GB',
dyson_parent.CONF_DEVICES: [
{
'device_id': 'XX-XXXXX-XX',
'device_ip': '192.168.0.1'
}
]
}}
@asynctest.patch('libpurecool.dyson.DysonAccount.login', return_value=True)
@asynctest.patch('libpurecool.dyson.DysonAccount.devices',
return_value=[_get_dyson_purecool_device()])
async def test_purecool_aiq_attributes(devices, login, hass):
"""Test state attributes."""
await async_setup_component(hass, dyson_parent.DOMAIN, _get_config())
await hass.async_block_till_done()
fan_state = hass.states.get("air_quality.living_room")
attributes = fan_state.attributes
assert fan_state.state == '14'
assert attributes[ATTR_PM_2_5] == 14
assert attributes[ATTR_PM_10] == 25
assert attributes[ATTR_NO2] == 42
assert attributes[dyson.ATTR_VOC] == 35
@asynctest.patch('libpurecool.dyson.DysonAccount.login', return_value=True)
@asynctest.patch('libpurecool.dyson.DysonAccount.devices',
return_value=[_get_dyson_purecool_device()])
async def test_purecool_aiq_update_state(devices, login, hass):
"""Test state update."""
device = devices.return_value[0]
await async_setup_component(hass, dyson_parent.DOMAIN, _get_config())
await hass.async_block_till_done()
event = {
"msg": "ENVIRONMENTAL-CURRENT-SENSOR-DATA",
"time": "2019-03-29T10:00:01.000Z",
"data": {
"pm10": "0080",
"p10r": "0151",
"hact": "0040",
"va10": "0055",
"p25r": "0161",
"noxl": "0069",
"pm25": "0035",
"sltm": "OFF",
"tact": "2960"
}
}
device.environmental_state = \
DysonEnvironmentalSensorV2State(json.dumps(event))
for call in device.add_message_listener.call_args_list:
callback = call[0][0]
if type(callback.__self__) == dyson.DysonAirSensor:
callback(device.environmental_state)
await hass.async_block_till_done()
fan_state = hass.states.get("air_quality.living_room")
attributes = fan_state.attributes
assert fan_state.state == '35'
assert attributes[ATTR_PM_2_5] == 35
assert attributes[ATTR_PM_10] == 80
assert attributes[ATTR_NO2] == 69
assert attributes[dyson.ATTR_VOC] == 55
@asynctest.patch('libpurecool.dyson.DysonAccount.login', return_value=True)
@asynctest.patch('libpurecool.dyson.DysonAccount.devices',
return_value=[_get_dyson_purecool_device()])
async def test_purecool_component_setup_only_once(devices, login, hass):
"""Test if entities are created only once."""
config = _get_config()
await async_setup_component(hass, dyson_parent.DOMAIN, config)
await hass.async_block_till_done()
discovery.load_platform(hass, AIQ_DOMAIN,
dyson_parent.DOMAIN, {}, config)
await hass.async_block_till_done()
assert len(hass.data[dyson.DYSON_AIQ_DEVICES]) == 1
@asynctest.patch('libpurecool.dyson.DysonAccount.login', return_value=True)
@asynctest.patch('libpurecool.dyson.DysonAccount.devices',
return_value=[_get_dyson_purecool_device()])
async def test_purecool_aiq_without_discovery(devices, login, hass):
"""Test if component correctly returns if discovery not set."""
await async_setup_component(hass, dyson_parent.DOMAIN, _get_config())
await hass.async_block_till_done()
add_entities_mock = mock.MagicMock()
dyson.setup_platform(hass, None, add_entities_mock, None)
assert add_entities_mock.call_count == 0
@asynctest.patch('libpurecool.dyson.DysonAccount.login', return_value=True)
@asynctest.patch('libpurecool.dyson.DysonAccount.devices',
return_value=[_get_dyson_purecool_device()])
async def test_purecool_aiq_empty_environment_state(devices, login, hass):
"""Test device with empty environmental state."""
await async_setup_component(hass, dyson_parent.DOMAIN, _get_config())
await hass.async_block_till_done()
device = hass.data[dyson.DYSON_AIQ_DEVICES][0]
device._device.environmental_state = None
assert device.state is None
assert device.particulate_matter_2_5 is None
assert device.particulate_matter_10 is None
assert device.nitrogen_dioxide is None
assert device.volatile_organic_compounds is None<|fim▁end|>
|
return {dyson_parent.DOMAIN: {
|
<|file_name|>marisa-build.rs<|end_file_name|><|fim▁begin|>// Copyright (c) 2010-2013, Susumu Yata
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#include <stdio.h>
#endif // _WIN32
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <marisa.h>
#include "cmdopt.h"
namespace {
int param_num_tries = MARISA_DEFAULT_NUM_TRIES;
marisa::TailMode param_tail_mode = MARISA_DEFAULT_TAIL;
marisa::NodeOrder param_node_order = MARISA_DEFAULT_ORDER;
marisa::CacheLevel param_cache_level = MARISA_DEFAULT_CACHE;
const char *output_filename = NULL;
void print_help(const char *cmd) {
std::cerr << "Usage: " << cmd << " [OPTION]... [FILE]...\n\n"
"Options:\n"
" -n, --num-tries=[N] limit the number of tries"
" [" << MARISA_MIN_NUM_TRIES << ", " << MARISA_MAX_NUM_TRIES
<< "] (default: 3)\n"
" -t, --text-tail build a dictionary with text TAIL (default)\n"
" -b, --binary-tail build a dictionary with binary TAIL\n"
" -w, --weight-order arrange siblings in weight order (default)\n"
" -l, --label-order arrange siblings in label order\n"
" -c, --cache-level=[N] specify the cache size"
" [1, 5] (default: 3)\n"
" -o, --output=[FILE] write tries to FILE (default: stdout)\n"
" -h, --help print this help\n"
<< std::endl;
}
void read_keys(std::istream &input, marisa::Keyset *keyset) {
std::string line;
while (std::getline(input, line)) {
const std::string::size_type delim_pos = line.find_last_of('\t');
float weight = 1.0F;
if (delim_pos != line.npos) {
char *end_of_value;
weight = (float)std::strtod(&line[delim_pos + 1], &end_of_value);
if (*end_of_value == '\0') {
line.resize(delim_pos);
}
}
keyset->push_back(line.c_str(), line.length(), weight);
}
}
int build(const char * const *args, std::size_t num_args) {
marisa::Keyset keyset;
if (num_args == 0) try {
read_keys(std::cin, &keyset);
} catch (const marisa::Exception &ex) {
std::cerr << ex.what() << ": failed to read keys" << std::endl;
return 10;
}
for (std::size_t i = 0; i < num_args; ++i) try {
std::ifstream input_file(args[i], std::ios::binary);
if (!input_file) {
std::cerr << "error: failed to open: " << args[i] << std::endl;
return 11;
}
read_keys(input_file, &keyset);
} catch (const marisa::Exception &ex) {
std::cerr << ex.what() << ": failed to read keys" << std::endl;
return 12;
}
marisa::Trie trie;
try {
trie.build(keyset, param_num_tries | param_tail_mode | param_node_order |
param_cache_level);
} catch (const marisa::Exception &ex) {
std::cerr << ex.what() << ": failed to build a dictionary" << std::endl;
return 20;
}
std::cerr << "#keys: " << trie.num_keys() << std::endl;
std::cerr << "#nodes: " << trie.num_nodes() << std::endl;
std::cerr << "size: " << trie.io_size() << std::endl;
if (output_filename != NULL) {
try {
trie.save(output_filename);
} catch (const marisa::Exception &ex) {
std::cerr << ex.what() << ": failed to write a dictionary to file: "
<< output_filename << std::endl;
return 30;
}
} else {
#ifdef _WIN32
const int stdout_fileno = ::_fileno(stdout);
if (stdout_fileno < 0) {
std::cerr << "error: failed to get the file descriptor of "
"standard output" << std::endl;
return 31;
}
if (::_setmode(stdout_fileno, _O_BINARY) == -1) {
std::cerr << "error: failed to set binary mode" << std::endl;
return 32;
}
#endif // _WIN32
try {
std::cout << trie;
} catch (const marisa::Exception &ex) {
std::cerr << ex.what()
<< ": failed to write a dictionary to standard output" << std::endl;
return 33;
}
}
return 0;
}
} // namespace
int main(int argc, char *argv[]) {
std::ios::sync_with_stdio(false);
::cmdopt_option long_options[] = {
{ "max-num-tries", 1, NULL, 'n' },
{ "text-tail", 0, NULL, 't' },
{ "binary-tail", 0, NULL, 'b' },
{ "weight-order", 0, NULL, 'w' },
{ "label-order", 0, NULL, 'l' },
{ "cache-level", 1, NULL, 'c' },
{ "output", 1, NULL, 'o' },
{ "help", 0, NULL, 'h' },
{ NULL, 0, NULL, 0 }
};
::cmdopt_t cmdopt;
::cmdopt_init(&cmdopt, argc, argv, "n:tbwlc:o:h", long_options);
int label;
while ((label = ::cmdopt_get(&cmdopt)) != -1) {
switch (label) {
case 'n': {
char *end_of_value;
const long value = std::strtol(cmdopt.optarg, &end_of_value, 10);
if ((*end_of_value != '\0') || (value <= 0) ||
(value > MARISA_MAX_NUM_TRIES)) {
std::cerr << "error: option `-n' with an invalid argument: "
<< cmdopt.optarg << std::endl;
return 1;
}
param_num_tries = (int)value;
break;
}
case 't': {
param_tail_mode = MARISA_TEXT_TAIL;
break;
}
case 'b': {
param_tail_mode = MARISA_BINARY_TAIL;
break;
}
case 'w': {
param_node_order = MARISA_WEIGHT_ORDER;
break;
}
case 'l': {
param_node_order = MARISA_LABEL_ORDER;
break;
}
case 'c': {
char *end_of_value;
const long value = std::strtol(cmdopt.optarg, &end_of_value, 10);
if ((*end_of_value != '\0') || (value < 1) || (value > 5)) {
std::cerr << "error: option `-c' with an invalid argument: "
<< cmdopt.optarg << std::endl;
return 2;
} else if (value == 1) {
param_cache_level = MARISA_TINY_CACHE;
} else if (value == 2) {
param_cache_level = MARISA_SMALL_CACHE;
} else if (value == 3) {
param_cache_level = MARISA_NORMAL_CACHE;
} else if (value == 4) {
param_cache_level = MARISA_LARGE_CACHE;
} else if (value == 5) {
param_cache_level = MARISA_HUGE_CACHE;
}
break;
}
case 'o': {
output_filename = cmdopt.optarg;
break;
}
case 'h': {
print_help(argv[0]);
return 0;
}
default: {
return 1;
}
}<|fim▁hole|><|fim▁end|>
|
}
return build(cmdopt.argv + cmdopt.optind, cmdopt.argc - cmdopt.optind);
}
|
<|file_name|>feeds.py<|end_file_name|><|fim▁begin|>"""(Re)builds feeds for categories"""
import os
import datetime
import jinja2
from google.appengine.api import app_identity
import dao
import util
def build_and_save_for_category(cat, store, prefix):
"""Build and save feeds for category"""
feed = build_feed(cat)
save_feeds(store, feed, prefix, cat.key.id())
def build_feed(cat):
"""Build feed for category"""
feed = Feed(title=cat.title, link=get_app_url())
items = dao.latest_torrents(feed_size(cat), cat.key)
for item in items:
feed.add_item(item)
return feed
def get_app_url():
"""Returns full URL for app engine app"""
app_id = app_identity.get_application_id()
return 'http://{}.appspot.com/'.format(app_id)
def save_feeds(store, feed, prefix, name):
"""Saves feeds to storage"""
xml = feed.render_short_rss()
path = os.path.join(prefix, 'short', '{}.xml'.format(name))
store.put(path, xml.encode('utf-8'), 'application/rss+xml')
class Feed(object):
"""Represents feed with torrent entries"""
def __init__(self, title, link, ttl=60, description=None):
self.title = title
self.link = link
self.description = description or title
self.ttl = ttl
self.items = []
self.lastBuildDate = None
self.latest_item_dt = datetime.datetime.utcfromtimestamp(0)
def add_item(self, item):
self.items.append(item)
if self.latest_item_dt < item.dt:
self.latest_item_dt = item.dt
def render_short_rss(self):
self.lastBuildDate = self.latest_item_dt
env = make_jinja_env()
template = env.get_template('rss_short.xml')
return template.render(feed=self)
def make_jinja_env():
jinja2_env = jinja2.Environment(
loader=jinja2.FileSystemLoader('templates'),
# loader=PackageLoader('package_name', 'templates'),
autoescape=True,
extensions=['jinja2.ext.autoescape']
)
jinja2_env.filters['rfc822date'] = util.datetime_to_rfc822
return jinja2_env
<|fim▁hole|> """Returns number of feed entries for category"""
if category.key.id() == 'r0': # Root category
return 100
elif category.key.id().startswith('c'): # Level 2 category
return 50
return 25 # category with subcategories<|fim▁end|>
|
def feed_size(category):
|
<|file_name|>index.go<|end_file_name|><|fim▁begin|>// Copyright (c) 2014 Couchbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mapping
import (
"encoding/json"
"fmt"
"github.com/blevesearch/bleve/analysis"
"github.com/blevesearch/bleve/analysis/analyzer/standard"
"github.com/blevesearch/bleve/analysis/datetime/optional"
"github.com/blevesearch/bleve/document"
"github.com/blevesearch/bleve/registry"
)
var MappingJSONStrict = false
const defaultTypeField = "_type"
const defaultType = "_default"
const defaultField = "_all"
const defaultAnalyzer = standard.Name
const defaultDateTimeParser = optional.Name
// An IndexMappingImpl controls how objects are placed
// into an index.
// First the type of the object is determined.
// Once the type is know, the appropriate
// DocumentMapping is selected by the type.
// If no mapping was determined for that type,
// a DefaultMapping will be used.
type IndexMappingImpl struct {
TypeMapping map[string]*DocumentMapping `json:"types,omitempty"`
DefaultMapping *DocumentMapping `json:"default_mapping"`
TypeField string `json:"type_field"`
DefaultType string `json:"default_type"`
DefaultAnalyzer string `json:"default_analyzer"`
DefaultDateTimeParser string `json:"default_datetime_parser"`
DefaultField string `json:"default_field"`
StoreDynamic bool `json:"store_dynamic"`
IndexDynamic bool `json:"index_dynamic"`
CustomAnalysis *customAnalysis `json:"analysis,omitempty"`
cache *registry.Cache
}
// AddCustomCharFilter defines a custom char filter for use in this mapping
func (im *IndexMappingImpl) AddCustomCharFilter(name string, config map[string]interface{}) error {
_, err := im.cache.DefineCharFilter(name, config)
if err != nil {
return err
}
im.CustomAnalysis.CharFilters[name] = config
return nil
}
// AddCustomTokenizer defines a custom tokenizer for use in this mapping
func (im *IndexMappingImpl) AddCustomTokenizer(name string, config map[string]interface{}) error {
_, err := im.cache.DefineTokenizer(name, config)
if err != nil {
return err
}
im.CustomAnalysis.Tokenizers[name] = config
return nil
}
// AddCustomTokenMap defines a custom token map for use in this mapping
func (im *IndexMappingImpl) AddCustomTokenMap(name string, config map[string]interface{}) error {
_, err := im.cache.DefineTokenMap(name, config)
if err != nil {
return err
}
im.CustomAnalysis.TokenMaps[name] = config
return nil
}
// AddCustomTokenFilter defines a custom token filter for use in this mapping
func (im *IndexMappingImpl) AddCustomTokenFilter(name string, config map[string]interface{}) error {
_, err := im.cache.DefineTokenFilter(name, config)
if err != nil {
return err
}
im.CustomAnalysis.TokenFilters[name] = config
return nil
}
// AddCustomAnalyzer defines a custom analyzer for use in this mapping. The
// config map must have a "type" string entry to resolve the analyzer
// constructor. The constructor is invoked with the remaining entries and
// returned analyzer is registered in the IndexMapping.
//
// bleve comes with predefined analyzers, like
// github.com/blevesearch/bleve/analysis/analyzers/custom_analyzer. They are
// available only if their package is imported by client code. To achieve this,
// use their metadata to fill configuration entries:
//
// import (
// "github.com/blevesearch/bleve/analysis/analyzers/custom_analyzer"
// "github.com/blevesearch/bleve/analysis/char_filters/html_char_filter"
// "github.com/blevesearch/bleve/analysis/token_filters/lower_case_filter"
// "github.com/blevesearch/bleve/analysis/tokenizers/unicode"
// )
//
// m := bleve.NewIndexMapping()
// err := m.AddCustomAnalyzer("html", map[string]interface{}{
// "type": custom_analyzer.Name,
// "char_filters": []string{
// html_char_filter.Name,
// },
// "tokenizer": unicode.Name,
// "token_filters": []string{
// lower_case_filter.Name,
// ...
// },
// })
func (im *IndexMappingImpl) AddCustomAnalyzer(name string, config map[string]interface{}) error {
_, err := im.cache.DefineAnalyzer(name, config)
if err != nil {
return err
}
im.CustomAnalysis.Analyzers[name] = config
return nil
}
// AddCustomDateTimeParser defines a custom date time parser for use in this mapping
func (im *IndexMappingImpl) AddCustomDateTimeParser(name string, config map[string]interface{}) error {
_, err := im.cache.DefineDateTimeParser(name, config)
if err != nil {
return err
}
im.CustomAnalysis.DateTimeParsers[name] = config
return nil
}
// NewIndexMapping creates a new IndexMapping that will use all the default indexing rules
func NewIndexMapping() *IndexMappingImpl {
return &IndexMappingImpl{
TypeMapping: make(map[string]*DocumentMapping),
DefaultMapping: NewDocumentMapping(),
TypeField: defaultTypeField,
DefaultType: defaultType,
DefaultAnalyzer: defaultAnalyzer,
DefaultDateTimeParser: defaultDateTimeParser,
DefaultField: defaultField,
IndexDynamic: IndexDynamic,
StoreDynamic: StoreDynamic,
CustomAnalysis: newCustomAnalysis(),
cache: registry.NewCache(),
}
}
// Validate will walk the entire structure ensuring the following
// explicitly named and default analyzers can be built
func (im *IndexMappingImpl) Validate() error {
_, err := im.cache.AnalyzerNamed(im.DefaultAnalyzer)
if err != nil {
return err
}
_, err = im.cache.DateTimeParserNamed(im.DefaultDateTimeParser)
if err != nil {
return err
}
err = im.DefaultMapping.Validate(im.cache)
if err != nil {
return err
}
for _, docMapping := range im.TypeMapping {
err = docMapping.Validate(im.cache)
if err != nil {
return err
}
}
return nil
}
// AddDocumentMapping sets a custom document mapping for the specified type
func (im *IndexMappingImpl) AddDocumentMapping(doctype string, dm *DocumentMapping) {
im.TypeMapping[doctype] = dm
}
<|fim▁hole|> docMapping := im.TypeMapping[docType]
if docMapping == nil {
docMapping = im.DefaultMapping
}
return docMapping
}
// UnmarshalJSON offers custom unmarshaling with optional strict validation
func (im *IndexMappingImpl) UnmarshalJSON(data []byte) error {
var tmp map[string]json.RawMessage
err := json.Unmarshal(data, &tmp)
if err != nil {
return err
}
// set defaults for fields which might have been omitted
im.cache = registry.NewCache()
im.CustomAnalysis = newCustomAnalysis()
im.TypeField = defaultTypeField
im.DefaultType = defaultType
im.DefaultAnalyzer = defaultAnalyzer
im.DefaultDateTimeParser = defaultDateTimeParser
im.DefaultField = defaultField
im.DefaultMapping = NewDocumentMapping()
im.TypeMapping = make(map[string]*DocumentMapping)
im.StoreDynamic = StoreDynamic
im.IndexDynamic = IndexDynamic
var invalidKeys []string
for k, v := range tmp {
switch k {
case "analysis":
err := json.Unmarshal(v, &im.CustomAnalysis)
if err != nil {
return err
}
case "type_field":
err := json.Unmarshal(v, &im.TypeField)
if err != nil {
return err
}
case "default_type":
err := json.Unmarshal(v, &im.DefaultType)
if err != nil {
return err
}
case "default_analyzer":
err := json.Unmarshal(v, &im.DefaultAnalyzer)
if err != nil {
return err
}
case "default_datetime_parser":
err := json.Unmarshal(v, &im.DefaultDateTimeParser)
if err != nil {
return err
}
case "default_field":
err := json.Unmarshal(v, &im.DefaultField)
if err != nil {
return err
}
case "default_mapping":
err := json.Unmarshal(v, &im.DefaultMapping)
if err != nil {
return err
}
case "types":
err := json.Unmarshal(v, &im.TypeMapping)
if err != nil {
return err
}
case "store_dynamic":
err := json.Unmarshal(v, &im.StoreDynamic)
if err != nil {
return err
}
case "index_dynamic":
err := json.Unmarshal(v, &im.IndexDynamic)
if err != nil {
return err
}
default:
invalidKeys = append(invalidKeys, k)
}
}
if MappingJSONStrict && len(invalidKeys) > 0 {
return fmt.Errorf("index mapping contains invalid keys: %v", invalidKeys)
}
err = im.CustomAnalysis.registerAll(im)
if err != nil {
return err
}
return nil
}
func (im *IndexMappingImpl) determineType(data interface{}) string {
// first see if the object implements bleveClassifier
bleveClassifier, ok := data.(bleveClassifier)
if ok {
return bleveClassifier.BleveType()
}
// next see if the object implements Classifier
classifier, ok := data.(Classifier)
if ok {
return classifier.Type()
}
// now see if we can find a type using the mapping
typ, ok := mustString(lookupPropertyPath(data, im.TypeField))
if ok {
return typ
}
return im.DefaultType
}
func (im *IndexMappingImpl) MapDocument(doc *document.Document, data interface{}) error {
docType := im.determineType(data)
docMapping := im.mappingForType(docType)
walkContext := im.newWalkContext(doc, docMapping)
if docMapping.Enabled {
docMapping.walkDocument(data, []string{}, []uint64{}, walkContext)
// see if the _all field was disabled
allMapping := docMapping.documentMappingForPath("_all")
if allMapping == nil || allMapping.Enabled {
field := document.NewCompositeFieldWithIndexingOptions("_all", true, []string{}, walkContext.excludedFromAll, document.IndexField|document.IncludeTermVectors)
doc.AddField(field)
}
}
return nil
}
type walkContext struct {
doc *document.Document
im *IndexMappingImpl
dm *DocumentMapping
excludedFromAll []string
}
func (im *IndexMappingImpl) newWalkContext(doc *document.Document, dm *DocumentMapping) *walkContext {
return &walkContext{
doc: doc,
im: im,
dm: dm,
excludedFromAll: []string{},
}
}
// AnalyzerNameForPath attempts to find the best analyzer to use with only a
// field name will walk all the document types, look for field mappings at the
// provided path, if one exists and it has an explicit analyzer that is
// returned.
func (im *IndexMappingImpl) AnalyzerNameForPath(path string) string {
// first we look for explicit mapping on the field
for _, docMapping := range im.TypeMapping {
analyzerName := docMapping.analyzerNameForPath(path)
if analyzerName != "" {
return analyzerName
}
}
// now try the default mapping
pathMapping := im.DefaultMapping.documentMappingForPath(path)
if pathMapping != nil {
if len(pathMapping.Fields) > 0 {
if pathMapping.Fields[0].Analyzer != "" {
return pathMapping.Fields[0].Analyzer
}
}
}
// next we will try default analyzers for the path
pathDecoded := decodePath(path)
for _, docMapping := range im.TypeMapping {
rv := docMapping.defaultAnalyzerName(pathDecoded)
if rv != "" {
return rv
}
}
return im.DefaultAnalyzer
}
func (im *IndexMappingImpl) AnalyzerNamed(name string) *analysis.Analyzer {
analyzer, err := im.cache.AnalyzerNamed(name)
if err != nil {
logger.Printf("error using analyzer named: %s", name)
return nil
}
return analyzer
}
func (im *IndexMappingImpl) DateTimeParserNamed(name string) analysis.DateTimeParser {
if name == "" {
name = im.DefaultDateTimeParser
}
dateTimeParser, err := im.cache.DateTimeParserNamed(name)
if err != nil {
logger.Printf("error using datetime parser named: %s", name)
return nil
}
return dateTimeParser
}
func (im *IndexMappingImpl) datetimeParserNameForPath(path string) string {
// first we look for explicit mapping on the field
for _, docMapping := range im.TypeMapping {
pathMapping := docMapping.documentMappingForPath(path)
if pathMapping != nil {
if len(pathMapping.Fields) > 0 {
if pathMapping.Fields[0].Analyzer != "" {
return pathMapping.Fields[0].Analyzer
}
}
}
}
return im.DefaultDateTimeParser
}
func (im *IndexMappingImpl) AnalyzeText(analyzerName string, text []byte) (analysis.TokenStream, error) {
analyzer, err := im.cache.AnalyzerNamed(analyzerName)
if err != nil {
return nil, err
}
return analyzer.Analyze(text), nil
}
// FieldAnalyzer returns the name of the analyzer used on a field.
func (im *IndexMappingImpl) FieldAnalyzer(field string) string {
return im.AnalyzerNameForPath(field)
}
// wrapper to satisfy new interface
func (im *IndexMappingImpl) DefaultSearchField() string {
return im.DefaultField
}<|fim▁end|>
|
func (im *IndexMappingImpl) mappingForType(docType string) *DocumentMapping {
|
<|file_name|>bitcoin_es_DO.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="es_DO" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About PieCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>PieCoin</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The PieCoin developers
Copyright © 2015 The PieCoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) and cryptographic software written by Eric Young (<a href="mailto:[email protected]">[email protected]</a>) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Haga doble clic para editar una dirección o etiqueta</translation>
</message>
<message>
<location line="+24"/>
<source>Create a new address</source>
<translation>Crear una nueva dirección</translation>
</message>
<message>
<location line="+10"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copiar la dirección seleccionada al portapapeles del sistema</translation>
</message>
<message>
<location line="-7"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-43"/>
<source>These are your PieCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>&Copy Address</source>
<translation>&Copiar dirección</translation>
</message>
<message>
<location line="+7"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign a message to prove you own a PieCoin address</source>
<translation type="unfinished"/><|fim▁hole|> <source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Delete the currently selected address from the list</source>
<translation>Borrar de la lista la dirección seleccionada</translation>
</message>
<message>
<location line="-10"/>
<source>Verify a message to ensure it was signed with a specified PieCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Delete</source>
<translation>&Eliminar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Copiar &etiqueta</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Editar</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos de columnas separadas por coma (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+145"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(sin etiqueta)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Diálogo de contraseña</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Introducir contraseña</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nueva contraseña</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repita la nueva contraseña</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+38"/>
<source>Encrypt wallet</source>
<translation>Cifrar la cartera</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Esta operación requiere su contraseña para desbloquear la cartera</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Desbloquear cartera</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Esta operación requiere su contraseña para descifrar la cartera.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Descifrar la certare</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Cambiar contraseña</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Introduzca la contraseña anterior de la cartera y la nueva. </translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>Confirmar cifrado de la cartera</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>¿Seguro que desea cifrar su monedero?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANTE: Cualquier copia de seguridad que haya realizado previamente de su archivo de monedero debe reemplazarse con el nuevo archivo de monedero cifrado. Por razones de seguridad, las copias de seguridad previas del archivo de monedero no cifradas serán inservibles en cuanto comience a usar el nuevo monedero cifrado.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Aviso: ¡La tecla de bloqueo de mayúsculas está activada!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Monedero cifrado</translation>
</message>
<message>
<location line="-140"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>PieCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Ha fallado el cifrado del monedero</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Ha fallado el cifrado del monedero debido a un error interno. El monedero no ha sido cifrado.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Las contraseñas no coinciden.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Ha fallado el desbloqueo del monedero</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La contraseña introducida para descifrar el monedero es incorrecta.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Ha fallado el descifrado del monedero</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Se ha cambiado correctamente la contraseña del monedero.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+297"/>
<source>Sign &message...</source>
<translation>Firmar &mensaje...</translation>
</message>
<message>
<location line="-64"/>
<source>Show general overview of wallet</source>
<translation>Mostrar vista general del monedero</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transacciones</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Examinar el historial de transacciones</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-18"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>E&xit</source>
<translation>&Salir</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Salir de la aplicación</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about PieCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Acerca de &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Mostrar información acerca de Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opciones...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Cifrar monedero…</translation>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation>Copia de &respaldo del monedero...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Cambiar la contraseña…</translation>
</message>
<message>
<location line="+9"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-55"/>
<source>Send coins to a PieCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source>Modify configuration options for PieCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Backup wallet to another location</source>
<translation>Copia de seguridad del monedero en otra ubicación</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cambiar la contraseña utilizada para el cifrado del monedero</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>Ventana de &depuración</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Abrir la consola de depuración y diagnóstico</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Verificar mensaje...</translation>
</message>
<message>
<location line="-214"/>
<location line="+551"/>
<source>PieCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-551"/>
<source>Wallet</source>
<translation>Monedero</translation>
</message>
<message>
<location line="+193"/>
<source>&About PieCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>Mo&strar/ocultar</translation>
</message>
<message>
<location line="+8"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Archivo</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Configuración</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>A&yuda</translation>
</message>
<message>
<location line="+17"/>
<source>Tabs toolbar</source>
<translation>Barra de pestañas</translation>
</message>
<message>
<location line="+46"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+58"/>
<source>PieCoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to PieCoin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+488"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-808"/>
<source>&Dashboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+273"/>
<source>Up to date</source>
<translation>Actualizado</translation>
</message>
<message>
<location line="+43"/>
<source>Catching up...</source>
<translation>Actualizando...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Transacción enviada</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Transacción entrante</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Fecha: %1
Cantidad: %2
Tipo: %3
Dirección: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid PieCoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Wallet is <b>not encrypted</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>El monedero está <b>cifrado</b> y actualmente <b>desbloqueado</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>El monedero está <b>cifrado</b> y actualmente <b>bloqueado</b></translation>
</message>
<message>
<location line="+24"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+91"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+433"/>
<source>%n hour(s)</source>
<translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation>
</message>
<message>
<location line="-456"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+27"/>
<location line="+433"/>
<source>%n day(s)</source>
<translation><numerusform>%n día</numerusform><numerusform>%n días</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+6"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+0"/>
<source>%1 and %2</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+0"/>
<source>%n year(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+324"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+104"/>
<source>A fatal error occurred. PieCoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+110"/>
<source>Network Alert</source>
<translation>Alerta de red</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Cantidad:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Cuantía:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Prioridad:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Tasa:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Envío pequeño:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+552"/>
<source>no</source>
<translation>no</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Después de tasas:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Cambio:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>(des)selecciona todos</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Modo arbol</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Modo lista</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Confirmaciones</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Confirmado</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prioridad</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Copiar dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar etiqueta</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Copiar cantidad</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Copiar identificador de transacción</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Copiar cantidad</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Copiar donación</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Copiar después de aplicar donación</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copiar bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Copiar prioridad</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copiar envío pequeño</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copiar cambio</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>lo más alto</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>alto</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>medio-alto</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>medio</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>bajo-medio</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>bajo</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>lo más bajo</translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>si</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(sin etiqueta)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>Enviar desde %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(cambio)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editar Dirección</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etiqueta</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Dirección</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Nueva dirección de recepción</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nueva dirección de envío</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Editar dirección de recepción</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Editar dirección de envío</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>La dirección introducida "%1" ya está presente en la libreta de direcciones.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid PieCoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>No se pudo desbloquear el monedero.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Ha fallado la generación de la nueva clave.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+426"/>
<location line="+12"/>
<source>PieCoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opciones</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Principal</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Comisión de &transacciones</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start PieCoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start PieCoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Red</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the PieCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Mapear el puerto usando &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the PieCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Dirección &IP del proxy:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Puerto:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Puerto del servidor proxy (ej. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>&Versión SOCKS:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Versión del proxy SOCKS (ej. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Ventana</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Minimizar la ventana a la bandeja de iconos del sistema.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimizar a la bandeja en vez de a la barra de tareas</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimizar en lugar de salir de la aplicación al cerrar la ventana. Cuando esta opción está activa, la aplicación solo se puede cerrar seleccionando Salir desde el menú.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimizar al cerrar</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Interfaz</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>I&dioma de la interfaz de usuario</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting PieCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>Mostrar las cantidades en la &unidad:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Elegir la subdivisión predeterminada para mostrar cantidades en la interfaz y cuando se envían monedas.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show coin control features or not.</source>
<translation>Mostrar o no características de control de moneda</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Whether to select the coin outputs randomly or with minimal coin age.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Minimize weight consumption (experimental)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use black visual theme (requires restart)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Aceptar</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>predeterminado</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting PieCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>La dirección proxy indicada es inválida.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Desde</translation>
</message>
<message>
<location line="+46"/>
<location line="+247"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the PieCoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-173"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Unconfirmed:</source>
<translation>No confirmado(s):</translation>
</message>
<message>
<location line="-113"/>
<source>Wallet</source>
<translation>Monedero</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Su balance actual gastable</translation>
</message>
<message>
<location line="+80"/>
<source>Immature:</source>
<translation>No disponible:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Saldo recién minado que aún no está disponible.</translation>
</message>
<message>
<location line="+23"/>
<source>Total:</source>
<translation>Total:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Su balance actual total</translation>
</message>
<message>
<location line="+50"/>
<source><b>Recent transactions</b></source>
<translation><b>Movimientos recientes</b></translation>
</message>
<message>
<location line="-118"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-32"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>desincronizado</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start PieCoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nombre del cliente</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<source>N/A</source>
<translation>N/D</translation>
</message>
<message>
<location line="-194"/>
<source>Client version</source>
<translation>Versión del cliente</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Información</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Utilizando la versión OpenSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Hora de inicio</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Red</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Número de conexiones</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Cadena de bloques</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Número actual de bloques</translation>
</message>
<message>
<location line="+197"/>
<source>&Network Traffic</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Totals</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>In:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Out:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-383"/>
<source>Last block time</source>
<translation>Hora del último bloque</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Abrir</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the PieCoin-Qt help message to get a list with possible PieCoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Consola</translation>
</message>
<message>
<location line="-237"/>
<source>Build date</source>
<translation>Fecha de compilación</translation>
</message>
<message>
<location line="-104"/>
<source>PieCoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>PieCoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+256"/>
<source>Debug log file</source>
<translation>Archivo de registro de depuración</translation>
</message>
<message>
<location line="+7"/>
<source>Open the PieCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Borrar consola</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="+325"/>
<source>Welcome to the PieCoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Use las flechas arriba y abajo para navegar por el historial y <b>Control+L</b> para limpiar la pantalla.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Escriba <b>help</b> para ver un resumen de los comandos disponibles.</translation>
</message>
<message>
<location line="+127"/>
<source>%1 B</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 KB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 MB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 GB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 h %2 m</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+181"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Enviar monedas</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Características de control de la moneda</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Entradas...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>Seleccionado automaticamente</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Fondos insuficientes!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Cantidad:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Cuantía:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 PIE</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation>Prioridad:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Tasa:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Envío pequeño:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Después de tasas:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Enviar a múltiples destinatarios de una vez</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Añadir &destinatario</translation>
</message>
<message>
<location line="+16"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Limpiar &todo</translation>
</message>
<message>
<location line="+24"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 PIE</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirmar el envío</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Enviar</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a PieCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Copiar cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar cuantía</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Copiar donación</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Copiar después de aplicar donación</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copiar bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Copiar prioridad</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copiar envío pequeño</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copiar Cambio</translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirmar el envío de monedas</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>La dirección de recepción no es válida, compruébela de nuevo.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>La cantidad por pagar tiene que ser mayor de 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>La cantidad sobrepasa su saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>El total sobrepasa su saldo cuando se incluye la tasa de envío de %1</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Se ha encontrado una dirección duplicada. Solo se puede enviar a cada dirección una vez por operación de envío.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+247"/>
<source>WARNING: Invalid PieCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(sin etiqueta)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Ca&ntidad:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Pagar a:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Etiquete esta dirección para añadirla a la libreta</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etiqueta:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Pegar dirección desde portapapeles</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a PieCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Firmas - Firmar / verificar un mensaje</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&Firmar mensaje</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Puede firmar mensajes con sus direcciones para demostrar que las posee. Tenga cuidado de no firmar cualquier cosa vaga, ya que los ataques de phishing pueden tratar de engañarle para suplantar su identidad. Firme solo declaraciones totalmente detalladas con las que usted esté de acuerdo.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Pegar dirección desde portapapeles</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Introduzca el mensaje que desea firmar aquí</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copiar la firma actual al portapapeles del sistema</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this PieCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Limpiar todos los campos de la firma de mensaje</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Limpiar &todo</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Verificar mensaje</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Introduzca la dirección para la firma, el mensaje (asegurándose de copiar tal cual los saltos de línea, espacios, tabulaciones, etc.) y la firma a continuación para verificar el mensaje. Tenga cuidado de no asumir más información de lo que dice el propio mensaje firmado para evitar fraudes basados en ataques de tipo man-in-the-middle.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified PieCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Limpiar todos los campos de la verificación de mensaje</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a PieCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Haga clic en "Firmar mensaje" para generar la firma</translation>
</message>
<message>
<location line="+3"/>
<source>Enter PieCoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>La dirección introducida es inválida.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Verifique la dirección e inténtelo de nuevo.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>La dirección introducida no corresponde a una clave.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Se ha cancelado el desbloqueo del monedero. </translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>No se dispone de la clave privada para la dirección introducida.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Ha fallado la firma del mensaje.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Mensaje firmado.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>No se puede decodificar la firma.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Compruebe la firma e inténtelo de nuevo.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>La firma no coincide con el resumen del mensaje.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>La verificación del mensaje ha fallado.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Mensaje verificado.</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+75"/>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+25"/>
<source>Open until %1</source>
<translation>Abierto hasta %1</translation>
</message>
<message>
<location line="+6"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/fuera de línea</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/no confirmado</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmaciones</translation>
</message>
<message>
<location line="+17"/>
<source>Status</source>
<translation>Estado</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, transmitir a través de %n nodo</numerusform><numerusform>, transmitir a través de %n nodos</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Fuente</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generado</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Para</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>dirección propia</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etiqueta</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Crédito</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>disponible en %n bloque más</numerusform><numerusform>disponible en %n bloques más</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>no aceptada</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Débito</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Comisión de transacción</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Cantidad neta</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mensaje</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comentario</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Identificador de transacción</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Información de depuración</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transacción</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>entradas</translation>
</message>
<message>
<location line="+21"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>verdadero</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>falso</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, todavía no se ha sido difundido satisfactoriamente</translation>
</message>
<message numerus="yes">
<location line="-36"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+71"/>
<source>unknown</source>
<translation>desconocido</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detalles de transacción</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Esta ventana muestra información detallada sobre la transacción</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+231"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+52"/>
<source>Open until %1</source>
<translation>Abierto hasta %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmado (%1 confirmaciones)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Abrir para %n bloque más</numerusform><numerusform>Abrir para %n bloques más</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Este bloque no ha sido recibido por otros nodos y probablemente no sea aceptado!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generado pero no aceptado</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Recibidos de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pago propio</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(nd)</translation>
</message>
<message>
<location line="+194"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Estado de transacción. Pasa el ratón sobre este campo para ver el número de confirmaciones.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Fecha y hora en que se recibió la transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipo de transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Dirección de destino de la transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Cantidad retirada o añadida al saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+54"/>
<location line="+17"/>
<source>All</source>
<translation>Todo</translation>
</message>
<message>
<location line="-16"/>
<source>Today</source>
<translation>Hoy</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Esta semana</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Este mes</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Mes pasado</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Este año</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Rango...</translation>
</message>
<message>
<location line="+12"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>A usted mismo</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Otra</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Introduzca una dirección o etiqueta que buscar</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Cantidad mínima</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copiar dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar cuantía</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copiar identificador de transacción</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Editar etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Mostrar detalles de la transacción</translation>
</message>
<message>
<location line="+138"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos de columnas separadas por coma (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmado</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Rango:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>para</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+208"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+173"/>
<source>PieCoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Uso:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or PieCoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Muestra comandos
</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Recibir ayuda para un comando
</translation>
</message>
<message>
<location line="-147"/>
<source>Options:</source>
<translation>Opciones:
</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: PieCoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: PieCoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Especificar archivo de monedero (dentro del directorio de datos)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Especificar directorio para los datos</translation>
</message>
<message>
<location line="-25"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=PieCoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "PieCoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Establecer el tamaño de caché de la base de datos en megabytes (predeterminado: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 22077 or testnet: 27077)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Mantener como máximo <n> conexiones a pares (predeterminado: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Conectar a un nodo para obtener direcciones de pares y desconectar</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Especifique su propia dirección pública</translation>
</message>
<message>
<location line="+4"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Always query for peer addresses via DNS lookup (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Umbral para la desconexión de pares con mal comportamiento (predeterminado: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Número de segundos en que se evita la reconexión de pares con mal comportamiento (predeterminado: 86400)</translation>
</message>
<message>
<location line="-37"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Ha ocurrido un error al configurar el puerto RPC %u para escucha en IPv4: %s</translation>
</message>
<message>
<location line="+65"/>
<source>Listen for JSON-RPC connections on <port> (default: 31415 or testnet: 27088)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-17"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aceptar comandos consola y JSON-RPC
</translation>
</message>
<message>
<location line="+1"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Ejecutar en segundo plano como daemon y aceptar comandos
</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Usar la red de pruebas
</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Aceptar conexiones desde el exterior (predeterminado: 1 si no -proxy o -connect)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Ha ocurrido un error al configurar el puerto RPC %u para escuchar mediante IPv6. Recurriendo a IPv4: %s</translation>
</message>
<message>
<location line="+96"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Aviso: ¡-paytxfee tiene un valor muy alto! Esta es la comisión que pagará si envía una transacción.</translation>
</message>
<message>
<location line="-103"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong PieCoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+132"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Aviso: ¡Error al leer wallet.dat! Todas las claves se han leído correctamente, pero podrían faltar o ser incorrectos los datos de transacciones o las entradas de la libreta de direcciones.</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Aviso: ¡Recuperados datos de wallet.dat corrupto! El wallet.dat original se ha guardado como wallet.{timestamp}.bak en %s; si hubiera errores en su saldo o transacciones, deberá restaurar una copia de seguridad.</translation>
</message>
<message>
<location line="-31"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Intento de recuperar claves privadas de un wallet.dat corrupto</translation>
</message>
<message>
<location line="+5"/>
<source>Block creation options:</source>
<translation>Opciones de creación de bloques:</translation>
</message>
<message>
<location line="-69"/>
<source>Connect only to the specified node(s)</source>
<translation>Conectar sólo a los nodos (o nodo) especificados</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Descubrir dirección IP propia (predeterminado: 1 al escuchar sin -externalip)</translation>
</message>
<message>
<location line="+101"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Ha fallado la escucha en todos los puertos. Use -listen=0 si desea esto.</translation>
</message>
<message>
<location line="-91"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+89"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Búfer de recepción máximo por conexión, <n>*1000 bytes (predeterminado: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Búfer de recepción máximo por conexión, , <n>*1000 bytes (predeterminado: 1000)</translation>
</message>
<message>
<location line="-17"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Conectarse solo a nodos de la red <net> (IPv4, IPv6 o Tor)</translation>
</message>
<message>
<location line="+31"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>Opciones SSL: (ver la Bitcoin Wiki para instrucciones de configuración SSL)</translation>
</message>
<message>
<location line="-81"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Enviar información de trazas/depuración a la consola en lugar de al archivo debug.log</translation>
</message>
<message>
<location line="+5"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+30"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Establecer tamaño mínimo de bloque en bytes (predeterminado: 0)</translation>
</message>
<message>
<location line="-35"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Reducir el archivo debug.log al iniciar el cliente (predeterminado: 1 sin -debug)</translation>
</message>
<message>
<location line="-43"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Especificar el tiempo máximo de conexión en milisegundos (predeterminado: 5000)</translation>
</message>
<message>
<location line="+116"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-86"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Usar UPnP para asignar el puerto de escucha (predeterminado: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Usar UPnP para asignar el puerto de escucha (predeterminado: 1 al escuchar)</translation>
</message>
<message>
<location line="-26"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Username for JSON-RPC connections</source>
<translation>Nombre de usuario para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="+51"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Aviso: Esta versión es obsoleta, actualización necesaria!</translation>
</message>
<message>
<location line="-54"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupto. Ha fallado la recuperación.</translation>
</message>
<message>
<location line="-56"/>
<source>Password for JSON-RPC connections</source>
<translation>Contraseña para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="-32"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>If <category> is not supplied, output all debugging information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source><category> can be:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permitir conexiones JSON-RPC desde la dirección IP especificada
</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Enviar comando al nodo situado en <ip> (predeterminado: 127.0.0.1)
</translation>
</message>
<message>
<location line="+1"/>
<source>Wait for RPC server to start</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Ejecutar un comando cuando cambia el mejor bloque (%s en cmd se sustituye por el hash de bloque)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Ejecutar comando cuando una transacción del monedero cambia (%s en cmd se remplazará por TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Actualizar el monedero al último formato</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Ajustar el número de claves en reserva <n> (predeterminado: 100)
</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Volver a examinar la cadena de bloques en busca de transacciones del monedero perdidas</translation>
</message>
<message>
<location line="+3"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Usar OpenSSL (https) para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Certificado del servidor (predeterminado: server.cert)
</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Clave privada del servidor (predeterminado: server.pem)
</translation>
</message>
<message>
<location line="+10"/>
<source>Initialization sanity check failed. PieCoin is shutting down.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-174"/>
<source>This help message</source>
<translation>Este mensaje de ayuda
</translation>
</message>
<message>
<location line="+104"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>No es posible conectar con %s en este sistema (bind ha dado el error %d, %s)</translation>
</message>
<message>
<location line="-133"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permitir búsquedas DNS para -addnode, -seednode y -connect</translation>
</message>
<message>
<location line="+126"/>
<source>Loading addresses...</source>
<translation>Cargando direcciones...</translation>
</message>
<message>
<location line="-12"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Error al cargar wallet.dat: el monedero está dañado</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of PieCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart PieCoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Error al cargar wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Dirección -proxy inválida: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>La red especificada en -onlynet '%s' es desconocida</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Solicitada versión de proxy -socks desconocida: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>No se puede resolver la dirección de -bind: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>No se puede resolver la dirección de -externalip: '%s'</translation>
</message>
<message>
<location line="-23"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Cantidad inválida para -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+60"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Cuantía no válida</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Fondos insuficientes</translation>
</message>
<message>
<location line="-40"/>
<source>Loading block index...</source>
<translation>Cargando el índice de bloques...</translation>
</message>
<message>
<location line="-110"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Añadir un nodo al que conectarse y tratar de mantener la conexión abierta</translation>
</message>
<message>
<location line="+125"/>
<source>Unable to bind to %s on this computer. PieCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-101"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Minimize weight consumption (experimental) (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>How many blocks to check at startup (default: 500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Keep at most <n> unconnectable blocks in memory (default: %u)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. PieCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Loading wallet...</source>
<translation>Cargando monedero...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>No se puede rebajar el monedero</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>No se puede escribir la dirección predeterminada</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Reexplorando...</translation>
</message>
<message>
<location line="+2"/>
<source>Done loading</source>
<translation>Generado pero no aceptado</translation>
</message>
<message>
<location line="-161"/>
<source>To use the %s option</source>
<translation>Para utilizar la opción %s</translation>
</message>
<message>
<location line="+188"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="-18"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Tiene que establecer rpcpassword=<contraseña> en el fichero de configuración: ⏎
%s ⏎
Si el archivo no existe, créelo con permiso de lectura solamente del propietario.</translation>
</message>
</context>
</TS><|fim▁end|>
|
</message>
<message>
<location line="+3"/>
|
<|file_name|>phobia.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from generator import Generator
import logging
class Phobia(Generator):
""" Define a phobia to be used in your game """
def __init__(self, redis, features={}):
Generator.__init__(self, redis, features)
self.logger = logging.getLogger(__name__)
<|fim▁hole|> if not hasattr(self, 'text'):
self.text = self.render_template(self.template)
self.text = self.render_template(self.text)
self.text = self.text[0].capitalize() + self.text[1:]
def __str__(self):
return self.text<|fim▁end|>
|
# Double parse the template to fill in templated template values.
|
<|file_name|>composedquery.py<|end_file_name|><|fim▁begin|>## begin license ##
#
# "Meresco Lucene" is a set of components and tools to integrate Lucene into Meresco
#
# Copyright (C) 2013-2016, 2019-2021 Seecr (Seek You Too B.V.) https://seecr.nl
# Copyright (C) 2013-2014 Stichting Bibliotheek.nl (BNL) http://www.bibliotheek.nl
# Copyright (C) 2015-2016, 2019 Koninklijke Bibliotheek (KB) http://www.kb.nl
# Copyright (C) 2016, 2020-2021 Stichting Kennisnet https://www.kennisnet.nl
# Copyright (C) 2021 Data Archiving and Network Services https://dans.knaw.nl
# Copyright (C) 2021 SURF https://www.surf.nl
# Copyright (C) 2021 The Netherlands Institute for Sound and Vision https://beeldengeluid.nl
#
# This file is part of "Meresco Lucene"
#
# "Meresco Lucene" is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# "Meresco Lucene" 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with "Meresco Lucene"; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
## end license ##
from .utils import simplifiedDict
from meresco.components.json import JsonDict
from simplejson.decoder import JSONDecodeError
class ComposedQuery(object):
def __init__(self, resultsFromCore, query=None):
self.cores = set()
self._queries = {}
self._filterQueries = {}
self._excludeFilterQueries = {}
self._facets = {}
self._drilldownQueries = {}
self._otherCoreFacetFilters = {}
self._rankQueries = {}
self._matches = {}
self._unites = []
self._sortKeys = []
self.resultsFrom = resultsFromCore
if query:
self.setCoreQuery(resultsFromCore, query=query)
else:
self.cores.add(resultsFromCore)
def _makeProperty(name, defaultValue=None):
return property(
fget=lambda self: getattr(self, name, defaultValue),
fset=lambda self, value: setattr(self, name, value)
)
stop = _makeProperty('_stop')
start = _makeProperty('_start')
sortKeys = _makeProperty('_sortKeys')
suggestionRequest = _makeProperty('_suggestionRequest')
dedupField = _makeProperty('_dedupField')
dedupSortField = _makeProperty('_dedupSortField')
storedFields = _makeProperty('_storedFields')
clustering = _makeProperty('_clustering')
clusteringConfig = _makeProperty('_clusteringConfig')
unqualifiedTermFields = _makeProperty('_unqualifiedTermFields')
rankQueryScoreRatio = _makeProperty('_rankQueryScoreRatio')
relationalFilterJson = _makeProperty('_relationalFilterJson')
del _makeProperty
def setCoreQuery(self, core, query, filterQueries=None, facets=None):
self.cores.add(core)
self._queries[core] = query
if not filterQueries is None:
for filterQuery in filterQueries:
self.addFilterQuery(core, filterQuery)
if not facets is None:
for facet in facets:
self.addFacet(core, facet)
return self
def addFilterQuery(self, core, query):
self.cores.add(core)
self._filterQueries.setdefault(core, []).append(query)
return self
def addExcludeFilterQuery(self, core, query):
self.cores.add(core)
self._excludeFilterQueries.setdefault(core, []).append(query)
return self
def addFacet(self, core, facet):
self.cores.add(core)
self._facets.setdefault(core, []).append(facet)
return self
def addDrilldownQuery(self, core, drilldownQuery):
self.cores.add(core)
self._drilldownQueries.setdefault(core, []).append(drilldownQuery)
return self
def addOtherCoreFacetFilter(self, core, query):
self.cores.add(core)
self._otherCoreFacetFilters.setdefault(core, []).append(query)
return self
def setRankQuery(self, core, query):
self.cores.add(core)
self._rankQueries[core] = query
return self
def addMatch(self, matchCoreASpec, matchCoreBSpec):
self._matches[(matchCoreASpec['core'], matchCoreBSpec['core'])] = (matchCoreASpec, matchCoreBSpec)
resultsFromCoreSpecFound = False
for matchCoreSpec in [matchCoreASpec, matchCoreBSpec]:
coreName = matchCoreSpec['core']
if coreName == self.resultsFrom:
resultsFromCoreSpecFound = True
try:
matchCoreSpec['uniqueKey']
except KeyError:
raise ValueError("Match for result core '%s' must have a uniqueKey specification." % self.resultsFrom)
if not resultsFromCoreSpecFound:
raise ValueError("Match that does not include resultsFromCore ('%s') not yet supported" % self.resultsFrom)
return self
def addUnite(self, uniteCoreASpec, uniteCoreBSpec):
if len(self.unites) > 0:
raise ValueError("No more than 1 addUnite supported")
for uniteCoreSpec in (uniteCoreASpec, uniteCoreBSpec):
self.cores.add(uniteCoreSpec['core'])
self._unites.append(Unite(self, uniteCoreASpec, uniteCoreBSpec))
return self
def addSortKey(self, sortKey):
core = sortKey.get('core', self.resultsFrom)
self.cores.add(core)
self._sortKeys.append(sortKey)
def queryFor(self, core):
return self._queries.get(core)
def excludeFilterQueriesFor(self, core):
return self._excludeFilterQueries.get(core, [])
def filterQueriesFor(self, core):
return self._filterQueries.get(core, [])
def facetsFor(self, core):
return self._facets.get(core, [])
def drilldownQueriesFor(self, core):
return self._drilldownQueries.get(core, [])
def otherCoreFacetFiltersFor(self, core):
return self._otherCoreFacetFilters.get(core, [])
def rankQueryFor(self, core):
return self._rankQueries.get(core)
def keyName(self, core, otherCore):
if core == otherCore: #TODO: Needed for filters/rank's in same core as queried core
for matchCoreASpec, matchCoreBSpec in self._matches.values():
if matchCoreASpec['core'] == core:
coreSpec = matchCoreASpec
break
elif matchCoreBSpec['core'] == core:
coreSpec = matchCoreBSpec
break
else:
coreSpec, _ = self._matchCoreSpecs(core, otherCore)
return coreSpec.get('uniqueKey', coreSpec.get('key'))
def keyNames(self, core):
keyNames = set()
for coreName in self.cores:
if coreName != core:
keyNames.add(self.keyName(core, coreName))
return keyNames
def queriesFor(self, core):
return [q for q in [self.queryFor(core)] + self.filterQueriesFor(core) if q]
@property
def unites(self):
return self._unites[:]
@property
def filterQueries(self):
return self._filterQueries.items()
@property
def numberOfUsedCores(self):
return len(self.cores)
def isSingleCoreQuery(self):
return self.numberOfUsedCores == 1
def coresInMatches(self):
return set(c for matchKey in self._matches.keys() for c in matchKey)
def validate(self):
for core in self.cores:
if core == self.resultsFrom:
continue
try:
self._matchCoreSpecs(self.resultsFrom, core)
except KeyError:
raise ValueError("No match set for cores %s" % str((self.resultsFrom, core)))
if self.relationalFilterJson:
try:
JsonDict.loads(self.relationalFilterJson)
except JSONDecodeError:
raise ValueError("Value '%s' for 'relationalFilterJson' can not be parsed as JSON." % self.relationalFilterJson)
def convertWith(self, **converts):
def convertQuery(core, query):
if query is None:
return None
convertFunction = converts[core]
if core == self.resultsFrom:<|fim▁hole|> if self.unqualifiedTermFields:
kwargs['unqualifiedTermFields'] = self.unqualifiedTermFields
return convertFunction(query, **kwargs)
return convertFunction(query)
self._queries = dict((core, convertQuery(core, v)) for core, v in self._queries.items())
self._filterQueries = dict((core, [convertQuery(core, v) for v in values]) for core, values in self._filterQueries.items())
self._excludeFilterQueries = dict((core, [convertQuery(core, v) for v in values]) for core, values in self._excludeFilterQueries.items())
self._rankQueries = dict((core, convertQuery(core, v)) for core, v in self._rankQueries.items())
for unite in self._unites:
unite.convertQuery(convertQuery)
self._otherCoreFacetFilters = dict((core, [convertQuery(core, v) for v in values]) for core, values in self._otherCoreFacetFilters.items())
def asDict(self):
result = dict(vars(self))
result['_matches'] = dict(('->'.join(key), value) for key, value in result['_matches'].items())
result['_unites'] = [unite.asDict() for unite in self._unites]
result['cores'] = list(sorted(self.cores))
return result
@classmethod
def fromDict(cls, dct):
cq = cls(dct['resultsFrom'])
matches = dct['_matches']
dct['_matches'] = dict((tuple(key.split('->')), value) for key, value in matches.items())
dct['_unites'] = [Unite.fromDict(cq, uniteDict) for uniteDict in dct['_unites']]
dct['cores'] = set(dct['cores'])
for attr, value in dct.items():
setattr(cq, attr, value)
return cq
def _matchCoreSpecs(self, *cores):
try:
coreASpec, coreBSpec = self._matches[cores]
except KeyError:
coreBSpec, coreASpec = self._matches[tuple(reversed(cores))]
return coreASpec, coreBSpec
def __repr__(self):
return "%s%s" % (self.__class__.__name__, self.asDict())
def infoDict(self):
return {
'type': self.__class__.__name__,
'query': simplifiedDict(dict((k.replace('_', ''), v) for k,v in self.asDict().items()))
}
class Unite(object):
def __init__(self, parent, coreASpec, coreBSpec):
self._parent = parent
self.coreASpec = coreASpec
self.coreBSpec = coreBSpec
def queries(self):
keyNameA = self._parent.keyName(self.coreASpec['core'], self.coreBSpec['core'])
keyNameB = self._parent.keyName(self.coreBSpec['core'], self.coreASpec['core'])
resultKeyName = keyNameA if self._parent.resultsFrom == self.coreASpec['core'] else keyNameB
yield dict(core=self.coreASpec['core'], query=self.coreASpec['query'], keyName=keyNameA), resultKeyName
yield dict(core=self.coreBSpec['core'], query=self.coreBSpec['query'], keyName=keyNameB), resultKeyName
def convertQuery(self, convertQueryFunction):
for spec in [self.coreASpec, self.coreBSpec]:
spec['query'] = convertQueryFunction(spec['core'], spec['query'])
def asDict(self):
return {'A': [self.coreASpec['core'], self.coreASpec['query']], 'B': [self.coreBSpec['core'], self.coreBSpec['query']]}
@classmethod
def fromDict(cls, parent, dct):
return cls(parent, dict(core=dct['A'][0], query=dct['A'][1]), dict(core=dct['B'][0], query=dct['B'][1]))<|fim▁end|>
|
kwargs = {'composedQuery': self}
|
<|file_name|>district-demographic-estimate-controller.js<|end_file_name|><|fim▁begin|>/*
* This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 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 Mozilla Public License for more details.
*
* You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
*/
function DistrictDemographicEstimateController($scope, categories, years, DistrictDemographicEstimates, SaveDistrictDemographicEstimates) {
$scope.categories = categories;
$scope.years = years;
$scope.year = years[0];
$scope.OnPopulationChanged = function(population, district, category){
var pop = $scope.toNumber(population.value);
if(category.isPrimaryEstimate){
angular.forEach(district.districtEstimates, function(estimate){
if(population.demographicEstimateId !== estimate.demographicEstimateId){
estimate.value = $scope.round(estimate.conversionFactor * pop / 100) ;
}
});
}
};
$scope.onParamChanged = function(){
DistrictDemographicEstimates.get({year: $scope.year}, function(data){
$scope.form = data.estimates;
angular.forEach($scope.form.estimateLineItems, function(fe){
fe.indexedEstimates = _.indexBy( fe.districtEstimates , 'demographicEstimateId' );
});
});
};
$scope.toNumber = function (val) {
if (angular.isDefined(val) && val !== null) {
return parseInt(val, 10);
}
return 0;
};
$scope.round = function(val){
return Math.ceil(val);
};
$scope.save = function(){
SaveDistrictDemographicEstimates.update($scope.form, function(data){
// show the saved message
//TODO: move this string to the messages property file.
$scope.message = "District demographic estimates successfully saved.";
});
};
$scope.onParamChanged();
}<|fim▁hole|> categories: function ($q, $timeout, DemographicEstimateCategories) {
var deferred = $q.defer();
$timeout(function () {
DemographicEstimateCategories.get({}, function (data) {
deferred.resolve(data.estimate_categories);
}, {});
}, 100);
return deferred.promise;
}, years: function ($q, $timeout, OperationYears) {
var deferred = $q.defer();
$timeout(function () {
OperationYears.get({}, function (data) {
deferred.resolve(data.years);
});
}, 100);
return deferred.promise;
}
};<|fim▁end|>
|
DistrictDemographicEstimateController.resolve = {
|
<|file_name|>urls.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.conf.urls import url
from . import views
urlpatterns = [
url(r"^$", views.home, name="board"),
url(r"^/all$", views.all_feed, name="board_all"),
url(r"^/course/(?P<course_id>.*)?$", views.course_feed, name="board_course"),
url(r"^/submit/course/(?P<course_id>.*)?$", views.course_feed_post, name="board_course_post"),
url(r"^/meme/submit/course/(?P<course_id>.*)?$", views.course_feed_post_meme, name="board_course_post_meme"),
url(r"^/section/(?P<section_id>.*)?$", views.section_feed, name="board_section"),
url(r"^/submit/section/(?P<section_id>.*)?$", views.section_feed_post, name="board_section_post"),
url(r"^/meme/submit/section/(?P<section_id>.*)?$", views.section_feed_post_meme, name="board_section_post_meme"),
url(r"^/meme/get$", views.get_memes_json, name="board_get_memes_json"),<|fim▁hole|>
url(r"^/post/(?P<post_id>\d+)?$", views.view_post, name="board_post"),
url(r"^/post/(?P<post_id>\d+)/comment$", views.comment_view, name="board_comment"),
# url(r"^/add$", views.add_post_view, name="add_boardpost"),
url(r"^/post/(?P<id>\d+)/modify$", views.modify_post_view, name="board_modify_post"),
url(r"^/post/(?P<id>\d+)/delete$", views.delete_post_view, name="board_delete_post"),
url(r"^/comment/(?P<id>\d+)/delete$", views.delete_comment_view, name="board_delete_comment"),
url(r"^/post/(?P<id>\d+)/react$", views.react_post_view, name="board_react_post"),
]<|fim▁end|>
| |
<|file_name|>new_blog.rs<|end_file_name|><|fim▁begin|>// Common routines and constants for creating a new silica site
use ::logger::{log_err, log_info};
use std::fs::{self, File};
use std::io::Write;
use git2::Repository;
use cmdline::{CUR_CONFIG_NAME, SITE_EXISTS, NOT_SILICA_SITE};
use chrono::*;
use ::errors::*;
// Macro to check if we are in a valid silica site
// This must be used in a function with a Result as the return type
macro_rules! assert_valid_site {
() => ( match fs::metadata("./silica.toml") {
Ok(_) => true,
Err(_) => {
if let Ok(_) = fs::metadata("../silica.toml") {
true
} else {
println!("Hello");
bail!(NOT_SILICA_SITE);
}
}
}
)
}
macro_rules! join_str {
($a:expr, $b:expr) => ({
let mut a = "".to_owned();
a.push_str(&$a);
a.push_str(&$b);
a
});
}
pub fn exists_config(conf_path: &str) -> bool {
if let Ok(val) = fs::metadata(conf_path) {
return val.is_file();
}
false
}
pub fn exists_dir(dir_path: &str) -> bool {
if let Ok(val) = fs::metadata(dir_path) {
return val.is_dir();
}
false
}
pub fn populate_directories(base_dir: &str) {
let config_file = join_str!(base_dir, "/silica.toml");
let content_dir = join_str!(base_dir, "/content");
let static_dir = join_str!(base_dir, "/static");
let themes_dir = join_str!(base_dir, "/themes");
let posts_dir = join_str!(base_dir, "/content/posts");
let _ = fs::create_dir(&base_dir);
let _ = fs::create_dir(&static_dir);
let _ = fs::create_dir(&content_dir);
let _ = fs::create_dir(&themes_dir);
let _ = fs::create_dir(&posts_dir);<|fim▁hole|> match File::create(config_file) {
Ok(mut fd) => {
let _ = fd.write(b"# global config file\n\nname =\nauthor =\ntheme =\n[[social]]\ngithub =\nfacebook =\ntwitter =\n");
}
Err(why) => {
println!("{:?}", why);
}
}
}
pub fn create_new_site(site_name: &str) {
if exists_config(CUR_CONFIG_NAME) || exists_dir(site_name) {
return log_err(SITE_EXISTS);
}
let prefix = "./";
let base_dir = join_str!(prefix, site_name);
let repo = match Repository::init(&base_dir[..]) {
Ok(repo) => repo,
Err(e) => panic!("failed to init: {}", e),
};
log_info(&format!("Initialized empty Git repository in {}", base_dir));
populate_directories(&base_dir);
println!("\nHey, your new site is ready at: {}\n", base_dir);
}
pub fn create_new_post(post_name: &str, as_draft: bool) -> Result<()> {
assert_valid_site!();
let mut post_name = post_name.to_owned();
if !post_name.contains(".md") {
post_name.push_str(".md");
}
let post_name = "./content/posts/".to_owned() + &post_name;
let local_time: DateTime<Local> = Local::now();
let local_time = local_time.format("%a %b %e %T %Y").to_string();
let post_timestamp = "date = ".to_owned() + &local_time + "\n";
let post_metadata_end = "---\n";
let post_title = "title = ".to_owned() + &post_name + "\n";
let draft_flag = "draft = ".to_owned() + &as_draft.to_string() + "\n";
let f = File::create(&post_name[..]);
match f {
Ok(mut handle) => {
let _ = handle.write(post_timestamp.as_bytes());
let _ = handle.write(post_title.as_bytes());
let _ = handle.write(draft_flag.as_bytes());
let _ = handle.write_all(post_metadata_end.as_bytes());
log_info(&format!("\nCreated a post at: {}\n", post_name));
}
Err(_) => bail!("Error creating post")
}
Ok(())
}<|fim▁end|>
| |
<|file_name|>browser_host.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use browser::{self, ServoCefBrowserExtensions};
use eutil::Downcast;
use interfaces::{CefBrowser, CefBrowserHost, CefClient, cef_browser_t, cef_browser_host_t, cef_client_t};
use types::cef_event_flags_t::{EVENTFLAG_ALT_DOWN, EVENTFLAG_CONTROL_DOWN, EVENTFLAG_SHIFT_DOWN};
use types::cef_key_event_type_t::{KEYEVENT_CHAR, KEYEVENT_KEYDOWN, KEYEVENT_KEYUP, KEYEVENT_RAWKEYDOWN};
use types::{cef_mouse_button_type_t, cef_mouse_event, cef_rect_t, cef_key_event, cef_window_handle_t};
use wrappers::CefWrap;
use compositing::windowing::{WindowEvent, MouseWindowEvent};
use euclid::point::Point2D;
use euclid::size::Size2D;
use libc::{c_double, c_int};
use msg::constellation_msg::{self, KeyModifiers, KeyState, MouseButton};
use std::cell::{Cell, RefCell};
pub struct ServoCefBrowserHost {
/// A reference to the browser.
pub browser: RefCell<Option<CefBrowser>>,
/// A reference to the client.
pub client: CefClient,
/// flag for return value of prepare_for_composite
pub composite_ok: Cell<bool>,
}
// From blink ui/events/keycodes/keyboard_codes_posix.h.
#[allow(dead_code)]
#[allow(non_snake_case)]
mod KeyboardCode {
pub const VKEY_BACK : u8 = 0x08;
pub const VKEY_TAB : u8 = 0x09;
pub const VKEY_BACKTAB : u8 = 0x0A;
pub const VKEY_CLEAR : u8 = 0x0C;
pub const VKEY_RETURN : u8 = 0x0D;
pub const VKEY_SHIFT : u8 = 0x10;
pub const VKEY_CONTROL : u8 = 0x11;
pub const VKEY_MENU : u8 = 0x12;
pub const VKEY_PAUSE : u8 = 0x13;
pub const VKEY_CAPITAL : u8 = 0x14;
pub const VKEY_KANA : u8 = 0x15;
//VKEY_HANGUL = 0x15,
pub const VKEY_JUNJA : u8 = 0x17;
pub const VKEY_FINAL : u8 = 0x18;
pub const VKEY_HANJA : u8 = 0x19;
//VKEY_KANJI = 0x19,
pub const VKEY_ESCAPE : u8 = 0x1B;
pub const VKEY_CONVERT : u8 = 0x1C;
pub const VKEY_NONCONVERT : u8 = 0x1D;
pub const VKEY_ACCEPT : u8 = 0x1E;
pub const VKEY_MODECHANGE : u8 = 0x1F;
pub const VKEY_SPACE : u8 = 0x20;
pub const VKEY_PRIOR : u8 = 0x21;
pub const VKEY_NEXT : u8 = 0x22;
pub const VKEY_END : u8 = 0x23;
pub const VKEY_HOME : u8 = 0x24;
pub const VKEY_LEFT : u8 = 0x25;
pub const VKEY_UP : u8 = 0x26;
pub const VKEY_RIGHT : u8 = 0x27;
pub const VKEY_DOWN : u8 = 0x28;
pub const VKEY_SELECT : u8 = 0x29;
pub const VKEY_PRINT : u8 = 0x2A;
pub const VKEY_EXECUTE : u8 = 0x2B;
pub const VKEY_SNAPSHOT : u8 = 0x2C;
pub const VKEY_INSERT : u8 = 0x2D;
pub const VKEY_DELETE : u8 = 0x2E;
pub const VKEY_HELP : u8 = 0x2F;
pub const VKEY_0 : u8 = 0x30;
pub const VKEY_1 : u8 = 0x31;
pub const VKEY_2 : u8 = 0x32;
pub const VKEY_3 : u8 = 0x33;
pub const VKEY_4 : u8 = 0x34;
pub const VKEY_5 : u8 = 0x35;
pub const VKEY_6 : u8 = 0x36;
pub const VKEY_7 : u8 = 0x37;
pub const VKEY_8 : u8 = 0x38;
pub const VKEY_9 : u8 = 0x39;
pub const VKEY_A : u8 = 0x41;
pub const VKEY_B : u8 = 0x42;
pub const VKEY_C : u8 = 0x43;
pub const VKEY_D : u8 = 0x44;
pub const VKEY_E : u8 = 0x45;
pub const VKEY_F : u8 = 0x46;
pub const VKEY_G : u8 = 0x47;
pub const VKEY_H : u8 = 0x48;
pub const VKEY_I : u8 = 0x49;
pub const VKEY_J : u8 = 0x4A;
pub const VKEY_K : u8 = 0x4B;
pub const VKEY_L : u8 = 0x4C;
pub const VKEY_M : u8 = 0x4D;
pub const VKEY_N : u8 = 0x4E;
pub const VKEY_O : u8 = 0x4F;
pub const VKEY_P : u8 = 0x50;
pub const VKEY_Q : u8 = 0x51;
pub const VKEY_R : u8 = 0x52;
pub const VKEY_S : u8 = 0x53;
pub const VKEY_T : u8 = 0x54;
pub const VKEY_U : u8 = 0x55;
pub const VKEY_V : u8 = 0x56;
pub const VKEY_W : u8 = 0x57;
pub const VKEY_X : u8 = 0x58;
pub const VKEY_Y : u8 = 0x59;
pub const VKEY_Z : u8 = 0x5A;
pub const VKEY_LWIN : u8 = 0x5B;
pub const VKEY_RWIN : u8 = 0x5C;
pub const VKEY_APPS : u8 = 0x5D;
pub const VKEY_SLEEP : u8 = 0x5F;
pub const VKEY_NUMPAD0 : u8 = 0x60;
pub const VKEY_NUMPAD1 : u8 = 0x61;
pub const VKEY_NUMPAD2 : u8 = 0x62;
pub const VKEY_NUMPAD3 : u8 = 0x63;
pub const VKEY_NUMPAD4 : u8 = 0x64;
pub const VKEY_NUMPAD5 : u8 = 0x65;
pub const VKEY_NUMPAD6 : u8 = 0x66;
pub const VKEY_NUMPAD7 : u8 = 0x67;
pub const VKEY_NUMPAD8 : u8 = 0x68;
pub const VKEY_NUMPAD9 : u8 = 0x69;
pub const VKEY_MULTIPLY : u8 = 0x6A;
pub const VKEY_ADD : u8 = 0x6B;
pub const VKEY_SEPARATOR : u8 = 0x6C;
pub const VKEY_SUBTRACT : u8 = 0x6D;
pub const VKEY_DECIMAL : u8 = 0x6E;
pub const VKEY_DIVIDE : u8 = 0x6F;
pub const VKEY_F1 : u8 = 0x70;
pub const VKEY_F2 : u8 = 0x71;
pub const VKEY_F3 : u8 = 0x72;
pub const VKEY_F4 : u8 = 0x73;
pub const VKEY_F5 : u8 = 0x74;
pub const VKEY_F6 : u8 = 0x75;
pub const VKEY_F7 : u8 = 0x76;
pub const VKEY_F8 : u8 = 0x77;
pub const VKEY_F9 : u8 = 0x78;
pub const VKEY_F10 : u8 = 0x79;
pub const VKEY_F11 : u8 = 0x7A;
pub const VKEY_F12 : u8 = 0x7B;
pub const VKEY_F13 : u8 = 0x7C;
pub const VKEY_F14 : u8 = 0x7D;
pub const VKEY_F15 : u8 = 0x7E;
pub const VKEY_F16 : u8 = 0x7F;
pub const VKEY_F17 : u8 = 0x80;
pub const VKEY_F18 : u8 = 0x81;
pub const VKEY_F19 : u8 = 0x82;
pub const VKEY_F20 : u8 = 0x83;
pub const VKEY_F21 : u8 = 0x84;
pub const VKEY_F22 : u8 = 0x85;
pub const VKEY_F23 : u8 = 0x86;
pub const VKEY_F24 : u8 = 0x87;
pub const VKEY_NUMLOCK : u8 = 0x90;
pub const VKEY_SCROLL : u8 = 0x91;
pub const VKEY_LSHIFT : u8 = 0xA0;
pub const VKEY_RSHIFT : u8 = 0xA1;
pub const VKEY_LCONTROL : u8 = 0xA2;
pub const VKEY_RCONTROL : u8 = 0xA3;
pub const VKEY_LMENU : u8 = 0xA4;
pub const VKEY_RMENU : u8 = 0xA5;
pub const VKEY_BROWSER_BACK : u8 = 0xA6;
pub const VKEY_BROWSER_FORWARD : u8 = 0xA7;
pub const VKEY_BROWSER_REFRESH : u8 = 0xA8;
pub const VKEY_BROWSER_STOP : u8 = 0xA9;
pub const VKEY_BROWSER_SEARCH : u8 = 0xAA;
pub const VKEY_BROWSER_FAVORITES : u8 = 0xAB;
pub const VKEY_BROWSER_HOME : u8 = 0xAC;
pub const VKEY_VOLUME_MUTE : u8 = 0xAD;
pub const VKEY_VOLUME_DOWN : u8 = 0xAE;
pub const VKEY_VOLUME_UP : u8 = 0xAF;
pub const VKEY_MEDIA_NEXT_TRACK : u8 = 0xB0;
pub const VKEY_MEDIA_PREV_TRACK : u8 = 0xB1;
pub const VKEY_MEDIA_STOP : u8 = 0xB2;
pub const VKEY_MEDIA_PLAY_PAUSE : u8 = 0xB3;
pub const VKEY_MEDIA_LAUNCH_MAIL : u8 = 0xB4;
pub const VKEY_MEDIA_LAUNCH_MEDIA_SELECT : u8 = 0xB5;
pub const VKEY_MEDIA_LAUNCH_APP1 : u8 = 0xB6;
pub const VKEY_MEDIA_LAUNCH_APP2 : u8 = 0xB7;
pub const VKEY_OEM_1 : u8 = 0xBA;
pub const VKEY_OEM_PLUS : u8 = 0xBB;
pub const VKEY_OEM_COMMA : u8 = 0xBC;
pub const VKEY_OEM_MINUS : u8 = 0xBD;
pub const VKEY_OEM_PERIOD : u8 = 0xBE;
pub const VKEY_OEM_2 : u8 = 0xBF;
pub const VKEY_OEM_3 : u8 = 0xC0;
pub const VKEY_OEM_4 : u8 = 0xDB;
pub const VKEY_OEM_5 : u8 = 0xDC;
pub const VKEY_OEM_6 : u8 = 0xDD;
pub const VKEY_OEM_7 : u8 = 0xDE;
pub const VKEY_OEM_8 : u8 = 0xDF;
pub const VKEY_OEM_102 : u8 = 0xE2;
pub const VKEY_OEM_103 : u8 = 0xE3; // GTV KEYCODE_MEDIA_REWIND
pub const VKEY_OEM_104 : u8 = 0xE4; // GTV KEYCODE_MEDIA_FAST_FORWARD
pub const VKEY_PROCESSKEY : u8 = 0xE5;
pub const VKEY_PACKET : u8 = 0xE7;
pub const VKEY_DBE_SBCSCHAR : u8 = 0xF3;
pub const VKEY_DBE_DBCSCHAR : u8 = 0xF4;
pub const VKEY_ATTN : u8 = 0xF6;
pub const VKEY_CRSEL : u8 = 0xF7;
pub const VKEY_EXSEL : u8 = 0xF8;
pub const VKEY_EREOF : u8 = 0xF9;
pub const VKEY_PLAY : u8 = 0xFA;
pub const VKEY_ZOOM : u8 = 0xFB;
pub const VKEY_NONAME : u8 = 0xFC;
pub const VKEY_PA1 : u8 = 0xFD;
pub const VKEY_OEM_CLEAR : u8 = 0xFE;
pub const VKEY_UNKNOWN : u8 = 0x0;
// POSIX specific VKEYs. Note that as of Windows SDK 7.1, 0x97-9F, 0xD8-DA,
// and 0xE8 are unassigned.
pub const VKEY_WLAN : u8 = 0x97;
pub const VKEY_POWER : u8 = 0x98;
pub const VKEY_BRIGHTNESS_DOWN : u8 = 0xD8;
pub const VKEY_BRIGHTNESS_UP : u8 = 0xD9;
pub const VKEY_KBD_BRIGHTNESS_DOWN : u8 = 0xDA;
pub const VKEY_KBD_BRIGHTNESS_UP : u8 = 0xE8;
// Windows does not have a specific key code for AltGr. We use the unused 0xE1
// (VK_OEM_AX) code to represent AltGr, matching the behaviour of Firefox on
// Linux.
pub const VKEY_ALTGR : u8 = 0xE1;
// Windows does not have a specific key code for Compose. We use the unused
// 0xE6 (VK_ICO_CLEAR) code to represent Compose.
pub const VKEY_COMPOSE : u8 = 0xE6;
}
// this is way too much work to do 100% correctly right now.
// see xkb_keyboard_layout_engine.cc -> XkbKeyboardLayoutEngine::Lookup in chromium for details
fn get_key_msg(keycode: c_int, character: u16) -> Option<constellation_msg::Key> {
match keycode as u8 {
KeyboardCode::VKEY_BACK => Some(constellation_msg::Key::Backspace),
KeyboardCode::VKEY_RIGHT => Some(constellation_msg::Key::Right),
KeyboardCode::VKEY_LEFT => Some(constellation_msg::Key::Left),
KeyboardCode::VKEY_UP => Some(constellation_msg::Key::Up),
KeyboardCode::VKEY_DOWN => Some(constellation_msg::Key::Down),
KeyboardCode::VKEY_RSHIFT => Some(constellation_msg::Key::RightShift),
KeyboardCode::VKEY_SHIFT | KeyboardCode::VKEY_LSHIFT => Some(constellation_msg::Key::LeftShift),
KeyboardCode::VKEY_RCONTROL => Some(constellation_msg::Key::RightControl),
KeyboardCode::VKEY_CONTROL | KeyboardCode::VKEY_LCONTROL => Some(constellation_msg::Key::LeftControl),
KeyboardCode::VKEY_LWIN => Some(constellation_msg::Key::LeftSuper),
KeyboardCode::VKEY_RWIN => Some(constellation_msg::Key::RightSuper),
KeyboardCode::VKEY_MENU => Some(constellation_msg::Key::LeftAlt),
KeyboardCode::VKEY_APPS => Some(constellation_msg::Key::Menu),
KeyboardCode::VKEY_ALTGR => Some(constellation_msg::Key::RightAlt), //not sure if correct...
KeyboardCode::VKEY_ESCAPE => Some(constellation_msg::Key::Escape),
KeyboardCode::VKEY_INSERT => Some(constellation_msg::Key::Insert),
KeyboardCode::VKEY_DELETE => Some(constellation_msg::Key::Delete),
KeyboardCode::VKEY_NEXT => Some(constellation_msg::Key::PageUp),
KeyboardCode::VKEY_PRIOR => Some(constellation_msg::Key::PageDown),
KeyboardCode::VKEY_HOME => Some(constellation_msg::Key::Home),
KeyboardCode::VKEY_END => Some(constellation_msg::Key::End),
KeyboardCode::VKEY_CAPITAL => Some(constellation_msg::Key::CapsLock),
KeyboardCode::VKEY_F1 => Some(constellation_msg::Key::F1),
KeyboardCode::VKEY_F2 => Some(constellation_msg::Key::F2),
KeyboardCode::VKEY_F3 => Some(constellation_msg::Key::F3),
KeyboardCode::VKEY_F4 => Some(constellation_msg::Key::F4),
KeyboardCode::VKEY_F5 => Some(constellation_msg::Key::F5),
KeyboardCode::VKEY_F6 => Some(constellation_msg::Key::F6),
KeyboardCode::VKEY_F7 => Some(constellation_msg::Key::F7),
KeyboardCode::VKEY_F8 => Some(constellation_msg::Key::F8),
KeyboardCode::VKEY_F9 => Some(constellation_msg::Key::F9),
KeyboardCode::VKEY_F10 => Some(constellation_msg::Key::F10),
KeyboardCode::VKEY_F11 => Some(constellation_msg::Key::F11),
KeyboardCode::VKEY_F12 => Some(constellation_msg::Key::F12),
KeyboardCode::VKEY_F13 => Some(constellation_msg::Key::F13),
KeyboardCode::VKEY_F14 => Some(constellation_msg::Key::F14),
KeyboardCode::VKEY_F15 => Some(constellation_msg::Key::F15),
KeyboardCode::VKEY_F16 => Some(constellation_msg::Key::F16),
KeyboardCode::VKEY_F17 => Some(constellation_msg::Key::F17),
KeyboardCode::VKEY_F18 => Some(constellation_msg::Key::F18),
KeyboardCode::VKEY_F19 => Some(constellation_msg::Key::F19),
KeyboardCode::VKEY_F20 => Some(constellation_msg::Key::F20),
KeyboardCode::VKEY_F21 => Some(constellation_msg::Key::F21),
KeyboardCode::VKEY_F22 => Some(constellation_msg::Key::F22),
KeyboardCode::VKEY_F23 => Some(constellation_msg::Key::F23),
KeyboardCode::VKEY_F24 => Some(constellation_msg::Key::F24),
KeyboardCode::VKEY_NUMPAD0 => Some(constellation_msg::Key::Kp0),
KeyboardCode::VKEY_NUMPAD1 => Some(constellation_msg::Key::Kp1),
KeyboardCode::VKEY_NUMPAD2 => Some(constellation_msg::Key::Kp2),
KeyboardCode::VKEY_NUMPAD3 => Some(constellation_msg::Key::Kp3),
KeyboardCode::VKEY_NUMPAD4 => Some(constellation_msg::Key::Kp4),
KeyboardCode::VKEY_NUMPAD5 => Some(constellation_msg::Key::Kp5),
KeyboardCode::VKEY_NUMPAD6 => Some(constellation_msg::Key::Kp6),
KeyboardCode::VKEY_NUMPAD7 => Some(constellation_msg::Key::Kp7),
KeyboardCode::VKEY_NUMPAD8 => Some(constellation_msg::Key::Kp8),
KeyboardCode::VKEY_NUMPAD9 => Some(constellation_msg::Key::Kp9),
KeyboardCode::VKEY_DECIMAL => Some(constellation_msg::Key::KpDecimal),
KeyboardCode::VKEY_DIVIDE => Some(constellation_msg::Key::KpDivide),
KeyboardCode::VKEY_MULTIPLY => Some(constellation_msg::Key::KpMultiply),
KeyboardCode::VKEY_SUBTRACT => Some(constellation_msg::Key::KpSubtract),
KeyboardCode::VKEY_ADD => Some(constellation_msg::Key::KpAdd),
KeyboardCode::VKEY_NUMLOCK => Some(constellation_msg::Key::NumLock),
KeyboardCode::VKEY_PRINT => Some(constellation_msg::Key::PrintScreen),
KeyboardCode::VKEY_PAUSE => Some(constellation_msg::Key::Pause),
//VKEY_BACK
_ => { match character as u8 {
b'[' => Some(constellation_msg::Key::LeftBracket),
b']' => Some(constellation_msg::Key::RightBracket),
b'=' => Some(constellation_msg::Key::Equal),
b';' => Some(constellation_msg::Key::Semicolon),
b'/' => Some(constellation_msg::Key::Slash),
b'.' => Some(constellation_msg::Key::Period),
b'-' => Some(constellation_msg::Key::Minus),
b',' => Some(constellation_msg::Key::Comma),
b'\'' => Some(constellation_msg::Key::Apostrophe),
b'\\' => Some(constellation_msg::Key::Backslash),
b'`' => Some(constellation_msg::Key::GraveAccent),
b'\t' => Some(constellation_msg::Key::Tab),
b'a' | b'A' => Some(constellation_msg::Key::A),
b'b' | b'B' => Some(constellation_msg::Key::B),
b'c' | b'C' => Some(constellation_msg::Key::C),
b'd' | b'D' => Some(constellation_msg::Key::D),
b'e' | b'E' => Some(constellation_msg::Key::E),
b'f' | b'F' => Some(constellation_msg::Key::F),
b'g' | b'G' => Some(constellation_msg::Key::G),
b'h' | b'H' => Some(constellation_msg::Key::H),
b'i' | b'I' => Some(constellation_msg::Key::I),
b'j' | b'J' => Some(constellation_msg::Key::J),
b'k' | b'K' => Some(constellation_msg::Key::K),
b'l' | b'L' => Some(constellation_msg::Key::L),
b'm' | b'M' => Some(constellation_msg::Key::M),
b'n' | b'N' => Some(constellation_msg::Key::N),
b'o' | b'O' => Some(constellation_msg::Key::O),
b'p' | b'P' => Some(constellation_msg::Key::P),
b'q' | b'Q' => Some(constellation_msg::Key::Q),
b'r' | b'R' => Some(constellation_msg::Key::R),
b's' | b'S' => Some(constellation_msg::Key::S),
b't' | b'T' => Some(constellation_msg::Key::T),
b'u' | b'U' => Some(constellation_msg::Key::U),
b'v' | b'V' => Some(constellation_msg::Key::V),
b'w' | b'W' => Some(constellation_msg::Key::W),
b'x' | b'X' => Some(constellation_msg::Key::X),
b'y' | b'Y' => Some(constellation_msg::Key::Y),
b'z' | b'Z' => Some(constellation_msg::Key::Z),
b'0' => Some(constellation_msg::Key::Num0),
b'1' => Some(constellation_msg::Key::Num1),
b'2' => Some(constellation_msg::Key::Num2),
b'3' => Some(constellation_msg::Key::Num3),
b'4' => Some(constellation_msg::Key::Num4),
b'5' => Some(constellation_msg::Key::Num5),
b'6' => Some(constellation_msg::Key::Num6),
b'7' => Some(constellation_msg::Key::Num7),
b'8' => Some(constellation_msg::Key::Num8),
b'9' => Some(constellation_msg::Key::Num9),
b'\n' | b'\r' => Some(constellation_msg::Key::Enter),
b' ' => Some(constellation_msg::Key::Space),
_ => None
}
}
}
}
// unhandled
//pub enum Key {
//World1,
//World2,
//ScrollLock,
//KpEnter,
//KpEqual,
//RightAlt,
//}
full_cef_class_impl! {
ServoCefBrowserHost : CefBrowserHost, cef_browser_host_t {
fn get_client(&this,) -> *mut cef_client_t {{
this.downcast().client.clone()
}}
fn get_browser(&this,) -> *mut cef_browser_t {{
let browser = this.downcast().browser.borrow_mut();
browser.clone().unwrap()
}}
fn was_resized(&this,) -> () {{
let mut rect = cef_rect_t::zero();
if cfg!(target_os="macos") {
if check_ptr_exist!(this.get_client(), get_render_handler) &&
check_ptr_exist!(this.get_client().get_render_handler(), get_backing_rect) {
this.get_client()
.get_render_handler()
.get_backing_rect(this.downcast().browser.borrow().clone().unwrap(), &mut rect);
}
} else if check_ptr_exist!(this.get_client(), get_render_handler) &&
check_ptr_exist!(this.get_client().get_render_handler(), get_view_rect) {
this.get_client()
.get_render_handler()
.get_view_rect(this.downcast().browser.borrow().clone().unwrap(), &mut rect);
}
let size = Size2D::typed(rect.width as u32, rect.height as u32);
this.downcast().send_window_event(WindowEvent::Resize(size));
}}
fn close_browser(&this, _force: c_int [c_int],) -> () {{
browser::close(this.downcast().browser.borrow_mut().take().unwrap());
}}
fn send_focus_event(&this, focus: c_int [c_int],) -> () {{
let focus: c_int = focus;
if focus != 0 {
this.downcast().send_window_event(WindowEvent::Refresh);
}
}}
fn send_key_event(&this, event: *const cef_key_event [&cef_key_event],) -> () {{
let event: &cef_key_event = event;
let key = match get_key_msg((*event).windows_key_code, (*event).character) {
Some(keycode) => keycode,
None => {
error!("Unhandled keycode({}) passed!", (*event).windows_key_code);
return;
}
};
let key_state = match (*event).t {
// in tests with cef-real, this event had no effect
KEYEVENT_RAWKEYDOWN => return,
KEYEVENT_KEYDOWN => KeyState::Pressed,
KEYEVENT_CHAR => KeyState::Repeated,
KEYEVENT_KEYUP => KeyState::Released,
};
let mut key_modifiers = KeyModifiers::empty();
if (*event).modifiers & EVENTFLAG_SHIFT_DOWN as u32 != 0 {
key_modifiers = key_modifiers | constellation_msg::SHIFT;
}
if (*event).modifiers & EVENTFLAG_CONTROL_DOWN as u32 != 0 {
key_modifiers = key_modifiers | constellation_msg::CONTROL;
}
if (*event).modifiers & EVENTFLAG_ALT_DOWN as u32 != 0 {
key_modifiers = key_modifiers | constellation_msg::ALT;
}
this.downcast().send_window_event(WindowEvent::KeyEvent(key, key_state, key_modifiers))
}}
fn send_mouse_click_event(&this,
event: *const cef_mouse_event [&cef_mouse_event],
mouse_button_type: cef_mouse_button_type_t [cef_mouse_button_type_t],
mouse_up: c_int [c_int],
_click_count: c_int [c_int],)
-> () {{
let event: &cef_mouse_event = event;
let mouse_button_type: cef_mouse_button_type_t = mouse_button_type;
let mouse_up: c_int = mouse_up;
let button_type = match mouse_button_type {
cef_mouse_button_type_t::MBT_LEFT => MouseButton::Left,
cef_mouse_button_type_t::MBT_MIDDLE => MouseButton::Middle,
cef_mouse_button_type_t::MBT_RIGHT => MouseButton::Right,
};
let point = Point2D::typed((*event).x as f32, (*event).y as f32);
if mouse_up != 0 {
this.downcast().send_window_event(WindowEvent::MouseWindowEventClass(
MouseWindowEvent::Click(button_type, point)))
} else {
this.downcast().send_window_event(WindowEvent::MouseWindowEventClass(
MouseWindowEvent::MouseUp(button_type, point)))
}
}}
fn send_mouse_move_event(&this, event: *const cef_mouse_event [&cef_mouse_event],
_mouse_exited: c_int [c_int],)
-> () {{
let event: &cef_mouse_event = event;
let point = Point2D::typed((*event).x as f32, (*event).y as f32);
this.downcast().send_window_event(WindowEvent::MouseWindowMoveEventClass(point))
}}
fn send_mouse_wheel_event(&this,
event: *const cef_mouse_event [&cef_mouse_event],
delta_x: c_int [c_int],
delta_y: c_int [c_int],)
-> () {{
let event: &cef_mouse_event = event;
let delta_x: c_int = delta_x;
let delta_y: c_int = delta_y;
let delta = Point2D::typed(delta_x as f32, delta_y as f32);
let origin = Point2D::typed((*event).x as i32, (*event).y as i32);
this.downcast().send_window_event(WindowEvent::Scroll(delta, origin))
}}
fn get_zoom_level(&this,) -> c_double {{
this.downcast().pinch_zoom_level() as c_double
}}
fn set_zoom_level(&this, new_zoom_level: c_double [c_double],) -> () {{
let new_zoom_level: c_double = new_zoom_level;
let old_zoom_level = this.get_zoom_level();
this.downcast().send_window_event(WindowEvent::PinchZoom((new_zoom_level / old_zoom_level) as f32))
}}
fn initialize_compositing(&this,) -> () {{
this.downcast().send_window_event(WindowEvent::InitializeCompositing);
}}
fn composite(&this,) -> () {{
this.downcast().composite_ok.set(true);
this.downcast().send_window_event(WindowEvent::Refresh);
this.downcast().composite_ok.set(false);
}}
fn get_window_handle(&this,) -> cef_window_handle_t {{
let t = this.downcast();<|fim▁hole|> let browser = t.browser.borrow();
browser::get_window(&browser.as_ref().unwrap()) as cef_window_handle_t
}}
}
}
impl ServoCefBrowserHost {
pub fn new(client: CefClient) -> ServoCefBrowserHost {
ServoCefBrowserHost {
browser: RefCell::new(None),
client: client,
composite_ok: Cell::new(false),
}
}
fn send_window_event(&self, event: WindowEvent) {
self.browser.borrow_mut().as_mut().unwrap().send_window_event(event);
}
fn pinch_zoom_level(&self) -> f32 {
self.browser.borrow_mut().as_mut().unwrap().pinch_zoom_level()
}
}
pub trait ServoCefBrowserHostExtensions {
fn set_browser(&self, browser: CefBrowser);
}
impl ServoCefBrowserHostExtensions for CefBrowserHost {
fn set_browser(&self, browser: CefBrowser) {
*self.downcast().browser.borrow_mut() = Some(browser)
}
}<|fim▁end|>
| |
<|file_name|>suffix.js<|end_file_name|><|fim▁begin|>// support CommonJS, AMD & browser
/* istanbul ignore next */<|fim▁hole|> define(function() { return (window.riot = riot) })
else
window.riot = riot
})(typeof window != 'undefined' ? window : void 0);<|fim▁end|>
|
if (typeof exports === T_OBJECT)
module.exports = riot
else if (typeof define === 'function' && define.amd)
|
<|file_name|>process_data.py<|end_file_name|><|fim▁begin|>import cPickle
import numpy as np
import sys
from collections import OrderedDict
def format_chars(chars_sent_ls):
max_leng = max([len(l) for l in chars_sent_ls])
to_pads = [max_leng - len(l) for l in chars_sent_ls]
for i, to_pad in enumerate(to_pads):
if to_pad % 2 == 0:
chars_sent_ls[i] = [0] * (to_pad / 2) + chars_sent_ls[i] + [0] * (to_pad / 2)
else:
chars_sent_ls[i] = [0] * (1 + (to_pad / 2)) + chars_sent_ls[i] + [0] * (to_pad / 2)
return chars_sent_ls
def load_bin_vec(fname, vocab):
"""
Loads word vecs from word2vec bin file
"""
word_vecs = OrderedDict()
with open(fname, "rb") as f:
header = f.readline()
vocab_size, layer1_size = map(int, header.split())
binary_len = np.dtype('float32').itemsize * layer1_size
for line in xrange(vocab_size):
word = []
while True:
ch = f.read(1)
if ch == ' ':
word = ''.join(word)
break
if ch != '\n':
word.append(ch)
if word in vocab:
idx = vocab[word]
word_vecs[idx] = np.fromstring(f.read(binary_len), dtype='float32')
else:
f.read(binary_len)
return word_vecs
def add_unknown_words(word_vecs, vocab, min_df=1, k=200):<|fim▁hole|> 0.25 is chosen so the unknown vectors have (approximately) same variance as pre-trained ones
"""
for word in vocab:
if word not in word_vecs:
idx = vocab[word]
word_vecs[idx] = np.random.uniform(-0.25,0.25,k)
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def is_user(s):
if len(s)>1 and s[0] == "@":
return True
else:
return False
def is_url(s):
if len(s)>4 and s[:5] == "http:":
return True
else:
return False
def digits(n):
digit_str = ''
for i in range(n):
digit_str = digit_str + 'DIGIT'
return digit_str
def establishdic(fname, gname, hname, binfile):
data = open(fname, "rb").readlines() + open(gname, "rb").readlines() + open(hname, "rb").readlines()
char_dict = OrderedDict()
vocab_dict = OrderedDict()
tag_dict = OrderedDict()
char_count = 0
vocab_count = 0
tag_count = 0
for line in data:
line = line.replace('\n', '').replace('\r', '')
line = line.split("\t")
if line == ['', ''] or line == [''] or line[0].isdigit() != True:
continue
vocab = line[1]
tag = line[3]
if is_number(vocab): # check if the term is a number
vocab = digits(len(vocab))
if is_url(vocab):
vocab = "URL"
if is_user(vocab):
vocab = "USR"
if vocab not in vocab_dict:
vocab_dict[vocab] = vocab_count
vocab_count += 1
if tag not in tag_dict:
tag_dict[tag] = tag_count
tag_count += 1
# generate char dictionary
chars = list(vocab)
for char in chars:
if char not in char_dict:
char_dict[char] = char_count
char_count += 1
pos_dictionary = OrderedDict()
pos_dictionary['words2idx'] = vocab_dict
pos_dictionary['labels2idx'] = tag_dict
pos_dictionary['chars2idx'] = char_dict
wordvec_dict = load_bin_vec(binfile, vocab_dict)
add_unknown_words(wordvec_dict, vocab_dict)
pos_dictionary['idx2vec'] = wordvec_dict
return pos_dictionary
def sepdata(fname, gname, hname, pos_dictionary):
vocab_dict = pos_dictionary['words2idx']
tag_dict = pos_dictionary['labels2idx']
char_dict = pos_dictionary['chars2idx']
# of all sets
dataset_words = []
dataset_labels = []
dataset_chars = []
for f in [fname, gname, hname]:
data = open(f, "rb").readlines()
# of a whole set
words_set = []
tag_labels_set = []
chars_set = []
# of a whole sentence
example_words = []
example_tag_labels = []
example_char = []
count = 0
for line in data:
line = line.replace('\n', '').replace('\r', '')
line = line.split("\t")
if (not line[0].isdigit()) and (line != ['']):
continue # this is the heading line
# this means a example finishes
if (line == ['', ''] or line == ['']) and (len(example_words) > 0):
words_set.append(np.array(example_words, dtype = "int32"))
tag_labels_set.append(np.array(example_tag_labels, dtype = "int32"))
chars_set.append(np.array(example_char, dtype = "int32"))
# restart a new example after one finishes
example_words = []
example_tag_labels = []
example_char = []
count += 1
else: # part of an example
vocab = line[1]
tag = line[3]
if is_number(vocab): # check if the term is a number
vocab = digits(len(vocab))
if is_url(vocab):
vocab = "URL"
if is_user(vocab):
vocab = "USR"
example_words.append(vocab_dict[vocab])
example_tag_labels.append(tag_dict[tag])
char_word_list = map(lambda u: char_dict[u], list(vocab))
example_char.append(char_word_list)
example_char = format_chars(example_char)
# for each example do a padding
dataset_words.append(words_set)
dataset_labels.append(tag_labels_set)
dataset_chars.append(chars_set)
train_pos= [dataset_words[0], dataset_chars[0], dataset_labels[0]]
valid_pos = [dataset_words[1], dataset_chars[1], dataset_labels[1]]
test_pos = [dataset_words[2], dataset_chars[2], dataset_labels[2]]
assert len(dataset_words[0]+dataset_words[1]+dataset_words[2]) == len(train_pos[0]) + len(valid_pos[0]) + len(test_pos[0])
return train_pos, valid_pos, test_pos
def main():
if len(sys.argv) != 6:
sys.exit("file paths not specified")
binfile = sys.argv[1]
fname = sys.argv[2] # train file
gname = sys.argv[3] # validation file
hname = sys.argv[4] # test file
outfilename = sys.argv[5]
pos_dictionary = establishdic(fname, gname, hname, binfile)
train_pos, valid_pos, test_pos = sepdata(fname, gname, hname, pos_dictionary)
print "train pos examples", len(train_pos[0])
print "valid pos examples", len(valid_pos[0])
print "test pos examples", len(test_pos[0])
with open(outfilename + ".pkl", "wb") as f:
cPickle.dump([train_pos, valid_pos, test_pos, pos_dictionary], f)
print "data %s is generated." % (outfilename + ".pkl")
if __name__ == '__main__':
main()<|fim▁end|>
|
"""
For words that occur in at least min_df documents, create a separate word vector.
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># --------------------------------------------------------
# TensorFlow for Dragon<|fim▁hole|># Copyright(c) 2017 SeetaTech
# Written by Ting Pan
# --------------------------------------------------------<|fim▁end|>
| |
<|file_name|>config.py<|end_file_name|><|fim▁begin|># Author: Drone
import web
from app.helpers import utils
from app.helpers import formatting
projectName = 'Remote Function Trainer'
listLimit = 40
# connect to database
db = web.database(dbn='mysql', db='rft', user='root', passwd='1234')
t = db.transaction()
#t.commit()
# in development debug error messages and reloader
web.config.debug = False
# in develpment template caching is set to false
cache = False
<|fim▁hole|>
# set global base template
view = web.template.render('app/views', cache=cache, globals=globals)
# in production the internal errors are emailed to us
web.config.email_errors = ''<|fim▁end|>
|
# template global functions
globals = utils.get_all_functions(formatting)
|
<|file_name|>tenants_test.go<|end_file_name|><|fim▁begin|>// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache License, Version 2.0 (the "License").
// You may not use this product except in compliance with the License.
//
// This product may include a number of subcomponents with separate copyright notices and
// license terms. Your use of these subcomponents is subject to the terms and conditions
// of the subcomponent's license, as noted in the LICENSE file.
package photon
import (
"fmt"
"reflect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/vmware/photon-controller-go-sdk/photon/internal/mocks"
)
var _ = Describe("Tenant", func() {
var (
server *mocks.Server
client *Client
tenantID string
)
BeforeEach(func() {
server, client = testSetup()
})
AfterEach(func() {
cleanTenants(client)
server.Close()
})
Describe("CreateAndDeleteTenant", func() {
It("Tenant create and delete succeeds", func() {
mockTask := createMockTask("CREATE_TENANT", "COMPLETED")
server.SetResponseJson(200, mockTask)
tenantSpec := &TenantCreateSpec{Name: randomString(10, "go-sdk-tenant-")}
task, err := client.Tenants.Create(tenantSpec)
task, err = client.Tasks.Wait(task.ID)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(task.Operation).Should(Equal("CREATE_TENANT"))
Expect(task.State).Should(Equal("COMPLETED"))
mockTask = createMockTask("DELETE_TENANT", "COMPLETED")
server.SetResponseJson(200, mockTask)
task, err = client.Tenants.Delete(task.Entity.ID)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(task.Operation).Should(Equal("DELETE_TENANT"))
Expect(task.State).Should(Equal("COMPLETED"))
})
It("Tenant create fails", func() {
tenantSpec := &TenantCreateSpec{}
task, err := client.Tenants.Create(tenantSpec)
server.SetResponseJson(200, createMockTenantsPage())
Expect(err).ShouldNot(BeNil())
Expect(task).Should(BeNil())
})
It("creates and deletes a tenant with security groups specified", func() {
// Create a tenant with security groups.
mockTask := createMockTask("CREATE_TENANT", "COMPLETED")
server.SetResponseJson(200, mockTask)
securityGroups := []string{randomString(10), randomString(10)}
expected := &Tenant{
SecurityGroups: []SecurityGroup{
{securityGroups[0], false},
{securityGroups[1], false},
},
}
tenantSpec := &TenantCreateSpec{
Name: randomString(10, "go-sdk-tenant-"),
SecurityGroups: securityGroups,
}
task, err := client.Tenants.Create(tenantSpec)
Expect(task).ShouldNot(BeNil())
Expect(err).Should(BeNil())
task, err = client.Tasks.Wait(task.ID)
Expect(task).ShouldNot(BeNil())
Expect(err).Should(BeNil())
Expect(task.Operation).Should(Equal("CREATE_TENANT"))
Expect(task.State).Should(Equal("COMPLETED"))
tenantId := task.Entity.ID
// Verify that the tenant has the security groups set properly.
server.SetResponseJson(200, expected)
tenant, err := client.Tenants.Get(tenantId)
Expect(err).Should(BeNil())
Expect(tenant.SecurityGroups).Should(Equal(expected.SecurityGroups))
// Delete the tenant.
mockTask = createMockTask("DELETE_TENANT", "COMPLETED")
server.SetResponseJson(200, mockTask)
task, err = client.Tenants.Delete(tenantId)
Expect(task).ShouldNot(BeNil())
Expect(err).Should(BeNil())
Expect(task.Operation).Should(Equal("DELETE_TENANT"))
Expect(task.State).Should(Equal("COMPLETED"))
})
})
Describe("GetTenant", func() {
It("Get returns a tenant ID", func() {
mockTask := createMockTask("CREATE_TENANT", "COMPLETED")
server.SetResponseJson(200, mockTask)
tenantName := randomString(10, "go-sdk-tenant-")
tenantSpec := &TenantCreateSpec{Name: tenantName}
task, err := client.Tenants.Create(tenantSpec)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(task.Operation).Should(Equal("CREATE_TENANT"))
Expect(task.State).Should(Equal("COMPLETED"))
mockTenantsPage := createMockTenantsPage(Tenant{Name: tenantName})
server.SetResponseJson(200, mockTenantsPage)
tenants, err := client.Tenants.GetAll()
mockTenantPage := createMockTenantPage()
server.SetResponseJson(200, mockTenantPage)
mockTenant, err := client.Tenants.Get("TestTenant")
Expect(mockTenant.Name).Should(Equal("TestTenant"))
Expect(mockTenant.ID).Should(Equal("12345"))
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(tenants).ShouldNot(BeNil())
var found bool
for _, tenant := range tenants.Items {
if tenant.Name == tenantName && tenant.ID == task.Entity.ID {
found = true
break
}
}
Expect(found).Should(BeTrue())
mockTask = createMockTask("DELETE_TENANT", "COMPLETED")
server.SetResponseJson(200, mockTask)
_, err = client.Tenants.Delete(task.Entity.ID)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
})
})
Describe("GetTenantTasks", func() {
var (
option string
)
Context("no extra options for GetTask", func() {
BeforeEach(func() {
option = ""
})
It("GetTasks returns a completed task", func() {
mockTask := createMockTask("CREATE_TENANT", "COMPLETED")
mockTask.Entity.ID = "mock-task-id"
server.SetResponseJson(200, mockTask)
tenantSpec := &TenantCreateSpec{Name: randomString(10, "go-sdk-tenant-")}
task, err := client.Tenants.Create(tenantSpec)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(task.Operation).Should(Equal("CREATE_TENANT"))
Expect(task.State).Should(Equal("COMPLETED"))
mockTasksPage := createMockTasksPage(*mockTask)
server.SetResponseJson(200, mockTasksPage)
taskList, err := client.Tenants.GetTasks(task.Entity.ID, &TaskGetOptions{State: option})
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(taskList).ShouldNot(BeNil())
Expect(taskList.Items).Should(ContainElement(*task))
mockTask = createMockTask("DELETE_TENANT", "COMPLETED")
server.SetResponseJson(200, mockTask)
_, err = client.Tenants.Delete(task.Entity.ID)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
})
})
Context("Searching COMPLETED state for GetTask", func() {
BeforeEach(func() {
option = "COMPLETED"
})
It("GetTasks returns a completed task", func() {
mockTask := createMockTask("CREATE_TENANT", "COMPLETED")
mockTask.Entity.ID = "mock-task-id"
server.SetResponseJson(200, mockTask)
tenantSpec := &TenantCreateSpec{Name: randomString(10, "go-sdk-tenant-")}
task, err := client.Tenants.Create(tenantSpec)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(task.Operation).Should(Equal("CREATE_TENANT"))
Expect(task.State).Should(Equal("COMPLETED"))
mockTasksPage := createMockTasksPage(*mockTask)
server.SetResponseJson(200, mockTasksPage)
taskList, err := client.Tenants.GetTasks(task.Entity.ID, &TaskGetOptions{State: option})
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(taskList).ShouldNot(BeNil())
Expect(taskList.Items).Should(ContainElement(*task))
mockTask = createMockTask("DELETE_TENANT", "COMPLETED")
server.SetResponseJson(200, mockTask)
_, err = client.Tenants.Delete(task.Entity.ID)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
})
})
})
Describe("TenantQuota", func() {
It("Get Tenant Quota succeeds", func() {
mockQuota := createMockQuota()
// Create Tenant
tenantID = createTenant(server, client)
// Get current Quota
server.SetResponseJson(200, mockQuota)
quota, err := client.Tenants.GetQuota(tenantID)
GinkgoT().Log(err)
eq := reflect.DeepEqual(quota.QuotaLineItems, mockQuota.QuotaLineItems)
Expect(eq).Should(Equal(true))
})
It("Set Tenant Quota succeeds", func() {
mockQuotaSpec := &QuotaSpec{
"vmCpu": {Unit: "COUNT", Limit: 10, Usage: 0},
"vmMemory": {Unit: "GB", Limit: 18, Usage: 0},
"diskCapacity": {Unit: "GB", Limit: 100, Usage: 0},
}
// Create Tenant
tenantID = createTenant(server, client)
mockTask := createMockTask("SET_QUOTA", "COMPLETED")
server.SetResponseJson(200, mockTask)
task, err := client.Tenants.SetQuota(tenantID, mockQuotaSpec)
task, err = client.Tasks.Wait(task.ID)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(task.Operation).Should(Equal("SET_QUOTA"))
Expect(task.State).Should(Equal("COMPLETED"))
})
It("Update Tenant Quota succeeds", func() {
mockQuotaSpec := &QuotaSpec{
"vmCpu": {Unit: "COUNT", Limit: 30, Usage: 0},
"vmMemory": {Unit: "GB", Limit: 40, Usage: 0},
"diskCapacity": {Unit: "GB", Limit: 150, Usage: 0},
}
// Create Tenant
tenantID = createTenant(server, client)
mockTask := createMockTask("UPDATE_QUOTA", "COMPLETED")
server.SetResponseJson(200, mockTask)
task, err := client.Tenants.UpdateQuota(tenantID, mockQuotaSpec)
task, err = client.Tasks.Wait(task.ID)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(task.Operation).Should(Equal("UPDATE_QUOTA"))
Expect(task.State).Should(Equal("COMPLETED"))
})
It("Exclude Tenant Quota Items succeeds", func() {
mockQuotaSpec := &QuotaSpec{
"vmCpu2": {Unit: "COUNT", Limit: 10, Usage: 0},
"vmMemory3": {Unit: "GB", Limit: 18, Usage: 0},
}
// Create Tenant
tenantID = createTenant(server, client)
mockTask := createMockTask("DELETE_QUOTA", "COMPLETED")
server.SetResponseJson(200, mockTask)
task, err := client.Tenants.ExcludeQuota(tenantID, mockQuotaSpec)
task, err = client.Tasks.Wait(task.ID)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(task.Operation).Should(Equal("DELETE_QUOTA"))
Expect(task.State).Should(Equal("COMPLETED"))
})
})
})
var _ = Describe("Project", func() {
var (
server *mocks.Server
client *Client
tenantID string
)
BeforeEach(func() {
server, client = testSetup()
tenantID = createTenant(server, client)
})
AfterEach(func() {
cleanTenants(client)
server.Close()
})
Describe("CreateGetAndDeleteProject", func() {
It("Project create and delete succeeds", func() {
mockTask := createMockTask("CREATE_PROJECT", "COMPLETED")
server.SetResponseJson(200, mockTask)
projSpec := &ProjectCreateSpec{
Name: randomString(10, "go-sdk-project-"),
}
task, err := client.Tenants.CreateProject(tenantID, projSpec)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(task.Operation).Should(Equal("CREATE_PROJECT"))
Expect(task.State).Should(Equal("COMPLETED"))
mockProjects := createMockProjectsPage(ProjectCompact{Name: projSpec.Name})
server.SetResponseJson(200, mockProjects)
projList, err := client.Tenants.GetProjects(tenantID, &ProjectGetOptions{})
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(projList).ShouldNot(BeNil())
var found bool
for _, proj := range projList.Items {
if proj.Name == projSpec.Name && proj.ID == task.Entity.ID {
found = true
break
}
}
Expect(found).Should(BeTrue())
mockTask = createMockTask("DELETE_PROJECT", "COMPLETED")
server.SetResponseJson(200, mockTask)
task, err = client.Projects.Delete(task.Entity.ID)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(task.Operation).Should(Equal("DELETE_PROJECT"))
Expect(task.State).Should(Equal("COMPLETED"))
})
})
Describe("SecurityGroups", func() {
It("sets security groups for a tenant", func() {
// Create a tenant
mockTask := createMockTask("CREATE_TENANT", "COMPLETED")
server.SetResponseJson(200, mockTask)
tenantSpec := &TenantCreateSpec{Name: randomString(10, "go-sdk-tenant-")}
task, err := client.Tenants.Create(tenantSpec)
task, err = client.Tasks.Wait(task.ID)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(task.Operation).Should(Equal("CREATE_TENANT"))
Expect(task.State).Should(Equal("COMPLETED"))
// Set security groups for the tenant
expected := &Tenant{
SecurityGroups: []SecurityGroup{
{randomString(10), false},
{randomString(10), false},
},
}
mockTask = createMockTask("SET_TENANT_SECURITY_GROUPS", "COMPLETED")
server.SetResponseJson(200, mockTask)
securityGroups := &SecurityGroupsSpec{
[]string{expected.SecurityGroups[0].Name, expected.SecurityGroups[1].Name},
}
createTask, err := client.Tenants.SetSecurityGroups(task.Entity.ID, securityGroups)
createTask, err = client.Tasks.Wait(createTask.ID)
Expect(err).Should(BeNil())
// Get the security groups for the tenant
server.SetResponseJson(200, expected)
tenant, err := client.Tenants.Get(task.Entity.ID)
Expect(err).Should(BeNil())
fmt.Fprintf(GinkgoWriter, "Got tenant: %+v", tenant)
Expect(expected.SecurityGroups).Should(Equal(tenant.SecurityGroups))
// Delete the tenant
mockTask = createMockTask("DELETE_TENANT", "COMPLETED")
server.SetResponseJson(200, mockTask)
task, err = client.Tenants.Delete(task.Entity.ID)
task, err = client.Tasks.Wait(task.ID)
Expect(err).Should(BeNil())
Expect(task.Operation).Should(Equal("DELETE_TENANT"))
Expect(task.State).Should(Equal("COMPLETED"))
})
})
})
var _ = Describe("IAM", func() {
var (
server *mocks.Server
client *Client
tenantID string
)
BeforeEach(func() {
server, client = testSetup()
tenantID = createTenant(server, client)
})
AfterEach(func() {<|fim▁hole|> Describe("ManageTenantIamPolicy", func() {
It("Set IAM Policy succeeds", func() {
mockTask := createMockTask("SET_IAM_POLICY", "COMPLETED")
server.SetResponseJson(200, mockTask)
var policy []*RoleBinding
policy = []*RoleBinding{{Role: "owner", Subjects: []string{"[email protected]"}}}
task, err := client.Tenants.SetIam(tenantID, policy)
task, err = client.Tasks.Wait(task.ID)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(task.Operation).Should(Equal("SET_IAM_POLICY"))
Expect(task.State).Should(Equal("COMPLETED"))
})
It("Modify IAM Policy succeeds", func() {
mockTask := createMockTask("MODIFY_IAM_POLICY", "COMPLETED")
server.SetResponseJson(200, mockTask)
var delta []*RoleBindingDelta
delta = []*RoleBindingDelta{{Subject: "[email protected]", Action: "ADD", Role: "owner"}}
task, err := client.Tenants.ModifyIam(tenantID, delta)
task, err = client.Tasks.Wait(task.ID)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(task).ShouldNot(BeNil())
Expect(task.Operation).Should(Equal("MODIFY_IAM_POLICY"))
Expect(task.State).Should(Equal("COMPLETED"))
})
It("Get IAM Policy succeeds", func() {
var policy []*RoleBinding
policy = []*RoleBinding{{Role: "owner", Subjects: []string{"[email protected]"}}}
server.SetResponseJson(200, policy)
response, err := client.Tenants.GetIam(tenantID)
GinkgoT().Log(err)
Expect(err).Should(BeNil())
Expect(response[0].Subjects).Should(Equal(policy[0].Subjects))
Expect(response[0].Role).Should(Equal(policy[0].Role))
})
})
})<|fim▁end|>
|
cleanTenants(client)
server.Close()
})
|
<|file_name|>hipchat.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import json
from tornado import httpclient as hc
from tornado import gen
from graphite_beacon.handlers import LOGGER, AbstractHandler
class HipChatHandler(AbstractHandler):
name = 'hipchat'
# Default options
defaults = {
'url': 'https://api.hipchat.com',
'room': None,
'key': None,
}
colors = {
'critical': 'red',
'warning': 'yellow',
'normal': 'green',
}
def init_handler(self):
self.room = self.options.get('room')
self.key = self.options.get('key')
assert self.room, 'Hipchat room is not defined.'
assert self.key, 'Hipchat key is not defined.'
self.client = hc.AsyncHTTPClient()
@gen.coroutine
def notify(self, level, *args, **kwargs):
LOGGER.debug("Handler (%s) %s", self.name, level)
data = {
'message': self.get_short(level, *args, **kwargs).decode('UTF-8'),
'notify': True,
'color': self.colors.get(level, 'gray'),
'message_format': 'text',
}
yield self.client.fetch('{url}/v2/room/{room}/notification?auth_token={token}'.format(
url=self.options.get('url'), room=self.room, token=self.key), headers={
'Content-Type': 'application/json'}, method='POST', body=json.dumps(data))<|fim▁end|>
| |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>mod load_model;<|fim▁hole|><|fim▁end|>
|
mod model;
pub use self::load_model::LoadModelError;
pub use self::model::ModelError;
|
<|file_name|>migrant.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import argparse
import binascii
import datetime
import gzip
import json
import magic
import os
import pymongo
import sys
def read_gzip(filename):<|fim▁hole|> content = file.read()
return content
def read_plain(filename):
with open(filename) as file:
content = file.read()
return content
readers = {
b'application/x-gzip': read_gzip,
b'text/plain': read_plain,
}
def read(filename):
type = magic.from_file(filename, mime=True)
return readers[type](filename).decode()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-m', help='path to moita configuration file',
dest='moita', metavar='MOITA', required=True)
parser.add_argument('filename', nargs='+')
args = parser.parse_args()
sys.path.append(os.path.dirname(args.moita))
import config
connection = pymongo.MongoClient()
collection = connection[config.DATABASE].timetables
for file in args.filename:
content = json.loads(read(file))
identifier = binascii.unhexlify(
os.path.basename(file).split('.', 1)[0]).decode()
content['_id'] = identifier
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(file))
content['updated_at'] = mtime
collection.save(content)<|fim▁end|>
|
with gzip.open(filename) as file:
|
<|file_name|>data.js<|end_file_name|><|fim▁begin|>//<|fim▁hole|>// window.onload = function() {
// var data = {username:'52200', password:'123', remember:52200};
// fetch('/api/users/getUser?id=1').then(function(res) {
// console.log("请求的数据是", res);
// if (res.ok) {
// alert('Submitted!');
// } else {
// alert('Error!');
// }
// }).then(function(body) {
// console.log("请求body的数据是", body);
// // body
// });
// };<|fim▁end|>
| |
<|file_name|>AllSessionUrlsForBuildAreAlikeTest.java<|end_file_name|><|fim▁begin|><|fim▁hole|>/**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2020 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.pnc.indyrepositorymanager;
import org.jboss.pnc.indyrepositorymanager.fixture.TestBuildExecution;
import org.jboss.pnc.enums.RepositoryType;
import org.jboss.pnc.spi.repositorymanager.BuildExecution;
import org.jboss.pnc.spi.repositorymanager.model.RepositoryConnectionInfo;
import org.jboss.pnc.spi.repositorymanager.model.RepositorySession;
import org.jboss.pnc.test.category.ContainerTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
@Category(ContainerTest.class)
public class AllSessionUrlsForBuildAreAlikeTest extends AbstractRepositoryManagerDriverTest {
@Test
public void formatRepositoryURLForSimpleInfo_AllURLsMatch() throws Exception {
// create a dummy non-chained build execution and a repo session based on it
BuildExecution execution = new TestBuildExecution();
RepositorySession repositoryConfiguration = driver.createBuildRepository(
execution,
accessToken,
accessToken,
RepositoryType.MAVEN,
Collections.emptyMap(),
false);
assertThat(repositoryConfiguration, notNullValue());
RepositoryConnectionInfo connectionInfo = repositoryConfiguration.getConnectionInfo();
assertThat(connectionInfo, notNullValue());
// check that all URLs in the connection info are the same (this might be different in another repo driver)
String expectedUrl = connectionInfo.getDependencyUrl();
assertThat(connectionInfo.getToolchainUrl(), equalTo(expectedUrl));
// assertThat(connectionInfo.getDeployPath(), equalTo(expectedUrl));
}
}<|fim▁end|>
| |
<|file_name|>PrivateChannel.js<|end_file_name|><|fim▁begin|>"use strict";
const Channel = require("./Channel");
const Collection = require("../util/Collection");
const Endpoints = require("../rest/Endpoints");
const Message = require("./Message");
const OPCodes = require("../Constants").GatewayOPCodes;
const User = require("./User");
/**
* Represents a private channel
* @extends Channel
* @prop {String} id The ID of the channel
* @prop {String} mention A string that mentions the channel
* @prop {Number} type The type of the channel
* @prop {String} lastMessageID The ID of the last message in this channel
* @prop {User} recipient The recipient in this private channel (private channels only)
* @prop {Collection<Message>} messages Collection of Messages in this channel
*/
class PrivateChannel extends Channel {
constructor(data, client) {
super(data);
this._client = client;
this.lastMessageID = data.last_message_id;
this.call = this.lastCall = null;
if(this.type === 1 || this.type === undefined) {
this.recipient = new User(data.recipients[0], client);
}
this.messages = new Collection(Message, client.options.messageLimit);
}
/**
* Ring fellow group channel recipient(s)
* @arg {String[]} recipients The IDs of the recipients to ring
*/
ring(recipients) {
this._client.requestHandler.request("POST", Endpoints.CHANNEL_CALL_RING(this.id), true, {
recipients
});
}
/**
* Check if the channel has an existing call
*/
syncCall() {
this._client.shards.values().next().value.sendWS(OPCodes.SYNC_CALL, {
channel_id: this.id
});
}
/**
* Leave the channel
* @returns {Promise}
*/
leave() {
return this._client.deleteChannel.call(this._client, this.id);
}
/**
* Send typing status in a text channel
* @returns {Promise}
*/
sendTyping() {
return (this._client || this.guild.shard.client).sendChannelTyping.call((this._client || this.guild.shard.client), this.id);
}
/**
* Get a previous message in a text channel
* @arg {String} messageID The ID of the message
* @returns {Promise<Message>}
*/
getMessage(messageID) {
return (this._client || this.guild.shard.client).getMessage.call((this._client || this.guild.shard.client), this.id, messageID);
}
/**
* Get a previous message in a text channel
* @arg {Number} [limit=50] The max number of messages to get
* @arg {String} [before] Get messages before this message ID
* @arg {String} [after] Get messages after this message ID
* @arg {String} [around] Get messages around this message ID (does not work with limit > 100)
* @returns {Promise<Message[]>}
*/
getMessages(limit, before, after, around) {
return (this._client || this.guild.shard.client).getMessages.call((this._client || this.guild.shard.client), this.id, limit, before, after, around);
}
/**
* Get all the pins in a text channel
* @returns {Promise<Message[]>}
*/
getPins() {
return (this._client || this.guild.shard.client).getPins.call((this._client || this.guild.shard.client), this.id);
}
/**
* Create a message in a text channel
* Note: If you want to DM someone, the user ID is **not** the DM channel ID. use Client.getDMChannel() to get the DM channel ID for a user
* @arg {String | Object} content A string or object. If an object is passed:
* @arg {String} content.content A content string
* @arg {Boolean} [content.tts] Set the message TTS flag
* @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default)
* @arg {Object} [content.embed] An embed object. See [the official Discord API documentation entry](https://discordapp.com/developers/docs/resources/channel#embed-object) for object structure
* @arg {Object} [file] A file object
* @arg {String} file.file A buffer containing file data
* @arg {String} file.name What to name the file
* @returns {Promise<Message>}
*/
createMessage(content, file) {
return (this._client || this.guild.shard.client).createMessage.call((this._client || this.guild.shard.client), this.id, content, file);
}
/**
* Edit a message
* @arg {String} messageID The ID of the message
* @arg {String | Array | Object} content A string, array of strings, or object. If an object is passed:
* @arg {String} content.content A content string
* @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default)
* @arg {Object} [content.embed] An embed object. See [the official Discord API documentation entry](https://discordapp.com/developers/docs/resources/channel#embed-object) for object structure
* @returns {Promise<Message>}
*/
editMessage(messageID, content) {
return (this._client || this.guild.shard.client).editMessage.call((this._client || this.guild.shard.client), this.id, messageID, content);
}
/**
* Pin a message
* @arg {String} messageID The ID of the message
* @returns {Promise}
*/
pinMessage(messageID) {
return (this._client || this.guild.shard.client).pinMessage.call((this._client || this.guild.shard.client), this.id, messageID);
}
/**
* Unpin a message
* @arg {String} messageID The ID of the message
* @returns {Promise}
*/
unpinMessage(messageID) {
return (this._client || this.guild.shard.client).unpinMessage.call((this._client || this.guild.shard.client), this.id, messageID);
}
/**
* Get a list of users who reacted with a specific reaction
* @arg {String} messageID The ID of the message
* @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
* @arg {Number} [limit=100] The maximum number of users to get
* @arg {String} [before] Get users before this user ID
* @arg {String} [after] Get users after this user ID
* @returns {Promise<User[]>}
*/
getMessageReaction(messageID, reaction, limit, before, after) {
return (this._client || this.guild.shard.client).getMessageReaction.call((this._client || this.guild.shard.client), this.id, messageID, reaction, limit, before, after);
}
/**
* Add a reaction to a message
* @arg {String} messageID The ID of the message
* @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
* @arg {String} [userID="@me"] The ID of the user to react as
* @returns {Promise}
*/
addMessageReaction(messageID, reaction, userID) {
return (this._client || this.guild.shard.client).addMessageReaction.call((this._client || this.guild.shard.client), this.id, messageID, reaction, userID);
}
/**
* Remove a reaction from a message
* @arg {String} messageID The ID of the message
* @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
* @arg {String} [userID="@me"] The ID of the user to remove the reaction for
* @returns {Promise}
*/
removeMessageReaction(messageID, reaction, userID) {
return (this._client || this.guild.shard.client).removeMessageReaction.call((this._client || this.guild.shard.client), this.id, messageID, reaction, userID);
}
/**
* Remove all reactions from a message
* @arg {String} messageID The ID of the message
* @returns {Promise}
*/
removeMessageReactions(messageID) {
return (this._client || this.guild.shard.client).removeMessageReactions.call((this._client || this.guild.shard.client), this.id, messageID);
}
/**
* Delete a message
* @arg {String} messageID The ID of the message
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
deleteMessage(messageID, reason) {
return (this._client || this.guild.shard.client).deleteMessage.call((this._client || this.guild.shard.client), this.id, messageID, reason);
}
/**
* Un-send a message. You're welcome Programmix
* @arg {String} messageID The ID of the message
* @returns {Promise}
*/
unsendMessage(messageID) {
return (this._client || this.guild.shard.client).deleteMessage.call((this._client || this.guild.shard.client), this.id, messageID);
}
toJSON() {
var base = super.toJSON(true);
for(var prop of ["call", "lastCall", "lastMessageID", "messages", "recipient"]) {
base[prop] = this[prop] && this[prop].toJSON ? this[prop].toJSON() : this[prop];
}
return base;
}
}<|fim▁hole|><|fim▁end|>
|
module.exports = PrivateChannel;
|
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>extern crate peg;
<|fim▁hole|><|fim▁end|>
|
fn main() {
peg::cargo_build("src/glop.rustpeg");
}
|
<|file_name|>livebargraph.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 25 21:11:45 2017
@author: hubert
"""
import numpy as np
import matplotlib.pyplot as plt
class LiveBarGraph(object):
"""
"""
def __init__(self, band_names=['delta', 'theta', 'alpha', 'beta'],
ch_names=['TP9', 'AF7', 'AF8', 'TP10']):
"""
"""
self.band_names = band_names
self.ch_names = ch_names
self.n_bars = self.band_names * self.ch_names
self.x =<|fim▁hole|>
self.fig, self.ax = plt.subplots()
self.ax.set_ylim((0, 1))
y = np.zeros((self.n_bars,))
x = range(self.n_bars)
self.rects = self.ax.bar(x, y)
def update(self, new_y):
[rect.set_height(y) for rect, y in zip(self.rects, new_y)]
if __name__ == '__main__':
bar = LiveBarGraph()
plt.show()
while True:
bar.update(np.random.random(10))
plt.pause(0.1)<|fim▁end|>
| |
<|file_name|>second.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
name = raw_input("please enter your name:")<|fim▁hole|>print "my name is {} and i live in {}".format(name,address)<|fim▁end|>
|
address = raw_input("please enter your address:")
|
<|file_name|>forgot_username.py<|end_file_name|><|fim▁begin|>from cornflake.exceptions import ValidationError
from flask import Response
from radar.api.serializers.auth import ForgotUsernameSerializer
from radar.api.views.generics import ApiView, request_json
from radar.auth.exceptions import UserNotFound
from radar.auth.forgot_username import forgot_username
class ForgotUsernameView(ApiView):
@request_json(ForgotUsernameSerializer)
def post(self, data):
email = data['email']
try:<|fim▁hole|> forgot_username(email)
except UserNotFound:
raise ValidationError({'email': 'No users found with that email address.'})
return Response(status=200)
def register_views(app):
app.add_public_endpoint('forgot_username')
app.add_url_rule('/forgot-username', view_func=ForgotUsernameView.as_view('forgot_username'))<|fim▁end|>
| |
<|file_name|>AfterNew15-out.java<|end_file_name|><|fim▁begin|>import java.io.File;
import java.io.FilenameFilter;<|fim▁hole|>
class A {
{
new java.io.File("aaa").list(new FilenameFilter() {
public boolean accept(File dir, String name) {
<selection>return false; //To change body of implemented methods use File | Settings | File Templates.</selection>
}
});
}
}<|fim▁end|>
| |
<|file_name|>client_updater.py<|end_file_name|><|fim▁begin|>import sys
import time
import logging
from socketio import socketio_manage
from socketio.mixins import BroadcastMixin
from socketio.namespace import BaseNamespace
from DataAggregation.webdata_aggregator import getAvailableWorkshops
logger = logging.getLogger(__name__)
std_out_logger = logging.StreamHandler(sys.stdout)<|fim▁hole|>def broadcast_msg(server, ns_name, event, *args):
pkt = dict(type="event",
name=event,
args=args,
endpoint=ns_name)
for sessid, socket in server.sockets.iteritems():
socket.send_packet(pkt)
def workshops_monitor(server):
sizes = []
workshops = getAvailableWorkshops()
for w in workshops:
tmp = [w.workshopName, w.q.qsize()]
sizes.append(tmp)
broadcast_msg(server, '', "sizes", tmp)
while True:
logger.info("Participants viewing frontend:" + str(len(server.sockets)))
workshops_available = []
curr_workshops = getAvailableWorkshops()
for w in curr_workshops:
workshops_available.append([w.workshopName, w.q.qsize()])
wq = filter(lambda x: x[0] == w.workshopName, sizes)[0]
if wq[1] != w.q.qsize():
wq[1] = w.q.qsize()
logging.info("client_updater: New update being pushed to clients: " + str(wq))
broadcast_msg(server, '', 'sizes', wq)
logger.info("Workshops available:" + str(workshops_available))
time.sleep(1)
class RequestHandlerApp(object):
def __call__(self, environ, start_response):
if environ['PATH_INFO'].startswith('/socket.io'):
socketio_manage(environ, {'': QueueStatusHandler})
class QueueStatusHandler(BaseNamespace, BroadcastMixin):
def on_connect(self):
sizes = []
workshops = getAvailableWorkshops()
for w in workshops:
tmp = [w.workshopName, w.q.qsize()]
sizes.append(tmp)
self.emit('sizes', tmp)<|fim▁end|>
|
logger.addHandler(std_out_logger)
|
<|file_name|>contributors.js<|end_file_name|><|fim▁begin|>var utils = require('./utils')
, request = require('request')
;
module.exports = {
fetchGithubInfo: function(email, cb) {
var githubProfile = {};
var api_call = "https://api.github.com/search/users?q="+email+"%20in:email";
var options = { url: api_call, headers: { 'User-Agent': 'Blogdown' } };
console.log("Calling "+api_call);<|fim▁hole|> if(err) return cb(err);
res = JSON.parse(body);
if(res.total_count==1)
githubProfile = res.items[0];
cb(null, githubProfile);
});
},
fetchGravatarProfile: function(email, cb) {
var gravatarProfile = {};
var hash = utils.getHash(email);
var api_call = "http://en.gravatar.com/"+hash+".json";
console.log("Calling "+api_call);
var options = { url: api_call, headers: { 'User-Agent': 'Blogdown' } };
request(options, function(err, res, body) {
if(err) return cb(err);
try {
res = JSON.parse(body);
} catch(e) {
console.error("fetchGravatarProfile: Couldn't parse response JSON ", body, e);
return cb(e);
}
if(res.entry && res.entry.length > 0)
gravatarProfile = res.entry[0];
return cb(null, gravatarProfile);
});
}
};<|fim▁end|>
|
request(options, function(err, res, body) {
|
<|file_name|>var-captured-in-nested-closure.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-command:rbreak zzz
// gdb-command:run
// gdb-command:finish
// gdb-command:print variable
// gdb-check:$1 = 1
// gdb-command:print constant
// gdb-check:$2 = 2
// gdb-command:print a_struct
// gdb-check:$3 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *struct_ref
// gdb-check:$4 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *owned
// gdb-check:$5 = 6
// gdb-command:print managed->val
// gdb-check:$6 = 7
// gdb-command:print closure_local
// gdb-check:$7 = 8
// gdb-command:continue
// gdb-command:finish
// gdb-command:print variable
// gdb-check:$8 = 1
// gdb-command:print constant
// gdb-check:$9 = 2
// gdb-command:print a_struct
// gdb-check:$10 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *struct_ref
// gdb-check:$11 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *owned
// gdb-check:$12 = 6
// gdb-command:print managed->val
// gdb-check:$13 = 7
// gdb-command:print closure_local
// gdb-check:$14 = 8
// gdb-command:continue
#![feature(managed_boxes)]
#![allow(unused_variable)]
struct Struct {
a: int,
b: f64,
c: uint
}
fn main() {
let mut variable = 1;
let constant = 2;
let a_struct = Struct {
a: -3,
b: 4.5,
c: 5
};
let struct_ref = &a_struct;
let owned = box 6;
let managed = @7;
let closure = || {
let closure_local = 8;
let nested_closure = || {
zzz();
variable = constant + a_struct.a + struct_ref.a + *owned + *managed + closure_local;
};
zzz();
nested_closure();
};
closure();
}
fn zzz() {()}<|fim▁end|>
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
|
<|file_name|>window.rs<|end_file_name|><|fim▁begin|>use std::ops::{Bound, Range, RangeBounds};
/// A owned window around an underlying buffer.
///
/// Normally slices work great for considering sub-portions of a buffer, but
/// unfortunately a slice is a *borrowed* type in Rust which has an associated
/// lifetime. When working with future and async I/O these lifetimes are not
/// always appropriate, and are sometimes difficult to store in tasks. This
/// type strives to fill this gap by providing an "owned slice" around an
/// underlying buffer of bytes.
///
/// A `Window<T>` wraps an underlying buffer, `T`, and has configurable
/// start/end indexes to alter the behavior of the `AsRef<[u8]>` implementation
/// that this type carries.
///
/// This type can be particularly useful when working with the `write_all`
/// combinator in this crate. Data can be sliced via `Window`, consumed by
/// `write_all`, and then earned back once the write operation finishes through
/// the `into_inner` method on this type.
#[derive(Debug)]
pub struct Window<T> {
inner: T,
range: Range<usize>,<|fim▁hole|> /// slice.
///
/// Further methods can be called on the returned `Window<T>` to alter the
/// window into the data provided.
pub fn new(t: T) -> Self {
Self { range: 0..t.as_ref().len(), inner: t }
}
/// Gets a shared reference to the underlying buffer inside of this
/// `Window`.
pub fn get_ref(&self) -> &T {
&self.inner
}
/// Gets a mutable reference to the underlying buffer inside of this
/// `Window`.
pub fn get_mut(&mut self) -> &mut T {
&mut self.inner
}
/// Consumes this `Window`, returning the underlying buffer.
pub fn into_inner(self) -> T {
self.inner
}
/// Returns the starting index of this window into the underlying buffer
/// `T`.
pub fn start(&self) -> usize {
self.range.start
}
/// Returns the end index of this window into the underlying buffer
/// `T`.
pub fn end(&self) -> usize {
self.range.end
}
/// Changes the range of this window to the range specified.
///
/// # Panics
///
/// This method will panic if `range` is out of bounds for the underlying
/// slice or if [`start_bound()`] of `range` comes after the [`end_bound()`].
///
/// [`start_bound()`]: std::ops::RangeBounds::start_bound
/// [`end_bound()`]: std::ops::RangeBounds::end_bound
pub fn set<R: RangeBounds<usize>>(&mut self, range: R) {
let start = match range.start_bound() {
Bound::Included(n) => *n,
Bound::Excluded(n) => *n + 1,
Bound::Unbounded => 0,
};
let end = match range.end_bound() {
Bound::Included(n) => *n + 1,
Bound::Excluded(n) => *n,
Bound::Unbounded => self.inner.as_ref().len(),
};
assert!(end <= self.inner.as_ref().len());
assert!(start <= end);
self.range.start = start;
self.range.end = end;
}
}
impl<T: AsRef<[u8]>> AsRef<[u8]> for Window<T> {
fn as_ref(&self) -> &[u8] {
&self.inner.as_ref()[self.range.start..self.range.end]
}
}
impl<T: AsMut<[u8]>> AsMut<[u8]> for Window<T> {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.inner.as_mut()[self.range.start..self.range.end]
}
}<|fim▁end|>
|
}
impl<T: AsRef<[u8]>> Window<T> {
/// Creates a new window around the buffer `t` defaulting to the entire
|
<|file_name|>index.js<|end_file_name|><|fim▁begin|>/*
*
* UI reducer
*
*/
import { fromJS } from 'immutable';
import {
SET_PRODUCT_QUANTITY_SELECTOR,
} from './constants';
const initialState = fromJS({
product: {
quantitySelected: 1,
},
});
function uiReducer(state = initialState, action) {
switch (action.type) {<|fim▁hole|> }
}
export default uiReducer;<|fim▁end|>
|
case SET_PRODUCT_QUANTITY_SELECTOR:
return state.setIn(['product', 'quantitySelected'], action.quantity);
default:
return state;
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>use binary_podman::{BinaryTrait, PodmanBinary};
use buildpack::{
eyre::Report,
libcnb::{
build::{BuildContext, BuildResult, BuildResultBuilder},
detect::{DetectContext, DetectResult, DetectResultBuilder},<|fim▁hole|> Buildpack, Error, Result,
},
tag_for_path, BuildpackTrait,
};
pub struct DockerfileBuildpack;
impl Buildpack for DockerfileBuildpack {
type Platform = GenericPlatform;
type Metadata = GenericMetadata;
type Error = Report;
fn detect(&self, _context: DetectContext<Self>) -> Result<DetectResult, Self::Error> {
if Self::any_exist(&["Dockerfile", "Containerfile"]) {
DetectResultBuilder::pass().build()
} else {
DetectResultBuilder::fail().build()
}
}
fn build(&self, context: BuildContext<Self>) -> Result<BuildResult, Self::Error> {
let tag = tag_for_path(&context.app_dir);
PodmanBinary {}
.ensure_version_sync(">=1")
.map_err(Error::BuildpackError)?
.run_sync(&["build", "--tag", &tag, "."])
.map_err(Error::BuildpackError)?;
BuildResultBuilder::new().build()
}
}
impl BuildpackTrait for DockerfileBuildpack {
fn toml() -> &'static str {
include_str!("../buildpack.toml")
}
}<|fim▁end|>
|
generic::{GenericMetadata, GenericPlatform},
|
<|file_name|>filtermanager.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Martijn Voncken <[email protected]>
#
# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with the OpenSSL library.
# See LICENSE for more details.
#
import copy
import logging
import deluge.component as component
from deluge.common import TORRENT_STATE
log = logging.getLogger(__name__)
STATE_SORT = ["All", "Active"] + TORRENT_STATE
# Special purpose filters:
def filter_keywords(torrent_ids, values):
# Cleanup
keywords = ",".join([v.lower() for v in values])
keywords = keywords.split(",")
for keyword in keywords:
torrent_ids = filter_one_keyword(torrent_ids, keyword)
return torrent_ids
def filter_one_keyword(torrent_ids, keyword):
"""
search torrent on keyword.
searches title,state,tracker-status,tracker,files
"""
all_torrents = component.get("TorrentManager").torrents
for torrent_id in torrent_ids:
torrent = all_torrents[torrent_id]
if keyword in torrent.filename.lower():
yield torrent_id
elif keyword in torrent.state.lower():
yield torrent_id
elif torrent.trackers and keyword in torrent.trackers[0]["url"]:
yield torrent_id
elif keyword in torrent_id:
yield torrent_id
# Want to find broken torrents (search on "error", or "unregistered")
elif keyword in torrent.tracker_status.lower():
yield torrent_id
else:
for t_file in torrent.get_files():
if keyword in t_file["path"].lower():
yield torrent_id
break
def filter_by_name(torrent_ids, search_string):
all_torrents = component.get("TorrentManager").torrents
try:
search_string, match_case = search_string[0].split('::match')
except ValueError:
search_string = search_string[0]
match_case = False
if match_case is False:
search_string = search_string.lower()
for torrent_id in torrent_ids:
torrent_name = all_torrents[torrent_id].get_name()
if match_case is False:
torrent_name = all_torrents[torrent_id].get_name().lower()
else:
torrent_name = all_torrents[torrent_id].get_name()
if search_string in torrent_name:
yield torrent_id
<|fim▁hole|> filtered_torrent_ids = []
tm = component.get("TorrentManager")
# If this is a tracker_host, then we need to filter on it
if values[0] != "Error":
for torrent_id in torrent_ids:
if values[0] == tm[torrent_id].get_status(["tracker_host"])["tracker_host"]:
filtered_torrent_ids.append(torrent_id)
return filtered_torrent_ids
# Check torrent's tracker_status for 'Error:' and return those torrent_ids
for torrent_id in torrent_ids:
if "Error:" in tm[torrent_id].get_status(["tracker_status"])["tracker_status"]:
filtered_torrent_ids.append(torrent_id)
return filtered_torrent_ids
class FilterManager(component.Component):
"""FilterManager
"""
def __init__(self, core):
component.Component.__init__(self, "FilterManager")
log.debug("FilterManager init..")
self.core = core
self.torrents = core.torrentmanager
self.registered_filters = {}
self.register_filter("keyword", filter_keywords)
self.register_filter("name", filter_by_name)
self.tree_fields = {}
self.prev_filter_tree_keys = None
self.filter_tree_items = None
self.register_tree_field("state", self._init_state_tree)
def _init_tracker_tree():
return {"Error": 0}
self.register_tree_field("tracker_host", _init_tracker_tree)
self.register_filter("tracker_host", tracker_error_filter)
def _init_users_tree():
return {"": 0}
self.register_tree_field("owner", _init_users_tree)
def filter_torrent_ids(self, filter_dict):
"""
returns a list of torrent_id's matching filter_dict.
core filter method
"""
if not filter_dict:
return self.torrents.get_torrent_list()
# Sanitize input: filter-value must be a list of strings
for key, value in filter_dict.items():
if isinstance(value, basestring):
filter_dict[key] = [value]
# Optimized filter for id
if "id" in filter_dict:
torrent_ids = list(filter_dict["id"])
del filter_dict["id"]
else:
torrent_ids = self.torrents.get_torrent_list()
# Return if there's nothing more to filter
if not filter_dict:
return torrent_ids
# Special purpose, state=Active.
if "state" in filter_dict:
# We need to make sure this is a list for the logic below
filter_dict["state"] = list(filter_dict["state"])
if "state" in filter_dict and "Active" in filter_dict["state"]:
filter_dict["state"].remove("Active")
if not filter_dict["state"]:
del filter_dict["state"]
torrent_ids = self.filter_state_active(torrent_ids)
if not filter_dict:
return torrent_ids
# Registered filters
for field, values in filter_dict.items():
if field in self.registered_filters:
# Filters out doubles
torrent_ids = list(set(self.registered_filters[field](torrent_ids, values)))
del filter_dict[field]
if not filter_dict:
return torrent_ids
torrent_keys, plugin_keys = self.torrents.separate_keys(filter_dict.keys(), torrent_ids)
# Leftover filter arguments, default filter on status fields.
for torrent_id in list(torrent_ids):
status = self.core.create_torrent_status(torrent_id, torrent_keys, plugin_keys)
for field, values in filter_dict.iteritems():
if (not status[field] in values) and torrent_id in torrent_ids:
torrent_ids.remove(torrent_id)
return torrent_ids
def get_filter_tree(self, show_zero_hits=True, hide_cat=None):
"""
returns {field: [(value,count)] }
for use in sidebar.
"""
torrent_ids = self.torrents.get_torrent_list()
tree_keys = list(self.tree_fields.keys())
if hide_cat:
for cat in hide_cat:
tree_keys.remove(cat)
torrent_keys, plugin_keys = self.torrents.separate_keys(tree_keys, torrent_ids)
# Keys are the same, so use previous items
if self.prev_filter_tree_keys != tree_keys:
self.filter_tree_items = dict((field, self.tree_fields[field]()) for field in tree_keys)
self.prev_filter_tree_keys = tree_keys
items = copy.deepcopy(self.filter_tree_items)
for torrent_id in list(torrent_ids):
status = self.core.create_torrent_status(torrent_id, torrent_keys, plugin_keys) # status={key:value}
for field in tree_keys:
value = status[field]
items[field][value] = items[field].get(value, 0) + 1
if "tracker_host" in items:
items["tracker_host"]["All"] = len(torrent_ids)
items["tracker_host"]["Error"] = len(tracker_error_filter(torrent_ids, ("Error",)))
if not show_zero_hits:
for cat in ["state", "owner", "tracker_host"]:
if cat in tree_keys:
self._hide_state_items(items[cat])
# Return a dict of tuples:
sorted_items = {}
for field in tree_keys:
sorted_items[field] = sorted(items[field].iteritems())
if "state" in tree_keys:
sorted_items["state"].sort(self._sort_state_items)
return sorted_items
def _init_state_tree(self):
init_state = {}
init_state["All"] = len(self.torrents.get_torrent_list())
for state in TORRENT_STATE:
init_state[state] = 0
init_state["Active"] = len(self.filter_state_active(self.torrents.get_torrent_list()))
return init_state
def register_filter(self, id, filter_func, filter_value=None):
self.registered_filters[id] = filter_func
def deregister_filter(self, id):
del self.registered_filters[id]
def register_tree_field(self, field, init_func=lambda: {}):
self.tree_fields[field] = init_func
def deregister_tree_field(self, field):
if field in self.tree_fields:
del self.tree_fields[field]
def filter_state_active(self, torrent_ids):
for torrent_id in list(torrent_ids):
status = self.torrents[torrent_id].get_status(["download_payload_rate", "upload_payload_rate"])
if status["download_payload_rate"] or status["upload_payload_rate"]:
pass
else:
torrent_ids.remove(torrent_id)
return torrent_ids
def _hide_state_items(self, state_items):
"for hide(show)-zero hits"
for (value, count) in state_items.items():
if value != "All" and count == 0:
del state_items[value]
def _sort_state_items(self, x, y):
""
if x[0] in STATE_SORT:
ix = STATE_SORT.index(x[0])
else:
ix = 99
if y[0] in STATE_SORT:
iy = STATE_SORT.index(y[0])
else:
iy = 99
return ix - iy<|fim▁end|>
|
def tracker_error_filter(torrent_ids, values):
|
<|file_name|>test_executor.py<|end_file_name|><|fim▁begin|>import unittest
from mock import Mock, patch<|fim▁hole|>from concurrent.futures import ThreadPoolExecutor
import re
class TestExecutor(unittest.TestCase):
output = 'TestExecutor output'
outputs = ['TestExecutor 1', 'TestExecutor 2']
def test_runnable_output(self):
executor = Executor()
with patch.object(Runnable, 'run', return_value=TestExecutor.output):
executor.run(Runnable())
executor.wait()
results = executor.results
self.assertEqual(1, len(results))
self.assertEqual(TestExecutor.output, results[0])
def test_runnable_outputs(self):
executor = Executor()
runnable = Runnable()
with patch.object(Runnable, 'run', side_effect=TestExecutor.outputs):
executor.run(runnable)
executor.run(runnable)
executor.wait()
results = executor.results
self.assertListEqual(TestExecutor.outputs, results)
def test_function_output(self):
executor = Executor()
executor.run_function(background_function)
executor.wait()
output = executor.results[0]
self.assertEqual(TestExecutor.output, output)
def test_function_outputs(self):
executor = Executor()
runnable = Runnable()
with patch.object(Runnable, 'run', side_effect=TestExecutor.outputs):
executor.run(runnable)
executor.run(runnable)
executor.wait()
results = executor.results
self.assertListEqual(TestExecutor.outputs, results)
def test_against_runnable_memory_leak(self):
executor = Executor()
with patch.object(Runnable, 'run'):
executor.run(Runnable())
executor.wait()
self.assertEqual(0, len(executor._future_runnables))
def test_against_function_memory_leak(self):
executor = Executor()
executor.run_function(background_function)
executor.wait()
self.assertEqual(0, len(executor._function_titles))
def test_if_shutdown_shutdowns_executor(self):
executor = Executor()
executor._executor = Mock()
executor.shutdown()
executor._executor.shutdown.called_once_with()
def test_if_shutdown_clears_function_resources(self):
executor = Executor()
executor._function_titles = Mock()
executor.shutdown()
executor._function_titles.clear.assert_called_once_with()
def test_if_shutdown_clears_runnable_resources(self):
executor = Executor()
executor._future_runnables = Mock()
executor.shutdown()
executor._future_runnables.clear.assert_called_once_with()
def test_exception_logging(self):
executor = Executor()
executor._log = Mock()
with patch.object(Runnable, 'run', side_effect=Exception):
executor.run(Runnable)
executor.wait()
self.assertEqual(1, executor._log.error.call_count)
@patch.object(ThreadPoolExecutor, '__init__', return_value=None)
def test_specified_max_workers(self, pool_mock):
max = 42
Executor(max)
pool_mock.assert_called_once_with(42)
def test_calledprocesserror_logging(self):
executor = Executor()
executor._log = Mock()
exception = CalledProcessError(returncode=1, cmd='command')
with patch.object(Runnable, 'run', side_effect=exception):
executor.run(Runnable)
executor.wait()
self.assertEqual(1, executor._log.error.call_count)
def test_if_logged_title_is_hidden_if_it_equals_command(self):
command = 'command'
runnable = Runnable()
runnable.title = command
exception = CalledProcessError(returncode=1, cmd=command)
runnable.run = Mock(side_effect=exception)
executor = Executor()
executor._log = Mock()
executor.run(runnable)
executor.wait()
executor._log.error.assert_called_once_with(Matcher(has_not_title))
def test_logged_title_when_it_differs_from_command(self):
command, title = 'command', 'title'
runnable = Runnable()
runnable.title = title
exception = CalledProcessError(returncode=1, cmd=command)
runnable.run = Mock(side_effect=exception)
executor = Executor()
executor._log = Mock()
executor.run(runnable)
executor.wait()
executor._log.error.assert_called_once_with(Matcher(has_title))
def has_title(msg):
return re.match("(?ims).*Title", msg) is not None
def has_not_title(msg):
return re.match("(?ims).*Title", msg) is None
class Matcher:
def __init__(self, compare):
self.compare = compare
def __eq__(self, msg):
return self.compare(msg)
def background_function():
return TestExecutor.output
if __name__ == '__main__':
unittest.main()<|fim▁end|>
|
from expyrimenter import Executor
from expyrimenter.runnable import Runnable
from subprocess import CalledProcessError
|
<|file_name|>ToggleTableViewModeCompactAction.java<|end_file_name|><|fim▁begin|>/*
* This file is part of trolCommander, http://www.trolsoft.ru/en/soft/trolcommander
* Copyright (C) 2014-2016 Oleg Trifonov
*
* trolCommander is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* trolCommander 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mucommander.ui.action.impl;
import com.mucommander.ui.action.AbstractActionDescriptor;
import com.mucommander.ui.action.ActionCategory;
import com.mucommander.ui.action.ActionDescriptor;
import com.mucommander.ui.action.MuAction;
import com.mucommander.ui.main.MainFrame;
import com.mucommander.ui.main.table.views.TableViewMode;
import javax.swing.KeyStroke;
import java.awt.event.KeyEvent;
import java.util.Map;
/**
* @author Oleg Trifonov
* Created on 15/04/15.
*/
public class ToggleTableViewModeCompactAction extends MuAction {
/**
* Creates a new <code>ToggleTableViewModeCompactAction</code>
*
* @param mainFrame the MainFrame to associate with this new MuAction
* @param properties the initial properties to use in this action. The Hashtable may simply be empty if no initial
*/
ToggleTableViewModeCompactAction(MainFrame mainFrame, Map<String, Object> properties) {
super(mainFrame, properties);<|fim▁hole|> @Override
public void performAction() {
getMainFrame().getActiveTable().setViewMode(TableViewMode.COMPACT);
}
@Override
public ActionDescriptor getDescriptor() {
return new Descriptor();
}
public static final class Descriptor extends AbstractActionDescriptor {
public static final String ACTION_ID = "ToggleTableViewModeCompact";
public String getId() { return ACTION_ID; }
public ActionCategory getCategory() { return ActionCategory.VIEW; }
public KeyStroke getDefaultAltKeyStroke() { return null; }
public KeyStroke getDefaultKeyStroke() {
return KeyStroke.getKeyStroke(KeyEvent.VK_2, KeyEvent.CTRL_DOWN_MASK);
}
public MuAction createAction(MainFrame mainFrame, Map<String, Object> properties) {
return new ToggleTableViewModeCompactAction(mainFrame, properties);
}
}
}<|fim▁end|>
|
}
|
<|file_name|>profile-status.js<|end_file_name|><|fim▁begin|>Vue.http.options.emulateJSON = true;
var profile_status = new Vue({
el: '#profile-status',<|fim▁hole|> isSuggestShow: 0,
suggest: [
{text: 'Предложение оплаты услуг, вирт за деньги, проституция, мошенничество, шантаж, спам', style: 'bg_ored'},
{text: 'Фото из интернета, парень под видои девушки, вымышленные данные, обман, фейк', style: 'bg_ored'},
{text: 'Оскорбления, хамство, троллинг, грубые сообщения, жалобы на интим фото, провокации', style: 'bg_oyel'},
{text: 'Пишет всем подряд, игнорирует анкетные данные, гей пишет натуралам, рассылки', style: 'bg_oyel'},
{text: 'Ложно, отклоненные жалобы, причина не ясна, ссора, выяснение отношений', style: 'bg_ogrn'},
],
text: 'Статус не установлен',
style: '',
user: '',
},
created: function () {
this.user = $('#profile-status__text').data('user');
var text = $('#profile-status__text').text().trim();
if (text) {
this.text = text;
}
},
mounted: function () {
this.set_style();
},
methods: {
variant: function (event) {
this.isSuggestShow = true;
},
post: function () {
if (this.user) {
this.$http.post('/userinfo/setcomm/', {
id: this.user,
text: this.text
});
}
},
save: function (i) {
this.text = this.suggest[i].text;
this.style = this.suggest[i].style;
this.isSuggestShow = false;
this.post();
},
set_style: function () {
if (this.text == this.suggest[0].text) {
this.style = this.suggest[0].style;
};
if (this.text == this.suggest[1].text) {
this.style = this.suggest[0].style;
};
if (this.text == this.suggest[2].text) {
this.style = this.suggest[2].style;
};
if (this.text == this.suggest[3].text) {
this.style = this.suggest[2].style;
};
if (this.text == this.suggest[4].text) {
this.style = this.suggest[4].style;
};
}
}
});<|fim▁end|>
|
data: {
|
<|file_name|>sinker.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 ASMlover. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list ofconditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materialsprovided with the<|fim▁hole|># THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import zmq
if __name__ == '__main__':
ctx = zmq.Context()
sinker = ctx.socket(zmq.PULL)
sinker.bind('tcp://*:6666')
print 'sender server init success ...'
msg = sinker.recv()
print '\t%s' % msg
while True:
try:
msg = sinker.recv()
print msg
except KeyboardInterrupt:
break
sinker.close()<|fim▁end|>
|
# distribution.
#
|
<|file_name|>tumblr.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class TumblrIE(InfoExtractor):
_VALID_URL = r'http://(?P<blog_name>.*?)\.tumblr\.com/(?:post|video)/(?P<id>[0-9]+)(?:$|[/?#])'
_TESTS = [{
'url': 'http://tatianamaslanydaily.tumblr.com/post/54196191430/orphan-black-dvd-extra-behind-the-scenes',
'md5': '479bb068e5b16462f5176a6828829767',
'info_dict': {
'id': '54196191430',
'ext': 'mp4',
'title': 'tatiana maslany news, Orphan Black || DVD extra - behind the scenes ↳...',
'description': 'md5:37db8211e40b50c7c44e95da14f630b7',
'thumbnail': 're:http://.*\.jpg',
}
}, {
'url': 'http://5sostrum.tumblr.com/post/90208453769/yall-forgetting-the-greatest-keek-of-them-all',<|fim▁hole|> 'id': '90208453769',
'ext': 'mp4',
'title': '5SOS STRUM ;]',
'description': 'md5:dba62ac8639482759c8eb10ce474586a',
'thumbnail': 're:http://.*\.jpg',
}
}]
def _real_extract(self, url):
m_url = re.match(self._VALID_URL, url)
video_id = m_url.group('id')
blog = m_url.group('blog_name')
url = 'http://%s.tumblr.com/post/%s/' % (blog, video_id)
webpage = self._download_webpage(url, video_id)
iframe_url = self._search_regex(
r'src=\'(https?://www\.tumblr\.com/video/[^\']+)\'',
webpage, 'iframe url')
iframe = self._download_webpage(iframe_url, video_id)
video_url = self._search_regex(r'<source src="([^"]+)"',
iframe, 'video url')
# The only place where you can get a title, it's not complete,
# but searching in other places doesn't work for all videos
video_title = self._html_search_regex(
r'(?s)<title>(?P<title>.*?)(?: \| Tumblr)?</title>',
webpage, 'title')
return {
'id': video_id,
'url': video_url,
'ext': 'mp4',
'title': video_title,
'description': self._og_search_description(webpage, default=None),
'thumbnail': self._og_search_thumbnail(webpage, default=None),
}<|fim▁end|>
|
'md5': 'bf348ef8c0ef84fbf1cbd6fa6e000359',
'info_dict': {
|
<|file_name|>ComposedSQL.java<|end_file_name|><|fim▁begin|>package org.blendee.jdbc;
/**<|fim▁hole|> */
public interface ComposedSQL extends ChainPreparedStatementComplementer {
/**
* このインスタンスが持つ SQL 文を返します。
* @return SQL 文
*/
String sql();
/**
* {@link PreparedStatementComplementer} を入れ替えた新しい {@link ComposedSQL} を生成します。
* @param complementer 入れ替える {@link PreparedStatementComplementer}
* @return 同じ SQL を持つ、別のインスタンス
*/
default ComposedSQL reproduce(PreparedStatementComplementer complementer) {
var sql = sql();
return new ComposedSQL() {
@Override
public String sql() {
return sql;
}
@Override
public int complement(int done, BPreparedStatement statement) {
complementer.complement(statement);
return Integer.MIN_VALUE;
}
};
}
/**
* {@link ChainPreparedStatementComplementer} を入れ替えた新しい {@link ComposedSQL} を生成します。
* @param complementer 入れ替える {@link ChainPreparedStatementComplementer}
* @return 同じ SQL を持つ、別のインスタンス
*/
default ComposedSQL reproduce(ChainPreparedStatementComplementer complementer) {
var sql = sql();
return new ComposedSQL() {
@Override
public String sql() {
return sql;
}
@Override
public int complement(int done, BPreparedStatement statement) {
return complementer.complement(done, statement);
}
};
}
}<|fim▁end|>
|
* プレースホルダを持つ SQL 文と、プレースホルダにセットする値を持つものを表すインターフェイスです。
* @author 千葉 哲嗣
|
<|file_name|>create.rs<|end_file_name|><|fim▁begin|>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use clap::ArgMatches;
use libimagdiary::diary::Diary;
use libimagdiary::diaryid::DiaryId;
use libimagdiary::error::DiaryErrorKind as DEK;
use libimagdiary::error::ResultExt;
use libimagentryedit::edit::Edit;
use libimagrt::runtime::Runtime;
use libimagerror::trace::trace_error_exit;
use libimagerror::trace::MapErrTrace;
use libimagutil::warn_exit::warn_exit;
use libimagstore::store::FileLockEntry;
use libimagstore::store::Store;
use util::get_diary_name;
use util::get_diary_timed_config;
use util::Timed;
pub fn create(rt: &Runtime) {
let diaryname = get_diary_name(rt)
.unwrap_or_else( || warn_exit("No diary selected. Use either the configuration file or the commandline option", 1));
let mut entry = create_entry(rt.store(), &diaryname, rt);
let res = if rt.cli().subcommand_matches("create").unwrap().is_present("no-edit") {
debug!("Not editing new diary entry");
Ok(())
} else {
debug!("Editing new diary entry");
entry.edit_content(rt)
.chain_err(|| DEK::DiaryEditError)
};
if let Err(e) = res {
trace_error_exit(&e, 1);
} else {
info!("Ok!");
}
}
fn create_entry<'a>(diary: &'a Store, diaryname: &str, rt: &Runtime) -> FileLockEntry<'a> {
use util::parse_timed_string;
let create = rt.cli().subcommand_matches("create").unwrap();
let create_timed = create.value_of("timed")
.map(|t| parse_timed_string(t, diaryname).map_err_trace_exit_unwrap(1))
.map(Some)
.unwrap_or_else(|| match get_diary_timed_config(rt, diaryname) {
Err(e) => trace_error_exit(&e, 1),
Ok(Some(t)) => Some(t),
Ok(None) => {
warn!("Missing config: 'diary.diaries.{}.timed'", diaryname);
warn!("Assuming 'false'");
None
}
});
let entry = match create_timed {
Some(timed) => {
let id = create_id_from_clispec(&create, &diaryname, timed);
diary.retrieve(id).chain_err(|| DEK::StoreReadError)
},<|fim▁hole|>
None => {
debug!("Creating non-timed entry");
diary.new_entry_today(diaryname)
}
};
match entry {
Err(e) => trace_error_exit(&e, 1),
Ok(e) => {
debug!("Created: {}", e.get_location());
e
}
}
}
fn create_id_from_clispec(create: &ArgMatches, diaryname: &str, timed_type: Timed) -> DiaryId {
use std::str::FromStr;
let get_hourly_id = |create: &ArgMatches| -> DiaryId {
let time = DiaryId::now(String::from(diaryname));
let hr = create
.value_of("hour")
.map(|v| { debug!("Creating hourly entry with hour = {:?}", v); v })
.and_then(|s| {
FromStr::from_str(s)
.map_err(|_| warn!("Could not parse hour: '{}'", s))
.ok()
})
.unwrap_or(time.hour());
time.with_hour(hr)
};
match timed_type {
Timed::Hourly => {
debug!("Creating hourly-timed entry");
get_hourly_id(create)
},
Timed::Minutely => {
let time = get_hourly_id(create);
let min = create
.value_of("minute")
.map(|m| { debug!("minute = {:?}", m); m })
.and_then(|s| {
FromStr::from_str(s)
.map_err(|_| warn!("Could not parse minute: '{}'", s))
.ok()
})
.unwrap_or(time.minute());
time.with_minute(min)
},
}
}<|fim▁end|>
| |
<|file_name|>small-enum-range-edge.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// this is for the wrapping_add call below.
#![feature(core)]
/*!
* Tests the range assertion wraparound case in trans::middle::adt::load_discr.
*/
#[repr(u8)]
#[derive(Copy, Clone)]
enum Eu { Lu = 0, Hu = 255 }
static CLu: Eu = Eu::Lu;
static CHu: Eu = Eu::Hu;
#[repr(i8)]
#[derive(Copy, Clone)]
enum Es { Ls = -128, Hs = 127 }
static CLs: Es = Es::Ls;
static CHs: Es = Es::Hs;
pub fn main() {
assert_eq!((Eu::Hu as u8).wrapping_add(1), Eu::Lu as u8);
assert_eq!((Es::Hs as i8).wrapping_add(1), Es::Ls as i8);<|fim▁hole|>}<|fim▁end|>
|
assert_eq!(CLu as u8, Eu::Lu as u8);
assert_eq!(CHu as u8, Eu::Hu as u8);
assert_eq!(CLs as i8, Es::Ls as i8);
assert_eq!(CHs as i8, Es::Hs as i8);
|
<|file_name|>main.js<|end_file_name|><|fim▁begin|>'use strict';
/**
* @ngdoc function
* @name sbAdminApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the sbAdminApp
*/
angular.module('sbAdminApp')
.controller('MainCtrl', function($scope,$position) {
})
.controller('StoreCtrl',['$scope','$position','$state','XLSXReaderService',function ($scope,$position,$state,XLSXReaderService) {
console.log($state.params.id);
$scope.data = [{"UPC":"test"," Short Description":"test","Long description":"test","Store Price":111111,"Metric (ea or lb) ":12,"Department":"Vegetables","Sub-department ":"Fresh","Synonyms":"legumes"},{"UPC":"test2"," Short Description":"test2","Long description":"test2","Store Price":12222,"Metric (ea or lb) ":43,"Department":"Vegetables","Sub-department ":"Fresh","Synonyms":"legumes"}];
$scope.stores = [
{id:1, name:'Store 1'},
{id:2, name:'Store 2'},
{id:3, name:'Store 3'}
];
$scope.store = {};
$scope.saveStore = function (store) {
console.log(store);
store.id = $scope.stores.length + 1;
$scope.store = store;
$scope.stores.unshift(store);
$scope.store = {};
}
if($state.params.id){
$scope.store = _.find($scope.stores, function(chr) {
return chr.id = $state.params.id;
})
};
$scope.import = function (file) {
$scope.isProcessing = true;
$scope.sheets = [];
$scope.excelFile = file;
XLSXReaderService.readFile($scope.excelFile, true, false).then(function (xlsxData) {
$scope.sheets = xlsxData.sheets;
$scope.json_string = JSON.stringify($scope.sheets["Sheet1"], null, 2);
$scope.json_string = $scope.parseExcelData($scope.json_string);
$scope.data = $scope.json_string;
console.log(JSON.stringify($scope.data));
});
}
$scope.parseExcelData = function (json_string) {
var excelData = JSON.parse(json_string);
var headers = excelData.data[0];
var array = [];
for (var i = 1; i < excelData.data.length; i++) {
var item = excelData.data[i];
var element = {};<|fim▁hole|> if(item[j]!=null){
var propertyName = headers[j];
element[propertyName] = item[j];
}
}
array.push(element);
}
var list = array;
return list;
}
}]);<|fim▁end|>
|
for (var j = 0; j < item.length; j++) {
|
<|file_name|>Array.prototype.es6.js<|end_file_name|><|fim▁begin|>/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Array.prototype.es6
* @polyfill
* @nolint
*/
/* eslint-disable no-bitwise, no-extend-native, radix, no-self-compare */<|fim▁hole|>// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
function findIndex(predicate, context) {
if (this == null) {
throw new TypeError(
'Array.prototype.findIndex called on null or undefined'
);
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
const list = Object(this);
const length = list.length >>> 0;
for (let i = 0; i < length; i++) {
if (predicate.call(context, list[i], i, list)) {
return i;
}
}
return -1;
}
if (!Array.prototype.findIndex) {
Object.defineProperty(Array.prototype, 'findIndex', {
enumerable: false,
writable: true,
configurable: true,
value: findIndex,
});
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
enumerable: false,
writable: true,
configurable: true,
value(predicate, context) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
const index = findIndex.call(this, predicate, context);
return index === -1 ? undefined : this[index];
},
});
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
enumerable: false,
writable: true,
configurable: true,
value(searchElement) {
const O = Object(this);
const len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
const n = parseInt(arguments[1]) || 0;
let k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {
k = 0;
}
}
let currentElement;
while (k < len) {
currentElement = O[k];
if (
searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)
) {
return true;
}
k++;
}
return false;
},
});
}<|fim▁end|>
| |
<|file_name|>project.ts<|end_file_name|><|fim▁begin|>import {LoggerContext} from "../logging/logger-context";
import {ParameterContainer} from "../core/parameter-container";<|fim▁hole|>}<|fim▁end|>
|
export class Project {
private loggerContext = new LoggerContext();
private parameterContainer = new ParameterContainer();
|
<|file_name|>hdfs.py<|end_file_name|><|fim▁begin|>"""File system module."""
# Copyright 2014 Cloudera Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This file may adapt small portions of https://github.com/mtth/hdfs (MIT
# license), see the LICENSES directory.
import posixpath
from functools import wraps as implements
import ibis.common.exceptions as com
from ibis.config import options
class HDFSError(com.IbisError):
"""HDFS Error class."""
pass
class HDFS:
"""Interface class to HDFS.
Interface class to HDFS for ibis that abstracts away (and protects
user/developer against) various 3rd party library API differences.
"""
def exists(self, path: str) -> bool:
"""Check if the file exists.
Parameters
----------
path : string
Returns
-------
bool
Raises
------
NotImplementedError
"""
raise NotImplementedError
def status(self, path: str) -> dict:
"""Check if the status of the path.
Parameters
----------
path : string
Returns
-------
status : dict
Raises
------
NotImplementedError
"""
raise NotImplementedError
def chmod(self, hdfs_path: str, permissions: str):
"""Change permissions of a file of directory.
Parameters
----------
hdfs_path : string
Directory or path
permissions : string
Octal permissions string
Raises
------
NotImplementedError
"""
raise NotImplementedError
def chown(self, hdfs_path: str, owner: str = None, group: str = None):
"""Change owner (and/or group) of a file or directory.
Parameters
----------
hdfs_path : string
Directory or path
owner : string, optional
Name of owner
group : string, optional
Name of group
Raises
------
NotImplementedError
"""
raise NotImplementedError
def head(
self, hdfs_path: str, nbytes: int = 1024, offset: int = 0
) -> bytes:
"""Retrieve the requested number of bytes from a file.
Parameters
----------
hdfs_path : string
Absolute HDFS path
nbytes : int, default 1024 (1K)
Number of bytes to retrieve
offset : int, default 0
Number of bytes at beginning of file to skip before retrieving data
Returns
-------
head_data : bytes
Raises
------
NotImplementedError
"""
raise NotImplementedError
def get(
self, hdfs_path: str, local_path: str = '.', overwrite: bool = False
) -> str:
"""
Download remote file or directory to the local filesystem.
Parameters
----------
hdfs_path : string
local_path : string, default '.'
overwrite : bool, default False
Further keyword arguments passed down to any internal API used.
Returns
-------
written_path : string
The path to the written file or directory
Raises
------
NotImplementedError
"""
raise NotImplementedError
def put(
self,
hdfs_path: str,
resource,
overwrite: bool = False,
verbose: bool = None,
**kwargs,
) -> str:
"""
Write file or directory to HDFS.
Parameters
----------
hdfs_path : string
Directory or path
resource : string or buffer-like
Relative or absolute path to local resource, or a file-like object
overwrite : boolean, default False
verbose : boolean, default ibis options.verbose
Further keyword arguments passed down to any internal API used.
Returns
-------
written_path : string
The path to the written file or directory
Raises
------
NotImplementedError
"""
raise NotImplementedError
def put_tarfile(
self,
hdfs_path: str,
local_path: str,
compression: str = 'gzip',
verbose: bool = None,
overwrite: bool = False,
):
"""
Write contents of tar archive to HDFS.
Write contents of tar archive to HDFS directly without having to
decompress it locally first.
Parameters
----------
hdfs_path : string
local_path : string
compression : {'gzip', 'bz2', None}
overwrite : boolean, default False
verbose : boolean, default None (global default)
Raises
------
ValueError
if given compression is none of the following: None, gzip or bz2.
"""
import tarfile
modes = {None: 'r', 'gzip': 'r:gz', 'bz2': 'r:bz2'}
if compression not in modes:
raise ValueError(f'Invalid compression type {compression}')
mode = modes[compression]
tf = tarfile.open(local_path, mode=mode)
for info in tf:
if not info.isfile():
continue
buf = tf.extractfile(info)
abspath = posixpath.join(hdfs_path, info.path)
self.put(abspath, buf, verbose=verbose, overwrite=overwrite)
def put_zipfile(self, hdfs_path: str, local_path: str):
"""Write contents of zipfile archive to HDFS.
Parameters
----------
hdfs_path : string
local_path : string
Raises
------
NotImplementedError
"""
raise NotImplementedError
def write(
self,
hdfs_path: str,
buf,
overwrite: bool = False,
blocksize: int = None,
replication=None,
buffersize: int = None,
):
"""HDFS Write function.
Parameters
----------
hdfs_path : string
buf
overwrite : bool, defaul False
blocksize : int
replication
buffersize : int
Raises
------
NotImplementedError
"""
raise NotImplementedError
def mkdir(self, path: str):
"""Create new directory.
Parameters
----------
path : string
"""
pass
def ls(self, hdfs_path: str, status: bool = False) -> list:
"""Return contents of directory.
Parameters
----------
hdfs_path : string
status : bool
Returns
-------
list
Raises
------
NotImplementedError
"""
raise NotImplementedError
def size(self, hdfs_path: str) -> int:
"""Return total size of file or directory.
Parameters
----------
hdfs_path : basestring
Returns
-------
size : int
Raises
------
NotImplementedError
"""
raise NotImplementedError
def tail(self, hdfs_path: str, nbytes: int = 1024) -> bytes:
"""Retrieve the requested number of bytes from the end of a file.
Parameters
----------
hdfs_path : string
nbytes : int
Returns
-------
data_tail : bytes
Raises
------
NotImplementedError
"""
raise NotImplementedError
def mv(
self, hdfs_path_src: str, hdfs_path_dest: str, overwrite: bool = True
):
"""Move hdfs_path_src to hdfs_path_dest.
Parameters
----------
hdfs_path_src: string
hdfs_path_dest: string
overwrite : boolean, default True
Overwrite hdfs_path_dest if it exists.
Raises
------
NotImplementedError
"""
raise NotImplementedError
def cp(self, hdfs_path_src: str, hdfs_path_dest: str):
"""Copy hdfs_path_src to hdfs_path_dest.
Parameters
----------
hdfs_path_src : string
hdfs_path_dest : string
Raises
------
NotImplementedError
"""
raise NotImplementedError
def rm(self, path: str):
"""Delete a single file.
Parameters
----------
path : string
"""
return self.delete(path)
def rmdir(self, path: str):
"""Delete a directory and all its contents.
Parameters
----------
path : string
"""
self.client.delete(path, recursive=True)
def _find_any_file(self, hdfs_dir):
contents = self.ls(hdfs_dir, status=True)
def valid_filename(name):
head, tail = posixpath.split(name)
tail = tail.lower()
return (
not tail.endswith('.tmp')
and not tail.endswith('.copying')
and not tail.startswith('_')
and not tail.startswith('.')
)
for filename, meta in contents:
if meta['type'].lower() == 'file' and valid_filename(filename):
return filename
raise com.IbisError('No files found in the passed directory')
class WebHDFS(HDFS):
"""A WebHDFS-based interface to HDFS using the HDFSCli library."""
def __init__(self, client):
self.client = client
@property
def protocol(self) -> str:
"""Return the protocol used by WebHDFS.
Returns
-------
protocol : string
"""
return 'webhdfs'
def status(self, path: str) -> dict:
"""Retrieve HDFS metadata for path.
Parameters
----------
path : str
Returns
-------
status : dict
Client status
"""
return self.client.status(path)
@implements(HDFS.chmod)
def chmod(self, path: str, permissions: str):
"""Change the permissions of a HDFS file.
Parameters
----------
path : string
permissions : string
New octal permissions string of the file.
"""
self.client.set_permission(path, permissions)
@implements(HDFS.chown)
def chown(self, path: str, owner=None, group=None):
"""
Change the owner of a HDFS file.
At least one of `owner` and `group` must be specified.
Parameters
----------
hdfs_path : HDFS path.
owner : string, optional
group: string, optional
"""
self.client.set_owner(path, owner, group)
@implements(HDFS.exists)
def exists(self, path: str) -> dict:
"""Check if the HDFS file exists.
Parameters
----------
path : string
Returns
-------
bool
"""
return not self.client.status(path, strict=False) is None
@implements(HDFS.ls)
def ls(self, hdfs_path: str, status: bool = False) -> list:
"""Return contents of directory.
Parameters
----------
hdfs_path : string
status : bool
Returns
-------
list
"""
return self.client.list(hdfs_path, status=status)
@implements(HDFS.mkdir)
def mkdir(self, dir_path: str):
"""Create new directory.
Parameters
----------
path : string
"""
self.client.makedirs(dir_path)
@implements(HDFS.size)
def size(self, hdfs_path: str) -> int:
"""Return total size of file or directory.
Parameters
----------
hdfs_path : string
Returns
-------
size : int
"""
return self.client.content(hdfs_path)['length']
@implements(HDFS.mv)
def mv(
self, hdfs_path_src: str, hdfs_path_dest: str, overwrite: bool = True
):
"""Move hdfs_path_src to hdfs_path_dest.
Parameters
----------
hdfs_path_src: string
hdfs_path_dest: string
overwrite : boolean, default True
Overwrite hdfs_path_dest if it exists.
"""
if overwrite and self.exists(hdfs_path_dest):
if self.status(hdfs_path_dest)['type'] == 'FILE':
self.rm(hdfs_path_dest)
self.client.rename(hdfs_path_src, hdfs_path_dest)
def delete(self, hdfs_path: str, recursive: bool = False) -> bool:
"""Delete a file located at `hdfs_path`.
Parameters
----------
hdfs_path : string
recursive : bool, default False
Returns
-------
bool
True if the function was successful.
"""
return self.client.delete(hdfs_path, recursive=recursive)
@implements(HDFS.head)
def head(
self, hdfs_path: str, nbytes: int = 1024, offset: int = 0
) -> bytes:
"""Retrieve the requested number of bytes from a file.
Parameters
----------
hdfs_path : string
Absolute HDFS path
nbytes : int, default 1024 (1K)
Number of bytes to retrieve
offset : int, default 0
Number of bytes at beginning of file to skip before retrieving data
Returns
-------
head_data : bytes
"""
_reader = self.client.read(hdfs_path, offset=offset, length=nbytes)
with _reader as reader:
return reader.read()
@implements(HDFS.put)
def put(
self,
hdfs_path: str,
resource,
overwrite: bool = False,
verbose: bool = None,
**kwargs,
):
"""
Write file or directory to HDFS.
Parameters
----------
hdfs_path : string
Directory or path
resource : string or buffer-like
Relative or absolute path to local resource, or a file-like object
overwrite : boolean, default False
verbose : boolean, default ibis options.verbose
Further keyword arguments passed down to any internal API used.
Returns
-------
written_path : string
The path to the written file or directory
"""
verbose = verbose or options.verbose
if isinstance(resource, str):
# `resource` is a path.
return self.client.upload(
hdfs_path, resource, overwrite=overwrite, **kwargs
)
else:
# `resource` is a file-like object.
hdfs_path = self.client.resolve(hdfs_path)
self.client.write(
hdfs_path, data=resource, overwrite=overwrite, **kwargs
)
return hdfs_path
@implements(HDFS.get)
def get(
self,
hdfs_path: str,
local_path: str,
overwrite: bool = False,
verbose: bool = None,
**kwargs,
) -> str:
"""
Download remote file or directory to the local filesystem.
Parameters
----------
hdfs_path : string
local_path : string, default '.'
overwrite : bool, default False
Further keyword arguments passed down to any internal API used.
Returns
-------
written_path : string
The path to the written file or directory
"""
verbose = verbose or options.verbose
return self.client.download(
hdfs_path, local_path, overwrite=overwrite, **kwargs
)
def hdfs_connect(
host='localhost',
port=50070,
protocol='webhdfs',
use_https='default',
auth_mechanism='NOSASL',
verify=True,
session=None,
**kwds,
):
"""Connect to HDFS.
Parameters
----------
host : str
Host name of the HDFS NameNode
port : int
NameNode's WebHDFS port
protocol : str,
The protocol used to communicate with HDFS. The only valid value is
``'webhdfs'``.
use_https : bool
Connect to WebHDFS with HTTPS, otherwise plain HTTP. For secure
authentication, the default for this is True, otherwise False.
auth_mechanism : str
Set to NOSASL or PLAIN for non-secure clusters.
Set to GSSAPI or LDAP for Kerberos-secured clusters.
verify : bool
Set to :data:`False` to turn off verifying SSL certificates.
session : Optional[requests.Session]
A custom :class:`requests.Session` object.
Notes
-----
Other keywords are forwarded to HDFS library classes.
Returns
-------
WebHDFS
"""
import requests<|fim▁hole|>
if session is None:
session = requests.Session()
session.verify = verify
if auth_mechanism in ('GSSAPI', 'LDAP'):
from hdfs.ext.kerberos import KerberosClient
if use_https == 'default':
prefix = 'https'
else:
prefix = 'https' if use_https else 'http'
# note SSL
url = f'{prefix}://{host}:{port}'
kwds.setdefault('mutual_auth', 'OPTIONAL')
hdfs_client = KerberosClient(url, session=session, **kwds)
else:
if use_https == 'default':
prefix = 'http'
else:
prefix = 'https' if use_https else 'http'
from hdfs.client import InsecureClient
url = f'{prefix}://{host}:{port}'
hdfs_client = InsecureClient(url, session=session, **kwds)
return WebHDFS(hdfs_client)<|fim▁end|>
| |
<|file_name|>LassoLarsIC.py<|end_file_name|><|fim▁begin|># Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Created on Jan 21, 2020
@author: alfoa, wangc
Lasso model fit with Lars using BIC or AIC for model selection.
"""
#Internal Modules (Lazy Importer)--------------------------------------------------------------------
#Internal Modules (Lazy Importer) End----------------------------------------------------------------
#External Modules------------------------------------------------------------------------------------
from numpy import finfo
#External Modules End--------------------------------------------------------------------------------
#Internal Modules------------------------------------------------------------------------------------
from SupervisedLearning.ScikitLearn import ScikitLearnBase<|fim▁hole|> """
Lasso model fit with Lars using BIC or AIC for model selection
"""
info = {'problemtype':'regression', 'normalize':False}
def __init__(self):
"""
Constructor that will appropriately initialize a supervised learning object
@ In, None
@ Out, None
"""
super().__init__()
import sklearn
import sklearn.linear_model
self.model = sklearn.linear_model.LassoLarsIC
@classmethod
def getInputSpecification(cls):
"""
Method to get a reference to a class that specifies the input data for
class cls.
@ In, cls, the class for which we are retrieving the specification
@ Out, inputSpecification, InputData.ParameterInput, class to use for
specifying input of cls.
"""
specs = super(LassoLarsIC, cls).getInputSpecification()
specs.description = r"""The \xmlNode{LassoLarsIC} (\textit{Lasso model fit with Lars using BIC or AIC for model selection})
is a Lasso model fit with Lars using BIC or AIC for model selection.
The optimization objective for Lasso is:
$(1 / (2 * n\_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1$
AIC is the Akaike information criterion and BIC is the Bayes Information criterion. Such criteria
are useful to select the value of the regularization parameter by making a trade-off between the
goodness of fit and the complexity of the model. A good model should explain well the data
while being simple.
\zNormalizationNotPerformed{LassoLarsIC}
"""
specs.addSub(InputData.parameterInputFactory("criterion", contentType=InputTypes.makeEnumType("criterion", "criterionType",['bic', 'aic']),
descr=r"""The type of criterion to use.""", default='aic'))
specs.addSub(InputData.parameterInputFactory("fit_intercept", contentType=InputTypes.BoolType,
descr=r"""Whether the intercept should be estimated or not. If False,
the data is assumed to be already centered.""", default=True))
specs.addSub(InputData.parameterInputFactory("normalize", contentType=InputTypes.BoolType,
descr=r"""This parameter is ignored when fit_intercept is set to False. If True,
the regressors X will be normalized before regression by subtracting the mean and
dividing by the l2-norm.""", default=True))
specs.addSub(InputData.parameterInputFactory("max_iter", contentType=InputTypes.IntegerType,
descr=r"""The maximum number of iterations.""", default=500))
specs.addSub(InputData.parameterInputFactory("precompute", contentType=InputTypes.StringType,
descr=r"""Whether to use a precomputed Gram matrix to speed up calculations.
For sparse input this option is always True to preserve sparsity.""", default='auto'))
specs.addSub(InputData.parameterInputFactory("eps", contentType=InputTypes.FloatType,
descr=r"""The machine-precision regularization in the computation of the Cholesky
diagonal factors. Increase this for very ill-conditioned systems. Unlike the tol
parameter in some iterative optimization-based algorithms, this parameter does not
control the tolerance of the optimization.""", default=finfo(float).eps))
specs.addSub(InputData.parameterInputFactory("positive", contentType=InputTypes.BoolType,
descr=r"""When set to True, forces the coefficients to be positive.""", default=False))
specs.addSub(InputData.parameterInputFactory("verbose", contentType=InputTypes.BoolType,
descr=r"""Amount of verbosity.""", default=False))
return specs
def _handleInput(self, paramInput):
"""
Function to handle the common parts of the distribution parameter input.
@ In, paramInput, ParameterInput, the already parsed input.
@ Out, None
"""
super()._handleInput(paramInput)
settings, notFound = paramInput.findNodesAndExtractValues(['fit_intercept','max_iter', 'normalize', 'precompute',
'eps','positive','criterion', 'verbose'])
# notFound must be empty
assert(not notFound)
self.initializeModel(settings)<|fim▁end|>
|
from utils import InputData, InputTypes
#Internal Modules End--------------------------------------------------------------------------------
class LassoLarsIC(ScikitLearnBase):
|
<|file_name|>event.rs<|end_file_name|><|fim▁begin|>use system::memory;
<|fim▁hole|>
pub fn set_event_cancel(b: bool) {
memory::write(0x803BD3A3, b);
}<|fim▁end|>
|
pub fn event_cancel() -> bool {
memory::read(0x803BD3A3)
}
|
<|file_name|>owner.go<|end_file_name|><|fim▁begin|>package pod
import (
"fmt"
"strings"
lru "github.com/hashicorp/golang-lru"
"github.com/rancher/norman/api/access"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/values"
"github.com/rancher/rancher/pkg/controllers/managementagent/workload"
"github.com/rancher/rancher/pkg/ref"
schema "github.com/rancher/rancher/pkg/schemas/project.cattle.io/v3"
"github.com/sirupsen/logrus"
)
var (
ownerCache, _ = lru.New(100000)
)
type key struct {<|fim▁hole|> Kind string
Name string
}
type value struct {
Kind string
Name string
}
func getOwnerWithKind(apiContext *types.APIContext, namespace, ownerKind, name string) (string, string, error) {
subContext := apiContext.SubContext["/v3/schemas/project"]
if subContext == "" {
subContext = apiContext.SubContext["/v3/schemas/cluster"]
}
if subContext == "" {
logrus.Warnf("failed to find subcontext to lookup replicaSet owner")
return "", "", nil
}
key := key{
SubContext: subContext,
Namespace: namespace,
Kind: strings.ToLower(ownerKind),
Name: name,
}
val, ok := ownerCache.Get(key)
if ok {
value, _ := val.(value)
return value.Kind, value.Name, nil
}
data := map[string]interface{}{}
if err := access.ByID(apiContext, &schema.Version, ownerKind, ref.FromStrings(namespace, name), &data); err != nil {
return "", "", err
}
kind, name := getOwner(data)
if !workload.WorkloadKinds[kind] {
kind = ""
name = ""
}
ownerCache.Add(key, value{
Kind: kind,
Name: name,
})
return kind, name, nil
}
func getOwner(data map[string]interface{}) (string, string) {
ownerReferences, ok := values.GetSlice(data, "ownerReferences")
if !ok {
return "", ""
}
for _, ownerReference := range ownerReferences {
controller, _ := ownerReference["controller"].(bool)
if !controller {
continue
}
kind, _ := ownerReference["kind"].(string)
name, _ := ownerReference["name"].(string)
return kind, name
}
return "", ""
}
func SaveOwner(apiContext *types.APIContext, kind, name string, data map[string]interface{}) {
parentKind, parentName := getOwner(data)
namespace, _ := data["namespaceId"].(string)
subContext := apiContext.SubContext["/v3/schemas/project"]
if subContext == "" {
subContext = apiContext.SubContext["/v3/schemas/cluster"]
}
if subContext == "" {
return
}
key := key{
SubContext: subContext,
Namespace: namespace,
Kind: strings.ToLower(kind),
Name: name,
}
ownerCache.Add(key, value{
Kind: parentKind,
Name: parentName,
})
}
func resolveWorkloadID(apiContext *types.APIContext, data map[string]interface{}) string {
kind, name := getOwner(data)
if kind == "" || !workload.WorkloadKinds[kind] {
return ""
}
namespace, _ := data["namespaceId"].(string)
if ownerKind := strings.ToLower(kind); ownerKind == workload.ReplicaSetType || ownerKind == workload.JobType {
k, n, err := getOwnerWithKind(apiContext, namespace, ownerKind, name)
if err != nil {
return ""
}
if k != "" {
kind, name = k, n
}
}
return strings.ToLower(fmt.Sprintf("%s:%s:%s", kind, namespace, name))
}<|fim▁end|>
|
SubContext string
Namespace string
|
<|file_name|>test_sqlstore.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import os
from misura.canon import option
from misura.canon.option import get_typed_cols, get_insert_cmd, base_col_def, print_tree
import sqlite3
from misura.canon.tests import testdir
db = testdir + 'storage/tmpdb'
c1 = testdir + 'storage/Conf.csv'
def go(t):
o = option.Option(**{'handle': t, 'type': t})
o.validate()
return o
class SqlStore(unittest.TestCase):
@classmethod
def setUpClass(cls):
if os.path.exists(db):
os.remove(db)
cls.conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES)
st0 = option.CsvStore(kid='/base/')
st0.merge_file(c1)
st0.validate()
cls.desc = st0.desc
def test_get_typed_cols(self):
print(get_typed_cols(go('Integer')))
print(get_typed_cols(go('String')))
print(get_typed_cols(go('Point')))
print(get_typed_cols(go('Role')))
print(get_typed_cols(go('RoleIO')))
print(get_typed_cols(go('Log')))
print(get_typed_cols(go('Meta')))
def test_get_insert_cmd(self):
print(get_insert_cmd(go('Integer'), base_col_def))
print(get_insert_cmd(go('String'), base_col_def))
print(get_insert_cmd(go('Point'), base_col_def))
print(get_insert_cmd(go('Role'), base_col_def))
print(get_insert_cmd(go('RoleIO'), base_col_def))
print(get_insert_cmd(go('Log'), base_col_def))
print(get_insert_cmd(go('Meta'), base_col_def))
def test_column_definition(self):
s = option.SqlStore()
print(s.column_definition(go('Integer'))[1])
print(s.column_definition(go('String'))[1])
print(s.column_definition(go('Point'))[1])
print(s.column_definition(go('Role'))[1])
print(s.column_definition(go('RoleIO'))[1])
print(s.column_definition(go('Log'))[1])
print(s.column_definition(go('Meta'))[1])
<|fim▁hole|> s = option.SqlStore()
s.cursor = self.conn.cursor()
s.write_desc(self.desc)
print('READING')
r = s.read_tree()
print(r)
print('print(tree\n', print_tree(r))
print('WRITING AGAIN')
s.write_tree(r)
print("READING AGAIN")
r = s.read_tree()
print(r)
print('print(tree2\n', print_tree(r))
# @unittest.skip('')
def test_tables(self):
st0 = option.CsvStore(kid='ciao')
st0.merge_file(c1)
st = option.SqlStore(kid='ciao')
st.desc = st0.desc
k0 = set(st.desc.keys())
cursor = self.conn.cursor()
st.write_table(cursor, 'conf1')
self.conn.commit()
cursor.execute('select handle from conf1')
r = cursor.fetchall()
k1 = set([eval(k[0]) for k in r])
self.assertEqual(k0, k1)
st2 = option.SqlStore(kid='ciao')
st2.read_table(cursor, 'conf1')
self.assertEqual(st.desc, st2.desc)
if __name__ == "__main__":
unittest.main()<|fim▁end|>
|
def test_write_desc(self):
|
<|file_name|>app.component.ts<|end_file_name|><|fim▁begin|>// #docregion pt1
import {Component} from 'angular2/core';
// #docregion hero-class-1
export class Hero {
id: number;
name: string;
}
// #enddocregion hero-class-1
@Component({
selector: 'my-app',
template:`
<h1>{{title}}</h1><|fim▁hole|> <div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name">
</div>
`
})
export class AppComponent {
title = 'Tour of Heroes';
hero: Hero = {
id: 1,
name: 'Windstorm'
};
}
// #enddocregion pt1<|fim▁end|>
|
<h2>{{hero.name}} details!</h2>
|
<|file_name|>media_queries.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Gecko's media-query device and expression representation.
use app_units::AU_PER_PX;
use app_units::Au;
use context::QuirksMode;
use cssparser::{CssStringWriter, Parser, RGBA, Token, BasicParseError};
use euclid::ScaleFactor;
use euclid::Size2D;
use font_metrics::get_metrics_provider_for_product;
use gecko::values::{convert_nscolor_to_rgba, convert_rgba_to_nscolor};
use gecko_bindings::bindings;
use gecko_bindings::structs;
use gecko_bindings::structs::{nsCSSKeyword, nsCSSProps_KTableEntry, nsCSSValue, nsCSSUnit};
use gecko_bindings::structs::{nsMediaExpression_Range, nsMediaFeature};
use gecko_bindings::structs::{nsMediaFeature_ValueType, nsMediaFeature_RangeType, nsMediaFeature_RequirementFlags};
use gecko_bindings::structs::{nsPresContext, RawGeckoPresContextOwned};
use gecko_bindings::structs::nsIAtom;
use media_queries::MediaType;
use parser::ParserContext;
use properties::{ComputedValues, StyleBuilder};
use properties::longhands::font_size;
use rule_cache::RuleCacheConditions;
use servo_arc::Arc;
use std::cell::RefCell;
use std::fmt::{self, Write};
use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicUsize, Ordering};
use str::starts_with_ignore_ascii_case;
use string_cache::Atom;
use style_traits::{CSSPixel, DevicePixel};
use style_traits::{ToCss, ParseError, StyleParseError};
use style_traits::viewport::ViewportConstraints;
use values::{CSSFloat, CustomIdent, serialize_dimension};
use values::computed::{self, ToComputedValue};
use values::specified::Length;
/// The `Device` in Gecko wraps a pres context, has a default values computed,
/// and contains all the viewport rule state.
pub struct Device {
/// NB: The pres context lifetime is tied to the styleset, who owns the
/// stylist, and thus the `Device`, so having a raw pres context pointer
/// here is fine.
pres_context: RawGeckoPresContextOwned,
default_values: Arc<ComputedValues>,
/// The font size of the root element
/// This is set when computing the style of the root
/// element, and used for rem units in other elements.
///
/// When computing the style of the root element, there can't be any
/// other style being computed at the same time, given we need the style of
/// the parent to compute everything else. So it is correct to just use
/// a relaxed atomic here.
root_font_size: AtomicIsize,
/// The body text color, stored as an `nscolor`, used for the "tables
/// inherit from body" quirk.
///
/// https://quirks.spec.whatwg.org/#the-tables-inherit-color-from-body-quirk
body_text_color: AtomicUsize,
/// Whether any styles computed in the document relied on the root font-size
/// by using rem units.
used_root_font_size: AtomicBool,
/// Whether any styles computed in the document relied on the viewport size
/// by using vw/vh/vmin/vmax units.
used_viewport_size: AtomicBool,
}
unsafe impl Sync for Device {}
unsafe impl Send for Device {}
impl Device {
/// Trivially constructs a new `Device`.
pub fn new(pres_context: RawGeckoPresContextOwned) -> Self {
assert!(!pres_context.is_null());
Device {
pres_context: pres_context,
default_values: ComputedValues::default_values(unsafe { &*pres_context }),
// FIXME(bz): Seems dubious?
root_font_size: AtomicIsize::new(font_size::get_initial_value().0.to_i32_au() as isize),
body_text_color: AtomicUsize::new(unsafe { &*pres_context }.mDefaultColor as usize),
used_root_font_size: AtomicBool::new(false),
used_viewport_size: AtomicBool::new(false),
}
}
/// Tells the device that a new viewport rule has been found, and stores the
/// relevant viewport constraints.
pub fn account_for_viewport_rule(
&mut self,
_constraints: &ViewportConstraints
) {
unreachable!("Gecko doesn't support @viewport");
}
/// Returns the default computed values as a reference, in order to match
/// Servo.
pub fn default_computed_values(&self) -> &ComputedValues {
&self.default_values
}
/// Returns the default computed values as an `Arc`.
pub fn default_computed_values_arc(&self) -> &Arc<ComputedValues> {
&self.default_values
}
/// Get the font size of the root element (for rem)
pub fn root_font_size(&self) -> Au {
self.used_root_font_size.store(true, Ordering::Relaxed);
Au::new(self.root_font_size.load(Ordering::Relaxed) as i32)
}
/// Set the font size of the root element (for rem)
pub fn set_root_font_size(&self, size: Au) {
self.root_font_size.store(size.0 as isize, Ordering::Relaxed)
}
/// Sets the body text color for the "inherit color from body" quirk.
///
/// https://quirks.spec.whatwg.org/#the-tables-inherit-color-from-body-quirk
pub fn set_body_text_color(&self, color: RGBA) {
self.body_text_color.store(convert_rgba_to_nscolor(&color) as usize, Ordering::Relaxed)
}
/// Returns the body text color.
pub fn body_text_color(&self) -> RGBA {
convert_nscolor_to_rgba(self.body_text_color.load(Ordering::Relaxed) as u32)
}
/// Gets the pres context associated with this document.
pub fn pres_context(&self) -> &nsPresContext {
unsafe { &*self.pres_context }
}
/// Recreates the default computed values.
pub fn reset_computed_values(&mut self) {
self.default_values = ComputedValues::default_values(self.pres_context());
}
/// Rebuild all the cached data.
pub fn rebuild_cached_data(&mut self) {
self.reset_computed_values();
self.used_root_font_size.store(false, Ordering::Relaxed);
self.used_viewport_size.store(false, Ordering::Relaxed);
}
/// Returns whether we ever looked up the root font size of the Device.
pub fn used_root_font_size(&self) -> bool {
self.used_root_font_size.load(Ordering::Relaxed)
}
/// Recreates all the temporary state that the `Device` stores.
///
/// This includes the viewport override from `@viewport` rules, and also the
/// default computed values.
pub fn reset(&mut self) {
self.reset_computed_values();
}
/// Returns the current media type of the device.
pub fn media_type(&self) -> MediaType {
unsafe {
// Gecko allows emulating random media with mIsEmulatingMedia and
// mMediaEmulated.
let context = self.pres_context();
let medium_to_use = if context.mIsEmulatingMedia() != 0 {
context.mMediaEmulated.raw::<nsIAtom>()
} else {
context.mMedium
};
MediaType(CustomIdent(Atom::from(medium_to_use)))
}
}
/// Returns the current viewport size in app units.
pub fn au_viewport_size(&self) -> Size2D<Au> {
let area = &self.pres_context().mVisibleArea;
Size2D::new(Au(area.width), Au(area.height))
}
/// Returns the current viewport size in app units, recording that it's been
/// used for viewport unit resolution.
pub fn au_viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> {
self.used_viewport_size.store(true, Ordering::Relaxed);
self.au_viewport_size()
}
/// Returns whether we ever looked up the viewport size of the Device.
pub fn used_viewport_size(&self) -> bool {
self.used_viewport_size.load(Ordering::Relaxed)
}
/// Returns the device pixel ratio.
pub fn device_pixel_ratio(&self) -> ScaleFactor<f32, CSSPixel, DevicePixel> {
let override_dppx = self.pres_context().mOverrideDPPX;
if override_dppx > 0.0 { return ScaleFactor::new(override_dppx); }
let au_per_dpx = self.pres_context().mCurAppUnitsPerDevPixel as f32;
let au_per_px = AU_PER_PX as f32;
ScaleFactor::new(au_per_px / au_per_dpx)
}
/// Returns whether document colors are enabled.
pub fn use_document_colors(&self) -> bool {
self.pres_context().mUseDocumentColors() != 0
}
/// Returns the default background color.
pub fn default_background_color(&self) -> RGBA {
convert_nscolor_to_rgba(self.pres_context().mBackgroundColor)
}
/// Applies text zoom to a font-size or line-height value (see nsStyleFont::ZoomText).
pub fn zoom_text(&self, size: Au) -> Au {
size.scale_by(self.pres_context().mEffectiveTextZoom)
}
/// Un-apply text zoom (see nsStyleFont::UnzoomText).
pub fn unzoom_text(&self, size: Au) -> Au {
size.scale_by(1. / self.pres_context().mEffectiveTextZoom)
}
}
/// A expression for gecko contains a reference to the media feature, the value
/// the media query contained, and the range to evaluate.
#[derive(Clone, Debug)]
pub struct Expression {
feature: &'static nsMediaFeature,
value: Option<MediaExpressionValue>,
range: nsMediaExpression_Range
}
impl ToCss for Expression {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
dest.write_str("(")?;
if (self.feature.mReqFlags & nsMediaFeature_RequirementFlags::eHasWebkitPrefix as u8) != 0 {
dest.write_str("-webkit-")?;
}
match self.range {
nsMediaExpression_Range::eMin => dest.write_str("min-")?,
nsMediaExpression_Range::eMax => dest.write_str("max-")?,
nsMediaExpression_Range::eEqual => {},
}
// NB: CssStringWriter not needed, feature names are under control.
write!(dest, "{}", Atom::from(unsafe { *self.feature.mName }))?;
if let Some(ref val) = self.value {
dest.write_str(": ")?;
val.to_css(dest, self)?;
}
dest.write_str(")")
}
}
impl PartialEq for Expression {
fn eq(&self, other: &Expression) -> bool {
self.feature.mName == other.feature.mName &&
self.value == other.value && self.range == other.range
}
}
/// A resolution.
#[derive(Clone, Debug, PartialEq)]
pub enum Resolution {
/// Dots per inch.
Dpi(CSSFloat),
/// Dots per pixel.
Dppx(CSSFloat),
/// Dots per centimeter.
Dpcm(CSSFloat),
}
impl Resolution {
fn to_dpi(&self) -> CSSFloat {
match *self {
Resolution::Dpi(f) => f,
Resolution::Dppx(f) => f * 96.0,
Resolution::Dpcm(f) => f * 2.54,
}
}
fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
let (value, unit) = match *input.next()? {
Token::Dimension { value, ref unit, .. } => {
(value, unit)
},
ref t => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
};
if value <= 0. {
return Err(StyleParseError::UnspecifiedError.into())
}
(match_ignore_ascii_case! { &unit,
"dpi" => Ok(Resolution::Dpi(value)),
"dppx" => Ok(Resolution::Dppx(value)),
"dpcm" => Ok(Resolution::Dpcm(value)),
_ => Err(())
}).map_err(|()| StyleParseError::UnexpectedDimension(unit.clone()).into())
}
}
impl ToCss for Resolution {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
match *self {
Resolution::Dpi(v) => serialize_dimension(v, "dpi", dest),
Resolution::Dppx(v) => serialize_dimension(v, "dppx", dest),
Resolution::Dpcm(v) => serialize_dimension(v, "dpcm", dest),
}
}
}
/// A value found or expected in a media expression.
#[derive(Clone, Debug, PartialEq)]
pub enum MediaExpressionValue {
/// A length.
Length(Length),
/// A (non-negative) integer.
Integer(u32),
/// A floating point value.
Float(CSSFloat),
/// A boolean value, specified as an integer (i.e., either 0 or 1).
BoolInteger(bool),
/// Two integers separated by '/', with optional whitespace on either side
/// of the '/'.
IntRatio(u32, u32),
/// A resolution.
Resolution(Resolution),
/// An enumerated value, defined by the variant keyword table in the
/// feature's `mData` member.
Enumerated(i16),
/// An identifier.
///
/// TODO(emilio): Maybe atomize?
Ident(String),
}
impl MediaExpressionValue {
fn from_css_value(for_expr: &Expression, css_value: &nsCSSValue) -> Option<Self> {
use gecko::conversions::string_from_chars_pointer;
// NB: If there's a null value, that means that we don't support the
// feature.
if css_value.mUnit == nsCSSUnit::eCSSUnit_Null {
return None;
}
match for_expr.feature.mValueType {
nsMediaFeature_ValueType::eLength => {
debug_assert!(css_value.mUnit == nsCSSUnit::eCSSUnit_Pixel);
let pixels = css_value.float_unchecked();
Some(MediaExpressionValue::Length(Length::from_px(pixels)))
}
nsMediaFeature_ValueType::eInteger => {
let i = css_value.integer_unchecked();
debug_assert!(i >= 0);
Some(MediaExpressionValue::Integer(i as u32))
}
nsMediaFeature_ValueType::eFloat => {
debug_assert!(css_value.mUnit == nsCSSUnit::eCSSUnit_Number);
Some(MediaExpressionValue::Float(css_value.float_unchecked()))
}
nsMediaFeature_ValueType::eBoolInteger => {
debug_assert!(css_value.mUnit == nsCSSUnit::eCSSUnit_Integer);
let i = css_value.integer_unchecked();
debug_assert!(i == 0 || i == 1);
Some(MediaExpressionValue::BoolInteger(i == 1))
}
nsMediaFeature_ValueType::eResolution => {
debug_assert!(css_value.mUnit == nsCSSUnit::eCSSUnit_Inch);
Some(MediaExpressionValue::Resolution(Resolution::Dpi(css_value.float_unchecked())))
}
nsMediaFeature_ValueType::eEnumerated => {
let value = css_value.integer_unchecked() as i16;
Some(MediaExpressionValue::Enumerated(value))
}
nsMediaFeature_ValueType::eIdent => {
debug_assert!(css_value.mUnit == nsCSSUnit::eCSSUnit_Ident);
let string = unsafe {
let buffer = *css_value.mValue.mString.as_ref();
debug_assert!(!buffer.is_null());
string_from_chars_pointer(buffer.offset(1) as *const u16)
};
Some(MediaExpressionValue::Ident(string))
}
nsMediaFeature_ValueType::eIntRatio => {
let array = unsafe { css_value.array_unchecked() };
debug_assert_eq!(array.len(), 2);
let first = array[0].integer_unchecked();
let second = array[1].integer_unchecked();
debug_assert!(first >= 0 && second >= 0);
Some(MediaExpressionValue::IntRatio(first as u32, second as u32))
}
}
}
}
impl MediaExpressionValue {
fn to_css<W>(&self, dest: &mut W, for_expr: &Expression) -> fmt::Result
where W: fmt::Write,
{
match *self {
MediaExpressionValue::Length(ref l) => l.to_css(dest),
MediaExpressionValue::Integer(v) => v.to_css(dest),
MediaExpressionValue::Float(v) => v.to_css(dest),
MediaExpressionValue::BoolInteger(v) => {
dest.write_str(if v { "1" } else { "0" })
},
MediaExpressionValue::IntRatio(a, b) => {
a.to_css(dest)?;
dest.write_char('/')?;
b.to_css(dest)
},
MediaExpressionValue::Resolution(ref r) => r.to_css(dest),
MediaExpressionValue::Ident(ref ident) => {
CssStringWriter::new(dest).write_str(ident)
}
MediaExpressionValue::Enumerated(value) => unsafe {
use std::{slice, str};
use std::os::raw::c_char;
// NB: All the keywords on nsMediaFeatures are static,
// well-formed utf-8.
let mut length = 0;
let (keyword, _value) =
find_in_table(*for_expr.feature.mData.mKeywordTable.as_ref(),
|_kw, val| val == value)
.expect("Value not found in the keyword table?");
let buffer: *const c_char =
bindings::Gecko_CSSKeywordString(keyword, &mut length);
let buffer =
slice::from_raw_parts(buffer as *const u8, length as usize);
let string = str::from_utf8_unchecked(buffer);
dest.write_str(string)
}
}
}
}
fn find_feature<F>(mut f: F) -> Option<&'static nsMediaFeature>
where F: FnMut(&'static nsMediaFeature) -> bool,
{
unsafe {
let mut features = structs::nsMediaFeatures_features.as_ptr();
while !(*features).mName.is_null() {
if f(&*features) {
return Some(&*features);
}
features = features.offset(1);
}
}
None
}
unsafe fn find_in_table<F>(mut current_entry: *const nsCSSProps_KTableEntry,
mut f: F)
-> Option<(nsCSSKeyword, i16)>
where F: FnMut(nsCSSKeyword, i16) -> bool
{
loop {
let value = (*current_entry).mValue;
let keyword = (*current_entry).mKeyword;
if value == -1 {
return None; // End of the table.
}
if f(keyword, value) {
return Some((keyword, value));
}
current_entry = current_entry.offset(1);
}
}
fn parse_feature_value<'i, 't>(feature: &nsMediaFeature,
feature_value_type: nsMediaFeature_ValueType,
context: &ParserContext,
input: &mut Parser<'i, 't>)
-> Result<MediaExpressionValue, ParseError<'i>> {
let value = match feature_value_type {
nsMediaFeature_ValueType::eLength => {
let length = Length::parse_non_negative(context, input)?;
// FIXME(canaltinova): See bug 1396057. Gecko doesn't support calc
// inside media queries. This check is for temporarily remove it
// for parity with gecko. We should remove this check when we want
// to support it.
if let Length::Calc(_) = length {
return Err(StyleParseError::UnspecifiedError.into())
}
MediaExpressionValue::Length(length)
},
nsMediaFeature_ValueType::eInteger => {
// FIXME(emilio): We should use `Integer::parse` to handle `calc`
// properly in integer expressions. Note that calc is still not
// supported in media queries per FIXME above.
let i = input.expect_integer()?;
if i < 0 {
return Err(StyleParseError::UnspecifiedError.into())
}
MediaExpressionValue::Integer(i as u32)
}
nsMediaFeature_ValueType::eBoolInteger => {
let i = input.expect_integer()?;
if i < 0 || i > 1 {
return Err(StyleParseError::UnspecifiedError.into())
}
MediaExpressionValue::BoolInteger(i == 1)
}
nsMediaFeature_ValueType::eFloat => {
MediaExpressionValue::Float(input.expect_number()?)
}
nsMediaFeature_ValueType::eIntRatio => {
let a = input.expect_integer()?;
if a <= 0 {
return Err(StyleParseError::UnspecifiedError.into())
}
input.expect_delim('/')?;
let b = input.expect_integer()?;
if b <= 0 {
return Err(StyleParseError::UnspecifiedError.into())
}
MediaExpressionValue::IntRatio(a as u32, b as u32)
}
nsMediaFeature_ValueType::eResolution => {
MediaExpressionValue::Resolution(Resolution::parse(input)?)
}
nsMediaFeature_ValueType::eEnumerated => {
let keyword = input.expect_ident()?;
let keyword = unsafe {
bindings::Gecko_LookupCSSKeyword(keyword.as_bytes().as_ptr(),
keyword.len() as u32)
};
let first_table_entry: *const nsCSSProps_KTableEntry = unsafe {
*feature.mData.mKeywordTable.as_ref()
};
let value =
match unsafe { find_in_table(first_table_entry, |kw, _| kw == keyword) } {
Some((_kw, value)) => {
value
}
None => return Err(StyleParseError::UnspecifiedError.into()),
};
MediaExpressionValue::Enumerated(value)
}
nsMediaFeature_ValueType::eIdent => {
MediaExpressionValue::Ident(input.expect_ident()?.as_ref().to_owned())
}
};
Ok(value)
}
impl Expression {
/// Trivially construct a new expression.
fn new(feature: &'static nsMediaFeature,
value: Option<MediaExpressionValue>,
range: nsMediaExpression_Range) -> Self {
Expression {
feature: feature,
value: value,
range: range,
}
}
<|fim▁hole|> /// (media-feature: media-value)
/// ```
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
input.expect_parenthesis_block().map_err(|err|
match err {
BasicParseError::UnexpectedToken(t) => StyleParseError::ExpectedIdentifier(t),
_ => StyleParseError::UnspecifiedError,
}
)?;
input.parse_nested_block(|input| {
// FIXME: remove extra indented block when lifetimes are non-lexical
let feature;
let range;
{
let ident = input.expect_ident().map_err(|err|
match err {
BasicParseError::UnexpectedToken(t) => StyleParseError::ExpectedIdentifier(t),
_ => StyleParseError::UnspecifiedError,
}
)?;
let mut flags = 0;
let result = {
let mut feature_name = &**ident;
if unsafe { structs::StylePrefs_sWebkitPrefixedAliasesEnabled } &&
starts_with_ignore_ascii_case(feature_name, "-webkit-") {
feature_name = &feature_name[8..];
flags |= nsMediaFeature_RequirementFlags::eHasWebkitPrefix as u8;
if unsafe { structs::StylePrefs_sWebkitDevicePixelRatioEnabled } {
flags |= nsMediaFeature_RequirementFlags::eWebkitDevicePixelRatioPrefEnabled as u8;
}
}
let range = if starts_with_ignore_ascii_case(feature_name, "min-") {
feature_name = &feature_name[4..];
nsMediaExpression_Range::eMin
} else if starts_with_ignore_ascii_case(feature_name, "max-") {
feature_name = &feature_name[4..];
nsMediaExpression_Range::eMax
} else {
nsMediaExpression_Range::eEqual
};
let atom = Atom::from(feature_name);
match find_feature(|f| atom.as_ptr() == unsafe { *f.mName }) {
Some(f) => Ok((f, range)),
None => Err(()),
}
};
match result {
Ok((f, r)) => {
feature = f;
range = r;
},
Err(()) => {
return Err(StyleParseError::MediaQueryExpectedFeatureName(ident.clone()).into())
},
}
if (feature.mReqFlags & !flags) != 0 {
return Err(StyleParseError::MediaQueryExpectedFeatureName(ident.clone()).into());
}
if range != nsMediaExpression_Range::eEqual &&
feature.mRangeType != nsMediaFeature_RangeType::eMinMaxAllowed {
return Err(StyleParseError::MediaQueryExpectedFeatureName(ident.clone()).into());
}
}
// If there's no colon, this is a media query of the form
// '(<feature>)', that is, there's no value specified.
//
// Gecko doesn't allow ranged expressions without a value, so just
// reject them here too.
if input.try(|i| i.expect_colon()).is_err() {
if range != nsMediaExpression_Range::eEqual {
return Err(StyleParseError::RangedExpressionWithNoValue.into())
}
return Ok(Expression::new(feature, None, range));
}
let value = parse_feature_value(feature,
feature.mValueType,
context, input).map_err(|_|
StyleParseError::MediaQueryExpectedFeatureValue
)?;
Ok(Expression::new(feature, Some(value), range))
})
}
/// Returns whether this media query evaluates to true for the given device.
pub fn matches(&self, device: &Device, quirks_mode: QuirksMode) -> bool {
let mut css_value = nsCSSValue::null();
unsafe {
(self.feature.mGetter.unwrap())(device.pres_context,
self.feature,
&mut css_value)
};
let value = match MediaExpressionValue::from_css_value(self, &css_value) {
Some(v) => v,
None => return false,
};
self.evaluate_against(device, &value, quirks_mode)
}
fn evaluate_against(&self,
device: &Device,
actual_value: &MediaExpressionValue,
quirks_mode: QuirksMode)
-> bool {
use self::MediaExpressionValue::*;
use std::cmp::Ordering;
debug_assert!(self.range == nsMediaExpression_Range::eEqual ||
self.feature.mRangeType == nsMediaFeature_RangeType::eMinMaxAllowed,
"Whoops, wrong range");
let default_values = device.default_computed_values();
let provider = get_metrics_provider_for_product();
// http://dev.w3.org/csswg/mediaqueries3/#units
// em units are relative to the initial font-size.
let mut conditions = RuleCacheConditions::default();
let context = computed::Context {
is_root_element: false,
builder: StyleBuilder::for_derived_style(device, default_values, None, None),
font_metrics_provider: &provider,
cached_system_font: None,
in_media_query: true,
// TODO: pass the correct value here.
quirks_mode: quirks_mode,
for_smil_animation: false,
for_non_inherited_property: None,
rule_cache_conditions: RefCell::new(&mut conditions),
};
let required_value = match self.value {
Some(ref v) => v,
None => {
// If there's no value, always match unless it's a zero length
// or a zero integer or boolean.
return match *actual_value {
BoolInteger(v) => v,
Integer(v) => v != 0,
Length(ref l) => l.to_computed_value(&context).px() != 0.,
_ => true,
}
}
};
// FIXME(emilio): Handle the possible floating point errors?
let cmp = match (required_value, actual_value) {
(&Length(ref one), &Length(ref other)) => {
one.to_computed_value(&context).to_i32_au()
.cmp(&other.to_computed_value(&context).to_i32_au())
}
(&Integer(one), &Integer(ref other)) => one.cmp(other),
(&BoolInteger(one), &BoolInteger(ref other)) => one.cmp(other),
(&Float(one), &Float(ref other)) => one.partial_cmp(other).unwrap(),
(&IntRatio(one_num, one_den), &IntRatio(other_num, other_den)) => {
// Extend to avoid overflow.
(one_num as u64 * other_den as u64).cmp(
&(other_num as u64 * one_den as u64))
}
(&Resolution(ref one), &Resolution(ref other)) => {
let actual_dpi = unsafe {
if (*device.pres_context).mOverrideDPPX > 0.0 {
self::Resolution::Dppx((*device.pres_context).mOverrideDPPX)
.to_dpi()
} else {
other.to_dpi()
}
};
one.to_dpi().partial_cmp(&actual_dpi).unwrap()
}
(&Ident(ref one), &Ident(ref other)) => {
debug_assert!(self.feature.mRangeType != nsMediaFeature_RangeType::eMinMaxAllowed);
return one == other;
}
(&Enumerated(one), &Enumerated(other)) => {
debug_assert!(self.feature.mRangeType != nsMediaFeature_RangeType::eMinMaxAllowed);
return one == other;
}
_ => unreachable!(),
};
cmp == Ordering::Equal || match self.range {
nsMediaExpression_Range::eMin => cmp == Ordering::Less,
nsMediaExpression_Range::eEqual => false,
nsMediaExpression_Range::eMax => cmp == Ordering::Greater,
}
}
}<|fim▁end|>
|
/// Parse a media expression of the form:
///
/// ```
|
<|file_name|>event.rs<|end_file_name|><|fim▁begin|>use events;
pub fn vkeycode_to_element(code: u16) -> Option<events::VirtualKeyCode> {
Some(match code {
0x00 => events::VirtualKeyCode::A,
0x01 => events::VirtualKeyCode::S,
0x02 => events::VirtualKeyCode::D,
0x03 => events::VirtualKeyCode::F,
0x04 => events::VirtualKeyCode::H,
0x05 => events::VirtualKeyCode::G,
0x06 => events::VirtualKeyCode::Z,
0x07 => events::VirtualKeyCode::X,
0x08 => events::VirtualKeyCode::C,
0x09 => events::VirtualKeyCode::V,
//0x0a => World 1,
0x0b => events::VirtualKeyCode::B,
0x0c => events::VirtualKeyCode::Q,
0x0d => events::VirtualKeyCode::W,
0x0e => events::VirtualKeyCode::E,
0x0f => events::VirtualKeyCode::R,
0x10 => events::VirtualKeyCode::Y,
0x11 => events::VirtualKeyCode::T,
0x12 => events::VirtualKeyCode::Key1,
0x13 => events::VirtualKeyCode::Key2,
0x14 => events::VirtualKeyCode::Key3,<|fim▁hole|> 0x17 => events::VirtualKeyCode::Key5,
0x18 => events::VirtualKeyCode::Equals,
0x19 => events::VirtualKeyCode::Key9,
0x1a => events::VirtualKeyCode::Key7,
0x1b => events::VirtualKeyCode::Minus,
0x1c => events::VirtualKeyCode::Key8,
0x1d => events::VirtualKeyCode::Key0,
0x1e => events::VirtualKeyCode::RBracket,
0x1f => events::VirtualKeyCode::O,
0x20 => events::VirtualKeyCode::U,
0x21 => events::VirtualKeyCode::LBracket,
0x22 => events::VirtualKeyCode::I,
0x23 => events::VirtualKeyCode::P,
0x24 => events::VirtualKeyCode::Return,
0x25 => events::VirtualKeyCode::L,
0x26 => events::VirtualKeyCode::J,
0x27 => events::VirtualKeyCode::Apostrophe,
0x28 => events::VirtualKeyCode::K,
0x29 => events::VirtualKeyCode::Semicolon,
0x2a => events::VirtualKeyCode::Backslash,
0x2b => events::VirtualKeyCode::Comma,
0x2c => events::VirtualKeyCode::Slash,
0x2d => events::VirtualKeyCode::N,
0x2e => events::VirtualKeyCode::M,
0x2f => events::VirtualKeyCode::Period,
0x30 => events::VirtualKeyCode::Tab,
0x31 => events::VirtualKeyCode::Space,
0x32 => events::VirtualKeyCode::Grave,
0x33 => events::VirtualKeyCode::Back,
//0x34 => unkown,
0x35 => events::VirtualKeyCode::Escape,
0x36 => events::VirtualKeyCode::RWin,
0x37 => events::VirtualKeyCode::LWin,
0x38 => events::VirtualKeyCode::LShift,
//0x39 => Caps lock,
//0x3a => Left alt,
0x3b => events::VirtualKeyCode::LControl,
0x3c => events::VirtualKeyCode::RShift,
//0x3d => Right alt,
0x3e => events::VirtualKeyCode::RControl,
//0x3f => Fn key,
//0x40 => F17 Key,
0x41 => events::VirtualKeyCode::Decimal,
//0x42 -> unkown,
0x43 => events::VirtualKeyCode::Multiply,
//0x44 => unkown,
0x45 => events::VirtualKeyCode::Add,
//0x46 => unkown,
0x47 => events::VirtualKeyCode::Numlock,
//0x48 => KeypadClear,
0x49 => events::VirtualKeyCode::VolumeUp,
0x4a => events::VirtualKeyCode::VolumeDown,
0x4b => events::VirtualKeyCode::Divide,
0x4c => events::VirtualKeyCode::NumpadEnter,
//0x4d => unkown,
0x4e => events::VirtualKeyCode::Subtract,
//0x4f => F18 key,
//0x50 => F19 Key,
0x51 => events::VirtualKeyCode::NumpadEquals,
0x52 => events::VirtualKeyCode::Numpad0,
0x53 => events::VirtualKeyCode::Numpad1,
0x54 => events::VirtualKeyCode::Numpad2,
0x55 => events::VirtualKeyCode::Numpad3,
0x56 => events::VirtualKeyCode::Numpad4,
0x57 => events::VirtualKeyCode::Numpad5,
0x58 => events::VirtualKeyCode::Numpad6,
0x59 => events::VirtualKeyCode::Numpad7,
//0x5a => F20 Key,
0x5b => events::VirtualKeyCode::Numpad8,
0x5c => events::VirtualKeyCode::Numpad9,
//0x5d => unkown,
//0x5e => unkown,
//0x5f => unkown,
0x60 => events::VirtualKeyCode::F5,
0x61 => events::VirtualKeyCode::F6,
0x62 => events::VirtualKeyCode::F7,
0x63 => events::VirtualKeyCode::F3,
0x64 => events::VirtualKeyCode::F8,
0x65 => events::VirtualKeyCode::F9,
//0x66 => unkown,
0x67 => events::VirtualKeyCode::F11,
//0x68 => unkown,
0x69 => events::VirtualKeyCode::F13,
//0x6a => F16 Key,
0x6b => events::VirtualKeyCode::F14,
//0x6c => unkown,
0x6d => events::VirtualKeyCode::F10,
//0x6e => unkown,
0x6f => events::VirtualKeyCode::F12,
//0x70 => unkown,
0x71 => events::VirtualKeyCode::F15,
0x72 => events::VirtualKeyCode::Insert,
0x73 => events::VirtualKeyCode::Home,
0x74 => events::VirtualKeyCode::PageUp,
0x75 => events::VirtualKeyCode::Delete,
0x76 => events::VirtualKeyCode::F4,
0x77 => events::VirtualKeyCode::End,
0x78 => events::VirtualKeyCode::F2,
0x79 => events::VirtualKeyCode::PageDown,
0x7a => events::VirtualKeyCode::F1,
0x7b => events::VirtualKeyCode::Left,
0x7c => events::VirtualKeyCode::Right,
0x7d => events::VirtualKeyCode::Down,
0x7e => events::VirtualKeyCode::Up,
//0x7f => unkown,
_ => return None,
})
}<|fim▁end|>
|
0x15 => events::VirtualKeyCode::Key4,
0x16 => events::VirtualKeyCode::Key6,
|
<|file_name|>grift.go<|end_file_name|><|fim▁begin|>package grift
import (
"fmt"
"io"
"log"
"os"
"sort"
"sync"
"time"
)
var CommandName = "grift"
var griftList = map[string]Grift{}
var descriptions = map[string]string{}
var lock = &sync.Mutex{}
type Grift func(c *Context) error
// Add a grift. If there is already a grift
// with the given name the two grifts will
// be bundled together.
func Add(name string, grift Grift) error {
lock.Lock()
defer lock.Unlock()
if griftList[name] != nil {
fn := griftList[name]
griftList[name] = func(c *Context) error {
err := fn(c)
if err != nil {
return err
}
return grift(c)
}
} else {
griftList[name] = grift
}
return nil
}
// Set a grift. This is similar to `Add` but it will
// overwrite an existing grift with the same name.
func Set(name string, grift Grift) error {
lock.Lock()
defer lock.Unlock()
griftList[name] = grift
return nil
}
// Rename a grift. Useful if you want to re-define
// an existing grift, but don't want to write over
// the original.
func Rename(old string, new string) error {
lock.Lock()
defer lock.Unlock()
if griftList[old] == nil {
return fmt.Errorf("No task named %s defined!", old)
}
griftList[new] = griftList[old]
delete(griftList, old)
return nil
}
// Remove a grift. Not incredibly useful, but here for
// completeness.
func Remove(name string) error {
lock.Lock()
defer lock.Unlock()
delete(griftList, name)
delete(descriptions, name)
return nil
}
// Desc sets a helpful descriptive text for a grift.
// This description will be shown when `grift list`
// is run.
func Desc(name string, description string) error {
lock.Lock()
defer lock.Unlock()
descriptions[name] = description
return nil
}
// Run a grift. This allows for the chaining for grifts.
// One grift can Run another grift and so on.
func Run(name string, c *Context) error {
if griftList[name] == nil {
return fmt.Errorf("No task named '%s' defined!", name)
}
if c.Verbose {
defer func(start time.Time) {
log.Printf("Completed task %s in %s\n", name, time.Now().Sub(start))
}(time.Now())
log.Printf("Starting task %s\n", name)
}
return griftList[name](c)
}
// List of the names of the defined grifts.
func List() []string {
keys := []string{}
for k := range griftList {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// Exec the grift stack. This is the main "entry point" to
// the grift system.
func Exec(args []string, verbose bool) error {
name := "default"
if len(args) >= 1 {
name = args[0]
}
switch name {
case "list":
PrintGrifts(os.Stdout)
default:
c := NewContext(name)
c.Verbose = verbose
if len(args) >= 1 {
c.Args = args[1:]
}<|fim▁hole|>}
// PrintGrifts to the screen, nice, sorted, and with descriptions,
// should they exist.
func PrintGrifts(w io.Writer) {
for _, k := range List() {
m := fmt.Sprintf("%s %s", CommandName, k)
desc := descriptions[k]
if desc != "" {
m = fmt.Sprintf("%s | %s", m, desc)
}
fmt.Fprintln(w, m)
}
}<|fim▁end|>
|
return Run(name, c)
}
return nil
|
<|file_name|>isset-unset.js<|end_file_name|><|fim▁begin|>var expect = require('chai').expect,
Model = require('../lib/model');
describe('attribute initial state', function () {
var ModelClass, NestedClass;
before(function () {
NestedClass = Model.inherit({
attributes: {
a: Model.attributeTypes.String.inherit({
default: 'a'
})
}
});
ModelClass = Model.inherit({
attributes: {
a: Model.attributeTypes.String.inherit({
default: 'a'
}),
nested: Model.attributeTypes.Model(NestedClass),
collection: Model.attributeTypes.ModelsList(NestedClass)
}
});
});
describe('isSet', function () {
it('should be false if attribute was not set', function () {
var model = new ModelClass();
expect(model.isSet('a')).to.be.equal(false);
});
it('should be false if attribute was initialized with null value', function () {
var model = new ModelClass({a: null});
expect(model.isSet('a')).to.be.equal(false);
});
it('should be true if attribute was set when inited', function () {
var model = new ModelClass({
a: 'a'
});
expect(model.isSet('a')).to.be.equal(true);
});
it('should be true if attribute was set', function () {
var model = new ModelClass();
model.set('a', true);
expect(model.isSet('a')).to.be.equal(true);
});
it('should be false after set and revert', function () {
var model = new ModelClass();
model.set('a', true);
model.revert();
expect(model.isSet('a')).to.be.equal(false);
});
it('should be true after set, commit and revert', function () {
var model = new ModelClass();
model.set('a', true);
model.revert();
expect(model.isSet('a')).to.be.equal(false);
});
});
describe('unset', function () {<|fim▁hole|> model.unset('a');
expect(model.get('a')).to.be.equal('a');
});
it('should make isSet to be false', function () {
var model = new ModelClass({
a: 'a-1'
});
model.unset('a');
expect(model.isSet('a')).to.be.equal(false);
});
it('should emit change', function (done) {
var model = new ModelClass({
a: 'a-1'
});
model.ready().then(function () {
model.on('change:a', function () {
done();
});
model.unset('a');
}).done();
});
});
describe('set', function () {
it('should unset when setting null', function () {
var model = new ModelClass({
a: 'a-1'
});
model.set('a', null);
expect(model.get('a')).to.be.equal('a');
});
});
});<|fim▁end|>
|
it('should change value to default', function () {
var model = new ModelClass({
a: 'a-1'
});
|
<|file_name|>sliplink.py<|end_file_name|><|fim▁begin|># Copyright (c) 2007-2017 Joseph Hager.
#
# Copycat is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License,<|fim▁hole|># WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Copycat; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
"""Sliplink"""
class Sliplink(object):
"""Sliplink is a link between two nodes in the slipnet.
Attributes:
from_node: The node this link starts at.
to_node: The node this link ends at.
label: The node that labels this link.
fixed_length: A static length of the link has no label."""
def __init__(self, from_node, to_node, label, fixed_length):
"""Initializes Sliplink."""
self.from_node = from_node
self.to_node = to_node
self.label = label
self.fixed_length = fixed_length
def intrinsic_degree_of_association(self):
"""Return the intrinsic degree of association of the link."""
if self.fixed_length != None:
return 100 - self.fixed_length
else:
return self.label.intrinsic_degree_of_association()
def degree_of_association(self):
"""Return the degree of association of the link."""
if self.fixed_length != None:
return 100 - self.fixed_length
else:
return self.label.degree_of_association()<|fim▁end|>
|
# as published by the Free Software Foundation.
#
# Copycat is distributed in the hope that it will be useful, but
|
<|file_name|>channel_collection_type_manager.hh<|end_file_name|><|fim▁begin|>/**
\file "Object/inst/channel_collection_type_manager.hh"
Template class for instance_collection's type manager.
$Id: channel_collection_type_manager.hh,v 1.3 2007/04/15 05:52:17 fang Exp $
*/
#ifndef __HAC_OBJECT_INST_CHANNEL_COLLECTION_TYPE_MANAGER_H__
#define __HAC_OBJECT_INST_CHANNEL_COLLECTION_TYPE_MANAGER_H__
#include <iosfwd>
#include "Object/type/canonical_type_fwd.hh" // for conditional
#include "util/persistent_fwd.hh"
#include "util/boolean_types.hh"
#include "util/memory/pointer_classes_fwd.hh"
#include "Object/devel_switches.hh"
namespace HAC {
namespace entity {
class const_param_expr_list;
using std::istream;
using std::ostream;
using util::good_bool;
using util::bad_bool;
using util::persistent_object_manager;
using util::memory::count_ptr;
class footprint;
template <class> struct class_traits;
//=============================================================================
/**
Generic instance collection type manager for classes with
full type references as type information.
Not appropriate for built-in types.
*/
template <class Tag>
class channel_collection_type_manager {
private:
typedef channel_collection_type_manager<Tag> this_type;
typedef class_traits<Tag> traits_type;
protected:
typedef typename traits_type::instance_collection_generic_type
instance_collection_generic_type;
typedef typename traits_type::instance_collection_parameter_type
instance_collection_parameter_type;
typedef typename traits_type::type_ref_ptr_type
type_ref_ptr_type;
typedef typename traits_type::resolved_type_ref_type
resolved_type_ref_type;
/**
The type parameter is ONLY a definition.
*/
instance_collection_parameter_type type_parameter;
struct dumper;
void
collect_transient_info_base(persistent_object_manager&) const;
void
write_object_base(const persistent_object_manager&, ostream&) const;
void
load_object_base(const persistent_object_manager&, istream&);
public:
const instance_collection_parameter_type&
__get_raw_type(void) const { return this->type_parameter; }
resolved_type_ref_type
get_resolved_canonical_type(void) const;
/**
No-op, channels don't have process footprints.
*/
good_bool
complete_type_definition_footprint(
const count_ptr<const const_param_expr_list>&) const {
return good_bool(true);
}
bool
is_complete_type(void) const { return this->type_parameter; }
bool
is_relaxed_type(void) const { return false; }
/// built-in channels don't have process footprints
static
good_bool
create_definition_footprint(
const instance_collection_parameter_type&,
const footprint& /* top */) {
return good_bool(true);
}
protected:
/**
NOTE: called during connection checking.
*/
bool<|fim▁hole|> bad_bool
check_type(const instance_collection_parameter_type&) const;
/**
\param t type must be resolved constant.
\pre first time called for the collection.
*/
good_bool
commit_type_first_time(const instance_collection_parameter_type& t);
}; // end struct channel_collection_type_manager
//=============================================================================
} // end namespace entity
} // end namespace HAC
#endif // __HAC_OBJECT_INST_CHANNEL_COLLECTION_TYPE_MANAGER_H__<|fim▁end|>
|
must_be_collectibly_type_equivalent(const this_type&) const;
|
<|file_name|>size.rs<|end_file_name|><|fim▁begin|>use internal;
#[repr(C)]
#[derive(Debug, PartialEq, PartialOrd, Copy, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Size {
pub width: f32,
pub height: f32,
}
impl From<Size> for internal::YGSize {
fn from(s: Size) -> internal::YGSize {
internal::YGSize {
width: s.width,
height: s.height,
}<|fim▁hole|> }
}<|fim▁end|>
| |
<|file_name|>unique_list.hh<|end_file_name|><|fim▁begin|>// {{{ GPL License
// This file is part of gringo - a grounder for logic programs.
// Copyright (C) 2013 Roland Kaminski
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU 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 General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// }}}
#ifndef _GRINGO_UNIQUE_LIST_HH
#define _GRINGO_UNIQUE_LIST_HH
#include <functional>
#include <algorithm>
#include <memory>
#include <cassert>
#include <gringo/utility.hh>
namespace Gringo {
// {{{ declaration of unique_list
template <class Value>
struct unique_list_node {
template <class... Args>
explicit unique_list_node(Args&&... args)
: value(std::forward<Args>(args)...)
, hash(0)
, succ(nullptr)
, prev(nullptr) { }
using node_type = unique_list_node;
using node_ptr_type = std::unique_ptr<node_type>;
Value value;
size_t hash;
unique_list_node *succ;
unique_list_node *prev;
node_ptr_type eqSucc;
};
template <class Value>
class unique_list_iterator : public std::iterator<std::bidirectional_iterator_tag, Value, int> {
using iterator = std::iterator<std::bidirectional_iterator_tag, Value, int>;
public:
template <class V, class X, class H, class E>
friend struct unique_list;
template <class V>
friend struct unique_list_const_iterator;
unique_list_iterator() : _node(nullptr) { }
unique_list_iterator(unique_list_iterator const &x) = default;
unique_list_iterator& operator=(const unique_list_iterator&) = default;
bool operator==(const unique_list_iterator &x) const { return _node == x._node; }
bool operator!=(const unique_list_iterator &x) const { return _node != x._node; }
unique_list_iterator& operator++() {
_node = _node->succ;
return *this;
}
unique_list_iterator operator++(int) {
unique_list_iterator x = *this;
++(*this);
return x;
}
unique_list_iterator& operator--() {
_node = _node->prev;
return *this;
}
unique_list_iterator operator--(int) {
unique_list_iterator x = *this;
--(*this);
return x;
}
typename iterator::reference operator*() const { return _node->value; }
typename iterator::pointer operator->() const { return &_node->value; }
private:
using node_type = unique_list_node<Value>;
unique_list_iterator(node_type *node) : _node(node) { }
node_type *_node;
};
template <class Value>
class unique_list_const_iterator : public std::iterator<std::bidirectional_iterator_tag, Value const, int> {
using iterator = std::iterator<std::bidirectional_iterator_tag, Value const, int>;
public:
template <class V, class X, class H, class E>
friend struct unique_list;
unique_list_const_iterator() : _node(nullptr) { }
unique_list_const_iterator(unique_list_const_iterator const &x) = default;
unique_list_const_iterator(unique_list_iterator<Value> const &x) : _node(x._node) { }
unique_list_const_iterator& operator=(const unique_list_const_iterator&) = default;
bool operator==(const unique_list_const_iterator &x) const { return _node == x._node; }
bool operator!=(const unique_list_const_iterator &x) const { return _node != x._node; }
unique_list_const_iterator& operator++() {
_node = _node->succ;
return *this;
}
unique_list_const_iterator operator++(int) {
unique_list_const_iterator x = *this;
++(*this);
return x;
}
unique_list_const_iterator& operator--() {
_node = _node->prev;
return *this;
}
unique_list_const_iterator operator--(int) {
unique_list_const_iterator x = *this;
--(*this);
return x;
}
typename iterator::reference operator*() const { return _node->value; }
typename iterator::pointer operator->() const { return &_node->value; }
private:
using node_type = unique_list_node<Value>;
unique_list_const_iterator(node_type *node) : _node(node) { }
node_type *_node;
};
template <class T>
struct identity {
using result_type = T;
template <class U>
T const &operator()(U const &x) const { return x; }
};
template <class T>
struct extract_first {
using result_type = T;
template <class U>
T const &operator()(U const &x) const { return std::get<0>(x); }
};
template <
class Value,
class ExtractKey = identity<Value>,
class Hasher = std::hash<typename ExtractKey::result_type>,
class EqualTo = std::equal_to<typename ExtractKey::result_type>
>
class unique_list : Hasher, EqualTo, ExtractKey {
using node_type = unique_list_node<Value>;
using node_ptr_type = typename node_type::node_ptr_type;
using buckets_type = std::unique_ptr<node_ptr_type[]>;
public:
using hasher = Hasher;
using key_equal = EqualTo;
using key_extract = ExtractKey;
using key_type = typename key_extract::result_type;
using value_type = Value;
using reference = Value &;
using const_reference = Value const &;
using difference_type = int;
using size_type = unsigned;
using iterator = unique_list_iterator<Value>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_iterator = unique_list_const_iterator<Value>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
unique_list()
: _size(0)
, _reserved(0)
, _front(0)
, _back(0)
, _buckets(nullptr) { }
unique_list(unique_list &&list)
: hasher(std::move(list))
, key_equal(std::move(list))
, _size(list._size)
, _reserved(list._reserved)
, _front(list._front)
, _back(list._back)
, _buckets(std::move(list._buckets)) { list.clear(); }
unique_list &operator=(unique_list &&list) {
static_cast<Hasher&>(*this) = std::move(list);
static_cast<EqualTo&>(*this) = std::move(list);
_size = list._size;
_reserved = list._reserved;
_front = list._front;
_back = list._back;
_buckets = std::move(list._buckets);
list.clear();
return *this;
}
unsigned reserved() const { return _reserved; }
unsigned size() const { return _size; }
bool empty() const { return !_size; }
double max_load_factor() const { return 0.9; }
double load_factor() const { return (size() + 1.0) / reserved(); }
void clear() {
_size = 0;
_reserved = 0;
_front = nullptr;
_back = nullptr;
_buckets.reset(nullptr);
}
void reserve(unsigned n) {
if (_reserved < n) {
unsigned reserved(_reserved * 1.5);
if (n < 5 || (reserved <= n)) { reserved = n; }
else {
do { reserved *= 1.5; }
while (reserved < n);
}
if (_buckets) {
buckets_type buckets(new node_ptr_type[reserved]);
std::swap(reserved, _reserved);
std::swap(buckets, _buckets);
for (auto it = buckets.get(), ie = buckets.get() + reserved; it != ie; ++it) {
node_ptr_type pos{std::move(*it)};
while (pos) {
node_ptr_type next{std::move(pos->eqSucc)};
move(std::move(pos));
pos = std::move(next);
}
}
}
else {
_buckets.reset(new node_ptr_type[reserved]);
_reserved = reserved;
}
}
}
template <class... Args>
std::pair<iterator, bool> emplace_back(Args&&... args) {
if (load_factor() >= max_load_factor()) { reserve(reserved() + 1); }
node_ptr_type node(new node_type(std::forward<Args>(args)...));
node->hash = static_cast<hasher&>(*this)(static_cast<key_extract&>(*this)(node->value));
return push_back(std::move(node));
}
iterator erase(const_iterator x) {
(x._node->prev ? x._node->prev->succ : _front) = x._node->succ;
(x._node->succ ? x._node->succ->prev : _back ) = x._node->prev;
iterator ret(x._node->succ);
std::reference_wrapper<node_ptr_type> pos{get_bucket(x._node->hash)};
while (pos.get().get() != x._node) { pos = pos.get()->eqSucc; }
pos.get() = std::move(pos.get()->eqSucc);
--_size;
return ret;
}
size_type erase(key_type const &x) {
auto it(static_cast<unique_list const*>(this)->find(x));
if (it != end()) {
erase(it);
return 1;
}
else { return 0; }
}
iterator erase(const_iterator a, const_iterator b) {
if (a != b) {
(a._node->prev ? a._node->prev->succ : _front) = b._node;
(b._node ? b._node->prev : _back ) = a._node->prev;
while (a != b) {
auto c = a++;
std::reference_wrapper<node_ptr_type> pos{get_bucket(c._node->hash)};
while (pos.get().get() != c._node) { pos = pos.get()->eqSucc; }
pos.get() = std::move(pos.get()->eqSucc);
--_size;
}
}
return b._node;
}
void swap(unique_list &list) {
std::swap(static_cast<hasher&>(*this), static_cast<hasher&>(list));
std::swap(static_cast<key_equal&>(*this), static_cast<key_equal&>(list));
std::swap(static_cast<key_extract&>(*this), static_cast<key_extract&>(list));
std::swap(_size, list._size);
std::swap(_reserved, list._reserved);
std::swap(_front, list._front);
std::swap(_back, list._back);
std::swap(_buckets, list._buckets);
}
iterator find(key_type const &x) {
return static_cast<unique_list const*>(this)->find(x)._node;
}
const_iterator find(key_type const &x) const {
if (!empty()) {
std::reference_wrapper<node_ptr_type> pos{get_bucket((this->*(&Hasher::operator()))(x))};
while (pos.get()) {
if (static_cast<key_equal const &>(*this)(
static_cast<key_extract const &>(*this)(pos.get()->value),
x
)) { return pos.get().get(); }
pos = pos.get()->eqSucc;
}
}
return end();
}<|fim▁hole|> iterator end() { return iterator(); }
reverse_iterator rbegin() { return reverse_iterator(end()); }
reverse_iterator rend() { return reverse_iterator(begin()); }
const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
value_type const &front() const { return _front->value; }
value_type const &back() const { return _back->value; }
value_type &front() { return _front->value; }
value_type &back() { return _back->value; }
private:
std::pair<iterator, bool> push_back(node_ptr_type&& node) {
std::reference_wrapper<node_ptr_type> pos{get_bucket(node)};
while (pos.get()) {
if (static_cast<key_equal&>(*this)(
static_cast<key_extract&>(*this)(pos.get()->value),
static_cast<key_extract&>(*this)(node->value))) { return {iterator(pos.get().get()), false}; }
pos = pos.get()->eqSucc;
}
pos.get() = std::move(node);
++_size;
if (_back) {
pos.get()->prev = _back;
_back->succ = pos.get().get();
}
else { _front = pos.get().get(); }
_back = pos.get().get();
return {iterator(pos.get().get()), true};
}
node_ptr_type& get_bucket(size_t hash) const {
assert(_reserved);
return _buckets[hash_mix(hash) % _reserved];
}
node_ptr_type& get_bucket(node_ptr_type const &node) const {
assert(_reserved);
return get_bucket(node->hash);
}
void move(node_ptr_type&& node) {
node_ptr_type& ret = get_bucket(node);
node->eqSucc = std::move(ret);
ret = std::move(node);
}
unsigned _size;
unsigned _reserved;
node_type *_front;
node_type *_back;
buckets_type _buckets;
};
// }}}
} // namespace Gringo
#endif // _GRINGO_UNIQUE_LIST_HH<|fim▁end|>
|
const_iterator begin() const { return const_iterator(_front); }
const_iterator end() const { return const_iterator(); }
iterator begin() { return iterator(_front); }
|
<|file_name|>Utils.java<|end_file_name|><|fim▁begin|>/*<|fim▁hole|> * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.mgt.util;
import org.apache.axiom.om.util.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.mgt.IdentityMgtConfig;
import org.wso2.carbon.identity.mgt.constants.IdentityMgtConstants;
import org.wso2.carbon.identity.mgt.dto.UserDTO;
import org.wso2.carbon.identity.mgt.internal.IdentityMgtServiceComponent;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.user.api.Tenant;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.UserCoreConstants;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager;
import org.wso2.carbon.user.core.util.UserCoreUtil;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.io.ByteArrayInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
/**
*
*/
public class Utils {
private static final Log log = LogFactory.getLog(Utils.class);
private Utils() {
}
public static UserDTO processUserId(String userId) throws IdentityException {
if (userId == null || userId.trim().length() < 1) {
throw IdentityException.error("Can not proceed with out a user id");
}
UserDTO userDTO = new UserDTO(userId);
if (!IdentityMgtConfig.getInstance().isSaasEnabled()) {
validateTenant(userDTO);
}
userDTO.setTenantId(getTenantId(userDTO.getTenantDomain()));
return userDTO;
}
public static void validateTenant(UserDTO user) throws IdentityException {
if (user.getTenantDomain() != null && !user.getTenantDomain().isEmpty()) {
if (!user.getTenantDomain().equals(
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.getTenantDomain())) {
throw IdentityException.error(
"Failed access to unauthorized tenant domain");
}
user.setTenantId(getTenantId(user.getTenantDomain()));
}
}
/**
* gets no of verified user challenges
*
* @param userDTO bean class that contains user and tenant Information
* @return no of verified challenges
* @throws IdentityException if fails
*/
public static int getVerifiedChallenges(UserDTO userDTO) throws IdentityException {
int noOfChallenges = 0;
try {
UserRegistry registry = IdentityMgtServiceComponent.getRegistryService().
getConfigSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
String identityKeyMgtPath = IdentityMgtConstants.IDENTITY_MANAGEMENT_CHALLENGES +
RegistryConstants.PATH_SEPARATOR + userDTO.getUserId() +
RegistryConstants.PATH_SEPARATOR + userDTO.getUserId();
Resource resource;
if (registry.resourceExists(identityKeyMgtPath)) {
resource = registry.get(identityKeyMgtPath);
String property = resource.getProperty(IdentityMgtConstants.VERIFIED_CHALLENGES);
if (property != null) {
return Integer.parseInt(property);
}
}
} catch (RegistryException e) {
log.error("Error while processing userKey", e);
}
return noOfChallenges;
}
/**
* gets the tenant id from the tenant domain
*
* @param domain - tenant domain name
* @return tenantId
* @throws IdentityException if fails or tenant doesn't exist
*/
public static int getTenantId(String domain) throws IdentityException {
int tenantId;
TenantManager tenantManager = IdentityMgtServiceComponent.getRealmService().getTenantManager();
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(domain)) {
tenantId = MultitenantConstants.SUPER_TENANT_ID;
if (log.isDebugEnabled()) {
String msg = "Domain is not defined implicitly. So it is Super Tenant domain.";
log.debug(msg);
}
} else {
try {
tenantId = tenantManager.getTenantId(domain);
if (tenantId < 1 && tenantId != MultitenantConstants.SUPER_TENANT_ID) {
String msg = "This action can not be performed by the users in non-existing domains.";
log.error(msg);
throw IdentityException.error(msg);
}
} catch (org.wso2.carbon.user.api.UserStoreException e) {
String msg = "Error in retrieving tenant id of tenant domain: " + domain + ".";
log.error(msg, e);
throw IdentityException.error(msg, e);
}
}
return tenantId;
}
/**
* Get the claims from the user store manager
*
* @param userName user name
* @param tenantId tenantId
* @param claim claim name
* @return claim value
* @throws IdentityException if fails
*/
public static String getClaimFromUserStoreManager(String userName, int tenantId, String claim)
throws IdentityException {
org.wso2.carbon.user.core.UserStoreManager userStoreManager = null;
RealmService realmService = IdentityMgtServiceComponent.getRealmService();
String claimValue = "";
try {
if (realmService.getTenantUserRealm(tenantId) != null) {
userStoreManager = (org.wso2.carbon.user.core.UserStoreManager) realmService.getTenantUserRealm(tenantId).
getUserStoreManager();
}
} catch (Exception e) {
String msg = "Error retrieving the user store manager for tenant id : " + tenantId;
log.error(msg, e);
throw IdentityException.error(msg, e);
}
try {
if (userStoreManager != null) {
Map<String, String> claimsMap = userStoreManager
.getUserClaimValues(userName, new String[]{claim}, UserCoreConstants.DEFAULT_PROFILE);
if (claimsMap != null && !claimsMap.isEmpty()) {
claimValue = claimsMap.get(claim);
}
}
return claimValue;
} catch (Exception e) {
String msg = "Unable to retrieve the claim for user : " + userName;
log.error(msg, e);
throw IdentityException.error(msg, e);
}
}
public static Map<String,String> getClaimsFromUserStoreManager(String userName, int tenantId, String[] claims)
throws IdentityException {
Map<String, String> claimValues = new HashMap<>();
org.wso2.carbon.user.core.UserStoreManager userStoreManager = null;
RealmService realmService = IdentityMgtServiceComponent.getRealmService();
try {
if (realmService.getTenantUserRealm(tenantId) != null) {
userStoreManager = (org.wso2.carbon.user.core.UserStoreManager) realmService.getTenantUserRealm(tenantId).
getUserStoreManager();
}
} catch (UserStoreException e) {
throw IdentityException.error("Error retrieving the user store manager for tenant id : " + tenantId, e);
}
try {
if (userStoreManager != null) {
claimValues = userStoreManager.getUserClaimValues(userName, claims, UserCoreConstants.DEFAULT_PROFILE);
}
} catch (Exception e) {
throw IdentityException.error("Unable to retrieve the claim for user : " + userName, e);
}
return claimValues;
}
/**
* get email address from user store
*
* @param userName user name
* @param tenantId tenant id
* @return email address
*/
public static String getEmailAddressForUser(String userName, int tenantId) {
String email = null;
try {
if (log.isDebugEnabled()) {
log.debug("Retrieving email address from user profile.");
}
Tenant tenant = IdentityMgtServiceComponent.getRealmService().
getTenantManager().getTenant(tenantId);
if (tenant != null && tenant.getAdminName().equals(userName)) {
email = tenant.getEmail();
}
if (email == null || email.trim().length() < 1) {
email = getClaimFromUserStoreManager(userName, tenantId,
UserCoreConstants.ClaimTypeURIs.EMAIL_ADDRESS);
}
if ((email == null || email.trim().length() < 1) && MultitenantUtils.isEmailUserName()) {
email = UserCoreUtil.removeDomainFromName(userName);
}
} catch (Exception e) {
String msg = "Unable to retrieve an email address associated with the given user : " + userName;
log.warn(msg, e); // It is common to have users with no email address defined.
}
return email;
}
/**
* Update Password with the user input
*
* @return true - if password was successfully reset
* @throws IdentityException
*/
public static boolean updatePassword(String userId, int tenantId, String password) throws IdentityException {
String tenantDomain = null;
if (userId == null || userId.trim().length() < 1 ||
password == null || password.trim().length() < 1) {
String msg = "Unable to find the required information for updating password";
log.error(msg);
throw IdentityException.error(msg);
}
try {
UserStoreManager userStoreManager = IdentityMgtServiceComponent.
getRealmService().getTenantUserRealm(tenantId).getUserStoreManager();
userStoreManager.updateCredentialByAdmin(userId, password);
if (log.isDebugEnabled()) {
String msg = "Password is updated for user: " + userId;
log.debug(msg);
}
return true;
} catch (UserStoreException e) {
String msg = "Error in changing the password, user name: " + userId + " domain: " +
tenantDomain + ".";
log.error(msg, e);
throw IdentityException.error(msg, e);
}
}
/**
* @param value
* @return
* @throws UserStoreException
*/
public static String doHash(String value) throws UserStoreException {
try {
String digsestFunction = "SHA-256";
MessageDigest dgst = MessageDigest.getInstance(digsestFunction);
byte[] byteValue = dgst.digest(value.getBytes());
return Base64.encode(byteValue);
} catch (NoSuchAlgorithmException e) {
log.error(e.getMessage(), e);
throw new UserStoreException(e.getMessage(), e);
}
}
/**
* Set claim to user store manager
*
* @param userName user name
* @param tenantId tenant id
* @param claim claim uri
* @param value claim value
* @throws IdentityException if fails
*/
public static void setClaimInUserStoreManager(String userName, int tenantId, String claim,
String value) throws IdentityException {
org.wso2.carbon.user.core.UserStoreManager userStoreManager = null;
RealmService realmService = IdentityMgtServiceComponent.getRealmService();
try {
if (realmService.getTenantUserRealm(tenantId) != null) {
userStoreManager = (org.wso2.carbon.user.core.UserStoreManager) realmService.getTenantUserRealm(tenantId).
getUserStoreManager();
}
} catch (Exception e) {
String msg = "Error retrieving the user store manager for the tenant";
log.error(msg, e);
throw IdentityException.error(msg, e);
}
try {
if (userStoreManager != null) {
String oldValue = userStoreManager.getUserClaimValue(userName, claim, null);
if (oldValue == null || !oldValue.equals(value)) {
Map<String,String> claimMap = new HashMap<String,String>();
claimMap.put(claim, value);
userStoreManager.setUserClaimValues(userName, claimMap, UserCoreConstants.DEFAULT_PROFILE);
}
}
} catch (Exception e) {
String msg = "Unable to set the claim for user : " + userName;
log.error(msg, e);
throw IdentityException.error(msg, e);
}
}
public static String getUserStoreDomainName(String userName) {
int index;
String userDomain;
if ((index = userName.indexOf(CarbonConstants.DOMAIN_SEPARATOR)) >= 0) {
// remove domain name if exist
userDomain = userName.substring(0, index);
} else {
userDomain = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME;
}
return userDomain;
}
public static String[] getChallengeUris() {
//TODO
return new String[]{IdentityMgtConstants.DEFAULT_CHALLENGE_QUESTION_URI01,
IdentityMgtConstants.DEFAULT_CHALLENGE_QUESTION_URI02};
}
public static Policy getSecurityPolicy() {
String policyString = " <wsp:Policy wsu:Id=\"UTOverTransport\" xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\"\n" +
" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">\n" +
" <wsp:ExactlyOne>\n" +
" <wsp:All>\n" +
" <sp:TransportBinding xmlns:sp=\"http://schemas.xmlsoap.org/ws/2005/07/securitypolicy\">\n" +
" <wsp:Policy>\n" +
" <sp:TransportToken>\n" +
" <wsp:Policy>\n" +
" <sp:HttpsToken RequireClientCertificate=\"true\"/>\n" +
" </wsp:Policy>\n" +
" </sp:TransportToken>\n" +
" <sp:AlgorithmSuite>\n" +
" <wsp:Policy>\n" +
" <sp:Basic256/>\n" +
" </wsp:Policy>\n" +
" </sp:AlgorithmSuite>\n" +
" <sp:Layout>\n" +
" <wsp:Policy>\n" +
" <sp:Lax/>\n" +
" </wsp:Policy>\n" +
" </sp:Layout>\n" +
" <sp:IncludeTimestamp/>\n" +
" </wsp:Policy>\n" +
" </sp:TransportBinding>\n" +
" </wsp:All>\n" +
" </wsp:ExactlyOne>\n" +
" </wsp:Policy>";
return PolicyEngine.getPolicy(new ByteArrayInputStream(policyString.getBytes()));
}
}<|fim▁end|>
|
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
|
<|file_name|>negative_log_likelihood.rs<|end_file_name|><|fim▁begin|>//! TODO: DOC
//!
use capnp_util::*;
use co::{IBackend, ITensorDesc, SharedTensor};
use layer::*;
use juice_capnp::negative_log_likelihood_config as capnp_config;
use util::{ArcLock, native_backend};
#[derive(Debug, Clone)]
#[allow(missing_copy_implementations)]
/// NegativeLogLikelihood Loss Layer
pub struct NegativeLogLikelihood {
num_classes: usize,
}
impl NegativeLogLikelihood {
/// Create a NegativeLogLikelihood layer from a NegativeLogLikelihoodConfig.
pub fn from_config(config: &NegativeLogLikelihoodConfig) -> NegativeLogLikelihood {
NegativeLogLikelihood { num_classes: config.num_classes }
}
fn calculate_outer_num(softmax_axis: usize, input_shape: &[usize]) -> usize {
input_shape.iter().take(softmax_axis + 1).fold(1, |prod, i| prod * i)
}
fn calculate_inner_num(softmax_axis: usize, input_shape: &[usize]) -> usize {
input_shape.iter().skip(softmax_axis + 1).fold(1, |prod, i| prod * i)
}
fn batch_size(input_shape: &[usize]) -> usize {
match input_shape.len() {
1 => 1,
2 => input_shape[0],
_ => panic!("NegativeLogLikelihood layer only supports 1D/2D inputs"),
}
}
}
impl<B: IBackend> ILayer<B> for NegativeLogLikelihood {
impl_ilayer_loss!();
fn sync_native(&self) -> bool {
true
}
fn reshape(&mut self,
backend: ::std::rc::Rc<B>,
input_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
input_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>,
weights_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
weights_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>,
output_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
output_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>) {
let data = input_data[0].read().unwrap();
let label = input_data[1].read().unwrap();
input_gradient[0].write().unwrap().resize(data.desc()).unwrap();
output_data[0].write().unwrap().resize(label.desc()).unwrap();
}
}
impl<B: IBackend> ComputeOutput<f32, B> for NegativeLogLikelihood {
fn compute_output(&self,
backend: &B,
_weights: &[&SharedTensor<f32>],
input_data: &[&SharedTensor<f32>],
output_data: &mut [&mut SharedTensor<f32>]) {
let probabilities = input_data[0];
let labels = input_data[1];
let batch_size = Self::batch_size(labels.desc());
let native = native_backend();
let native_labels = labels.read(native.device()).unwrap()
.as_slice::<f32>();
let native_probabilities = probabilities.read(native.device()).unwrap()
.as_slice::<f32>();
let mut writable_loss = Vec::<f32>::new();
for &label_value in native_labels {
let probability_value = native_probabilities[label_value as usize];
writable_loss.push(-probability_value);
}
let mut loss = writable_loss.iter().fold(0f32, |sum, &val| sum + val);
loss = loss / (batch_size as f32);
writable_loss = vec![loss];
::util::write_to_memory(output_data[0].write_only(native.device()).unwrap(),
&writable_loss);
}
}
impl<B: IBackend> ComputeInputGradient<f32, B> for NegativeLogLikelihood {
fn compute_input_gradient(&self,
backend: &B,
weights_data: &[&SharedTensor<f32>],
output_data: &[&SharedTensor<f32>],
output_gradients: &[&SharedTensor<f32>],
input_data: &[&SharedTensor<f32>],
input_gradients: &mut [&mut SharedTensor<f32>]) {
let labels = input_data[1];<|fim▁hole|> let native_labels = labels.read(native.device()).unwrap()
.as_slice::<f32>();
let mut writable_gradient = vec![0f32; input_gradients[0].desc().size()];
for (batch_n, &label_value) in native_labels.iter().enumerate() {
let index = (num_classes * batch_n) + label_value as usize;
writable_gradient[index] = -1f32;
}
::util::write_to_memory(input_gradients[0].write_only(native.device()).unwrap(),
&writable_gradient);
}
}
impl<B: IBackend> ComputeParametersGradient<f32, B> for NegativeLogLikelihood {}
#[derive(Debug, Clone)]
#[allow(missing_copy_implementations)]
/// Specifies configuration parameters for a NegativeLogLikelihood Layer.
pub struct NegativeLogLikelihoodConfig {
/// How many different classes can be classified.
pub num_classes: usize,
}
impl<'a> CapnpWrite<'a> for NegativeLogLikelihoodConfig {
type Builder = capnp_config::Builder<'a>;
/// Write the NegativeLogLikelihoodConfig into a capnp message.
fn write_capnp(&self, builder: &mut Self::Builder) {
builder.set_num_classes(self.num_classes as u64);
}
}
impl<'a> CapnpRead<'a> for NegativeLogLikelihoodConfig {
type Reader = capnp_config::Reader<'a>;
fn read_capnp(reader: Self::Reader) -> Self {
let num_classes = reader.get_num_classes() as usize;
NegativeLogLikelihoodConfig { num_classes: num_classes }
}
}
impl Into<LayerType> for NegativeLogLikelihoodConfig {
fn into(self) -> LayerType {
LayerType::NegativeLogLikelihood(self)
}
}<|fim▁end|>
|
let batch_size = Self::batch_size(input_data[0].desc());
let num_classes = self.num_classes;
let native = native_backend();
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|>import sys
import pigpio
import time
from colorama import Fore, Back, Style
def set_speed(lspeed, rspeed):
pi.hardware_PWM(left_servo_pin, 800, int(lspeed)*10000)
pi.hardware_PWM(right_servo_pin, 800, int(rspeed)*10000)
pi = pigpio.pi()
left_servo_pin = 13
right_servo_pin = 12
dead_pin = 17<|fim▁hole|>
try:
while True:
set_speed(ls, rs)
if pi.read(dead_pin) == pigpio.LOW:
set_speed(0, 0)
except :
set_speed(0, 0)
sys.exit(0)<|fim▁end|>
|
die_distance = 8
ls = 100
rs = 100
print("start")
|
<|file_name|>publish_queue.js<|end_file_name|><|fim▁begin|>'use strict';
var openUrl = require('./utils').open;
module.exports = new PublishQueue();
function PublishQueue() {
this.openPublishQueue = function() {
openUrl('/#/publish_queue');
};
this.getRow = function(rowNo) {
return element.all(by.css('[ng-click="preview(queue_item);"]')).get(rowNo);<|fim▁hole|> };
this.getHeadline = function(rowNo) {
var row = this.getRow(rowNo);
return row.all(by.className('ng-binding')).get(2);
};
this.getUniqueName = function(rowNo) {
var row = this.getRow(rowNo);
return row.all(by.className('ng-binding')).get(1);
};
this.getDestination = function(rowNo) {
var row = this.getRow(rowNo);
return row.all(by.className('ng-binding')).get(6);
};
this.previewAction = function(rowNo) {
var row = this.getRow(rowNo);
row.click();
};
this.openCompositeItem = function(group) {
var _list = element(by.css('[data-title="' + group.toLowerCase() + '"]'))
.all(by.repeater('child in item.childData'));
_list.all(by.css('[ng-click="open(data)"]')).get(0).click();
};
this.getCompositeItemHeadline = function(index) {
return element.all(by.className('package-item__item-headline')).get(index).getText();
};
this.getOpenedItemHeadline = function() {
return element.all(by.className('headline')).get(0).getText();
};
this.getPreviewTitle = function() {
return element(by.css('.content-container'))
.element(by.binding('selected.preview.headline'))
.getText();
};
this.searchAction = function(search) {
element(by.css('.flat-searchbar')).click();
browser.sleep(100);
element(by.model('query')).clear();
element(by.model('query')).sendKeys(search);
};
var list = element(by.className('list-pane'));
this.getItemCount = function () {
browser.sleep(500); // wait for a while to get list populated.
return list.all(by.repeater('queue_item in publish_queue track by queue_item._id')).count();
};
}<|fim▁end|>
| |
<|file_name|>visited.rs<|end_file_name|><|fim▁begin|>extern crate maze;<|fim▁hole|>#[test]
#[should_panic]
fn should_panic_if_index_out_of_range_for_visited() {
let vis = Visited::new(5, 7);
vis.visited(5, 7);
}
#[test]
fn should_have_initial_visited_state_of_false() {
let vis = Visited::new(10, 10);
for x in 0..10 {
for y in 0..10 {
assert!(!vis.visited(x, y));
}
}
}
#[test]
fn should_maintain_visited_state() {
let mut vis = Visited::new(10, 10);
assert!(!vis.visited(0,0));
vis.mark_visited(0,0);
assert!(vis.visited(0,0));
assert!(!vis.visited(0,9));
vis.mark_visited(0,9);
assert!(vis.visited(0,9));
assert!(!vis.visited(9,0));
vis.mark_visited(9,0);
assert!(vis.visited(9,0));
assert!(!vis.visited(9,9));
vis.mark_visited(9,9);
assert!(vis.visited(9,9));
}
#[test]
#[should_panic]
fn should_panic_if_index_out_of_range_for_neighbours_unvisited() {
let vis = Visited::new(5, 5);
vis.visited_neighbour(5, 5, WallDirection::NORTH);
}
#[test]
#[should_panic]
fn should_panic_if_neighbour_out_of_range_for_neighbours_unvisited() {
let vis = Visited::new(5, 5);
vis.visited_neighbour(4, 4, WallDirection::NORTH);
}
#[test]
fn should_get_visited_state_of_neighbour() {
let mut vis = Visited::new(10, 10);
vis.mark_visited(0, 1);
assert!(vis.visited_neighbour(0, 0, WallDirection::NORTH));
assert!(!vis.visited_neighbour(0, 0, WallDirection::EAST));
vis.mark_visited(1, 0);
assert!(vis.visited_neighbour(0, 0, WallDirection::EAST));
assert!(!vis.visited_neighbour(5, 4, WallDirection::NORTH));
assert!(!vis.visited_neighbour(5, 4, WallDirection::EAST));
assert!(!vis.visited_neighbour(5, 4, WallDirection::SOUTH));
assert!(!vis.visited_neighbour(5, 4, WallDirection::WEST));
vis.mark_visited(5, 5);
assert!(vis.visited_neighbour(5, 4, WallDirection::NORTH));
vis.mark_visited(5, 3);
assert!(vis.visited_neighbour(5, 4, WallDirection::SOUTH));
vis.mark_visited(4, 4);
assert!(vis.visited_neighbour(5, 4, WallDirection::WEST));
vis.mark_visited(6, 4);
assert!(vis.visited_neighbour(5, 4, WallDirection::EAST));
}<|fim▁end|>
|
use maze::visited::{Visited};
use maze::square_maze::{WallDirection};
|
<|file_name|>main.go<|end_file_name|><|fim▁begin|>package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
<|fim▁hole|> // Third party code for routing
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", Index)
router.HandleFunc("/settings", Settings)
router.HandleFunc("/updateSettings", UpdateSettings)
router.HandleFunc("/example/{id}", ExampleId)
router.HandleFunc("/worldspan", Worldspan)
router.HandleFunc("/api/{apiName}", ApiCall)
// File servers
path := os.Getenv("GOPATH") + "/src/api-simulator/"
router.PathPrefix("/css/").Handler(http.StripPrefix("/css/",
http.FileServer(http.Dir(path + "css"))))
router.PathPrefix("/js/").Handler(http.StripPrefix("/js/",
http.FileServer(http.Dir(path + "/js"))))
log.Fatal(http.ListenAndServe(":8080", router))
}
func Index(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, "Root directory of the API simulator\n")
}
func Settings(response http.ResponseWriter, request *http.Request) {
settingsPage := settingsPage{response: response}
settingsPage.respond()
}
// Handles Ajax requests for updating various settings
func UpdateSettings(response http.ResponseWriter, request *http.Request) {
request.ParseForm()
switch request.FormValue("action") {
case "saveApi":
saveApiFromForm(request, response)
case "saveMessage":
saveMessageFromForm(request, response)
case "saveResponse":
saveResponseFromForm(request, response)
case "saveNewField":
saveNewFieldFromForm(request, response)
case "updateField":
updateFieldFromForm(request, response)
default:
log.Fatal("Invalid action requested")
}
}
// Save a provided field that was entered on the form
func updateFieldFromForm(request *http.Request, response http.ResponseWriter) {
id := request.FormValue("id")
value := request.FormValue("value")
// Get the ID from the id
regExNums := regexp.MustCompile("[0-9]+")
numbers := regExNums.FindAllString(id, -1)
var databaseId string
if(len(numbers) > 0) {
databaseId = numbers[len(numbers)-1]
}
// Get the field name from the id
regExLetters := regexp.MustCompile("[A-Za-z]+")
letters := regExLetters.FindAllString(id, 1)
if(len(letters) < 1) {
log.Fatal("Did not have any letters in the id field")
}
fieldName := letters[0]
switch fieldName {
case "responseField":
model := responsesModel{}
id, _ := strconv.Atoi(databaseId)
model.loadFromId(id)
model.Template = value
model.save()
case "identifierField", "messageField":
model := messagesModel{}
id, _ := strconv.Atoi(databaseId)
model.loadFromId(id)
switch fieldName {
case "identifierField":
model.Identifier = value
case "messageField":
model.Template = value
}
database := database{}
database.connect()
database.updateMessages(model)
case "apiNameField", "beginningEscapeField", "endingEscapeField", "apiWildCard":
apiModel := apiModel{}
apiModel.loadFromId(databaseId)
switch fieldName {
case "apiNameField":
apiModel.Name = value
case "beginningEscapeField":
apiModel.BeginningEscape = value
case "endingEscapeField":
apiModel.EndingEscape = value
case "apiWildCard":
apiModel.WildCard = value
}
database := database{}
database.connect()
database.updateApi(apiModel)
default:
log.Fatal("Unknown field provided")
}
}
// Save an API that was entered on the settings page
func saveApiFromForm(request *http.Request, response http.ResponseWriter) {
model := apiModel{Name: request.FormValue("apiName"),
BeginningEscape: request.FormValue("beginningEscape"),
EndingEscape: request.FormValue("endingEscape"),
WildCard: request.FormValue("wildCard")}
database := database{}
database.connect()
result := database.insertApi(model)
ajaxResponse := ajaxResponse{Status: result, Error: "None"}
json.NewEncoder(response).Encode(ajaxResponse)
}
// Saves a messgae that was entered on the settings page
func saveMessageFromForm(request *http.Request, response http.ResponseWriter) {
apiId, _ := strconv.Atoi(request.FormValue("apiId"))
model := messagesModel{ApiId: apiId,
Identifier: request.FormValue("identifier")}
database := database{}
database.connect()
result := database.insertMessage(model)
ajaxResponse := ajaxResponse{Status: result, Error: "None"}
json.NewEncoder(response).Encode(ajaxResponse)
}
// Save the response that was received from the submitted form
func saveResponseFromForm(request *http.Request, response http.ResponseWriter) {
messageId, _ := strconv.Atoi(request.FormValue("messageId"))
isDefault, _ := strconv.ParseBool(request.FormValue("isDefault"))
model := responsesModel {MessageId: messageId,
Template: request.FormValue("response"),
Default: isDefault,
Condition: request.FormValue("condition")}
database := database{}
database.connect()
result := database.insertResponse(model)
ajaxResponse := ajaxResponse{Status: result, Error: "None"}
json.NewEncoder(response).Encode(ajaxResponse)
}
// Save a new message field that was received from the settings page
func saveNewFieldFromForm(request *http.Request, response http.ResponseWriter) {
messageId, _ := strconv.Atoi(request.FormValue("id"))
// Currently we are assuming that it's a message
//fieldType := request.FormValue("type")
fieldValue := request.FormValue("value")
model := messageFieldsModel {MessageId: messageId,
FieldName: fieldValue}
database := database{}
database.connect()
result, id := database.insertMessageField(model)
ajaxResponse := ajaxResponse{Status: result, Error: "None", Id: id}
json.NewEncoder(response).Encode(ajaxResponse)
}
func ExampleId(response http.ResponseWriter, request *http.Request) {
providedVars := mux.Vars(request)
identifier := strings.TrimSpace(providedVars["id"])
fmt.Fprintln(response, "Provided ID: ", identifier)
}
func ApiCall(response http.ResponseWriter, request *http.Request) {
providedVars := mux.Vars(request)
apiName := strings.TrimSpace(providedVars["apiName"])
apiHandler := apiHandler{request: *request, response: response}
if(!apiHandler.withApiName(apiName)) {
fmt.Fprintln(response, "Invalid API name provided: "+ apiName)
return
}
apiHandler.respond()
}
func Worldspan(response http.ResponseWriter, request *http.Request) {
worldspan := worldspanConnection{response: response, request: request}
worldspan.respond()
}<|fim▁end|>
| |
<|file_name|>syncengine.py<|end_file_name|><|fim▁begin|># Copyright (C) 2016-2020 Matthias Klumpp <[email protected]>
#
# Licensed under the GNU Lesser General Public License Version 3
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the license, or
# (at your option) any later version.
#
# This software 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this software. If not, see <http://www.gnu.org/licenses/>.
import re
from typing import List
from apt_pkg import version_compare
from laniakea import LocalConfig, LkModule
from laniakea.repository import Repository, make_newest_packages_dict, version_revision
from laniakea.db import session_scope, config_get_distro_tag, \
ArchiveSuite, ArchiveComponent, ArchiveArchitecture, SourcePackage, SynchrotronIssue, \
SynchrotronIssueKind, SynchrotronSource, SynchrotronConfig, SyncBlacklistEntry
from laniakea.dakbridge import DakBridge
from laniakea.logging import log<|fim▁hole|> '''
Execute package synchronization in Synchrotron
'''
def __init__(self, target_suite_name: str, source_suite_name: str):
self._lconf = LocalConfig()
self._dak = DakBridge()
# FIXME: Don't hardcode this!
repo_name = 'master'
# the repository of the distribution we import stuff into
self._target_repo = Repository(self._lconf.archive_root_dir,
repo_name)
self._target_repo.set_trusted(True)
self._target_suite_name = target_suite_name
self._source_suite_name = source_suite_name
self._distro_tag = config_get_distro_tag()
self._synced_source_pkgs = []
with session_scope() as session:
sync_source = session.query(SynchrotronSource) \
.filter(SynchrotronSource.suite_name == self._source_suite_name).one()
# FIXME: Synchrotron needs adjustments to work
# better with the new "multiple autosync tasks" model.
# This code will need to be revised for that
# (currently it is just a 1:1 translation from D code)
# the repository of the distribution we use to sync stuff from
self._source_repo = Repository(sync_source.repo_url,
sync_source.os_name,
self._lconf.synchrotron_sourcekeyrings)
# we trust everything by default
self._imports_trusted = True
with session_scope() as session:
self._sync_blacklist = set([value for value, in session.query(SyncBlacklistEntry.pkgname)])
def _publish_synced_spkg_events(self, src_os, src_suite, dest_suite, forced=False, emitter=None):
''' Submit events for the synced source packages to the message stream '''
if not emitter:
emitter = EventEmitter(LkModule.SYNCHROTRON)
for spkg in self._synced_source_pkgs:
data = {'name': spkg.name,
'version': spkg.version,
'src_os': src_os,
'suite_src': src_suite,
'suite_dest': dest_suite,
'forced': forced}
emitter.submit_event('src-package-imported', data)
def _get_repo_source_package_map(self, repo, suite_name: str, component_name: str):
''' Get an associative array of the newest source packages present in a repository. '''
suite = ArchiveSuite(suite_name)
component = ArchiveComponent(component_name)
spkgs = repo.source_packages(suite, component)
return make_newest_packages_dict(spkgs)
def _get_repo_binary_package_map(self, repo, suite_name: str, component_name: str,
arch_name: str = None, with_installer: bool = True):
''' Get an associative array of the newest binary packages present in a repository. '''
suite = ArchiveSuite(suite_name)
component = ArchiveComponent(component_name)
arch = ArchiveArchitecture(arch_name)
arch_all = ArchiveArchitecture('all')
bpkgs = repo.binary_packages(suite, component, arch)
bpkgs.extend(repo.binary_packages(suite, component, arch_all)) # always append arch:all packages
if with_installer:
# add d-i packages to the mix
bpkgs.extend(repo.installer_packages(suite, component, arch))
bpkgs.extend(repo.installer_packages(suite, component, arch_all)) # always append arch:all packages
return make_newest_packages_dict(bpkgs)
def _get_target_source_packages(self, component: str):
''' Get mapping of all sources packages in a suite and its parent suite. '''
with session_scope() as session:
target_suite = session.query(ArchiveSuite) \
.filter(ArchiveSuite.name == self._target_suite_name).one()
suite_pkgmap = self._get_repo_source_package_map(self._target_repo,
target_suite.name,
component)
if target_suite.parent:
# we have a parent suite
parent_map = self._get_repo_source_package_map(self._target_repo,
target_suite.parent.name,
component)
# merge the two arrays, keeping only the latest versions
suite_pkgmap = make_newest_packages_dict(list(parent_map.values()) + list(suite_pkgmap.values()))
return suite_pkgmap
def _import_package_files(self, suite: str, component: str, fnames: List[str]):
''' Import an arbitrary amount of packages via the archive management software. '''
return self._dak.import_package_files(suite, component, fnames, self._imports_trusted, True)
def _import_source_package(self, spkg: SourcePackage, component: str) -> bool:
'''
Import a source package from the source repository into the
target repo.
'''
dscfile = None
for f in spkg.files:
# the source repository might be on a remote location, so we need to
# request each file to be there.
# (dak will fetch the files referenced in the .dsc file from the same directory)
if f.fname.endswith('.dsc'):
dscfile = self._source_repo.get_file(f)
self._source_repo.get_file(f)
if not dscfile:
log.error('Critical consistency error: Source package {} in repository {} has no .dsc file.'
.format(spkg.name, self._source_repo.base_dir))
return False
if self._import_package_files(self._target_suite_name, component, [dscfile]):
self._synced_source_pkgs.append(spkg)
return True
return False
def _import_binaries_for_source(self, sync_conf, target_suite, component: str, spkgs: List[SourcePackage],
ignore_target_changes: bool = False) -> bool:
''' Import binary packages for the given set of source packages into the archive. '''
if not sync_conf.sync_binaries:
log.debug('Skipping binary syncs.')
return True
# list of valid architectrures supported by the target
target_archs = [a.name for a in target_suite.architectures]
# cache of binary-package mappings for the source
src_bpkg_arch_map = {}
for aname in target_archs:
src_bpkg_arch_map[aname] = self._get_repo_binary_package_map(self._source_repo, self._source_suite_name, component, aname)
# cache of binary-package mappings from the target repository
dest_bpkg_arch_map = {}
for aname in target_archs:
dest_bpkg_arch_map[aname] = self._get_repo_binary_package_map(self._target_repo, self._target_suite_name, component, aname)
for spkg in spkgs:
bin_files_synced = False
existing_packages = False
for arch_name in target_archs:
if arch_name not in src_bpkg_arch_map:
continue
src_bpkg_map = src_bpkg_arch_map[arch_name]
dest_bpkg_map = dest_bpkg_arch_map[arch_name]
bin_files = []
for bin_i in spkg.binaries:
if bin_i.name not in src_bpkg_map:
if bin_i.name in dest_bpkg_map:
existing_packages = True # package only exists in target
continue
if arch_name != 'all' and bin_i.architectures == ['all']:
# we handle arch:all explicitly
continue
bpkg = src_bpkg_map[bin_i.name]
if bin_i.version != bpkg.source_version:
log.debug('Not syncing binary package \'{}\': Version number \'{}\' does not match source package version \'{}\'.'
.format(bpkg.name, bin_i.version, bpkg.source_version))
continue
ebpkg = dest_bpkg_map.get(bpkg.name)
if ebpkg:
if version_compare(ebpkg.version, bpkg.version) >= 0:
log.debug('Not syncing binary package \'{}/{}\': Existing binary package with bigger/equal version \'{}\' found.'
.format(bpkg.name, bpkg.version, ebpkg.version))
existing_packages = True
continue
# Filter out manual rebuild uploads matching the pattern XbY.
# sometimes rebuild uploads of not-modified packages happen, and if the source
# distro did a binNMU, we don't want to sync that, even if it's bigger
# This rebuild-upload check must only happen if we haven't just updated the source package
# (in that case the source package version will be bigger than the existing binary package version)
if version_compare(spkg.version, ebpkg.version) >= 0:
if re.match(r'(.*)b([0-9]+)', ebpkg.version):
log.debug('Not syncing binary package \'{}/{}\': Existing binary package with rebuild upload \'{}\' found.'
.format(bpkg.name, bpkg.version, ebpkg.version))
existing_packages = True
continue
if not ignore_target_changes and self._distro_tag in version_revision(ebpkg.version):
# safety measure, we should never get here as packages with modifications were
# filtered out previously.
log.debug('Can not sync binary package {}/{}: Target has modifications.'.format(bin_i.name, bin_i.version))
continue
fname = self._source_repo.get_file(bpkg.bin_file)
bin_files.append(fname)
# now import the binary packages, if there is anything to import
if bin_files:
bin_files_synced = True
ret = self._import_package_files(self._target_suite_name, component, bin_files)
if not ret:
return False
if not bin_files_synced and not existing_packages:
log.warning('No binary packages synced for source {}/{}'.format(spkg.name, spkg.version))
return True
def sync_packages(self, component: str, pkgnames: List[str], force: bool = False):
self._synced_source_pkgs = []
with session_scope() as session:
sync_conf = session.query(SynchrotronConfig) \
.join(SynchrotronConfig.destination_suite) \
.join(SynchrotronConfig.source) \
.filter(ArchiveSuite.name == self._target_suite_name,
SynchrotronSource.suite_name == self._source_suite_name).one_or_none()
if not sync_conf:
log.error('Unable to find a sync config for this source/destination combination.')
return False
if not sync_conf.sync_enabled:
log.error('Can not synchronize package: Synchronization is disabled for this configuration.')
return False
target_suite = session.query(ArchiveSuite) \
.filter(ArchiveSuite.name == self._target_suite_name).one()
dest_pkg_map = self._get_target_source_packages(component)
src_pkg_map = self._get_repo_source_package_map(self._source_repo,
self._source_suite_name,
component)
for pkgname in pkgnames:
spkg = src_pkg_map.get(pkgname)
dpkg = dest_pkg_map.get(pkgname)
if not spkg:
log.info('Can not sync {}: Does not exist in source.'.format(pkgname))
continue
if pkgname in self._sync_blacklist:
log.info('Can not sync {}: The package is blacklisted.'.format(pkgname))
continue
if dpkg:
if version_compare(dpkg.version, spkg.version) >= 0:
if force:
log.warning('{}: Target version \'{}\' is newer/equal than source version \'{}\'.'
.format(pkgname, dpkg.version, spkg.version))
else:
log.info('Can not sync {}: Target version \'{}\' is newer/equal than source version \'{}\'.'
.format(pkgname, dpkg.version, spkg.version))
continue
if not force:
if self._distro_tag in version_revision(dpkg.version):
log.error('Not syncing {}/{}: Destination has modifications (found {}).'
.format(spkg.name, spkg.version, dpkg.version))
continue
# sync source package
# the source package must always be known to dak first
ret = self._import_source_package(spkg, component)
if not ret:
return False
ret = self._import_binaries_for_source(sync_conf, target_suite, component, self._synced_source_pkgs, force)
# TODO: Analyze the input, fetch the packages from the source distribution and
# import them into the target in their correct order.
# Then apply the correct, synced override from the source distro.
self._publish_synced_spkg_events(sync_conf.source.os_name,
sync_conf.source.suite_name,
sync_conf.destination_suite.name,
force)
return ret
def autosync(self, session, sync_conf, remove_cruft: bool = True):
''' Synchronize all packages that are newer '''
self._synced_source_pkgs = []
active_src_pkgs = [] # source packages which should have their binary packages updated
res_issues = []
target_suite = session.query(ArchiveSuite) \
.filter(ArchiveSuite.name == self._target_suite_name).one()
sync_conf = session.query(SynchrotronConfig) \
.join(SynchrotronConfig.destination_suite) \
.join(SynchrotronConfig.source) \
.filter(ArchiveSuite.name == self._target_suite_name,
SynchrotronSource.suite_name == self._source_suite_name).one_or_none()
for component in target_suite.components:
dest_pkg_map = self._get_target_source_packages(component.name)
# The source package lists contains many different versions, some source package
# versions are explicitly kept for GPL-compatibility.
# Sometimes a binary package migrates into another suite, dragging a newer source-package
# that it was built against with itslf into the target suite.
# These packages then have a source with a high version number, but might not have any
# binaries due to them migrating later.
# We need to care for that case when doing binary syncs (TODO: and maybe safeguard against it
# when doing source-only syncs too?), That's why we don't filter out the newest packages in
# binary-sync-mode.
if sync_conf.sync_binaries:
src_pkg_range = self._source_repo.source_packages(ArchiveSuite(self._source_suite_name), component)
else:
src_pkg_range = self._get_repo_source_package_map(self._source_repo,
self._source_suite_name,
component).values()
for spkg in src_pkg_range:
# ignore blacklisted packages in automatic sync
if spkg.name in self._sync_blacklist:
continue
dpkg = dest_pkg_map.get(spkg.name)
if dpkg:
if version_compare(dpkg.version, spkg.version) >= 0:
log.debug('Skipped sync of {}: Target version \'{}\' is equal/newer than source version \'{}\'.'
.format(spkg.name, dpkg.version, spkg.version))
continue
# check if we have a modified target package,
# indicated via its Debian revision, e.g. "1.0-0tanglu1"
if self._distro_tag in version_revision(dpkg.version):
log.info('Not syncing {}/{}: Destination has modifications (found {}).'
.format(spkg.name, spkg.version, dpkg.version))
# add information that this package needs to be merged to the issue list
issue = SynchrotronIssue()
issue.package_name = spkg.name
issue.source_version = spkg.version
issue.target_version = dpkg.version
issue.kind = SynchrotronIssueKind.MERGE_REQUIRED
res_issues.append(issue)
continue
# sync source package
# the source package must always be known to dak first
ret = self._import_source_package(spkg, component.name)
if not ret:
return False, []
# a new source package is always active and needs it's binary packages synced, in
# case we do binary syncs.
active_src_pkgs.append(spkg)
# all packages in the target distribution are considered active, as long as they don't
# have modifications.
for spkg in dest_pkg_map.values():
if self._distro_tag in version_revision(spkg.version):
active_src_pkgs.append(spkg)
# import binaries as well. We test for binary updates for all available active source packages,
# as binNMUs might have happened in the source distribution.
# (an active package in this context is any source package which doesn't have modifications in the
# target distribution)
ret = self._import_binaries_for_source(sync_conf, target_suite, component.name, active_src_pkgs)
if not ret:
return False, []
# test for cruft packages
target_pkg_index = {}
for component in target_suite.components:
dest_pkg_map = self._get_repo_source_package_map(self._target_repo,
target_suite.name,
component.name)
for pkgname, pkg in dest_pkg_map.items():
target_pkg_index[pkgname] = pkg
# check which packages are present in the target, but not in the source suite
for component in target_suite.components:
src_pkg_map = self._get_repo_source_package_map(self._source_repo,
self._source_suite_name,
component.name)
for pkgname in src_pkg_map.keys():
target_pkg_index.pop(pkgname, None)
# remove cruft packages
if remove_cruft:
for pkgname, dpkg in target_pkg_index.items():
dpkg_ver_revision = version_revision(dpkg.version, False)
# native packages are never removed
if not dpkg_ver_revision:
continue
# check if the package is intoduced as new in the distro, in which case we won't remove it
if dpkg_ver_revision.startswith('0' + self._distro_tag):
continue
# if this package was modified in the target distro, we will also not remove it, but flag it
# as "potential cruft" for someone to look at.
if self._distro_tag in dpkg_ver_revision:
issue = SynchrotronIssue()
issue.kind = SynchrotronIssueKind.MAYBE_CRUFT
issue.source_suite = self._source_suite_name
issue.target_suite = self._target_suite_name
issue.package_name = dpkg.name
issue.source_version = None
issue.target_version = dpkg.version
res_issues.append(issue)
continue
# check if we can remove this package without breaking stuff
if self._dak.package_is_removable(dpkg.name, target_suite.name):
# try to remove the package
try:
self._dak.remove_package(dpkg.name, target_suite.name)
except Exception as e:
issue = SynchrotronIssue()
issue.kind = SynchrotronIssueKind.REMOVAL_FAILED
issue.source_suite = self._source_suite_name
issue.target_suite = self._target_suite_name
issue.package_name = dpkg.name
issue.source_version = None
issue.target_version = dpkg.version
issue.details = str(e)
res_issues.append(issue)
else:
# looks like we can not remove this
issue = SynchrotronIssue()
issue.kind = SynchrotronIssueKind.REMOVAL_FAILED
issue.source_suite = self._source_suite_name
issue.target_suite = self._target_suite_name
issue.package_name = dpkg.name
issue.source_version = None
issue.target_version = dpkg.version
issue.details = 'This package can not be removed without breaking other packages. It needs manual removal.'
res_issues.append(issue)
self._publish_synced_spkg_events(sync_conf.source.os_name,
sync_conf.source.suite_name,
sync_conf.destination_suite.name,
False)
return True, res_issues<|fim▁end|>
|
from laniakea.msgstream import EventEmitter
class SyncEngine:
|
<|file_name|>QuestionaireOutlineTreeProvider.java<|end_file_name|><|fim▁begin|>/**
* generated by Xtext
*/
package dk.itu.smdp.group2.ui.outline;
import org.eclipse.xtext.ui.editor.outline.impl.DefaultOutlineTreeProvider;<|fim▁hole|>/**
* Customization of the default outline structure.
*
* see http://www.eclipse.org/Xtext/documentation.html#outline
*/
@SuppressWarnings("all")
public class QuestionaireOutlineTreeProvider extends DefaultOutlineTreeProvider {
}<|fim▁end|>
| |
<|file_name|>search.js<|end_file_name|><|fim▁begin|>import { get } from '../get'
export function getSearchData(page, cityName, category, keyword) {
const keywordStr = keyword ? '/' + keyword : ''
const result = get('/api/search/' + page + '/' + cityName + '/' + category + keywordStr)<|fim▁hole|>}<|fim▁end|>
|
return result
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>//! Assignment operators (`+=`, `-=`, `*=`, etc) traits
//!
//! Note that no operator sugar is provided, i.e. `x += y` won't use these traits.
//!
//! This crate is only a convenience for me, as I've the need of using these traits as bounds in
//! some of my libraries, and I'd rather not duplicate the definitions in each library.
//!
//! This crate will be deprecated once these traits land in stdlib. (See rust-lang/rfcs#393)
#![deny(missing_docs)]
#![deny(warnings)]
/// The `+=` operator (without the sugar)<|fim▁hole|>
/// The `/=` operator (without the sugar)
pub trait DivAssign<Rhs=Self> {
/// `a /= b` -> `DivAssign::div_assign(&mut a, b)`
fn div_assign(&mut self, Rhs);
}
/// The `*=` operator (without the sugar)
pub trait MulAssign<Rhs=Self> {
/// `a *= b` -> `Mulssign::mul_assign(&mut a, b)`
fn mul_assign(&mut self, Rhs);
}
/// The `-=` operator (without the sugar)
pub trait SubAssign<Rhs=Self> {
/// `a -= b` -> `SubAssign::sub_assign(&mut a, b)`
fn sub_assign(&mut self, Rhs);
}<|fim▁end|>
|
pub trait AddAssign<Rhs=Self> {
/// `a += b` -> `AddAssign::add_assign(&mut a, b)`
fn add_assign(&mut self, Rhs);
}
|
<|file_name|>toptips.service.ts<|end_file_name|><|fim▁begin|>import { DOCUMENT } from '@angular/common';
import { ApplicationRef, ComponentFactoryResolver, Inject, Injectable, Injector } from '@angular/core';
import { BaseService } from 'ngx-weui/core';
import { ToptipsComponent, ToptipsType } from './toptips.component';
@Injectable({ providedIn: 'root' })
export class ToptipsService extends BaseService {
constructor(
protected readonly resolver: ComponentFactoryResolver,
protected readonly applicationRef: ApplicationRef,
protected readonly injector: Injector,
@Inject(DOCUMENT) protected readonly doc: any,
) {
super();
}
/**
* 构建一个Toptips并显示
*
* @param text 文本
* @param type 类型
* @param 显示时长后自动关闭(单位:ms)
*/
show(text: string, type: ToptipsType, time: number = 2000): ToptipsComponent {
const componentRef = this.build(ToptipsComponent);
if (type) {
componentRef.instance.type = type;
}
if (text) {
componentRef.instance.text = text;
}
componentRef.instance.time = time;
componentRef.instance.hide.subscribe(() => {
setTimeout(() => {
this.destroy(componentRef);
}, 100);
});
return componentRef.instance.onShow();
}
/**
* 构建一个Warn Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
warn(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'warn', time);
}
/**
* 构建一个Info Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
info(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'info', time);
}
/**
* 构建一个Primary Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
primary(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'primary', time);
}
/**
* 构建一个Success Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
success(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'primary', time);
}
/**
* 构建一个Default Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
default(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'default', time);
}<|fim▁hole|><|fim▁end|>
|
}
|
<|file_name|>elasticsearch.py<|end_file_name|><|fim▁begin|># coding=utf-8
"""
Collect the elasticsearch stats for the local node
#### Dependencies
* urlib2
"""
import urllib2
import re
try:
import json
json # workaround for pyflakes issue #13
except ImportError:
import simplejson as json
import diamond.collector
RE_LOGSTASH_INDEX = re.compile('^(.*)-\d\d\d\d\.\d\d\.\d\d$')
class ElasticSearchCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(ElasticSearchCollector,
self).get_default_config_help()
config_help.update({
'host': "",
'port': "",
'stats': "Available stats: \n"
+ " - jvm (JVM information) \n"
+ " - thread_pool (Thread pool information) \n"
+ " - indices (Individual index stats)\n",
'logstash_mode': "If 'indices' stats are gathered, remove "
+ "the YYYY.MM.DD suffix from the index name "
+ "(e.g. logstash-adm-syslog-2014.01.03) and use that "
+ "as a bucket for all 'day' index stats.",
})
return config_help
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(ElasticSearchCollector, self).get_default_config()
config.update({
'host': '127.0.0.1',
'port': 9200,
'path': 'elasticsearch',
'stats': ['jvm', 'thread_pool', 'indices'],
'logstash_mode': False,
})
return config
def _get(self, path):
url = 'http://%s:%i/%s' % (
self.config['host'], int(self.config['port']), path)
try:
response = urllib2.urlopen(url)
except Exception, err:
self.log.error("%s: %s", url, err)
return False
try:
return json.load(response)
except (TypeError, ValueError):
self.log.error("Unable to parse response from elasticsearch as a"
+ " json object")
return False
def _copy_one_level(self, metrics, prefix, data, filter=lambda key: True):
for key, value in data.iteritems():
if filter(key):
metric_path = '%s.%s' % (prefix, key)
self._set_or_sum_metric(metrics, metric_path, value)
def _copy_two_level(self, metrics, prefix, data, filter=lambda key: True):
for key1, d1 in data.iteritems():
self._copy_one_level(metrics, '%s.%s' % (prefix, key1), d1, filter)
def _index_metrics(self, metrics, prefix, index):
if self.config['logstash_mode']:
"""Remove the YYYY.MM.DD bit from logstash indices.
This way we keep using the same metric naming and not polute
our metrics system (e.g. Graphite) with new metrics every day."""
m = RE_LOGSTASH_INDEX.match(prefix)
if m:
prefix = m.group(1)
# keep a telly of the number of indexes
self._set_or_sum_metric(metrics,
'%s.indexes_in_group' % prefix, 1)
self._add_metric(metrics, '%s.docs.count' % prefix, index,
['docs', 'count'])
self._add_metric(metrics, '%s.docs.deleted' % prefix, index,
['docs', 'deleted'])
self._add_metric(metrics, '%s.datastore.size' % prefix, index,
['store', 'size_in_bytes'])
# publish all 'total' and 'time_in_millis' stats
self._copy_two_level(
metrics, prefix, index,
lambda key: key.endswith('total') or key.endswith('time_in_millis'))
def _add_metric(self, metrics, metric_path, data, data_path):
"""If the path specified by data_path (a list) exists in data,
add to metrics. Use when the data path may not be present"""
current_item = data
for path_element in data_path:
current_item = current_item.get(path_element)
if current_item is None:
return
self._set_or_sum_metric(metrics, metric_path, current_item)
def _set_or_sum_metric(self, metrics, metric_path, value):
"""If we already have a datapoint for this metric, lets add
the value. This is used when the logstash mode is enabled."""
if metric_path in metrics:
metrics[metric_path] += value
else:
metrics[metric_path] = value
def collect(self):
if json is None:
self.log.error('Unable to import json')
return {}
result = self._get('_nodes/_local/stats?all=true')
if not result:
return
metrics = {}
node = result['nodes'].keys()[0]
data = result['nodes'][node]
#
# http connections to ES
metrics['http.current'] = data['http']['current_open']
#
# indices
indices = data['indices']
metrics['indices.docs.count'] = indices['docs']['count']
metrics['indices.docs.deleted'] = indices['docs']['deleted']
metrics['indices.datastore.size'] = indices['store']['size_in_bytes']
transport = data['transport']
metrics['transport.rx.count'] = transport['rx_count']
metrics['transport.rx.size'] = transport['rx_size_in_bytes']
metrics['transport.tx.count'] = transport['tx_count']
metrics['transport.tx.size'] = transport['tx_size_in_bytes']
# elasticsearch < 0.90RC2
if 'cache' in indices:
cache = indices['cache']
self._add_metric(metrics, 'cache.bloom.size', cache,
['bloom_size_in_bytes'])
self._add_metric(metrics, 'cache.field.evictions', cache,
['field_evictions'])
self._add_metric(metrics, 'cache.field.size', cache,
['field_size_in_bytes'])
metrics['cache.filter.count'] = cache['filter_count']
metrics['cache.filter.evictions'] = cache['filter_evictions']<|fim▁hole|> ['id_cache_size_in_bytes'])
# elasticsearch >= 0.90RC2
if 'filter_cache' in indices:
cache = indices['filter_cache']
metrics['cache.filter.evictions'] = cache['evictions']
metrics['cache.filter.size'] = cache['memory_size_in_bytes']
self._add_metric(metrics, 'cache.filter.count', cache, ['count'])
# elasticsearch >= 0.90RC2
if 'id_cache' in indices:
cache = indices['id_cache']
self._add_metric(metrics, 'cache.id.size', cache,
['memory_size_in_bytes'])
# elasticsearch >= 0.90
if 'fielddata' in indices:
fielddata = indices['fielddata']
self._add_metric(metrics, 'fielddata.size', fielddata,
['memory_size_in_bytes'])
self._add_metric(metrics, 'fielddata.evictions', fielddata,
['evictions'])
#
# process mem/cpu (may not be present, depending on access restrictions)
self._add_metric(metrics, 'process.cpu.percent', data,
['process', 'cpu', 'percent'])
self._add_metric(metrics, 'process.mem.resident', data,
['process', 'mem', 'resident_in_bytes'])
self._add_metric(metrics, 'process.mem.share', data,
['process', 'mem', 'share_in_bytes'])
self._add_metric(metrics, 'process.mem.virtual', data,
['process', 'mem', 'total_virtual_in_bytes'])
#
# filesystem (may not be present, depending on access restrictions)
if 'fs' in data and 'data' in data['fs'] and data['fs']['data']:
fs_data = data['fs']['data'][0]
self._add_metric(metrics, 'disk.reads.count', fs_data,
['disk_reads'])
self._add_metric(metrics, 'disk.reads.size', fs_data,
['disk_read_size_in_bytes'])
self._add_metric(metrics, 'disk.writes.count', fs_data,
['disk_writes'])
self._add_metric(metrics, 'disk.writes.size', fs_data,
['disk_write_size_in_bytes'])
#
# jvm
if 'jvm' in self.config['stats']:
jvm = data['jvm']
mem = jvm['mem']
for k in ('heap_used', 'heap_committed', 'non_heap_used',
'non_heap_committed'):
metrics['jvm.mem.%s' % k] = mem['%s_in_bytes' % k]
for pool, d in mem['pools'].iteritems():
pool = pool.replace(' ', '_')
metrics['jvm.mem.pools.%s.used' % pool] = d['used_in_bytes']
metrics['jvm.mem.pools.%s.max' % pool] = d['max_in_bytes']
metrics['jvm.threads.count'] = jvm['threads']['count']
gc = jvm['gc']
collection_count = 0
collection_time_in_millis = 0
for collector, d in gc['collectors'].iteritems():
metrics['jvm.gc.collection.%s.count' % collector] = d[
'collection_count']
collection_count += d['collection_count']
metrics['jvm.gc.collection.%s.time' % collector] = d[
'collection_time_in_millis']
collection_time_in_millis += d['collection_time_in_millis']
# calculate the totals, as they're absent in elasticsearch > 0.90.10
if 'collection_count' in gc:
metrics['jvm.gc.collection.count'] = gc['collection_count']
else:
metrics['jvm.gc.collection.count'] = collection_count
k = 'collection_time_in_millis'
if k in gc:
metrics['jvm.gc.collection.time'] = gc[k]
else:
metrics['jvm.gc.collection.time'] = collection_time_in_millis
#
# thread_pool
if 'thread_pool' in self.config['stats']:
self._copy_two_level(metrics, 'thread_pool', data['thread_pool'])
#
# network
self._copy_two_level(metrics, 'network', data['network'])
if 'indices' in self.config['stats']:
#
# individual index stats
result = self._get('_stats?clear=true&docs=true&store=true&'
+ 'indexing=true&get=true&search=true')
if not result:
return
_all = result['_all']
self._index_metrics(metrics, 'indices._all', _all['primaries'])
if 'indices' in _all:
indices = _all['indices']
elif 'indices' in result: # elasticsearch >= 0.90RC2
indices = result['indices']
else:
return
for name, index in indices.iteritems():
self._index_metrics(metrics, 'indices.%s' % name,
index['primaries'])
for key in metrics:
self.publish(key, metrics[key])<|fim▁end|>
|
metrics['cache.filter.size'] = cache['filter_size_in_bytes']
self._add_metric(metrics, 'cache.id.size', cache,
|
<|file_name|>model_box.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# File: model_box.py
import numpy as np
from collections import namedtuple
import tensorflow as tf
from tensorpack.tfutils.scope_utils import under_name_scope
from config import config
@under_name_scope()
def clip_boxes(boxes, window, name=None):
"""
Args:
boxes: nx4, xyxy
window: [h, w]
"""
boxes = tf.maximum(boxes, 0.0)
m = tf.tile(tf.reverse(window, [0]), [2]) # (4,)
boxes = tf.minimum(boxes, tf.to_float(m), name=name)
return boxes
@under_name_scope()
def decode_bbox_target(box_predictions, anchors):
"""
Args:
box_predictions: (..., 4), logits
anchors: (..., 4), floatbox. Must have the same shape
Returns:
box_decoded: (..., 4), float32. With the same shape.
"""
orig_shape = tf.shape(anchors)
box_pred_txtytwth = tf.reshape(box_predictions, (-1, 2, 2))
box_pred_txty, box_pred_twth = tf.split(box_pred_txtytwth, 2, axis=1)
# each is (...)x1x2
anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2))
anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y2, 2, axis=1)
waha = anchors_x2y2 - anchors_x1y1
xaya = (anchors_x2y2 + anchors_x1y1) * 0.5
clip = np.log(config.PREPROC.MAX_SIZE / 16.)
wbhb = tf.exp(tf.minimum(box_pred_twth, clip)) * waha
xbyb = box_pred_txty * waha + xaya
x1y1 = xbyb - wbhb * 0.5
x2y2 = xbyb + wbhb * 0.5 # (...)x1x2
out = tf.concat([x1y1, x2y2], axis=-2)
return tf.reshape(out, orig_shape)
@under_name_scope()
def encode_bbox_target(boxes, anchors):
"""
Args:
boxes: (..., 4), float32
anchors: (..., 4), float32
Returns:
box_encoded: (..., 4), float32 with the same shape.
"""
anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2))
anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y2, 2, axis=1)
waha = anchors_x2y2 - anchors_x1y1
xaya = (anchors_x2y2 + anchors_x1y1) * 0.5
boxes_x1y1x2y2 = tf.reshape(boxes, (-1, 2, 2))
boxes_x1y1, boxes_x2y2 = tf.split(boxes_x1y1x2y2, 2, axis=1)
wbhb = boxes_x2y2 - boxes_x1y1
xbyb = (boxes_x2y2 + boxes_x1y1) * 0.5
# Note that here not all boxes are valid. Some may be zero
txty = (xbyb - xaya) / waha
twth = tf.log(wbhb / waha) # may contain -inf for invalid boxes
encoded = tf.concat([txty, twth], axis=1) # (-1x2x2)
return tf.reshape(encoded, tf.shape(boxes))
@under_name_scope()
def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True):
"""
Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes.
Args:<|fim▁hole|> box_ind: (n,)
crop_size (int):
Returns:
n,C,size,size
"""
assert isinstance(crop_size, int), crop_size
boxes = tf.stop_gradient(boxes)
# TF's crop_and_resize produces zeros on border
if pad_border:
# this can be quite slow
image = tf.pad(image, [[0, 0], [0, 0], [1, 1], [1, 1]], mode='SYMMETRIC')
boxes = boxes + 1
@under_name_scope()
def transform_fpcoor_for_tf(boxes, image_shape, crop_shape):
"""
The way tf.image.crop_and_resize works (with normalized box):
Initial point (the value of output[0]): x0_box * (W_img - 1)
Spacing: w_box * (W_img - 1) / (W_crop - 1)
Use the above grid to bilinear sample.
However, what we want is (with fpcoor box):
Spacing: w_box / W_crop
Initial point: x0_box + spacing/2 - 0.5
(-0.5 because bilinear sample (in my definition) assumes floating point coordinate
(0.0, 0.0) is the same as pixel value (0, 0))
This function transform fpcoor boxes to a format to be used by tf.image.crop_and_resize
Returns:
y1x1y2x2
"""
x0, y0, x1, y1 = tf.split(boxes, 4, axis=1)
spacing_w = (x1 - x0) / tf.to_float(crop_shape[1])
spacing_h = (y1 - y0) / tf.to_float(crop_shape[0])
nx0 = (x0 + spacing_w / 2 - 0.5) / tf.to_float(image_shape[1] - 1)
ny0 = (y0 + spacing_h / 2 - 0.5) / tf.to_float(image_shape[0] - 1)
nw = spacing_w * tf.to_float(crop_shape[1] - 1) / tf.to_float(image_shape[1] - 1)
nh = spacing_h * tf.to_float(crop_shape[0] - 1) / tf.to_float(image_shape[0] - 1)
return tf.concat([ny0, nx0, ny0 + nh, nx0 + nw], axis=1)
# Expand bbox to a minium size of 1
# boxes_x1y1, boxes_x2y2 = tf.split(boxes, 2, axis=1)
# boxes_wh = boxes_x2y2 - boxes_x1y1
# boxes_center = tf.reshape((boxes_x2y2 + boxes_x1y1) * 0.5, [-1, 2])
# boxes_newwh = tf.maximum(boxes_wh, 1.)
# boxes_x1y1new = boxes_center - boxes_newwh * 0.5
# boxes_x2y2new = boxes_center + boxes_newwh * 0.5
# boxes = tf.concat([boxes_x1y1new, boxes_x2y2new], axis=1)
image_shape = tf.shape(image)[2:]
boxes = transform_fpcoor_for_tf(boxes, image_shape, [crop_size, crop_size])
image = tf.transpose(image, [0, 2, 3, 1]) # nhwc
ret = tf.image.crop_and_resize(
image, boxes, tf.to_int32(box_ind),
crop_size=[crop_size, crop_size])
ret = tf.transpose(ret, [0, 3, 1, 2]) # ncss
return ret
@under_name_scope()
def roi_align(featuremap, boxes, resolution):
"""
Args:
featuremap: 1xCxHxW
boxes: Nx4 floatbox
resolution: output spatial resolution
Returns:
NxCx res x res
"""
# sample 4 locations per roi bin
ret = crop_and_resize(
featuremap, boxes,
tf.zeros([tf.shape(boxes)[0]], dtype=tf.int32),
resolution * 2)
ret = tf.nn.avg_pool(ret, [1, 1, 2, 2], [1, 1, 2, 2], padding='SAME', data_format='NCHW')
return ret
class RPNAnchors(namedtuple('_RPNAnchors', ['boxes', 'gt_labels', 'gt_boxes'])):
"""
boxes (FS x FS x NA x 4): The anchor boxes.
gt_labels (FS x FS x NA):
gt_boxes (FS x FS x NA x 4): Groundtruth boxes corresponding to each anchor.
"""
def encoded_gt_boxes(self):
return encode_bbox_target(self.gt_boxes, self.boxes)
def decode_logits(self, logits):
return decode_bbox_target(logits, self.boxes)
@under_name_scope()
def narrow_to(self, featuremap):
"""
Slice anchors to the spatial size of this featuremap.
"""
shape2d = tf.shape(featuremap)[2:] # h,w
slice3d = tf.concat([shape2d, [-1]], axis=0)
slice4d = tf.concat([shape2d, [-1, -1]], axis=0)
boxes = tf.slice(self.boxes, [0, 0, 0, 0], slice4d)
gt_labels = tf.slice(self.gt_labels, [0, 0, 0], slice3d)
gt_boxes = tf.slice(self.gt_boxes, [0, 0, 0, 0], slice4d)
return RPNAnchors(boxes, gt_labels, gt_boxes)
if __name__ == '__main__':
"""
Demonstrate what's wrong with tf.image.crop_and_resize:
"""
import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()
# want to crop 2x2 out of a 5x5 image, and resize to 4x4
image = np.arange(25).astype('float32').reshape(5, 5)
boxes = np.asarray([[1, 1, 3, 3]], dtype='float32')
target = 4
print(crop_and_resize(
image[None, None, :, :], boxes, [0], target)[0][0])
"""
Expected values:
4.5 5 5.5 6
7 7.5 8 8.5
9.5 10 10.5 11
12 12.5 13 13.5
You cannot easily get the above results with tf.image.crop_and_resize.
Try out yourself here:
"""
print(tf.image.crop_and_resize(
image[None, :, :, None],
np.asarray([[1, 1, 2, 2]]) / 4.0, [0], [target, target])[0][:, :, 0])<|fim▁end|>
|
image: NCHW
boxes: nx4, x1y1x2y2
|
<|file_name|>test.js<|end_file_name|><|fim▁begin|>var successCount = 0;
for each (arg in args) {
if (process(arg)) {
successCount++;
}
}
write(successCount + " out of " + args.length + " benchmarks passed the test", "test.result");
exit();
function process(name) {
log = name + ".result";
s = "";
stgWork = import(name + ".g");
s += "Processing STG:\n";
s += " - importing: ";
if (stgWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
save(stgWork, name + ".stg.work");
s += " - verification: ";
if (checkStgCombined(stgWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - CSC check: ";
if (checkStgCsc(stgWork) == true) {
cscStgWork = stgWork;
s += "OK\n";
} else {
s += "CONFLICT\n";
s += " - Conflict resolution: ";
cscStgWork = resolveCscConflictMpsat(stgWork);
if (cscStgWork == null) {
cscStgWork = resolveCscConflictPetrify(stgWork);
if (cscStgWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
}
s += "OK\n";
save(cscStgWork, name + "-csc.stg.work");
}
s += "Complex gate:\n";
s += " - synthesis: ";
cgCircuitWork = synthComplexGateMpsat(cscStgWork);
if (cgCircuitWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - verification: ";
if (checkCircuitCombined(cgCircuitWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += "Generalised C-element:\n";
s += " - synthesis: ";
gcCircuitWork = synthGeneralisedCelementMpsat(cscStgWork);
if (gcCircuitWork == null) {
s += "FAILED\n";
write(s, log);
return false;<|fim▁hole|> s += "OK\n";
s += " - verification: ";
if (checkCircuitCombined(gcCircuitWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += "Standard C-element:\n";
s += " - synthesis: ";
stdcCircuitWork = synthStandardCelementMpsat(cscStgWork);
if (stdcCircuitWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - verification: ";
if (checkCircuitCombined(stdcCircuitWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += "Technology mapping:\n";
s += " - synthesis: ";
tmCircuitWork = synthTechnologyMappingMpsat(cscStgWork);
if (tmCircuitWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - verification: ";
if (checkCircuitCombined(tmCircuitWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
write(s, log);
return true;
}<|fim▁end|>
|
}
|
<|file_name|>faceTriangulation.C<|end_file_name|><|fim▁begin|>/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
foam-extend 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with foam-extend. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "faceTriangulation.H"
#include "plane.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
const Foam::scalar Foam::faceTriangulation::edgeRelTol = 1E-6;
// Edge to the right of face vertex i
Foam::label Foam::faceTriangulation::right(const label, label i)
{
return i;
}
// Edge to the left of face vertex i
Foam::label Foam::faceTriangulation::left(const label size, label i)
{
return i ? i-1 : size-1;
}
// Calculate (normalized) edge vectors.
// edges[i] gives edge between point i+1 and i.
Foam::tmp<Foam::vectorField> Foam::faceTriangulation::calcEdges
(
const face& f,
const pointField& points
)
{
tmp<vectorField> tedges(new vectorField(f.size()));
vectorField& edges = tedges();
forAll(f, i)
{
point thisPt = points[f[i]];
point nextPt = points[f[f.fcIndex(i)]];
vector vec(nextPt - thisPt);
vec /= mag(vec) + VSMALL;
edges[i] = vec;
}
return tedges;
}
// Calculates half angle components of angle from e0 to e1
void Foam::faceTriangulation::calcHalfAngle
(
const vector& normal,
const vector& e0,
const vector& e1,
scalar& cosHalfAngle,
scalar& sinHalfAngle
)
{
// truncate cos to +-1 to prevent negative numbers
scalar cos = max(-1, min(1, e0 & e1));
scalar sin = (e0 ^ e1) & normal;
if (sin < -ROOTVSMALL)
{
// 3rd or 4th quadrant
cosHalfAngle = - Foam::sqrt(0.5*(1 + cos));
sinHalfAngle = Foam::sqrt(0.5*(1 - cos));
}
else
{
// 1st or 2nd quadrant
cosHalfAngle = Foam::sqrt(0.5*(1 + cos));
sinHalfAngle = Foam::sqrt(0.5*(1 - cos));
}
}
// Calculate intersection point between edge p1-p2 and ray (in 2D).
// Return true and intersection point if intersection between p1 and p2.
Foam::pointHit Foam::faceTriangulation::rayEdgeIntersect
(
const vector& normal,
const point& rayOrigin,
const vector& rayDir,
const point& p1,
const point& p2,
scalar& posOnEdge
)
{
// Start off from miss
pointHit result(p1);
// Construct plane normal to rayDir and intersect
const vector y = normal ^ rayDir;
posOnEdge = plane(rayOrigin, y).normalIntersect(p1, (p2-p1));
// Check intersection to left of p1 or right of p2
if ((posOnEdge < 0) || (posOnEdge > 1))
{
// Miss
}
else
{
// Check intersection behind rayOrigin
point intersectPt = p1 + posOnEdge * (p2 - p1);
if (((intersectPt - rayOrigin) & rayDir) < 0)
{
// Miss
}
else
{
// Hit
result.setHit();
result.setPoint(intersectPt);
result.setDistance(mag(intersectPt - rayOrigin));
}
}
return result;
}
// Return true if triangle given its three points (anticlockwise ordered)
// contains point
bool Foam::faceTriangulation::triangleContainsPoint
(
const vector& n,
const point& p0,
const point& p1,
const point& p2,
const point& pt
)
{
scalar area01Pt = triPointRef(p0, p1, pt).normal() & n;
scalar area12Pt = triPointRef(p1, p2, pt).normal() & n;
scalar area20Pt = triPointRef(p2, p0, pt).normal() & n;
if ((area01Pt > 0) && (area12Pt > 0) && (area20Pt > 0))
{
return true;
}
else if ((area01Pt < 0) && (area12Pt < 0) && (area20Pt < 0))
{
FatalErrorIn("triangleContainsPoint") << abort(FatalError);
return false;
}
else
{
return false;
}
}
// Starting from startIndex find diagonal. Return in index1, index2.
// Index1 always startIndex except when convex polygon
void Foam::faceTriangulation::findDiagonal
(
const pointField& points,
const face& f,
const vectorField& edges,
const vector& normal,
const label startIndex,
label& index1,
label& index2
)
{
const point& startPt = points[f[startIndex]];
// Calculate angle at startIndex
const vector& rightE = edges[right(f.size(), startIndex)];
const vector leftE = -edges[left(f.size(), startIndex)];
// Construct ray which bisects angle
scalar cosHalfAngle = GREAT;
scalar sinHalfAngle = GREAT;
calcHalfAngle(normal, rightE, leftE, cosHalfAngle, sinHalfAngle);
vector rayDir
(
cosHalfAngle*rightE
+ sinHalfAngle*(normal ^ rightE)
);
// rayDir should be normalized already but is not due to rounding errors
// so normalize.
rayDir /= mag(rayDir) + VSMALL;
//
// Check all edges (apart from rightE and leftE) for nearest intersection
//
label faceVertI = f.fcIndex(startIndex);
pointHit minInter(false, vector::zero, GREAT, true);
label minIndex = -1;
scalar minPosOnEdge = GREAT;
for (label i = 0; i < f.size() - 2; i++)
{
scalar posOnEdge;
pointHit inter =
rayEdgeIntersect
(
normal,
startPt,
rayDir,
points[f[faceVertI]],
points[f[f.fcIndex(faceVertI)]],
posOnEdge
);
if (inter.hit() && inter.distance() < minInter.distance())
{
minInter = inter;
minIndex = faceVertI;
minPosOnEdge = posOnEdge;
}
faceVertI = f.fcIndex(faceVertI);
}
if (minIndex == -1)
{
//WarningIn("faceTriangulation::findDiagonal")
// << "Could not find intersection starting from " << f[startIndex]
// << " for face " << f << endl;
index1 = -1;
index2 = -1;
return;
}
const label leftIndex = minIndex;
const label rightIndex = f.fcIndex(minIndex);
// Now ray intersects edge from leftIndex to rightIndex.
// Check for intersection being one of the edge points. Make sure never
// to return two consecutive points.
if (mag(minPosOnEdge) < edgeRelTol && f.fcIndex(startIndex) != leftIndex)
{
index1 = startIndex;
index2 = leftIndex;
return;
}
if
(
mag(minPosOnEdge - 1) < edgeRelTol
&& f.fcIndex(rightIndex) != startIndex
)
{
index1 = startIndex;
index2 = rightIndex;
return;
}
// Select visible vertex that minimizes
// angle to bisection. Visibility checking by checking if inside triangle
// formed by startIndex, leftIndex, rightIndex
const point& leftPt = points[f[leftIndex]];
const point& rightPt = points[f[rightIndex]];
minIndex = -1;
scalar maxCos = -GREAT;
// all vertices except for startIndex and ones to left and right of it.
faceVertI = f.fcIndex(f.fcIndex(startIndex));
for (label i = 0; i < f.size() - 3; i++)
{
const point& pt = points[f[faceVertI]];
if
(
(faceVertI == leftIndex)
|| (faceVertI == rightIndex)
|| (triangleContainsPoint(normal, startPt, leftPt, rightPt, pt))
)
{
// pt inside triangle (so perhaps visible)
// Select based on minimal angle (so guaranteed visible).
vector edgePt0 = pt - startPt;
edgePt0 /= mag(edgePt0);
scalar cos = rayDir & edgePt0;
if (cos > maxCos)
{
maxCos = cos;
minIndex = faceVertI;
}
}
faceVertI = f.fcIndex(faceVertI);
}
if (minIndex == -1)
{
// no vertex found. Return startIndex and one of the intersected edge
// endpoints.
index1 = startIndex;
if (f.fcIndex(startIndex) != leftIndex)
{
index2 = leftIndex;
}
else
{
index2 = rightIndex;
}
return;
}
index1 = startIndex;
index2 = minIndex;
}
// Find label of vertex to start splitting from. Is:
// 1] flattest concave angle
// 2] flattest convex angle if no concave angles.
Foam::label Foam::faceTriangulation::findStart
(
const face& f,
const vectorField& edges,
const vector& normal
)
{
const label size = f.size();
scalar minCos = GREAT;
label minIndex = -1;
forAll(f, fp)
{
const vector& rightEdge = edges[right(size, fp)];
const vector leftEdge = -edges[left(size, fp)];
if (((rightEdge ^ leftEdge) & normal) < ROOTVSMALL)
{
scalar cos = rightEdge & leftEdge;
if (cos < minCos)
{
minCos = cos;
minIndex = fp;
}
}
}
if (minIndex == -1)
{
// No concave angle found. Get flattest convex angle
minCos = GREAT;
forAll(f, fp)
{
const vector& rightEdge = edges[right(size, fp)];
const vector leftEdge = -edges[left(size, fp)];
scalar cos = rightEdge & leftEdge;
if (cos < minCos)
{
minCos = cos;
minIndex = fp;
}
}
}
return minIndex;
}
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
// Split face f into triangles. Handles all simple (convex & concave)
// polygons.
bool Foam::faceTriangulation::split
(
const bool fallBack,
const pointField& points,
const face& f,
const vector& normal,
label& triI
)
{
const label size = f.size();<|fim▁hole|> (
"split(const bool, const pointField&, const face&"
", const vector&, label&)"
) << "Illegal face:" << f
<< " with points " << UIndirectList<point>(points, f)()
<< endl;
return false;
}
else if (size == 3)
{
// Triangle. Just copy.
triFace& tri = operator[](triI++);
tri[0] = f[0];
tri[1] = f[1];
tri[2] = f[2];
return true;
}
else
{
// General case. Start splitting for -flattest concave angle
// -or flattest convex angle if no concave angles.
tmp<vectorField> tedges(calcEdges(f, points));
const vectorField& edges = tedges();
label startIndex = findStart(f, edges, normal);
// Find diagonal to split face across
label index1 = -1;
label index2 = -1;
for (label iter = 0; iter < f.size(); iter++)
{
findDiagonal
(
points,
f,
edges,
normal,
startIndex,
index1,
index2
);
if (index1 != -1 && index2 != -1)
{
// Found correct diagonal
break;
}
// Try splitting from next startingIndex.
startIndex = f.fcIndex(startIndex);
}
if (index1 == -1 || index2 == -1)
{
if (fallBack)
{
// Do naive triangulation. Find smallest angle to start
// triangulating from.
label maxIndex = -1;
scalar maxCos = -GREAT;
forAll(f, fp)
{
const vector& rightEdge = edges[right(size, fp)];
const vector leftEdge = -edges[left(size, fp)];
scalar cos = rightEdge & leftEdge;
if (cos > maxCos)
{
maxCos = cos;
maxIndex = fp;
}
}
WarningIn
(
"split(const bool, const pointField&, const face&"
", const vector&, label&)"
) << "Cannot find valid diagonal on face " << f
<< " with points " << UIndirectList<point>(points, f)()
<< nl
<< "Returning naive triangulation starting from "
<< f[maxIndex] << " which might not be correct for a"
<< " concave or warped face" << endl;
label fp = f.fcIndex(maxIndex);
for (label i = 0; i < size-2; i++)
{
label nextFp = f.fcIndex(fp);
triFace& tri = operator[](triI++);
tri[0] = f[maxIndex];
tri[1] = f[fp];
tri[2] = f[nextFp];
fp = nextFp;
}
return true;
}
else
{
WarningIn
(
"split(const bool, const pointField&, const face&"
", const vector&, label&)"
) << "Cannot find valid diagonal on face " << f
<< " with points " << UIndirectList<point>(points, f)()
<< nl
<< "Returning empty triFaceList" << endl;
return false;
}
}
// Split into two subshapes.
// face1: index1 to index2
// face2: index2 to index1
// Get sizes of the two subshapes
label diff = 0;
if (index2 > index1)
{
diff = index2 - index1;
}
else
{
// folded round
diff = index2 + size - index1;
}
label nPoints1 = diff + 1;
label nPoints2 = size - diff + 1;
if (nPoints1 == size || nPoints2 == size)
{
FatalErrorIn
(
"split(const bool, const pointField&, const face&"
", const vector&, label&)"
) << "Illegal split of face:" << f
<< " with points " << UIndirectList<point>(points, f)()
<< " at indices " << index1 << " and " << index2
<< abort(FatalError);
}
// Collect face1 points
face face1(nPoints1);
label faceVertI = index1;
for (int i = 0; i < nPoints1; i++)
{
face1[i] = f[faceVertI];
faceVertI = f.fcIndex(faceVertI);
}
// Collect face2 points
face face2(nPoints2);
faceVertI = index2;
for (int i = 0; i < nPoints2; i++)
{
face2[i] = f[faceVertI];
faceVertI = f.fcIndex(faceVertI);
}
// Decompose the split faces
//Pout<< "Split face:" << f << " into " << face1 << " and " << face2
// << endl;
//string oldPrefix(Pout.prefix());
//Pout.prefix() = " " + oldPrefix;
bool splitOk =
split(fallBack, points, face1, normal, triI)
&& split(fallBack, points, face2, normal, triI);
//Pout.prefix() = oldPrefix;
return splitOk;
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
// Null constructor
Foam::faceTriangulation::faceTriangulation()
:
triFaceList()
{}
// Construct from components
Foam::faceTriangulation::faceTriangulation
(
const pointField& points,
const face& f,
const bool fallBack
)
:
triFaceList(f.size()-2)
{
vector avgNormal = f.normal(points);
avgNormal /= mag(avgNormal) + VSMALL;
label triI = 0;
bool valid = split(fallBack, points, f, avgNormal, triI);
if (!valid)
{
setSize(0);
}
}
// Construct from components
Foam::faceTriangulation::faceTriangulation
(
const pointField& points,
const face& f,
const vector& n,
const bool fallBack
)
:
triFaceList(f.size()-2)
{
label triI = 0;
bool valid = split(fallBack, points, f, n, triI);
if (!valid)
{
setSize(0);
}
}
// Construct from Istream
Foam::faceTriangulation::faceTriangulation(Istream& is)
:
triFaceList(is)
{}
// ************************************************************************* //<|fim▁end|>
|
if (size <= 2)
{
WarningIn
|
<|file_name|>las.rs<|end_file_name|><|fim▁begin|>//! Sink points into a las file.
use std::io::{Write, Seek};
use std::path::Path;
use las;
use Result;
use error::Error;
use point::{Point, ScanDirection};
use sink::{FileSink, Sink};
impl<W: Write + Seek> Sink for las::writer::OpenWriter<W> {
fn sink(&mut self, point: &Point) -> Result<()> {
try!(self.write_point(&try!(from_point(point))));
Ok(())
}
fn close_sink(self: Box<Self>) -> Result<()> {
self.close().map_err(|e| Error::from(e)).map(|_| ())
}
}
fn from_point(point: &Point) -> Result<las::Point> {
Ok(las::Point {
x: point.x,
y: point.y,
z: point.z,
intensity: point.intensity.as_u16(),
return_number: try!(las::point::ReturnNumber::from_u8(point.return_number.unwrap_or(0) as u8)),
number_of_returns: try!(las::point::NumberOfReturns::from_u8(point.number_of_returns.unwrap_or(0) as u8)),
scan_direction: match point.scan_direction {
ScanDirection::Forward | ScanDirection::Unknown => las::point::ScanDirection::Forward,
ScanDirection::Backward => las::point::ScanDirection::Backward
},
edge_of_flight_line: point.edge_of_flight_line,
classification: try!(las::point::Classification::from_u8(point.classification)),
synthetic: point.synthetic,
key_point: point.key_point,
withheld: point.withheld,
scan_angle_rank: point.scan_angle.unwrap_or(0.0) as i8,
user_data: point.user_data.unwrap_or(0),
point_source_id: point.point_source_id.unwrap_or(0),
gps_time: point.gps_time,
// FIXME these should be properties too
red: None,
green: None,
blue: None,
extra_bytes: None,
})
}
impl<W: Write + Seek> FileSink for las::Writer<W> {
type Config = LasConfig;
fn open_file_sink<P: AsRef<Path>>(path: P, config: LasConfig) -> Result<Box<Sink>> {
let mut writer = try!(las::Writer::from_path(path));
if let Some(s) = config.scale_factors {
writer = writer.scale_factors(s.x, s.y, s.z);
}
if let Some(a) = config.auto_offsets {
writer = writer.auto_offsets(a);
}
if let Some(p) = config.point_format {
writer = writer.point_format(try!(las::PointFormat::from_u8(p)));
}
if let Some(v) = config.version {
writer = writer.version(v.major, v.minor);
}
Ok(Box::new(try!(writer.open())))
}
}
/// Decodable configuration
#[derive(Clone, Copy, Debug, RustcDecodable)]
pub struct LasConfig {
scale_factors: Option<ScaleFactors>,
auto_offsets: Option<bool>,
point_format: Option<u8>,
version: Option<Version>,
}
impl Default for LasConfig {
fn default() -> LasConfig {
LasConfig {
auto_offsets: Some(true),
point_format: Some(1),
version: Some(Version { major: 1, minor: 2}),
scale_factors: None,
}
}
}
/// Simple wrapper around x, y, and z scale factors.
#[derive(Clone, Copy, Debug, RustcDecodable)]
pub struct ScaleFactors {
x: f64,
y: f64,
z: f64,
}
/// Simple wrapper around version pair.
#[derive(Clone, Copy, Debug, RustcDecodable)]
pub struct Version {
major: u8,
minor: u8,
}
#[cfg(test)]
mod tests {
use std::fs::remove_file;
use las;
use toml;
use sink::{open_file_sink, Sink};
use source::{open_file_source, Source};
#[test]
fn read_write_las() {
let mut source = las::Reader::from_path("data/1.0_0.las").unwrap();
let mut sink = las::Writer::from_path("read_write_las.las").unwrap().open().unwrap();
for point in &source.source_to_end(100).unwrap() {
sink.sink(point).unwrap()
}
let _ = sink.close().unwrap();
let mut source = las::Reader::from_path("read_write_las.las").unwrap();
let points = source.source_to_end(100).unwrap();
assert_eq!(1, points.len());
remove_file("read_write_las.las").unwrap();
}
#[test]
fn source_and_sink() {
let mut source = open_file_source("data/1.0_0.las", None).unwrap();
let config = toml::Parser::new(r#"
scale_factors = { x = 0.01, y = 0.01, z = 0.01 }<|fim▁hole|> version = { major = 1, minor = 2 }
"#)
.parse()
.unwrap();
let mut sink = open_file_sink("source_and_sink.las", Some(toml::Value::Table(config)))
.unwrap();
for point in &source.source_to_end(100).unwrap() {
sink.sink(point).unwrap();
}
sink.close_sink().unwrap();
let mut source = las::Reader::from_path("source_and_sink.las").unwrap();
let points = source.source_to_end(100).unwrap();
assert_eq!(1, points.len());
remove_file("source_and_sink.las").unwrap();
}
}<|fim▁end|>
|
point_format = 0
auto_offsets = true
|
<|file_name|>serializers.py<|end_file_name|><|fim▁begin|>"""
Serializers for Video Abstraction Layer
Serialization is usually sent through the VideoSerializer which uses the
EncodedVideoSerializer which uses the profile_name as it's profile field.
"""
from rest_framework import serializers
from django.core.exceptions import ValidationError
from edxval.models import Profile, Video, EncodedVideo, Subtitle, CourseVideo
class EncodedVideoSerializer(serializers.ModelSerializer):
"""
Serializer for EncodedVideo object.
Uses the profile_name as it's profile value instead of a Profile object.
"""
profile = serializers.SlugRelatedField(slug_field="profile_name")
class Meta: # pylint: disable=C1001, C0111
model = EncodedVideo
fields = (
"created",
"modified",
"url",
"file_size",
"bitrate",
"profile",
)
def get_identity(self, data):
"""
This hook is required for bulk update.
We need to override the default, to use the slug as the identity.
"""
return data.get('profile', None)
class SubtitleSerializer(serializers.ModelSerializer):
"""
Serializer for Subtitle objects
"""
content_url = serializers.CharField(source='get_absolute_url', read_only=True)
content = serializers.CharField(write_only=True)
def validate_content(self, attrs, source):
"""
Validate that the subtitle is in the correct format
"""
value = attrs[source]
if attrs.get('fmt') == 'sjson':
import json
try:
loaded = json.loads(value)
except ValueError:
raise serializers.ValidationError("Not in JSON format")
else:
attrs[source] = json.dumps(loaded)
return attrs
class Meta: # pylint: disable=C1001, C0111<|fim▁hole|> "fmt",
"language",
"content_url",
"content",
)
class CourseSerializer(serializers.RelatedField):
"""
Field for CourseVideo
"""
def to_native(self, value):
return value.course_id
def from_native(self, data):
if data:
course_video = CourseVideo(course_id=data)
course_video.full_clean(exclude=["video"])
return course_video
class VideoSerializer(serializers.ModelSerializer):
"""
Serializer for Video object
encoded_videos takes a list of dicts EncodedVideo data.
"""
encoded_videos = EncodedVideoSerializer(many=True, allow_add_remove=True)
subtitles = SubtitleSerializer(many=True, allow_add_remove=True, required=False)
courses = CourseSerializer(many=True, read_only=False)
url = serializers.SerializerMethodField('get_url')
class Meta: # pylint: disable=C1001, C0111
model = Video
lookup_field = "edx_video_id"
exclude = ('id',)
def get_url(self, obj):
"""
Return relative url for the object
"""
return obj.get_absolute_url()
def restore_fields(self, data, files):
"""
Overridden function used to check against duplicate profile names.
Converts a dictionary of data into a dictionary of deserialized fields. Also
checks if there are duplicate profile_name(s). If there is, the deserialization
is rejected.
"""
reverted_data = {}
if data is not None and not isinstance(data, dict):
self._errors['non_field_errors'] = ['Invalid data']
return None
try:
profiles = [ev["profile"] for ev in data.get("encoded_videos", [])]
if len(profiles) != len(set(profiles)):
self._errors['non_field_errors'] = ['Invalid data: duplicate profiles']
except KeyError:
raise ValidationError("profile required for deserializing")
except TypeError:
raise ValidationError("profile field needs to be a profile_name (str)")
for field_name, field in self.fields.items():
field.initialize(parent=self, field_name=field_name)
try:
field.field_from_native(data, files, field_name, reverted_data)
except ValidationError as err:
self._errors[field_name] = list(err.messages)
return reverted_data<|fim▁end|>
|
model = Subtitle
lookup_field = "id"
fields = (
|
<|file_name|>vmware_dvswitch.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: vmware_dvswitch
short_description: Create or remove a distributed vSwitch
description:
- Create or remove a distributed vSwitch
version_added: 2.0
author: "Joseph Callen (@jcpowermac)"
notes:
- Tested on vSphere 5.5
requirements:
- "python >= 2.6"
- PyVmomi
options:
datacenter_name:
description:
- The name of the datacenter that will contain the dvSwitch
required: True
switch_name:
description:
- The name of the switch to create or remove
required: True
mtu:
description:
- The switch maximum transmission unit
required: True
uplink_quantity:
description:
- Quantity of uplink per ESXi host added to the switch
required: True
discovery_proto:
description:
- Link discovery protocol between Cisco and Link Layer discovery
choices:
- 'cdp'
- 'lldp'
required: True
discovery_operation:
description:
- Select the discovery operation
choices:
- 'both'
- 'none'
- 'advertise'
- 'listen'
state:
description:
- Create or remove dvSwitch
default: 'present'
choices:
- 'present'
- 'absent'
required: False
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
- name: Create dvswitch<|fim▁hole|> module: vmware_dvswitch
hostname: vcenter_ip_or_hostname
username: vcenter_username
password: vcenter_password
datacenter_name: datacenter
switch_name: dvSwitch
mtu: 9000
uplink_quantity: 2
discovery_proto: lldp
discovery_operation: both
state: present
'''
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import (HAS_PYVMOMI,
connect_to_api,
find_datacenter_by_name,
find_dvs_by_name,
vmware_argument_spec,
wait_for_task
)
class VMwareDVSwitch(object):
def __init__(self, module):
self.module = module
self.dvs = None
self.switch_name = self.module.params['switch_name']
self.datacenter_name = self.module.params['datacenter_name']
self.mtu = self.module.params['mtu']
self.uplink_quantity = self.module.params['uplink_quantity']
self.discovery_proto = self.module.params['discovery_proto']
self.discovery_operation = self.module.params['discovery_operation']
self.state = self.module.params['state']
self.content = connect_to_api(module)
def process_state(self):
try:
dvs_states = {
'absent': {
'present': self.state_destroy_dvs,
'absent': self.state_exit_unchanged,
},
'present': {
'update': self.state_update_dvs,
'present': self.state_exit_unchanged,
'absent': self.state_create_dvs,
}
}
dvs_states[self.state][self.check_dvs_configuration()]()
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
except Exception as e:
self.module.fail_json(msg=str(e))
def create_dvswitch(self, network_folder):
result = None
changed = False
spec = vim.DistributedVirtualSwitch.CreateSpec()
spec.configSpec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec()
spec.configSpec.uplinkPortPolicy = vim.DistributedVirtualSwitch.NameArrayUplinkPortPolicy()
spec.configSpec.linkDiscoveryProtocolConfig = vim.host.LinkDiscoveryProtocolConfig()
spec.configSpec.name = self.switch_name
spec.configSpec.maxMtu = self.mtu
spec.configSpec.linkDiscoveryProtocolConfig.protocol = self.discovery_proto
spec.configSpec.linkDiscoveryProtocolConfig.operation = self.discovery_operation
spec.productInfo = vim.dvs.ProductSpec()
spec.productInfo.name = "DVS"
spec.productInfo.vendor = "VMware"
for count in range(1, self.uplink_quantity+1):
spec.configSpec.uplinkPortPolicy.uplinkPortName.append("uplink%d" % count)
task = network_folder.CreateDVS_Task(spec)
changed, result = wait_for_task(task)
return changed, result
def state_exit_unchanged(self):
self.module.exit_json(changed=False)
def state_destroy_dvs(self):
task = self.dvs.Destroy_Task()
changed, result = wait_for_task(task)
self.module.exit_json(changed=changed, result=str(result))
def state_update_dvs(self):
self.module.exit_json(changed=False, msg="Currently not implemented.")
def state_create_dvs(self):
changed = True
result = None
if not self.module.check_mode:
dc = find_datacenter_by_name(self.content, self.datacenter_name)
changed, result = self.create_dvswitch(dc.networkFolder)
self.module.exit_json(changed=changed, result=str(result))
def check_dvs_configuration(self):
self.dvs = find_dvs_by_name(self.content, self.switch_name)
if self.dvs is None:
return 'absent'
else:
return 'present'
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(dict(datacenter_name=dict(required=True, type='str'),
switch_name=dict(required=True, type='str'),
mtu=dict(required=True, type='int'),
uplink_quantity=dict(required=True, type='int'),
discovery_proto=dict(required=True, choices=['cdp', 'lldp'], type='str'),
discovery_operation=dict(required=True, choices=['both', 'none', 'advertise', 'listen'], type='str'),
state=dict(default='present', choices=['present', 'absent'], type='str')))
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_PYVMOMI:
module.fail_json(msg='pyvmomi is required for this module')
vmware_dvswitch = VMwareDVSwitch(module)
vmware_dvswitch.process_state()
if __name__ == '__main__':
main()<|fim▁end|>
|
local_action:
|
<|file_name|>neptune.py<|end_file_name|><|fim▁begin|>import math
class Neptune:
"""
NEPTUNE - VSOP87 Series Version C
HELIOCENTRIC DYNAMICAL ECLIPTIC AND EQUINOX OF THE DATE
Rectangular (X,Y,Z) Coordinates in AU (Astronomical Units)
Series Validity Span: 4000 BC < Date < 8000 AD
Theoretical accuracy over span: +-1 arc sec
R*R = X*X + Y*Y + Z*Z
t = (JD - 2451545) / 365250
C++ Programming Language
VSOP87 Functions Source Code
Generated By The VSOP87 Source Code Generator Tool
(c) Jay Tanner 2015
Ref:
Planetary Theories in Rectangular and Spherical Variables
VSOP87 Solutions
Pierre Bretagnon, Gerard Francou
Journal of Astronomy & Astrophysics
vol. 202, p309-p315
1988
Source code provided under the provisions of the
GNU General Public License (GPL), version 3.
http://www.gnu.org/licenses/gpl.html
"""
def __init__(self, t):
self.t = t
def calculate(self):
# Neptune_X0 (t) // 821 terms of order 0
X0 = 0
X0 += 30.05973100580 * math.cos(5.31188633083 + 38.3768531213 * self.t)
X0 += 0.40567587218 * math.cos(3.98149970131 + 0.2438174835 * self.t)
X0 += 0.13506026414 * math.cos(3.50055820972 + 76.50988875911 * self.t)
X0 += 0.15716341901 * math.cos(0.11310077968 + 36.892380413 * self.t)
X0 += 0.14935642614 * math.cos(1.08477702063 + 39.86132582961 * self.t)
X0 += 0.02590782232 * math.cos(1.99609768221 + 1.7282901918 * self.t)
X0 += 0.01073890204 * math.cos(5.38477153556 + 75.0254160508 * self.t)
X0 += 0.00816388197 * math.cos(0.78185518038 + 3.21276290011 * self.t)
X0 += 0.00702768075 * math.cos(1.45363642119 + 35.40790770471 * self.t)
X0 += 0.00687594822 * math.cos(0.72075739344 + 37.88921815429 * self.t)
X0 += 0.00565555652 * math.cos(5.98943773879 + 41.3457985379 * self.t)
X0 += 0.00495650075 * math.cos(0.59957534348 + 529.9347825781 * self.t)
X0 += 0.00306025380 * math.cos(0.39916788140 + 73.5409433425 * self.t)
X0 += 0.00272446904 * math.cos(0.87404115637 + 213.5429129215 * self.t)
X0 += 0.00135892298 * math.cos(5.54654979922 + 77.9943614674 * self.t)
X0 += 0.00122117697 * math.cos(1.30863876781 + 34.9202727377 * self.t)
X0 += 0.00090968285 * math.cos(1.68886748674 + 114.6429243969 * self.t)
X0 += 0.00068915400 * math.cos(5.83470374400 + 4.6972356084 * self.t)
X0 += 0.00040370680 * math.cos(2.66129691063 + 33.9234349964 * self.t)
X0 += 0.00028891307 * math.cos(4.78947715515 + 42.83027124621 * self.t)
X0 += 0.00029247752 * math.cos(1.62319522731 + 72.05647063421 * self.t)
X0 += 0.00025576289 * math.cos(1.48342967006 + 71.5688356672 * self.t)
X0 += 0.00020517968 * math.cos(2.55621077117 + 33.43580002939 * self.t)
X0 += 0.00012614154 * math.cos(3.56929744338 + 113.15845168861 * self.t)
X0 += 0.00012788929 * math.cos(2.73769634046 + 111.67397898031 * self.t)
X0 += 0.00012013477 * math.cos(0.94915799508 + 1059.6257476727 * self.t)
X0 += 0.00009854638 * math.cos(0.25713641240 + 36.404745446 * self.t)
X0 += 0.00008385825 * math.cos(1.65242210861 + 108.2173985967 * self.t)
X0 += 0.00007577585 * math.cos(0.09970777629 + 426.8420083595 * self.t)
X0 += 0.00006452053 * math.cos(4.62556526073 + 6.1817083167 * self.t)
X0 += 0.00006551074 * math.cos(1.91884050790 + 1.24065522479 * self.t)
X0 += 0.00004652534 * math.cos(0.10344003066 + 37.8555882595 * self.t)
X0 += 0.00004732958 * math.cos(4.09711900918 + 79.47883417571 * self.t)
X0 += 0.00004557247 * math.cos(1.09712661798 + 38.89811798311 * self.t)
X0 += 0.00004322550 * math.cos(2.37744779374 + 38.32866901151 * self.t)
X0 += 0.00004315539 * math.cos(5.10473140788 + 38.4250372311 * self.t)
X0 += 0.00004089036 * math.cos(1.99429063701 + 37.4136452748 * self.t)
X0 += 0.00004248658 * math.cos(5.63379709294 + 28.81562556571 * self.t)
X0 += 0.00004622142 * math.cos(2.73995451568 + 70.08436295889 * self.t)
X0 += 0.00003926447 * math.cos(5.48975060892 + 39.34006096781 * self.t)
X0 += 0.00003148422 * math.cos(5.18755364576 + 76.0222537921 * self.t)
X0 += 0.00003940981 * math.cos(2.29766376691 + 98.6561710411 * self.t)
X0 += 0.00003323363 * math.cos(4.68776245279 + 4.4366031775 * self.t)
X0 += 0.00003282964 * math.cos(2.81551282614 + 39.3736908626 * self.t)
X0 += 0.00003110464 * math.cos(1.84416897204 + 47.9380806769 * self.t)
X0 += 0.00002927062 * math.cos(2.83767313961 + 70.5719979259 * self.t)
X0 += 0.00002748919 * math.cos(3.86990252936 + 32.4389622881 * self.t)
X0 += 0.00003316668 * math.cos(1.82194084200 + 144.8659615262 * self.t)
X0 += 0.00002822405 * math.cos(3.78131048254 + 31.9513273211 * self.t)
X0 += 0.00002695972 * math.cos(3.85276301548 + 110.189506272 * self.t)
X0 += 0.00002522990 * math.cos(4.66308619966 + 311.9552664791 * self.t)
X0 += 0.00001888129 * math.cos(3.20464683230 + 35.9291725665 * self.t)
X0 += 0.00001648229 * math.cos(4.07040254381 + 30.300098274 * self.t)
X0 += 0.00001826545 * math.cos(3.58021128918 + 44.31474395451 * self.t)
X0 += 0.00001956241 * math.cos(4.14516146871 + 206.42936592071 * self.t)
X0 += 0.00001681257 * math.cos(4.27560127770 + 40.8245336761 * self.t)
X0 += 0.00001533383 * math.cos(1.17732213608 + 38.26497853671 * self.t)
X0 += 0.00001893076 * math.cos(0.75017402977 + 220.6564599223 * self.t)
X0 += 0.00001527526 * math.cos(0.02173638301 + 38.4887277059 * self.t)
X0 += 0.00002085691 * math.cos(1.56948272604 + 149.8070146181 * self.t)
X0 += 0.00002070612 * math.cos(2.82581806721 + 136.78920667889 * self.t)
X0 += 0.00001535699 * math.cos(0.61413315675 + 73.0533083755 * self.t)
X0 += 0.00001667976 * math.cos(2.91712458990 + 106.73292588839 * self.t)
X0 += 0.00001289620 * math.cos(3.39708861100 + 46.4536079686 * self.t)
X0 += 0.00001559811 * math.cos(0.55870841967 + 38.11622069041 * self.t)
X0 += 0.00001545705 * math.cos(0.64028776037 + 38.6374855522 * self.t)
X0 += 0.00001435033 * math.cos(0.72855949679 + 522.8212355773 * self.t)
X0 += 0.00001406206 * math.cos(3.61717027558 + 537.0483295789 * self.t)
X0 += 0.00001256446 * math.cos(2.70907758736 + 34.1840674273 * self.t)
X0 += 0.00001387973 * math.cos(3.71843398082 + 116.12739710521 * self.t)
X0 += 0.00001457739 * math.cos(1.98981635014 + 181.5145244557 * self.t)
X0 += 0.00001228429 * math.cos(2.78646343835 + 72.31710306511 * self.t)
X0 += 0.00001140665 * math.cos(3.96643713353 + 7.83293736379 * self.t)
X0 += 0.00001080801 * math.cos(4.75483465055 + 42.5696388153 * self.t)
X0 += 0.00001201409 * math.cos(0.74547986507 + 2.7251279331 * self.t)
X0 += 0.00001228671 * math.cos(2.65249731727 + 148.32254190981 * self.t)
X0 += 0.00000722014 * math.cos(6.16806714444 + 152.77596003471 * self.t)
X0 += 0.00000608545 * math.cos(4.49536985567 + 35.4560918145 * self.t)
X0 += 0.00000722865 * math.cos(3.09340262825 + 143.38148881789 * self.t)
X0 += 0.00000632820 * math.cos(3.41702130042 + 7.66618102501 * self.t)
X0 += 0.00000642369 * math.cos(3.97490787694 + 68.5998902506 * self.t)
X0 += 0.00000553789 * math.cos(2.98606728111 + 41.2976144281 * self.t)
X0 += 0.00000682276 * math.cos(2.15806346682 + 218.1630873852 * self.t)
X0 += 0.00000463186 * math.cos(2.74420554348 + 31.7845709823 * self.t)
X0 += 0.00000521560 * math.cos(0.34813640632 + 0.719390363 * self.t)
X0 += 0.00000437892 * math.cos(1.29807722623 + 1589.3167127673 * self.t)
X0 += 0.00000398091 * math.cos(5.50783691510 + 6.3484646555 * self.t)
X0 += 0.00000384065 * math.cos(4.72632236146 + 44.96913526031 * self.t)
X0 += 0.00000395583 * math.cos(5.05527677390 + 108.70503356371 * self.t)
X0 += 0.00000327446 * math.cos(2.69199709491 + 60.52313540329 * self.t)
X0 += 0.00000358824 * math.cos(4.99912098256 + 30.4668546128 * self.t)
X0 += 0.00000315179 * math.cos(0.17468500209 + 74.53778108379 * self.t)
X0 += 0.00000343384 * math.cos(1.74645896957 + 0.7650823453 * self.t)
X0 += 0.00000399611 * math.cos(5.33540800911 + 31.2633061205 * self.t)
X0 += 0.00000314611 * math.cos(2.98803024638 + 419.72846135871 * self.t)
X0 += 0.00000347596 * math.cos(3.26643963659 + 180.03005174739 * self.t)
X0 += 0.00000382279 * math.cos(0.21764578681 + 487.1213262793 * self.t)
X0 += 0.00000300918 * math.cos(4.04922612099 + 69.0875252176 * self.t)
X0 += 0.00000340448 * math.cos(3.90546849629 + 146.8380692015 * self.t)
X0 += 0.00000298710 * math.cos(5.18013539651 + 84.5866436064 * self.t)
X0 += 0.00000290629 * math.cos(1.74873675275 + 110.45013870291 * self.t)
X0 += 0.00000336211 * math.cos(2.14815098729 + 45.49040012211 * self.t)
X0 += 0.00000305606 * math.cos(5.63265481978 + 640.1411037975 * self.t)
X0 += 0.00000333702 * math.cos(2.32938316969 + 254.8116503147 * self.t)
X0 += 0.00000268060 * math.cos(3.30852201658 + 37.0042549976 * self.t)
X0 += 0.00000264760 * math.cos(4.12724058864 + 39.749451245 * self.t)
X0 += 0.00000315240 * math.cos(2.72241788492 + 388.70897272171 * self.t)
X0 += 0.00000227098 * math.cos(4.59157281152 + 273.8222308413 * self.t)
X0 += 0.00000306112 * math.cos(1.75345186469 + 6283.3196674749 * self.t)
X0 += 0.00000284373 * math.cos(3.36139825385 + 12.77399045571 * self.t)
X0 += 0.00000221105 * math.cos(3.50940363876 + 213.0552779545 * self.t)
X0 += 0.00000242568 * math.cos(2.06437650010 + 14.258463164 * self.t)
X0 += 0.00000241087 * math.cos(4.16115355874 + 105.2484531801 * self.t)
X0 += 0.00000226136 * math.cos(2.83815938853 + 80.963306884 * self.t)
X0 += 0.00000245904 * math.cos(0.54462524204 + 27.3311528574 * self.t)
X0 += 0.00000265825 * math.cos(4.10952660358 + 944.7390057923 * self.t)
X0 += 0.00000207893 * math.cos(5.07812851336 + 30.95448957981 * self.t)
X0 += 0.00000214661 * math.cos(2.65402494691 + 316.6356871401 * self.t)
X0 += 0.00000190638 * math.cos(2.32667703756 + 69.3963417583 * self.t)
X0 += 0.00000246295 * math.cos(1.98638488517 + 102.84895673509 * self.t)
X0 += 0.00000202915 * math.cos(0.60029260077 + 415.04804069769 * self.t)
X0 += 0.00000176465 * math.cos(0.14731292877 + 36.7805058284 * self.t)
X0 += 0.00000193886 * math.cos(3.35476299352 + 174.9222423167 * self.t)
X0 += 0.00000175209 * math.cos(1.12575693515 + 39.97320041421 * self.t)
X0 += 0.00000177868 * math.cos(3.43923391414 + 216.67861467689 * self.t)
X0 += 0.00000138494 * math.cos(5.45265920432 + 75.98862389731 * self.t)
X0 += 0.00000152234 * math.cos(4.81662104772 + 11.2895177474 * self.t)
X0 += 0.00000147648 * math.cos(1.68543706672 + 151.2914873264 * self.t)
X0 += 0.00000156202 * math.cos(3.65252575052 + 146.3504342345 * self.t)
X0 += 0.00000152289 * math.cos(0.07345728764 + 23.87457247379 * self.t)
X0 += 0.00000177911 * math.cos(3.17643554721 + 10213.5293636945 * self.t)
X0 += 0.00000162474 * math.cos(4.13351391379 + 63.9797157869 * self.t)
X0 += 0.00000121226 * math.cos(5.10584286197 + 38.16440480021 * self.t)
X0 += 0.00000129049 * math.cos(3.80684906955 + 37.1048287341 * self.t)
X0 += 0.00000120334 * math.cos(2.37637214462 + 38.5893014424 * self.t)
X0 += 0.00000168977 * math.cos(2.49551838497 + 291.4602132442 * self.t)
X0 += 0.00000121138 * math.cos(1.49657109299 + 33.26904369061 * self.t)
X0 += 0.00000129366 * math.cos(2.36903010922 + 45.7992166628 * self.t)
X0 += 0.00000144682 * math.cos(0.63023431786 + 49.42255338521 * self.t)
X0 += 0.00000122915 * math.cos(3.67433526761 + 39.6488775085 * self.t)
X0 += 0.00000113400 * math.cos(0.42160185021 + 83.1021708981 * self.t)
X0 += 0.00000154892 * math.cos(1.74989069653 + 77.4730966056 * self.t)
X0 += 0.00000106737 * math.cos(0.57437068095 + 4.8639919472 * self.t)
X0 += 0.00000104756 * math.cos(5.96272070512 + 43.484662552 * self.t)
X0 += 0.00000125142 * math.cos(5.82780261996 + 4.2096006414 * self.t)
X0 += 0.00000103541 * math.cos(5.25634741505 + 41.08516610701 * self.t)
X0 += 0.00000133573 * math.cos(3.92147215781 + 182.998997164 * self.t)
X0 += 0.00000103627 * math.cos(2.29256111601 + 35.6685401356 * self.t)
X0 += 0.00000116874 * math.cos(5.41378396536 + 62.4952430786 * self.t)
X0 += 0.00000098063 * math.cos(3.25654027665 + 9.8050450391 * self.t)
X0 += 0.00000111411 * math.cos(4.34345309647 + 141.8970161096 * self.t)
X0 += 0.00000114294 * math.cos(5.56228935636 + 633.0275567967 * self.t)
X0 += 0.00000104705 * math.cos(6.26072139356 + 433.9555553603 * self.t)
X0 += 0.00000121306 * math.cos(1.44892345337 + 40.8581635709 * self.t)
X0 += 0.00000096954 * math.cos(6.17373469303 + 1052.51220067191 * self.t)
X0 += 0.00000085104 * math.cos(4.79018222360 + 36.6799320919 * self.t)
X0 += 0.00000085209 * math.cos(5.94497188324 + 105.76971804189 * self.t)
X0 += 0.00000085291 * math.cos(2.59495207397 + 109.701871305 * self.t)
X0 += 0.00000083260 * math.cos(0.00625676877 + 529.44714761109 * self.t)
X0 += 0.00000080200 * math.cos(2.69199769694 + 40.07377415071 * self.t)
X0 += 0.00000107927 * math.cos(0.01570870082 + 1162.7185218913 * self.t)
X0 += 0.00000095241 * math.cos(3.61102256601 + 253.32717760639 * self.t)
X0 += 0.00000089535 * math.cos(3.25178384851 + 32.9602271499 * self.t)
X0 += 0.00000089793 * math.cos(2.76430560225 + 65.46418849521 * self.t)
X0 += 0.00000072027 * math.cos(0.11366576076 + 36.9405645228 * self.t)
X0 += 0.00000080381 * math.cos(5.21057317852 + 67.1154175423 * self.t)
X0 += 0.00000099502 * math.cos(2.53010647936 + 453.1810763355 * self.t)
X0 += 0.00000088685 * math.cos(1.33848394125 + 251.6759485593 * self.t)
X0 += 0.00000094971 * math.cos(4.11602347578 + 219.6475600935 * self.t)
X0 += 0.00000077015 * math.cos(5.30660266172 + 5.6604434549 * self.t)
X0 += 0.00000069098 * math.cos(1.84984192453 + 22.3900997655 * self.t)
X0 += 0.00000079079 * math.cos(4.12824954018 + 44.48150029329 * self.t)
X0 += 0.00000069159 * math.cos(3.95901333551 + 1066.7392946735 * self.t)
X0 += 0.00000064446 * math.cos(4.03076164648 + 66.9486612035 * self.t)
X0 += 0.00000088518 * math.cos(2.66179796694 + 328.1087761737 * self.t)
X0 += 0.00000065817 * math.cos(1.42821476263 + 36.3711155512 * self.t)
X0 += 0.00000071422 * math.cos(4.23104971231 + 43.79347909271 * self.t)
X0 += 0.00000063298 * math.cos(2.21146718451 + 9.1506537333 * self.t)
X0 += 0.00000077320 * math.cos(0.26842720811 + 97.17169833279 * self.t)
X0 += 0.00000073912 * math.cos(1.72397638430 + 2.6769438233 * self.t)
X0 += 0.00000073965 * math.cos(5.55809543248 + 2.9521304692 * self.t)
X0 += 0.00000056194 * math.cos(4.45857439361 + 949.4194264533 * self.t)
X0 += 0.00000059173 * math.cos(1.41372632607 + 100.14064374939 * self.t)
X0 += 0.00000067507 * math.cos(3.94700376513 + 7.14491616321 * self.t)
X0 += 0.00000071718 * math.cos(0.93392607299 + 2.20386307129 * self.t)
X0 += 0.00000063606 * math.cos(5.17175542607 + 25.8466801491 * self.t)
X0 += 0.00000071523 * math.cos(2.05830478088 + 662.28738607949 * self.t)
X0 += 0.00000057219 * math.cos(0.88485013288 + 15.7429358723 * self.t)
X0 += 0.00000050322 * math.cos(1.08310288762 + 37.15301284391 * self.t)
X0 += 0.00000066615 * math.cos(3.42462264660 + 846.3266522347 * self.t)
X0 += 0.00000056220 * math.cos(4.52386924168 + 178.5455790391 * self.t)
X0 += 0.00000067883 * math.cos(3.88546727303 + 224.5886131854 * self.t)
X0 += 0.00000057761 * math.cos(5.16493680948 + 145.35359649321 * self.t)
X0 += 0.00000053973 * math.cos(6.25404762289 + 107.2205608554 * self.t)
X0 += 0.00000057588 * math.cos(4.84839311245 + 25.3590451821 * self.t)
X0 += 0.00000049026 * math.cos(1.27836371915 + 19.2543980101 * self.t)
X0 += 0.00000063036 * math.cos(4.29760573349 + 256.296123023 * self.t)
X0 += 0.00000045304 * math.cos(0.86492921312 + 4.1759707466 * self.t)
X0 += 0.00000045669 * math.cos(2.17547535945 + 117.6118698135 * self.t)
X0 += 0.00000052821 * math.cos(3.77933473571 + 289.97574053589 * self.t)
X0 += 0.00000044016 * math.cos(2.25498623278 + 32.7477788288 * self.t)
X0 += 0.00000042933 * math.cos(6.21504221321 + 28.98238190449 * self.t)
X0 += 0.00000038369 * math.cos(0.36602717013 + 39.6006933987 * self.t)
X0 += 0.00000038805 * math.cos(4.12403932769 + 103.3365917021 * self.t)
X0 += 0.00000037679 * math.cos(3.40097359574 + 9.3174100721 * self.t)
X0 += 0.00000040292 * math.cos(6.03933270535 + 111.18634401329 * self.t)
X0 += 0.00000050011 * math.cos(6.19966711969 + 221.61966776881 * self.t)
X0 += 0.00000037056 * math.cos(4.63008749202 + 8.32057233081 * self.t)
X0 += 0.00000036562 * math.cos(0.18548635975 + 448.98829064149 * self.t)
X0 += 0.00000044628 * math.cos(3.82762130859 + 525.2543619171 * self.t)
X0 += 0.00000038213 * math.cos(0.28030378709 + 75.54668091261 * self.t)
X0 += 0.00000045963 * math.cos(4.06403723861 + 183.486632131 * self.t)
X0 += 0.00000048222 * math.cos(2.81328685847 + 364.7573391032 * self.t)
X0 += 0.00000038164 * math.cos(5.23367149002 + 44.00592741381 * self.t)
X0 += 0.00000047779 * math.cos(6.19272750750 + 3340.8562441833 * self.t)
X0 += 0.00000042228 * math.cos(5.64690940917 + 77.0311536209 * self.t)
X0 += 0.00000035247 * math.cos(0.20766845689 + 34.7535163989 * self.t)
X0 += 0.00000046804 * math.cos(3.96902162832 + 33.6964324603 * self.t)
X0 += 0.00000034352 * math.cos(1.08289070011 + 33.71098667531 * self.t)
X0 += 0.00000034949 * math.cos(2.01384094499 + 3.37951923889 * self.t)
X0 += 0.00000036030 * math.cos(2.17275904548 + 71.09326278771 * self.t)
X0 += 0.00000038112 * math.cos(5.65470955047 + 45.9659730016 * self.t)
X0 += 0.00000033119 * math.cos(5.27794057043 + 7.3573644843 * self.t)
X0 += 0.00000032049 * math.cos(4.61840704188 + 34.44469985821 * self.t)
X0 += 0.00000031910 * math.cos(1.77890975693 + 81.61769818981 * self.t)
X0 += 0.00000038697 * math.cos(2.66910057126 + 184.97110483931 * self.t)
X0 += 0.00000041486 * math.cos(2.58550378076 + 310.4707937708 * self.t)
X0 += 0.00000038631 * math.cos(2.31715796823 + 50.9070260935 * self.t)
X0 += 0.00000042711 * math.cos(2.19232104972 + 1021.49271203491 * self.t)
X0 += 0.00000032006 * math.cos(0.97590559431 + 42.00018984371 * self.t)
X0 += 0.00000038436 * math.cos(0.31352578874 + 5.92107588581 * self.t)
X0 += 0.00000038880 * math.cos(3.29381198979 + 76.55807286891 * self.t)
X0 += 0.00000041190 * math.cos(4.58002024645 + 563.87503252191 * self.t)
X0 += 0.00000029786 * math.cos(1.00565266044 + 77.5067265004 * self.t)
X0 += 0.00000040604 * math.cos(4.47511985144 + 292.9446859525 * self.t)
X0 += 0.00000035275 * math.cos(1.67517293934 + 304.84171947829 * self.t)
X0 += 0.00000038242 * math.cos(2.80091349300 + 17.76992530181 * self.t)
X0 += 0.00000034445 * math.cos(4.48124108827 + 319.06881347989 * self.t)
X0 += 0.00000028725 * math.cos(5.51593817617 + 67.6366824041 * self.t)
X0 += 0.00000032809 * math.cos(5.57900930431 + 91.54262404029 * self.t)
X0 += 0.00000038880 * math.cos(0.56654650956 + 76.4617046493 * self.t)
X0 += 0.00000030731 * math.cos(5.22467991145 + 67.60305250931 * self.t)
X0 += 0.00000028459 * math.cos(0.11298908847 + 43.0427195673 * self.t)
X0 += 0.00000035368 * math.cos(3.56936550095 + 313.43973918739 * self.t)
X0 += 0.00000035703 * math.cos(0.06787236157 + 258.26823069831 * self.t)
X0 += 0.00000032317 * math.cos(2.30071476395 + 78.9575693139 * self.t)
X0 += 0.00000029243 * math.cos(0.30724049567 + 61.01077037031 * self.t)
X0 += 0.00000026235 * math.cos(3.88058959053 + 137.2768416459 * self.t)
X0 += 0.00000026519 * math.cos(6.20266742881 + 57.4993082325 * self.t)
X0 += 0.00000024931 * math.cos(5.73688334159 + 42.997027585 * self.t)
X0 += 0.00000027608 * math.cos(5.39681935370 + 103.7639804718 * self.t)
X0 += 0.00000028680 * math.cos(4.65490114562 + 215.1941419686 * self.t)
X0 += 0.00000025052 * math.cos(5.70195779765 + 350.08830211689 * self.t)
X0 += 0.00000031386 * math.cos(4.10756442698 + 22.22334342671 * self.t)
X0 += 0.00000027545 * math.cos(1.30787829275 + 100.6282787164 * self.t)
X0 += 0.00000022617 * math.cos(3.46251776435 + 36.8441963032 * self.t)
X0 += 0.00000024909 * math.cos(0.20851017271 + 24.36220744081 * self.t)
X0 += 0.00000026216 * math.cos(4.94808817995 + 491.8017469403 * self.t)
X0 += 0.00000028040 * math.cos(2.83295165264 + 11.55015017831 * self.t)
X0 += 0.00000023047 * math.cos(4.24570423583 + 35.51978228931 * self.t)
X0 += 0.00000027067 * math.cos(3.95547247738 + 326.62430346539 * self.t)
X0 += 0.00000026192 * math.cos(2.35959813381 + 20.7388707184 * self.t)
X0 += 0.00000023134 * math.cos(2.59485537406 + 68.4331339118 * self.t)
X0 += 0.00000021423 * math.cos(0.87822750255 + 39.90950993941 * self.t)
X0 += 0.00000025696 * math.cos(0.32414101638 + 186.4555775476 * self.t)
X0 += 0.00000026985 * math.cos(3.53264939991 + 69.6087900794 * self.t)
X0 += 0.00000023284 * math.cos(2.71588030137 + 79.43065006591 * self.t)
X0 += 0.00000022894 * math.cos(0.61847067768 + 227.77000692311 * self.t)
X0 += 0.00000022482 * math.cos(0.72349596890 + 39.8131417198 * self.t)
X0 += 0.00000023480 * math.cos(4.39643703557 + 30.9881194746 * self.t)
X0 += 0.00000020858 * math.cos(3.23577429095 + 41.2339239533 * self.t)
X0 += 0.00000020327 * math.cos(1.15567976096 + 39.0312444271 * self.t)
X0 += 0.00000020327 * math.cos(0.04331485179 + 37.72246181551 * self.t)
X0 += 0.00000022639 * math.cos(0.21515321589 + 0.9800227939 * self.t)
X0 += 0.00000022639 * math.cos(0.21515321589 + 1.46765776091 * self.t)
X0 += 0.00000019139 * math.cos(0.03506366059 + 205.9417309537 * self.t)
X0 += 0.00000019118 * math.cos(1.62564867989 + 2119.00767786191 * self.t)
X0 += 0.00000025698 * math.cos(2.97643019475 + 401.4059020327 * self.t)
X0 += 0.00000021582 * math.cos(4.29532713983 + 81.13006322279 * self.t)
X0 += 0.00000025509 * math.cos(4.64829559110 + 329.593248882 * self.t)
X0 += 0.00000024296 * math.cos(2.11682013072 + 62.0076081116 * self.t)
X0 += 0.00000023969 * math.cos(0.88887585882 + 135.3047339706 * self.t)
X0 += 0.00000020599 * math.cos(4.51946091131 + 491.3141119733 * self.t)
X0 += 0.00000016829 * math.cos(5.63589438225 + 3.1645787903 * self.t)
X0 += 0.00000020030 * math.cos(4.02146628228 + 217.4750661846 * self.t)
X0 += 0.00000020377 * math.cos(0.89378346451 + 209.6107596584 * self.t)
X0 += 0.00000017251 * math.cos(2.57319624936 + 350.5759370839 * self.t)
X0 += 0.00000019625 * math.cos(6.12382765898 + 129.6756596781 * self.t)
X0 += 0.00000022707 * math.cos(5.69106089810 + 1436.2969352491 * self.t)
X0 += 0.00000017142 * math.cos(0.00501932570 + 29.4700168715 * self.t)
X0 += 0.00000016188 * math.cos(4.90861200887 + 39.00999256771 * self.t)
X0 += 0.00000016188 * math.cos(2.57356791106 + 37.7437136749 * self.t)
X0 += 0.00000020858 * math.cos(4.67505024087 + 58.9837809408 * self.t)
X0 += 0.00000015747 * math.cos(1.88900821622 + 154.260432743 * self.t)
X0 += 0.00000019714 * math.cos(0.33238117487 + 294.91679362781 * self.t)
X0 += 0.00000019078 * math.cos(2.73754913300 + 202.4972126576 * self.t)
X0 += 0.00000021530 * math.cos(3.37996249680 + 114.1552894299 * self.t)
X0 += 0.00000019068 * math.cos(1.82733694293 + 138.2736793872 * self.t)
X0 += 0.00000018723 * math.cos(6.21404671018 + 323.74923414091 * self.t)
X0 += 0.00000018916 * math.cos(5.47002080885 + 40.3825906914 * self.t)
X0 += 0.00000015843 * math.cos(0.27660393480 + 72.577735496 * self.t)
X0 += 0.00000020695 * math.cos(5.32080415125 + 86.07111631471 * self.t)
X0 += 0.00000015895 * math.cos(5.73200518668 + 736.1203310153 * self.t)
X0 += 0.00000014983 * math.cos(2.13549071268 + 743.23387801611 * self.t)
X0 += 0.00000014928 * math.cos(0.78464963633 + 34.23225153711 * self.t)
X0 += 0.00000015461 * math.cos(6.04598420333 + 20.850745303 * self.t)
X0 += 0.00000016206 * math.cos(6.05974800797 + 138.76131435421 * self.t)
X0 += 0.00000015978 * math.cos(0.85734083354 + 515.70768857651 * self.t)
X0 += 0.00000014173 * math.cos(2.99587831656 + 99.1438060081 * self.t)
X0 += 0.00000018749 * math.cos(3.37545937432 + 54.5303628159 * self.t)
X0 += 0.00000013971 * math.cos(5.11256155147 + 76.77052119001 * self.t)
X0 += 0.00000013971 * math.cos(5.03098185419 + 76.2492563282 * self.t)
X0 += 0.00000014035 * math.cos(4.45768361334 + 235.68919520349 * self.t)
X0 += 0.00000018894 * math.cos(4.59865824553 + 31.4757544416 * self.t)
X0 += 0.00000014967 * math.cos(0.97104009185 + 52.3914988018 * self.t)
X0 += 0.00000017392 * math.cos(1.69348450373 + 74.0622082043 * self.t)
X0 += 0.00000014788 * math.cos(5.00944229014 + 56.01483552421 * self.t)
X0 += 0.00000015758 * math.cos(5.97423795440 + 208.8624922605 * self.t)
X0 += 0.00000012911 * math.cos(0.41434497695 + 42.5214547055 * self.t)
X0 += 0.00000014356 * math.cos(4.89778066710 + 251.8427048981 * self.t)
X0 += 0.00000016266 * math.cos(4.96350311575 + 853.4401992355 * self.t)
X0 += 0.00000015513 * math.cos(1.02523907534 + 59.038662695 * self.t)
X0 += 0.00000012783 * math.cos(2.34267333656 + 107.52937739611 * self.t)
X0 += 0.00000016075 * math.cos(4.73335524561 + 366.24181181149 * self.t)
X0 += 0.00000014277 * math.cos(4.88488299527 + 19.36627259471 * self.t)
X0 += 0.00000014742 * math.cos(1.55115458505 + 82.4477795923 * self.t)
X0 += 0.00000015111 * math.cos(4.13629021798 + 363.27286639489 * self.t)
X0 += 0.00000014981 * math.cos(5.88358063018 + 82.6145359311 * self.t)
X0 += 0.00000014840 * math.cos(0.62836299110 + 44.0541115236 * self.t)
X0 += 0.00000015592 * math.cos(1.03195525294 + 8.6293888715 * self.t)
X0 += 0.00000014568 * math.cos(2.02105422692 + 73.80157577341 * self.t)
X0 += 0.00000012251 * math.cos(1.18824225128 + 47.28368937111 * self.t)
X0 += 0.00000011447 * math.cos(0.91374266731 + 175.40987728371 * self.t)
X0 += 0.00000013900 * math.cos(5.64591952885 + 700.4204217173 * self.t)
X0 += 0.00000015583 * math.cos(3.88966860773 + 837.4534458797 * self.t)
X0 += 0.00000012109 * math.cos(2.10142517621 + 33.0084112597 * self.t)
X0 += 0.00000012379 * math.cos(5.59016916358 + 140.4125434013 * self.t)
X0 += 0.00000011481 * math.cos(5.22670638349 + 39.2069345238 * self.t)
X0 += 0.00000011481 * math.cos(2.25547353643 + 37.54677171881 * self.t)
X0 += 0.00000011452 * math.cos(1.21111994028 + 529.4135177163 * self.t)
X0 += 0.00000010981 * math.cos(0.01852111423 + 63.49208081989 * self.t)
X0 += 0.00000012137 * math.cos(2.33017731448 + 42.3090063844 * self.t)
X0 += 0.00000013771 * math.cos(4.49397894473 + 76.62176334371 * self.t)
X0 += 0.00000011036 * math.cos(3.16457889057 + 530.45604743991 * self.t)
X0 += 0.00000011537 * math.cos(4.29449656032 + 199.3158189199 * self.t)
X0 += 0.00000011189 * math.cos(3.24467764115 + 80.1332254815 * self.t)
X0 += 0.00000012835 * math.cos(1.26831311464 + 38.85242600079 * self.t)
X0 += 0.00000012879 * math.cos(4.74400685998 + 5.69407334969 * self.t)
X0 += 0.00000013663 * math.cos(3.12818073078 + 438.0544649622 * self.t)
X0 += 0.00000010132 * math.cos(4.37559264666 + 187.9400502559 * self.t)
X0 += 0.00000012619 * math.cos(4.66177013386 + 65.2035560643 * self.t)
X0 += 0.00000010088 * math.cos(6.12382762451 + 26.58288545949 * self.t)
X0 += 0.00000011959 * math.cos(5.90953104234 + 64.7159210973 * self.t)
X0 += 0.00000011578 * math.cos(4.24710384177 + 275.3067035496 * self.t)
X0 += 0.00000012795 * math.cos(3.23836197733 + 17.8817998864 * self.t)
X0 += 0.00000013771 * math.cos(5.64956481971 + 76.3980141745 * self.t)
X0 += 0.00000010044 * math.cos(0.10145082472 + 147.83490694279 * self.t)
X0 += 0.00000013632 * math.cos(2.86683446064 + 45.277951801 * self.t)
X0 += 0.00000011660 * math.cos(2.65801239040 + 143.9027536797 * self.t)
X0 += 0.00000009938 * math.cos(4.21970476320 + 6.86972951729 * self.t)
X0 += 0.00000009719 * math.cos(6.05786462616 + 956.53297345411 * self.t)
X0 += 0.00000011441 * math.cos(0.61314587598 + 533.8669358412 * self.t)
X0 += 0.00000010240 * math.cos(2.91846731922 + 80.7026744531 * self.t)
X0 += 0.00000010031 * math.cos(5.38075474506 + 43.74529498291 * self.t)
X0 += 0.00000010063 * math.cos(5.77064020369 + 0.27744737829 * self.t)
X0 += 0.00000011428 * math.cos(3.77013145660 + 526.00262931501 * self.t)
X0 += 0.00000009279 * math.cos(6.16721103485 + 79.6455905145 * self.t)
X0 += 0.00000010172 * math.cos(2.46540726742 + 568.0678182159 * self.t)
X0 += 0.00000009198 * math.cos(5.07759437389 + 112.6708167216 * self.t)
X0 += 0.00000009831 * math.cos(2.49002547943 + 20.9056270572 * self.t)
X0 += 0.00000009830 * math.cos(3.51040521049 + 544.1618765797 * self.t)
X0 += 0.00000008646 * math.cos(4.49185896918 + 30.7756711535 * self.t)
X0 += 0.00000009315 * math.cos(0.15689765715 + 65.63094483399 * self.t)
X0 += 0.00000009201 * math.cos(0.09219461091 + 184.48346987229 * self.t)
X0 += 0.00000008674 * math.cos(2.01170720350 + 624.1543504417 * self.t)
X0 += 0.00000010739 * math.cos(0.49719235939 + 331.56535655731 * self.t)
X0 += 0.00000009612 * math.cos(5.38629260665 + 182.00215942271 * self.t)
X0 += 0.00000008664 * math.cos(5.62437013922 + 1479.11039154791 * self.t)
X0 += 0.00000008092 * math.cos(5.65922856578 + 6.8360996225 * self.t)
X0 += 0.00000010092 * math.cos(4.71596617075 + 419.2408263917 * self.t)
X0 += 0.00000010233 * math.cos(4.88231209018 + 402.89037474099 * self.t)
X0 += 0.00000008502 * math.cos(2.03567120581 + 17.39416491939 * self.t)
X0 += 0.00000010189 * math.cos(2.58985636739 + 21.7020785649 * self.t)
X0 += 0.00000009829 * math.cos(5.23644081358 + 121.2352065359 * self.t)
X0 += 0.00000008406 * math.cos(2.47191018350 + 376.9150050599 * self.t)
X0 += 0.00000008060 * math.cos(5.62304271115 + 415.7963080956 * self.t)
X0 += 0.00000009455 * math.cos(0.06796991442 + 167.80869531589 * self.t)
X0 += 0.00000007941 * math.cos(1.43287391293 + 526.7533888404 * self.t)
X0 += 0.00000007870 * math.cos(2.90339733997 + 533.1161763158 * self.t)
X0 += 0.00000007695 * math.cos(0.92731028198 + 906.60597015449 * self.t)
X0 += 0.00000007862 * math.cos(0.91484097138 + 1265.81129610991 * self.t)
X0 += 0.00000008062 * math.cos(1.12885573257 + 105.7360881471 * self.t)
X0 += 0.00000008904 * math.cos(4.30824949636 + 399.9214293244 * self.t)
X0 += 0.00000008050 * math.cos(0.14722556593 + 143.8691237849 * self.t)
X0 += 0.00000009102 * math.cos(4.77518241515 + 348.17644063891 * self.t)
X0 += 0.00000007137 * math.cos(1.26110622464 + 117.5636857037 * self.t)
X0 += 0.00000007076 * math.cos(3.19957487812 + 26.84351789039 * self.t)
X0 += 0.00000008418 * math.cos(1.48515415206 + 77.73372903651 * self.t)
X0 += 0.00000008257 * math.cos(4.44435970504 + 117.77862615229 * self.t)
X0 += 0.00000007868 * math.cos(5.07706724776 + 288.4912678276 * self.t)
X0 += 0.00000008093 * math.cos(0.41458983168 + 1692.40948698591 * self.t)
X0 += 0.00000006910 * math.cos(0.44789832682 + 216.72430665921 * self.t)
X0 += 0.00000007092 * math.cos(0.01337002281 + 452.65981147369 * self.t)
X0 += 0.00000007060 * math.cos(1.93108090539 + 453.7023411973 * self.t)
X0 += 0.00000008233 * math.cos(3.50880140177 + 480.00777927849 * self.t)
X0 += 0.00000006772 * math.cos(4.46250089888 + 210.36151918381 * self.t)
X0 += 0.00000007025 * math.cos(1.42668370417 + 55.9029609396 * self.t)
X0 += 0.00000008356 * math.cos(2.10000097648 + 95.7354097343 * self.t)
X0 += 0.00000007404 * math.cos(1.00293545057 + 75.2860484817 * self.t)
X0 += 0.00000006839 * math.cos(0.99943444853 + 41.5125548767 * self.t)
X0 += 0.00000007909 * math.cos(1.64368221183 + 36.63174798211 * self.t)
X0 += 0.00000007909 * math.cos(2.69690505451 + 40.12195826051 * self.t)
X0 += 0.00000006362 * math.cos(0.26347531595 + 29.99128173331 * self.t)
X0 += 0.00000006712 * math.cos(0.84138813413 + 133.82026126229 * self.t)
X0 += 0.00000007571 * math.cos(2.81738238064 + 23.707816135 * self.t)
X0 += 0.00000006677 * math.cos(0.10164158344 + 1.20702533 * self.t)
X0 += 0.00000007600 * math.cos(0.07294781428 + 494.2348732801 * self.t)
X0 += 0.00000008009 * math.cos(0.39086308190 + 170.72945662269 * self.t)
X0 += 0.00000007584 * math.cos(6.04989436828 + 119.2630988606 * self.t)
X0 += 0.00000006599 * math.cos(2.25520576507 + 32.226513967 * self.t)
X0 += 0.00000006085 * math.cos(4.97064703625 + 322.00412900171 * self.t)
X0 += 0.00000005953 * math.cos(2.49854544351 + 52214.1831362697 * self.t)
X0 += 0.00000007827 * math.cos(3.28593277837 + 474.7030278917 * self.t)
X0 += 0.00000007907 * math.cos(4.46293464979 + 485.63685357099 * self.t)
X0 += 0.00000007372 * math.cos(4.88712847504 + 55.05162767771 * self.t)
X0 += 0.00000006966 * math.cos(5.60552242454 + 647.25465079831 * self.t)
X0 += 0.00000006266 * math.cos(5.78133779594 + 177.0611063308 * self.t)
X0 += 0.00000005900 * math.cos(4.92602771915 + 52061.16335875149 * self.t)
X0 += 0.00000006221 * math.cos(2.35523958706 + 602.00806815971 * self.t)
X0 += 0.00000005552 * math.cos(5.87735995607 + 223.1041404771 * self.t)
X0 += 0.00000005976 * math.cos(1.83099110545 + 10.8018827804 * self.t)
X0 += 0.00000007600 * math.cos(5.33804556108 + 488.6057989876 * self.t)
X0 += 0.00000006831 * math.cos(0.04615498459 + 1582.2031657665 * self.t)
X0 += 0.00000005654 * math.cos(3.04032114806 + 12604.5285531041 * self.t)
X0 += 0.00000005798 * math.cos(1.13675043219 + 27.4979091962 * self.t)
X0 += 0.00000007216 * math.cos(0.18192294134 + 739.0410923221 * self.t)
X0 += 0.00000006579 * math.cos(3.94809746775 + 2.69149803831 * self.t)
X0 += 0.00000005758 * math.cos(2.82344188087 + 30.0394658431 * self.t)
X0 += 0.00000005270 * math.cos(3.46743079634 + 6166.94845288619 * self.t)
X0 += 0.00000007398 * math.cos(0.58333334375 + 709.721016842 * self.t)
X0 += 0.00000005679 * math.cos(5.91776083103 + 17.22740858061 * self.t)
X0 += 0.00000005205 * math.cos(2.61017638124 + 426.3543733925 * self.t)
X0 += 0.00000005146 * math.cos(0.81172664742 + 46.7624245093 * self.t)
X0 += 0.00000005694 * math.cos(2.94913098744 + 168.98435148349 * self.t)
X0 += 0.00000006627 * math.cos(6.07668723879 + 221.13203280179 * self.t)
X0 += 0.00000005443 * math.cos(4.34867602386 + 525.7419968841 * self.t)
X0 += 0.00000006475 * math.cos(2.52364293984 + 591.07424248041 * self.t)
X0 += 0.00000004984 * math.cos(4.89088409053 + 10097.15814910579 * self.t)
X0 += 0.00000005318 * math.cos(5.22697316848 + 44.52719227561 * self.t)
X0 += 0.00000006699 * math.cos(2.95047965393 + 2157.1407134997 * self.t)
X0 += 0.00000006443 * math.cos(5.65068156930 + 675.0445615878 * self.t)
X0 += 0.00000005078 * math.cos(0.96513123174 + 101.62511645769 * self.t)
X0 += 0.00000005394 * math.cos(0.88948762211 + 368.21391948681 * self.t)
X0 += 0.00000005072 * math.cos(2.52597530610 + 272.33775813299 * self.t)
X0 += 0.00000005208 * math.cos(4.53150187093 + 277.2788112249 * self.t)
X0 += 0.00000005332 * math.cos(1.28621962216 + 280.9357778421 * self.t)
X0 += 0.00000005989 * math.cos(5.89271411050 + 93.0270967486 * self.t)
X0 += 0.00000006329 * math.cos(0.49570607842 + 18.87863762769 * self.t)
X0 += 0.00000005551 * math.cos(2.57045763275 + 57.3874336479 * self.t)
X0 += 0.00000006471 * math.cos(0.04463535540 + 68.1243173711 * self.t)
X0 += 0.00000004708 * math.cos(2.23921095477 + 95.68722562449 * self.t)
X0 += 0.00000005891 * math.cos(5.96441381591 + 381.5954257209 * self.t)
X0 += 0.00000004717 * math.cos(4.31682479516 + 104.2852453336 * self.t)
X0 += 0.00000005675 * math.cos(1.71229301179 + 1165.6392831981 * self.t)
X0 += 0.00000005888 * math.cos(0.43219504278 + 42.34263627919 * self.t)
X0 += 0.00000005587 * math.cos(4.09170092519 + 459.6066021357 * self.t)
X0 += 0.00000005456 * math.cos(1.50864831442 + 75.50098893029 * self.t)
X0 += 0.00000005940 * math.cos(6.28075673596 + 6318.4837576961 * self.t)
X0 += 0.00000005207 * math.cos(4.55134069280 + 436.5699922539 * self.t)
X0 += 0.00000006160 * math.cos(4.76046448210 + 749.82616015511 * self.t)
X0 += 0.00000006137 * math.cos(4.59348226478 + 713.17759722561 * self.t)
X0 += 0.00000004547 * math.cos(2.39218547281 + 32.47259218289 * self.t)
X0 += 0.00000005246 * math.cos(4.97888240032 + 109.9625037359 * self.t)
X0 += 0.00000005244 * math.cos(2.33674770879 + 73.5891274523 * self.t)
X0 += 0.00000005572 * math.cos(6.12038028190 + 102.11275142471 * self.t)
X0 += 0.00000005638 * math.cos(1.42053892188 + 10248.6934539157 * self.t)
X0 += 0.00000004513 * math.cos(1.62848698862 + 1272.9248431107 * self.t)
X0 += 0.00000004340 * math.cos(2.36449866810 + 384.02855206069 * self.t)
X0 += 0.00000004263 * math.cos(4.24631269159 + 1577.52274510549 * self.t)
X0 += 0.00000005964 * math.cos(4.92643136579 + 786.47472308461 * self.t)
X0 += 0.00000004962 * math.cos(6.09839378254 + 257.78059573129 * self.t)
X0 += 0.00000005327 * math.cos(5.70215230442 + 107.74182571721 * self.t)
X0 += 0.00000005572 * math.cos(0.87438107795 + 291.2934569054 * self.t)
X0 += 0.00000004336 * math.cos(5.80113193852 + 53.40958840249 * self.t)
X0 += 0.00000004427 * math.cos(3.00157250839 + 189.42452296421 * self.t)
X0 += 0.00000004157 * math.cos(3.46647899628 + 29.5036467663 * self.t)
X0 += 0.00000004646 * math.cos(2.87774169214 + 13285.93981804009 * self.t)
X0 += 0.00000005507 * math.cos(4.27464738844 + 178.11819026941 * self.t)
X0 += 0.00000005348 * math.cos(1.42468292991 + 24.88347230261 * self.t)
X0 += 0.00000005339 * math.cos(3.91840662285 + 314.6635794648 * self.t)
X0 += 0.00000004678 * math.cos(4.43608792406 + 1474.4299708869 * self.t)
X0 += 0.00000004090 * math.cos(3.35633664186 + 765.3801602981 * self.t)
X0 += 0.00000005008 * math.cos(5.85701520659 + 352.06040979221 * self.t)
X0 += 0.00000005562 * math.cos(0.40887335705 + 6248.1555772537 * self.t)
X0 += 0.00000004983 * math.cos(3.16236150253 + 1055.43296197871 * self.t)
X0 += 0.00000004566 * math.cos(5.25700629292 + 325.1398307571 * self.t)
X0 += 0.00000005327 * math.cos(5.25347269162 + 439.53893767049 * self.t)
X0 += 0.00000005121 * math.cos(5.84825704577 + 711.6931245173 * self.t)
X0 += 0.00000004181 * math.cos(1.11749590962 + 6606.1994373488 * self.t)
X0 += 0.00000004293 * math.cos(4.65873798886 + 46.71424039951 * self.t)
X0 += 0.00000005532 * math.cos(0.53479774781 + 320.03202132639 * self.t)
X0 += 0.00000004492 * math.cos(0.09912827297 + 52177.53457334019 * self.t)
X0 += 0.00000004312 * math.cos(1.38883413817 + 22.8777347325 * self.t)
X0 += 0.00000005332 * math.cos(1.83070192574 + 10178.3652734733 * self.t)
X0 += 0.00000004593 * math.cos(0.14820750962 + 1025.6854977289 * self.t)
X0 += 0.00000005439 * math.cos(5.09447580219 + 823.12328601411 * self.t)
X0 += 0.00000003870 * math.cos(4.27995377915 + 1596.43025976811 * self.t)
X0 += 0.00000003892 * math.cos(2.11564791977 + 226.07308589371 * self.t)
X0 += 0.00000004891 * math.cos(2.80814026706 + 8.1417539045 * self.t)
X0 += 0.00000004689 * math.cos(3.52062924653 + 276.79117625789 * self.t)
X0 += 0.00000004268 * math.cos(2.59269427473 + 374.15181032 * self.t)
X0 += 0.00000003828 * math.cos(2.28076604659 + 2138.2331988371 * self.t)
X0 += 0.00000004592 * math.cos(3.87527577295 + 1376.0176173293 * self.t)
X0 += 0.00000004629 * math.cos(0.97709160917 + 122.71967924421 * self.t)
X0 += 0.00000003871 * math.cos(3.17548325596 + 531.4192552864 * self.t)
X0 += 0.00000004995 * math.cos(0.32063762943 + 32.69959471901 * self.t)
X0 += 0.00000004711 * math.cos(0.43748317622 + 52252.31617190749 * self.t)
X0 += 0.00000003893 * math.cos(0.12475334110 + 116.294153444 * self.t)
X0 += 0.00000004481 * math.cos(4.66479841820 + 53.0458901076 * self.t)
X0 += 0.00000004136 * math.cos(2.59386926777 + 503.1080796351 * self.t)
X0 += 0.00000004508 * math.cos(4.38574998818 + 562.12992738271 * self.t)
X0 += 0.00000005025 * math.cos(0.39865233659 + 283.38345839689 * self.t)
X0 += 0.00000004789 * math.cos(2.68692249791 + 627.7228054099 * self.t)
X0 += 0.00000004021 * math.cos(0.14454426922 + 6603.23049193219 * self.t)
X0 += 0.00000005163 * math.cos(4.77460676620 + 25519.83532335829 * self.t)
X0 += 0.00000004150 * math.cos(3.86319541901 + 27.443027442 * self.t)
X0 += 0.00000003623 * math.cos(2.29457319711 + 1665.5827840429 * self.t)
X0 += 0.00000004634 * math.cos(1.79141170909 + 3227.45397501119 * self.t)
X0 += 0.00000004060 * math.cos(6.21658618282 + 304.4780211834 * self.t)
X0 += 0.00000003862 * math.cos(0.50812728673 + 74.504151189 * self.t)
X0 += 0.00000003561 * math.cos(4.92971224760 + 358.6526919312 * self.t)
X0 += 0.00000004557 * math.cos(6.27521064672 + 25974.74468988559 * self.t)
X0 += 0.00000004264 * math.cos(1.56884112199 + 634.93941827469 * self.t)
X0 += 0.00000004482 * math.cos(1.70550805319 + 342.61105682121 * self.t)
X0 += 0.00000003539 * math.cos(0.56907944763 + 119.7507338276 * self.t)
X0 += 0.00000004304 * math.cos(0.63784646457 + 12567.8799901746 * self.t)
X0 += 0.00000004138 * math.cos(4.03567139847 + 107.2541907502 * self.t)
X0 += 0.00000004284 * math.cos(0.05420881503 + 294.42915866079 * self.t)
X0 += 0.00000003723 * math.cos(5.58644401851 + 987.325459555 * self.t)
X0 += 0.00000003723 * math.cos(5.58644401851 + 987.813094522 * self.t)
X0 += 0.00000004606 * math.cos(5.49553530451 + 14.42521950279 * self.t)
X0 += 0.00000004236 * math.cos(6.22240593144 + 155.9116617901 * self.t)
X0 += 0.00000004458 * math.cos(2.64590572483 + 395.8225197225 * self.t)
X0 += 0.00000004798 * math.cos(5.23929868658 + 530.195415009 * self.t)
X0 += 0.00000003640 * math.cos(2.22734915897 + 2564.8313897131 * self.t)
X0 += 0.00000003563 * math.cos(5.37459598926 + 12451.50877558589 * self.t)
X0 += 0.00000003443 * math.cos(2.13809774331 + 245.2504227591 * self.t)
X0 += 0.00000003429 * math.cos(4.73423412994 + 530.0466571627 * self.t)
X0 += 0.00000003872 * math.cos(4.09217464449 + 308.98632106249 * self.t)
X0 += 0.00000003406 * math.cos(5.88979864779 + 529.82290799351 * self.t)
X0 += 0.00000004348 * math.cos(1.52419659995 + 20311.92816802509 * self.t)
X0 += 0.00000004589 * math.cos(5.24153025487 + 181.08713568601 * self.t)
X0 += 0.00000003854 * math.cos(5.92510183178 + 12564.91104475801 * self.t)
X0 += 0.00000003789 * math.cos(4.29351893525 + 3101.6359018085 * self.t)
X0 += 0.00000003783 * math.cos(0.26936683978 + 1614.17130803499 * self.t)
X0 += 0.00000003904 * math.cos(0.00421090422 + 369.8014580591 * self.t)
X0 += 0.00000003765 * math.cos(4.70889835066 + 1025.94613015981 * self.t)
X0 += 0.00000004231 * math.cos(5.35914297519 + 31.52393855141 * self.t)
X0 += 0.00000004303 * math.cos(4.97345150272 + 396.785727569 * self.t)
X0 += 0.00000004085 * math.cos(1.80921070558 + 14.47091148511 * self.t)
X0 += 0.00000004085 * math.cos(1.80921070558 + 13.9832765181 * self.t)
X0 += 0.00000003346 * math.cos(4.91522066963 + 20351.54567637119 * self.t)
X0 += 0.00000004021 * math.cos(6.08537487228 + 748.3416874468 * self.t)
X0 += 0.00000003753 * math.cos(1.17204243376 + 524.99372948619 * self.t)
X0 += 0.00000003935 * math.cos(1.24122122244 + 1617.14025345159 * self.t)
X0 += 0.00000004432 * math.cos(3.45778366813 + 511.3515908212 * self.t)
X0 += 0.00000004170 * math.cos(4.42864444413 + 274.87931477991 * self.t)
X0 += 0.00000003317 * math.cos(1.79347554880 + 266.70868384049 * self.t)
X0 += 0.00000004545 * math.cos(4.56531161641 + 244.5624015585 * self.t)
X0 += 0.00000003589 * math.cos(1.55384880430 + 59.526297662 * self.t)
X0 += 0.00000003464 * math.cos(0.37736158688 + 102.27950776349 * self.t)
X0 += 0.00000004526 * math.cos(4.55402483522 + 525.7901809939 * self.t)
X0 += 0.00000004603 * math.cos(4.40260765490 + 26088.1469590577 * self.t)
X0 += 0.00000004021 * math.cos(5.38581853850 + 52174.56562792359 * self.t)
X0 += 0.00000003276 * math.cos(1.95663025139 + 1306.3774580875 * self.t)
X0 += 0.00000003214 * math.cos(3.94235488355 + 20348.57673095459 * self.t)
X0 += 0.00000003706 * math.cos(5.25360971143 + 27.07052042651 * self.t)
X0 += 0.00000003759 * math.cos(4.32245166720 + 164.83974989929 * self.t)
X0 += 0.00000003184 * math.cos(2.01654309849 + 538.0115374254 * self.t)
X0 += 0.00000004430 * math.cos(5.37917502758 + 529.6741501472 * self.t)
X0 += 0.00000004064 * math.cos(1.03322736236 + 6130.2998899567 * self.t)
X0 += 0.00000003918 * math.cos(4.20575585414 + 375.43053235159 * self.t)
X0 += 0.00000004058 * math.cos(5.13313296042 + 433.4342904985 * self.t)
X0 += 0.00000003919 * math.cos(0.36694469487 + 1092.8177302186 * self.t)
X0 += 0.00000003919 * math.cos(0.36694469487 + 1093.3053651856 * self.t)
X0 += 0.00000003175 * math.cos(1.14568678321 + 241.3664536058 * self.t)
X0 += 0.00000003135 * math.cos(5.81037649777 + 127.22797912329 * self.t)
X0 += 0.00000003834 * math.cos(1.84941829775 + 14.3133449182 * self.t)
X0 += 0.00000004022 * math.cos(1.72079825603 + 1477.8383671607 * self.t)
X0 += 0.00000003221 * math.cos(1.09261076661 + 78.1611178062 * self.t)
X0 += 0.00000003426 * math.cos(0.06166201047 + 519.8522901607 * self.t)
X0 += 0.00000004369 * math.cos(0.74973637733 + 746.3695797715 * self.t)
X0 += 0.00000003160 * math.cos(2.01821245093 + 664.99569906519 * self.t)
X0 += 0.00000004060 * math.cos(6.06087716530 + 51.87023394 * self.t)
X0 += 0.00000003107 * math.cos(5.38240469077 + 28.9275001503 * self.t)
X0 += 0.00000003259 * math.cos(5.62260974194 + 657.8821520644 * self.t)
X0 += 0.00000003428 * math.cos(1.24133782529 + 2351.5322942751 * self.t)
X0 += 0.00000003235 * math.cos(1.64692472660 + 406.3469551246 * self.t)
X0 += 0.00000003161 * math.cos(5.69758725685 + 982.8720414301 * self.t)
X0 += 0.00000004351 * math.cos(1.04662835997 + 20388.19423930069 * self.t)
X0 += 0.00000003384 * math.cos(0.30649784029 + 660.851097481 * self.t)
X0 += 0.00000003452 * math.cos(4.39659352485 + 326.1823604807 * self.t)
X0 += 0.00000003298 * math.cos(0.15489069807 + 1403.84115801359 * self.t)
X0 += 0.00000003278 * math.cos(3.68945780931 + 941.7700603757 * self.t)
X0 += 0.00000003723 * math.cos(5.00962048402 + 451.9572360581 * self.t)
X0 += 0.00000003173 * math.cos(5.46640783518 + 1400.87221259699 * self.t)
X0 += 0.00000004113 * math.cos(1.87439213951 + 1049.31625271919 * self.t)
X0 += 0.00000004012 * math.cos(2.15082049909 + 52.6039471229 * self.t)
X0 += 0.00000004142 * math.cos(4.89782789900 + 978.6792557361 * self.t)
X0 += 0.00000004295 * math.cos(1.37302733197 + 875.58648151749 * self.t)
X0 += 0.00000003224 * math.cos(3.81995287471 + 459.1189671687 * self.t)
X0 += 0.00000003151 * math.cos(3.69005421605 + 381.8560581518 * self.t)
X0 += 0.00000003633 * math.cos(1.38559724652 + 256.78375799 * self.t)
X0 += 0.00000004250 * math.cos(0.10595516218 + 528.71094230071 * self.t)
X0 += 0.00000004186 * math.cos(2.09187651842 + 943.25453308399 * self.t)
X0 += 0.00000003406 * math.cos(0.25126866750 + 170.46882419179 * self.t)
X0 += 0.00000003231 * math.cos(4.61367643853 + 400.8209466961 * self.t)
X0 += 0.00000003726 * math.cos(0.55318715397 + 1096.48675892331 * self.t)
X0 += 0.00000003792 * math.cos(0.75464081409 + 111.9346114112 * self.t)
X0 += 0.00000003651 * math.cos(4.56933341620 + 154.42718908179 * self.t)
X0 += 0.00000003839 * math.cos(2.45649426115 + 10060.50958617629 * self.t)
X0 += 0.00000003356 * math.cos(0.62546125542 + 1586.34776735071 * self.t)
X0 += 0.00000003219 * math.cos(5.97786590701 + 213.7096692603 * self.t)
X0 += 0.00000003671 * math.cos(1.51743688101 + 57.6023740965 * self.t)
X0 += 0.00000004187 * math.cos(0.29242250575 + 2772.54460848389 * self.t)
X0 += 0.00000002960 * math.cos(2.20142019667 + 2461.7386154945 * self.t)
X0 += 0.00000003331 * math.cos(0.81281655951 + 10133.80671203529 * self.t)
X0 += 0.00000003341 * math.cos(1.17831577639 + 243.7659500508 * self.t)
X0 += 0.00000003466 * math.cos(4.73891819304 + 1150.92455422949 * self.t)
X0 += 0.00000003296 * math.cos(3.49817757911 + 1653.78881638109 * self.t)
X0 += 0.00000003014 * math.cos(1.90092216670 + 1477.3989163035 * self.t)
X0 += 0.00000004118 * math.cos(2.83150543771 + 25596.5890296009 * self.t)
X0 += 0.00000002951 * math.cos(5.04298380276 + 42.78208713641 * self.t)
X0 += 0.00000002951 * math.cos(5.58078877076 + 33.9716191062 * self.t)
X0 += 0.00000003830 * math.cos(4.59720174528 + 323.48860171 * self.t)
X0 += 0.00000003313 * math.cos(1.64840054600 + 939.1099314998 * self.t)
X0 += 0.00000003031 * math.cos(2.75126158832 + 156450.90896068608 * self.t)
X0 += 0.00000003606 * math.cos(3.92819651217 + 1082.2596649217 * self.t)
X0 += 0.00000002967 * math.cos(0.01380556143 + 6.3941566378 * self.t)
X0 += 0.00000002995 * math.cos(3.55729257964 + 139.7099679857 * self.t)
X0 += 0.00000003251 * math.cos(3.50186784018 + 709.29362807231 * self.t)
X0 += 0.00000003480 * math.cos(0.61716473120 + 518.1408149163 * self.t)
X0 += 0.00000003906 * math.cos(2.84871380483 + 1119.90506559249 * self.t)
X0 += 0.00000003406 * math.cos(1.85522558472 + 148.79811478929 * self.t)
X0 += 0.00000003359 * math.cos(1.74239209634 + 642.8494167832 * self.t)
X0 += 0.00000003027 * math.cos(0.29741383095 + 184.0078969928 * self.t)
X0 += 0.00000002918 * math.cos(2.25866029656 + 83.6234357599 * self.t)
X0 += 0.00000003347 * math.cos(6.10666820526 + 217.68751450571 * self.t)
X0 += 0.00000003277 * math.cos(0.27333269638 + 912.5438609877 * self.t)
X0 += 0.00000003277 * math.cos(0.27333269638 + 913.03149595471 * self.t)
X0 += 0.00000003196 * math.cos(5.84286985933 + 363.1061100561 * self.t)
X0 += 0.00000002869 * math.cos(4.50334436600 + 285.35556607221 * self.t)
X0 += 0.00000003158 * math.cos(1.18152957041 + 540.01727499551 * self.t)
X0 += 0.00000002810 * math.cos(5.14802919795 + 1592.2856581839 * self.t)
X0 += 0.00000003471 * math.cos(6.13160952457 + 144.39038864671 * self.t)
X0 += 0.00000003159 * math.cos(4.14451339136 + 197.5561595657 * self.t)
X0 += 0.00000003227 * math.cos(5.73841253304 + 6203.5970158157 * self.t)
X0 += 0.00000003750 * math.cos(5.81139240481 + 303.35724676999 * self.t)
X0 += 0.00000003848 * math.cos(3.38110828764 + 26048.04181574459 * self.t)
X0 += 0.00000002741 * math.cos(1.70084306406 + 70.8326303568 * self.t)
X0 += 0.00000002826 * math.cos(2.07742210458 + 460.2946233363 * self.t)
X0 += 0.00000002748 * math.cos(0.98378370701 + 600.52359545141 * self.t)
X0 += 0.00000003057 * math.cos(6.13629771077 + 23.81969071961 * self.t)
X0 += 0.00000003057 * math.cos(1.34588220916 + 52.934015523 * self.t)
X0 += 0.00000003446 * math.cos(3.54046646150 + 500.1391342185 * self.t)
X0 += 0.00000002703 * math.cos(4.69192633180 + 908.0904428628 * self.t)
X0 += 0.00000002817 * math.cos(3.26718539283 + 210.6221516147 * self.t)
X0 += 0.00000002848 * math.cos(5.88127781412 + 450.4727633498 * self.t)
X0 += 0.00000002724 * math.cos(0.93671586048 + 23.18655127321 * self.t)
X0 += 0.00000002905 * math.cos(5.85039527890 + 149.3193796511 * self.t)
X0 += 0.00000002848 * math.cos(6.20081143930 + 622.66987773339 * self.t)
X0 += 0.00000002733 * math.cos(3.50715759295 + 262.72164882321 * self.t)
X0 += 0.00000002863 * math.cos(0.69834580836 + 175.57663362249 * self.t)
X0 += 0.00000002681 * math.cos(1.11809511751 + 25.1922888433 * self.t)
X0 += 0.00000002822 * math.cos(1.57963221264 + 259.7527034066 * self.t)
X0 += 0.00000003174 * math.cos(6.18541771069 + 347.1193567003 * self.t)
X0 += 0.00000003271 * math.cos(1.40248413653 + 458.5977023069 * self.t)
X0 += 0.00000002894 * math.cos(4.18128306427 + 71.82946809809 * self.t)
X0 += 0.00000003490 * math.cos(2.85083291634 + 664.3713683394 * self.t)
X0 += 0.00000003506 * math.cos(5.48691285949 + 771.3481117113 * self.t)
X0 += 0.00000003326 * math.cos(2.12303698267 + 45.2297676912 * self.t)
X0 += 0.00000002988 * math.cos(0.23324807191 + 299.37021175271 * self.t)
X0 += 0.00000002916 * math.cos(3.60780287924 + 6642.8480002783 * self.t)
X0 += 0.00000002916 * math.cos(0.46621022565 + 6643.3356352453 * self.t)
X0 += 0.00000002630 * math.cos(1.12694509764 + 2751.79141717511 * self.t)
X0 += 0.00000002903 * math.cos(4.31055308658 + 477.08701797169 * self.t)
X0 += 0.00000002804 * math.cos(0.26456593020 + 6681.46867088311 * self.t)
X0 += 0.00000002622 * math.cos(2.30179163581 + 521.8580277308 * self.t)
X0 += 0.00000002606 * math.cos(6.15707729666 + 410.8552550037 * self.t)
X0 += 0.00000003046 * math.cos(2.36386768037 + 959.45373476091 * self.t)
X0 += 0.00000003127 * math.cos(3.04512463308 + 225.5518210319 * self.t)
X0 += 0.00000002700 * math.cos(4.45467896965 + 963.6465204549 * self.t)
X0 += 0.00000002778 * math.cos(1.65860124839 + 238.39750818919 * self.t)
X0 += 0.00000003029 * math.cos(4.72630934575 + 473.2185551834 * self.t)
X0 += 0.00000002671 * math.cos(4.60029996028 + 531.9405201482 * self.t)
X0 += 0.00000002914 * math.cos(3.86169076602 + 554.31380496631 * self.t)
X0 += 0.00000003087 * math.cos(6.08851917121 + 340.2664421304 * self.t)
X0 += 0.00000003438 * math.cos(2.32466413132 + 6171.40187101109 * self.t)
X0 += 0.00000002879 * math.cos(5.61809470376 + 218.6507223522 * self.t)
X0 += 0.00000003140 * math.cos(5.02001385281 + 609.1216151605 * self.t)
X0 += 0.00000003003 * math.cos(0.53592571188 + 464.97504399731 * self.t)
X0 += 0.00000003257 * math.cos(1.52476284257 + 305.96249389171 * self.t)
X0 += 0.00000003211 * math.cos(5.64833047248 + 416.532513406 * self.t)
X0 += 0.00000003265 * math.cos(1.54950325507 + 24.7347144563 * self.t)
X0 += 0.00000002644 * math.cos(1.01963899758 + 508.5941415757 * self.t)
X0 += 0.00000002764 * math.cos(4.98225869197 + 410.59462257279 * self.t)
X0 += 0.00000003428 * math.cos(5.71088563789 + 1012.6195056799 * self.t)
X0 += 0.00000002614 * math.cos(4.07639961382 + 213.5910970313 * self.t)
X0 += 0.00000003469 * math.cos(5.28643352424 + 24.14975911971 * self.t)
X0 += 0.00000002606 * math.cos(0.81160096517 + 213.4947288117 * self.t)
X0 += 0.00000003444 * math.cos(2.56432157215 + 891.57323487331 * self.t)
X0 += 0.00000002540 * math.cos(4.32167771768 + 564.8718702632 * self.t)
X0 += 0.00000002540 * math.cos(4.32167771768 + 565.35950523021 * self.t)
X0 += 0.00000002754 * math.cos(2.69535555411 + 57.5541899867 * self.t)
X0 += 0.00000002531 * math.cos(0.59020723407 + 800.5924346291 * self.t)
X0 += 0.00000002557 * math.cos(0.66999256840 + 341.49028240779 * self.t)
X0 += 0.00000002601 * math.cos(4.54885591305 + 261.2371761149 * self.t)
X0 += 0.00000003027 * math.cos(0.20183300410 + 331.07772159029 * self.t)
X0 += 0.00000002494 * math.cos(0.58142193078 + 203.9816853659 * self.t)
X0 += 0.00000002590 * math.cos(1.76325981719 + 1190.5420625756 * self.t)
X0 += 0.00000003494 * math.cos(2.90876238684 + 534.0793841623 * self.t)
X0 += 0.00000003144 * math.cos(0.01981710217 + 1503.9649868156 * self.t)
X0 += 0.00000002818 * math.cos(3.61898449244 + 49.31067880061 * self.t)
X0 += 0.00000002791 * math.cos(4.48606671949 + 288.32451148881 * self.t)
X0 += 0.00000002471 * math.cos(1.23009614301 + 411.11588743459 * self.t)
X0 += 0.00000003059 * math.cos(3.30977686438 + 172.48911597691 * self.t)
X0 += 0.00000002972 * math.cos(0.30229231666 + 569.29165849331 * self.t)
X0 += 0.00000003418 * math.cos(5.40293550246 + 638.3959986583 * self.t)
X0 += 0.00000002541 * math.cos(4.99016167757 + 1448.09090291091 * self.t)
X0 += 0.00000002663 * math.cos(0.43151826022 + 573.6968925084 * self.t)
X0 += 0.00000002439 * math.cos(4.39632185677 + 1625.9652756968 * self.t)
X0 += 0.00000002739 * math.cos(5.72535305895 + 112.8832650427 * self.t)
X0 += 0.00000002821 * math.cos(5.66863744979 + 402.93606672331 * self.t)
X0 += 0.00000003412 * math.cos(1.27007980380 + 772.8325844196 * self.t)
X0 += 0.00000002624 * math.cos(5.85528852490 + 1624.4808029885 * self.t)
X0 += 0.00000003170 * math.cos(0.53682796950 + 1011.13503297159 * self.t)
X0 += 0.00000002908 * math.cos(4.60949958082 + 635.94831810351 * self.t)
X0 += 0.00000002664 * math.cos(2.68003479349 + 409.41896640519 * self.t)
X0 += 0.00000003091 * math.cos(1.88245278611 + 379.25961975071 * self.t)
X0 += 0.00000003301 * math.cos(1.91350932819 + 19.7936613644 * self.t)
X0 += 0.00000003176 * math.cos(3.29730129609 + 300.9095662152 * self.t)
X0 += 0.00000003022 * math.cos(5.94822554077 + 52.0189917863 * self.t)
X0 += 0.00000002890 * math.cos(1.53549747897 + 293.4323209195 * self.t)
X0 += 0.00000002698 * math.cos(1.69370735844 + 78149.06650032569 * self.t)
X0 += 0.00000002558 * math.cos(0.74578099458 + 1371.3371966683 * self.t)
X0 += 0.00000002619 * math.cos(3.80578981072 + 202.0095776906 * self.t)
X0 += 0.00000003176 * math.cos(3.75055063339 + 10101.61156723069 * self.t)
X0 += 0.00000003341 * math.cos(2.34080319182 + 345.8955164229 * self.t)
X0 += 0.00000002373 * math.cos(4.96475711609 + 130.8513158457 * self.t)
X0 += 0.00000002644 * math.cos(2.68099240015 + 305.10235190919 * self.t)
X0 += 0.00000003339 * math.cos(4.63303989765 + 2849.2983147265 * self.t)
X0 += 0.00000002410 * math.cos(1.58163612779 + 951.8525527931 * self.t)
X0 += 0.00000003303 * math.cos(2.25771292490 + 769.5729459921 * self.t)
X0 += 0.00000003302 * math.cos(4.85894681967 + 90.1520274241 * self.t)
X0 += 0.00000002416 * math.cos(6.00635580174 + 527.929045008 * self.t)
X0 += 0.00000002361 * math.cos(5.34789183737 + 905.1214974462 * self.t)
X0 += 0.00000002737 * math.cos(4.77190944455 + 1206.2199993907 * self.t)
X0 += 0.00000002441 * math.cos(3.82975575752 + 246.73489546739 * self.t)
X0 += 0.00000002441 * math.cos(0.68816310393 + 247.2225304344 * self.t)
X0 += 0.00000002957 * math.cos(4.25832811500 + 238.23075185041 * self.t)
X0 += 0.00000003263 * math.cos(0.98630889937 + 1506.93393223219 * self.t)
X0 += 0.00000003293 * math.cos(5.93270574395 + 66.1522096958 * self.t)
X0 += 0.00000003241 * math.cos(3.43806050184 + 978.4186233052 * self.t)
X0 += 0.00000003149 * math.cos(3.64971867049 + 271.9103693633 * self.t)
X0 += 0.00000003149 * math.cos(3.64971867050 + 271.4227343963 * self.t)
X0 += 0.00000002328 * math.cos(5.07609916236 + 31.73887900 * self.t)
X0 += 0.00000002372 * math.cos(0.68652074740 + 309.0345051723 * self.t)
X0 += 0.00000002372 * math.cos(3.82811340099 + 309.5221401393 * self.t)
X0 += 0.00000002369 * math.cos(4.33012817739 + 418.9801939608 * self.t)
X0 += 0.00000003007 * math.cos(4.64009260533 + 1437.7814079574 * self.t)
X0 += 0.00000003034 * math.cos(5.98346126252 + 330.8627811417 * self.t)
X0 += 0.00000002345 * math.cos(2.80677153952 + 453.9318358609 * self.t)
X0 += 0.00000003118 * math.cos(3.73398781358 + 1434.81246254079 * self.t)
X0 += 0.00000002324 * math.cos(3.85931736808 + 495.2462652364 * self.t)
X0 += 0.00000002340 * math.cos(5.41992470939 + 452.43031681009 * self.t)
X0 += 0.00000002336 * math.cos(0.04655833240 + 189.591279303 * self.t)
X0 += 0.00000002920 * math.cos(3.78758562864 + 1549.69920442121 * self.t)
X0 += 0.00000002494 * math.cos(0.79353025531 + 1187.57311715899 * self.t)
X0 += 0.00000002692 * math.cos(4.17807622816 + 425.13053311509 * self.t)
X0 += 0.00000002874 * math.cos(4.63267401857 + 1654.2764513481 * self.t)
X0 += 0.00000002809 * math.cos(5.67077170621 + 317.5843407716 * self.t)
X0 += 0.00000002735 * math.cos(3.93990204220 + 1513.05064149171 * self.t)
X0 += 0.00000002949 * math.cos(6.26993364897 + 186.71620997851 * self.t)
X0 += 0.00000002320 * math.cos(0.74326897219 + 487.38195871019 * self.t)
X0 += 0.00000003113 * math.cos(6.20902109610 + 353.28425006961 * self.t)
X0 += 0.00000003086 * math.cos(4.87476303199 + 1230.5990217789 * self.t)
X0 += 0.00000002722 * math.cos(2.16494792915 + 49.6831858161 * self.t)
X0 += 0.00000003064 * math.cos(3.68765217385 + 133.13224006171 * self.t)
X0 += 0.00000003064 * math.cos(3.68765217385 + 132.64460509469 * self.t)
X0 += 0.00000002470 * math.cos(2.78243316001 + 532.3824631329 * self.t)
X0 += 0.00000002640 * math.cos(0.51790972890 + 394.33804701421 * self.t)
X0 += 0.00000002252 * math.cos(1.84613004390 + 22.6507321964 * self.t)
X0 += 0.00000003151 * math.cos(5.26039361613 + 859.77184894361 * self.t)
X0 += 0.00000002671 * math.cos(0.92145640556 + 37.3679532925 * self.t)
X0 += 0.00000002380 * math.cos(0.86687455354 + 429.2751346993 * self.t)
X0 += 0.00000002655 * math.cos(2.72088152594 + 484.1523808627 * self.t)
X0 += 0.00000003005 * math.cos(3.02367934874 + 1929.33933741419 * self.t)
X0 += 0.00000002550 * math.cos(5.60497907633 + 496.9431862658 * self.t)
X0 += 0.00000002290 * math.cos(3.41120190653 + 455.18681390559 * self.t)
X0 += 0.00000002608 * math.cos(3.85525903926 + 422.9580392062 * self.t)
X0 += 0.00000002226 * math.cos(2.09977531258 + 47.82620609231 * self.t)
X0 += 0.00000002233 * math.cos(4.94028872789 + 877.3461408717 * self.t)
X0 += 0.00000002764 * math.cos(0.83501700112 + 356.68058425589 * self.t)
X0 += 0.00000002719 * math.cos(1.98953734068 + 177.5823711926 * self.t)
X0 += 0.00000002999 * math.cos(2.06885612973 + 1926.37039199759 * self.t)
X0 += 0.00000002693 * math.cos(3.57972778548 + 6284.8041401832 * self.t)
X0 += 0.00000002369 * math.cos(1.19578023344 + 70.88081446661 * self.t)
X0 += 0.00000002498 * math.cos(3.71851216671 + 315.1512144318 * self.t)
X0 += 0.00000002204 * math.cos(3.20466206592 + 442.886135597 * self.t)
X0 += 0.00000002261 * math.cos(3.32534753019 + 621.2335891349 * self.t)
X0 += 0.00000002213 * math.cos(6.16263836668 + 1189.0575898673 * self.t)
X0 += 0.00000002492 * math.cos(2.67366070604 + 406.9712858504 * self.t)
X0 += 0.00000002976 * math.cos(1.45402284302 + 1014.1039783882 * self.t)
X0 += 0.00000002840 * math.cos(5.35710509350 + 522.3336006103 * self.t)
X0 += 0.00000002340 * math.cos(1.72448626630 + 440.43845504219 * self.t)
X0 += 0.00000003012 * math.cos(1.13512104183 + 15.9096922111 * self.t)
X0 += 0.00000003012 * math.cos(4.27671369542 + 16.3973271781 * self.t)
X0 += 0.00000002372 * math.cos(0.24227395275 + 132.5964209849 * self.t)
X0 += 0.00000002232 * math.cos(2.42168492591 + 158.12984768129 * self.t)
X0 += 0.00000002961 * math.cos(4.37134416172 + 286.3524038135 * self.t)
X0 += 0.00000002961 * math.cos(4.37134416172 + 286.8400387805 * self.t)
# Neptune_X1 (t) // 342 terms of order 1
X1 = 0
X1 += 0.00357822049 * math.cos(4.60537437341 + 0.2438174835 * self.t)
X1 += 0.00256200629 * math.cos(2.01693264233 + 36.892380413 * self.t)
X1 += 0.00242677799 * math.cos(5.46293481092 + 39.86132582961 * self.t)
X1 += 0.00106073143 * math.cos(3.07856435709 + 37.88921815429 * self.t)
X1 += 0.00103735195 * math.cos(6.08270773807 + 38.3768531213 * self.t)
X1 += 0.00118508231 * math.cos(2.88623136735 + 76.50988875911 * self.t)
X1 += 0.00021930692 * math.cos(3.20019569049 + 35.40790770471 * self.t)
X1 += 0.00017445772 * math.cos(4.26396070854 + 41.3457985379 * self.t)
X1 += 0.00013038843 * math.cos(5.36684741537 + 3.21276290011 * self.t)
X1 += 0.00004928885 * math.cos(2.08893204170 + 73.5409433425 * self.t)
X1 += 0.00002742686 * math.cos(4.06389633495 + 77.9943614674 * self.t)
X1 += 0.00002155134 * math.cos(4.11881068429 + 4.6972356084 * self.t)
X1 += 0.00001882800 * math.cos(4.42038284259 + 33.9234349964 * self.t)
X1 += 0.00001572888 * math.cos(1.07810551784 + 114.6429243969 * self.t)
X1 += 0.00001326507 * math.cos(6.02985868883 + 75.0254160508 * self.t)
X1 += 0.00001343094 * math.cos(3.03838214796 + 42.83027124621 * self.t)
X1 += 0.00000897979 * math.cos(4.26993024752 + 426.8420083595 * self.t)
X1 += 0.00000865617 * math.cos(1.66618456177 + 37.8555882595 * self.t)
X1 += 0.00000849963 * math.cos(5.81599535394 + 38.89811798311 * self.t)
X1 += 0.00000922754 * math.cos(3.34516686314 + 72.05647063421 * self.t)
X1 += 0.00000726258 * math.cos(4.24833812431 + 36.404745446 * self.t)
X1 += 0.00000778220 * math.cos(5.84479856092 + 206.42936592071 * self.t)
X1 += 0.00000754025 * math.cos(5.33205816073 + 220.6564599223 * self.t)
X1 += 0.00000607406 * math.cos(0.10576615596 + 1059.6257476727 * self.t)
X1 += 0.00000571831 * math.cos(2.42930874906 + 522.8212355773 * self.t)
X1 += 0.00000560995 * math.cos(1.91555986158 + 537.0483295789 * self.t)
X1 += 0.00000501078 * math.cos(1.71335109406 + 28.81562556571 * self.t)
X1 += 0.00000493238 * math.cos(5.24702261334 + 39.3736908626 * self.t)
X1 += 0.00000474802 * math.cos(4.40715596351 + 98.6561710411 * self.t)
X1 += 0.00000453975 * math.cos(1.71443209341 + 35.9291725665 * self.t)
X1 += 0.00000471731 * math.cos(4.84217171915 + 1.7282901918 * self.t)
X1 += 0.00000410057 * math.cos(5.76579953705 + 40.8245336761 * self.t)
X1 += 0.00000366899 * math.cos(5.76755572930 + 47.9380806769 * self.t)
X1 += 0.00000450109 * math.cos(1.25670451550 + 76.0222537921 * self.t)
X1 += 0.00000354347 * math.cos(6.27109348494 + 1.24065522479 * self.t)
X1 += 0.00000300159 * math.cos(2.88687992256 + 6.1817083167 * self.t)
X1 += 0.00000327501 * math.cos(4.20479564636 + 33.43580002939 * self.t)
X1 += 0.00000174973 * math.cos(5.64027558321 + 32.4389622881 * self.t)
X1 += 0.00000171503 * math.cos(4.43985554308 + 34.1840674273 * self.t)
X1 += 0.00000156749 * math.cos(2.59545084410 + 79.47883417571 * self.t)
X1 += 0.00000152549 * math.cos(0.58219894744 + 30.300098274 * self.t)
X1 += 0.00000150775 * math.cos(3.03954929901 + 42.5696388153 * self.t)
X1 += 0.00000162280 * math.cos(0.79977049351 + 31.2633061205 * self.t)
X1 += 0.00000131609 * math.cos(1.62895622934 + 7.83293736379 * self.t)
X1 += 0.00000136159 * math.cos(4.57878446789 + 70.5719979259 * self.t)
X1 += 0.00000134616 * math.cos(0.39184091634 + 45.49040012211 * self.t)
X1 += 0.00000116304 * math.cos(0.61710594601 + 46.4536079686 * self.t)
X1 += 0.00000115918 * math.cos(1.81843338530 + 44.31474395451 * self.t)
X1 += 0.00000110293 * math.cos(6.26561089969 + 35.4560918145 * self.t)
X1 += 0.00000099282 * math.cos(5.06218386285 + 2.7251279331 * self.t)
X1 += 0.00000099914 * math.cos(1.21626942611 + 41.2976144281 * self.t)
X1 += 0.00000108706 * math.cos(3.09142093314 + 113.15845168861 * self.t)
X1 += 0.00000088965 * math.cos(4.26680850699 + 60.52313540329 * self.t)
X1 += 0.00000086886 * math.cos(5.46872067794 + 31.9513273211 * self.t)
X1 += 0.00000072232 * math.cos(3.50587405737 + 640.1411037975 * self.t)
X1 += 0.00000086985 * math.cos(4.80098575405 + 419.72846135871 * self.t)
X1 += 0.00000073430 * math.cos(4.36511226727 + 70.08436295889 * self.t)
X1 += 0.00000053395 * math.cos(4.46520807878 + 433.9555553603 * self.t)
X1 += 0.00000057451 * math.cos(1.08003733120 + 213.5429129215 * self.t)
X1 += 0.00000051458 * math.cos(4.01726374522 + 69.3963417583 * self.t)
X1 += 0.00000048797 * math.cos(6.01365170443 + 111.67397898031 * self.t)
X1 += 0.00000048557 * math.cos(6.24808481100 + 2.6769438233 * self.t)
X1 += 0.00000042206 * math.cos(3.23823062186 + 74.53778108379 * self.t)
X1 += 0.00000042550 * math.cos(1.67247318349 + 7.66618102501 * self.t)
X1 += 0.00000039462 * math.cos(5.84051041865 + 31.7845709823 * self.t)
X1 += 0.00000039445 * math.cos(0.94630986910 + 12.77399045571 * self.t)
X1 += 0.00000042389 * math.cos(5.59019905902 + 110.189506272 * self.t)
X1 += 0.00000044118 * math.cos(0.44615133445 + 1589.3167127673 * self.t)
X1 += 0.00000037988 * math.cos(2.73850879415 + 6.3484646555 * self.t)
X1 += 0.00000037802 * math.cos(5.98781130211 + 14.258463164 * self.t)
X1 += 0.00000036280 * math.cos(6.27894536142 + 273.8222308413 * self.t)
X1 += 0.00000037247 * math.cos(4.62968774107 + 73.0533083755 * self.t)
X1 += 0.00000036282 * math.cos(2.85336450932 + 84.5866436064 * self.t)
X1 += 0.00000040018 * math.cos(4.27418471085 + 4.4366031775 * self.t)
X1 += 0.00000032400 * math.cos(1.64328879813 + 44.96913526031 * self.t)
X1 += 0.00000031842 * math.cos(5.16652228087 + 34.9202727377 * self.t)
X1 += 0.00000032037 * math.cos(2.94551844856 + 27.3311528574 * self.t)
X1 += 0.00000034456 * math.cos(3.37152599360 + 529.9347825781 * self.t)
X1 += 0.00000031208 * math.cos(1.73420111381 + 1052.51220067191 * self.t)
X1 += 0.00000030002 * math.cos(2.33639558082 + 1066.7392946735 * self.t)
X1 += 0.00000033805 * math.cos(6.04114496470 + 149.8070146181 * self.t)
X1 += 0.00000033096 * math.cos(2.45794089359 + 116.12739710521 * self.t)
X1 += 0.00000030571 * math.cos(4.02151161164 + 22.3900997655 * self.t)
X1 += 0.00000024020 * math.cos(0.23821463973 + 63.9797157869 * self.t)
X1 += 0.00000023780 * math.cos(4.34619784366 + 105.76971804189 * self.t)
X1 += 0.00000023110 * math.cos(2.51348904373 + 23.87457247379 * self.t)
X1 += 0.00000022233 * math.cos(1.21582777350 + 174.9222423167 * self.t)
X1 += 0.00000021377 * math.cos(3.74139728076 + 316.6356871401 * self.t)
X1 += 0.00000025400 * math.cos(4.52702077197 + 106.73292588839 * self.t)
X1 += 0.00000020754 * math.cos(0.94473828111 + 5.6604434549 * self.t)
X1 += 0.00000025572 * math.cos(5.46068636869 + 529.44714761109 * self.t)
X1 += 0.00000019878 * math.cos(1.01805940417 + 32.9602271499 * self.t)
X1 += 0.00000019754 * math.cos(4.49000124955 + 49.42255338521 * self.t)
X1 += 0.00000019241 * math.cos(6.01413524726 + 7.14491616321 * self.t)
X1 += 0.00000017979 * math.cos(1.48478132886 + 62.4952430786 * self.t)
X1 += 0.00000019513 * math.cos(5.64767624982 + 68.5998902506 * self.t)
X1 += 0.00000018273 * math.cos(5.20130356006 + 227.77000692311 * self.t)
X1 += 0.00000017552 * math.cos(5.80350239388 + 69.0875252176 * self.t)
X1 += 0.00000016704 * math.cos(3.94483252805 + 40.8581635709 * self.t)
X1 += 0.00000016996 * math.cos(1.10449263633 + 91.54262404029 * self.t)
X1 += 0.00000016800 * math.cos(0.51632981099 + 30.4668546128 * self.t)
X1 += 0.00000016800 * math.cos(0.51632981099 + 30.95448957981 * self.t)
X1 += 0.00000016400 * math.cos(5.02426208775 + 33.26904369061 * self.t)
X1 += 0.00000017242 * math.cos(0.18352088447 + 11.55015017831 * self.t)
X1 += 0.00000015590 * math.cos(1.99260946960 + 37.1048287341 * self.t)
X1 += 0.00000015590 * math.cos(5.48957045033 + 39.6488775085 * self.t)
X1 += 0.00000015469 * math.cos(0.19931591320 + 43.79347909271 * self.t)
X1 += 0.00000016590 * math.cos(2.76837508684 + 33.71098667531 * self.t)
X1 += 0.00000019347 * math.cos(5.63498287914 + 152.77596003471 * self.t)
X1 += 0.00000014994 * math.cos(2.71995630411 + 319.06881347989 * self.t)
X1 += 0.00000014395 * math.cos(0.95950619453 + 110.45013870291 * self.t)
X1 += 0.00000015528 * math.cos(1.16348592635 + 79.43065006591 * self.t)
X1 += 0.00000013727 * math.cos(2.45811249773 + 43.484662552 * self.t)
X1 += 0.00000013988 * math.cos(3.96979676090 + 4.2096006414 * self.t)
X1 += 0.00000014467 * math.cos(0.42164709009 + 108.70503356371 * self.t)
X1 += 0.00000016652 * math.cos(3.17617180933 + 304.84171947829 * self.t)
X1 += 0.00000015153 * math.cos(3.21783791411 + 72.31710306511 * self.t)
X1 += 0.00000012810 * math.cos(2.37864271463 + 11.2895177474 * self.t)
X1 += 0.00000012751 * math.cos(0.61424962834 + 45.7992166628 * self.t)
X1 += 0.00000013293 * math.cos(4.71511827202 + 43.0427195673 * self.t)
X1 += 0.00000012751 * math.cos(2.55685741962 + 515.70768857651 * self.t)
X1 += 0.00000011616 * math.cos(2.50185569269 + 97.17169833279 * self.t)
X1 += 0.00000011538 * math.cos(6.20327139591 + 633.0275567967 * self.t)
X1 += 0.00000011046 * math.cos(1.26188662646 + 25.8466801491 * self.t)
X1 += 0.00000011032 * math.cos(3.82567311622 + 4.8639919472 * self.t)
X1 += 0.00000011189 * math.cos(3.94939417077 + 83.1021708981 * self.t)
X1 += 0.00000010860 * math.cos(0.38739756984 + 9.8050450391 * self.t)
X1 += 0.00000010958 * math.cos(1.48375898962 + 415.04804069769 * self.t)
X1 += 0.00000010244 * math.cos(0.26615444717 + 71.09326278771 * self.t)
X1 += 0.00000011427 * math.cos(1.50679043329 + 129.6756596781 * self.t)
X1 += 0.00000009895 * math.cos(5.62468142972 + 251.6759485593 * self.t)
X1 += 0.00000009802 * math.cos(1.83814841533 + 44.48150029329 * self.t)
X1 += 0.00000011029 * math.cos(4.69741395112 + 143.38148881789 * self.t)
X1 += 0.00000009235 * math.cos(5.99370019321 + 199.3158189199 * self.t)
X1 += 0.00000008899 * math.cos(3.54958918415 + 7.3573644843 * self.t)
X1 += 0.00000007746 * math.cos(5.89688581764 + 103.3365917021 * self.t)
X1 += 0.00000008691 * math.cos(3.86130807292 + 32.7477788288 * self.t)
X1 += 0.00000007714 * math.cos(5.08136079606 + 65.46418849521 * self.t)
X1 += 0.00000008007 * math.cos(1.80952555463 + 544.1618765797 * self.t)
X1 += 0.00000007513 * math.cos(1.47497152514 + 69.6087900794 * self.t)
X1 += 0.00000007336 * math.cos(5.00489054996 + 15.7429358723 * self.t)
X1 += 0.00000007195 * math.cos(6.14029832936 + 949.4194264533 * self.t)
X1 += 0.00000009601 * math.cos(0.96952505042 + 80.963306884 * self.t)
X1 += 0.00000008094 * math.cos(3.27383873772 + 526.7533888404 * self.t)
X1 += 0.00000008109 * math.cos(1.06293290956 + 533.1161763158 * self.t)
X1 += 0.00000006906 * math.cos(5.27751864757 + 137.2768416459 * self.t)
X1 += 0.00000007455 * math.cos(5.82601593331 + 105.2484531801 * self.t)
X1 += 0.00000007826 * math.cos(4.02401038086 + 77.0311536209 * self.t)
X1 += 0.00000006529 * math.cos(0.86598314454 + 65.2035560643 * self.t)
X1 += 0.00000007134 * math.cos(3.62090018772 + 44.00592741381 * self.t)
X1 += 0.00000006186 * math.cos(2.42103444520 + 31.4757544416 * self.t)
X1 += 0.00000006186 * math.cos(2.42103444520 + 30.9881194746 * self.t)
X1 += 0.00000007698 * math.cos(0.17876132177 + 14.47091148511 * self.t)
X1 += 0.00000007434 * math.cos(5.53413189412 + 146.8380692015 * self.t)
X1 += 0.00000006317 * math.cos(0.53538901275 + 66.9486612035 * self.t)
X1 += 0.00000006903 * math.cos(6.20818943193 + 75.98862389731 * self.t)
X1 += 0.00000005591 * math.cos(1.90701487438 + 448.98829064149 * self.t)
X1 += 0.00000006425 * math.cos(5.04706195455 + 678.27413943531 * self.t)
X1 += 0.00000005483 * math.cos(3.18327336885 + 34.44469985821 * self.t)
X1 += 0.00000005483 * math.cos(4.29890655108 + 42.3090063844 * self.t)
X1 += 0.00000005519 * math.cos(2.84195707915 + 853.4401992355 * self.t)
X1 += 0.00000005483 * math.cos(3.53790147295 + 100.14064374939 * self.t)
X1 += 0.00000005483 * math.cos(3.53790147295 + 100.6282787164 * self.t)
X1 += 0.00000006288 * math.cos(1.03240051727 + 143.9027536797 * self.t)
X1 += 0.00000006239 * math.cos(5.78066710550 + 17.76992530181 * self.t)
X1 += 0.00000005246 * math.cos(5.09114965169 + 209.6107596584 * self.t)
X1 += 0.00000005331 * math.cos(3.26471064810 + 45.9659730016 * self.t)
X1 += 0.00000005131 * math.cos(6.10583196953 + 217.4750661846 * self.t)
X1 += 0.00000005325 * math.cos(4.39759756568 + 19.2543980101 * self.t)
X1 += 0.00000005172 * math.cos(0.86928942503 + 25.3590451821 * self.t)
X1 += 0.00000005139 * math.cos(2.60427452606 + 6.86972951729 * self.t)
X1 += 0.00000005992 * math.cos(1.19287924990 + 9.3174100721 * self.t)
X1 += 0.00000005011 * math.cos(3.34804654196 + 38.85242600079 * self.t)
X1 += 0.00000004975 * math.cos(1.43964900757 + 525.2543619171 * self.t)
X1 += 0.00000004910 * math.cos(5.04787040559 + 45.277951801 * self.t)
X1 += 0.00000005250 * math.cos(4.87798510402 + 0.719390363 * self.t)
X1 += 0.00000004731 * math.cos(1.56230403811 + 40.3825906914 * self.t)
X1 += 0.00000004731 * math.cos(2.77828322823 + 36.3711155512 * self.t)
X1 += 0.00000005910 * math.cos(6.11804979728 + 6168.43292559449 * self.t)
X1 += 0.00000004700 * math.cos(6.23394030506 + 50.9070260935 * self.t)
X1 += 0.00000005127 * math.cos(0.06949696047 + 140.9338082631 * self.t)
X1 += 0.00000005321 * math.cos(3.67018745291 + 1104.87233031131 * self.t)
X1 += 0.00000006339 * math.cos(2.59865692618 + 10175.3963280567 * self.t)
X1 += 0.00000004983 * math.cos(3.03193615352 + 1090.6452363097 * self.t)
X1 += 0.00000005487 * math.cos(4.85218420019 + 180.03005174739 * self.t)
X1 += 0.00000004560 * math.cos(3.95095239655 + 323.74923414091 * self.t)
X1 += 0.00000004689 * math.cos(1.24271255508 + 1068.22376738181 * self.t)
X1 += 0.00000005562 * math.cos(1.26401999292 + 10098.64262181409 * self.t)
X1 += 0.00000004432 * math.cos(2.40638908148 + 415.7963080956 * self.t)
X1 += 0.00000004456 * math.cos(6.17485306628 + 235.68919520349 * self.t)
X1 += 0.00000004289 * math.cos(5.97528879519 + 1051.0277279636 * self.t)
X1 += 0.00000004145 * math.cos(3.13378236518 + 33.6964324603 * self.t)
X1 += 0.00000004167 * math.cos(1.72807331665 + 416.532513406 * self.t)
X1 += 0.00000004107 * math.cos(2.49036069416 + 61.01077037031 * self.t)
X1 += 0.00000004088 * math.cos(5.45739808026 + 423.66061462181 * self.t)
X1 += 0.00000005027 * math.cos(4.43953537205 + 21.7020785649 * self.t)
X1 += 0.00000004030 * math.cos(5.01269280095 + 216.72430665921 * self.t)
X1 += 0.00000004278 * math.cos(4.65333719777 + 310.4707937708 * self.t)
X1 += 0.00000004013 * math.cos(1.39689438468 + 104275.10267753768 * self.t)
X1 += 0.00000004505 * math.cos(1.22507263591 + 291.9478482112 * self.t)
X1 += 0.00000003959 * math.cos(6.18034607330 + 210.36151918381 * self.t)
X1 += 0.00000003962 * math.cos(4.02082978591 + 978.93988816699 * self.t)
X1 += 0.00000005561 * math.cos(1.74843583918 + 1409.47023230609 * self.t)
X1 += 0.00000005073 * math.cos(3.58205424554 + 1498.3359125231 * self.t)
X1 += 0.00000004227 * math.cos(1.48715312131 + 534.38820070301 * self.t)
X1 += 0.00000004054 * math.cos(4.02884108627 + 430.02340209721 * self.t)
X1 += 0.00000003863 * math.cos(2.24264031920 + 1127.50624756031 * self.t)
X1 += 0.00000004367 * math.cos(1.71153359581 + 58.9837809408 * self.t)
X1 += 0.00000004694 * math.cos(3.33961949377 + 77.5067265004 * self.t)
X1 += 0.00000004144 * math.cos(3.59057653937 + 518.1408149163 * self.t)
X1 += 0.00000004289 * math.cos(3.29776439152 + 921.3206991231 * self.t)
X1 += 0.00000004039 * math.cos(3.79987840474 + 1622.76932774409 * self.t)
X1 += 0.00000005180 * math.cos(5.37115331697 + 99.1438060081 * self.t)
X1 += 0.00000004845 * math.cos(6.04321981604 + 136.78920667889 * self.t)
X1 += 0.00000004827 * math.cos(2.78459346340 + 418.2439886504 * self.t)
X1 += 0.00000003722 * math.cos(0.22932453326 + 1065.2548219652 * self.t)
X1 += 0.00000004729 * math.cos(3.76762324044 + 421.212934067 * self.t)
X1 += 0.00000003490 * math.cos(5.25995346649 + 986.8041946932 * self.t)
X1 += 0.00000003715 * math.cos(6.02151166051 + 254.10907489909 * self.t)
X1 += 0.00000003488 * math.cos(1.23861297869 + 187.9400502559 * self.t)
X1 += 0.00000003989 * math.cos(3.79961685835 + 95.7354097343 * self.t)
X1 += 0.00000003603 * math.cos(0.65230587403 + 67.1154175423 * self.t)
X1 += 0.00000003530 * math.cos(2.51065807549 + 24.36220744081 * self.t)
X1 += 0.00000003538 * math.cos(3.09031960755 + 57.4993082325 * self.t)
X1 += 0.00000003838 * math.cos(1.99815683749 + 979.90309601349 * self.t)
X1 += 0.00000003615 * math.cos(3.17553643085 + 493.2862196486 * self.t)
X1 += 0.00000003457 * math.cos(0.22865254260 + 807.70598162989 * self.t)
X1 += 0.00000003648 * math.cos(3.01000228275 + 647.25465079831 * self.t)
X1 += 0.00000004048 * math.cos(4.68171378592 + 979.69064769239 * self.t)
X1 += 0.00000004414 * math.cos(3.57495606042 + 1062.59469308931 * self.t)
X1 += 0.00000003631 * math.cos(2.31921127570 + 486.1726726478 * self.t)
X1 += 0.00000003347 * math.cos(5.70639780704 + 151.2914873264 * self.t)
X1 += 0.00000003305 * math.cos(0.52158954660 + 1544.07013012871 * self.t)
X1 += 0.00000003428 * math.cos(1.68792809396 + 107.2205608554 * self.t)
X1 += 0.00000003286 * math.cos(5.12949558917 + 1131.6990332543 * self.t)
X1 += 0.00000003389 * math.cos(1.65565102713 + 28.98238190449 * self.t)
X1 += 0.00000003353 * math.cos(3.87388681549 + 10289.7954349701 * self.t)
X1 += 0.00000003214 * math.cos(2.40799794941 + 569.5522909242 * self.t)
X1 += 0.00000003210 * math.cos(5.76688710335 + 114.1552894299 * self.t)
X1 += 0.00000003353 * math.cos(3.19692974184 + 157.8837694654 * self.t)
X1 += 0.00000003339 * math.cos(3.69632773816 + 443.0985839181 * self.t)
X1 += 0.00000003188 * math.cos(1.05807532391 + 361.13400238079 * self.t)
X1 += 0.00000003390 * math.cos(0.82325646834 + 1558.2972241303 * self.t)
X1 += 0.00000003933 * math.cos(0.51543027693 + 313.43973918739 * self.t)
X1 += 0.00000003131 * math.cos(5.23811887945 + 275.3067035496 * self.t)
X1 += 0.00000003156 * math.cos(4.66486358528 + 431.8404353331 * self.t)
X1 += 0.00000003993 * math.cos(3.33001170426 + 67.6366824041 * self.t)
X1 += 0.00000003708 * math.cos(1.81916567333 + 500.39976664941 * self.t)
X1 += 0.00000004051 * math.cos(2.84746860357 + 59.038662695 * self.t)
X1 += 0.00000003757 * math.cos(3.59917867608 + 296.4012663361 * self.t)
X1 += 0.00000003138 * math.cos(5.35145867078 + 347.1193567003 * self.t)
X1 += 0.00000003086 * math.cos(3.24315098824 + 392.9017584157 * self.t)
X1 += 0.00000003466 * math.cos(0.02941146445 + 215.1941419686 * self.t)
X1 += 0.00000003139 * math.cos(4.67079139650 + 159.36824217371 * self.t)
X1 += 0.00000003466 * math.cos(1.90282193275 + 2145.34674583789 * self.t)
X1 += 0.00000003737 * math.cos(1.95939265626 + 449.0364747513 * self.t)
X1 += 0.00000003286 * math.cos(3.39700619187 + 435.44002806861 * self.t)
X1 += 0.00000003043 * math.cos(3.45909355839 + 2.20386307129 * self.t)
X1 += 0.00000003999 * math.cos(1.21766663097 + 6245.1866318371 * self.t)
X1 += 0.00000003999 * math.cos(4.35925928456 + 6244.69899687009 * self.t)
X1 += 0.00000002999 * math.cos(1.64598289911 + 526.00262931501 * self.t)
X1 += 0.00000003014 * math.cos(3.95092279768 + 1054.94532701169 * self.t)
X1 += 0.00000003091 * math.cos(2.95397758261 + 42.997027585 * self.t)
X1 += 0.00000003274 * math.cos(1.10162661548 + 736.1203310153 * self.t)
X1 += 0.00000002965 * math.cos(2.69144881941 + 533.8669358412 * self.t)
X1 += 0.00000003149 * math.cos(0.77764778909 + 103.7639804718 * self.t)
X1 += 0.00000003610 * math.cos(3.04477019722 + 55.05162767771 * self.t)
X1 += 0.00000002937 * math.cos(4.36852075939 + 385.2523923381 * self.t)
X1 += 0.00000002903 * math.cos(5.92315544183 + 117.5636857037 * self.t)
X1 += 0.00000002968 * math.cos(2.85171539624 + 613.31440085451 * self.t)
X1 += 0.00000003097 * math.cos(2.85040396879 + 1395.24313830449 * self.t)
X1 += 0.00000002931 * math.cos(5.17875295945 + 202.4972126576 * self.t)
X1 += 0.00000003013 * math.cos(3.06605929280 + 121.2352065359 * self.t)
X1 += 0.00000003206 * math.cos(1.29027400076 + 53.40958840249 * self.t)
X1 += 0.00000003269 * math.cos(5.16847517364 + 480.00777927849 * self.t)
X1 += 0.00000003948 * math.cos(3.85972628729 + 112.8832650427 * self.t)
X1 += 0.00000002824 * math.cos(1.57846497121 + 176.406715025 * self.t)
X1 += 0.00000002827 * math.cos(1.93940329091 + 429.81095377611 * self.t)
X1 += 0.00000003348 * math.cos(5.12243609352 + 6284.8041401832 * self.t)
X1 += 0.00000002862 * math.cos(0.86276885894 + 384.02855206069 * self.t)
X1 += 0.00000003228 * math.cos(0.42457598020 + 52.6039471229 * self.t)
X1 += 0.00000003446 * math.cos(3.75606585057 + 62.0076081116 * self.t)
X1 += 0.00000003096 * math.cos(3.26760360935 + 71.82946809809 * self.t)
X1 += 0.00000003031 * math.cos(4.66996407487 + 494.2348732801 * self.t)
X1 += 0.00000003021 * math.cos(1.39292760491 + 328.5964111407 * self.t)
X1 += 0.00000002731 * math.cos(2.36952809744 + 432.471082652 * self.t)
X1 += 0.00000003171 * math.cos(0.25949036332 + 10215.0138364028 * self.t)
X1 += 0.00000002674 * math.cos(0.72177739894 + 158.12984768129 * self.t)
X1 += 0.00000002901 * math.cos(5.80027365050 + 559.4697985068 * self.t)
X1 += 0.00000002631 * math.cos(5.78146252380 + 2008.8013566425 * self.t)
X1 += 0.00000002695 * math.cos(5.11715867535 + 81.61769818981 * self.t)
X1 += 0.00000002695 * math.cos(1.97556602176 + 81.13006322279 * self.t)
X1 += 0.00000002721 * math.cos(2.68965946829 + 326.1823604807 * self.t)
X1 += 0.00000002775 * math.cos(5.84695952836 + 457.8614969965 * self.t)
X1 += 0.00000003054 * math.cos(1.52217085552 + 6281.8351947666 * self.t)
X1 += 0.00000002852 * math.cos(4.47706032032 + 186.71620997851 * self.t)
X1 += 0.00000002538 * math.cos(0.16145086268 + 111.18634401329 * self.t)
X1 += 0.00000002835 * math.cos(4.50055998275 + 419.50145882259 * self.t)
X1 += 0.00000002868 * math.cos(2.09813621145 + 844.56699288049 * self.t)
X1 += 0.00000002530 * math.cos(1.04013419881 + 1050.7525413177 * self.t)
X1 += 0.00000002843 * math.cos(2.58892628620 + 830.3398988789 * self.t)
X1 += 0.00000002848 * math.cos(3.12250765680 + 659.36662477269 * self.t)
X1 += 0.00000003031 * math.cos(4.13022602708 + 406.3469551246 * self.t)
X1 += 0.00000002907 * math.cos(5.28583383732 + 573.6968925084 * self.t)
X1 += 0.00000002536 * math.cos(3.44172011173 + 82.6145359311 * self.t)
X1 += 0.00000002957 * math.cos(0.45041658093 + 947.70795120889 * self.t)
X1 += 0.00000003321 * math.cos(2.30536254604 + 449.9996825978 * self.t)
X1 += 0.00000003117 * math.cos(3.17172140219 + 457.32567791969 * self.t)
X1 += 0.00000002902 * math.cos(2.94761781535 + 10212.0448909862 * self.t)
X1 += 0.00000002459 * math.cos(2.17142711813 + 450.73339578069 * self.t)
X1 += 0.00000002557 * math.cos(2.89791026532 + 525.4813644532 * self.t)
X1 += 0.00000002624 * math.cos(1.78027142371 + 946.2234785006 * self.t)
X1 += 0.00000002417 * math.cos(4.80936350850 + 351.5727748252 * self.t)
X1 += 0.00000002454 * math.cos(4.84992044892 + 196.01680510321 * self.t)
X1 += 0.00000002585 * math.cos(0.99587951695 + 248.70700314271 * self.t)
X1 += 0.00000002549 * math.cos(1.80324449988 + 1062.80714141041 * self.t)
X1 += 0.00000002615 * math.cos(2.49010683388 + 425.13053311509 * self.t)
X1 += 0.00000002387 * math.cos(3.61270640757 + 654.3681977991 * self.t)
X1 += 0.00000002439 * math.cos(6.16957116292 + 462.74230389109 * self.t)
X1 += 0.00000002367 * math.cos(4.32238656757 + 107.52937739611 * self.t)
X1 += 0.00000002538 * math.cos(2.61932649618 + 481.2316195559 * self.t)
X1 += 0.00000002479 * math.cos(1.99143603619 + 205.9417309537 * self.t)
X1 += 0.00000002791 * math.cos(0.73480816467 + 24.14975911971 * self.t)
X1 += 0.00000002626 * math.cos(1.16663444616 + 213.0552779545 * self.t)
X1 += 0.00000002445 * math.cos(4.84988920933 + 146.87169909629 * self.t)
X1 += 0.00000002575 * math.cos(1.89431453798 + 86.07111631471 * self.t)
X1 += 0.00000003120 * math.cos(5.91742201237 + 456.36247007319 * self.t)
X1 += 0.00000002587 * math.cos(0.02224873460 + 400.8209466961 * self.t)
X1 += 0.00000002261 * math.cos(4.82066845150 + 644.33388949151 * self.t)
X1 += 0.00000002796 * math.cos(5.01395178381 + 216.67861467689 * self.t)
X1 += 0.00000002896 * math.cos(2.29072801127 + 1685.2959399851 * self.t)
X1 += 0.00000002453 * math.cos(3.24288673382 + 109.9625037359 * self.t)
X1 += 0.00000002325 * math.cos(4.96633817815 + 442.886135597 * self.t)
X1 += 0.00000002387 * math.cos(5.32424727918 + 599.0873068529 * self.t)
X1 += 0.00000002873 * math.cos(3.56351208170 + 834.5326845729 * self.t)
X1 += 0.00000002963 * math.cos(0.77021714990 + 2119.00767786191 * self.t)
X1 += 0.00000002233 * math.cos(5.94426610995 + 709.29362807231 * self.t)
X1 += 0.00000002337 * math.cos(4.30558394222 + 210.5739675049 * self.t)
X1 += 0.00000002259 * math.cos(3.67528651606 + 29.5036467663 * self.t)
X1 += 0.00000002300 * math.cos(0.62755545112 + 986.0534351678 * self.t)
X1 += 0.00000002199 * math.cos(2.78438991669 + 606.2008538537 * self.t)
X1 += 0.00000002325 * math.cos(3.26991047297 + 109.701871305 * self.t)
# Neptune_X2 (t) // 113 terms of order 2
X2 = 0
X2 += 0.01620002167 * math.cos(0.60038473142 + 38.3768531213 * self.t)
X2 += 0.00028138323 * math.cos(5.58440767451 + 0.2438174835 * self.t)
X2 += 0.00012318619 * math.cos(2.58513114618 + 39.86132582961 * self.t)
X2 += 0.00008346956 * math.cos(5.13440715484 + 37.88921815429 * self.t)
X2 += 0.00005131003 * math.cos(5.12974075920 + 76.50988875911 * self.t)
X2 += 0.00004109792 * math.cos(1.46495026130 + 36.892380413 * self.t)
X2 += 0.00001369663 * math.cos(3.55762715050 + 1.7282901918 * self.t)
X2 += 0.00000633706 * math.cos(2.38135108376 + 3.21276290011 * self.t)
X2 += 0.00000583006 * math.cos(1.54592369321 + 41.3457985379 * self.t)
X2 += 0.00000546517 * math.cos(0.70972594452 + 75.0254160508 * self.t)
X2 += 0.00000246224 * math.cos(2.44618778574 + 213.5429129215 * self.t)
X2 += 0.00000159773 * math.cos(1.26414365966 + 206.42936592071 * self.t)
X2 += 0.00000156619 * math.cos(3.61656709171 + 220.6564599223 * self.t)
X2 += 0.00000191674 * math.cos(2.17166123081 + 529.9347825781 * self.t)
X2 += 0.00000188212 * math.cos(4.43184732741 + 35.40790770471 * self.t)
X2 += 0.00000117788 * math.cos(4.12530218101 + 522.8212355773 * self.t)
X2 += 0.00000114488 * math.cos(0.05081176794 + 35.9291725665 * self.t)
X2 += 0.00000112666 * math.cos(0.21220394551 + 537.0483295789 * self.t)
X2 += 0.00000105949 * math.cos(1.13080468733 + 40.8245336761 * self.t)
X2 += 0.00000077696 * math.cos(0.84633184914 + 77.9943614674 * self.t)
X2 += 0.00000090798 * math.cos(2.05479887039 + 73.5409433425 * self.t)
X2 += 0.00000067696 * math.cos(2.44679430551 + 426.8420083595 * self.t)
X2 += 0.00000074860 * math.cos(1.44346648461 + 4.6972356084 * self.t)
X2 += 0.00000064717 * math.cos(6.06001471150 + 34.9202727377 * self.t)
X2 += 0.00000051378 * math.cos(6.13002795973 + 36.404745446 * self.t)
X2 += 0.00000050205 * math.cos(0.67007332287 + 42.83027124621 * self.t)
X2 += 0.00000040929 * math.cos(6.22049348014 + 33.9234349964 * self.t)
X2 += 0.00000036136 * math.cos(6.15460243008 + 98.6561710411 * self.t)
X2 += 0.00000033953 * math.cos(5.02568302050 + 1059.6257476727 * self.t)
X2 += 0.00000034603 * math.cos(3.26702076082 + 76.0222537921 * self.t)
X2 += 0.00000035441 * math.cos(2.49518827466 + 31.2633061205 * self.t)
X2 += 0.00000029614 * math.cos(3.34814694529 + 28.81562556571 * self.t)
X2 += 0.00000031027 * math.cos(4.97087448592 + 45.49040012211 * self.t)
X2 += 0.00000035521 * math.cos(1.13028002523 + 39.3736908626 * self.t)
X2 += 0.00000025488 * math.cos(4.04320892614 + 47.9380806769 * self.t)
X2 += 0.00000020115 * math.cos(3.93227849656 + 1.24065522479 * self.t)
X2 += 0.00000014328 * math.cos(2.73754899228 + 433.9555553603 * self.t)
X2 += 0.00000015503 * math.cos(3.13160557995 + 114.6429243969 * self.t)
X2 += 0.00000016998 * math.cos(0.93393874821 + 33.43580002939 * self.t)
X2 += 0.00000013166 * math.cos(0.39556817176 + 419.72846135871 * self.t)
X2 += 0.00000013053 * math.cos(6.11304367644 + 60.52313540329 * self.t)
X2 += 0.00000010637 * math.cos(5.94332175983 + 34.1840674273 * self.t)
X2 += 0.00000009610 * math.cos(1.65699013342 + 640.1411037975 * self.t)
X2 += 0.00000009354 * math.cos(1.41415954295 + 42.5696388153 * self.t)
X2 += 0.00000011447 * math.cos(6.19793150566 + 71.5688356672 * self.t)
X2 += 0.00000008454 * math.cos(2.75562169800 + 2.7251279331 * self.t)
X2 += 0.00000009012 * math.cos(4.44112001347 + 72.05647063421 * self.t)
X2 += 0.00000009594 * math.cos(5.79483289118 + 69.3963417583 * self.t)
X2 += 0.00000007419 * math.cos(3.49645345230 + 227.77000692311 * self.t)
X2 += 0.00000006800 * math.cos(5.14250085135 + 113.15845168861 * self.t)
X2 += 0.00000006267 * math.cos(0.79586518424 + 1066.7392946735 * self.t)
X2 += 0.00000006895 * math.cos(4.31090775556 + 111.67397898031 * self.t)
X2 += 0.00000005770 * math.cos(1.23253284004 + 32.4389622881 * self.t)
X2 += 0.00000005686 * math.cos(2.23805923850 + 30.300098274 * self.t)
X2 += 0.00000006679 * math.cos(4.85529332414 + 258.78949556011 * self.t)
X2 += 0.00000007799 * math.cos(1.58396135295 + 7.3573644843 * self.t)
X2 += 0.00000005906 * math.cos(5.92485931723 + 44.31474395451 * self.t)
X2 += 0.00000005606 * math.cos(5.17941805418 + 46.4536079686 * self.t)
X2 += 0.00000005525 * math.cos(3.61911776351 + 1052.51220067191 * self.t)
X2 += 0.00000007257 * math.cos(0.17315189128 + 1097.7587833105 * self.t)
X2 += 0.00000005427 * math.cos(1.80586256737 + 105.76971804189 * self.t)
X2 += 0.00000005179 * math.cos(4.25986194250 + 515.70768857651 * self.t)
X2 += 0.00000005163 * math.cos(6.27919257182 + 7.83293736379 * self.t)
X2 += 0.00000004688 * math.cos(2.52139212878 + 222.14093263061 * self.t)
X2 += 0.00000005379 * math.cos(5.86341629561 + 22.3900997655 * self.t)
X2 += 0.00000004607 * math.cos(4.89100806572 + 549.1603035533 * self.t)
X2 += 0.00000004101 * math.cos(0.29016053329 + 213.0552779545 * self.t)
X2 += 0.00000004262 * math.cos(5.51395238453 + 204.9448932124 * self.t)
X2 += 0.00000003916 * math.cos(0.21419544093 + 207.913838629 * self.t)
X2 += 0.00000004089 * math.cos(4.97684127402 + 304.84171947829 * self.t)
X2 += 0.00000003729 * math.cos(1.40848954224 + 199.3158189199 * self.t)
X2 += 0.00000003680 * math.cos(5.54809318630 + 1589.3167127673 * self.t)
X2 += 0.00000003702 * math.cos(1.01863119774 + 319.06881347989 * self.t)
X2 += 0.00000004832 * math.cos(1.26423594188 + 215.0273856298 * self.t)
X2 += 0.00000003474 * math.cos(1.17401543445 + 103.3365917021 * self.t)
X2 += 0.00000003298 * math.cos(0.10619126376 + 544.1618765797 * self.t)
X2 += 0.00000004521 * math.cos(0.07911565781 + 108.2173985967 * self.t)
X2 += 0.00000003967 * math.cos(2.67776762695 + 944.7390057923 * self.t)
X2 += 0.00000004059 * math.cos(3.01104350847 + 149.8070146181 * self.t)
X2 += 0.00000004009 * math.cos(5.61852534309 + 533.1161763158 * self.t)
X2 += 0.00000003288 * math.cos(1.44957894842 + 407.9344936969 * self.t)
X2 += 0.00000003976 * math.cos(5.00221858099 + 526.7533888404 * self.t)
X2 += 0.00000003343 * math.cos(0.65785646071 + 531.4192552864 * self.t)
X2 += 0.00000003932 * math.cos(3.66244745467 + 91.54262404029 * self.t)
X2 += 0.00000003478 * math.cos(6.19876429652 + 6.1817083167 * self.t)
X2 += 0.00000002967 * math.cos(1.04478648324 + 860.55374623631 * self.t)
X2 += 0.00000003058 * math.cos(0.02482940557 + 342.9747551161 * self.t)
X2 += 0.00000003974 * math.cos(2.04910269520 + 335.8612081153 * self.t)
X2 += 0.00000002849 * math.cos(0.86611245106 + 666.4801717735 * self.t)
X2 += 0.00000002999 * math.cos(1.27874757189 + 937.62545879149 * self.t)
X2 += 0.00000003008 * math.cos(5.16783990611 + 74.53778108379 * self.t)
X2 += 0.00000003080 * math.cos(3.04902400148 + 129.6756596781 * self.t)
X2 += 0.00000003346 * math.cos(4.64303639862 + 1162.7185218913 * self.t)
X2 += 0.00000002625 * math.cos(1.69459459452 + 273.8222308413 * self.t)
X2 += 0.00000002931 * math.cos(1.57809055514 + 235.68919520349 * self.t)
X2 += 0.00000002579 * math.cos(0.48473918174 + 1073.85284167431 * self.t)
X2 += 0.00000002550 * math.cos(6.14366282644 + 26.58288545949 * self.t)
X2 += 0.00000002542 * math.cos(4.22297682017 + 1265.81129610991 * self.t)
X2 += 0.00000002483 * math.cos(1.73279038376 + 453.1810763355 * self.t)
X2 += 0.00000002732 * math.cos(1.76626805419 + 563.38739755489 * self.t)
X2 += 0.00000002508 * math.cos(1.67664275102 + 37.8555882595 * self.t)
X2 += 0.00000002508 * math.cos(0.34076894500 + 425.35753565121 * self.t)
X2 += 0.00000002680 * math.cos(5.74609617365 + 454.6655490438 * self.t)
X2 += 0.00000002511 * math.cos(3.15018930028 + 209.6107596584 * self.t)
X2 += 0.00000002512 * math.cos(1.74477024139 + 217.4750661846 * self.t)
X2 += 0.00000002552 * math.cos(5.67032305105 + 79.47883417571 * self.t)
X2 += 0.00000002457 * math.cos(2.67033044982 + 38.89811798311 * self.t)
X2 += 0.00000002343 * math.cos(1.93599816349 + 981.3875687218 * self.t)
X2 += 0.00000002501 * math.cos(1.67412173715 + 669.4009330803 * self.t)
X2 += 0.00000002330 * math.cos(3.95065162563 + 38.32866901151 * self.t)
X2 += 0.00000002327 * math.cos(0.39474993260 + 38.4250372311 * self.t)
X2 += 0.00000002481 * math.cos(5.56752927904 + 655.1738390787 * self.t)
X2 += 0.00000002569 * math.cos(4.22623902188 + 464.97504399731 * self.t)
# Neptune_X3 (t) // 37 terms of order 3
X3 = 0
X3 += 0.00000985355 * math.cos(0.69240373955 + 38.3768531213 * self.t)
X3 += 0.00000482798 * math.cos(0.83271959724 + 37.88921815429 * self.t)
X3 += 0.00000416447 * math.cos(0.37037561694 + 0.2438174835 * self.t)
X3 += 0.00000303825 * math.cos(0.53797420117 + 39.86132582961 * self.t)
X3 += 0.00000089203 * math.cos(1.52338099991 + 36.892380413 * self.t)
X3 += 0.00000070862 * math.cos(5.83899744010 + 76.50988875911 * self.t)
X3 += 0.00000028900 * math.cos(5.65001946959 + 41.3457985379 * self.t)
X3 += 0.00000022279 * math.cos(2.95886685234 + 206.42936592071 * self.t)
X3 += 0.00000021480 * math.cos(1.87359273442 + 220.6564599223 * self.t)
X3 += 0.00000016157 * math.cos(5.83581915834 + 522.8212355773 * self.t)
X3 += 0.00000015714 * math.cos(4.76719570238 + 537.0483295789 * self.t)
X3 += 0.00000011404 * math.cos(2.25961154910 + 35.40790770471 * self.t)
X3 += 0.00000013199 * math.cos(0.06057423298 + 7.3573644843 * self.t)
X3 += 0.00000007024 * math.cos(0.69890179308 + 3.21276290011 * self.t)
X3 += 0.00000006772 * math.cos(1.19679143435 + 69.3963417583 * self.t)
X3 += 0.00000004517 * math.cos(3.28893027439 + 45.49040012211 * self.t)
X3 += 0.00000004523 * math.cos(4.18705629066 + 31.2633061205 * self.t)
X3 += 0.00000003682 * math.cos(1.47261975259 + 98.6561710411 * self.t)
X3 += 0.00000003656 * math.cos(0.60146659814 + 968.64494742849 * self.t)
X3 += 0.00000003927 * math.cos(0.54740561653 + 426.8420083595 * self.t)
X3 += 0.00000003199 * math.cos(1.67327016260 + 1519.6765535255 * self.t)
X3 += 0.00000003498 * math.cos(3.27476696786 + 407.9344936969 * self.t)
X3 += 0.00000003304 * math.cos(2.24745680549 + 422.1615876985 * self.t)
X3 += 0.00000003331 * math.cos(1.97045240379 + 36.404745446 * self.t)
X3 += 0.00000003244 * math.cos(2.85168281358 + 484.2005649725 * self.t)
X3 += 0.00000002689 * math.cos(0.89932845788 + 441.06910236111 * self.t)
X3 += 0.00000003247 * math.cos(1.76512860403 + 498.42765897409 * self.t)
X3 += 0.00000002651 * math.cos(0.45669916115 + 304.84171947829 * self.t)
X3 += 0.00000002645 * math.cos(5.61672793904 + 461.77909604459 * self.t)
X3 += 0.00000002542 * math.cos(5.76347018476 + 444.5830566264 * self.t)
X3 += 0.00000002524 * math.cos(0.75739625090 + 433.9555553603 * self.t)
X3 += 0.00000002472 * math.cos(5.63416184223 + 319.06881347989 * self.t)
X3 += 0.00000002355 * math.cos(0.46192754883 + 447.552002043 * self.t)
X3 += 0.00000002876 * math.cos(5.22513442854 + 853.4401992355 * self.t)
X3 += 0.00000002279 * math.cos(4.63709500769 + 458.810150628 * self.t)
X3 += 0.00000002147 * math.cos(2.63611189369 + 175.40987728371 * self.t)
X3 += 0.00000002637 * math.cos(3.63693499332 + 73.5409433425 * self.t)
# Neptune_X4 (t) // 14 terms of order 4
X4 = 0
X4 += 0.00003455306 * math.cos(3.61464892215 + 38.3768531213 * self.t)
X4 += 0.00000047405 * math.cos(2.21390996774 + 0.2438174835 * self.t)
X4 += 0.00000021936 * math.cos(2.72972488197 + 37.88921815429 * self.t)
X4 += 0.00000015596 * math.cos(1.87854121560 + 76.50988875911 * self.t)
X4 += 0.00000017186 * math.cos(5.53785371687 + 39.86132582961 * self.t)
X4 += 0.00000017459 * math.cos(4.82899740364 + 36.892380413 * self.t)
X4 += 0.00000004229 * math.cos(1.43245860878 + 515.70768857651 * self.t)
X4 += 0.00000004334 * math.cos(5.41648117577 + 433.9555553603 * self.t)
X4 += 0.00000003547 * math.cos(5.75561157107 + 989.98558843089 * self.t)
X4 += 0.00000003155 * math.cos(4.85322840051 + 467.40817033709 * self.t)
X4 += 0.00000003017 * math.cos(0.06479449145 + 227.77000692311 * self.t)
X4 += 0.00000002981 * math.cos(0.29920864811 + 1.7282901918 * self.t)
X4 += 0.00000002295 * math.cos(0.13749342692 + 220.6564599223 * self.t)
X4 += 0.00000002296 * math.cos(4.70646260044 + 206.42936592071 * self.t)
# Neptune_X5 (t) // 1 term of order 5
X5 = 0
X5 += 0.00000026291 * math.cos(3.71724730200 + 38.3768531213 * self.t)
X = (X0+
X1*self.t+
X2*self.t*self.t+
X3*self.t*self.t*self.t+
X4*self.t*self.t*self.t*self.t+
X5*self.t*self.t*self.t*self.t*self.t)
# Neptune_Y0 (t) // 821 terms of order 0
Y0 = 0
Y0 += 30.05973100580 * math.cos(3.74109000403 + 38.3768531213 * self.t)
Y0 += 0.40567587218 * math.cos(2.41070337452 + 0.2438174835 * self.t)
Y0 += 0.13506026414 * math.cos(1.92976188293 + 76.50988875911 * self.t)
Y0 += 0.15716341901 * math.cos(4.82548976006 + 36.892380413 * self.t)
Y0 += 0.14935642614 * math.cos(5.79716600101 + 39.86132582961 * self.t)
Y0 += 0.02590782232 * math.cos(0.42530135542 + 1.7282901918 * self.t)
Y0 += 0.01073890204 * math.cos(3.81397520876 + 75.0254160508 * self.t)
Y0 += 0.00816388197 * math.cos(5.49424416077 + 3.21276290011 * self.t)
Y0 += 0.00702768075 * math.cos(6.16602540157 + 35.40790770471 * self.t)
Y0 += 0.00687594822 * math.cos(2.29155372023 + 37.88921815429 * self.t)
Y0 += 0.00565555652 * math.cos(4.41864141199 + 41.3457985379 * self.t)
Y0 += 0.00495650075 * math.cos(5.31196432386 + 529.9347825781 * self.t)
Y0 += 0.00306025380 * math.cos(5.11155686178 + 73.5409433425 * self.t)
Y0 += 0.00272446904 * math.cos(5.58643013675 + 213.5429129215 * self.t)
Y0 += 0.00135892298 * math.cos(3.97575347243 + 77.9943614674 * self.t)
Y0 += 0.00122117697 * math.cos(2.87943509460 + 34.9202727377 * self.t)
Y0 += 0.00090968285 * math.cos(0.11807115994 + 114.6429243969 * self.t)
Y0 += 0.00068915400 * math.cos(4.26390741720 + 4.6972356084 * self.t)
Y0 += 0.00040370680 * math.cos(1.09050058383 + 33.9234349964 * self.t)
Y0 += 0.00028891307 * math.cos(3.21868082836 + 42.83027124621 * self.t)
Y0 += 0.00029247752 * math.cos(0.05239890051 + 72.05647063421 * self.t)
Y0 += 0.00025576289 * math.cos(3.05422599686 + 71.5688356672 * self.t)
Y0 += 0.00020517968 * math.cos(4.12700709797 + 33.43580002939 * self.t)
Y0 += 0.00012614154 * math.cos(1.99850111659 + 113.15845168861 * self.t)
Y0 += 0.00012788929 * math.cos(1.16690001367 + 111.67397898031 * self.t)
Y0 += 0.00012013477 * math.cos(5.66154697546 + 1059.6257476727 * self.t)
Y0 += 0.00009854638 * math.cos(1.82793273920 + 36.404745446 * self.t)
Y0 += 0.00008385825 * math.cos(3.22321843541 + 108.2173985967 * self.t)
Y0 += 0.00007577585 * math.cos(4.81209675667 + 426.8420083595 * self.t)
Y0 += 0.00006452053 * math.cos(3.05476893393 + 6.1817083167 * self.t)
Y0 += 0.00006551074 * math.cos(3.48963683470 + 1.24065522479 * self.t)
Y0 += 0.00004652534 * math.cos(4.81582901104 + 37.8555882595 * self.t)
Y0 += 0.00004732958 * math.cos(2.52632268239 + 79.47883417571 * self.t)
Y0 += 0.00004557247 * math.cos(5.80951559837 + 38.89811798311 * self.t)
Y0 += 0.00004322550 * math.cos(0.80665146695 + 38.32866901151 * self.t)
Y0 += 0.00004315539 * math.cos(3.53393508109 + 38.4250372311 * self.t)
Y0 += 0.00004089036 * math.cos(0.42349431022 + 37.4136452748 * self.t)
Y0 += 0.00004248658 * math.cos(4.06300076615 + 28.81562556571 * self.t)
Y0 += 0.00004622142 * math.cos(4.31075084247 + 70.08436295889 * self.t)
Y0 += 0.00003926447 * math.cos(3.91895428213 + 39.34006096781 * self.t)
Y0 += 0.00003148422 * math.cos(0.47516466537 + 76.0222537921 * self.t)
Y0 += 0.00003940981 * math.cos(3.86846009370 + 98.6561710411 * self.t)
Y0 += 0.00003323363 * math.cos(3.11696612599 + 4.4366031775 * self.t)
Y0 += 0.00003282964 * math.cos(4.38630915294 + 39.3736908626 * self.t)
Y0 += 0.00003110464 * math.cos(0.27337264525 + 47.9380806769 * self.t)
Y0 += 0.00002927062 * math.cos(1.26687681282 + 70.5719979259 * self.t)
Y0 += 0.00002748919 * math.cos(2.29910620256 + 32.4389622881 * self.t)
Y0 += 0.00003316668 * math.cos(3.39273716880 + 144.8659615262 * self.t)
Y0 += 0.00002822405 * math.cos(5.35210680933 + 31.9513273211 * self.t)
Y0 += 0.00002695972 * math.cos(2.28196668869 + 110.189506272 * self.t)
Y0 += 0.00002522990 * math.cos(6.23388252645 + 311.9552664791 * self.t)
Y0 += 0.00001888129 * math.cos(1.63385050550 + 35.9291725665 * self.t)
Y0 += 0.00001648229 * math.cos(2.49960621702 + 30.300098274 * self.t)
Y0 += 0.00001826545 * math.cos(2.00941496239 + 44.31474395451 * self.t)
Y0 += 0.00001956241 * math.cos(2.57436514192 + 206.42936592071 * self.t)
Y0 += 0.00001681257 * math.cos(2.70480495091 + 40.8245336761 * self.t)
Y0 += 0.00001533383 * math.cos(5.88971111646 + 38.26497853671 * self.t)
Y0 += 0.00001893076 * math.cos(5.46256301015 + 220.6564599223 * self.t)
Y0 += 0.00001527526 * math.cos(4.73412536340 + 38.4887277059 * self.t)
Y0 += 0.00002085691 * math.cos(6.28187170642 + 149.8070146181 * self.t)
Y0 += 0.00002070612 * math.cos(4.39661439400 + 136.78920667889 * self.t)
Y0 += 0.00001535699 * math.cos(2.18492948354 + 73.0533083755 * self.t)
Y0 += 0.00001667976 * math.cos(4.48792091670 + 106.73292588839 * self.t)
Y0 += 0.00001289620 * math.cos(1.82629228420 + 46.4536079686 * self.t)
Y0 += 0.00001559811 * math.cos(5.27109740006 + 38.11622069041 * self.t)
Y0 += 0.00001545705 * math.cos(5.35267674075 + 38.6374855522 * self.t)
Y0 += 0.00001435033 * math.cos(5.44094847718 + 522.8212355773 * self.t)
Y0 += 0.00001406206 * math.cos(2.04637394879 + 537.0483295789 * self.t)
Y0 += 0.00001256446 * math.cos(1.13828126057 + 34.1840674273 * self.t)
Y0 += 0.00001387973 * math.cos(2.14763765402 + 116.12739710521 * self.t)
Y0 += 0.00001457739 * math.cos(3.56061267693 + 181.5145244557 * self.t)
Y0 += 0.00001228429 * math.cos(1.21566711155 + 72.31710306511 * self.t)
Y0 += 0.00001140665 * math.cos(5.53723346032 + 7.83293736379 * self.t)
Y0 += 0.00001080801 * math.cos(3.18403832376 + 42.5696388153 * self.t)
Y0 += 0.00001201409 * math.cos(2.31627619186 + 2.7251279331 * self.t)
Y0 += 0.00001228671 * math.cos(1.08170099047 + 148.32254190981 * self.t)
Y0 += 0.00000722014 * math.cos(4.59727081765 + 152.77596003471 * self.t)
Y0 += 0.00000608545 * math.cos(2.92457352888 + 35.4560918145 * self.t)
Y0 += 0.00000722865 * math.cos(4.66419895504 + 143.38148881789 * self.t)
Y0 += 0.00000632820 * math.cos(1.84622497362 + 7.66618102501 * self.t)
Y0 += 0.00000642369 * math.cos(5.54570420373 + 68.5998902506 * self.t)
Y0 += 0.00000553789 * math.cos(1.41527095431 + 41.2976144281 * self.t)
Y0 += 0.00000682276 * math.cos(3.72885979362 + 218.1630873852 * self.t)
Y0 += 0.00000463186 * math.cos(1.17340921668 + 31.7845709823 * self.t)
Y0 += 0.00000521560 * math.cos(1.91893273311 + 0.719390363 * self.t)
Y0 += 0.00000437892 * math.cos(6.01046620661 + 1589.3167127673 * self.t)
Y0 += 0.00000398091 * math.cos(0.79544793472 + 6.3484646555 * self.t)
Y0 += 0.00000384065 * math.cos(3.15552603467 + 44.96913526031 * self.t)
Y0 += 0.00000395583 * math.cos(3.48448044710 + 108.70503356371 * self.t)
Y0 += 0.00000327446 * math.cos(4.26279342171 + 60.52313540329 * self.t)
Y0 += 0.00000358824 * math.cos(0.28673200218 + 30.4668546128 * self.t)
Y0 += 0.00000315179 * math.cos(1.74548132888 + 74.53778108379 * self.t)
Y0 += 0.00000343384 * math.cos(0.17566264278 + 0.7650823453 * self.t)
Y0 += 0.00000399611 * math.cos(3.76461168231 + 31.2633061205 * self.t)
Y0 += 0.00000314611 * math.cos(1.41723391958 + 419.72846135871 * self.t)
Y0 += 0.00000347596 * math.cos(4.83723596339 + 180.03005174739 * self.t)
Y0 += 0.00000382279 * math.cos(1.78844211361 + 487.1213262793 * self.t)
Y0 += 0.00000300918 * math.cos(2.47842979419 + 69.0875252176 * self.t)
Y0 += 0.00000340448 * math.cos(2.33467216950 + 146.8380692015 * self.t)
Y0 += 0.00000298710 * math.cos(3.60933906971 + 84.5866436064 * self.t)
Y0 += 0.00000290629 * math.cos(0.17794042595 + 110.45013870291 * self.t)
Y0 += 0.00000336211 * math.cos(0.57735466050 + 45.49040012211 * self.t)
Y0 += 0.00000305606 * math.cos(4.06185849299 + 640.1411037975 * self.t)
Y0 += 0.00000333702 * math.cos(3.90017949649 + 254.8116503147 * self.t)
Y0 += 0.00000268060 * math.cos(1.73772568979 + 37.0042549976 * self.t)
Y0 += 0.00000264760 * math.cos(2.55644426185 + 39.749451245 * self.t)
Y0 += 0.00000315240 * math.cos(1.15162155813 + 388.70897272171 * self.t)
Y0 += 0.00000227098 * math.cos(6.16236913832 + 273.8222308413 * self.t)
Y0 += 0.00000306112 * math.cos(0.18265553789 + 6283.3196674749 * self.t)
Y0 += 0.00000284373 * math.cos(1.79060192705 + 12.77399045571 * self.t)
Y0 += 0.00000221105 * math.cos(5.08019996555 + 213.0552779545 * self.t)
Y0 += 0.00000242568 * math.cos(0.49358017330 + 14.258463164 * self.t)
Y0 += 0.00000241087 * math.cos(5.73194988554 + 105.2484531801 * self.t)
Y0 += 0.00000226136 * math.cos(1.26736306174 + 80.963306884 * self.t)
Y0 += 0.00000245904 * math.cos(5.25701422242 + 27.3311528574 * self.t)
Y0 += 0.00000265825 * math.cos(5.68032293038 + 944.7390057923 * self.t)
Y0 += 0.00000207893 * math.cos(3.50733218656 + 30.95448957981 * self.t)
Y0 += 0.00000214661 * math.cos(1.08322862012 + 316.6356871401 * self.t)
Y0 += 0.00000190638 * math.cos(0.75588071076 + 69.3963417583 * self.t)
Y0 += 0.00000246295 * math.cos(3.55718121196 + 102.84895673509 * self.t)
Y0 += 0.00000202915 * math.cos(2.17108892757 + 415.04804069769 * self.t)
Y0 += 0.00000176465 * math.cos(4.85970190916 + 36.7805058284 * self.t)
Y0 += 0.00000193886 * math.cos(4.92555932032 + 174.9222423167 * self.t)
Y0 += 0.00000175209 * math.cos(5.83814591553 + 39.97320041421 * self.t)
Y0 += 0.00000177868 * math.cos(5.01003024093 + 216.67861467689 * self.t)
Y0 += 0.00000138494 * math.cos(3.88186287753 + 75.98862389731 * self.t)
Y0 += 0.00000152234 * math.cos(3.24582472092 + 11.2895177474 * self.t)
Y0 += 0.00000147648 * math.cos(0.11464073993 + 151.2914873264 * self.t)
Y0 += 0.00000156202 * math.cos(5.22332207731 + 146.3504342345 * self.t)
Y0 += 0.00000152289 * math.cos(1.64425361444 + 23.87457247379 * self.t)
Y0 += 0.00000177911 * math.cos(1.60563922042 + 10213.5293636945 * self.t)
Y0 += 0.00000162474 * math.cos(2.56271758700 + 63.9797157869 * self.t)
Y0 += 0.00000121226 * math.cos(3.53504653517 + 38.16440480021 * self.t)
Y0 += 0.00000129049 * math.cos(2.23605274276 + 37.1048287341 * self.t)
Y0 += 0.00000120334 * math.cos(0.80557581782 + 38.5893014424 * self.t)
Y0 += 0.00000168977 * math.cos(4.06631471177 + 291.4602132442 * self.t)
Y0 += 0.00000121138 * math.cos(6.20896007337 + 33.26904369061 * self.t)
Y0 += 0.00000129366 * math.cos(0.79823378243 + 45.7992166628 * self.t)
Y0 += 0.00000144682 * math.cos(5.34262329825 + 49.42255338521 * self.t)
Y0 += 0.00000122915 * math.cos(2.10353894081 + 39.6488775085 * self.t)
Y0 += 0.00000113400 * math.cos(5.13399083059 + 83.1021708981 * self.t)
Y0 += 0.00000154892 * math.cos(0.17909436973 + 77.4730966056 * self.t)
Y0 += 0.00000106737 * math.cos(2.14516700774 + 4.8639919472 * self.t)
Y0 += 0.00000104756 * math.cos(4.39192437833 + 43.484662552 * self.t)
Y0 += 0.00000125142 * math.cos(1.11541363958 + 4.2096006414 * self.t)
Y0 += 0.00000103541 * math.cos(3.68555108825 + 41.08516610701 * self.t)
Y0 += 0.00000133573 * math.cos(5.49226848460 + 182.998997164 * self.t)
Y0 += 0.00000103627 * math.cos(0.72176478921 + 35.6685401356 * self.t)
Y0 += 0.00000116874 * math.cos(3.84298763857 + 62.4952430786 * self.t)
Y0 += 0.00000098063 * math.cos(1.68574394986 + 9.8050450391 * self.t)
Y0 += 0.00000111411 * math.cos(5.91424942326 + 141.8970161096 * self.t)
Y0 += 0.00000114294 * math.cos(3.99149302956 + 633.0275567967 * self.t)
Y0 += 0.00000104705 * math.cos(4.68992506677 + 433.9555553603 * self.t)
Y0 += 0.00000121306 * math.cos(3.01971978017 + 40.8581635709 * self.t)
Y0 += 0.00000096954 * math.cos(4.60293836623 + 1052.51220067191 * self.t)
Y0 += 0.00000085104 * math.cos(3.21938589681 + 36.6799320919 * self.t)
Y0 += 0.00000085209 * math.cos(1.23258290286 + 105.76971804189 * self.t)
Y0 += 0.00000085291 * math.cos(4.16574840077 + 109.701871305 * self.t)
Y0 += 0.00000083260 * math.cos(1.57705309557 + 529.44714761109 * self.t)
Y0 += 0.00000080200 * math.cos(1.12120137014 + 40.07377415071 * self.t)
Y0 += 0.00000107927 * math.cos(4.72809768120 + 1162.7185218913 * self.t)
Y0 += 0.00000095241 * math.cos(5.18181889280 + 253.32717760639 * self.t)
Y0 += 0.00000089535 * math.cos(1.68098752171 + 32.9602271499 * self.t)
Y0 += 0.00000089793 * math.cos(1.19350927545 + 65.46418849521 * self.t)
Y0 += 0.00000072027 * math.cos(4.82605474115 + 36.9405645228 * self.t)
Y0 += 0.00000080381 * math.cos(0.49818419813 + 67.1154175423 * self.t)
Y0 += 0.00000099502 * math.cos(4.10090280616 + 453.1810763355 * self.t)
Y0 += 0.00000088685 * math.cos(6.05087292163 + 251.6759485593 * self.t)
Y0 += 0.00000094971 * math.cos(5.68681980258 + 219.6475600935 * self.t)
Y0 += 0.00000077015 * math.cos(3.73580633492 + 5.6604434549 * self.t)
Y0 += 0.00000069098 * math.cos(3.42063825132 + 22.3900997655 * self.t)
Y0 += 0.00000079079 * math.cos(5.69904586697 + 44.48150029329 * self.t)
Y0 += 0.00000069159 * math.cos(2.38821700872 + 1066.7392946735 * self.t)
Y0 += 0.00000064446 * math.cos(2.45996531968 + 66.9486612035 * self.t)
Y0 += 0.00000088518 * math.cos(4.23259429373 + 328.1087761737 * self.t)
Y0 += 0.00000065817 * math.cos(6.14060374302 + 36.3711155512 * self.t)
Y0 += 0.00000071422 * math.cos(2.66025338551 + 43.79347909271 * self.t)
Y0 += 0.00000063298 * math.cos(0.64067085772 + 9.1506537333 * self.t)
Y0 += 0.00000077320 * math.cos(1.83922353490 + 97.17169833279 * self.t)
Y0 += 0.00000073912 * math.cos(3.29477271110 + 2.6769438233 * self.t)
Y0 += 0.00000073965 * math.cos(3.98729910569 + 2.9521304692 * self.t)
Y0 += 0.00000056194 * math.cos(2.88777806681 + 949.4194264533 * self.t)
Y0 += 0.00000059173 * math.cos(2.98452265287 + 100.14064374939 * self.t)
Y0 += 0.00000067507 * math.cos(2.37620743833 + 7.14491616321 * self.t)
Y0 += 0.00000071718 * math.cos(2.50472239979 + 2.20386307129 * self.t)
Y0 += 0.00000063606 * math.cos(3.60095909928 + 25.8466801491 * self.t)
Y0 += 0.00000071523 * math.cos(3.62910110768 + 662.28738607949 * self.t)
Y0 += 0.00000057219 * math.cos(5.59723911326 + 15.7429358723 * self.t)
Y0 += 0.00000050322 * math.cos(5.79549186801 + 37.15301284391 * self.t)
Y0 += 0.00000066615 * math.cos(1.85382631980 + 846.3266522347 * self.t)
Y0 += 0.00000056220 * math.cos(6.09466556848 + 178.5455790391 * self.t)
Y0 += 0.00000067883 * math.cos(2.31467094623 + 224.5886131854 * self.t)
Y0 += 0.00000057761 * math.cos(3.59414048269 + 145.35359649321 * self.t)
Y0 += 0.00000053973 * math.cos(4.68325129609 + 107.2205608554 * self.t)
Y0 += 0.00000057588 * math.cos(0.13600413206 + 25.3590451821 * self.t)
Y0 += 0.00000049026 * math.cos(5.99075269953 + 19.2543980101 * self.t)
Y0 += 0.00000063036 * math.cos(5.86840206029 + 256.296123023 * self.t)
Y0 += 0.00000045304 * math.cos(5.57731819351 + 4.1759707466 * self.t)
Y0 += 0.00000045669 * math.cos(0.60467903265 + 117.6118698135 * self.t)
Y0 += 0.00000052821 * math.cos(5.35013106251 + 289.97574053589 * self.t)
Y0 += 0.00000044016 * math.cos(0.68418990599 + 32.7477788288 * self.t)
Y0 += 0.00000042933 * math.cos(1.50265323283 + 28.98238190449 * self.t)
Y0 += 0.00000038369 * math.cos(5.07841615051 + 39.6006933987 * self.t)
Y0 += 0.00000038805 * math.cos(2.55324300089 + 103.3365917021 * self.t)
Y0 += 0.00000037679 * math.cos(4.97176992254 + 9.3174100721 * self.t)
Y0 += 0.00000040292 * math.cos(1.32694372497 + 111.18634401329 * self.t)
Y0 += 0.00000050011 * math.cos(4.62887079290 + 221.61966776881 * self.t)
Y0 += 0.00000037056 * math.cos(3.05929116522 + 8.32057233081 * self.t)
Y0 += 0.00000036562 * math.cos(1.75628268654 + 448.98829064149 * self.t)
Y0 += 0.00000044628 * math.cos(5.39841763538 + 525.2543619171 * self.t)
Y0 += 0.00000038213 * math.cos(4.99269276748 + 75.54668091261 * self.t)
Y0 += 0.00000045963 * math.cos(2.49324091181 + 183.486632131 * self.t)
Y0 += 0.00000048222 * math.cos(4.38408318526 + 364.7573391032 * self.t)
Y0 += 0.00000038164 * math.cos(3.66287516322 + 44.00592741381 * self.t)
Y0 += 0.00000047779 * math.cos(4.62193118070 + 3340.8562441833 * self.t)
Y0 += 0.00000042228 * math.cos(4.07611308238 + 77.0311536209 * self.t)
Y0 += 0.00000035247 * math.cos(4.92005743728 + 34.7535163989 * self.t)
Y0 += 0.00000046804 * math.cos(5.53981795511 + 33.6964324603 * self.t)
Y0 += 0.00000034352 * math.cos(5.79527968049 + 33.71098667531 * self.t)
Y0 += 0.00000034949 * math.cos(3.58463727178 + 3.37951923889 * self.t)
Y0 += 0.00000036030 * math.cos(0.60196271868 + 71.09326278771 * self.t)
Y0 += 0.00000038112 * math.cos(0.94232057009 + 45.9659730016 * self.t)
Y0 += 0.00000033119 * math.cos(3.70714424363 + 7.3573644843 * self.t)
Y0 += 0.00000032049 * math.cos(3.04761071508 + 34.44469985821 * self.t)
Y0 += 0.00000031910 * math.cos(0.20811343013 + 81.61769818981 * self.t)
Y0 += 0.00000038697 * math.cos(1.09830424446 + 184.97110483931 * self.t)
Y0 += 0.00000041486 * math.cos(4.15630010756 + 310.4707937708 * self.t)
Y0 += 0.00000038631 * math.cos(0.74636164144 + 50.9070260935 * self.t)
Y0 += 0.00000042711 * math.cos(0.62152472293 + 1021.49271203491 * self.t)
Y0 += 0.00000032006 * math.cos(5.68829457469 + 42.00018984371 * self.t)
Y0 += 0.00000038436 * math.cos(5.02591476913 + 5.92107588581 * self.t)
Y0 += 0.00000038880 * math.cos(1.72301566300 + 76.55807286891 * self.t)
Y0 += 0.00000041190 * math.cos(3.00922391966 + 563.87503252191 * self.t)
Y0 += 0.00000029786 * math.cos(2.57644898724 + 77.5067265004 * self.t)
Y0 += 0.00000040604 * math.cos(6.04591617823 + 292.9446859525 * self.t)
Y0 += 0.00000035275 * math.cos(3.24596926614 + 304.84171947829 * self.t)
Y0 += 0.00000038242 * math.cos(1.23011716621 + 17.76992530181 * self.t)
Y0 += 0.00000034445 * math.cos(6.05203741506 + 319.06881347989 * self.t)
Y0 += 0.00000028725 * math.cos(0.80354919578 + 67.6366824041 * self.t)
Y0 += 0.00000032809 * math.cos(0.86662032393 + 91.54262404029 * self.t)
Y0 += 0.00000038880 * math.cos(5.27893548994 + 76.4617046493 * self.t)
Y0 += 0.00000030731 * math.cos(3.65388358465 + 67.60305250931 * self.t)
Y0 += 0.00000028459 * math.cos(4.82537806886 + 43.0427195673 * self.t)
Y0 += 0.00000035368 * math.cos(5.14016182775 + 313.43973918739 * self.t)
Y0 += 0.00000035703 * math.cos(4.78026134196 + 258.26823069831 * self.t)
Y0 += 0.00000032317 * math.cos(0.72991843715 + 78.9575693139 * self.t)
Y0 += 0.00000029243 * math.cos(5.01962947605 + 61.01077037031 * self.t)
Y0 += 0.00000026235 * math.cos(2.30979326374 + 137.2768416459 * self.t)
Y0 += 0.00000026519 * math.cos(4.63187110201 + 57.4993082325 * self.t)
Y0 += 0.00000024931 * math.cos(1.02449436120 + 42.997027585 * self.t)
Y0 += 0.00000027608 * math.cos(0.68443037331 + 103.7639804718 * self.t)
Y0 += 0.00000028680 * math.cos(6.22569747241 + 215.1941419686 * self.t)
Y0 += 0.00000025052 * math.cos(0.98956881727 + 350.08830211689 * self.t)
Y0 += 0.00000031386 * math.cos(2.53676810018 + 22.22334342671 * self.t)
Y0 += 0.00000027545 * math.cos(6.02026727313 + 100.6282787164 * self.t)
Y0 += 0.00000022617 * math.cos(1.89172143755 + 36.8441963032 * self.t)
Y0 += 0.00000024909 * math.cos(4.92089915310 + 24.36220744081 * self.t)
Y0 += 0.00000026216 * math.cos(3.37729185316 + 491.8017469403 * self.t)
Y0 += 0.00000028040 * math.cos(1.26215532584 + 11.55015017831 * self.t)
Y0 += 0.00000023047 * math.cos(2.67490790904 + 35.51978228931 * self.t)
Y0 += 0.00000027067 * math.cos(5.52626880418 + 326.62430346539 * self.t)
Y0 += 0.00000026192 * math.cos(0.78880180701 + 20.7388707184 * self.t)
Y0 += 0.00000023134 * math.cos(1.02405904726 + 68.4331339118 * self.t)
Y0 += 0.00000021423 * math.cos(5.59061648293 + 39.90950993941 * self.t)
Y0 += 0.00000025696 * math.cos(5.03652999676 + 186.4555775476 * self.t)
Y0 += 0.00000026985 * math.cos(1.96185307311 + 69.6087900794 * self.t)
Y0 += 0.00000023284 * math.cos(1.14508397457 + 79.43065006591 * self.t)
Y0 += 0.00000022894 * math.cos(5.33085965806 + 227.77000692311 * self.t)
Y0 += 0.00000022482 * math.cos(5.43588494929 + 39.8131417198 * self.t)
Y0 += 0.00000023480 * math.cos(5.96723336237 + 30.9881194746 * self.t)
Y0 += 0.00000020858 * math.cos(1.66497796416 + 41.2339239533 * self.t)
Y0 += 0.00000020327 * math.cos(5.86806874135 + 39.0312444271 * self.t)
Y0 += 0.00000020327 * math.cos(4.75570383217 + 37.72246181551 * self.t)
Y0 += 0.00000022639 * math.cos(1.78594954268 + 0.9800227939 * self.t)
Y0 += 0.00000022639 * math.cos(4.92754219627 + 1.46765776091 * self.t)
Y0 += 0.00000019139 * math.cos(1.60585998738 + 205.9417309537 * self.t)
Y0 += 0.00000019118 * math.cos(0.05485235310 + 2119.00767786191 * self.t)
Y0 += 0.00000025698 * math.cos(4.54722652155 + 401.4059020327 * self.t)
Y0 += 0.00000021582 * math.cos(5.86612346662 + 81.13006322279 * self.t)
Y0 += 0.00000025509 * math.cos(6.21909191790 + 329.593248882 * self.t)
Y0 += 0.00000024296 * math.cos(3.68761645751 + 62.0076081116 * self.t)
Y0 += 0.00000023969 * math.cos(2.45967218561 + 135.3047339706 * self.t)
Y0 += 0.00000020599 * math.cos(6.09025723810 + 491.3141119733 * self.t)
Y0 += 0.00000016829 * math.cos(4.06509805545 + 3.1645787903 * self.t)
Y0 += 0.00000020030 * math.cos(2.45066995549 + 217.4750661846 * self.t)
Y0 += 0.00000020377 * math.cos(5.60617244490 + 209.6107596584 * self.t)
Y0 += 0.00000017251 * math.cos(1.00239992257 + 350.5759370839 * self.t)
Y0 += 0.00000019625 * math.cos(1.41143867859 + 129.6756596781 * self.t)
Y0 += 0.00000022707 * math.cos(0.97867191772 + 1436.2969352491 * self.t)
Y0 += 0.00000017142 * math.cos(4.71740830608 + 29.4700168715 * self.t)
Y0 += 0.00000016188 * math.cos(3.33781568208 + 39.00999256771 * self.t)
Y0 += 0.00000016188 * math.cos(1.00277158426 + 37.7437136749 * self.t)
Y0 += 0.00000020858 * math.cos(3.10425391408 + 58.9837809408 * self.t)
Y0 += 0.00000015747 * math.cos(0.31821188942 + 154.260432743 * self.t)
Y0 += 0.00000019714 * math.cos(5.04477015525 + 294.91679362781 * self.t)
Y0 += 0.00000019078 * math.cos(1.16675280621 + 202.4972126576 * self.t)
Y0 += 0.00000021530 * math.cos(4.95075882360 + 114.1552894299 * self.t)
Y0 += 0.00000019068 * math.cos(3.39813326972 + 138.2736793872 * self.t)
Y0 += 0.00000018723 * math.cos(4.64325038338 + 323.74923414091 * self.t)
Y0 += 0.00000018916 * math.cos(3.89922448206 + 40.3825906914 * self.t)
Y0 += 0.00000015843 * math.cos(4.98899291519 + 72.577735496 * self.t)
Y0 += 0.00000020695 * math.cos(3.75000782446 + 86.07111631471 * self.t)
Y0 += 0.00000015895 * math.cos(4.16120885988 + 736.1203310153 * self.t)
Y0 += 0.00000014983 * math.cos(0.56469438588 + 743.23387801611 * self.t)
Y0 += 0.00000014928 * math.cos(5.49703861671 + 34.23225153711 * self.t)
Y0 += 0.00000015461 * math.cos(4.47518787654 + 20.850745303 * self.t)
Y0 += 0.00000016206 * math.cos(4.48895168117 + 138.76131435421 * self.t)
Y0 += 0.00000015978 * math.cos(5.56972981392 + 515.70768857651 * self.t)
Y0 += 0.00000014173 * math.cos(1.42508198977 + 99.1438060081 * self.t)
Y0 += 0.00000018749 * math.cos(1.80466304752 + 54.5303628159 * self.t)
Y0 += 0.00000013971 * math.cos(3.54176522468 + 76.77052119001 * self.t)
Y0 += 0.00000013971 * math.cos(3.46018552739 + 76.2492563282 * self.t)
Y0 += 0.00000014035 * math.cos(6.02847994013 + 235.68919520349 * self.t)
Y0 += 0.00000018894 * math.cos(3.02786191873 + 31.4757544416 * self.t)
Y0 += 0.00000014967 * math.cos(5.68342907224 + 52.3914988018 * self.t)
Y0 += 0.00000017392 * math.cos(0.12268817693 + 74.0622082043 * self.t)
Y0 += 0.00000014788 * math.cos(3.43864596335 + 56.01483552421 * self.t)
Y0 += 0.00000015758 * math.cos(1.26184897401 + 208.8624922605 * self.t)
Y0 += 0.00000012911 * math.cos(5.12673395733 + 42.5214547055 * self.t)
Y0 += 0.00000014356 * math.cos(0.18539168671 + 251.8427048981 * self.t)
Y0 += 0.00000016266 * math.cos(3.39270678896 + 853.4401992355 * self.t)
Y0 += 0.00000015513 * math.cos(2.59603540214 + 59.038662695 * self.t)
Y0 += 0.00000012783 * math.cos(0.77187700977 + 107.52937739611 * self.t)
Y0 += 0.00000016075 * math.cos(0.02096626523 + 366.24181181149 * self.t)
Y0 += 0.00000014277 * math.cos(3.31408666848 + 19.36627259471 * self.t)
Y0 += 0.00000014742 * math.cos(6.26354356543 + 82.4477795923 * self.t)
Y0 += 0.00000015111 * math.cos(5.70708654477 + 363.27286639489 * self.t)
Y0 += 0.00000014981 * math.cos(1.17119164980 + 82.6145359311 * self.t)
Y0 += 0.00000014840 * math.cos(5.34075197148 + 44.0541115236 * self.t)
Y0 += 0.00000015592 * math.cos(5.74434423333 + 8.6293888715 * self.t)
Y0 += 0.00000014568 * math.cos(0.45025790013 + 73.80157577341 * self.t)
Y0 += 0.00000012251 * math.cos(5.90063123167 + 47.28368937111 * self.t)
Y0 += 0.00000011447 * math.cos(5.62613164770 + 175.40987728371 * self.t)
Y0 += 0.00000013900 * math.cos(0.93353054847 + 700.4204217173 * self.t)
Y0 += 0.00000015583 * math.cos(5.46046493452 + 837.4534458797 * self.t)
Y0 += 0.00000012109 * math.cos(0.53062884942 + 33.0084112597 * self.t)
Y0 += 0.00000012379 * math.cos(0.87778018320 + 140.4125434013 * self.t)
Y0 += 0.00000011481 * math.cos(3.65591005670 + 39.2069345238 * self.t)
Y0 += 0.00000011481 * math.cos(0.68467720964 + 37.54677171881 * self.t)
Y0 += 0.00000011452 * math.cos(5.92350892067 + 529.4135177163 * self.t)
Y0 += 0.00000010981 * math.cos(1.58931744102 + 63.49208081989 * self.t)
Y0 += 0.00000012137 * math.cos(0.75938098769 + 42.3090063844 * self.t)
Y0 += 0.00000013771 * math.cos(2.92318261793 + 76.62176334371 * self.t)
Y0 += 0.00000011036 * math.cos(1.59378256377 + 530.45604743991 * self.t)
Y0 += 0.00000011537 * math.cos(2.72370023352 + 199.3158189199 * self.t)
Y0 += 0.00000011189 * math.cos(1.67388131435 + 80.1332254815 * self.t)
Y0 += 0.00000012835 * math.cos(2.83910944143 + 38.85242600079 * self.t)
Y0 += 0.00000012879 * math.cos(0.03161787960 + 5.69407334969 * self.t)
Y0 += 0.00000013663 * math.cos(4.69897705757 + 438.0544649622 * self.t)
Y0 += 0.00000010132 * math.cos(2.80479631986 + 187.9400502559 * self.t)
Y0 += 0.00000012619 * math.cos(3.09097380707 + 65.2035560643 * self.t)
Y0 += 0.00000010088 * math.cos(1.41143864412 + 26.58288545949 * self.t)
Y0 += 0.00000011959 * math.cos(1.19714206196 + 64.7159210973 * self.t)
Y0 += 0.00000011578 * math.cos(5.81790016857 + 275.3067035496 * self.t)
Y0 += 0.00000012795 * math.cos(1.66756565053 + 17.8817998864 * self.t)
Y0 += 0.00000013771 * math.cos(4.07876849292 + 76.3980141745 * self.t)
Y0 += 0.00000010044 * math.cos(1.67224715151 + 147.83490694279 * self.t)
Y0 += 0.00000013632 * math.cos(1.29603813384 + 45.277951801 * self.t)
Y0 += 0.00000011660 * math.cos(4.22880871720 + 143.9027536797 * self.t)
Y0 += 0.00000009938 * math.cos(5.79050109000 + 6.86972951729 * self.t)
Y0 += 0.00000009719 * math.cos(4.48706829937 + 956.53297345411 * self.t)
Y0 += 0.00000011441 * math.cos(5.32553485636 + 533.8669358412 * self.t)
Y0 += 0.00000010240 * math.cos(1.34767099242 + 80.7026744531 * self.t)
Y0 += 0.00000010031 * math.cos(3.80995841826 + 43.74529498291 * self.t)
Y0 += 0.00000010063 * math.cos(1.05825122331 + 0.27744737829 * self.t)
Y0 += 0.00000011428 * math.cos(2.19933512981 + 526.00262931501 * self.t)
Y0 += 0.00000009279 * math.cos(1.45482205447 + 79.6455905145 * self.t)
Y0 += 0.00000010172 * math.cos(0.89461094062 + 568.0678182159 * self.t)
Y0 += 0.00000009198 * math.cos(0.36520539350 + 112.6708167216 * self.t)
Y0 += 0.00000009831 * math.cos(4.06082180622 + 20.9056270572 * self.t)
Y0 += 0.00000009830 * math.cos(1.93960888370 + 544.1618765797 * self.t)
Y0 += 0.00000008646 * math.cos(6.06265529598 + 30.7756711535 * self.t)
Y0 += 0.00000009315 * math.cos(1.72769398395 + 65.63094483399 * self.t)
Y0 += 0.00000009201 * math.cos(1.66299093770 + 184.48346987229 * self.t)
Y0 += 0.00000008674 * math.cos(3.58250353029 + 624.1543504417 * self.t)
Y0 += 0.00000010739 * math.cos(5.20958133978 + 331.56535655731 * self.t)
Y0 += 0.00000009612 * math.cos(3.81549627985 + 182.00215942271 * self.t)
Y0 += 0.00000008664 * math.cos(4.05357381243 + 1479.11039154791 * self.t)
Y0 += 0.00000008092 * math.cos(4.08843223898 + 6.8360996225 * self.t)
Y0 += 0.00000010092 * math.cos(0.00357719036 + 419.2408263917 * self.t)
Y0 += 0.00000010233 * math.cos(0.16992310980 + 402.89037474099 * self.t)
Y0 += 0.00000008502 * math.cos(3.60646753260 + 17.39416491939 * self.t)
Y0 += 0.00000010189 * math.cos(1.01906004060 + 21.7020785649 * self.t)
Y0 += 0.00000009829 * math.cos(3.66564448678 + 121.2352065359 * self.t)
Y0 += 0.00000008406 * math.cos(4.04270651029 + 376.9150050599 * self.t)
Y0 += 0.00000008060 * math.cos(4.05224638436 + 415.7963080956 * self.t)
Y0 += 0.00000009455 * math.cos(1.63876624122 + 167.80869531589 * self.t)
Y0 += 0.00000007941 * math.cos(6.14526289331 + 526.7533888404 * self.t)
Y0 += 0.00000007870 * math.cos(1.33260101318 + 533.1161763158 * self.t)
Y0 += 0.00000007695 * math.cos(2.49810660877 + 906.60597015449 * self.t)
Y0 += 0.00000007862 * math.cos(5.62722995177 + 1265.81129610991 * self.t)
Y0 += 0.00000008062 * math.cos(5.84124471296 + 105.7360881471 * self.t)
Y0 += 0.00000008904 * math.cos(5.87904582316 + 399.9214293244 * self.t)
Y0 += 0.00000008050 * math.cos(4.85961454632 + 143.8691237849 * self.t)
Y0 += 0.00000009102 * math.cos(3.20438608836 + 348.17644063891 * self.t)
Y0 += 0.00000007137 * math.cos(5.97349520503 + 117.5636857037 * self.t)
Y0 += 0.00000007076 * math.cos(4.77037120491 + 26.84351789039 * self.t)
Y0 += 0.00000008418 * math.cos(6.19754313245 + 77.73372903651 * self.t)
Y0 += 0.00000008257 * math.cos(6.01515603184 + 117.77862615229 * self.t)
Y0 += 0.00000007868 * math.cos(0.36467826737 + 288.4912678276 * self.t)
Y0 += 0.00000008093 * math.cos(5.12697881207 + 1692.40948698591 * self.t)
Y0 += 0.00000006910 * math.cos(5.16028730720 + 216.72430665921 * self.t)
Y0 += 0.00000007092 * math.cos(1.58416634960 + 452.65981147369 * self.t)
Y0 += 0.00000007060 * math.cos(3.50187723218 + 453.7023411973 * self.t)
Y0 += 0.00000008233 * math.cos(5.07959772857 + 480.00777927849 * self.t)
Y0 += 0.00000006772 * math.cos(2.89170457209 + 210.36151918381 * self.t)
Y0 += 0.00000007025 * math.cos(6.13907268455 + 55.9029609396 * self.t)
Y0 += 0.00000008356 * math.cos(3.67079730328 + 95.7354097343 * self.t)
Y0 += 0.00000007404 * math.cos(5.71532443096 + 75.2860484817 * self.t)
Y0 += 0.00000006839 * math.cos(2.57023077532 + 41.5125548767 * self.t)
Y0 += 0.00000007909 * math.cos(0.07288588503 + 36.63174798211 * self.t)
Y0 += 0.00000007909 * math.cos(1.12610872772 + 40.12195826051 * self.t)
Y0 += 0.00000006362 * math.cos(4.97586429633 + 29.99128173331 * self.t)
Y0 += 0.00000006712 * math.cos(2.41218446093 + 133.82026126229 * self.t)
Y0 += 0.00000007571 * math.cos(1.24658605384 + 23.707816135 * self.t)
Y0 += 0.00000006677 * math.cos(4.81403056382 + 1.20702533 * self.t)
Y0 += 0.00000007600 * math.cos(1.64374414108 + 494.2348732801 * self.t)
Y0 += 0.00000008009 * math.cos(1.96165940869 + 170.72945662269 * self.t)
Y0 += 0.00000007584 * math.cos(1.33750538789 + 119.2630988606 * self.t)
Y0 += 0.00000006599 * math.cos(0.68440943828 + 32.226513967 * self.t)
Y0 += 0.00000006085 * math.cos(3.39985070945 + 322.00412900171 * self.t)
Y0 += 0.00000005953 * math.cos(0.92774911672 + 52214.1831362697 * self.t)
Y0 += 0.00000007827 * math.cos(4.85672910517 + 474.7030278917 * self.t)
Y0 += 0.00000007907 * math.cos(6.03373097658 + 485.63685357099 * self.t)
Y0 += 0.00000007372 * math.cos(3.31633214824 + 55.05162767771 * self.t)
Y0 += 0.00000006966 * math.cos(4.03472609774 + 647.25465079831 * self.t)
Y0 += 0.00000006266 * math.cos(1.06894881555 + 177.0611063308 * self.t)
Y0 += 0.00000005900 * math.cos(0.21363873876 + 52061.16335875149 * self.t)
Y0 += 0.00000006221 * math.cos(0.78444326027 + 602.00806815971 * self.t)
Y0 += 0.00000005552 * math.cos(4.30656362928 + 223.1041404771 * self.t)
Y0 += 0.00000005976 * math.cos(3.40178743225 + 10.8018827804 * self.t)
Y0 += 0.00000007600 * math.cos(0.62565658069 + 488.6057989876 * self.t)
Y0 += 0.00000006831 * math.cos(4.75854396498 + 1582.2031657665 * self.t)
Y0 += 0.00000005654 * math.cos(1.46952482126 + 12604.5285531041 * self.t)
Y0 += 0.00000005798 * math.cos(2.70754675899 + 27.4979091962 * self.t)
Y0 += 0.00000007216 * math.cos(4.89431192173 + 739.0410923221 * self.t)
Y0 += 0.00000006579 * math.cos(2.37730114095 + 2.69149803831 * self.t)
Y0 += 0.00000005758 * math.cos(1.25264555408 + 30.0394658431 * self.t)
Y0 += 0.00000005270 * math.cos(5.03822712313 + 6166.94845288619 * self.t)
Y0 += 0.00000007398 * math.cos(2.15412967054 + 709.721016842 * self.t)
Y0 += 0.00000005679 * math.cos(4.34696450423 + 17.22740858061 * self.t)
Y0 += 0.00000005205 * math.cos(4.18097270804 + 426.3543733925 * self.t)
Y0 += 0.00000005146 * math.cos(5.52411562781 + 46.7624245093 * self.t)
Y0 += 0.00000005694 * math.cos(4.51992731423 + 168.98435148349 * self.t)
Y0 += 0.00000006627 * math.cos(1.36429825841 + 221.13203280179 * self.t)
Y0 += 0.00000005443 * math.cos(2.77787969707 + 525.7419968841 * self.t)
Y0 += 0.00000006475 * math.cos(0.95284661304 + 591.07424248041 * self.t)
Y0 += 0.00000004984 * math.cos(0.17849511014 + 10097.15814910579 * self.t)
Y0 += 0.00000005318 * math.cos(3.65617684169 + 44.52719227561 * self.t)
Y0 += 0.00000006699 * math.cos(1.37968332714 + 2157.1407134997 * self.t)
Y0 += 0.00000006443 * math.cos(4.07988524250 + 675.0445615878 * self.t)
Y0 += 0.00000005078 * math.cos(2.53592755854 + 101.62511645769 * self.t)
Y0 += 0.00000005394 * math.cos(5.60187660250 + 368.21391948681 * self.t)
Y0 += 0.00000005072 * math.cos(4.09677163290 + 272.33775813299 * self.t)
Y0 += 0.00000005208 * math.cos(2.96070554414 + 277.2788112249 * self.t)
Y0 += 0.00000005332 * math.cos(2.85701594895 + 280.9357778421 * self.t)
Y0 += 0.00000005989 * math.cos(1.18032513011 + 93.0270967486 * self.t)
Y0 += 0.00000006329 * math.cos(2.06650240521 + 18.87863762769 * self.t)
Y0 += 0.00000005551 * math.cos(0.99966130596 + 57.3874336479 * self.t)
Y0 += 0.00000006471 * math.cos(4.75702433578 + 68.1243173711 * self.t)
Y0 += 0.00000004708 * math.cos(3.81000728156 + 95.68722562449 * self.t)
Y0 += 0.00000005891 * math.cos(4.39361748912 + 381.5954257209 * self.t)
Y0 += 0.00000004717 * math.cos(5.88762112195 + 104.2852453336 * self.t)
Y0 += 0.00000005675 * math.cos(0.14149668499 + 1165.6392831981 * self.t)
Y0 += 0.00000005888 * math.cos(2.00299136957 + 42.34263627919 * self.t)
Y0 += 0.00000005587 * math.cos(2.52090459839 + 459.6066021357 * self.t)
Y0 += 0.00000005456 * math.cos(3.07944464122 + 75.50098893029 * self.t)
Y0 += 0.00000005940 * math.cos(4.70996040917 + 6318.4837576961 * self.t)
Y0 += 0.00000005207 * math.cos(6.12213701959 + 436.5699922539 * self.t)
Y0 += 0.00000006160 * math.cos(3.18966815531 + 749.82616015511 * self.t)
Y0 += 0.00000006137 * math.cos(3.02268593798 + 713.17759722561 * self.t)
Y0 += 0.00000004547 * math.cos(3.96298179960 + 32.47259218289 * self.t)
Y0 += 0.00000005246 * math.cos(0.26649341993 + 109.9625037359 * self.t)
Y0 += 0.00000005244 * math.cos(0.76595138199 + 73.5891274523 * self.t)
Y0 += 0.00000005572 * math.cos(4.54958395511 + 102.11275142471 * self.t)
Y0 += 0.00000005638 * math.cos(6.13292790226 + 10248.6934539157 * self.t)
Y0 += 0.00000004513 * math.cos(0.05769066183 + 1272.9248431107 * self.t)
Y0 += 0.00000004340 * math.cos(3.93529499489 + 384.02855206069 * self.t)
Y0 += 0.00000004263 * math.cos(5.81710901839 + 1577.52274510549 * self.t)
Y0 += 0.00000005964 * math.cos(3.35563503899 + 786.47472308461 * self.t)
Y0 += 0.00000004962 * math.cos(1.38600480216 + 257.78059573129 * self.t)
Y0 += 0.00000005327 * math.cos(4.13135597763 + 107.74182571721 * self.t)
Y0 += 0.00000005572 * math.cos(5.58677005833 + 291.2934569054 * self.t)
Y0 += 0.00000004336 * math.cos(1.08874295813 + 53.40958840249 * self.t)
Y0 += 0.00000004427 * math.cos(1.43077618159 + 189.42452296421 * self.t)
Y0 += 0.00000004157 * math.cos(5.03727532307 + 29.5036467663 * self.t)
Y0 += 0.00000004646 * math.cos(4.44853801893 + 13285.93981804009 * self.t)
Y0 += 0.00000005507 * math.cos(2.70385106164 + 178.11819026941 * self.t)
Y0 += 0.00000005348 * math.cos(6.13707191030 + 24.88347230261 * self.t)
Y0 += 0.00000005339 * math.cos(5.48920294964 + 314.6635794648 * self.t)
Y0 += 0.00000004678 * math.cos(6.00688425085 + 1474.4299708869 * self.t)
Y0 += 0.00000004090 * math.cos(4.92713296866 + 765.3801602981 * self.t)
Y0 += 0.00000005008 * math.cos(4.28621887979 + 352.06040979221 * self.t)
Y0 += 0.00000005562 * math.cos(5.12126233744 + 6248.1555772537 * self.t)
Y0 += 0.00000004983 * math.cos(1.59156517574 + 1055.43296197871 * self.t)
Y0 += 0.00000004566 * math.cos(0.54461731254 + 325.1398307571 * self.t)
Y0 += 0.00000005327 * math.cos(0.54108371123 + 439.53893767049 * self.t)
Y0 += 0.00000005121 * math.cos(4.27746071897 + 711.6931245173 * self.t)
Y0 += 0.00000004181 * math.cos(2.68829223641 + 6606.1994373488 * self.t)
Y0 += 0.00000004293 * math.cos(3.08794166207 + 46.71424039951 * self.t)
Y0 += 0.00000005532 * math.cos(2.10559407460 + 320.03202132639 * self.t)
Y0 += 0.00000004492 * math.cos(4.81151725335 + 52177.53457334019 * self.t)
Y0 += 0.00000004312 * math.cos(6.10122311855 + 22.8777347325 * self.t)
Y0 += 0.00000005332 * math.cos(0.25990559894 + 10178.3652734733 * self.t)
Y0 += 0.00000004593 * math.cos(4.86059649000 + 1025.6854977289 * self.t)
Y0 += 0.00000005439 * math.cos(3.52367947540 + 823.12328601411 * self.t)
Y0 += 0.00000003870 * math.cos(2.70915745235 + 1596.43025976811 * self.t)
Y0 += 0.00000003892 * math.cos(0.54485159298 + 226.07308589371 * self.t)
Y0 += 0.00000004891 * math.cos(4.37893659385 + 8.1417539045 * self.t)
Y0 += 0.00000004689 * math.cos(5.09142557332 + 276.79117625789 * self.t)<|fim▁hole|> Y0 += 0.00000004268 * math.cos(1.02189794794 + 374.15181032 * self.t)
Y0 += 0.00000003828 * math.cos(3.85156237339 + 2138.2331988371 * self.t)
Y0 += 0.00000004592 * math.cos(2.30447944615 + 1376.0176173293 * self.t)
Y0 += 0.00000004629 * math.cos(5.68948058955 + 122.71967924421 * self.t)
Y0 += 0.00000003871 * math.cos(1.60468692916 + 531.4192552864 * self.t)
Y0 += 0.00000004995 * math.cos(5.03302660981 + 32.69959471901 * self.t)
Y0 += 0.00000004711 * math.cos(5.14987215661 + 52252.31617190749 * self.t)
Y0 += 0.00000003893 * math.cos(1.69554966790 + 116.294153444 * self.t)
Y0 += 0.00000004481 * math.cos(3.09400209140 + 53.0458901076 * self.t)
Y0 += 0.00000004136 * math.cos(1.02307294098 + 503.1080796351 * self.t)
Y0 += 0.00000004508 * math.cos(2.81495366139 + 562.12992738271 * self.t)
Y0 += 0.00000005025 * math.cos(1.96944866339 + 283.38345839689 * self.t)
Y0 += 0.00000004789 * math.cos(1.11612617111 + 627.7228054099 * self.t)
Y0 += 0.00000004021 * math.cos(1.71534059601 + 6603.23049193219 * self.t)
Y0 += 0.00000005163 * math.cos(0.06221778581 + 25519.83532335829 * self.t)
Y0 += 0.00000004150 * math.cos(2.29239909221 + 27.443027442 * self.t)
Y0 += 0.00000003623 * math.cos(0.72377687032 + 1665.5827840429 * self.t)
Y0 += 0.00000004634 * math.cos(3.36220803589 + 3227.45397501119 * self.t)
Y0 += 0.00000004060 * math.cos(4.64578985602 + 304.4780211834 * self.t)
Y0 += 0.00000003862 * math.cos(5.22051626712 + 74.504151189 * self.t)
Y0 += 0.00000003561 * math.cos(3.35891592080 + 358.6526919312 * self.t)
Y0 += 0.00000004557 * math.cos(1.56282166634 + 25974.74468988559 * self.t)
Y0 += 0.00000004264 * math.cos(3.13963744879 + 634.93941827469 * self.t)
Y0 += 0.00000004482 * math.cos(0.13471172639 + 342.61105682121 * self.t)
Y0 += 0.00000003539 * math.cos(5.28146842802 + 119.7507338276 * self.t)
Y0 += 0.00000004304 * math.cos(5.35023544496 + 12567.8799901746 * self.t)
Y0 += 0.00000004138 * math.cos(5.60646772527 + 107.2541907502 * self.t)
Y0 += 0.00000004284 * math.cos(1.62500514182 + 294.42915866079 * self.t)
Y0 += 0.00000003723 * math.cos(0.87405503812 + 987.325459555 * self.t)
Y0 += 0.00000003723 * math.cos(4.01564769171 + 987.813094522 * self.t)
Y0 += 0.00000004606 * math.cos(0.78314632413 + 14.42521950279 * self.t)
Y0 += 0.00000004236 * math.cos(1.51001695106 + 155.9116617901 * self.t)
Y0 += 0.00000004458 * math.cos(1.07510939804 + 395.8225197225 * self.t)
Y0 += 0.00000004798 * math.cos(3.66850235979 + 530.195415009 * self.t)
Y0 += 0.00000003640 * math.cos(3.79814548576 + 2564.8313897131 * self.t)
Y0 += 0.00000003563 * math.cos(0.66220700888 + 12451.50877558589 * self.t)
Y0 += 0.00000003443 * math.cos(3.70889407011 + 245.2504227591 * self.t)
Y0 += 0.00000003429 * math.cos(3.16343780315 + 530.0466571627 * self.t)
Y0 += 0.00000003872 * math.cos(5.66297097129 + 308.98632106249 * self.t)
Y0 += 0.00000003406 * math.cos(4.31900232100 + 529.82290799351 * self.t)
Y0 += 0.00000004348 * math.cos(3.09499292675 + 20311.92816802509 * self.t)
Y0 += 0.00000004589 * math.cos(3.67073392808 + 181.08713568601 * self.t)
Y0 += 0.00000003854 * math.cos(4.35430550499 + 12564.91104475801 * self.t)
Y0 += 0.00000003789 * math.cos(5.86431526205 + 3101.6359018085 * self.t)
Y0 += 0.00000003783 * math.cos(1.84016316657 + 1614.17130803499 * self.t)
Y0 += 0.00000003904 * math.cos(1.57500723101 + 369.8014580591 * self.t)
Y0 += 0.00000003765 * math.cos(3.13810202386 + 1025.94613015981 * self.t)
Y0 += 0.00000004231 * math.cos(3.78834664840 + 31.52393855141 * self.t)
Y0 += 0.00000004303 * math.cos(3.40265517593 + 396.785727569 * self.t)
Y0 += 0.00000004085 * math.cos(0.23841437878 + 14.47091148511 * self.t)
Y0 += 0.00000004085 * math.cos(3.38000703237 + 13.9832765181 * self.t)
Y0 += 0.00000003346 * math.cos(0.20283168925 + 20351.54567637119 * self.t)
Y0 += 0.00000004021 * math.cos(4.51457854549 + 748.3416874468 * self.t)
Y0 += 0.00000003753 * math.cos(2.74283876055 + 524.99372948619 * self.t)
Y0 += 0.00000003935 * math.cos(2.81201754924 + 1617.14025345159 * self.t)
Y0 += 0.00000004432 * math.cos(5.02857999493 + 511.3515908212 * self.t)
Y0 += 0.00000004170 * math.cos(2.85784811733 + 274.87931477991 * self.t)
Y0 += 0.00000003317 * math.cos(3.36427187559 + 266.70868384049 * self.t)
Y0 += 0.00000004545 * math.cos(2.99451528962 + 244.5624015585 * self.t)
Y0 += 0.00000003589 * math.cos(6.26623778468 + 59.526297662 * self.t)
Y0 += 0.00000003464 * math.cos(1.94815791367 + 102.27950776349 * self.t)
Y0 += 0.00000004526 * math.cos(2.98322850842 + 525.7901809939 * self.t)
Y0 += 0.00000004603 * math.cos(2.83181132811 + 26088.1469590577 * self.t)
Y0 += 0.00000004021 * math.cos(3.81502221170 + 52174.56562792359 * self.t)
Y0 += 0.00000003276 * math.cos(3.52742657818 + 1306.3774580875 * self.t)
Y0 += 0.00000003214 * math.cos(5.51315121035 + 20348.57673095459 * self.t)
Y0 += 0.00000003706 * math.cos(3.68281338464 + 27.07052042651 * self.t)
Y0 += 0.00000003759 * math.cos(5.89324799399 + 164.83974989929 * self.t)
Y0 += 0.00000003184 * math.cos(0.44574677170 + 538.0115374254 * self.t)
Y0 += 0.00000004430 * math.cos(3.80837870078 + 529.6741501472 * self.t)
Y0 += 0.00000004064 * math.cos(2.60402368915 + 6130.2998899567 * self.t)
Y0 += 0.00000003918 * math.cos(5.77655218093 + 375.43053235159 * self.t)
Y0 += 0.00000004058 * math.cos(3.56233663362 + 433.4342904985 * self.t)
Y0 += 0.00000003919 * math.cos(1.93774102166 + 1092.8177302186 * self.t)
Y0 += 0.00000003919 * math.cos(5.07933367525 + 1093.3053651856 * self.t)
Y0 += 0.00000003175 * math.cos(2.71648311000 + 241.3664536058 * self.t)
Y0 += 0.00000003135 * math.cos(1.09798751738 + 127.22797912329 * self.t)
Y0 += 0.00000003834 * math.cos(3.42021462454 + 14.3133449182 * self.t)
Y0 += 0.00000004022 * math.cos(0.15000192924 + 1477.8383671607 * self.t)
Y0 += 0.00000003221 * math.cos(2.66340709341 + 78.1611178062 * self.t)
Y0 += 0.00000003426 * math.cos(4.77405099085 + 519.8522901607 * self.t)
Y0 += 0.00000004369 * math.cos(2.32053270413 + 746.3695797715 * self.t)
Y0 += 0.00000003160 * math.cos(3.58900877772 + 664.99569906519 * self.t)
Y0 += 0.00000004060 * math.cos(4.49008083850 + 51.87023394 * self.t)
Y0 += 0.00000003107 * math.cos(3.81160836398 + 28.9275001503 * self.t)
Y0 += 0.00000003259 * math.cos(0.91022076156 + 657.8821520644 * self.t)
Y0 += 0.00000003428 * math.cos(2.81213415208 + 2351.5322942751 * self.t)
Y0 += 0.00000003235 * math.cos(0.07612839981 + 406.3469551246 * self.t)
Y0 += 0.00000003161 * math.cos(0.98519827646 + 982.8720414301 * self.t)
Y0 += 0.00000004351 * math.cos(2.61742468676 + 20388.19423930069 * self.t)
Y0 += 0.00000003384 * math.cos(1.87729416709 + 660.851097481 * self.t)
Y0 += 0.00000003452 * math.cos(5.96738985165 + 326.1823604807 * self.t)
Y0 += 0.00000003298 * math.cos(1.72568702486 + 1403.84115801359 * self.t)
Y0 += 0.00000003278 * math.cos(5.26025413610 + 941.7700603757 * self.t)
Y0 += 0.00000003723 * math.cos(0.29723150363 + 451.9572360581 * self.t)
Y0 += 0.00000003173 * math.cos(0.75401885480 + 1400.87221259699 * self.t)
Y0 += 0.00000004113 * math.cos(3.44518846630 + 1049.31625271919 * self.t)
Y0 += 0.00000004012 * math.cos(0.58002417229 + 52.6039471229 * self.t)
Y0 += 0.00000004142 * math.cos(0.18543891861 + 978.6792557361 * self.t)
Y0 += 0.00000004295 * math.cos(2.94382365877 + 875.58648151749 * self.t)
Y0 += 0.00000003224 * math.cos(5.39074920150 + 459.1189671687 * self.t)
Y0 += 0.00000003151 * math.cos(2.11925788926 + 381.8560581518 * self.t)
Y0 += 0.00000003633 * math.cos(6.09798622690 + 256.78375799 * self.t)
Y0 += 0.00000004250 * math.cos(4.81834414256 + 528.71094230071 * self.t)
Y0 += 0.00000004186 * math.cos(3.66267284521 + 943.25453308399 * self.t)
Y0 += 0.00000003406 * math.cos(1.82206499429 + 170.46882419179 * self.t)
Y0 += 0.00000003231 * math.cos(6.18447276533 + 400.8209466961 * self.t)
Y0 += 0.00000003726 * math.cos(5.26557613435 + 1096.48675892331 * self.t)
Y0 += 0.00000003792 * math.cos(5.46702979448 + 111.9346114112 * self.t)
Y0 += 0.00000003651 * math.cos(6.14012974300 + 154.42718908179 * self.t)
Y0 += 0.00000003839 * math.cos(4.02729058795 + 10060.50958617629 * self.t)
Y0 += 0.00000003356 * math.cos(5.33785023580 + 1586.34776735071 * self.t)
Y0 += 0.00000003219 * math.cos(1.26547692662 + 213.7096692603 * self.t)
Y0 += 0.00000003671 * math.cos(3.08823320781 + 57.6023740965 * self.t)
Y0 += 0.00000004187 * math.cos(1.86321883254 + 2772.54460848389 * self.t)
Y0 += 0.00000002960 * math.cos(3.77221652347 + 2461.7386154945 * self.t)
Y0 += 0.00000003331 * math.cos(2.38361288630 + 10133.80671203529 * self.t)
Y0 += 0.00000003341 * math.cos(2.74911210318 + 243.7659500508 * self.t)
Y0 += 0.00000003466 * math.cos(0.02652921265 + 1150.92455422949 * self.t)
Y0 += 0.00000003296 * math.cos(5.06897390591 + 1653.78881638109 * self.t)
Y0 += 0.00000003014 * math.cos(3.47171849350 + 1477.3989163035 * self.t)
Y0 += 0.00000004118 * math.cos(1.26070911091 + 25596.5890296009 * self.t)
Y0 += 0.00000002951 * math.cos(3.47218747597 + 42.78208713641 * self.t)
Y0 += 0.00000002951 * math.cos(4.00999244396 + 33.9716191062 * self.t)
Y0 += 0.00000003830 * math.cos(3.02640541849 + 323.48860171 * self.t)
Y0 += 0.00000003313 * math.cos(3.21919687279 + 939.1099314998 * self.t)
Y0 += 0.00000003031 * math.cos(4.32205791511 + 156450.90896068608 * self.t)
Y0 += 0.00000003606 * math.cos(2.35740018537 + 1082.2596649217 * self.t)
Y0 += 0.00000002967 * math.cos(4.72619454182 + 6.3941566378 * self.t)
Y0 += 0.00000002995 * math.cos(5.12808890644 + 139.7099679857 * self.t)
Y0 += 0.00000003251 * math.cos(1.93107151339 + 709.29362807231 * self.t)
Y0 += 0.00000003480 * math.cos(2.18796105799 + 518.1408149163 * self.t)
Y0 += 0.00000003906 * math.cos(4.41951013162 + 1119.90506559249 * self.t)
Y0 += 0.00000003406 * math.cos(3.42602191152 + 148.79811478929 * self.t)
Y0 += 0.00000003359 * math.cos(0.17159576955 + 642.8494167832 * self.t)
Y0 += 0.00000003027 * math.cos(5.00980281133 + 184.0078969928 * self.t)
Y0 += 0.00000002918 * math.cos(0.68786396977 + 83.6234357599 * self.t)
Y0 += 0.00000003347 * math.cos(4.53587187847 + 217.68751450571 * self.t)
Y0 += 0.00000003277 * math.cos(1.84412902317 + 912.5438609877 * self.t)
Y0 += 0.00000003277 * math.cos(4.98572167676 + 913.03149595471 * self.t)
Y0 += 0.00000003196 * math.cos(4.27207353253 + 363.1061100561 * self.t)
Y0 += 0.00000002869 * math.cos(2.93254803921 + 285.35556607221 * self.t)
Y0 += 0.00000003158 * math.cos(5.89391855080 + 540.01727499551 * self.t)
Y0 += 0.00000002810 * math.cos(3.57723287116 + 1592.2856581839 * self.t)
Y0 += 0.00000003471 * math.cos(4.56081319778 + 144.39038864671 * self.t)
Y0 += 0.00000003159 * math.cos(5.71530971815 + 197.5561595657 * self.t)
Y0 += 0.00000003227 * math.cos(1.02602355265 + 6203.5970158157 * self.t)
Y0 += 0.00000003750 * math.cos(1.09900342443 + 303.35724676999 * self.t)
Y0 += 0.00000003848 * math.cos(4.95190461444 + 26048.04181574459 * self.t)
Y0 += 0.00000002741 * math.cos(0.13004673727 + 70.8326303568 * self.t)
Y0 += 0.00000002826 * math.cos(3.64821843137 + 460.2946233363 * self.t)
Y0 += 0.00000002748 * math.cos(5.69617268740 + 600.52359545141 * self.t)
Y0 += 0.00000003057 * math.cos(4.56550138397 + 23.81969071961 * self.t)
Y0 += 0.00000003057 * math.cos(6.05827118955 + 52.934015523 * self.t)
Y0 += 0.00000003446 * math.cos(1.96967013470 + 500.1391342185 * self.t)
Y0 += 0.00000002703 * math.cos(6.26272265860 + 908.0904428628 * self.t)
Y0 += 0.00000002817 * math.cos(1.69638906604 + 210.6221516147 * self.t)
Y0 += 0.00000002848 * math.cos(1.16888883373 + 450.4727633498 * self.t)
Y0 += 0.00000002724 * math.cos(5.64910484087 + 23.18655127321 * self.t)
Y0 += 0.00000002905 * math.cos(1.13800629851 + 149.3193796511 * self.t)
Y0 += 0.00000002848 * math.cos(1.48842245891 + 622.66987773339 * self.t)
Y0 += 0.00000002733 * math.cos(1.93636126616 + 262.72164882321 * self.t)
Y0 += 0.00000002863 * math.cos(2.26914213515 + 175.57663362249 * self.t)
Y0 += 0.00000002681 * math.cos(5.83048409789 + 25.1922888433 * self.t)
Y0 += 0.00000002822 * math.cos(0.00883588585 + 259.7527034066 * self.t)
Y0 += 0.00000003174 * math.cos(1.47302873031 + 347.1193567003 * self.t)
Y0 += 0.00000003271 * math.cos(2.97328046332 + 458.5977023069 * self.t)
Y0 += 0.00000002894 * math.cos(5.75207939107 + 71.82946809809 * self.t)
Y0 += 0.00000003490 * math.cos(1.28003658954 + 664.3713683394 * self.t)
Y0 += 0.00000003506 * math.cos(3.91611653269 + 771.3481117113 * self.t)
Y0 += 0.00000003326 * math.cos(0.55224065588 + 45.2297676912 * self.t)
Y0 += 0.00000002988 * math.cos(4.94563705230 + 299.37021175271 * self.t)
Y0 += 0.00000002916 * math.cos(5.17859920603 + 6642.8480002783 * self.t)
Y0 += 0.00000002916 * math.cos(5.17859920603 + 6643.3356352453 * self.t)
Y0 += 0.00000002630 * math.cos(5.83933407803 + 2751.79141717511 * self.t)
Y0 += 0.00000002903 * math.cos(5.88134941337 + 477.08701797169 * self.t)
Y0 += 0.00000002804 * math.cos(4.97695491059 + 6681.46867088311 * self.t)
Y0 += 0.00000002622 * math.cos(0.73099530901 + 521.8580277308 * self.t)
Y0 += 0.00000002606 * math.cos(1.44468831628 + 410.8552550037 * self.t)
Y0 += 0.00000003046 * math.cos(0.79307135358 + 959.45373476091 * self.t)
Y0 += 0.00000003127 * math.cos(1.47432830628 + 225.5518210319 * self.t)
Y0 += 0.00000002700 * math.cos(2.88388264285 + 963.6465204549 * self.t)
Y0 += 0.00000002778 * math.cos(3.22939757518 + 238.39750818919 * self.t)
Y0 += 0.00000003029 * math.cos(0.01392036536 + 473.2185551834 * self.t)
Y0 += 0.00000002671 * math.cos(3.02950363348 + 531.9405201482 * self.t)
Y0 += 0.00000002914 * math.cos(2.29089443923 + 554.31380496631 * self.t)
Y0 += 0.00000003087 * math.cos(1.37613019083 + 340.2664421304 * self.t)
Y0 += 0.00000003438 * math.cos(3.89546045811 + 6171.40187101109 * self.t)
Y0 += 0.00000002879 * math.cos(4.04729837696 + 218.6507223522 * self.t)
Y0 += 0.00000003140 * math.cos(3.44921752602 + 609.1216151605 * self.t)
Y0 += 0.00000003003 * math.cos(5.24831469226 + 464.97504399731 * self.t)
Y0 += 0.00000003257 * math.cos(6.23715182295 + 305.96249389171 * self.t)
Y0 += 0.00000003211 * math.cos(0.93594149210 + 416.532513406 * self.t)
Y0 += 0.00000003265 * math.cos(6.26189223545 + 24.7347144563 * self.t)
Y0 += 0.00000002644 * math.cos(5.73202797797 + 508.5941415757 * self.t)
Y0 += 0.00000002764 * math.cos(0.26986971158 + 410.59462257279 * self.t)
Y0 += 0.00000003428 * math.cos(0.99849665750 + 1012.6195056799 * self.t)
Y0 += 0.00000002614 * math.cos(2.50560328703 + 213.5910970313 * self.t)
Y0 += 0.00000003469 * math.cos(3.71563719744 + 24.14975911971 * self.t)
Y0 += 0.00000002606 * math.cos(5.52398994555 + 213.4947288117 * self.t)
Y0 += 0.00000003444 * math.cos(0.99352524535 + 891.57323487331 * self.t)
Y0 += 0.00000002540 * math.cos(5.89247404448 + 564.8718702632 * self.t)
Y0 += 0.00000002540 * math.cos(2.75088139089 + 565.35950523021 * self.t)
Y0 += 0.00000002754 * math.cos(4.26615188091 + 57.5541899867 * self.t)
Y0 += 0.00000002531 * math.cos(2.16100356086 + 800.5924346291 * self.t)
Y0 += 0.00000002557 * math.cos(2.24078889519 + 341.49028240779 * self.t)
Y0 += 0.00000002601 * math.cos(2.97805958626 + 261.2371761149 * self.t)
Y0 += 0.00000003027 * math.cos(1.77262933089 + 331.07772159029 * self.t)
Y0 += 0.00000002494 * math.cos(5.29381091116 + 203.9816853659 * self.t)
Y0 += 0.00000002590 * math.cos(3.33405614398 + 1190.5420625756 * self.t)
Y0 += 0.00000003494 * math.cos(1.33796606005 + 534.0793841623 * self.t)
Y0 += 0.00000003144 * math.cos(1.59061342897 + 1503.9649868156 * self.t)
Y0 += 0.00000002818 * math.cos(2.04818816564 + 49.31067880061 * self.t)
Y0 += 0.00000002791 * math.cos(2.91527039269 + 288.32451148881 * self.t)
Y0 += 0.00000002471 * math.cos(2.80089246981 + 411.11588743459 * self.t)
Y0 += 0.00000003059 * math.cos(1.73898053758 + 172.48911597691 * self.t)
Y0 += 0.00000002972 * math.cos(5.01468129705 + 569.29165849331 * self.t)
Y0 += 0.00000003418 * math.cos(3.83213917567 + 638.3959986583 * self.t)
Y0 += 0.00000002541 * math.cos(3.41936535077 + 1448.09090291091 * self.t)
Y0 += 0.00000002663 * math.cos(5.14390724060 + 573.6968925084 * self.t)
Y0 += 0.00000002439 * math.cos(2.82552552997 + 1625.9652756968 * self.t)
Y0 += 0.00000002739 * math.cos(1.01296407856 + 112.8832650427 * self.t)
Y0 += 0.00000002821 * math.cos(4.09784112299 + 402.93606672331 * self.t)
Y0 += 0.00000003412 * math.cos(5.98246878418 + 772.8325844196 * self.t)
Y0 += 0.00000002624 * math.cos(4.28449219810 + 1624.4808029885 * self.t)
Y0 += 0.00000003170 * math.cos(2.10762429629 + 1011.13503297159 * self.t)
Y0 += 0.00000002908 * math.cos(3.03870325402 + 635.94831810351 * self.t)
Y0 += 0.00000002664 * math.cos(4.25083112029 + 409.41896640519 * self.t)
Y0 += 0.00000003091 * math.cos(0.31165645931 + 379.25961975071 * self.t)
Y0 += 0.00000003301 * math.cos(3.48430565498 + 19.7936613644 * self.t)
Y0 += 0.00000003176 * math.cos(4.86809762289 + 300.9095662152 * self.t)
Y0 += 0.00000003022 * math.cos(4.37742921398 + 52.0189917863 * self.t)
Y0 += 0.00000002890 * math.cos(6.24788645936 + 293.4323209195 * self.t)
Y0 += 0.00000002698 * math.cos(3.26450368524 + 78149.06650032569 * self.t)
Y0 += 0.00000002558 * math.cos(2.31657732137 + 1371.3371966683 * self.t)
Y0 += 0.00000002619 * math.cos(5.37658613752 + 202.0095776906 * self.t)
Y0 += 0.00000003176 * math.cos(5.32134696018 + 10101.61156723069 * self.t)
Y0 += 0.00000003341 * math.cos(3.91159951862 + 345.8955164229 * self.t)
Y0 += 0.00000002373 * math.cos(0.25236813570 + 130.8513158457 * self.t)
Y0 += 0.00000002644 * math.cos(4.25178872695 + 305.10235190919 * self.t)
Y0 += 0.00000003339 * math.cos(3.06224357085 + 2849.2983147265 * self.t)
Y0 += 0.00000002410 * math.cos(3.15243245459 + 951.8525527931 * self.t)
Y0 += 0.00000003303 * math.cos(3.82850925169 + 769.5729459921 * self.t)
Y0 += 0.00000003302 * math.cos(3.28815049288 + 90.1520274241 * self.t)
Y0 += 0.00000002416 * math.cos(4.43555947495 + 527.929045008 * self.t)
Y0 += 0.00000002361 * math.cos(0.63550285699 + 905.1214974462 * self.t)
Y0 += 0.00000002737 * math.cos(3.20111311776 + 1206.2199993907 * self.t)
Y0 += 0.00000002441 * math.cos(5.40055208431 + 246.73489546739 * self.t)
Y0 += 0.00000002441 * math.cos(5.40055208431 + 247.2225304344 * self.t)
Y0 += 0.00000002957 * math.cos(2.68753178821 + 238.23075185041 * self.t)
Y0 += 0.00000003263 * math.cos(2.55710522617 + 1506.93393223219 * self.t)
Y0 += 0.00000003293 * math.cos(1.22031676357 + 66.1522096958 * self.t)
Y0 += 0.00000003241 * math.cos(5.00885682863 + 978.4186233052 * self.t)
Y0 += 0.00000003149 * math.cos(2.07892234370 + 271.9103693633 * self.t)
Y0 += 0.00000003149 * math.cos(5.22051499729 + 271.4227343963 * self.t)
Y0 += 0.00000002328 * math.cos(0.36371018198 + 31.73887900 * self.t)
Y0 += 0.00000002372 * math.cos(2.25731707420 + 309.0345051723 * self.t)
Y0 += 0.00000002372 * math.cos(2.25731707420 + 309.5221401393 * self.t)
Y0 += 0.00000002369 * math.cos(5.90092450419 + 418.9801939608 * self.t)
Y0 += 0.00000003007 * math.cos(6.21088893213 + 1437.7814079574 * self.t)
Y0 += 0.00000003034 * math.cos(4.41266493573 + 330.8627811417 * self.t)
Y0 += 0.00000002345 * math.cos(4.37756786631 + 453.9318358609 * self.t)
Y0 += 0.00000003118 * math.cos(5.30478414038 + 1434.81246254079 * self.t)
Y0 += 0.00000002324 * math.cos(5.43011369487 + 495.2462652364 * self.t)
Y0 += 0.00000002340 * math.cos(0.70753572900 + 452.43031681009 * self.t)
Y0 += 0.00000002336 * math.cos(1.61735465920 + 189.591279303 * self.t)
Y0 += 0.00000002920 * math.cos(2.21678930184 + 1549.69920442121 * self.t)
Y0 += 0.00000002494 * math.cos(2.36432658211 + 1187.57311715899 * self.t)
Y0 += 0.00000002692 * math.cos(5.74887255496 + 425.13053311509 * self.t)
Y0 += 0.00000002874 * math.cos(3.06187769177 + 1654.2764513481 * self.t)
Y0 += 0.00000002809 * math.cos(0.95838272583 + 317.5843407716 * self.t)
Y0 += 0.00000002735 * math.cos(2.36910571540 + 1513.05064149171 * self.t)
Y0 += 0.00000002949 * math.cos(4.69913732218 + 186.71620997851 * self.t)
Y0 += 0.00000002320 * math.cos(2.31406529898 + 487.38195871019 * self.t)
Y0 += 0.00000003113 * math.cos(4.63822476931 + 353.28425006961 * self.t)
Y0 += 0.00000003086 * math.cos(3.30396670519 + 1230.5990217789 * self.t)
Y0 += 0.00000002722 * math.cos(0.59415160235 + 49.6831858161 * self.t)
Y0 += 0.00000003064 * math.cos(2.11685584705 + 133.13224006171 * self.t)
Y0 += 0.00000003064 * math.cos(5.25844850064 + 132.64460509469 * self.t)
Y0 += 0.00000002470 * math.cos(1.21163683322 + 532.3824631329 * self.t)
Y0 += 0.00000002640 * math.cos(5.23029870928 + 394.33804701421 * self.t)
Y0 += 0.00000002252 * math.cos(3.41692637069 + 22.6507321964 * self.t)
Y0 += 0.00000003151 * math.cos(3.68959728933 + 859.77184894361 * self.t)
Y0 += 0.00000002671 * math.cos(2.49225273236 + 37.3679532925 * self.t)
Y0 += 0.00000002380 * math.cos(2.43767088034 + 429.2751346993 * self.t)
Y0 += 0.00000002655 * math.cos(4.29167785274 + 484.1523808627 * self.t)
Y0 += 0.00000003005 * math.cos(4.59447567553 + 1929.33933741419 * self.t)
Y0 += 0.00000002550 * math.cos(0.89259009595 + 496.9431862658 * self.t)
Y0 += 0.00000002290 * math.cos(4.98199823333 + 455.18681390559 * self.t)
Y0 += 0.00000002608 * math.cos(2.28446271246 + 422.9580392062 * self.t)
Y0 += 0.00000002226 * math.cos(0.52897898579 + 47.82620609231 * self.t)
Y0 += 0.00000002233 * math.cos(3.36949240110 + 877.3461408717 * self.t)
Y0 += 0.00000002764 * math.cos(2.40581332791 + 356.68058425589 * self.t)
Y0 += 0.00000002719 * math.cos(3.56033366747 + 177.5823711926 * self.t)
Y0 += 0.00000002999 * math.cos(3.63965245652 + 1926.37039199759 * self.t)
Y0 += 0.00000002693 * math.cos(2.00893145868 + 6284.8041401832 * self.t)
Y0 += 0.00000002369 * math.cos(5.90816921383 + 70.88081446661 * self.t)
Y0 += 0.00000002498 * math.cos(2.14771583991 + 315.1512144318 * self.t)
Y0 += 0.00000002204 * math.cos(4.77545839271 + 442.886135597 * self.t)
Y0 += 0.00000002261 * math.cos(4.89614385698 + 621.2335891349 * self.t)
Y0 += 0.00000002213 * math.cos(1.45024938630 + 1189.0575898673 * self.t)
Y0 += 0.00000002492 * math.cos(4.24445703283 + 406.9712858504 * self.t)
Y0 += 0.00000002976 * math.cos(3.02481916981 + 1014.1039783882 * self.t)
Y0 += 0.00000002840 * math.cos(0.64471611311 + 522.3336006103 * self.t)
Y0 += 0.00000002340 * math.cos(3.29528259310 + 440.43845504219 * self.t)
Y0 += 0.00000003012 * math.cos(2.70591736862 + 15.9096922111 * self.t)
Y0 += 0.00000003012 * math.cos(2.70591736862 + 16.3973271781 * self.t)
Y0 += 0.00000002372 * math.cos(1.81307027955 + 132.5964209849 * self.t)
Y0 += 0.00000002232 * math.cos(3.99248125271 + 158.12984768129 * self.t)
Y0 += 0.00000002961 * math.cos(5.94214048852 + 286.3524038135 * self.t)
Y0 += 0.00000002961 * math.cos(2.80054783493 + 286.8400387805 * self.t)
# Neptune_Y1 (t) // 342 terms of order 1
Y1 = 0
Y1 += 0.00357822049 * math.cos(3.03457804662 + 0.2438174835 * self.t)
Y1 += 0.00256200629 * math.cos(0.44613631554 + 36.892380413 * self.t)
Y1 += 0.00242677799 * math.cos(3.89213848413 + 39.86132582961 * self.t)
Y1 += 0.00106073143 * math.cos(4.64936068389 + 37.88921815429 * self.t)
Y1 += 0.00103735195 * math.cos(4.51191141127 + 38.3768531213 * self.t)
Y1 += 0.00118508231 * math.cos(1.31543504055 + 76.50988875911 * self.t)
Y1 += 0.00021930692 * math.cos(1.62939936370 + 35.40790770471 * self.t)
Y1 += 0.00017445772 * math.cos(2.69316438174 + 41.3457985379 * self.t)
Y1 += 0.00013038843 * math.cos(3.79605108858 + 3.21276290011 * self.t)
Y1 += 0.00004928885 * math.cos(0.51813571490 + 73.5409433425 * self.t)
Y1 += 0.00002742686 * math.cos(2.49310000815 + 77.9943614674 * self.t)
Y1 += 0.00002155134 * math.cos(2.54801435750 + 4.6972356084 * self.t)
Y1 += 0.00001882800 * math.cos(2.84958651579 + 33.9234349964 * self.t)
Y1 += 0.00001572888 * math.cos(5.79049449823 + 114.6429243969 * self.t)
Y1 += 0.00001326507 * math.cos(4.45906236203 + 75.0254160508 * self.t)
Y1 += 0.00001343094 * math.cos(1.46758582116 + 42.83027124621 * self.t)
Y1 += 0.00000897979 * math.cos(2.69913392072 + 426.8420083595 * self.t)
Y1 += 0.00000865617 * math.cos(0.09538823497 + 37.8555882595 * self.t)
Y1 += 0.00000849963 * math.cos(4.24519902715 + 38.89811798311 * self.t)
Y1 += 0.00000922754 * math.cos(1.77437053635 + 72.05647063421 * self.t)
Y1 += 0.00000726258 * math.cos(5.81913445111 + 36.404745446 * self.t)
Y1 += 0.00000778220 * math.cos(4.27400223412 + 206.42936592071 * self.t)
Y1 += 0.00000754025 * math.cos(3.76126183394 + 220.6564599223 * self.t)
Y1 += 0.00000607406 * math.cos(4.81815513635 + 1059.6257476727 * self.t)
Y1 += 0.00000571831 * math.cos(0.85851242227 + 522.8212355773 * self.t)
Y1 += 0.00000560995 * math.cos(0.34476353479 + 537.0483295789 * self.t)
Y1 += 0.00000501078 * math.cos(0.14255476727 + 28.81562556571 * self.t)
Y1 += 0.00000493238 * math.cos(0.53463363296 + 39.3736908626 * self.t)
Y1 += 0.00000474802 * math.cos(5.97795229031 + 98.6561710411 * self.t)
Y1 += 0.00000453975 * math.cos(0.14363576661 + 35.9291725665 * self.t)
Y1 += 0.00000471731 * math.cos(3.27137539235 + 1.7282901918 * self.t)
Y1 += 0.00000410057 * math.cos(4.19500321025 + 40.8245336761 * self.t)
Y1 += 0.00000366899 * math.cos(4.19675940250 + 47.9380806769 * self.t)
Y1 += 0.00000450109 * math.cos(2.82750084230 + 76.0222537921 * self.t)
Y1 += 0.00000354347 * math.cos(1.55870450456 + 1.24065522479 * self.t)
Y1 += 0.00000300159 * math.cos(1.31608359577 + 6.1817083167 * self.t)
Y1 += 0.00000327501 * math.cos(5.77559197316 + 33.43580002939 * self.t)
Y1 += 0.00000174973 * math.cos(4.06947925642 + 32.4389622881 * self.t)
Y1 += 0.00000171503 * math.cos(2.86905921629 + 34.1840674273 * self.t)
Y1 += 0.00000156749 * math.cos(1.02465451730 + 79.47883417571 * self.t)
Y1 += 0.00000152549 * math.cos(5.29458792782 + 30.300098274 * self.t)
Y1 += 0.00000150775 * math.cos(1.46875297221 + 42.5696388153 * self.t)
Y1 += 0.00000162280 * math.cos(5.51215947389 + 31.2633061205 * self.t)
Y1 += 0.00000131609 * math.cos(3.19975255613 + 7.83293736379 * self.t)
Y1 += 0.00000136159 * math.cos(3.00798814109 + 70.5719979259 * self.t)
Y1 += 0.00000134616 * math.cos(5.10422989672 + 45.49040012211 * self.t)
Y1 += 0.00000116304 * math.cos(5.32949492640 + 46.4536079686 * self.t)
Y1 += 0.00000115918 * math.cos(0.24763705851 + 44.31474395451 * self.t)
Y1 += 0.00000110293 * math.cos(4.69481457289 + 35.4560918145 * self.t)
Y1 += 0.00000099282 * math.cos(0.34979488247 + 2.7251279331 * self.t)
Y1 += 0.00000099914 * math.cos(5.92865840649 + 41.2976144281 * self.t)
Y1 += 0.00000108706 * math.cos(1.52062460635 + 113.15845168861 * self.t)
Y1 += 0.00000088965 * math.cos(5.83760483379 + 60.52313540329 * self.t)
Y1 += 0.00000086886 * math.cos(0.75633169755 + 31.9513273211 * self.t)
Y1 += 0.00000072232 * math.cos(1.93507773057 + 640.1411037975 * self.t)
Y1 += 0.00000086985 * math.cos(3.23018942725 + 419.72846135871 * self.t)
Y1 += 0.00000073430 * math.cos(5.93590859407 + 70.08436295889 * self.t)
Y1 += 0.00000053395 * math.cos(2.89441175199 + 433.9555553603 * self.t)
Y1 += 0.00000057451 * math.cos(5.79242631159 + 213.5429129215 * self.t)
Y1 += 0.00000051458 * math.cos(2.44646741842 + 69.3963417583 * self.t)
Y1 += 0.00000048797 * math.cos(4.44285537763 + 111.67397898031 * self.t)
Y1 += 0.00000048557 * math.cos(1.53569583062 + 2.6769438233 * self.t)
Y1 += 0.00000042206 * math.cos(4.80902694866 + 74.53778108379 * self.t)
Y1 += 0.00000042550 * math.cos(0.10167685669 + 7.66618102501 * self.t)
Y1 += 0.00000039462 * math.cos(4.26971409186 + 31.7845709823 * self.t)
Y1 += 0.00000039445 * math.cos(5.65869884949 + 12.77399045571 * self.t)
Y1 += 0.00000042389 * math.cos(4.01940273222 + 110.189506272 * self.t)
Y1 += 0.00000044118 * math.cos(5.15854031484 + 1589.3167127673 * self.t)
Y1 += 0.00000037988 * math.cos(4.30930512095 + 6.3484646555 * self.t)
Y1 += 0.00000037802 * math.cos(4.41701497532 + 14.258463164 * self.t)
Y1 += 0.00000036280 * math.cos(1.56655638104 + 273.8222308413 * self.t)
Y1 += 0.00000037247 * math.cos(6.20048406786 + 73.0533083755 * self.t)
Y1 += 0.00000036282 * math.cos(1.28256818253 + 84.5866436064 * self.t)
Y1 += 0.00000040018 * math.cos(2.70338838405 + 4.4366031775 * self.t)
Y1 += 0.00000032400 * math.cos(0.07249247133 + 44.96913526031 * self.t)
Y1 += 0.00000031842 * math.cos(0.45413330049 + 34.9202727377 * self.t)
Y1 += 0.00000032037 * math.cos(1.37472212177 + 27.3311528574 * self.t)
Y1 += 0.00000034456 * math.cos(1.80072966680 + 529.9347825781 * self.t)
Y1 += 0.00000031208 * math.cos(0.16340478702 + 1052.51220067191 * self.t)
Y1 += 0.00000030002 * math.cos(0.76559925402 + 1066.7392946735 * self.t)
Y1 += 0.00000033805 * math.cos(4.47034863791 + 149.8070146181 * self.t)
Y1 += 0.00000033096 * math.cos(0.88714456679 + 116.12739710521 * self.t)
Y1 += 0.00000030571 * math.cos(5.59230793843 + 22.3900997655 * self.t)
Y1 += 0.00000024020 * math.cos(4.95060362012 + 63.9797157869 * self.t)
Y1 += 0.00000023780 * math.cos(5.91699417045 + 105.76971804189 * self.t)
Y1 += 0.00000023110 * math.cos(4.08428537053 + 23.87457247379 * self.t)
Y1 += 0.00000022233 * math.cos(2.78662410030 + 174.9222423167 * self.t)
Y1 += 0.00000021377 * math.cos(2.17060095397 + 316.6356871401 * self.t)
Y1 += 0.00000025400 * math.cos(6.09781709877 + 106.73292588839 * self.t)
Y1 += 0.00000020754 * math.cos(5.65712726150 + 5.6604434549 * self.t)
Y1 += 0.00000025572 * math.cos(0.74829738831 + 529.44714761109 * self.t)
Y1 += 0.00000019878 * math.cos(5.73044838456 + 32.9602271499 * self.t)
Y1 += 0.00000019754 * math.cos(2.91920492275 + 49.42255338521 * self.t)
Y1 += 0.00000019241 * math.cos(4.44333892046 + 7.14491616321 * self.t)
Y1 += 0.00000017979 * math.cos(6.19717030924 + 62.4952430786 * self.t)
Y1 += 0.00000019513 * math.cos(0.93528726944 + 68.5998902506 * self.t)
Y1 += 0.00000018273 * math.cos(3.63050723326 + 227.77000692311 * self.t)
Y1 += 0.00000017552 * math.cos(4.23270606709 + 69.0875252176 * self.t)
Y1 += 0.00000016704 * math.cos(5.51562885485 + 40.8581635709 * self.t)
Y1 += 0.00000016996 * math.cos(2.67528896312 + 91.54262404029 * self.t)
Y1 += 0.00000016800 * math.cos(2.08712613778 + 30.4668546128 * self.t)
Y1 += 0.00000016800 * math.cos(5.22871879137 + 30.95448957981 * self.t)
Y1 += 0.00000016400 * math.cos(3.45346576095 + 33.26904369061 * self.t)
Y1 += 0.00000017242 * math.cos(4.89590986485 + 11.55015017831 * self.t)
Y1 += 0.00000015590 * math.cos(0.42181314281 + 37.1048287341 * self.t)
Y1 += 0.00000015590 * math.cos(3.91877412353 + 39.6488775085 * self.t)
Y1 += 0.00000015469 * math.cos(4.91170489358 + 43.79347909271 * self.t)
Y1 += 0.00000016590 * math.cos(1.19757876004 + 33.71098667531 * self.t)
Y1 += 0.00000019347 * math.cos(4.06418655235 + 152.77596003471 * self.t)
Y1 += 0.00000014994 * math.cos(4.29075263091 + 319.06881347989 * self.t)
Y1 += 0.00000014395 * math.cos(5.67189517492 + 110.45013870291 * self.t)
Y1 += 0.00000015528 * math.cos(5.87587490674 + 79.43065006591 * self.t)
Y1 += 0.00000013727 * math.cos(0.88731617093 + 43.484662552 * self.t)
Y1 += 0.00000013988 * math.cos(5.54059308769 + 4.2096006414 * self.t)
Y1 += 0.00000014467 * math.cos(5.13403607047 + 108.70503356371 * self.t)
Y1 += 0.00000016652 * math.cos(4.74696813612 + 304.84171947829 * self.t)
Y1 += 0.00000015153 * math.cos(1.64704158732 + 72.31710306511 * self.t)
Y1 += 0.00000012810 * math.cos(0.80784638784 + 11.2895177474 * self.t)
Y1 += 0.00000012751 * math.cos(5.32663860873 + 45.7992166628 * self.t)
Y1 += 0.00000013293 * math.cos(3.14432194523 + 43.0427195673 * self.t)
Y1 += 0.00000012751 * math.cos(0.98606109283 + 515.70768857651 * self.t)
Y1 += 0.00000011616 * math.cos(4.07265201948 + 97.17169833279 * self.t)
Y1 += 0.00000011538 * math.cos(4.63247506911 + 633.0275567967 * self.t)
Y1 += 0.00000011046 * math.cos(5.97427560684 + 25.8466801491 * self.t)
Y1 += 0.00000011032 * math.cos(5.39646944302 + 4.8639919472 * self.t)
Y1 += 0.00000011189 * math.cos(2.37859784397 + 83.1021708981 * self.t)
Y1 += 0.00000010860 * math.cos(5.09978655023 + 9.8050450391 * self.t)
Y1 += 0.00000010958 * math.cos(3.05455531642 + 415.04804069769 * self.t)
Y1 += 0.00000010244 * math.cos(4.97854342755 + 71.09326278771 * self.t)
Y1 += 0.00000011427 * math.cos(3.07758676009 + 129.6756596781 * self.t)
Y1 += 0.00000009895 * math.cos(4.05388510292 + 251.6759485593 * self.t)
Y1 += 0.00000009802 * math.cos(3.40894474212 + 44.48150029329 * self.t)
Y1 += 0.00000011029 * math.cos(6.26821027792 + 143.38148881789 * self.t)
Y1 += 0.00000009235 * math.cos(4.42290386641 + 199.3158189199 * self.t)
Y1 += 0.00000008899 * math.cos(1.97879285736 + 7.3573644843 * self.t)
Y1 += 0.00000007746 * math.cos(4.32608949084 + 103.3365917021 * self.t)
Y1 += 0.00000008691 * math.cos(2.29051174612 + 32.7477788288 * self.t)
Y1 += 0.00000007714 * math.cos(3.51056446926 + 65.46418849521 * self.t)
Y1 += 0.00000008007 * math.cos(0.23872922784 + 544.1618765797 * self.t)
Y1 += 0.00000007513 * math.cos(6.18736050552 + 69.6087900794 * self.t)
Y1 += 0.00000007336 * math.cos(3.43409422317 + 15.7429358723 * self.t)
Y1 += 0.00000007195 * math.cos(4.56950200257 + 949.4194264533 * self.t)
Y1 += 0.00000009601 * math.cos(5.68191403081 + 80.963306884 * self.t)
Y1 += 0.00000008094 * math.cos(1.70304241092 + 526.7533888404 * self.t)
Y1 += 0.00000008109 * math.cos(5.77532188995 + 533.1161763158 * self.t)
Y1 += 0.00000006906 * math.cos(3.70672232078 + 137.2768416459 * self.t)
Y1 += 0.00000007455 * math.cos(1.11362695292 + 105.2484531801 * self.t)
Y1 += 0.00000007826 * math.cos(2.45321405406 + 77.0311536209 * self.t)
Y1 += 0.00000006529 * math.cos(5.57837212493 + 65.2035560643 * self.t)
Y1 += 0.00000007134 * math.cos(2.05010386093 + 44.00592741381 * self.t)
Y1 += 0.00000006186 * math.cos(0.85023811841 + 31.4757544416 * self.t)
Y1 += 0.00000006186 * math.cos(3.99183077200 + 30.9881194746 * self.t)
Y1 += 0.00000007698 * math.cos(4.89115030216 + 14.47091148511 * self.t)
Y1 += 0.00000007434 * math.cos(3.96333556733 + 146.8380692015 * self.t)
Y1 += 0.00000006317 * math.cos(5.24777799313 + 66.9486612035 * self.t)
Y1 += 0.00000006903 * math.cos(4.63739310514 + 75.98862389731 * self.t)
Y1 += 0.00000005591 * math.cos(3.47781120117 + 448.98829064149 * self.t)
Y1 += 0.00000006425 * math.cos(3.47626562775 + 678.27413943531 * self.t)
Y1 += 0.00000005483 * math.cos(1.61247704205 + 34.44469985821 * self.t)
Y1 += 0.00000005483 * math.cos(2.72811022429 + 42.3090063844 * self.t)
Y1 += 0.00000005519 * math.cos(1.27116075236 + 853.4401992355 * self.t)
Y1 += 0.00000005483 * math.cos(5.10869779974 + 100.14064374939 * self.t)
Y1 += 0.00000005483 * math.cos(1.96710514615 + 100.6282787164 * self.t)
Y1 += 0.00000006288 * math.cos(2.60319684406 + 143.9027536797 * self.t)
Y1 += 0.00000006239 * math.cos(4.20987077870 + 17.76992530181 * self.t)
Y1 += 0.00000005246 * math.cos(3.52035332490 + 209.6107596584 * self.t)
Y1 += 0.00000005331 * math.cos(4.83550697489 + 45.9659730016 * self.t)
Y1 += 0.00000005131 * math.cos(4.53503564274 + 217.4750661846 * self.t)
Y1 += 0.00000005325 * math.cos(2.82680123889 + 19.2543980101 * self.t)
Y1 += 0.00000005172 * math.cos(2.44008575183 + 25.3590451821 * self.t)
Y1 += 0.00000005139 * math.cos(4.17507085285 + 6.86972951729 * self.t)
Y1 += 0.00000005992 * math.cos(2.76367557670 + 9.3174100721 * self.t)
Y1 += 0.00000005011 * math.cos(4.91884286875 + 38.85242600079 * self.t)
Y1 += 0.00000004975 * math.cos(3.01044533436 + 525.2543619171 * self.t)
Y1 += 0.00000004910 * math.cos(3.47707407879 + 45.277951801 * self.t)
Y1 += 0.00000005250 * math.cos(0.16559612363 + 0.719390363 * self.t)
Y1 += 0.00000004731 * math.cos(6.27469301850 + 40.3825906914 * self.t)
Y1 += 0.00000004731 * math.cos(1.20748690143 + 36.3711155512 * self.t)
Y1 += 0.00000005910 * math.cos(1.40566081690 + 6168.43292559449 * self.t)
Y1 += 0.00000004700 * math.cos(4.66314397827 + 50.9070260935 * self.t)
Y1 += 0.00000005127 * math.cos(1.64029328726 + 140.9338082631 * self.t)
Y1 += 0.00000005321 * math.cos(2.09939112611 + 1104.87233031131 * self.t)
Y1 += 0.00000006339 * math.cos(1.02786059939 + 10175.3963280567 * self.t)
Y1 += 0.00000004983 * math.cos(1.46113982673 + 1090.6452363097 * self.t)
Y1 += 0.00000005487 * math.cos(0.13979521980 + 180.03005174739 * self.t)
Y1 += 0.00000004560 * math.cos(2.38015606975 + 323.74923414091 * self.t)
Y1 += 0.00000004689 * math.cos(5.95510153546 + 1068.22376738181 * self.t)
Y1 += 0.00000005562 * math.cos(2.83481631972 + 10098.64262181409 * self.t)
Y1 += 0.00000004432 * math.cos(0.83559275468 + 415.7963080956 * self.t)
Y1 += 0.00000004456 * math.cos(1.46246408589 + 235.68919520349 * self.t)
Y1 += 0.00000004289 * math.cos(4.40449246840 + 1051.0277279636 * self.t)
Y1 += 0.00000004145 * math.cos(4.70457869197 + 33.6964324603 * self.t)
Y1 += 0.00000004167 * math.cos(3.29886964345 + 416.532513406 * self.t)
Y1 += 0.00000004107 * math.cos(0.91956436736 + 61.01077037031 * self.t)
Y1 += 0.00000004088 * math.cos(3.88660175347 + 423.66061462181 * self.t)
Y1 += 0.00000005027 * math.cos(2.86873904525 + 21.7020785649 * self.t)
Y1 += 0.00000004030 * math.cos(3.44189647415 + 216.72430665921 * self.t)
Y1 += 0.00000004278 * math.cos(6.22413352457 + 310.4707937708 * self.t)
Y1 += 0.00000004013 * math.cos(2.96769071148 + 104275.10267753768 * self.t)
Y1 += 0.00000004505 * math.cos(5.93746161630 + 291.9478482112 * self.t)
Y1 += 0.00000003959 * math.cos(4.60954974650 + 210.36151918381 * self.t)
Y1 += 0.00000003962 * math.cos(5.59162611271 + 978.93988816699 * self.t)
Y1 += 0.00000005561 * math.cos(3.31923216598 + 1409.47023230609 * self.t)
Y1 += 0.00000005073 * math.cos(5.15285057233 + 1498.3359125231 * self.t)
Y1 += 0.00000004227 * math.cos(6.19954210169 + 534.38820070301 * self.t)
Y1 += 0.00000004054 * math.cos(2.45804475947 + 430.02340209721 * self.t)
Y1 += 0.00000003863 * math.cos(0.67184399240 + 1127.50624756031 * self.t)
Y1 += 0.00000004367 * math.cos(0.14073726901 + 58.9837809408 * self.t)
Y1 += 0.00000004694 * math.cos(4.91041582057 + 77.5067265004 * self.t)
Y1 += 0.00000004144 * math.cos(5.16137286617 + 518.1408149163 * self.t)
Y1 += 0.00000004289 * math.cos(1.72696806473 + 921.3206991231 * self.t)
Y1 += 0.00000004039 * math.cos(5.37067473153 + 1622.76932774409 * self.t)
Y1 += 0.00000005180 * math.cos(3.80035699018 + 99.1438060081 * self.t)
Y1 += 0.00000004845 * math.cos(1.33083083566 + 136.78920667889 * self.t)
Y1 += 0.00000004827 * math.cos(1.21379713661 + 418.2439886504 * self.t)
Y1 += 0.00000003722 * math.cos(4.94171351364 + 1065.2548219652 * self.t)
Y1 += 0.00000004729 * math.cos(2.19682691364 + 421.212934067 * self.t)
Y1 += 0.00000003490 * math.cos(0.54756448610 + 986.8041946932 * self.t)
Y1 += 0.00000003715 * math.cos(1.30912268012 + 254.10907489909 * self.t)
Y1 += 0.00000003488 * math.cos(5.95100195908 + 187.9400502559 * self.t)
Y1 += 0.00000003989 * math.cos(5.37041318514 + 95.7354097343 * self.t)
Y1 += 0.00000003603 * math.cos(2.22310220083 + 67.1154175423 * self.t)
Y1 += 0.00000003530 * math.cos(0.93986174870 + 24.36220744081 * self.t)
Y1 += 0.00000003538 * math.cos(1.51952328076 + 57.4993082325 * self.t)
Y1 += 0.00000003838 * math.cos(3.56895316428 + 979.90309601349 * self.t)
Y1 += 0.00000003615 * math.cos(1.60474010406 + 493.2862196486 * self.t)
Y1 += 0.00000003457 * math.cos(1.79944886939 + 807.70598162989 * self.t)
Y1 += 0.00000003648 * math.cos(1.43920595596 + 647.25465079831 * self.t)
Y1 += 0.00000004048 * math.cos(6.25251011272 + 979.69064769239 * self.t)
Y1 += 0.00000004414 * math.cos(2.00415973362 + 1062.59469308931 * self.t)
Y1 += 0.00000003631 * math.cos(0.74841494891 + 486.1726726478 * self.t)
Y1 += 0.00000003347 * math.cos(4.13560148025 + 151.2914873264 * self.t)
Y1 += 0.00000003305 * math.cos(5.23397852699 + 1544.07013012871 * self.t)
Y1 += 0.00000003428 * math.cos(0.11713176717 + 107.2205608554 * self.t)
Y1 += 0.00000003286 * math.cos(3.55869926238 + 1131.6990332543 * self.t)
Y1 += 0.00000003389 * math.cos(3.22644735392 + 28.98238190449 * self.t)
Y1 += 0.00000003353 * math.cos(2.30309048870 + 10289.7954349701 * self.t)
Y1 += 0.00000003214 * math.cos(0.83720162261 + 569.5522909242 * self.t)
Y1 += 0.00000003210 * math.cos(1.05449812296 + 114.1552894299 * self.t)
Y1 += 0.00000003353 * math.cos(1.62613341505 + 157.8837694654 * self.t)
Y1 += 0.00000003339 * math.cos(5.26712406495 + 443.0985839181 * self.t)
Y1 += 0.00000003188 * math.cos(2.62887165071 + 361.13400238079 * self.t)
Y1 += 0.00000003390 * math.cos(5.53564544873 + 1558.2972241303 * self.t)
Y1 += 0.00000003933 * math.cos(2.08622660372 + 313.43973918739 * self.t)
Y1 += 0.00000003131 * math.cos(0.52572989907 + 275.3067035496 * self.t)
Y1 += 0.00000003156 * math.cos(6.23565991208 + 431.8404353331 * self.t)
Y1 += 0.00000003993 * math.cos(4.90080803105 + 67.6366824041 * self.t)
Y1 += 0.00000003708 * math.cos(0.24836934654 + 500.39976664941 * self.t)
Y1 += 0.00000004051 * math.cos(4.41826493037 + 59.038662695 * self.t)
Y1 += 0.00000003757 * math.cos(2.02838234929 + 296.4012663361 * self.t)
Y1 += 0.00000003138 * math.cos(0.63906969040 + 347.1193567003 * self.t)
Y1 += 0.00000003086 * math.cos(1.67235466145 + 392.9017584157 * self.t)
Y1 += 0.00000003466 * math.cos(1.60020779124 + 215.1941419686 * self.t)
Y1 += 0.00000003139 * math.cos(3.09999506971 + 159.36824217371 * self.t)
Y1 += 0.00000003466 * math.cos(3.47361825954 + 2145.34674583789 * self.t)
Y1 += 0.00000003737 * math.cos(3.53018898305 + 449.0364747513 * self.t)
Y1 += 0.00000003286 * math.cos(1.82620986507 + 435.44002806861 * self.t)
Y1 += 0.00000003043 * math.cos(5.02988988519 + 2.20386307129 * self.t)
Y1 += 0.00000003999 * math.cos(5.93005561135 + 6245.1866318371 * self.t)
Y1 += 0.00000003999 * math.cos(5.93005561135 + 6244.69899687009 * self.t)
Y1 += 0.00000002999 * math.cos(0.07518657231 + 526.00262931501 * self.t)
Y1 += 0.00000003014 * math.cos(5.52171912448 + 1054.94532701169 * self.t)
Y1 += 0.00000003091 * math.cos(4.52477390940 + 42.997027585 * self.t)
Y1 += 0.00000003274 * math.cos(5.81401559586 + 736.1203310153 * self.t)
Y1 += 0.00000002965 * math.cos(1.12065249261 + 533.8669358412 * self.t)
Y1 += 0.00000003149 * math.cos(2.34844411589 + 103.7639804718 * self.t)
Y1 += 0.00000003610 * math.cos(1.47397387042 + 55.05162767771 * self.t)
Y1 += 0.00000002937 * math.cos(5.93931708618 + 385.2523923381 * self.t)
Y1 += 0.00000002903 * math.cos(4.35235911504 + 117.5636857037 * self.t)
Y1 += 0.00000002968 * math.cos(1.28091906944 + 613.31440085451 * self.t)
Y1 += 0.00000003097 * math.cos(4.42120029558 + 1395.24313830449 * self.t)
Y1 += 0.00000002931 * math.cos(3.60795663266 + 202.4972126576 * self.t)
Y1 += 0.00000003013 * math.cos(1.49526296600 + 121.2352065359 * self.t)
Y1 += 0.00000003206 * math.cos(2.86107032756 + 53.40958840249 * self.t)
Y1 += 0.00000003269 * math.cos(0.45608619325 + 480.00777927849 * self.t)
Y1 += 0.00000003948 * math.cos(5.43052261409 + 112.8832650427 * self.t)
Y1 += 0.00000002824 * math.cos(3.14926129801 + 176.406715025 * self.t)
Y1 += 0.00000002827 * math.cos(0.36860696411 + 429.81095377611 * self.t)
Y1 += 0.00000003348 * math.cos(3.55163976673 + 6284.8041401832 * self.t)
Y1 += 0.00000002862 * math.cos(2.43356518574 + 384.02855206069 * self.t)
Y1 += 0.00000003228 * math.cos(5.13696496058 + 52.6039471229 * self.t)
Y1 += 0.00000003446 * math.cos(5.32686217736 + 62.0076081116 * self.t)
Y1 += 0.00000003096 * math.cos(4.83839993614 + 71.82946809809 * self.t)
Y1 += 0.00000003031 * math.cos(6.24076040166 + 494.2348732801 * self.t)
Y1 += 0.00000003021 * math.cos(6.10531658530 + 328.5964111407 * self.t)
Y1 += 0.00000002731 * math.cos(0.79873177065 + 432.471082652 * self.t)
Y1 += 0.00000003171 * math.cos(4.97187934370 + 10215.0138364028 * self.t)
Y1 += 0.00000002674 * math.cos(2.29257372574 + 158.12984768129 * self.t)
Y1 += 0.00000002901 * math.cos(4.22947732371 + 559.4697985068 * self.t)
Y1 += 0.00000002631 * math.cos(4.21066619701 + 2008.8013566425 * self.t)
Y1 += 0.00000002695 * math.cos(3.54636234855 + 81.61769818981 * self.t)
Y1 += 0.00000002695 * math.cos(3.54636234855 + 81.13006322279 * self.t)
Y1 += 0.00000002721 * math.cos(4.26045579509 + 326.1823604807 * self.t)
Y1 += 0.00000002775 * math.cos(4.27616320157 + 457.8614969965 * self.t)
Y1 += 0.00000003054 * math.cos(6.23455983590 + 6281.8351947666 * self.t)
Y1 += 0.00000002852 * math.cos(2.90626399353 + 186.71620997851 * self.t)
Y1 += 0.00000002538 * math.cos(1.73224718947 + 111.18634401329 * self.t)
Y1 += 0.00000002835 * math.cos(6.07135630955 + 419.50145882259 * self.t)
Y1 += 0.00000002868 * math.cos(3.66893253825 + 844.56699288049 * self.t)
Y1 += 0.00000002530 * math.cos(2.61093052560 + 1050.7525413177 * self.t)
Y1 += 0.00000002843 * math.cos(4.15972261299 + 830.3398988789 * self.t)
Y1 += 0.00000002848 * math.cos(4.69330398359 + 659.36662477269 * self.t)
Y1 += 0.00000003031 * math.cos(2.55942970028 + 406.3469551246 * self.t)
Y1 += 0.00000002907 * math.cos(3.71503751053 + 573.6968925084 * self.t)
Y1 += 0.00000002536 * math.cos(5.01251643852 + 82.6145359311 * self.t)
Y1 += 0.00000002957 * math.cos(2.02121290773 + 947.70795120889 * self.t)
Y1 += 0.00000003321 * math.cos(3.87615887284 + 449.9996825978 * self.t)
Y1 += 0.00000003117 * math.cos(4.74251772899 + 457.32567791969 * self.t)
Y1 += 0.00000002902 * math.cos(1.37682148855 + 10212.0448909862 * self.t)
Y1 += 0.00000002459 * math.cos(3.74222344492 + 450.73339578069 * self.t)
Y1 += 0.00000002557 * math.cos(1.32711393852 + 525.4813644532 * self.t)
Y1 += 0.00000002624 * math.cos(3.35106775051 + 946.2234785006 * self.t)
Y1 += 0.00000002417 * math.cos(0.09697452811 + 351.5727748252 * self.t)
Y1 += 0.00000002454 * math.cos(3.27912412212 + 196.01680510321 * self.t)
Y1 += 0.00000002585 * math.cos(5.70826849733 + 248.70700314271 * self.t)
Y1 += 0.00000002549 * math.cos(0.23244817308 + 1062.80714141041 * self.t)
Y1 += 0.00000002615 * math.cos(4.06090316067 + 425.13053311509 * self.t)
Y1 += 0.00000002387 * math.cos(2.04191008078 + 654.3681977991 * self.t)
Y1 += 0.00000002439 * math.cos(1.45718218253 + 462.74230389109 * self.t)
Y1 += 0.00000002367 * math.cos(2.75159024078 + 107.52937739611 * self.t)
Y1 += 0.00000002538 * math.cos(4.19012282298 + 481.2316195559 * self.t)
Y1 += 0.00000002479 * math.cos(3.56223236298 + 205.9417309537 * self.t)
Y1 += 0.00000002791 * math.cos(5.44719714506 + 24.14975911971 * self.t)
Y1 += 0.00000002626 * math.cos(2.73743077295 + 213.0552779545 * self.t)
Y1 += 0.00000002445 * math.cos(0.13750022894 + 146.87169909629 * self.t)
Y1 += 0.00000002575 * math.cos(0.32351821119 + 86.07111631471 * self.t)
Y1 += 0.00000003120 * math.cos(1.20503303199 + 456.36247007319 * self.t)
Y1 += 0.00000002587 * math.cos(1.59304506140 + 400.8209466961 * self.t)
Y1 += 0.00000002261 * math.cos(3.24987212470 + 644.33388949151 * self.t)
Y1 += 0.00000002796 * math.cos(0.30156280343 + 216.67861467689 * self.t)
Y1 += 0.00000002896 * math.cos(0.71993168447 + 1685.2959399851 * self.t)
Y1 += 0.00000002453 * math.cos(4.81368306062 + 109.9625037359 * self.t)
Y1 += 0.00000002325 * math.cos(0.25394919776 + 442.886135597 * self.t)
Y1 += 0.00000002387 * math.cos(3.75345095238 + 599.0873068529 * self.t)
Y1 += 0.00000002873 * math.cos(5.13430840850 + 834.5326845729 * self.t)
Y1 += 0.00000002963 * math.cos(5.48260613029 + 2119.00767786191 * self.t)
Y1 += 0.00000002233 * math.cos(4.37346978315 + 709.29362807231 * self.t)
Y1 += 0.00000002337 * math.cos(2.73478761543 + 210.5739675049 * self.t)
Y1 += 0.00000002259 * math.cos(5.24608284286 + 29.5036467663 * self.t)
Y1 += 0.00000002300 * math.cos(2.19835177792 + 986.0534351678 * self.t)
Y1 += 0.00000002199 * math.cos(1.21359358990 + 606.2008538537 * self.t)
Y1 += 0.00000002325 * math.cos(4.84070679976 + 109.701871305 * self.t)
# Neptune_Y2 (t) // 113 terms of order 2
Y2 = 0
Y2 += 0.01620002167 * math.cos(5.31277371181 + 38.3768531213 * self.t)
Y2 += 0.00028138323 * math.cos(4.01361134771 + 0.2438174835 * self.t)
Y2 += 0.00012318619 * math.cos(1.01433481938 + 39.86132582961 * self.t)
Y2 += 0.00008346956 * math.cos(0.42201817445 + 37.88921815429 * self.t)
Y2 += 0.00005131003 * math.cos(3.55894443240 + 76.50988875911 * self.t)
Y2 += 0.00004109792 * math.cos(6.17733924169 + 36.892380413 * self.t)
Y2 += 0.00001369663 * math.cos(1.98683082370 + 1.7282901918 * self.t)
Y2 += 0.00000633706 * math.cos(0.81055475696 + 3.21276290011 * self.t)
Y2 += 0.00000583006 * math.cos(6.25831267359 + 41.3457985379 * self.t)
Y2 += 0.00000546517 * math.cos(5.42211492491 + 75.0254160508 * self.t)
Y2 += 0.00000246224 * math.cos(0.87539145895 + 213.5429129215 * self.t)
Y2 += 0.00000159773 * math.cos(5.97653264005 + 206.42936592071 * self.t)
Y2 += 0.00000156619 * math.cos(2.04577076492 + 220.6564599223 * self.t)
Y2 += 0.00000191674 * math.cos(0.60086490402 + 529.9347825781 * self.t)
Y2 += 0.00000188212 * math.cos(2.86105100061 + 35.40790770471 * self.t)
Y2 += 0.00000117788 * math.cos(2.55450585422 + 522.8212355773 * self.t)
Y2 += 0.00000114488 * math.cos(4.76320074833 + 35.9291725665 * self.t)
Y2 += 0.00000112666 * math.cos(4.92459292590 + 537.0483295789 * self.t)
Y2 += 0.00000105949 * math.cos(5.84319366771 + 40.8245336761 * self.t)
Y2 += 0.00000077696 * math.cos(5.55872082952 + 77.9943614674 * self.t)
Y2 += 0.00000090798 * math.cos(0.48400254359 + 73.5409433425 * self.t)
Y2 += 0.00000067696 * math.cos(0.87599797871 + 426.8420083595 * self.t)
Y2 += 0.00000074860 * math.cos(6.15585546499 + 4.6972356084 * self.t)
Y2 += 0.00000064717 * math.cos(1.34762573111 + 34.9202727377 * self.t)
Y2 += 0.00000051378 * math.cos(1.41763897935 + 36.404745446 * self.t)
Y2 += 0.00000050205 * math.cos(5.38246230326 + 42.83027124621 * self.t)
Y2 += 0.00000040929 * math.cos(4.64969715335 + 33.9234349964 * self.t)
Y2 += 0.00000036136 * math.cos(1.44221344970 + 98.6561710411 * self.t)
Y2 += 0.00000033953 * math.cos(3.45488669371 + 1059.6257476727 * self.t)
Y2 += 0.00000034603 * math.cos(4.83781708761 + 76.0222537921 * self.t)
Y2 += 0.00000035441 * math.cos(0.92439194787 + 31.2633061205 * self.t)
Y2 += 0.00000029614 * math.cos(1.77735061850 + 28.81562556571 * self.t)
Y2 += 0.00000031027 * math.cos(3.40007815913 + 45.49040012211 * self.t)
Y2 += 0.00000035521 * math.cos(2.70107635202 + 39.3736908626 * self.t)
Y2 += 0.00000025488 * math.cos(2.47241259934 + 47.9380806769 * self.t)
Y2 += 0.00000020115 * math.cos(5.50307482336 + 1.24065522479 * self.t)
Y2 += 0.00000014328 * math.cos(1.16675266548 + 433.9555553603 * self.t)
Y2 += 0.00000015503 * math.cos(1.56080925316 + 114.6429243969 * self.t)
Y2 += 0.00000016998 * math.cos(2.50473507501 + 33.43580002939 * self.t)
Y2 += 0.00000013166 * math.cos(5.10795715214 + 419.72846135871 * self.t)
Y2 += 0.00000013053 * math.cos(1.40065469605 + 60.52313540329 * self.t)
Y2 += 0.00000010637 * math.cos(4.37252543304 + 34.1840674273 * self.t)
Y2 += 0.00000009610 * math.cos(0.08619380662 + 640.1411037975 * self.t)
Y2 += 0.00000009354 * math.cos(6.12654852334 + 42.5696388153 * self.t)
Y2 += 0.00000011447 * math.cos(1.48554252527 + 71.5688356672 * self.t)
Y2 += 0.00000008454 * math.cos(4.32641802480 + 2.7251279331 * self.t)
Y2 += 0.00000009012 * math.cos(2.87032368668 + 72.05647063421 * self.t)
Y2 += 0.00000009594 * math.cos(4.22403656438 + 69.3963417583 * self.t)
Y2 += 0.00000007419 * math.cos(1.92565712551 + 227.77000692311 * self.t)
Y2 += 0.00000006800 * math.cos(3.57170452455 + 113.15845168861 * self.t)
Y2 += 0.00000006267 * math.cos(5.50825416463 + 1066.7392946735 * self.t)
Y2 += 0.00000006895 * math.cos(2.74011142877 + 111.67397898031 * self.t)
Y2 += 0.00000005770 * math.cos(5.94492182042 + 32.4389622881 * self.t)
Y2 += 0.00000005686 * math.cos(0.66726291170 + 30.300098274 * self.t)
Y2 += 0.00000006679 * math.cos(3.28449699734 + 258.78949556011 * self.t)
Y2 += 0.00000007799 * math.cos(0.01316502615 + 7.3573644843 * self.t)
Y2 += 0.00000005906 * math.cos(4.35406299044 + 44.31474395451 * self.t)
Y2 += 0.00000005606 * math.cos(3.60862172739 + 46.4536079686 * self.t)
Y2 += 0.00000005525 * math.cos(2.04832143671 + 1052.51220067191 * self.t)
Y2 += 0.00000007257 * math.cos(4.88554087166 + 1097.7587833105 * self.t)
Y2 += 0.00000005427 * math.cos(3.37665889417 + 105.76971804189 * self.t)
Y2 += 0.00000005179 * math.cos(2.68906561571 + 515.70768857651 * self.t)
Y2 += 0.00000005163 * math.cos(1.56680359144 + 7.83293736379 * self.t)
Y2 += 0.00000004688 * math.cos(0.95059580199 + 222.14093263061 * self.t)
Y2 += 0.00000005379 * math.cos(1.15102731522 + 22.3900997655 * self.t)
Y2 += 0.00000004607 * math.cos(0.17861908533 + 549.1603035533 * self.t)
Y2 += 0.00000004101 * math.cos(1.86095686008 + 213.0552779545 * self.t)
Y2 += 0.00000004262 * math.cos(3.94315605774 + 204.9448932124 * self.t)
Y2 += 0.00000003916 * math.cos(4.92658442131 + 207.913838629 * self.t)
Y2 += 0.00000004089 * math.cos(0.26445229364 + 304.84171947829 * self.t)
Y2 += 0.00000003729 * math.cos(6.12087852262 + 199.3158189199 * self.t)
Y2 += 0.00000003680 * math.cos(3.97729685951 + 1589.3167127673 * self.t)
Y2 += 0.00000003702 * math.cos(2.58942752453 + 319.06881347989 * self.t)
Y2 += 0.00000004832 * math.cos(5.97662492227 + 215.0273856298 * self.t)
Y2 += 0.00000003474 * math.cos(5.88640441483 + 103.3365917021 * self.t)
Y2 += 0.00000003298 * math.cos(4.81858024415 + 544.1618765797 * self.t)
Y2 += 0.00000004521 * math.cos(1.64991198460 + 108.2173985967 * self.t)
Y2 += 0.00000003967 * math.cos(4.24856395374 + 944.7390057923 * self.t)
Y2 += 0.00000004059 * math.cos(1.44024718167 + 149.8070146181 * self.t)
Y2 += 0.00000004009 * math.cos(4.04772901629 + 533.1161763158 * self.t)
Y2 += 0.00000003288 * math.cos(3.02037527521 + 407.9344936969 * self.t)
Y2 += 0.00000003976 * math.cos(3.43142225420 + 526.7533888404 * self.t)
Y2 += 0.00000003343 * math.cos(5.37024544109 + 531.4192552864 * self.t)
Y2 += 0.00000003932 * math.cos(5.23324378146 + 91.54262404029 * self.t)
Y2 += 0.00000003478 * math.cos(4.62796796973 + 6.1817083167 * self.t)
Y2 += 0.00000002967 * math.cos(5.75717546362 + 860.55374623631 * self.t)
Y2 += 0.00000003058 * math.cos(1.59562573237 + 342.9747551161 * self.t)
Y2 += 0.00000003974 * math.cos(3.61989902199 + 335.8612081153 * self.t)
Y2 += 0.00000002849 * math.cos(2.43690877786 + 666.4801717735 * self.t)
Y2 += 0.00000002999 * math.cos(2.84954389869 + 937.62545879149 * self.t)
Y2 += 0.00000003008 * math.cos(0.45545092573 + 74.53778108379 * self.t)
Y2 += 0.00000003080 * math.cos(4.61982032828 + 129.6756596781 * self.t)
Y2 += 0.00000003346 * math.cos(3.07224007183 + 1162.7185218913 * self.t)
Y2 += 0.00000002625 * math.cos(3.26539092131 + 273.8222308413 * self.t)
Y2 += 0.00000002931 * math.cos(3.14888688193 + 235.68919520349 * self.t)
Y2 += 0.00000002579 * math.cos(5.19712816213 + 1073.85284167431 * self.t)
Y2 += 0.00000002550 * math.cos(1.43127384605 + 26.58288545949 * self.t)
Y2 += 0.00000002542 * math.cos(2.65218049337 + 1265.81129610991 * self.t)
Y2 += 0.00000002483 * math.cos(3.30358671055 + 453.1810763355 * self.t)
Y2 += 0.00000002732 * math.cos(3.33706438099 + 563.38739755489 * self.t)
Y2 += 0.00000002508 * math.cos(0.10584642422 + 37.8555882595 * self.t)
Y2 += 0.00000002508 * math.cos(5.05315792539 + 425.35753565121 * self.t)
Y2 += 0.00000002680 * math.cos(1.03370719327 + 454.6655490438 * self.t)
Y2 += 0.00000002511 * math.cos(1.57939297348 + 209.6107596584 * self.t)
Y2 += 0.00000002512 * math.cos(0.17397391459 + 217.4750661846 * self.t)
Y2 += 0.00000002552 * math.cos(4.09952672426 + 79.47883417571 * self.t)
Y2 += 0.00000002457 * math.cos(1.09953412303 + 38.89811798311 * self.t)
Y2 += 0.00000002343 * math.cos(3.50679449028 + 981.3875687218 * self.t)
Y2 += 0.00000002501 * math.cos(3.24491806395 + 669.4009330803 * self.t)
Y2 += 0.00000002330 * math.cos(2.37985529884 + 38.32866901151 * self.t)
Y2 += 0.00000002327 * math.cos(5.10713891298 + 38.4250372311 * self.t)
Y2 += 0.00000002481 * math.cos(0.85514029866 + 655.1738390787 * self.t)
Y2 += 0.00000002569 * math.cos(2.65544269508 + 464.97504399731 * self.t)
# Neptune_Y3 (t) // 37 terms of order 3
Y3 = 0
Y3 += 0.00000985355 * math.cos(5.40479271994 + 38.3768531213 * self.t)
Y3 += 0.00000482798 * math.cos(2.40351592403 + 37.88921815429 * self.t)
Y3 += 0.00000416447 * math.cos(5.08276459732 + 0.2438174835 * self.t)
Y3 += 0.00000303825 * math.cos(5.25036318156 + 39.86132582961 * self.t)
Y3 += 0.00000089203 * math.cos(6.23576998030 + 36.892380413 * self.t)
Y3 += 0.00000070862 * math.cos(4.26820111330 + 76.50988875911 * self.t)
Y3 += 0.00000028900 * math.cos(4.07922314280 + 41.3457985379 * self.t)
Y3 += 0.00000022279 * math.cos(1.38807052555 + 206.42936592071 * self.t)
Y3 += 0.00000021480 * math.cos(0.30279640762 + 220.6564599223 * self.t)
Y3 += 0.00000016157 * math.cos(4.26502283154 + 522.8212355773 * self.t)
Y3 += 0.00000015714 * math.cos(3.19639937559 + 537.0483295789 * self.t)
Y3 += 0.00000011404 * math.cos(0.68881522230 + 35.40790770471 * self.t)
Y3 += 0.00000013199 * math.cos(4.77296321336 + 7.3573644843 * self.t)
Y3 += 0.00000007024 * math.cos(5.41129077346 + 3.21276290011 * self.t)
Y3 += 0.00000006772 * math.cos(5.90918041474 + 69.3963417583 * self.t)
Y3 += 0.00000004517 * math.cos(1.71813394760 + 45.49040012211 * self.t)
Y3 += 0.00000004523 * math.cos(2.61625996387 + 31.2633061205 * self.t)
Y3 += 0.00000003682 * math.cos(3.04341607939 + 98.6561710411 * self.t)
Y3 += 0.00000003656 * math.cos(2.17226292493 + 968.64494742849 * self.t)
Y3 += 0.00000003927 * math.cos(5.25979459691 + 426.8420083595 * self.t)
Y3 += 0.00000003199 * math.cos(3.24406648940 + 1519.6765535255 * self.t)
Y3 += 0.00000003498 * math.cos(4.84556329465 + 407.9344936969 * self.t)
Y3 += 0.00000003304 * math.cos(3.81825313228 + 422.1615876985 * self.t)
Y3 += 0.00000003331 * math.cos(3.54124873059 + 36.404745446 * self.t)
Y3 += 0.00000003244 * math.cos(4.42247914038 + 484.2005649725 * self.t)
Y3 += 0.00000002689 * math.cos(5.61171743826 + 441.06910236111 * self.t)
Y3 += 0.00000003247 * math.cos(3.33592493083 + 498.42765897409 * self.t)
Y3 += 0.00000002651 * math.cos(2.02749548795 + 304.84171947829 * self.t)
Y3 += 0.00000002645 * math.cos(0.90433895865 + 461.77909604459 * self.t)
Y3 += 0.00000002542 * math.cos(1.05108120438 + 444.5830566264 * self.t)
Y3 += 0.00000002524 * math.cos(5.46978523129 + 433.9555553603 * self.t)
Y3 += 0.00000002472 * math.cos(0.92177286185 + 319.06881347989 * self.t)
Y3 += 0.00000002355 * math.cos(2.03272387563 + 447.552002043 * self.t)
Y3 += 0.00000002876 * math.cos(3.65433810175 + 853.4401992355 * self.t)
Y3 += 0.00000002279 * math.cos(6.20789133449 + 458.810150628 * self.t)
Y3 += 0.00000002147 * math.cos(1.06531556689 + 175.40987728371 * self.t)
Y3 += 0.00000002637 * math.cos(2.06613866653 + 73.5409433425 * self.t)
# Neptune_Y4 (t) // 14 terms of order 4
Y4 = 0
Y4 += 0.00003455306 * math.cos(2.04385259535 + 38.3768531213 * self.t)
Y4 += 0.00000047405 * math.cos(0.64311364094 + 0.2438174835 * self.t)
Y4 += 0.00000021936 * math.cos(4.30052120876 + 37.88921815429 * self.t)
Y4 += 0.00000015596 * math.cos(0.30774488881 + 76.50988875911 * self.t)
Y4 += 0.00000017186 * math.cos(3.96705739007 + 39.86132582961 * self.t)
Y4 += 0.00000017459 * math.cos(3.25820107685 + 36.892380413 * self.t)
Y4 += 0.00000004229 * math.cos(6.14484758916 + 515.70768857651 * self.t)
Y4 += 0.00000004334 * math.cos(3.84568484898 + 433.9555553603 * self.t)
Y4 += 0.00000003547 * math.cos(1.04322259069 + 989.98558843089 * self.t)
Y4 += 0.00000003155 * math.cos(0.14083942013 + 467.40817033709 * self.t)
Y4 += 0.00000003017 * math.cos(4.77718347184 + 227.77000692311 * self.t)
Y4 += 0.00000002981 * math.cos(5.01159762849 + 1.7282901918 * self.t)
Y4 += 0.00000002295 * math.cos(4.84988240730 + 220.6564599223 * self.t)
Y4 += 0.00000002296 * math.cos(3.13566627364 + 206.42936592071 * self.t)
# Neptune_Y5 (t) // 1 term of order 5
Y5 = 0
Y5 += 0.00000026291 * math.cos(2.14645097520 + 38.3768531213 * self.t)
Y = ( Y0+
Y1*self.t+
Y2*self.t*self.t+
Y3*self.t*self.t*self.t+
Y4*self.t*self.t*self.t*self.t+
Y5*self.t*self.t*self.t*self.t*self.t)
# Neptune_Z0 (t) // 133 terms of order 0
Z0 = 0
Z0 += 0.92866054405 * math.cos(1.44103930278 + 38.1330356378 * self.t)
Z0 += 0.01245978462
Z0 += 0.00474333567 * math.cos(2.52218774238 + 36.6485629295 * self.t)
Z0 += 0.00451987936 * math.cos(3.50949720541 + 39.6175083461 * self.t)
Z0 += 0.00417558068 * math.cos(5.91310695421 + 76.2660712756 * self.t)
Z0 += 0.00084104329 * math.cos(4.38928900096 + 1.4844727083 * self.t)
Z0 += 0.00032704958 * math.cos(1.52048692001 + 74.7815985673 * self.t)
Z0 += 0.00030873335 * math.cos(3.29017611456 + 35.1640902212 * self.t)
Z0 += 0.00025812584 * math.cos(3.19303128782 + 2.9689454166 * self.t)
Z0 += 0.00016865319 * math.cos(2.13251104425 + 41.1019810544 * self.t)
Z0 += 0.00011789909 * math.cos(3.60001877675 + 213.299095438 * self.t)
Z0 += 0.00009770125 * math.cos(2.80133971586 + 73.297125859 * self.t)
Z0 += 0.00011279680 * math.cos(3.55816676334 + 529.6909650946 * self.t)
Z0 += 0.00004119873 * math.cos(1.67934316836 + 77.7505439839 * self.t)
Z0 += 0.00002818034 * math.cos(4.10661077794 + 114.3991069134 * self.t)
Z0 += 0.00002868677 * math.cos(4.27011526203 + 33.6796175129 * self.t)
Z0 += 0.00002213464 * math.cos(1.96045135168 + 4.4534181249 * self.t)
Z0 += 0.00001865650 * math.cos(5.05540709577 + 71.8126531507 * self.t)
Z0 += 0.00000840177 * math.cos(0.94268885160 + 42.5864537627 * self.t)
Z0 += 0.00000457516 * math.cos(5.71650412080 + 108.4612160802 * self.t)
Z0 += 0.00000530252 * math.cos(0.85800267793 + 111.4301614968 * self.t)
Z0 += 0.00000490859 * math.cos(6.07827301209 + 112.9146342051 * self.t)
Z0 += 0.00000331254 * math.cos(0.29304964526 + 70.3281804424 * self.t)
Z0 += 0.00000330045 * math.cos(2.83839676215 + 426.598190876 * self.t)
Z0 += 0.00000273589 * math.cos(3.91013681794 + 1059.3819301892 * self.t)
Z0 += 0.00000277586 * math.cos(1.45092010545 + 148.0787244263 * self.t)
Z0 += 0.00000274474 * math.cos(5.42657022437 + 32.1951448046 * self.t)
Z0 += 0.00000205306 * math.cos(0.75818737085 + 5.9378908332 * self.t)
Z0 += 0.00000173516 * math.cos(5.85498030099 + 145.1097790097 * self.t)
Z0 += 0.00000141275 * math.cos(1.73147597657 + 28.5718080822 * self.t)
Z0 += 0.00000139093 * math.cos(1.67466701191 + 184.7272873558 * self.t)
Z0 += 0.00000143647 * math.cos(2.51620047812 + 37.611770776 * self.t)
Z0 += 0.00000136955 * math.cos(0.20339778664 + 79.2350166922 * self.t)
Z0 += 0.00000126296 * math.cos(4.40661385040 + 37.1698277913 * self.t)
Z0 += 0.00000120906 * math.cos(1.61767636602 + 39.0962434843 * self.t)
Z0 += 0.00000111761 * math.cos(6.20948230785 + 98.8999885246 * self.t)
Z0 += 0.00000140758 * math.cos(3.50944989694 + 38.6543004996 * self.t)
Z0 += 0.00000111589 * math.cos(4.18561395578 + 47.6942631934 * self.t)
Z0 += 0.00000133509 * math.cos(4.78977105547 + 38.084851528 * self.t)
Z0 += 0.00000102622 * math.cos(0.81673762159 + 4.192785694 * self.t)
Z0 += 0.00000133292 * math.cos(1.23386935925 + 38.1812197476 * self.t)
Z0 += 0.00000098771 * math.cos(0.72335005782 + 106.9767433719 * self.t)
Z0 += 0.00000093919 * math.cos(0.56607810948 + 206.1855484372 * self.t)
Z0 += 0.00000081727 * math.cos(3.47861315258 + 220.4126424388 * self.t)
Z0 += 0.00000074559 * math.cos(2.31518880439 + 312.1990839626 * self.t)
Z0 += 0.00000074401 * math.cos(5.99935727164 + 181.7583419392 * self.t)
Z0 += 0.00000073141 * math.cos(1.80069951634 + 137.0330241624 * self.t)
Z0 += 0.00000066838 * math.cos(1.87185330904 + 221.3758502853 * self.t)
Z0 += 0.00000058303 * math.cos(5.61662561548 + 35.685355083 * self.t)
Z0 += 0.00000051685 * math.cos(6.02831347649 + 44.070926471 * self.t)
Z0 += 0.00000051928 * math.cos(0.40473854286 + 40.5807161926 * self.t)
Z0 += 0.00000048182 * math.cos(2.97141991737 + 37.8724032069 * self.t)
Z0 += 0.00000049439 * math.cos(1.66178905717 + 68.8437077341 * self.t)
Z0 += 0.00000047742 * math.cos(3.05261105371 + 38.3936680687 * self.t)
Z0 += 0.00000046428 * math.cos(2.66596739242 + 146.594251718 * self.t)
Z0 += 0.00000050936 * math.cos(0.19994012329 + 30.0562807905 * self.t)
Z0 += 0.00000041127 * math.cos(6.05239303825 + 115.8835796217 * self.t)
Z0 += 0.00000055537 * math.cos(2.11977296055 + 109.9456887885 * self.t)
Z0 += 0.00000041357 * math.cos(0.86667380713 + 143.6253063014 * self.t)
Z0 += 0.00000044492 * math.cos(6.00613878606 + 149.5631971346 * self.t)
Z0 += 0.00000037856 * math.cos(5.19945796177 + 72.0732855816 * self.t)
Z0 += 0.00000047361 * math.cos(3.58964541604 + 38.0211610532 * self.t)
Z0 += 0.00000034690 * math.cos(1.47398766326 + 8.0767548473 * self.t)
Z0 += 0.00000037349 * math.cos(5.15067903040 + 33.9402499438 * self.t)
Z0 += 0.00000034386 * math.cos(6.15246630929 + 218.4069048687 * self.t)
Z0 += 0.00000047180 * math.cos(2.43405967107 + 38.2449102224 * self.t)
Z0 += 0.00000033382 * math.cos(0.88396990078 + 42.3258213318 * self.t)
Z0 += 0.00000040753 * math.cos(3.59668759304 + 522.5774180938 * self.t)
Z0 += 0.00000033071 * math.cos(2.02572550598 + 258.0244132148 * self.t)
Z0 += 0.00000038849 * math.cos(5.79294381756 + 46.2097904851 * self.t)
Z0 += 0.00000031716 * math.cos(0.30412624027 + 536.8045120954 * self.t)
Z0 += 0.00000027605 * math.cos(2.81540405940 + 183.2428146475 * self.t)
Z0 += 0.00000024616 * math.cos(0.40597272412 + 30.7106720963 * self.t)
Z0 += 0.00000021716 * math.cos(0.90792314747 + 175.1660598002 * self.t)
Z0 += 0.00000021634 * math.cos(3.25469228647 + 388.4651552382 * self.t)
Z0 += 0.00000020384 * math.cos(5.80954414865 + 7.4223635415 * self.t)
Z0 += 0.00000018640 * math.cos(1.06424642993 + 180.2738692309 * self.t)
Z0 += 0.00000016716 * math.cos(0.02332590259 + 255.0554677982 * self.t)
Z0 += 0.00000018790 * math.cos(0.62408059806 + 35.212274331 * self.t)
Z0 += 0.00000016990 * math.cos(2.19726523790 + 294.6729761443 * self.t)
Z0 += 0.00000016083 * math.cos(4.20629091415 + 0.9632078465 * self.t)
Z0 += 0.00000021571 * math.cos(2.39337706760 + 152.5321425512 * self.t)
Z0 += 0.00000017102 * math.cos(5.39964889794 + 41.0537969446 * self.t)
Z0 += 0.00000014503 * math.cos(4.66614523797 + 110.2063212194 * self.t)
Z0 += 0.00000015218 * math.cos(2.93182248771 + 219.891377577 * self.t)
Z0 += 0.00000014757 * math.cos(2.02029526083 + 105.4922706636 * self.t)
Z0 += 0.00000013303 * math.cos(2.09362099250 + 639.897286314 * self.t)
Z0 += 0.00000013582 * math.cos(0.99222619680 + 44.7253177768 * self.t)
Z0 += 0.00000011309 * math.cos(4.15253392707 + 487.3651437628 * self.t)
Z0 += 0.00000012521 * math.cos(0.41449986025 + 186.2117600641 * self.t)
Z0 += 0.00000012363 * math.cos(3.07599476497 + 6.592282139 * self.t)
Z0 += 0.00000010825 * math.cos(4.13817476053 + 0.5212648618 * self.t)
Z0 += 0.00000014304 * math.cos(5.15644933777 + 31.5407534988 * self.t)
Z0 += 0.00000010056 * math.cos(4.27077049743 + 1589.0728952838 * self.t)
Z0 += 0.00000009355 * math.cos(1.23360360711 + 216.9224321604 * self.t)
Z0 += 0.00000008774 * math.cos(5.77195684843 + 12.5301729722 * self.t)
Z0 += 0.00000008445 * math.cos(0.17584724644 + 291.7040307277 * self.t)
Z0 += 0.00000008927 * math.cos(2.36869187243 + 331.3215390738 * self.t)
Z0 += 0.00000009613 * math.cos(0.28151591238 + 60.7669528868 * self.t)
Z0 += 0.00000008279 * math.cos(5.72084525545 + 36.7604375141 * self.t)
Z0 += 0.00000009111 * math.cos(3.49027191661 + 45.2465826386 * self.t)
Z0 += 0.00000008178 * math.cos(0.25637861075 + 39.5056337615 * self.t)
Z0 += 0.00000008598 * math.cos(3.10287346009 + 256.5399405065 * self.t)
Z0 += 0.00000009489 * math.cos(4.94205919676 + 151.0476698429 * self.t)
Z0 += 0.00000008564 * math.cos(2.15904622462 + 274.0660483248 * self.t)
Z0 += 0.00000007474 * math.cos(2.93279436008 + 27.0873353739 * self.t)
Z0 += 0.00000007944 * math.cos(0.38277699900 + 10213.285546211 * self.t)
Z0 += 0.00000007132 * math.cos(1.50971234331 + 944.9828232758 * self.t)
Z0 += 0.00000009005 * math.cos(0.07284074730 + 419.4846438752 * self.t)
Z0 += 0.00000007642 * math.cos(5.56097006597 + 187.6962327724 * self.t)
Z0 += 0.00000007705 * math.cos(1.54152595157 + 84.3428261229 * self.t)
Z0 += 0.00000006896 * math.cos(4.71453324740 + 406.1031376411 * self.t)
Z0 += 0.00000007282 * math.cos(5.81348163927 + 316.3918696566 * self.t)
Z0 += 0.00000006215 * math.cos(5.27967153537 + 7.1135470008 * self.t)
Z0 += 0.00000006090 * math.cos(4.48506819561 + 415.2918581812 * self.t)
Z0 += 0.00000006316 * math.cos(0.59502514374 + 453.424893819 * self.t)
Z0 += 0.00000006177 * math.cos(5.20115334051 + 80.7194894005 * self.t)
Z0 += 0.00000006324 * math.cos(2.18406254461 + 142.1408335931 * self.t)
Z0 += 0.00000005646 * math.cos(0.76840537906 + 11.0457002639 * self.t)
Z0 += 0.00000006102 * math.cos(5.58764378724 + 662.531203563 * self.t)
Z0 += 0.00000005334 * math.cos(4.52703538458 + 103.0927742186 * self.t)
Z0 += 0.00000006269 * math.cos(1.95162790177 + 605.9570363702 * self.t)
Z0 += 0.00000005591 * math.cos(5.20631788297 + 14.0146456805 * self.t)
Z0 += 0.00000004914 * math.cos(1.39906038110 + 253.5709950899 * self.t)
Z0 += 0.00000004519 * math.cos(2.07610590431 + 2042.4977891028 * self.t)
Z0 += 0.00000005681 * math.cos(4.80791039970 + 641.1211265914 * self.t)
Z0 += 0.00000006294 * math.cos(0.56936923702 + 31.019488637 * self.t)
Z0 += 0.00000004758 * math.cos(2.54312258712 + 367.9701020033 * self.t)
Z0 += 0.00000004406 * math.cos(0.33696669222 + 328.3525936572 * self.t)
Z0 += 0.00000004390 * math.cos(5.08949604858 + 286.596221297 * self.t)
Z0 += 0.00000004678 * math.cos(4.87546696295 + 442.7517005706 * self.t)
Z0 += 0.00000004407 * math.cos(5.58110402011 + 252.0865223816 * self.t)
Z0 += 0.00000004305 * math.cos(1.31724140028 + 493.0424021651 * self.t)
# Neptune_Z1 (t) // 61 terms of order 1
Z1 = 0
Z1 += 0.06832633707 * math.cos(3.80782656293 + 38.1330356378 * self.t)
Z1 -= 0.00064598028
Z1 += 0.00042738331 * math.cos(4.82540335637 + 36.6485629295 * self.t)
Z1 += 0.00031421638 * math.cos(6.08083255385 + 39.6175083461 * self.t)
Z1 += 0.00027088623 * math.cos(1.97557659098 + 76.2660712756 * self.t)
Z1 += 0.00005924197 * math.cos(0.48500737803 + 1.4844727083 * self.t)
Z1 += 0.00002429056 * math.cos(3.86784381378 + 74.7815985673 * self.t)
Z1 += 0.00002107258 * math.cos(6.19720726581 + 35.1640902212 * self.t)
Z1 += 0.00001644542 * math.cos(5.76041185818 + 2.9689454166 * self.t)
Z1 += 0.00001059588 * math.cos(4.89687990866 + 41.1019810544 * self.t)
Z1 += 0.00001084464 * math.cos(5.33722455731 + 213.299095438 * self.t)
Z1 += 0.00000880611 * math.cos(5.70150456912 + 529.6909650946 * self.t)
Z1 += 0.00000824125 * math.cos(5.04137560987 + 73.297125859 * self.t)
Z1 += 0.00000250821 * math.cos(4.25953295692 + 77.7505439839 * self.t)
Z1 += 0.00000158517 * math.cos(0.13500997625 + 114.3991069134 * self.t)
Z1 += 0.00000129390 * math.cos(4.76999039957 + 4.4534181249 * self.t)
Z1 += 0.00000105033 * math.cos(0.99234583035 + 33.6796175129 * self.t)
Z1 += 0.00000054734 * math.cos(3.96812588022 + 42.5864537627 * self.t)
Z1 += 0.00000034799 * math.cos(4.30403521625 + 37.611770776 * self.t)
Z1 += 0.00000041340 * math.cos(2.29314729799 + 206.1855484372 * self.t)
Z1 += 0.00000028374 * math.cos(1.67853213747 + 111.4301614968 * self.t)
Z1 += 0.00000025340 * math.cos(1.70015942799 + 220.4126424388 * self.t)
Z1 += 0.00000026021 * math.cos(6.09040669128 + 426.598190876 * self.t)
Z1 += 0.00000027198 * math.cos(5.95188476775 + 71.8126531507 * self.t)
Z1 += 0.00000021598 * math.cos(2.17619854748 + 112.9146342051 * self.t)
Z1 += 0.00000025154 * math.cos(4.13631230281 + 28.5718080822 * self.t)
Z1 += 0.00000020543 * math.cos(1.56946393801 + 38.6543004996 * self.t)
Z1 += 0.00000017216 * math.cos(2.81703507859 + 98.8999885246 * self.t)
Z1 += 0.00000019926 * math.cos(3.15301554161 + 108.4612160802 * self.t)
Z1 += 0.00000015544 * math.cos(2.07364839388 + 40.5807161926 * self.t)
Z1 += 0.00000015357 * math.cos(5.45891321516 + 522.5774180938 * self.t)
Z1 += 0.00000012266 * math.cos(3.82427247378 + 5.9378908332 * self.t)
Z1 += 0.00000013587 * math.cos(1.34795861192 + 47.6942631934 * self.t)
Z1 += 0.00000010839 * math.cos(4.75461825384 + 536.8045120954 * self.t)
Z1 += 0.00000010785 * math.cos(2.61566414257 + 79.2350166922 * self.t)
Z1 += 0.00000010916 * math.cos(3.88744647444 + 35.685355083 * self.t)
Z1 += 0.00000009833 * math.cos(3.62341506247 + 38.1812197476 * self.t)
Z1 += 0.00000009849 * math.cos(0.89613145346 + 38.084851528 * self.t)
Z1 += 0.00000009317 * math.cos(0.51297445145 + 37.1698277913 * self.t)
Z1 += 0.00000008955 * math.cos(4.00532631258 + 39.0962434843 * self.t)
Z1 += 0.00000007089 * math.cos(2.29610703652 + 137.0330241624 * self.t)
Z1 += 0.00000007573 * math.cos(3.20619266484 + 4.192785694 * self.t)
Z1 += 0.00000008063 * math.cos(5.86511590361 + 1059.3819301892 * self.t)
Z1 += 0.00000007655 * math.cos(3.39616255650 + 145.1097790097 * self.t)
Z1 += 0.00000006061 * math.cos(2.31235275416 + 109.9456887885 * self.t)
Z1 += 0.00000005726 * math.cos(6.23400745185 + 312.1990839626 * self.t)
Z1 += 0.00000003739 * math.cos(2.50010254963 + 30.0562807905 * self.t)
Z1 += 0.00000004145 * math.cos(2.00938305966 + 44.070926471 * self.t)
Z1 += 0.00000003480 * math.cos(5.88971113590 + 38.0211610532 * self.t)
Z1 += 0.00000003467 * math.cos(4.73412534395 + 38.2449102224 * self.t)
Z1 += 0.00000004736 * math.cos(6.28313624461 + 149.5631971346 * self.t)
Z1 += 0.00000003905 * math.cos(4.49400805134 + 106.9767433719 * self.t)
Z1 += 0.00000002982 * math.cos(1.80386443362 + 46.2097904851 * self.t)
Z1 += 0.00000003538 * math.cos(5.27114846878 + 37.8724032069 * self.t)
Z1 += 0.00000003508 * math.cos(5.35267669439 + 38.3936680687 * self.t)
Z1 += 0.00000002821 * math.cos(1.10242173566 + 33.9402499438 * self.t)
Z1 += 0.00000003150 * math.cos(2.14792830412 + 115.8835796217 * self.t)
Z1 += 0.00000003329 * math.cos(3.56226463770 + 181.7583419392 * self.t)
Z1 += 0.00000002787 * math.cos(1.21334651843 + 72.0732855816 * self.t)
Z1 += 0.00000002453 * math.cos(3.18401661435 + 42.3258213318 * self.t)
Z1 += 0.00000002523 * math.cos(5.51669920239 + 8.0767548473 * self.t)
# Neptune_Z2 (t) // 20 terms of order 2
Z2 = 0
Z2 += 0.00291361164 * math.cos(5.57085222635 + 38.1330356378 * self.t)
Z2 += 0.00002207820 * math.cos(0.45423510946 + 36.6485629295 * self.t)
Z2 -= 0.00002644401
Z2 += 0.00001184984 * math.cos(3.62696666572 + 76.2660712756 * self.t)
Z2 += 0.00000875873 * math.cos(1.60783110298 + 39.6175083461 * self.t)
Z2 += 0.00000253280 * math.cos(2.25499665308 + 1.4844727083 * self.t)
Z2 += 0.00000139875 * math.cos(1.66224942942 + 35.1640902212 * self.t)
Z2 += 0.00000105837 * math.cos(5.61746558118 + 74.7815985673 * self.t)
Z2 += 0.00000055479 * math.cos(0.51417309302 + 213.299095438 * self.t)
Z2 += 0.00000051858 * math.cos(1.20450519900 + 2.9689454166 * self.t)
Z2 += 0.00000040183 * math.cos(1.45604293605 + 529.6909650946 * self.t)
Z2 += 0.00000041153 * math.cos(0.64158589676 + 73.297125859 * self.t)
Z2 += 0.00000013931 * math.cos(0.27428875486 + 41.1019810544 * self.t)
Z2 += 0.00000009181 * math.cos(2.83312722213 + 33.6796175129 * self.t)
Z2 += 0.00000007421 * math.cos(4.32019600438 + 206.1855484372 * self.t)
Z2 += 0.00000006998 * math.cos(5.87666052849 + 77.7505439839 * self.t)
Z2 += 0.00000007085 * math.cos(1.66037085233 + 71.8126531507 * self.t)
Z2 += 0.00000006818 * math.cos(1.56386946094 + 114.3991069134 * self.t)
Z2 += 0.00000004838 * math.cos(0.83470875824 + 220.4126424388 * self.t)
Z2 += 0.00000002545 * math.cos(0.43712705655 + 4.4534181249 * self.t)
# Neptune_Z3 (t) // 8 terms of order 3
Z3 = 0
Z3 += 0.00008221290 * math.cos(1.01632472042 + 38.1330356378 * self.t)
Z3 += 0.00000103933
Z3 += 0.00000070154 * math.cos(2.36502685986 + 36.6485629295 * self.t)
Z3 += 0.00000031617 * math.cos(5.35266161292 + 76.2660712756 * self.t)
Z3 += 0.00000015470 * math.cos(3.21170859085 + 39.6175083461 * self.t)
Z3 += 0.00000007111 * math.cos(3.99067059016 + 1.4844727083 * self.t)
Z3 += 0.00000004656 * math.cos(3.62376309338 + 35.1640902212 * self.t)
Z3 += 0.00000002988 * math.cos(1.03727330540 + 74.7815985673 * self.t)
# Neptune_Z4 (t) // 1 term of order 4
Z4 = 0
Z4 += 0.00000172227 * math.cos(2.66872693322 + 38.1330356378 * self.t)
# Neptune_Z5 (t) // 1 term of order 5
Z5 = 0
Z5 += 0.00000003394 * math.cos(4.70646877989 + 38.1330356378 * self.t)
Z = ( Z0+
Z1*self.t+
Z2*self.t*self.t+
Z3*self.t*self.t*self.t+
Z4*self.t*self.t*self.t*self.t+
Z5*self.t*self.t*self.t*self.t*self.t)
return (X, Y, Z)<|fim▁end|>
| |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>use anyhow::Context;
use argh::FromArgs;
use engine::{Config, Processor};
use tokio::{fs::File, io::AsyncReadExt};
use tracing::{event, instrument, Level};
use tracing_subscriber::EnvFilter;
<|fim▁hole|>/// A simple site generator :)
struct Args {
#[argh(switch)]
/// forces rebuild
force: bool,
#[argh(positional)]
/// path to config file
config_filename: std::path::PathBuf,
}
#[instrument]
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args = argh::from_env::<Args>();
let format = tracing_subscriber::fmt::format().pretty();
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.event_format(format)
.init();
event!(Level::INFO, input_filename = ?args.config_filename);
let cfg = {
let mut f = File::open(&args.config_filename).await?;
let mut s = String::new();
f.read_to_string(&mut s).await?;
Ok::<_, anyhow::Error>(toml::from_str::<Config>(&s)?)
}?
.resolve(
&args
.config_filename
.parent()
.context("Parent folder of config file")?,
);
event!(Level::DEBUG, config = ?cfg);
let processor = Processor::new(cfg)?;
processor.render_toplevel(args.force).await?;
Ok(())
}<|fim▁end|>
|
#[derive(FromArgs)]
|
<|file_name|>urls.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url, include
import spirit.comment.bookmark.urls
import spirit.comment.flag.urls
import spirit.comment.history.urls
import spirit.comment.like.urls
from . import views
urlpatterns = [
url(r'^(?P<topic_id>\d+)/publish/$', views.publish, name='publish'),
url(r'^(?P<topic_id>\d+)/publish/(?P<pk>\d+)/quote/$', views.publish, name='publish'),
url(r'^(?P<pk>\d+)/update/$', views.update, name='update'),
url(r'^(?P<pk>\d+)/find/$', views.find, name='find'),
url(r'^(?P<topic_id>\d+)/move/$', views.move, name='move'),
url(r'^(?P<pk>\d+)/delete/$', views.delete, name='delete'),
url(r'^(?P<pk>\d+)/undelete/$', views.delete, kwargs={'remove': False, }, name='undelete'),<|fim▁hole|> url(r'^flag/', include(spirit.comment.flag.urls, namespace='flag')),
url(r'^history/', include(spirit.comment.history.urls, namespace='history')),
url(r'^like/', include(spirit.comment.like.urls, namespace='like')),
]<|fim▁end|>
|
url(r'^upload/$', views.image_upload_ajax, name='image-upload-ajax'),
url(r'^bookmark/', include(spirit.comment.bookmark.urls, namespace='bookmark')),
|
<|file_name|>utils.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.utils import six
from sortedone2many.fields import SortedOneToManyField
def inject_extra_field_to_model(from_model, field_name, field):
if not isinstance(from_model, six.string_types):
field.contribute_to_class(from_model, field_name)
return
raise Exception('from_model must be a Model Class')
# app_label, model_name = from_model.split('.')
# from django.apps import apps
# try:
# from_model_cls = apps.get_registered_model(app_label, model_name)
# field.contribute_to_class(from_model_cls, field_name)
# except:
# from django.db.models.signals import class_prepared
# def add_field(sender, **kwargs):
# if sender.__name__ == model_name and sender._meta.app_label == app_label:
# field.contribute_to_class(sender, field_name)<|fim▁hole|>
def add_sorted_one2many_relation(model_one,
model_many,
field_name_on_model_one=None,
related_name_on_model_many=None):
field_name = field_name_on_model_one or model_many._meta.model_name + '_set'
related_name = related_name_on_model_many or model_one._meta.model_name
field = SortedOneToManyField(model_many, related_name=related_name)
field.contribute_to_class(model_one, field_name)<|fim▁end|>
|
# # TODO: `add_field` is never called. `class_prepared` already fired or never fire??
# class_prepared.connect(add_field)
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>/*
* Panopticon - A libre disassembler
* Copyright (C) 2014, 2015 Panopticon authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//! MOS 6502 disassembler.
//!
//! This disassembler handles all documented opcode of the MOS Technology 6502 microprocessor.
#![allow(missing_docs)]
#[macro_use]
extern crate log;
#[macro_use]
extern crate panopticon_core;
#[macro_use]<|fim▁hole|>
extern crate byteorder;
mod syntax;
mod semantic;
mod disassembler;
pub use crate::disassembler::{Mos, Variant};<|fim▁end|>
|
extern crate lazy_static;
|
<|file_name|>MainActivity.java<|end_file_name|><|fim▁begin|>/*
* Copyright (c) by Michał Niedźwiecki 2016
* Contact: nkg753 on gmail or via GitHub profile: dzwiedziu-nkg
*
* This file is part of Bike Road Quality.
*
* Bike Road Quality is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Bike Road Quality 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package pl.nkg.brq.android.ui;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;<|fim▁hole|>
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pl.nkg.brq.android.R;
import pl.nkg.brq.android.events.SensorsRecord;
import pl.nkg.brq.android.events.SensorsServiceState;
import pl.nkg.brq.android.services.SensorsService;
public class MainActivity extends AppCompatActivity {
private static final int MY_PERMISSION_RESPONSE = 29;
@Bind(R.id.button_on)
Button mButtonOn;
@Bind(R.id.button_off)
Button mButtonOff;
@Bind(R.id.speedTextView)
TextView mSpeedTextView;
@Bind(R.id.altitudeTextView)
TextView mAltitudeTextView;
@Bind(R.id.shakeTextView)
TextView mShakeTextView;
@Bind(R.id.noiseTextView)
TextView mNoiseTextView;
@Bind(R.id.distanceTextView)
TextView mDistanceTextView;
@Bind(R.id.warningTextView)
TextView mWarningTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Prompt for permissions
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Log.w("BleActivity", "Location access not granted!");
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.BLUETOOTH},
MY_PERMISSION_RESPONSE);
}
}
ButterKnife.bind(this);
}
@Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
protected void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
@OnClick(R.id.button_on)
public void onButtonOnClick() {
startService(new Intent(MainActivity.this, SensorsService.class));
}
@OnClick(R.id.button_off)
public void onButtonOffClick() {
stopService(new Intent(MainActivity.this, SensorsService.class));
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(SensorsServiceState state) {
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(SensorsRecord record) {
mSpeedTextView.setText((int) (record.speed * 3.6) + " km/h");
mAltitudeTextView.setText((int) record.altitude + " m n.p.m.");
mShakeTextView.setText((int) (record.shake * 100) / 100.0 + " m/s²");
mNoiseTextView.setText((int) record.soundNoise + " db");
mDistanceTextView.setText((double) record.distance / 100.0 + " m");
if (record.distance < 120 && record.distance != 0) {
mWarningTextView.setVisibility(View.VISIBLE);
mWarningTextView.setText((double) record.distance / 100.0 + " m");
mWarningTextView.setTextSize(Math.min(5000 / record.distance, 100));
} else {
mWarningTextView.setVisibility(View.GONE);
}
}
}<|fim▁end|>
|
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
|
<|file_name|>proxy.go<|end_file_name|><|fim▁begin|>/*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"fmt"
"os"<|fim▁hole|> "runtime"
"k8s.io/kubernetes/cmd/kube-proxy/app"
"k8s.io/kubernetes/pkg/healthz"
"k8s.io/kubernetes/pkg/util"
"k8s.io/kubernetes/pkg/version/verflag"
"github.com/spf13/pflag"
)
func init() {
healthz.DefaultHealthz()
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
s := app.NewProxyServer()
s.AddFlags(pflag.CommandLine)
util.InitFlags()
util.InitLogs()
defer util.FlushLogs()
verflag.PrintAndExitIfRequested()
if err := s.Run(pflag.CommandLine.Args()); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
}<|fim▁end|>
| |
<|file_name|>app_config.py<|end_file_name|><|fim▁begin|>from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _<|fim▁hole|>
class ContactsAppConfig(AppConfig):
name = 'apps.contacts'
verbose_name = _('Contacts')<|fim▁end|>
| |
<|file_name|>test_oggspeex.py<|end_file_name|><|fim▁begin|>import os
import shutil
from mutagen._compat import cBytesIO
from mutagen.ogg import OggPage
from mutagen.oggspeex import OggSpeex, OggSpeexInfo, delete
from tests import add
from tests.test_ogg import TOggFileType
from tempfile import mkstemp
class TOggSpeex(TOggFileType):
Kind = OggSpeex
def setUp(self):
original = os.path.join("tests", "data", "empty.spx")
fd, self.filename = mkstemp(suffix='.ogg')
os.close(fd)
shutil.copy(original, self.filename)
self.audio = self.Kind(self.filename)
def test_module_delete(self):
delete(self.filename)<|fim▁hole|> def test_channels(self):
self.failUnlessEqual(2, self.audio.info.channels)
def test_sample_rate(self):
self.failUnlessEqual(44100, self.audio.info.sample_rate)
def test_bitrate(self):
self.failUnlessEqual(0, self.audio.info.bitrate)
def test_invalid_not_first(self):
page = OggPage(open(self.filename, "rb"))
page.first = False
self.failUnlessRaises(IOError, OggSpeexInfo, cBytesIO(page.write()))
def test_vendor(self):
self.failUnless(
self.audio.tags.vendor.startswith("Encoded with Speex 1.1.12"))
self.failUnlessRaises(KeyError, self.audio.tags.__getitem__, "vendor")
def test_not_my_ogg(self):
fn = os.path.join('tests', 'data', 'empty.oggflac')
self.failUnlessRaises(IOError, type(self.audio), fn)
self.failUnlessRaises(IOError, self.audio.save, fn)
self.failUnlessRaises(IOError, self.audio.delete, fn)
def test_multiplexed_in_headers(self):
shutil.copy(
os.path.join("tests", "data", "multiplexed.spx"), self.filename)
audio = self.Kind(self.filename)
audio.tags["foo"] = ["bar"]
audio.save()
audio = self.Kind(self.filename)
self.failUnlessEqual(audio.tags["foo"], ["bar"])
def test_mime(self):
self.failUnless("audio/x-speex" in self.audio.mime)
add(TOggSpeex)<|fim▁end|>
|
self.scan_file()
self.failIf(OggSpeex(self.filename).tags)
|
<|file_name|>views.py<|end_file_name|><|fim▁begin|>import locale
from atom.ext.guardian.views import RaisePermissionRequiredMixin
from braces.views import (
FormValidMessageMixin,
LoginRequiredMixin,
SelectRelatedMixin,
UserFormKwargsMixin,
)
from cached_property import cached_property
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.utils.encoding import force_text
from django.utils.html import mark_safe
from django.utils.timezone import now
from django.utils.translation import ugettext as _
from django.views.generic import (
ArchiveIndexView,
CreateView,
MonthArchiveView,
UpdateView,
)
from django.views.generic.list import BaseListView
from poradnia.cases.models import Case
from poradnia.keys.mixins import KeyAuthMixin
from poradnia.users.utils import PermissionMixin
from .forms import EventForm
from .models import Event
from .utils import EventCalendar
class EventCreateView(
RaisePermissionRequiredMixin, UserFormKwargsMixin, FormValidMessageMixin, CreateView
):
model = Event
form_class = EventForm
template_name = "events/form.html"
permission_required = ["cases.can_add_record"]
@cached_property
def case(self):
return get_object_or_404(Case, pk=self.kwargs["case_pk"])
def get_permission_object(self):
return self.case
def get_form_kwargs(self, *args, **kwargs):
kwargs = super().get_form_kwargs()
kwargs["case"] = self.case
return kwargs
def get_form_valid_message(self):
return _("Success added new event %(event)s") % ({"event": self.object})
class EventUpdateView(
RaisePermissionRequiredMixin, UserFormKwargsMixin, FormValidMessageMixin, UpdateView
):
model = Event
form_class = EventForm
template_name = "events/form.html"
permission_required = ["cases.can_add_record"]
def get_permission_object(self):
return self._object.case
@cached_property
def _object(self):
return super().get_object()
def get_object(self, *args, **kwargs):
return self._object
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs["case"] = self.object.case
return kwargs
def form_valid(self, form):
self.object.reminder_set.all().update(active=False)
return super().form_valid(form)
def get_form_valid_message(self):
return _("Success updated event %(event)s") % {"event": self.object}
class CalendarListView(PermissionMixin, LoginRequiredMixin, ArchiveIndexView):
model = Event
date_field = "time"
allow_future = True
date_list_period = "month"
class CalendarEventView(
PermissionMixin, SelectRelatedMixin, LoginRequiredMixin, MonthArchiveView
):
model = Event
date_field = "time"
allow_future = True
select_related = ["case", "record"]
template_name = "events/calendar.html"
def get_language_code(self):
return getattr(self.request, "LANGUAGE_CODE", settings.LANGUAGE_CODE)
def get_user_locale(self):
if self.get_language_code() in locale.locale_alias:
name = locale.locale_alias[self.get_language_code()].split(".")[0]
return (name, "UTF-8")
else:
return locale.getlocale()
def get_calendar(self):
date = (int(self.get_year()), int(self.get_month()))
cal = EventCalendar(self.object_list).formatmonth(*date)
return mark_safe(cal)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["calendar"] = self.get_calendar()
return context
class ICalendarView(KeyAuthMixin, PermissionMixin, BaseListView):
window = 1
model = Event
def get_event(self, obj):
from icalendar import Event
event = Event()
event["uid"] = obj.pk
event["dtstart"] = obj.time
event["summary"] = force_text(obj)
event["description"] = obj.text
return event
<|fim▁hole|> return [self.get_event(x) for x in self.get_queryset()]
def get_icalendar(self):
from icalendar import Calendar
cal = Calendar()
cal["summary"] = "Events for {}".format(self.request.user)
cal["dtstart"] = self.get_start()
cal["dtend"] = self.get_end()
for component in self.get_subcomponents():
cal.add_component(component)
return cal
def get_start(self):
return now() + relativedelta(months=+self.window)
def get_end(self):
return now() + relativedelta(months=-self.window)
def get_queryset(self):
qs = super().get_queryset()
qs = qs.filter(time__lt=self.get_start())
qs = qs.filter(time__gt=self.get_end())
return qs
def render_to_response(self, *args, **kwargs):
response = HttpResponse(content_type="application/force-download")
response["Content-Disposition"] = "attachment; filename=calendar.ics"
response.write(self.get_icalendar().to_ical())
return response<|fim▁end|>
|
def get_subcomponents(self):
|
<|file_name|>production.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
'''
Production Configurations
- Use djangosecure
- Use mailgun to send emails
- Use redis
'''
from __future__ import absolute_import, unicode_literals
from django.utils import six
from .common import * # noqa
# SECRET CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Raises ImproperlyConfigured exception if DJANO_SECRET_KEY not in os.environ
SECRET_KEY = env("DJANGO_SECRET_KEY")
# This ensures that Django will be able to detect a secure connection
# properly on Heroku.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# django-secure
# ------------------------------------------------------------------------------
INSTALLED_APPS += ("djangosecure", )
MIDDLEWARE_CLASSES = (
# Make sure djangosecure.middleware.SecurityMiddleware is listed first
'djangosecure.middleware.SecurityMiddleware',
) + MIDDLEWARE_CLASSES
# set this to 60 seconds and then to 518400 when you can prove it works
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True)
SECURE_FRAME_DENY = env.bool("DJANGO_SECURE_FRAME_DENY", default=True)
SECURE_CONTENT_TYPE_NOSNIFF = env.bool("DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True)
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = False
SESSION_COOKIE_HTTPONLY = True
SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True)
# SITE CONFIGURATION
# ------------------------------------------------------------------------------
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["*"]
# END SITE CONFIGURATION
# EMAIL<|fim▁hole|>EMAIL_BACKEND = 'django_mailgun.MailgunBackend'
MAILGUN_ACCESS_KEY = env('DJANGO_MAILGUN_API_KEY')
MAILGUN_SERVER_NAME = env('DJANGO_MAILGUN_SERVER_NAME')
EMAIL_SUBJECT_PREFIX = env("DJANGO_EMAIL_SUBJECT_PREFIX", default='[{{cookiecutter.project_name}}] ')
SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
# TEMPLATE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader
TEMPLATES[0]['OPTIONS']['loaders'] = [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
]),
]
# CACHE CONFIGURATION
# ------------------------------------------------------------------------------
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': [
'redis:6379',
],
'OPTIONS': {
'DB': 1,
'PARSER_CLASS': 'redis.connection.HiredisParser',
'CONNECTION_POOL_CLASS': 'redis.BlockingConnectionPool',
'CONNECTION_POOL_CLASS_KWARGS': {
'max_connections': 50,
'timeout': 20,
},
'MAX_CONNECTIONS': 1000,
'PICKLE_VERSION': -1,
},
},
}
# ASSET CONFIGURATION
# ------------------------------------------------------------------------------
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/static'
MEDIA_ROOT = '/media'
STATICFILES_DIRS = (
unicode(APPS_DIR.path("static")),
)
{% if cookiecutter.use_celery %}
# CELERY BROKER CONFIGURATION
# ------------------------------------------------------------------------------
BROKER_URL = "amqp://guest:guest@rabbitmq:5672//"
{% endif %}
{% if cookiecutter.use_sentry %}
# SENTRY CONFIGURATION
# ------------------------------------------------------------------------------
RAVEN_CONFIG = {
'dsn': env("SENTRY_URL"),
}
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
{% endif %}
# Your production stuff: Below this line define 3rd party library settings<|fim▁end|>
|
# ------------------------------------------------------------------------------
DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
default='{{cookiecutter.project_name}} <noreply@{{cookiecutter.domain_name}}>')
|
<|file_name|>helpdesk.js<|end_file_name|><|fim▁begin|>/**
* Heldesks' code (Zendesk, etc..)
*/
App.helpdesk = {
init: function () {
// fetch template content from the extension
if (window.location.hostname.indexOf('zendesk.com') !== -1) {
App.helpdesk.zendesk.init();
}
},
zendesk: {
init: function () {
// inject the zendesk script into the dom
var script = document.createElement('script');
script.type = "text/javascript";
script.src = chrome.extension.getURL("pages/helpdesk/zendesk.js");
if (document.body) {
document.body.appendChild(script);
script.onload = function () {<|fim▁hole|> }
// forward the message to the
window.addEventListener('message', function(event) {
if (event.data && event.data.request && event.data.request === 'suggestion-used') {
chrome.runtime.sendMessage({
'request': 'suggestion-used',
'data': {
'agent': {
'host': window.location.host,
'name': $('#face_box .name').text()
},
'url': window.location.href,
'template_id': event.data.template_id
}
});
}
});
var ticketUrl = "";
var ticketInterval = setInterval(function () {
if (window.location.pathname.indexOf('/agent/tickets/') !== -1) {
if (!ticketUrl || ticketUrl !== window.location.pathname) {
ticketUrl = window.location.pathname;
$('.macro-suggestions-container').remove();
var bodyInterval = setInterval(function () {
var subject = '';
var body = '';
$('.workspace').each(function (i, workspace) {
workspace = $(workspace);
if (workspace.css('display') !== 'none') {
var firstEvent = workspace.find('.event-container .event:first');
var isAgent = firstEvent.find('.user_photo').hasClass('agent');
// If it's an agent who has the last comment no point in suggesting anything
if (isAgent) {
return false;
}
subject = workspace.find('input[name=subject]').val();
body = firstEvent.find('.zd-comment').text();
}
});
if (!subject || !subject.length || !body.length) {
return;
}
clearInterval(bodyInterval);
chrome.runtime.sendMessage({
'request': 'suggestion',
'data': {
'agent': {
'host': window.location.host,
'name': $('#face_box .name').text()
},
'url': window.location.href,
'subject': subject,
'to': '',
'cc': '',
'bcc': '',
'from': '',
'body': body,
'helpdesk': 'zendesk'
}
}, function (macros) {
if (!_.size(macros)) {
return;
}
$('.macro-suggestions-container').remove();
var macroContainer = $("<div class='macro-suggestions-container'>");
for (var i in macros) {
var macro = macros[i];
var macroBtn = $("<a class='macro-suggestion'>");
var macroEl = $("<span class='macro-title'>");
/*
var scoreEl = $('<span class="macro-score"> </span>');
if (macro.score >= 0.9) {
scoreEl.addClass('macro-score-high');
}
if (macro.score >= 0.7 && macro.score < 0.9) {
scoreEl.addClass('macro-score-medium');
}
if (macro.score < 0.7) {
scoreEl.addClass('macro-score-low');
}
*/
macroBtn.attr('onclick', "gorgiasApplyMacroSuggestion(" + macro["external_id"] + ")");
macroBtn.attr('title', macro.body.replace(/\n/g, "<br />"));
macroBtn.attr('data-toggle', "tooltip");
macroBtn.attr('data-html', "true");
macroBtn.attr('data-placement', "bottom");
macroEl.html(macro.title);
macroBtn.append(macroEl);
//macroBtn.append(scoreEl);
macroContainer.append(macroBtn);
}
$('.comment_input .content .options').before(macroContainer);
});
}, 200);
}
} else {
ticketUrl = "";
}
}, 200);
}
}
};<|fim▁end|>
|
document.body.removeChild(script);
};
|
<|file_name|>submit_paste.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# -*-coding:UTF-8 -*
"""
The Submit paste module
================
This module is taking paste in redis queue ARDB_DB and submit to global
"""
##################################
# Import External packages
##################################
import os
import sys
import gzip
import io
import redis
import base64
import datetime
import time
# from sflock.main import unpack
# import sflock
sys.path.append(os.environ['AIL_BIN'])
##################################
# Import Project packages
##################################
from modules.abstract_module import AbstractModule
from packages import Tag
from lib import ConfigLoader
class SubmitPaste(AbstractModule):
"""
SubmitPaste module for AIL framework
"""
expire_time = 120
# Text max size
TEXT_MAX_SIZE = ConfigLoader.ConfigLoader().get_config_int("SubmitPaste", "TEXT_MAX_SIZE")
# File max size
FILE_MAX_SIZE = ConfigLoader.ConfigLoader().get_config_int("SubmitPaste", "FILE_MAX_SIZE")
# Allowed file type
ALLOWED_EXTENSIONS = ConfigLoader.ConfigLoader().get_config_str("SubmitPaste", "FILE_ALLOWED_EXTENSIONS").split(',')
def __init__(self):
"""
init
"""
super(SubmitPaste, self).__init__(queue_name='submit_paste')
self.r_serv_db = ConfigLoader.ConfigLoader().get_redis_conn("ARDB_DB")
self.r_serv_log_submit = ConfigLoader.ConfigLoader().get_redis_conn("Redis_Log_submit")
self.r_serv_tags = ConfigLoader.ConfigLoader().get_redis_conn("ARDB_Tags")
self.r_serv_metadata = ConfigLoader.ConfigLoader().get_redis_conn("ARDB_Metadata")
self.serv_statistics = ConfigLoader.ConfigLoader().get_redis_conn("ARDB_Statistics")
self.pending_seconds = 3
self.PASTES_FOLDER = os.path.join(os.environ['AIL_HOME'], ConfigLoader.ConfigLoader().get_config_str("Directories", "pastes")) + '/'
<|fim▁hole|> """
Main method of the Module to implement
"""
self.redis_logger.debug(f'compute UUID {uuid}')
# get temp value save on disk
ltags = self.r_serv_db.smembers(f'{uuid}:ltags')
ltagsgalaxies = self.r_serv_db.smembers(f'{uuid}:ltagsgalaxies')
paste_content = self.r_serv_db.get(f'{uuid}:paste_content')
isfile = self.r_serv_db.get(f'{uuid}:isfile')
password = self.r_serv_db.get(f'{uuid}:password')
source = self.r_serv_db.get(f'{uuid}:source')
if source in ['crawled', 'tests']:
source = 'submitted'
self.redis_logger.debug(f'isfile UUID {isfile}')
self.redis_logger.debug(f'source UUID {source}')
self.redis_logger.debug(f'paste_content UUID {paste_content}')
# needed if redis is restarted
self.r_serv_log_submit.set(f'{uuid}:end', 0)
self.r_serv_log_submit.set(f'{uuid}:processing', 0)
self.r_serv_log_submit.set(f'{uuid}:nb_total', -1)
self.r_serv_log_submit.set(f'{uuid}:nb_end', 0)
self.r_serv_log_submit.set(f'{uuid}:nb_sucess', 0)
self.r_serv_log_submit.set(f'{uuid}:processing', 1)
if isfile == 'True':
# file input
self._manage_file(uuid, paste_content, ltags, ltagsgalaxies, source)
else:
# textarea input paste
self._manage_text(uuid, paste_content, ltags, ltagsgalaxies, source)
# new paste created from file, remove uuid ref
self.remove_submit_uuid(uuid)
def run(self):
"""
Run Module endless process
"""
# Endless loop processing messages from the input queue
while self.proceed:
# Get one message (paste) from the QueueIn (copy of Redis_Global publish)
nb_submit = self.r_serv_db.scard('submitted:uuid')
if nb_submit > 0:
try:
uuid = self.r_serv_db.srandmember('submitted:uuid')
# Module processing with the message from the queue
self.redis_logger.debug(uuid)
self.compute(uuid)
except Exception as err:
self.redis_logger.error(f'Error in module {self.module_name}: {err}')
# Remove uuid ref
self.remove_submit_uuid(uuid)
else:
# Wait before next process
self.redis_logger.debug(f'{self.module_name}, waiting for new message, Idling {self.pending_seconds}s')
time.sleep(self.pending_seconds)
def _manage_text(self, uuid, paste_content, ltags, ltagsgalaxies, source):
"""
Create a paste for given text
"""
if sys.getsizeof(paste_content) < SubmitPaste.TEXT_MAX_SIZE:
self.r_serv_log_submit.set(f'{uuid}:nb_total', 1)
self.create_paste(uuid, paste_content.encode(), ltags, ltagsgalaxies, uuid, source)
time.sleep(0.5)
else:
self.abord_file_submission(uuid, f'Text size is over {SubmitPaste.TEXT_MAX_SIZE} bytes')
def _manage_file(self, uuid, file_full_path, ltags, ltagsgalaxies, source):
"""
Create a paste for given file
"""
self.redis_logger.debug('manage')
if os.path.exists(file_full_path):
self.redis_logger.debug(f'file exists {file_full_path}')
file_size = os.stat(file_full_path).st_size
self.redis_logger.debug(f'file size {file_size}')
# Verify file length
if file_size < SubmitPaste.FILE_MAX_SIZE:
# TODO sanitize filename
filename = file_full_path.split('/')[-1]
self.redis_logger.debug(f'sanitize filename {filename}')
self.redis_logger.debug('file size allowed')
if not '.' in filename:
self.redis_logger.debug('no extension for filename')
try:
# Read file
with open(file_full_path,'r') as f:
content = f.read()
self.r_serv_log_submit.set(uuid + ':nb_total', 1)
self.create_paste(uuid, content.encode(), ltags, ltagsgalaxies, uuid, source)
except:
self.abord_file_submission(uuid, "file error")
else:
file_type = filename.rsplit('.', 1)[1]
file_type = file_type.lower()
self.redis_logger.debug(f'file ext {file_type}')
if file_type in SubmitPaste.ALLOWED_EXTENSIONS:
self.redis_logger.debug('Extension allowed')
# TODO enum of possible file extension ?
# TODO verify file hash with virus total ?
if not self._is_compressed_type(file_type):
self.redis_logger.debug('Plain text file')
# plain txt file
with open(file_full_path,'r') as f:
content = f.read()
self.r_serv_log_submit.set(uuid + ':nb_total', 1)
self.create_paste(uuid, content.encode(), ltags, ltagsgalaxies, uuid, source)
else:
# Compressed file
self.abord_file_submission(uuid, "file decompression should be implemented")
# TODO add compress file management
# #decompress file
# try:
# if password == None:
# files = unpack(file_full_path.encode())
# #print(files.children)
# else:
# try:
# files = unpack(file_full_path.encode(), password=password.encode())
# #print(files.children)
# except sflock.exception.IncorrectUsageException:
# self.abord_file_submission(uuid, "Wrong Password")
# raise
# except:
# self.abord_file_submission(uuid, "file decompression error")
# raise
# self.redis_logger.debug('unpacking {} file'.format(files.unpacker))
# if(not files.children):
# self.abord_file_submission(uuid, "Empty compressed file")
# raise
# # set number of files to submit
# self.r_serv_log_submit.set(uuid + ':nb_total', len(files.children))
# n = 1
# for child in files.children:
# if self.verify_extention_filename(child.filename.decode()):
# self.create_paste(uuid, child.contents, ltags, ltagsgalaxies, uuid+'_'+ str(n) , source)
# n = n + 1
# else:
# self.redis_logger.error("Error in module %s: bad extention"%(self.module_name))
# self.addError(uuid, 'Bad file extension: {}'.format(child.filename.decode()) )
# except FileNotFoundError:
# self.redis_logger.error("Error in module %s: file not found"%(self.module_name))
# self.addError(uuid, 'File not found: {}'.format(file_full_path), uuid )
else:
self.abord_file_submission(uuid, f'File :{file_full_path} too large, over {SubmitPaste.FILE_MAX_SIZE} bytes')
else:
self.abord_file_submission(uuid, "Server Error, the archive can't be found")
def _is_compressed_type(self, file_type):
"""
Check if file type is in the list of compressed file extensions format
"""
compressed_type = ['zip', 'gz', 'tar.gz']
return file_type in compressed_type
def remove_submit_uuid(self, uuid):
# save temp value on disk
self.r_serv_db.delete(f'{uuid}:ltags')
self.r_serv_db.delete(f'{uuid}:ltagsgalaxies')
self.r_serv_db.delete(f'{uuid}:paste_content')
self.r_serv_db.delete(f'{uuid}:isfile')
self.r_serv_db.delete(f'{uuid}:password')
self.r_serv_db.delete(f'{uuid}:source')
self.r_serv_log_submit.expire(f'{uuid}:end', SubmitPaste.expire_time)
self.r_serv_log_submit.expire(f'{uuid}:processing', SubmitPaste.expire_time)
self.r_serv_log_submit.expire(f'{uuid}:nb_total', SubmitPaste.expire_time)
self.r_serv_log_submit.expire(f'{uuid}:nb_sucess', SubmitPaste.expire_time)
self.r_serv_log_submit.expire(f'{uuid}:nb_end', SubmitPaste.expire_time)
self.r_serv_log_submit.expire(f'{uuid}:error', SubmitPaste.expire_time)
self.r_serv_log_submit.expire(f'{uuid}:paste_submit_link', SubmitPaste.expire_time)
# delete uuid
self.r_serv_db.srem('submitted:uuid', uuid)
self.redis_logger.debug(f'{uuid} all file submitted')
print(f'{uuid} all file submitted')
def create_paste(self, uuid, paste_content, ltags, ltagsgalaxies, name, source=None):
# # TODO: Use Item create
result = False
now = datetime.datetime.now()
source = source if source else 'submitted'
save_path = source + '/' + now.strftime("%Y") + '/' + now.strftime("%m") + '/' + now.strftime("%d") + '/submitted_' + name + '.gz'
full_path = filename = os.path.join(os.environ['AIL_HOME'],
self.process.config.get("Directories", "pastes"), save_path)
self.redis_logger.debug(f'file path of the paste {full_path}')
if not os.path.isfile(full_path):
# file not exists in AIL paste directory
self.redis_logger.debug(f"new paste {paste_content}")
gzip64encoded = self._compress_encode_content(paste_content)
if gzip64encoded:
# use relative path
rel_item_path = save_path.replace(self.PASTES_FOLDER, '', 1)
self.redis_logger.debug(f"relative path {rel_item_path}")
# send paste to Global module
relay_message = f"{rel_item_path} {gzip64encoded}"
self.process.populate_set_out(relay_message, 'Mixer')
# increase nb of paste by feeder name
self.r_serv_log_submit.hincrby("mixer_cache:list_feeder", source, 1)
# add tags
for tag in ltags:
Tag.add_tag('item', tag, rel_item_path)
for tag in ltagsgalaxies:
Tag.add_tag('item', tag, rel_item_path)
self.r_serv_log_submit.incr(f'{uuid}:nb_end')
self.r_serv_log_submit.incr(f'{uuid}:nb_sucess')
if self.r_serv_log_submit.get(f'{uuid}:nb_end') == self.r_serv_log_submit.get(f'{uuid}:nb_total'):
self.r_serv_log_submit.set(f'{uuid}:end', 1)
self.redis_logger.debug(f' {rel_item_path} send to Global')
print(f' {rel_item_path} send to Global')
self.r_serv_log_submit.sadd(f'{uuid}:paste_submit_link', rel_item_path)
curr_date = datetime.date.today()
self.serv_statistics.hincrby(curr_date.strftime("%Y%m%d"),'submit_paste', 1)
self.redis_logger.debug("paste submitted")
else:
self.addError(uuid, f'File: {save_path} already exist in submitted pastes')
return result
def _compress_encode_content(self, content):
gzip64encoded = None
try:
gzipencoded = gzip.compress(content)
gzip64encoded = base64.standard_b64encode(gzipencoded).decode()
except:
self.abord_file_submission(uuid, "file error")
return gzip64encoded
def addError(self, uuid, errorMessage):
self.redis_logger.debug(errorMessage)
print(errorMessage)
error = self.r_serv_log_submit.get(f'{uuid}:error')
if error != None:
self.r_serv_log_submit.set(f'{uuid}:error', error + '<br></br>' + errorMessage)
self.r_serv_log_submit.incr(f'{uuid}:nb_end')
def abord_file_submission(self, uuid, errorMessage):
self.redis_logger.debug(f'abord {uuid}, {errorMessage}')
self.addError(uuid, errorMessage)
self.r_serv_log_submit.set(f'{uuid}:end', 1)
curr_date = datetime.date.today()
self.serv_statistics.hincrby(curr_date.strftime("%Y%m%d"),'submit_abord', 1)
self.remove_submit_uuid(uuid)
# # TODO: use Item function
def get_item_date(self, item_filename):
l_directory = item_filename.split('/')
return f'{l_directory[-4]}{l_directory[-3]}{l_directory[-2]}'
def verify_extention_filename(self, filename):
if not '.' in filename:
return True
else:
file_type = filename.rsplit('.', 1)[1]
#txt file
if file_type in SubmitPaste.ALLOWED_EXTENSIONS:
return True
else:
return False
if __name__ == '__main__':
module = SubmitPaste()
module.run()<|fim▁end|>
|
def compute(self, uuid):
|
<|file_name|>wamnclient.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import pygeoip
import json
from logsparser.lognormalizer import LogNormalizer as LN
import gzip
import glob
import socket
import urllib2
IP = 'IP.Of,Your.Server'
normalizer = LN('/usr/local/share/logsparser/normalizers')
gi = pygeoip.GeoIP('../GeoLiteCity.dat')
def complete(text, state):
return (glob.glob(text+'*')+[none])[state]
def sshcheck():
attacks = {}
users = {}
try:
import readline, rlcompleter
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
except ImportError:
print 'No Tab Completion'
LOGs = raw_input('Enter the path to the log file: ')
for LOG in LOGs.split(' '):
if LOG.endswith('.gz'):
auth_logs = gzip.GzipFile(LOG, 'r')
else:
auth_logs = open(LOG, 'r')
if len(LOGs) is '1':
print "Parsing log file"
else:
print "Parsing log files"
for log in auth_logs:
l = {"raw": log }
normalizer.normalize(l)
if l.get('action') == 'fail' and l.get('program') == 'sshd':
u = l['user']
p = l['source_ip']
o1, o2, o3, o4 = [int(i) for i in p.split('.')]
if o1 == 192 and o2 == 168 or o1 == 172 and o2 in range(16, 32) or o1 == 10:
print "Private IP, %s No geolocation data" %str(p)
attacks[p] = attacks.get(p, 0) + 1
getip()
dojson(attacks, IP)
def getip():
global IP
if IP is 0:
try:
i = urllib2.Request("http://icanhazip.com")
p = urllib2.urlopen(i)<|fim▁hole|> except:
print "can't seem to grab your IP please set IP variable so We can better map attacks"
def dojson(attacks, IP):
data = {}
for i,(a,p) in enumerate(attacks.iteritems()):
datalist = [{ 'ip': a, 'attacks': p, 'local_ip': IP }]
data[i] = datalist
newdata = data
newjson = json.dumps(newdata)
print json.loads(newjson)
send(newjson)
def send(data):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('Ip.Of.Your.Server', 9999))
s.sendall(data)
s.close()
try:
sshcheck()
except KeyboardInterrupt:
print '\nCtrl+C Exiting...'
exit(0)<|fim▁end|>
|
IP = p.read()
|
<|file_name|>range.go<|end_file_name|><|fim▁begin|>package main
import "fmt"
func main() {
pow := make([]int, 10) //Lam bien go 10phan tu
for i := range pow {
pow[i] = 1 << uint(i) // == 2**i
}
for _, value := range pow {
fmt.Printf("%d\n", value)
}<|fim▁hole|>}<|fim▁end|>
| |
<|file_name|>appmon.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
###
# Copyright (c) 2016 Nishant Das Patnaik.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###
import os, sys, argparse, time, codecs, binascii, frida, json, traceback, subprocess, tempfile
from flask import Flask, request, render_template
from termcolor import colored
import database as db
import platform as platform_module
print("""
___ .______ .______ .___ ___. ______ .__ __.
/ \ | _ \ | _ \ | \/ | / __ \ | \ | |
/ ^ \ | |_) | | |_) | | \ / | | | | | | \| |
/ /_\ \ | ___/ | ___/ | |\/| | | | | | | . ` |
/ _____ \ | | | | | | | | | `--' | | |\ |
/__/ \__\ | _| | _| |__| |__| \______/ |__| \__|
github.com/dpnishant
""")
app = Flask(__name__, static_url_path='/static')
#app.debug = True
device = ''
session = ''
temp_dir = tempfile.mkdtemp()
merged_script_path = os.path.join(temp_dir,'merged.js')
APP_LIST = []
@app.after_request
def add_header(r):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Cache-Control'] = 'public, max-age=0'
return r
@app.route('/api/fetch', methods=['GET'])
def serve_json():
index = request.args.get('id')
if request.args.get('reportdb'):
db_name = request.args.get('reportdb')
else:
db_name = request.args.get('app')
response = db.read_from_database(db_name, index)
#response = open('static/data.json').read()
return response
@app.route('/monitor/', methods=['GET'])
def monitor_page():
app_name = request.args.get('app')
return render_template('monitor.html', app_name=app_name)
@app.route('/', methods=['GET'])
def landing_page():
global APP_LIST, DB_MAP
app_dumps_dir = os.path.join('.','app_dumps')
for root, dirs, files in os.walk(app_dumps_dir):
path = root.split(os.sep)
for file in files:
file_path = os.path.join(root, file)
if file_path.endswith('.db'):
APP_LIST.append(file.replace('.db', ''))
return render_template('index.html', apps=APP_LIST)
def init_opts():
parser = argparse.ArgumentParser()
parser.add_argument('-a', action='store', dest='app_name', default='',
help='''Process Name;
Accepts "Twitter" for iOS;
"com.twitter.android" for Android; "Twitter" for macOS''')
parser.add_argument('--spawn', action='store', dest='spawn', default=0,
help='''Optional; Accepts 1=Spawn, 0=Attach; Needs "-p PLATFORM"''')
parser.add_argument('-p', action='store', dest='platform',
help='Platform Type; Accepts "ios", "iossim", "android" or "macos"')
parser.add_argument('-s', action='store', dest='script_path', default='',
help='''Path to agent script file;
Can be relative/absolute path for a file or directory;
Multiple scripts in a directory shall be merged;
Needs "-a APP_NAME"''')
parser.add_argument('-o', action='store', dest='output_dir',
help='''(Optional) Path to store any dumps/logs;
Accepts relative/absolute paths''')
parser.add_argument('-r', action='store', dest='report',
help='Report database name (Default is <appname>.db')
parser.add_argument('-ls', action='store', dest='list_apps', default=0,
help='''Optional; Accepts 1 or 0; Lists running Apps on target device; Needs "-p PLATFORM"''')
parser.add_argument('-v', action='version', version='AppMon Sniffer v0.1, Nishant Das Patnaik, 2016')
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
global output_dir, report_name
results = parser.parse_args()
app_name = results.app_name
platform = results.platform
script_path = results.script_path
list_apps = int(results.list_apps)
spawn = int(results.spawn)
output_dir = results.output_dir if results.output_dir else os.path.join('.','app_dumps')
report_name = results.report if results.report else app_name
if script_path is not None and app_name == '' and list_apps == 0:
parser.print_help()
sys.exit(1)
return app_name, platform, script_path, list_apps, output_dir, spawn
def merge_scripts(path):
global merged_script_path
script_source = ''
for root, dirs, files in os.walk(path):
path = root.split('/')
for file in files:
script_path = os.path.join(root, file)
if script_path.endswith('.js'):
source = ''
with codecs.open(script_path, 'r', 'utf-8') as f:
source = f.read()
script_source += '/* ____%s/%s____ */\n\n' % (os.path.basename(root), file) + source + '\n\n'
with codecs.open(merged_script_path, "w", "utf-8") as f:
f.write(script_source)
return merged_script_path
def _exit_():
print((colored('[INFO] Exiting...', 'green')))
try:
os.remove(merged_script_path)
except Exception as e:
pass
sys.exit(0)
def writeBinFile(fname, data):
with codecs.open(fname, "a", "utf-8") as f:
f.write(data + '\r\n\r\n')
def list_processes(session):
print(('PID\tProcesses\n', '===\t========='))
for app in session.enumerate_processes():
print(("%s\t%s" % (app.pid, app.name)))
def on_detached():
print((colored('[WARNING] "%s" has terminated!' % (app_name), 'red')))
def on_message(message, data):
os_string = platform_module.system()
if os_string == "Windows":
current_time = time.strftime('%b %d %Y %I:%M %p', time.localtime())
else:
current_time = time.strftime('%b %d %Y %l:%M %p', time.localtime())
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if message['type'] == 'send':
writePath = os.path.join(output_dir, str(report_name) + '.db')
db.save_to_database(writePath, message['payload'])
#writePath = os.path.join(output_dir, app_name + '.json')
#writeBinFile(writePath, message['payload']) #writeBinFile(writePath, binascii.unhexlify(message['payload']))
print((colored('[%s] Dumped to %s' % (current_time, writePath), 'green')))
elif message['type'] == 'error':
print((message['stack']))
def generate_injection():
injection_source = ''
if os.path.isfile(script_path):
with codecs.open(script_path, 'r', 'utf-8') as f:
injection_source = f.read()
elif os.path.isdir(script_path):
with codecs.open(merge_scripts(script_path), 'r', 'utf-8') as f:
injection_source = f.read()
print((colored('[INFO] Building injection...', 'yellow')))
return injection_source
def getDisplayName(session, app_name, platform):
try:
str_script = ""
if platform == "ios":
str_script = """/* ____CFBundleDisplayName Getter for iOS Gadget____ */
'use strict';
rpc.exports = {
gadgetdisplayname: function () {
if (ObjC.available) {
var dict = ObjC.classes.NSBundle.mainBundle().infoDictionary();
var iter = dict.keyEnumerator();
var key = "";
while ((key = iter.nextObject()) !== null) {
if (key.toString() === "CFBundleDisplayName") {
return dict.objectForKey_(key).toString();
}
}
} else { return null; }
}
};
"""
script = session.create_script(str_script)
script.load()
if script.exports.gadgetdisplayname:
app_name = script.exports.gadgetdisplayname()
script.unload()
return app_name
elif platform == "android":
str_script = """/* ____ getPackageName Getter for Android Gadget____ */
'use strict';
rpc.exports = {
gadgetdisplayname: function () {
var appName = "";
Java.perform(function(argument) {
const ActivityThread = Java.use('android.app.ActivityThread');
const app = ActivityThread.currentApplication();
appName = app.toString().split("@")[0];
});
return appName;
}};
"""
script = session.create_script(str_script)
script.load()
if script.exports.gadgetdisplayname:
app_name = script.exports.gadgetdisplayname()
script.unload()
return app_name
except Exception as e:
print((colored("[ERROR] " + str(e), "red")))
traceback.print_exc()
def getBundleID(device, app_name, platform):
try:
session = device.attach(app_name)
session.on('detached', on_detached)
script = session.create_script("""'use strict';
rpc.exports = {
iosbundleid: function () {
return ObjC.classes.NSBundle.mainBundle().bundleIdentifier().toString();
},
macosbundleid: function () {
return ObjC.classes.NSBundle.mainBundle().executablePath().toString();
}
};
""")
script.load()
if platform == 'ios':
bundleID = script.exports.iosbundleid()
elif platform == 'macos':
bundleID = script.exports.macosbundleid()
script.unload()
session.detach()
return bundleID
except Exception as e:
print((colored("[ERROR] " + str(e), "red")))
traceback.print_exc()
def init_session():
try:
session = None
if platform == 'ios' or platform == 'android':
try:
device = frida.get_usb_device(3) # added timeout to wait for 3 seconds
except Exception as e:
print((colored(str(e), "red")))
traceback.print_exc()
if platform == 'android':
print((colored("Troubleshooting Help", "blue")))
print((colored("HINT: Is USB Debugging enabled?", "blue")))
print((colored("HINT: Is `frida-server` running on mobile device (with +x permissions)?", "blue")))
print((colored("HINT: Is `adb` daemon running?", "blue")))
sys.exit(1)
elif platform == "ios":
print((colored("Troubleshooting Help", "blue")))
print((colored("HINT: Have you installed `frida` module from Cydia?", "blue")))
print((colored("HINT: Have used `ipa_installer` to inject the `FridaGadget` shared lbrary?", "blue")))
sys.exit(1)
elif platform == 'iossim':
try:
device = frida.get_remote_device()
except Exception as e:
print((colored("Troubleshooting Help", "blue")))
print((colored("HINT: Have you successfully integrated the FridaGadget dylib with the XCode Project?", "blue")))
print((colored("HINT: Do you see a message similar to \"[Frida INFO] Listening on 127.0.0.1 TCP port 27042\" on XCode console logs?", "blue")))
sys.exit(1)
elif platform == 'macos':
device = frida.get_local_device()
else:
print((colored('[ERROR] Unsupported Platform', 'red')))
sys.exit(1)
pid = None
if app_name:
try:
if platform == 'android' and spawn == 1:
print((colored("Now Spawning %s" % app_name, "green")))
pid = device.spawn([app_name])
#time.sleep(5)
session = device.attach(pid)
#time.sleep(5)
elif (platform == 'ios' or platform == 'macos') and spawn == 1:
bundleID = getBundleID(device, app_name, platform)
if bundleID:
print((colored("Now Spawning %s" % bundleID, "green")))
pid = device.spawn([bundleID])
#time.sleep(5)
session = device.attach(pid)
else:<|fim▁hole|> else:
arg_to_attach = app_name
if app_name.isdigit():
arg_to_attach = int(app_name)
session = device.attach(arg_to_attach)
except Exception as e:
print((colored('[ERROR] ' + str(e), 'red')))
traceback.print_exc()
if session:
print((colored('[INFO] Attached to %s' % (app_name), 'yellow')))
session.on('detached', on_detached)
except Exception as e:
print((colored('[ERROR] ' + str(e), 'red')))
traceback.print_exc()
sys.exit(1)
return device, session, pid
try:
app_name, platform, script_path, list_apps, output_dir, spawn = init_opts()
device, session, pid = init_session()
if int(list_apps) == 1:
list_processes(device)
sys.exit(0)
if session:
if app_name == "Gadget":
app_name = getDisplayName(session, app_name, platform)
script = session.create_script(generate_injection())
if script:
print((colored('[INFO] Instrumentation started...', 'yellow')))
script.on('message', on_message)
script.load()
if spawn == 1 and pid:
device.resume(pid)
app.run() #Start WebServer
except Exception as e:
print((colored('[ERROR] ' + str(e), 'red')))
traceback.print_exc()
sys.exit(1)
try:
while True:
pass
except KeyboardInterrupt:
script.unload()
session.detach()
_exit_()<|fim▁end|>
|
print((colored("[ERROR] Can't spawn %s" % app_name, "red")))
traceback.print_exc()
sys.exit(1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.