code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
namespace Vipr.Core.CodeModel
{
public abstract class OdcmClass : OdcmType
{
public bool IsAbstract { get; set; }
public bool IsOpen { get; set; }
public OdcmClass Base { get; set; }
public IList<OdcmClass> Derived { get; private set; }
public OdcmClassKind Kind { get; set; }
public List<OdcmProperty> Properties { get; private set; }
public List<OdcmMethod> Methods { get; private set; }
public OdcmClass(string name, OdcmNamespace @namespace, OdcmClassKind kind)
: base(name, @namespace)
{
Kind = kind;
Properties = new List<OdcmProperty>();
Methods = new List<OdcmMethod>();
Derived = new List<OdcmClass>();
}
}
}
| MSOpenTech/Vipr | src/Core/Vipr.Core/CodeModel/OdcmClass.cs | C# | mit | 1,000 |
var Checker = require('../../lib/checker');
var assert = require('assert');
var operators = require('../../lib/utils').unaryOperators;
describe('rules/require-space-after-prefix-unary-operators', function() {
var checker;
beforeEach(function() {
checker = new Checker();
checker.registerDefaultRules();
});
operators.forEach(function(operator) {
var sticked = 'var test;' + operator + 'test';
var stickedWithParenthesis = 'var test;' + operator + '(test)';
var notSticked = 'var test;' + operator + ' test';
var notStickedWithParenthesis = 'var test;' + operator + ' (test)';
[[operator], true].forEach(function(value) {
it('should report sticky operator for ' + sticked + ' with ' + value + ' option',
function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: value });
assert(checker.checkString(sticked).getErrorCount() === 1);
}
);
it('should not report sticky operator for ' + notSticked + ' with ' + value + ' option',
function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: value });
assert(checker.checkString(notSticked).isEmpty());
}
);
it('should report sticky operator for ' + stickedWithParenthesis + ' with ' + value + ' option',
function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: value });
assert(checker.checkString(stickedWithParenthesis).getErrorCount() === 1);
}
);
it('should not report sticky operator for ' + notStickedWithParenthesis + ' with ' + value + ' option',
function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: value });
assert(checker.checkString(notStickedWithParenthesis).isEmpty());
}
);
});
});
it('should report sticky operator if operand in parentheses', function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: ['-', '~', '!', '++'] });
assert(checker.checkString('var x = ~(0); ++(((x))); -( x ); !(++( x ));').getErrorCount() === 5);
});
it('should not report consecutive operators (#405)', function() {
checker.configure({ requireSpaceAfterPrefixUnaryOperators: ['!'] });
assert(checker.checkString('!~test;').isEmpty());
assert(checker.checkString('!~test;').isEmpty());
assert(checker.checkString('!++test;').isEmpty());
});
});
| appium/node-jscs | test/rules/require-space-after-prefix-unary-operators.js | JavaScript | mit | 2,695 |
/* Copyright (c) 2006-2009 Jan S. Rellermeyer
* Systems Group,
* Department of Computer Science, ETH Zurich.
* 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.
* - Neither the name of ETH Zurich nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* 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 OWNER 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.
*/
package ch.ethz.iks.util;
/**
* Interface for listeners of the Scheduler utility.
*
* @author Jan S. Rellermeyer, ETH Zurich
*/
public interface ScheduleListener {
/**
* called, when a scheduled object is due.
*
* @param scheduler
* the scheduler that has scheduled the object.
* @param timestamp
* the timestamp for which the object was scheduled.
* @param object
* the scheduled object.
*/
void due(final Scheduler scheduler, final long timestamp,
final Object object);
}
| nmizoguchi/pfg-r-osgi | ch.ethz.iks.r_osgi.remote/src/main/java/ch/ethz/iks/util/ScheduleListener.java | Java | mit | 2,191 |
foo || bar;
(x => x) || bar;
(function a(x) {
return x;
}) || 2;
0 || function () {
return alpha;
};
a && b && c;
a && b && c;
a || b || c;
a || b || c;
a || b && c;
a && (b || c);
(a || b) && c;
a && b || c; | kaicataldo/babel | packages/babel-generator/test/fixtures/types/LogicalExpression/output.js | JavaScript | mit | 215 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The "in" token can not be used as identifier
es5id: 7.6.1.1_A1.13
description: Checking if execution of "in=1" fails
negative: SyntaxError
---*/
in = 1;
| PiotrDabkowski/Js2Py | tests/test_cases/language/keywords/S7.6.1.1_A1.13.js | JavaScript | mit | 299 |
/*!
* jQuery JavaScript Library v1.8.3 -ajax,-ajax/jsonp,-ajax/script,-ajax/xhr,-effects,-dimensions
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: Thu Feb 07 2013 15:58:11 GMT-0600 (CST)
*/
(function( window, undefined ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
navigator = window.navigator,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Save a reference to some core methods
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// scripts is true for back-compat
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
return jQuery.merge( this, selector );
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.8.3 -ajax,-ajax/jsonp,-ajax/script,-ajax/xhr,-effects,-dimensions",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ),
"slice", core_slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key,
ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
function() {
var returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
eventName,
i,
isSupported,
clickFn,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: ( document.compatMode === "CSS1Compat" ),
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", clickFn = function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent("onclick");
div.detachEvent( "onclick", clickFn );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
input.setAttribute( "checked", "checked" );
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Run tests that need a body at doc ready
jQuery(function() {
var container, div, tds, marginDiv,
divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild( marginDiv );
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
container.style.zoom = 1;
}
// Null elements to avoid leaks in IE
body.removeChild( container );
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
fragment.removeChild( div );
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
// Remove at next major release (1.9/2.0)
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery.removeData( elem, type + "queue", true );
jQuery.removeData( elem, key, true );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook, fixSpecified,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea|)$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var removes, className, elem, c, cl, i, l;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
removes = ( value || "" ).split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
className = (" " + elem.className + " ").replace( rclass, " " );
// loop over each item in the removal list
for ( c = 0, cl = removes.length; c < cl; c++ ) {
// Remove until there is nothing to remove,
while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {
className = className.replace( " " + removes[ c ] + " " , " " );
}
}
elem.className = value ? jQuery.trim( className ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( core_rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
attrFn: {},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.split( core_rspace );
for ( ; i < attrNames.length; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.value = value + "" );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var t, tns, type, origType, namespaces, origCount,
j, events, special, eventType, handleObj,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, "events", true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
type = event.type || event,
namespaces = [];
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
for ( old = elem; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old === (elem.ownerDocument || document) ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = core_slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
event.metaKey = !!event.metaKey;
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "_submit_attached" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "_submit_attached", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "_change_attached", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var i,
cachedruns,
Expr,
getText,
isXML,
compile,
hasDuplicate,
outermostContext,
// Local document vars
setDocument,
document,
docElem,
documentIsXML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
sortOrder,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
support = {},
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Array methods
arr = [],
pop = arr.pop,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rsibling = /[\x20\t\r\n\f]*[+~]/,
rnative = /\{\s*\[native code\]\s*\}/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
funescape = function( _, escaped ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
return high !== high ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Use a stripped-down slice if we can't use a native one
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var cache,
keys = [];
return (cache = function( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
});
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( !documentIsXML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
// QSA path
if ( support.qsa && !rbuggyQSA.test(selector) ) {
old = true;
nid = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsXML = isXML( doc );
// Check if getElementsByTagName("*") returns only elements
support.tagNameNoComments = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if attributes should be retrieved by attribute nodes
support.attributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
});
// Check if getElementsByClassName can be trusted
support.getByClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
});
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
support.getByName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = doc.getElementsByName &&
// buggy browsers will return fewer than the correct 2
doc.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
doc.getElementsByName( expando + 0 ).length;
support.getIdNotName = !doc.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// IE6/7 return modified attributes
Expr.attrHandle = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}) ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
};
// ID find and filter
if ( support.getIdNotName ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.tagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Name
Expr.find["NAME"] = support.getByName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
};
// Class
Expr.find["CLASS"] = support.getByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) {
return context.getElementsByClassName( className );
}
};
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21),
// no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE8 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<input type='hidden' i=''/>";
if ( div.querySelectorAll("[i^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = new RegExp( rbuggyMatches.join("|") );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
var compare;
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) {
if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) {
if ( a === doc || contains( preferredDoc, a ) ) {
return -1;
}
if ( b === doc || contains( preferredDoc, b ) ) {
return 1;
}
return 0;
}
return compare & 4 ? -1 : 1;
}
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return ( ~b.sourceIndex || MAX_NEGATIVE ) - ( contains( preferredDoc, a ) && ~a.sourceIndex || MAX_NEGATIVE );
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
hasDuplicate = false;
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyQSA always contains :focus, so no need for an existence check
if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
var val;
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
if ( !documentIsXML ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( documentIsXML || support.attributes ) {
return elem.getAttribute( name );
}
return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
name :
val && val.specified ? val.value : null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
function siblingCheck( a, b ) {
var cur = a && b && a.nextSibling;
for ( ; cur; cur = cur.nextSibling ) {
if ( cur === b ) {
return -1;
}
}
return a ? 1 : -1;
}
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[4] ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.substr( result.length - check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifider
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsXML ?
elem.getAttribute("xml:lang") || elem.getAttribute("lang") :
elem.lang) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push( {
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
} );
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push( {
value: matched,
type: type,
matches: match
} );
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && combinator.dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Nested matchers should use non-integer dirruns
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
// `i` starts as a string, so matchedCount would equal "00" if there are no elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
for ( j = 0; (matcher = setMatchers[j]); j++ ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !documentIsXML &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
for ( i = matchExpr["needsContext"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
documentIsXML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Initialize with the default document
setDocument();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, l, length, n, r, ret,
self = this;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
ret = this.pushStack( "", "find", selector );
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "X<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
}
},
after: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( !isDisconnected( this[0] ) ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
}
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = [].concat.apply( [], args );
var results, first, fragment, iNoClone,
i = 0,
value = args[0],
scripts = [],
l = this.length;
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call( this, i, table ? self.html() : undefined );
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
results = jQuery.buildFragment( args, this, scripts );
fragment = results.fragment;
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
// Fragments from the fragment cache must always be cloned and never used in place.
for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
i === iNoClone ?
fragment :
jQuery.clone( fragment, true, true )
);
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
if ( jQuery.ajax ) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
if ( nodeName === "object" ) {
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ];
cachehit = fragment !== undefined;
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment;
}
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( ; i < l; i++ ) {
elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
clone;
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
safe = context === document && safeFragment,
ret = [];
// Ensure that context is a document
if ( !context || typeof context.createDocumentFragment === "undefined" ) {
context = document;
}
// Use the already-created safe fragment if context permits
for ( i = 0; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Ensure a safe container in which to render the html
safe = safe || createSafeFragment( context );
div = context.createElement("div");
safe.appendChild( div );
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Go to html and back, then peel off extra wrappers
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
depth = wrap[0];
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
hasBody = rtbody.test(elem);
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Take out of fragment container (we need a fresh div each time)
div.parentNode.removeChild( div );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
jQuery.merge( ret, elem );
}
}
// Fix #11356: Clear elements from safeFragment
if ( div ) {
elem = div = safe = null;
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
for ( i = 0; (elem = ret[i]) != null; i++ ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
}
// Append elements to a provided document fragment
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function( elems, /* internal */ acceptData ) {
var data, id, elem, type,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
jQuery.deletedIds.push( id );
}
}
}
}
}
});
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
})();
var curCSS, iframe, iframeDoc,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
eventsToggle = jQuery.fn.toggle;
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var elem, display,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && elem.style.display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
display = curCSS( elem, "display" );
if ( !values[ index ] && display !== "none" ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state, fn2 ) {
var bool = typeof state === "boolean";
if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {
return eventsToggle.apply( this, arguments );
}
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, numeric, extra ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( numeric || extra !== undefined ) {
num = parseFloat( val );
return numeric || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
curCSS = function( elem, name ) {
var ret, width, minWidth, maxWidth,
computed = window.getComputedStyle( elem, null ),
style = elem.style;
if ( computed ) {
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
// we use jQuery.css instead of curCSS here
// because of the reliableMarginRight CSS hook!
val += jQuery.css( elem, extra + cssExpand[ i ], true );
}
// From this point on we use curCSS for maximum performance (relevant in animations)
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
} else {
// at this point, extra isn't content, so add padding
val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
valueIsBorderBox = true,
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
if ( elemdisplay[ nodeName ] ) {
return elemdisplay[ nodeName ];
}
var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ),
display = elem.css("display");
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// Use the already-created iframe if possible
iframe = document.body.appendChild(
iframe || jQuery.extend( document.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
})
);
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write("<!doctype html><html><body>");
iframeDoc.close();
}
elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );
display = curCSS( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
} else {
return getWidthOrHeight( elem, name, extra );
}
}
},
set: function( elem, value, extra ) {
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "marginRight" );
}
});
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
var ret = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var rroot = /^(?:body|html)$/i;
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
if ( (body = doc.body) === elem ) {
return jQuery.offset.bodyOffset( elem );
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== "undefined" ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.body;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
| eric-seekas/jquery-builder | dist/1.8.3/jquery-ajax-dimensions-effects.js | JavaScript | mit | 217,443 |
/*global todomvc */
(function () {
'use strict';
/**
* The main controller for the app. The controller:
* - retrieves and persists the model via the todoStorage service
* - exposes the model to the template and provides event handlers
*/
todomvc.controller('TodoCtrl', function TodoCtrl($scope, $location, todoStorage, filterFilter, $speechRecognition) {
var todos = $scope.todos = todoStorage.get();
$scope.newTodo = '';
$scope.remainingCount = filterFilter(todos, {completed: false}).length;
$scope.editedTodo = null;
if ($location.path() === '') {
$location.path('/');
}
$scope.location = $location;
$scope.$watch('location.path()', function (path) {
$scope.statusFilter = (path === '/active') ?
{ completed: false } : (path === '/completed') ?
{ completed: true } : null;
});
$scope.$watch('remainingCount == 0', function (val) {
$scope.allChecked = val;
});
$scope.addTodo = function () {
var newTodo = $scope.newTodo.trim();
console.log(newTodo);
if (newTodo.length === 0) {
return;
}
todos.push({
title: newTodo,
completed: false
});
todoStorage.put(todos);
console.log(todos);
$scope.newTodo = '';
$scope.remainingCount++;
};
$scope.editTodo = function (todo) {
$scope.editedTodo = todo;
};
$scope.doneEditing = function (todo) {
$scope.editedTodo = null;
todo.title = todo.title.trim();
if (!todo.title) {
$scope.removeTodo(todo);
}
todoStorage.put(todos);
};
$scope.removeTodo = function (todo) {
$scope.remainingCount -= todo.completed ? 0 : 1;
todos.splice(todos.indexOf(todo), 1);
todoStorage.put(todos);
};
$scope.todoCompleted = function (todo) {
if (todo.completed) {
$scope.remainingCount--;
} else {
$scope.remainingCount++;
}
todoStorage.put(todos);
};
$scope.clearCompletedTodos = function () {
$scope.todos = todos = todos.filter(function (val) {
return !val.completed;
});
todoStorage.put(todos);
};
$scope.markAll = function (completed) {
todos.forEach(function (todo) {
todo.completed = completed;
});
$scope.remainingCount = completed ? 0 : todos.length;
todoStorage.put(todos);
};
/**
* Need to be added for speech recognition
*/
var findTodo = function(title){
for (var i=0; i<todos.length; i++){
if (todos[i].title === title) {
return todos[i];
}
}
return null;
};
var completeTodo = function(title){
for (var i=0; i<todos.length; i++){
if (todos[i].title === title) {
todos[i].completed = ! todos[i].completed;
$scope.todoCompleted(todos[i]);
$scope.$apply();
return true;
}
}
};
var LANG = 'en-US';
$speechRecognition.onstart(function(e){
$speechRecognition.speak('Yes? How can I help you?');
});
$speechRecognition.onerror(function(e){
var error = (e.error || '');
alert('An error occurred ' + error);
});
$speechRecognition.payAttention();
// $speechRecognition.setLang(LANG);
$speechRecognition.listen();
$scope.recognition = {};
$scope.recognition['en-US'] = {
'addToList': {
'regex': /^do .+/gi,
'lang': 'en-US',
'call': function(utterance){
var parts = utterance.split(' ');
if (parts.length > 1) {
$scope.newTodo = parts.slice(1).join(' ');
$scope.addTodo();
$scope.$apply();
}
}
},
'show-all': {
'regex': /show.*all/gi,
'lang': 'en-US',
'call': function(utterance){
$location.path('/');
$scope.$apply();
}
},
'show-active': {
'regex': /show.*active/gi,
'lang': 'en-US',
'call': function(utterance){
$location.path('/active');
$scope.$apply();
}
},
'show-completed': {
'regex': /show.*complete/gi,
'lang': 'en-US',
'call': function(utterance){
$location.path('/completed');
$scope.$apply();
}
},
'mark-all': {
'regex': /^mark/gi,
'lang': 'en-US',
'call': function(utterance){
$scope.markAll(1);
$scope.$apply();
}
},
'unmark-all': {
'regex': /^unmark/gi,
'lang': 'en-US',
'call': function(utterance){
$scope.markAll(1);
$scope.$apply();
}
},
'clear-completed': {
'regex': /clear.*/gi,
'lang': 'en-US',
'call': function(utterance){
$scope.clearCompletedTodos();
$scope.$apply();
}
},
'listTasks': [{
'regex': /^complete .+/gi,
'lang': 'en-US',
'call': function(utterance){
var parts = utterance.split(' ');
if (parts.length > 1) {
completeTodo(parts.slice(1).join(' '));
}
}
},{
'regex': /^remove .+/gi,
'lang': 'en-US',
'call': function(utterance){
var parts = utterance.split(' ');
if (parts.length > 1) {
var todo = findTodo(parts.slice(1).join(' '));
console.log(todo);
if (todo) {
$scope.removeTodo(todo);
$scope.$apply();
}
}
}
}]
};
var ignoreUtterance = {};
ignoreUtterance['addToList'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['addToList']);
ignoreUtterance['show-all'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['show-all']);
ignoreUtterance['show-active'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['show-active']);
ignoreUtterance['show-completed'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['show-completed']);
ignoreUtterance['mark-all'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['mark-all']);
ignoreUtterance['unmark-all'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['unmark-all']);
ignoreUtterance['clear-completed'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['clear-completed']);
/*
to ignore listener call returned function
*/
// ignoreUtterance['addToList']();
});
}()); | xtrasmal/adaptive-speech | demo/js/controllers/todoCtrl.js | JavaScript | mit | 5,691 |
/*
* Copyright 2007-2008, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is 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.
NOTICE: ORIGINAL FILE MODIFIED
*/
package com.aspose.words.examples.featurescomparison.documents.comments;
import java.math.BigInteger;
import java.util.Calendar;
import org.docx4j.convert.out.flatOpcXml.FlatOpcXmlCreator;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.CommentsPart;
import org.docx4j.samples.AbstractSample;
import org.docx4j.wml.Comments;
import org.docx4j.wml.Comments.Comment;
import org.docx4j.wml.P;
import com.aspose.words.examples.Utils;
/**
* Creates a WordprocessingML document from scratch, and adds a comment.
*
* Note that only w:commentReference is required; this example doesn't add
* w:commentRangeStart or w:commentRangeEnd
*
* <w:p> <w:commentRangeStart w:id="0"/> <w:r> <w:t>hello</w:t> </w:r>
* <w:commentRangeEnd w:id="0"/> <w:r> <w:rPr> <w:rStyle
* w:val="CommentReference"/> </w:rPr> <w:commentReference w:id="0"/> </w:r>
* </w:p>
*
*
* @author Jason Harrop
*/
public class Docx4jCommentsSample extends AbstractSample
{
static org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory();
public static void main(String[] args) throws Exception
{
// The path to the documents directory.
String dataDir = Utils.getDataDir(Docx4jCommentsSample.class);
outputfilepath = dataDir + "Docx4j_CommentsSample.docx";
//boolean save = (outputfilepath == null ? false : true);
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.createPackage();
// Create and add a Comments Part
CommentsPart cp = new CommentsPart();
wordMLPackage.getMainDocumentPart().addTargetPart(cp);
// Part must have minimal contents
Comments comments = factory.createComments();
cp.setJaxbElement(comments);
// Add a comment to the comments part
java.math.BigInteger commentId = BigInteger.valueOf(0);
Comment theComment = createComment(commentId, "fred", null,
"my first comment");
comments.getComment().add(theComment);
// Add comment reference to document
P paraToCommentOn = wordMLPackage.getMainDocumentPart()
.addParagraphOfText("here is some content");
paraToCommentOn.getContent().add(createRunCommentReference(commentId));
// ++, for next comment ...
commentId = commentId.add(java.math.BigInteger.ONE);
wordMLPackage.save(new java.io.File(outputfilepath));
System.out.println("Saved " + outputfilepath);
System.out.println("Done.");
}
private static org.docx4j.wml.Comments.Comment createComment(
java.math.BigInteger commentId, String author, Calendar date,
String message)
{
org.docx4j.wml.Comments.Comment comment = factory
.createCommentsComment();
comment.setId(commentId);
if (author != null)
{
comment.setAuthor(author);
}
if (date != null)
{
// String dateString = RFC3339_FORMAT.format(date.getTime()) ;
// comment.setDate(value)
// TODO - at present this is XMLGregorianCalendar
}
org.docx4j.wml.P commentP = factory.createP();
comment.getEGBlockLevelElts().add(commentP);
org.docx4j.wml.R commentR = factory.createR();
commentP.getContent().add(commentR);
org.docx4j.wml.Text commentText = factory.createText();
commentR.getContent().add(commentText);
commentText.setValue(message);
return comment;
}
private static org.docx4j.wml.R createRunCommentReference(
java.math.BigInteger commentId)
{
org.docx4j.wml.R run = factory.createR();
org.docx4j.wml.R.CommentReference commentRef = factory
.createRCommentReference();
run.getContent().add(commentRef);
commentRef.setId(commentId);
return run;
}
} | aspose-words/Aspose.Words-for-Java | Plugins/Aspose_Words_Java_for_Docx4j/src/main/java/com/aspose/words/examples/featurescomparison/documents/comments/Docx4jCommentsSample.java | Java | mit | 4,780 |
using System;
using System.Collections.Generic;
using Cake.Core.Diagnostics;
using Cake.Core.Tooling;
namespace Cake.Common.Tools.MSBuild
{
/// <summary>
/// Contains settings used by <see cref="MSBuildRunner"/>.
/// </summary>
public sealed class MSBuildSettings : ToolSettings
{
private readonly HashSet<string> _targets;
private readonly Dictionary<string, IList<string>> _properties;
/// <summary>
/// Gets the targets.
/// </summary>
/// <value>The targets.</value>
public ISet<string> Targets
{
get { return _targets; }
}
/// <summary>
/// Gets the properties.
/// </summary>
/// <value>The properties.</value>
public IDictionary<string, IList<string>> Properties
{
get { return _properties; }
}
/// <summary>
/// Gets or sets the platform target.
/// </summary>
/// <value>The platform target.</value>
public PlatformTarget? PlatformTarget { get; set; }
/// <summary>
/// Gets or sets the MSBuild platform.
/// </summary>
/// <value>The MSBuild platform.</value>
public MSBuildPlatform MSBuildPlatform { get; set; }
/// <summary>
/// Gets or sets the tool version.
/// </summary>
/// <value>The tool version.</value>
public MSBuildToolVersion ToolVersion { get; set; }
/// <summary>
/// Gets or sets the configuration.
/// </summary>
/// <value>The configuration.</value>
public string Configuration { get; set; }
/// <summary>
/// Gets or sets the maximum CPU count.
/// </summary>
/// <value>The maximum CPU count.</value>
public int MaxCpuCount { get; set; }
/// <summary>
/// Gets or sets whether or not node reuse is used.
/// When you’re doing multiple builds in a row, this helps reduce your total build time,
/// by avoiding the start up costs of each MSBuild child node.
/// </summary>
public bool? NodeReuse { get; set; }
/// <summary>
/// Gets or sets the amount of information to display in the build log.
/// Each logger displays events based on the verbosity level that you set for that logger.
/// </summary>
/// <value>The build log verbosity.</value>
public Verbosity Verbosity { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MSBuildSettings"/> class.
/// </summary>
public MSBuildSettings()
{
_targets = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
_properties = new Dictionary<string, IList<string>>(StringComparer.OrdinalIgnoreCase);
ToolVersion = MSBuildToolVersion.Default;
Configuration = string.Empty;
Verbosity = Verbosity.Normal;
MSBuildPlatform = MSBuildPlatform.Automatic;
}
}
} | andycmaj/cake | src/Cake.Common/Tools/MSBuild/MSBuildSettings.cs | C# | mit | 3,061 |
'use strict';
var gulp = require('gulp');
var shell = require('gulp-shell');
module.exports = function () {
gulp.task('git-add', function () {
return gulp.src('*.js', {
read: false
}).pipe(shell(['git ls-files --others docroot/sites/all | egrep \'.css|.js|.png|.map\' | xargs git add -f']));
});
};
| six519/disclose.ph | gulp/git.js | JavaScript | mit | 318 |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002, 2014 Oracle and/or its affiliates. All rights reserved.
*
*/
package com.sleepycat.persist.evolve;
import java.lang.reflect.Method;
import com.sleepycat.compat.DbCompat;
/**
* A mutation for converting an old version of an object value to conform to
* the current class or field definition. For example:
*
* <pre class="code">
* package my.package;
*
* // The old class. Version 0 is implied.
* //
* {@literal @Entity}
* class Person {
* // ...
* }
*
* // The new class. A new version number must be assigned.
* //
* {@literal @Entity(version=1)}
* class Person {
* // Incompatible changes were made here...
* }
*
* // Add a converter mutation.
* //
* Mutations mutations = new Mutations();
*
* mutations.addConverter(new Converter(Person.class.getName(), 0,
* new MyConversion()));
*
* // Configure the mutations as described {@link Mutations here}.</pre>
*
* <p>See {@link Conversion} for more information.</p>
*
* @see com.sleepycat.persist.evolve Class Evolution
* @author Mark Hayes
*/
public class Converter extends Mutation {
private static final long serialVersionUID = 4558176842096181863L;
private Conversion conversion;
/**
* Creates a mutation for converting all instances of the given class
* version to the current version of the class.
*/
public Converter(String className,
int classVersion,
Conversion conversion) {
this(className, classVersion, null, conversion);
}
/**
* Creates a mutation for converting all values of the given field in the
* given class version to a type compatible with the current declared type
* of the field.
*/
public Converter(String declaringClassName,
int declaringClassVersion,
String fieldName,
Conversion conversion) {
super(declaringClassName, declaringClassVersion, fieldName);
this.conversion = conversion;
/* Require explicit implementation of the equals method. */
Class cls = conversion.getClass();
try {
Method m = cls.getMethod("equals", Object.class);
if (m.getDeclaringClass() == Object.class) {
throw new IllegalArgumentException
("Conversion class does not implement the equals method " +
"explicitly (Object.equals is not sufficient): " +
cls.getName());
}
} catch (NoSuchMethodException e) {
throw DbCompat.unexpectedException(e);
}
}
/**
* Returns the converter instance specified to the constructor.
*/
public Conversion getConversion() {
return conversion;
}
/**
* Returns true if the conversion objects are equal in this object and
* given object, and if the {@link Mutation#equals} superclass method
* returns true.
*/
@Override
public boolean equals(Object other) {
if (other instanceof Converter) {
Converter o = (Converter) other;
return conversion.equals(o.conversion) &&
super.equals(other);
} else {
return false;
}
}
@Override
public int hashCode() {
return conversion.hashCode() + super.hashCode();
}
@Override
public String toString() {
return "[Converter " + super.toString() +
" Conversion: " + conversion + ']';
}
}
| prat0318/dbms | mini_dbms/je-5.0.103/src/com/sleepycat/persist/evolve/Converter.java | Java | mit | 3,660 |
module Rack
class Offline
class Config
def initialize(root, &block)
@cache = []
@network = []
@fallback = {}
@root = root
instance_eval(&block) if block_given?
end
def cache(*names)
@cache.concat(names)
end
def network(*names)
@network.concat(names)
end
def fallback(hash = {})
@fallback.merge!(hash)
end
def root
@root
end
end
end
end
| kakra/rack-offline | lib/rack/offline/config.rb | Ruby | mit | 490 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.catalina.util;
import java.beans.Introspector;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.juli.logging.Log;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.res.StringManager;
/**
* Provides introspection utilities that either require knowledge of Tomcat
* internals or are solely used by Tomcat internals.
*/
public class Introspection {
private static final StringManager sm =
StringManager.getManager("org.apache.catalina.util");
/**
* Extract the Java Bean property name from the setter name.
*
* Note: This method assumes that the method name has already been checked
* for correctness.
*/
public static String getPropertyName(Method setter) {
return Introspector.decapitalize(setter.getName().substring(3));
}
/**
* Determines if a method has a valid name and signature for a Java Bean
* setter.
*
* @param method The method to test
*
* @return <code>true</code> if the method does have a valid name and
* signature, else <code>false</code>
*/
public static boolean isValidSetter(Method method) {
if (method.getName().startsWith("set")
&& method.getName().length() > 3
&& method.getParameterTypes().length == 1
&& method.getReturnType().getName().equals("void")) {
return true;
}
return false;
}
/**
* Determines if a method is a valid lifecycle callback method.
*
* @param method
* The method to test
*
* @return <code>true</code> if the method is a valid lifecycle callback
* method, else <code>false</code>
*/
public static boolean isValidLifecycleCallback(Method method) {
if (method.getParameterTypes().length != 0
|| Modifier.isStatic(method.getModifiers())
|| method.getExceptionTypes().length > 0
|| !method.getReturnType().getName().equals("void")) {
return false;
}
return true;
}
/**
* Obtain the declared fields for a class taking account of any security
* manager that may be configured.
*/
public static Field[] getDeclaredFields(final Class<?> clazz) {
Field[] fields = null;
if (Globals.IS_SECURITY_ENABLED) {
fields = AccessController.doPrivileged(
new PrivilegedAction<Field[]>(){
@Override
public Field[] run(){
return clazz.getDeclaredFields();
}
});
} else {
fields = clazz.getDeclaredFields();
}
return fields;
}
/**
* Obtain the declared methods for a class taking account of any security
* manager that may be configured.
*/
public static Method[] getDeclaredMethods(final Class<?> clazz) {
Method[] methods = null;
if (Globals.IS_SECURITY_ENABLED) {
methods = AccessController.doPrivileged(
new PrivilegedAction<Method[]>(){
@Override
public Method[] run(){
return clazz.getDeclaredMethods();
}
});
} else {
methods = clazz.getDeclaredMethods();
}
return methods;
}
/**
* Attempt to load a class using the given Container's class loader. If the
* class cannot be loaded, a debug level log message will be written to the
* Container's log and null will be returned.
*/
public static Class<?> loadClass(Context context, String className) {
ClassLoader cl = context.getLoader().getClassLoader();
Log log = context.getLogger();
Class<?> clazz = null;
try {
clazz = cl.loadClass(className);
} catch (ClassNotFoundException e) {
log.debug(sm.getString("introspection.classLoadFailed", className), e);
} catch (NoClassDefFoundError e) {
log.debug(sm.getString("introspection.classLoadFailed", className), e);
} catch (ClassFormatError e) {
log.debug(sm.getString("introspection.classLoadFailed", className), e);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.debug(sm.getString("introspection.classLoadFailed", className), t);
}
return clazz;
}
/**
* Converts the primitive type to its corresponding wrapper.
*
* @param clazz
* Class that will be evaluated
* @return if the parameter is a primitive type returns its wrapper;
* otherwise returns the same class
*/
public static Class<?> convertPrimitiveType(Class<?> clazz) {
if (clazz.equals(char.class)) {
return Character.class;
} else if (clazz.equals(int.class)) {
return Integer.class;
} else if (clazz.equals(boolean.class)) {
return Boolean.class;
} else if (clazz.equals(double.class)) {
return Double.class;
} else if (clazz.equals(byte.class)) {
return Byte.class;
} else if (clazz.equals(short.class)) {
return Short.class;
} else if (clazz.equals(long.class)) {
return Long.class;
} else if (clazz.equals(float.class)) {
return Float.class;
} else {
return clazz;
}
}
}
| plumer/codana | tomcat_files/8.0.22/Introspection.java | Java | mit | 6,566 |
#
# THIS IS WORK IN PROGRESS
#
# The Python Imaging Library.
# $Id$
#
# FlashPix support for PIL
#
# History:
# 97-01-25 fl Created (reads uncompressed RGB images only)
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1997.
#
# See the README file for information on usage and redistribution.
#
from __future__ import print_function
from . import Image, ImageFile
from ._binary import i32le as i32, i8
import olefile
__version__ = "0.1"
# we map from colour field tuples to (mode, rawmode) descriptors
MODES = {
# opacity
(0x00007ffe): ("A", "L"),
# monochrome
(0x00010000,): ("L", "L"),
(0x00018000, 0x00017ffe): ("RGBA", "LA"),
# photo YCC
(0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),
(0x00028000, 0x00028001, 0x00028002, 0x00027ffe): ("RGBA", "YCCA;P"),
# standard RGB (NIFRGB)
(0x00030000, 0x00030001, 0x00030002): ("RGB", "RGB"),
(0x00038000, 0x00038001, 0x00038002, 0x00037ffe): ("RGBA", "RGBA"),
}
#
# --------------------------------------------------------------------
def _accept(prefix):
return prefix[:8] == olefile.MAGIC
##
# Image plugin for the FlashPix images.
class FpxImageFile(ImageFile.ImageFile):
format = "FPX"
format_description = "FlashPix"
def _open(self):
#
# read the OLE directory and see if this is a likely
# to be a FlashPix file
try:
self.ole = olefile.OleFileIO(self.fp)
except IOError:
raise SyntaxError("not an FPX file; invalid OLE file")
if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
raise SyntaxError("not an FPX file; bad root CLSID")
self._open_index(1)
def _open_index(self, index=1):
#
# get the Image Contents Property Set
prop = self.ole.getproperties([
"Data Object Store %06d" % index,
"\005Image Contents"
])
# size (highest resolution)
self._size = prop[0x1000002], prop[0x1000003]
size = max(self.size)
i = 1
while size > 64:
size = size / 2
i += 1
self.maxid = i - 1
# mode. instead of using a single field for this, flashpix
# requires you to specify the mode for each channel in each
# resolution subimage, and leaves it to the decoder to make
# sure that they all match. for now, we'll cheat and assume
# that this is always the case.
id = self.maxid << 16
s = prop[0x2000002 | id]
colors = []
for i in range(i32(s, 4)):
# note: for now, we ignore the "uncalibrated" flag
colors.append(i32(s, 8+i*4) & 0x7fffffff)
self.mode, self.rawmode = MODES[tuple(colors)]
# load JPEG tables, if any
self.jpeg = {}
for i in range(256):
id = 0x3000001 | (i << 16)
if id in prop:
self.jpeg[i] = prop[id]
self._open_subimage(1, self.maxid)
def _open_subimage(self, index=1, subimage=0):
#
# setup tile descriptors for a given subimage
stream = [
"Data Object Store %06d" % index,
"Resolution %04d" % subimage,
"Subimage 0000 Header"
]
fp = self.ole.openstream(stream)
# skip prefix
fp.read(28)
# header stream
s = fp.read(36)
size = i32(s, 4), i32(s, 8)
# tilecount = i32(s, 12)
tilesize = i32(s, 16), i32(s, 20)
# channels = i32(s, 24)
offset = i32(s, 28)
length = i32(s, 32)
if size != self.size:
raise IOError("subimage mismatch")
# get tile descriptors
fp.seek(28 + offset)
s = fp.read(i32(s, 12) * length)
x = y = 0
xsize, ysize = size
xtile, ytile = tilesize
self.tile = []
for i in range(0, len(s), length):
compression = i32(s, i+8)
if compression == 0:
self.tile.append(("raw", (x, y, x+xtile, y+ytile),
i32(s, i) + 28, (self.rawmode)))
elif compression == 1:
# FIXME: the fill decoder is not implemented
self.tile.append(("fill", (x, y, x+xtile, y+ytile),
i32(s, i) + 28, (self.rawmode, s[12:16])))
elif compression == 2:
internal_color_conversion = i8(s[14])
jpeg_tables = i8(s[15])
rawmode = self.rawmode
if internal_color_conversion:
# The image is stored as usual (usually YCbCr).
if rawmode == "RGBA":
# For "RGBA", data is stored as YCbCrA based on
# negative RGB. The following trick works around
# this problem :
jpegmode, rawmode = "YCbCrK", "CMYK"
else:
jpegmode = None # let the decoder decide
else:
# The image is stored as defined by rawmode
jpegmode = rawmode
self.tile.append(("jpeg", (x, y, x+xtile, y+ytile),
i32(s, i) + 28, (rawmode, jpegmode)))
# FIXME: jpeg tables are tile dependent; the prefix
# data must be placed in the tile descriptor itself!
if jpeg_tables:
self.tile_prefix = self.jpeg[jpeg_tables]
else:
raise IOError("unknown/invalid compression")
x = x + xtile
if x >= xsize:
x, y = 0, y + ytile
if y >= ysize:
break # isn't really required
self.stream = stream
self.fp = None
def load(self):
if not self.fp:
self.fp = self.ole.openstream(self.stream[:2] +
["Subimage 0000 Data"])
return ImageFile.ImageFile.load(self)
#
# --------------------------------------------------------------------
Image.register_open(FpxImageFile.format, FpxImageFile, _accept)
Image.register_extension(FpxImageFile.format, ".fpx")
| ryfeus/lambda-packs | pytorch/source/PIL/FpxImagePlugin.py | Python | mit | 6,282 |
<?php
namespace Backend\Modules\ContentBlocks\Event;
final class ContentBlockCreated extends ContentBlockEvent
{
/**
* @var string The name the listener needs to listen to to catch this event.
*/
const EVENT_NAME = 'content_blocks.event.content_block_created';
}
| Thijzer/forkcms | src/Backend/Modules/ContentBlocks/Event/ContentBlockCreated.php | PHP | mit | 283 |
/*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <srs_utest_amf0.hpp>
#include <string>
using namespace std;
#include <srs_core_autofree.hpp>
#include <srs_kernel_error.hpp>
#include <srs_kernel_stream.hpp>
// user scenario: coding and decoding with amf0
VOID TEST(AMF0Test, ScenarioMain)
{
// coded amf0 object
int nb_bytes = 0;
char* bytes = NULL;
// coding data to binaries by amf0
// for example, send connect app response to client.
if (true) {
// props: object
// fmsVer: string
// capabilities: number
// mode: number
// info: object
// level: string
// code: string
// descrption: string
// objectEncoding: number
// data: array
// version: string
// srs_sig: string
SrsAmf0Object* props = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, props, false);
props->set("fmsVer", SrsAmf0Any::str("FMS/3,5,3,888"));
props->set("capabilities", SrsAmf0Any::number(253));
props->set("mode", SrsAmf0Any::number(123));
SrsAmf0Object* info = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, info, false);
info->set("level", SrsAmf0Any::str("info"));
info->set("code", SrsAmf0Any::str("NetStream.Connnect.Success"));
info->set("descrption", SrsAmf0Any::str("connected"));
info->set("objectEncoding", SrsAmf0Any::number(3));
SrsAmf0EcmaArray* data = SrsAmf0Any::ecma_array();
info->set("data", data);
data->set("version", SrsAmf0Any::str("FMS/3,5,3,888"));
data->set("srs_sig", SrsAmf0Any::str("srs"));
// buf store the serialized props/info
nb_bytes = props->total_size() + info->total_size();
ASSERT_GT(nb_bytes, 0);
bytes = new char[nb_bytes];
// use SrsStream to write props/info to binary buf.
SrsStream s;
EXPECT_EQ(ERROR_SUCCESS, s.initialize(bytes, nb_bytes));
EXPECT_EQ(ERROR_SUCCESS, props->write(&s));
EXPECT_EQ(ERROR_SUCCESS, info->write(&s));
EXPECT_TRUE(s.empty());
// now, user can use the buf
EXPECT_EQ(0x03, bytes[0]);
EXPECT_EQ(0x09, bytes[nb_bytes - 1]);
}
SrsAutoFree(char, bytes, true);
// decoding amf0 object from bytes
// when user know the schema
if (true) {
ASSERT_TRUE(NULL != bytes);
// use SrsStream to assist amf0 object to read from bytes.
SrsStream s;
EXPECT_EQ(ERROR_SUCCESS, s.initialize(bytes, nb_bytes));
// decoding
// if user know the schema, for instance, it's an amf0 object,
// user can use specified object to decoding.
SrsAmf0Object* props = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, props, false);
EXPECT_EQ(ERROR_SUCCESS, props->read(&s));
// user can use specified object to decoding.
SrsAmf0Object* info = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, info, false);
EXPECT_EQ(ERROR_SUCCESS, info->read(&s));
// use the decoded data.
SrsAmf0Any* prop = NULL;
// if user requires specified property, use ensure of amf0 object
EXPECT_TRUE(NULL != (prop = props->ensure_property_string("fmsVer")));
// the property can assert to string.
ASSERT_TRUE(prop->is_string());
// get the prop string value.
EXPECT_STREQ("FMS/3,5,3,888", prop->to_str().c_str());
// get other type property value
EXPECT_TRUE(NULL != (prop = info->get_property("data")));
// we cannot assert the property is ecma array
if (prop->is_ecma_array()) {
SrsAmf0EcmaArray* data = prop->to_ecma_array();
// it must be a ecma array.
ASSERT_TRUE(NULL != data);
// get property of array
EXPECT_TRUE(NULL != (prop = data->ensure_property_string("srs_sig")));
ASSERT_TRUE(prop->is_string());
EXPECT_STREQ("srs", prop->to_str().c_str());
}
// confidence about the schema
EXPECT_TRUE(NULL != (prop = info->ensure_property_string("level")));
ASSERT_TRUE(prop->is_string());
EXPECT_STREQ("info", prop->to_str().c_str());
}
// use any to decoding it,
// if user donot know the schema
if (true) {
ASSERT_TRUE(NULL != bytes);
// use SrsStream to assist amf0 object to read from bytes.
SrsStream s;
EXPECT_EQ(ERROR_SUCCESS, s.initialize(bytes, nb_bytes));
// decoding a amf0 any, for user donot know
SrsAmf0Any* any = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &any));
SrsAutoFree(SrsAmf0Any, any, false);
// for amf0 object
if (any->is_object()) {
SrsAmf0Object* obj = any->to_object();
ASSERT_TRUE(NULL != obj);
// use foreach to process properties
for (int i = 0; i < obj->count(); ++i) {
string name = obj->key_at(i);
SrsAmf0Any* value = obj->value_at(i);
// use the property name
EXPECT_TRUE("" != name);
// use the property value
EXPECT_TRUE(NULL != value);
}
}
}
}
VOID TEST(AMF0Test, ApiSize)
{
// size of elem
EXPECT_EQ(2+6, SrsAmf0Size::utf8("winlin"));
EXPECT_EQ(2+0, SrsAmf0Size::utf8(""));
EXPECT_EQ(1+2+6, SrsAmf0Size::str("winlin"));
EXPECT_EQ(1+2+0, SrsAmf0Size::str(""));
EXPECT_EQ(1+8, SrsAmf0Size::number());
EXPECT_EQ(1, SrsAmf0Size::null());
EXPECT_EQ(1, SrsAmf0Size::undefined());
EXPECT_EQ(1+1, SrsAmf0Size::boolean());
// object: empty
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
// object: elem
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("age")+SrsAmf0Size::number();
o->set("age", SrsAmf0Any::number(9));
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("email")+SrsAmf0Size::null();
o->set("email", SrsAmf0Any::null());
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("email")+SrsAmf0Size::undefined();
o->set("email", SrsAmf0Any::undefined());
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("sex")+SrsAmf0Size::boolean();
o->set("sex", SrsAmf0Any::boolean(true));
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
// array: empty
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
// array: elem
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("age")+SrsAmf0Size::number();
o->set("age", SrsAmf0Any::number(9));
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("email")+SrsAmf0Size::null();
o->set("email", SrsAmf0Any::null());
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("email")+SrsAmf0Size::undefined();
o->set("email", SrsAmf0Any::undefined());
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("sex")+SrsAmf0Size::boolean();
o->set("sex", SrsAmf0Any::boolean(true));
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
// object: array
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0EcmaArray* args = SrsAmf0Any::ecma_array();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::ecma_array(args);
o->set("args", args);
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0EcmaArray* args = SrsAmf0Any::ecma_array();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::ecma_array(args);
o->set("args", args);
SrsAmf0EcmaArray* params = SrsAmf0Any::ecma_array();
params->set("p1", SrsAmf0Any::number(10));
size += SrsAmf0Size::utf8("params")+SrsAmf0Size::ecma_array(params);
o->set("params", params);
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
// array: object
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0Object* args = SrsAmf0Any::object();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::object(args);
o->set("args", args);
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0Object* args = SrsAmf0Any::object();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::object(args);
o->set("args", args);
SrsAmf0Object* params = SrsAmf0Any::object();
params->set("p1", SrsAmf0Any::number(10));
size += SrsAmf0Size::utf8("params")+SrsAmf0Size::object(params);
o->set("params", params);
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
// object: object
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0Object* args = SrsAmf0Any::object();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::object(args);
o->set("args", args);
SrsAmf0Object* params = SrsAmf0Any::object();
params->set("p1", SrsAmf0Any::number(10));
size += SrsAmf0Size::utf8("params")+SrsAmf0Size::object(params);
o->set("params", params);
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
// array: array
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0EcmaArray* args = SrsAmf0Any::ecma_array();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::ecma_array(args);
o->set("args", args);
SrsAmf0EcmaArray* params = SrsAmf0Any::ecma_array();
params->set("p1", SrsAmf0Any::number(10));
size += SrsAmf0Size::utf8("params")+SrsAmf0Size::ecma_array(params);
o->set("params", params);
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
}
VOID TEST(AMF0Test, ApiAnyElem)
{
SrsAmf0Any* o = NULL;
// string
if (true) {
o = SrsAmf0Any::str();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_string());
EXPECT_STREQ("", o->to_str().c_str());
}
if (true) {
o = SrsAmf0Any::str("winlin");
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_string());
EXPECT_STREQ("winlin", o->to_str().c_str());
}
// bool
if (true) {
o = SrsAmf0Any::boolean();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_boolean());
EXPECT_FALSE(o->to_boolean());
}
if (true) {
o = SrsAmf0Any::boolean(false);
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_boolean());
EXPECT_FALSE(o->to_boolean());
}
if (true) {
o = SrsAmf0Any::boolean(true);
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_boolean());
EXPECT_TRUE(o->to_boolean());
}
// number
if (true) {
o = SrsAmf0Any::number();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_number());
EXPECT_DOUBLE_EQ(0, o->to_number());
}
if (true) {
o = SrsAmf0Any::number(100);
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_number());
EXPECT_DOUBLE_EQ(100, o->to_number());
}
if (true) {
o = SrsAmf0Any::number(-100);
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_number());
EXPECT_DOUBLE_EQ(-100, o->to_number());
}
// null
if (true) {
o = SrsAmf0Any::null();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_null());
}
// undefined
if (true) {
o = SrsAmf0Any::undefined();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_undefined());
}
}
VOID TEST(AMF0Test, ApiAnyIO)
{
SrsStream s;
SrsAmf0Any* o = NULL;
char buf[1024];
memset(buf, 0, sizeof(buf));
EXPECT_EQ(ERROR_SUCCESS, s.initialize(buf, sizeof(buf)));
// object eof
if (true) {
s.reset();
s.current()[2] = 0x09;
o = SrsAmf0Any::object_eof();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_EQ(3, s.pos());
s.reset();
s.current()[0] = 0x01;
EXPECT_NE(ERROR_SUCCESS, o->read(&s));
}
if (true) {
s.reset();
o = SrsAmf0Any::object_eof();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_EQ(3, s.pos());
s.skip(-3);
EXPECT_EQ(0x09, s.read_3bytes());
}
// string
if (true) {
s.reset();
o = SrsAmf0Any::str("winlin");
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(2, s.read_1bytes());
EXPECT_EQ(6, s.read_2bytes());
EXPECT_EQ('w', s.current()[0]);
EXPECT_EQ('n', s.current()[5]);
s.reset();
s.current()[3] = 'x';
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_STREQ("xinlin", o->to_str().c_str());
}
// number
if (true) {
s.reset();
o = SrsAmf0Any::number(10);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(0, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_DOUBLE_EQ(10, o->to_number());
}
// boolean
if (true) {
s.reset();
o = SrsAmf0Any::boolean(true);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(1, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_TRUE(o->to_boolean());
}
if (true) {
s.reset();
o = SrsAmf0Any::boolean(false);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(1, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_FALSE(o->to_boolean());
}
// null
if (true) {
s.reset();
o = SrsAmf0Any::null();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(5, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_TRUE(o->is_null());
}
// undefined
if (true) {
s.reset();
o = SrsAmf0Any::undefined();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(6, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_TRUE(o->is_undefined());
}
// any: string
if (true) {
s.reset();
o = SrsAmf0Any::str("winlin");
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_string());
EXPECT_STREQ("winlin", po->to_str().c_str());
}
// any: number
if (true) {
s.reset();
o = SrsAmf0Any::number(10);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_number());
EXPECT_DOUBLE_EQ(10, po->to_number());
}
// any: boolean
if (true) {
s.reset();
o = SrsAmf0Any::boolean(true);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_boolean());
EXPECT_TRUE(po->to_boolean());
}
// any: null
if (true) {
s.reset();
o = SrsAmf0Any::null();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_null());
}
// any: undefined
if (true) {
s.reset();
o = SrsAmf0Any::undefined();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_undefined());
}
// mixed any
if (true) {
s.reset();
o = SrsAmf0Any::str("winlin");
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
o = SrsAmf0Any::number(10);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
o = SrsAmf0Any::boolean(true);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
o = SrsAmf0Any::null();
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
o = SrsAmf0Any::undefined();
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_string());
EXPECT_STREQ("winlin", po->to_str().c_str());
srs_freep(po);
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_number());
EXPECT_DOUBLE_EQ(10, po->to_number());
srs_freep(po);
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_boolean());
EXPECT_TRUE(po->to_boolean());
srs_freep(po);
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_null());
srs_freep(po);
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_undefined());
srs_freep(po);
}
}
VOID TEST(AMF0Test, ApiAnyAssert)
{
SrsStream s;
SrsAmf0Any* o = NULL;
char buf[1024];
memset(buf, 0, sizeof(buf));
EXPECT_EQ(ERROR_SUCCESS, s.initialize(buf, sizeof(buf)));
// read any
if (true) {
s.reset();
s.current()[0] = 0x12;
EXPECT_NE(ERROR_SUCCESS, srs_amf0_read_any(&s, &o));
EXPECT_TRUE(NULL == o);
srs_freep(o);
}
// any convert
if (true) {
o = SrsAmf0Any::str();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_string());
}
if (true) {
o = SrsAmf0Any::number();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_number());
}
if (true) {
o = SrsAmf0Any::boolean();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_boolean());
}
if (true) {
o = SrsAmf0Any::null();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_null());
}
if (true) {
o = SrsAmf0Any::undefined();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_undefined());
}
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_object());
}
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_ecma_array());
}
// empty object
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Any, o, false);
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(1+3, s.pos());
}
// empty ecma array
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0Any, o, false);
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(1+4+3, s.pos());
}
}
VOID TEST(AMF0Test, ApiObjectProps)
{
SrsAmf0Object* o = NULL;
// get/set property
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
EXPECT_TRUE(NULL == o->get_property("name"));
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_TRUE(NULL != o->get_property("name"));
EXPECT_TRUE(NULL == o->get_property("age"));
o->set("age", SrsAmf0Any::number(100));
EXPECT_TRUE(NULL != o->get_property("age"));
}
// index property
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_STREQ("name", o->key_at(0).c_str());
ASSERT_TRUE(o->value_at(0)->is_string());
EXPECT_STREQ("winlin", o->value_at(0)->to_str().c_str());
o->set("age", SrsAmf0Any::number(100));
EXPECT_STREQ("name", o->key_at(0).c_str());
ASSERT_TRUE(o->value_at(0)->is_string());
EXPECT_STREQ("winlin", o->value_at(0)->to_str().c_str());
EXPECT_STREQ("age", o->key_at(1).c_str());
ASSERT_TRUE(o->value_at(1)->is_number());
EXPECT_DOUBLE_EQ(100, o->value_at(1)->to_number());
}
// ensure property
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
EXPECT_TRUE(NULL == o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("age"));
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_TRUE(NULL != o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("age"));
o->set("age", SrsAmf0Any::number(100));
EXPECT_TRUE(NULL != o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("name"));
EXPECT_TRUE(NULL != o->ensure_property_number("age"));
EXPECT_TRUE(NULL == o->ensure_property_string("age"));
}
// count
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
EXPECT_EQ(0, o->count());
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(1, o->count());
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(1, o->count());
o->set("age", SrsAmf0Any::number(100));
EXPECT_EQ(2, o->count());
}
}
VOID TEST(AMF0Test, ApiEcmaArrayProps)
{
SrsAmf0EcmaArray* o = NULL;
// get/set property
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
EXPECT_TRUE(NULL == o->get_property("name"));
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_TRUE(NULL != o->get_property("name"));
EXPECT_TRUE(NULL == o->get_property("age"));
o->set("age", SrsAmf0Any::number(100));
EXPECT_TRUE(NULL != o->get_property("age"));
}
// index property
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_STREQ("name", o->key_at(0).c_str());
ASSERT_TRUE(o->value_at(0)->is_string());
EXPECT_STREQ("winlin", o->value_at(0)->to_str().c_str());
o->set("age", SrsAmf0Any::number(100));
EXPECT_STREQ("name", o->key_at(0).c_str());
ASSERT_TRUE(o->value_at(0)->is_string());
EXPECT_STREQ("winlin", o->value_at(0)->to_str().c_str());
EXPECT_STREQ("age", o->key_at(1).c_str());
ASSERT_TRUE(o->value_at(1)->is_number());
EXPECT_DOUBLE_EQ(100, o->value_at(1)->to_number());
}
// ensure property
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
EXPECT_TRUE(NULL == o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("age"));
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_TRUE(NULL != o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("age"));
o->set("age", SrsAmf0Any::number(100));
EXPECT_TRUE(NULL != o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("name"));
EXPECT_TRUE(NULL != o->ensure_property_number("age"));
EXPECT_TRUE(NULL == o->ensure_property_string("age"));
}
// count
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
EXPECT_EQ(0, o->count());
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(1, o->count());
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(1, o->count());
o->set("age", SrsAmf0Any::number(100));
EXPECT_EQ(2, o->count());
}
}
| wjyadlx/simple-rtmp-server | trunk/src/utest/srs_utest_amf0.cpp | C++ | mit | 32,587 |
#!/usr/bin/env node
'use strict';
/**
* bitcoind.js example
*/
process.title = 'bitcoind.js';
/**
* daemon
*/
var daemon = require('../').daemon({
datadir: process.env.BITCOINDJS_DIR || '~/.bitcoin',
});
daemon.on('ready', function() {
console.log('ready');
});
daemon.on('tx', function(txid) {
console.log('txid', txid);
});
daemon.on('error', function(err) {
daemon.log('error="%s"', err.message);
});
daemon.on('open', function(status) {
daemon.log('status="%s"', status);
});
| bankonme/bitcoind.js | example/index.js | JavaScript | mit | 502 |
package protocol
import (
"crypto/hmac"
"crypto/md5"
"hash"
"v2ray.com/core/common"
"v2ray.com/core/common/uuid"
)
const (
IDBytesLen = 16
)
type IDHash func(key []byte) hash.Hash
func DefaultIDHash(key []byte) hash.Hash {
return hmac.New(md5.New, key)
}
// The ID of en entity, in the form of a UUID.
type ID struct {
uuid uuid.UUID
cmdKey [IDBytesLen]byte
}
// Equals returns true if this ID equals to the other one.
func (id *ID) Equals(another *ID) bool {
return id.uuid.Equals(&(another.uuid))
}
func (id *ID) Bytes() []byte {
return id.uuid.Bytes()
}
func (id *ID) String() string {
return id.uuid.String()
}
func (id *ID) UUID() uuid.UUID {
return id.uuid
}
func (id ID) CmdKey() []byte {
return id.cmdKey[:]
}
// NewID returns an ID with given UUID.
func NewID(uuid uuid.UUID) *ID {
id := &ID{uuid: uuid}
md5hash := md5.New()
common.Must2(md5hash.Write(uuid.Bytes()))
common.Must2(md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21")))
md5hash.Sum(id.cmdKey[:0])
return id
}
func nextID(u *uuid.UUID) uuid.UUID {
md5hash := md5.New()
common.Must2(md5hash.Write(u.Bytes()))
common.Must2(md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81")))
var newid uuid.UUID
for {
md5hash.Sum(newid[:0])
if !newid.Equals(u) {
return newid
}
common.Must2(md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2")))
}
}
func NewAlterIDs(primary *ID, alterIDCount uint16) []*ID {
alterIDs := make([]*ID, alterIDCount)
prevID := primary.UUID()
for idx := range alterIDs {
newid := nextID(&prevID)
alterIDs[idx] = NewID(newid)
prevID = newid
}
return alterIDs
}
| LiuWenJu/v2ray-core | common/protocol/id.go | GO | mit | 1,634 |
<?php
$TRANSLATIONS = array(
"Shared with you" => "Опубликованы вами",
"Shared with others" => "Опубликованы другими",
"Shared by link" => "Доступно по ссылке",
"No files have been shared with you yet." => "Вы ещё не опубликовали файлы",
"You haven't shared any files yet." => "Вы не имеете файлов в открытом доступе",
"Add {name} from {owner}@{remote}" => "Добавить {name} из {owner}@{remote}",
"Password" => "Пароль",
"Invalid ownCloud url" => "Не верный ownCloud адрес",
"Shared by {owner}" => "Доступ открыл {owner}",
"Shared by" => "Опубликовано",
"This share is password-protected" => "Для доступа к информации необходимо ввести пароль",
"The password is wrong. Try again." => "Неверный пароль. Попробуйте еще раз.",
"Name" => "Имя",
"Share time" => "Дата публикации",
"Sorry, this link doesn’t seem to work anymore." => "Эта ссылка устарела и более не действительна.",
"Reasons might be:" => "Причиной может быть:",
"the item was removed" => "объект был удалён",
"the link expired" => "срок действия ссылки истёк",
"sharing is disabled" => "доступ к информации заблокирован",
"For more info, please ask the person who sent this link." => "Для получения дополнительной информации, пожалуйста, свяжитесь с тем, кто отправил Вам эту ссылку.",
"Save" => "Сохранить",
"Download" => "Скачать",
"Download %s" => "Скачать %s",
"Direct link" => "Прямая ссылка"
);
$PLURAL_FORMS = "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);";
| ACOKing/ArcherSys | owncloud-serv/apps/files_sharing/l10n/ru.php | PHP | mit | 1,975 |
<?php
class Node_BreakStmt extends NodeAbstract
{
} | VelvetMirror/test | vendor/bundles/Sensio/Bundle/GeneratorBundle/PHP-Parser/lib/Node/BreakStmt.php | PHP | mit | 52 |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Check DNSSEC trust chain.
# Todo: verify expiration dates
#
# Based on
# http://backreference.org/2010/11/17/dnssec-verification-with-dig/
# https://github.com/rthalley/dnspython/blob/master/tests/test_dnssec.py
import dns
import dns.name
import dns.query
import dns.dnssec
import dns.message
import dns.resolver
import dns.rdatatype
import dns.rdtypes.ANY.NS
import dns.rdtypes.ANY.CNAME
import dns.rdtypes.ANY.DLV
import dns.rdtypes.ANY.DNSKEY
import dns.rdtypes.ANY.DS
import dns.rdtypes.ANY.NSEC
import dns.rdtypes.ANY.NSEC3
import dns.rdtypes.ANY.NSEC3PARAM
import dns.rdtypes.ANY.RRSIG
import dns.rdtypes.ANY.SOA
import dns.rdtypes.ANY.TXT
import dns.rdtypes.IN.A
import dns.rdtypes.IN.AAAA
from .logging import get_logger
_logger = get_logger(__name__)
# hard-coded trust anchors (root KSKs)
trust_anchors = [
# KSK-2017:
dns.rrset.from_text('.', 1 , 'IN', 'DNSKEY', '257 3 8 AwEAAaz/tAm8yTn4Mfeh5eyI96WSVexTBAvkMgJzkKTOiW1vkIbzxeF3+/4RgWOq7HrxRixHlFlExOLAJr5emLvN7SWXgnLh4+B5xQlNVz8Og8kvArMtNROxVQuCaSnIDdD5LKyWbRd2n9WGe2R8PzgCmr3EgVLrjyBxWezF0jLHwVN8efS3rCj/EWgvIWgb9tarpVUDK/b58Da+sqqls3eNbuv7pr+eoZG+SrDK6nWeL3c6H5Apxz7LjVc1uTIdsIXxuOLYA4/ilBmSVIzuDWfdRUfhHdY6+cn8HFRm+2hM8AnXGXws9555KrUB5qihylGa8subX2Nn6UwNR1AkUTV74bU='),
# KSK-2010:
dns.rrset.from_text('.', 15202, 'IN', 'DNSKEY', '257 3 8 AwEAAagAIKlVZrpC6Ia7gEzahOR+9W29euxhJhVVLOyQbSEW0O8gcCjF FVQUTf6v58fLjwBd0YI0EzrAcQqBGCzh/RStIoO8g0NfnfL2MTJRkxoX bfDaUeVPQuYEhg37NZWAJQ9VnMVDxP/VHL496M/QZxkjf5/Efucp2gaD X6RS6CXpoY68LsvPVjR0ZSwzz1apAzvN9dlzEheX7ICJBBtuA6G3LQpz W5hOA2hzCTMjJPJ8LbqF6dsV6DoBQzgul0sGIcGOYl7OyQdXfZ57relS Qageu+ipAdTTJ25AsRTAoub8ONGcLmqrAmRLKBP1dfwhYB4N7knNnulq QxA+Uk1ihz0='),
]
def _check_query(ns, sub, _type, keys):
q = dns.message.make_query(sub, _type, want_dnssec=True)
response = dns.query.tcp(q, ns, timeout=5)
assert response.rcode() == 0, 'No answer'
answer = response.answer
assert len(answer) != 0, ('No DNS record found', sub, _type)
assert len(answer) != 1, ('No DNSSEC record found', sub, _type)
if answer[0].rdtype == dns.rdatatype.RRSIG:
rrsig, rrset = answer
elif answer[1].rdtype == dns.rdatatype.RRSIG:
rrset, rrsig = answer
else:
raise Exception('No signature set in record')
if keys is None:
keys = {dns.name.from_text(sub):rrset}
dns.dnssec.validate(rrset, rrsig, keys)
return rrset
def _get_and_validate(ns, url, _type):
# get trusted root key
root_rrset = None
for dnskey_rr in trust_anchors:
try:
# Check if there is a valid signature for the root dnskey
root_rrset = _check_query(ns, '', dns.rdatatype.DNSKEY, {dns.name.root: dnskey_rr})
break
except dns.dnssec.ValidationFailure:
# It's OK as long as one key validates
continue
if not root_rrset:
raise dns.dnssec.ValidationFailure('None of the trust anchors found in DNS')
keys = {dns.name.root: root_rrset}
# top-down verification
parts = url.split('.')
for i in range(len(parts), 0, -1):
sub = '.'.join(parts[i-1:])
name = dns.name.from_text(sub)
# If server is authoritative, don't fetch DNSKEY
query = dns.message.make_query(sub, dns.rdatatype.NS)
response = dns.query.udp(query, ns, 3)
assert response.rcode() == dns.rcode.NOERROR, "query error"
rrset = response.authority[0] if len(response.authority) > 0 else response.answer[0]
rr = rrset[0]
if rr.rdtype == dns.rdatatype.SOA:
continue
# get DNSKEY (self-signed)
rrset = _check_query(ns, sub, dns.rdatatype.DNSKEY, None)
# get DS (signed by parent)
ds_rrset = _check_query(ns, sub, dns.rdatatype.DS, keys)
# verify that a signed DS validates DNSKEY
for ds in ds_rrset:
for dnskey in rrset:
htype = 'SHA256' if ds.digest_type == 2 else 'SHA1'
good_ds = dns.dnssec.make_ds(name, dnskey, htype)
if ds == good_ds:
break
else:
continue
break
else:
raise Exception("DS does not match DNSKEY")
# set key for next iteration
keys = {name: rrset}
# get TXT record (signed by zone)
rrset = _check_query(ns, url, _type, keys)
return rrset
def query(url, rtype):
# 8.8.8.8 is Google's public DNS server
nameservers = ['8.8.8.8']
ns = nameservers[0]
try:
out = _get_and_validate(ns, url, rtype)
validated = True
except Exception as e:
_logger.info(f"DNSSEC error: {repr(e)}")
out = dns.resolver.resolve(url, rtype)
validated = False
return out, validated
| wakiyamap/electrum-mona | electrum_mona/dnssec.py | Python | mit | 5,922 |
SS::Application.routes.draw do
Gws::Report::Initializer
concern :deletion do
get :delete, on: :member
delete :destroy_all, on: :collection, path: ''
end
gws 'report' do
get '/' => redirect { |p, req| "#{req.path}/forms" }, as: :setting
resources :forms, concerns: :deletion do
match :publish, on: :member, via: [:get, :post]
match :depublish, on: :member, via: [:get, :post]
resources :columns, concerns: :deletion
end
resources :categories, concerns: [:deletion]
scope :files do
get '/' => redirect { |p, req| "#{req.path}/inbox" }, as: :files_main
resources :trashes, concerns: [:deletion], except: [:new, :create, :edit, :update] do
match :undo_delete, on: :member, via: [:get, :post]
end
resources :files, path: ':state', except: [:destroy] do
get :print, on: :member
match :publish, on: :member, via: [:get, :post]
match :depublish, on: :member, via: [:get, :post]
match :copy, on: :member, via: [:get, :post]
match :soft_delete, on: :member, via: [:get, :post]
post :soft_delete_all, on: :collection
end
resources :files, path: ':state/:form_id', only: [:new, :create], as: 'form_files'
end
namespace 'apis' do
get 'categories' => 'categories#index'
get 'files' => 'files#index'
end
end
end
| itowtips/shirasagi | config/routes/gws/report/routes.rb | Ruby | mit | 1,375 |
var path = require('path');
var util = require('util');
var Item = require('./item');
var constants = process.binding('constants');
/**
* A directory.
* @constructor
*/
function Directory() {
Item.call(this);
/**
* Items in this directory.
* @type {Object.<string, Item>}
*/
this._items = {};
/**
* Permissions.
*/
this._mode = 0777;
}
util.inherits(Directory, Item);
/**
* Add an item to the directory.
* @param {string} name The name to give the item.
* @param {Item} item The item to add.
* @return {Item} The added item.
*/
Directory.prototype.addItem = function(name, item) {
if (this._items.hasOwnProperty(name)) {
throw new Error('Item with the same name already exists: ' + name);
}
this._items[name] = item;
++item.links;
if (item instanceof Directory) {
// for '.' entry
++item.links;
// for subdirectory
++this.links;
}
this.setMTime(new Date());
return item;
};
/**
* Get a named item.
* @param {string} name Item name.
* @return {Item} The named item (or null if none).
*/
Directory.prototype.getItem = function(name) {
var item = null;
if (this._items.hasOwnProperty(name)) {
item = this._items[name];
}
return item;
};
/**
* Remove an item.
* @param {string} name Name of item to remove.
* @return {Item} The orphan item.
*/
Directory.prototype.removeItem = function(name) {
if (!this._items.hasOwnProperty(name)) {
throw new Error('Item does not exist in directory: ' + name);
}
var item = this._items[name];
delete this._items[name];
--item.links;
if (item instanceof Directory) {
// for '.' entry
--item.links;
// for subdirectory
--this.links;
}
this.setMTime(new Date());
return item;
};
/**
* Get list of item names in this directory.
* @return {Array.<string>} Item names.
*/
Directory.prototype.list = function() {
return Object.keys(this._items).sort();
};
/**
* Get directory stats.
* @return {Object} Stats properties.
*/
Directory.prototype.getStats = function() {
var stats = Item.prototype.getStats.call(this);
stats.mode = this.getMode() | constants.S_IFDIR;
stats.size = 1;
stats.blocks = 1;
return stats;
};
/**
* Export the constructor.
* @type {function()}
*/
exports = module.exports = Directory;
| wenjoy/homePage | node_modules/node-captcha/node_modules/canvas/node_modules/mocha/node_modules/mkdirp/node_modules/mock-fs/lib/directory.js | JavaScript | mit | 2,300 |
module MigrationConstraintHelpers
# Creates a foreign key from +table+.+field+ against referenced_table.referenced_field
#
# table: The tablename
# field: A field of the table
# referenced_table: The table which contains the field referenced
# referenced_field: The field (which should be part of the primary key) of the referenced table
# cascade: delete & update on cascade?
def foreign_key(table, field, referenced_table, referenced_field = :id, cascade = true)
execute "ALTER TABLE #{table} ADD CONSTRAINT #{constraint_name(table, field)}
FOREIGN KEY #{constraint_name(table, field)} (#{field_list(field)})
REFERENCES #{referenced_table}(#{field_list(referenced_field)})
#{(cascade ? 'ON DELETE CASCADE ON UPDATE CASCADE' : '')}"
end
# Drops a foreign key from +table+.+field+ that has been created before with
# foreign_key method
#
# table: The table name
# field: A field (or array of fields) of the table
def drop_foreign_key(table, field)
execute "ALTER TABLE #{table} DROP FOREIGN KEY #{constraint_name(table, field)}"
end
# Creates a primary key for +table+, which right now HAS NOT primary key defined
#
# table: The table name
# field: A field (or array of fields) of the table that will be part of the primary key
def primary_key(table, field)
execute "ALTER TABLE #{table} ADD PRIMARY KEY(#{field_list(field)})"
end
private
# Creates a constraint name for table and field given as parameters
#
# table: The table name
# field: A field of the table
def constraint_name(table, field)
"fk_#{table}_#{field_list_name(field)}"
end
def field_list(fields)
fields.is_a?(Array) ? fields.join(',') : fields
end
def field_list_name(fields)
fields.is_a?(Array) ? fields.join('_') : fields
end
end
| beachyapp/standalone-migrations | vendor/migration_helpers/lib/migration_helper.rb | Ruby | mit | 1,887 |
// Copyright 2006 The Closure Library 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.
/**
* @fileoverview Wrapper class for handling XmlHttpRequests.
*
* One off requests can be sent through goog.net.XhrIo.send() or an
* instance can be created to send multiple requests. Each request uses its
* own XmlHttpRequest object and handles clearing of the event callback to
* ensure no leaks.
*
* XhrIo is event based, it dispatches events on success, failure, finishing,
* ready-state change, or progress (download and upload).
*
* The ready-state or timeout event fires first, followed by
* a generic completed event. Then the abort, error, or success event
* is fired as appropriate. Progress events are fired as they are
* received. Lastly, the ready event will fire to indicate that the
* object may be used to make another request.
*
* The error event may also be called before completed and
* ready-state-change if the XmlHttpRequest.open() or .send() methods throw.
*
* This class does not support multiple requests, queuing, or prioritization.
*
* When progress events are supported by the browser, and progress is
* enabled via .setProgressEventsEnabled(true), the
* goog.net.EventType.PROGRESS event will be the re-dispatched browser
* progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event
* will be fired for download and upload progress respectively.
*
*/
goog.provide('goog.net.XhrIo');
goog.provide('goog.net.XhrIo.ResponseType');
goog.require('goog.Timer');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.debug.entryPointRegistry');
goog.require('goog.events.EventTarget');
goog.require('goog.json');
goog.require('goog.log');
goog.require('goog.net.ErrorCode');
goog.require('goog.net.EventType');
goog.require('goog.net.HttpStatus');
goog.require('goog.net.XmlHttp');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.structs');
goog.require('goog.structs.Map');
goog.require('goog.uri.utils');
goog.require('goog.userAgent');
goog.forwardDeclare('goog.Uri');
/**
* Basic class for handling XMLHttpRequests.
* @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when
* creating XMLHttpRequest objects.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.net.XhrIo = function(opt_xmlHttpFactory) {
goog.net.XhrIo.base(this, 'constructor');
/**
* Map of default headers to add to every request, use:
* XhrIo.headers.set(name, value)
* @type {!goog.structs.Map}
*/
this.headers = new goog.structs.Map();
/**
* Optional XmlHttpFactory
* @private {goog.net.XmlHttpFactory}
*/
this.xmlHttpFactory_ = opt_xmlHttpFactory || null;
/**
* Whether XMLHttpRequest is active. A request is active from the time send()
* is called until onReadyStateChange() is complete, or error() or abort()
* is called.
* @private {boolean}
*/
this.active_ = false;
/**
* The XMLHttpRequest object that is being used for the transfer.
* @private {?goog.net.XhrLike.OrNative}
*/
this.xhr_ = null;
/**
* The options to use with the current XMLHttpRequest object.
* @private {Object}
*/
this.xhrOptions_ = null;
/**
* Last URL that was requested.
* @private {string|goog.Uri}
*/
this.lastUri_ = '';
/**
* Method for the last request.
* @private {string}
*/
this.lastMethod_ = '';
/**
* Last error code.
* @private {!goog.net.ErrorCode}
*/
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
/**
* Last error message.
* @private {Error|string}
*/
this.lastError_ = '';
/**
* Used to ensure that we don't dispatch an multiple ERROR events. This can
* happen in IE when it does a synchronous load and one error is handled in
* the ready statte change and one is handled due to send() throwing an
* exception.
* @private {boolean}
*/
this.errorDispatched_ = false;
/**
* Used to make sure we don't fire the complete event from inside a send call.
* @private {boolean}
*/
this.inSend_ = false;
/**
* Used in determining if a call to {@link #onReadyStateChange_} is from
* within a call to this.xhr_.open.
* @private {boolean}
*/
this.inOpen_ = false;
/**
* Used in determining if a call to {@link #onReadyStateChange_} is from
* within a call to this.xhr_.abort.
* @private {boolean}
*/
this.inAbort_ = false;
/**
* Number of milliseconds after which an incomplete request will be aborted
* and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout
* is set.
* @private {number}
*/
this.timeoutInterval_ = 0;
/**
* Timer to track request timeout.
* @private {?number}
*/
this.timeoutId_ = null;
/**
* The requested type for the response. The empty string means use the default
* XHR behavior.
* @private {goog.net.XhrIo.ResponseType}
*/
this.responseType_ = goog.net.XhrIo.ResponseType.DEFAULT;
/**
* Whether a "credentialed" request is to be sent (one that is aware of
* cookies and authentication). This is applicable only for cross-domain
* requests and more recent browsers that support this part of the HTTP Access
* Control standard.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute
*
* @private {boolean}
*/
this.withCredentials_ = false;
/**
* Whether progress events are enabled for this request. This is
* disabled by default because setting a progress event handler
* causes pre-flight OPTIONS requests to be sent for CORS requests,
* even in cases where a pre-flight request would not otherwise be
* sent.
*
* @see http://xhr.spec.whatwg.org/#security-considerations
*
* Note that this can cause problems for Firefox 22 and below, as an
* older "LSProgressEvent" will be dispatched by the browser. That
* progress event is no longer supported, and can lead to failures,
* including throwing exceptions.
*
* @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631
* @see b/23469793
*
* @private {boolean}
*/
this.progressEventsEnabled_ = false;
/**
* True if we can use XMLHttpRequest's timeout directly.
* @private {boolean}
*/
this.useXhr2Timeout_ = false;
};
goog.inherits(goog.net.XhrIo, goog.events.EventTarget);
/**
* Response types that may be requested for XMLHttpRequests.
* @enum {string}
* @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute
*/
goog.net.XhrIo.ResponseType = {
DEFAULT: '',
TEXT: 'text',
DOCUMENT: 'document',
// Not supported as of Chrome 10.0.612.1 dev
BLOB: 'blob',
ARRAY_BUFFER: 'arraybuffer'
};
/**
* A reference to the XhrIo logger
* @private {goog.debug.Logger}
* @const
*/
goog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo');
/**
* The Content-Type HTTP header name
* @type {string}
*/
goog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type';
/**
* The pattern matching the 'http' and 'https' URI schemes
* @type {!RegExp}
*/
goog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i;
/**
* The methods that typically come along with form data. We set different
* headers depending on whether the HTTP action is one of these.
*/
goog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT'];
/**
* The Content-Type HTTP header value for a url-encoded form
* @type {string}
*/
goog.net.XhrIo.FORM_CONTENT_TYPE =
'application/x-www-form-urlencoded;charset=utf-8';
/**
* The XMLHttpRequest Level two timeout delay ms property name.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
*
* @private {string}
* @const
*/
goog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout';
/**
* The XMLHttpRequest Level two ontimeout handler property name.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
*
* @private {string}
* @const
*/
goog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout';
/**
* All non-disposed instances of goog.net.XhrIo created
* by {@link goog.net.XhrIo.send} are in this Array.
* @see goog.net.XhrIo.cleanup
* @private {!Array<!goog.net.XhrIo>}
*/
goog.net.XhrIo.sendInstances_ = [];
/**
* Static send that creates a short lived instance of XhrIo to send the
* request.
* @see goog.net.XhrIo.cleanup
* @param {string|goog.Uri} url Uri to make request to.
* @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function
* for when request is complete.
* @param {string=} opt_method Send method, default: GET.
* @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}
* opt_content Body data.
* @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the
* request.
* @param {number=} opt_timeoutInterval Number of milliseconds after which an
* incomplete request will be aborted; 0 means no timeout is set.
* @param {boolean=} opt_withCredentials Whether to send credentials with the
* request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}.
* @return {!goog.net.XhrIo} The sent XhrIo.
*/
goog.net.XhrIo.send = function(
url, opt_callback, opt_method, opt_content, opt_headers,
opt_timeoutInterval, opt_withCredentials) {
var x = new goog.net.XhrIo();
goog.net.XhrIo.sendInstances_.push(x);
if (opt_callback) {
x.listen(goog.net.EventType.COMPLETE, opt_callback);
}
x.listenOnce(goog.net.EventType.READY, x.cleanupSend_);
if (opt_timeoutInterval) {
x.setTimeoutInterval(opt_timeoutInterval);
}
if (opt_withCredentials) {
x.setWithCredentials(opt_withCredentials);
}
x.send(url, opt_method, opt_content, opt_headers);
return x;
};
/**
* Disposes all non-disposed instances of goog.net.XhrIo created by
* {@link goog.net.XhrIo.send}.
* {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance
* it creates when the request completes or fails. However, if
* the request never completes, then the goog.net.XhrIo is not disposed.
* This can occur if the window is unloaded before the request completes.
* We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo
* it creates and make the client of {@link goog.net.XhrIo.send} be
* responsible for disposing it in this case. However, this makes things
* significantly more complicated for the client, and the whole point
* of {@link goog.net.XhrIo.send} is that it's simple and easy to use.
* Clients of {@link goog.net.XhrIo.send} should call
* {@link goog.net.XhrIo.cleanup} when doing final
* cleanup on window unload.
*/
goog.net.XhrIo.cleanup = function() {
var instances = goog.net.XhrIo.sendInstances_;
while (instances.length) {
instances.pop().dispose();
}
};
/**
* Installs exception protection for all entry point introduced by
* goog.net.XhrIo instances which are not protected by
* {@link goog.debug.ErrorHandler#protectWindowSetTimeout},
* {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or
* {@link goog.events.protectBrowserEventEntryPoint}.
*
* @param {goog.debug.ErrorHandler} errorHandler Error handler with which to
* protect the entry point(s).
*/
goog.net.XhrIo.protectEntryPoints = function(errorHandler) {
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =
errorHandler.protectEntryPoint(
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);
};
/**
* Disposes of the specified goog.net.XhrIo created by
* {@link goog.net.XhrIo.send} and removes it from
* {@link goog.net.XhrIo.pendingStaticSendInstances_}.
* @private
*/
goog.net.XhrIo.prototype.cleanupSend_ = function() {
this.dispose();
goog.array.remove(goog.net.XhrIo.sendInstances_, this);
};
/**
* Returns the number of milliseconds after which an incomplete request will be
* aborted, or 0 if no timeout is set.
* @return {number} Timeout interval in milliseconds.
*/
goog.net.XhrIo.prototype.getTimeoutInterval = function() {
return this.timeoutInterval_;
};
/**
* Sets the number of milliseconds after which an incomplete request will be
* aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no
* timeout is set.
* @param {number} ms Timeout interval in milliseconds; 0 means none.
*/
goog.net.XhrIo.prototype.setTimeoutInterval = function(ms) {
this.timeoutInterval_ = Math.max(0, ms);
};
/**
* Sets the desired type for the response. At time of writing, this is only
* supported in very recent versions of WebKit (10.0.612.1 dev and later).
*
* If this is used, the response may only be accessed via {@link #getResponse}.
*
* @param {goog.net.XhrIo.ResponseType} type The desired type for the response.
*/
goog.net.XhrIo.prototype.setResponseType = function(type) {
this.responseType_ = type;
};
/**
* Gets the desired type for the response.
* @return {goog.net.XhrIo.ResponseType} The desired type for the response.
*/
goog.net.XhrIo.prototype.getResponseType = function() {
return this.responseType_;
};
/**
* Sets whether a "credentialed" request that is aware of cookie and
* authentication information should be made. This option is only supported by
* browsers that support HTTP Access Control. As of this writing, this option
* is not supported in IE.
*
* @param {boolean} withCredentials Whether this should be a "credentialed"
* request.
*/
goog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) {
this.withCredentials_ = withCredentials;
};
/**
* Gets whether a "credentialed" request is to be sent.
* @return {boolean} The desired type for the response.
*/
goog.net.XhrIo.prototype.getWithCredentials = function() {
return this.withCredentials_;
};
/**
* Sets whether progress events are enabled for this request. Note
* that progress events require pre-flight OPTIONS request handling
* for CORS requests, and may cause trouble with older browsers. See
* progressEventsEnabled_ for details.
* @param {boolean} enabled Whether progress events should be enabled.
*/
goog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) {
this.progressEventsEnabled_ = enabled;
};
/**
* Gets whether progress events are enabled.
* @return {boolean} Whether progress events are enabled for this request.
*/
goog.net.XhrIo.prototype.getProgressEventsEnabled = function() {
return this.progressEventsEnabled_;
};
/**
* Instance send that actually uses XMLHttpRequest to make a server call.
* @param {string|goog.Uri} url Uri to make request to.
* @param {string=} opt_method Send method, default: GET.
* @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}
* opt_content Body data.
* @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the
* request.
*/
goog.net.XhrIo.prototype.send = function(
url, opt_method, opt_content, opt_headers) {
if (this.xhr_) {
throw Error(
'[goog.net.XhrIo] Object is active with another request=' +
this.lastUri_ + '; newUri=' + url);
}
var method = opt_method ? opt_method.toUpperCase() : 'GET';
this.lastUri_ = url;
this.lastError_ = '';
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
this.lastMethod_ = method;
this.errorDispatched_ = false;
this.active_ = true;
// Use the factory to create the XHR object and options
this.xhr_ = this.createXhr();
this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() :
goog.net.XmlHttp.getOptions();
// Set up the onreadystatechange callback
this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this);
// Set up upload/download progress events, if progress events are supported.
if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) {
this.xhr_.onprogress =
goog.bind(function(e) { this.onProgressHandler_(e, true); }, this);
if (this.xhr_.upload) {
this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this);
}
}
/**
* Try to open the XMLHttpRequest (always async), if an error occurs here it
* is generally permission denied
* @preserveTry
*/
try {
goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr'));
this.inOpen_ = true;
this.xhr_.open(method, String(url), true); // Always async!
this.inOpen_ = false;
} catch (err) {
goog.log.fine(
this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message));
this.error_(goog.net.ErrorCode.EXCEPTION, err);
return;
}
// We can't use null since this won't allow requests with form data to have a
// content length specified which will cause some proxies to return a 411
// error.
var content = opt_content || '';
var headers = this.headers.clone();
// Add headers specific to this request
if (opt_headers) {
goog.structs.forEach(
opt_headers, function(value, key) { headers.set(key, value); });
}
// Find whether a content type header is set, ignoring case.
// HTTP header names are case-insensitive. See:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
var contentTypeKey =
goog.array.find(headers.getKeys(), goog.net.XhrIo.isContentTypeHeader_);
var contentIsFormData =
(goog.global['FormData'] && (content instanceof goog.global['FormData']));
if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) &&
!contentTypeKey && !contentIsFormData) {
// For requests typically with form data, default to the url-encoded form
// content type unless this is a FormData request. For FormData,
// the browser will automatically add a multipart/form-data content type
// with an appropriate multipart boundary.
headers.set(
goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE);
}
// Add the headers to the Xhr object
headers.forEach(function(value, key) {
this.xhr_.setRequestHeader(key, value);
}, this);
if (this.responseType_) {
this.xhr_.responseType = this.responseType_;
}
if (goog.object.containsKey(this.xhr_, 'withCredentials')) {
this.xhr_.withCredentials = this.withCredentials_;
}
/**
* Try to send the request, or other wise report an error (404 not found).
* @preserveTry
*/
try {
this.cleanUpTimeoutTimer_(); // Paranoid, should never be running.
if (this.timeoutInterval_ > 0) {
this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_);
goog.log.fine(
this.logger_, this.formatMsg_(
'Will abort after ' + this.timeoutInterval_ +
'ms if incomplete, xhr2 ' + this.useXhr2Timeout_));
if (this.useXhr2Timeout_) {
this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_;
this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] =
goog.bind(this.timeout_, this);
} else {
this.timeoutId_ =
goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this);
}
}
goog.log.fine(this.logger_, this.formatMsg_('Sending request'));
this.inSend_ = true;
this.xhr_.send(content);
this.inSend_ = false;
} catch (err) {
goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message));
this.error_(goog.net.ErrorCode.EXCEPTION, err);
}
};
/**
* Determines if the argument is an XMLHttpRequest that supports the level 2
* timeout value and event.
*
* Currently, FF 21.0 OS X has the fields but won't actually call the timeout
* handler. Perhaps the confusion in the bug referenced below hasn't
* entirely been resolved.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816
*
* @param {!goog.net.XhrLike.OrNative} xhr The request.
* @return {boolean} True if the request supports level 2 timeout.
* @private
*/
goog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) {
return goog.userAgent.IE && goog.userAgent.isVersionOrHigher(9) &&
goog.isNumber(xhr[goog.net.XhrIo.XHR2_TIMEOUT_]) &&
goog.isDef(xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_]);
};
/**
* @param {string} header An HTTP header key.
* @return {boolean} Whether the key is a content type header (ignoring
* case.
* @private
*/
goog.net.XhrIo.isContentTypeHeader_ = function(header) {
return goog.string.caseInsensitiveEquals(
goog.net.XhrIo.CONTENT_TYPE_HEADER, header);
};
/**
* Creates a new XHR object.
* @return {!goog.net.XhrLike.OrNative} The newly created XHR object.
* @protected
*/
goog.net.XhrIo.prototype.createXhr = function() {
return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() :
goog.net.XmlHttp();
};
/**
* The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_}
* milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts
* the request.
* @private
*/
goog.net.XhrIo.prototype.timeout_ = function() {
if (typeof goog == 'undefined') {
// If goog is undefined then the callback has occurred as the application
// is unloading and will error. Thus we let it silently fail.
} else if (this.xhr_) {
this.lastError_ =
'Timed out after ' + this.timeoutInterval_ + 'ms, aborting';
this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;
goog.log.fine(this.logger_, this.formatMsg_(this.lastError_));
this.dispatchEvent(goog.net.EventType.TIMEOUT);
this.abort(goog.net.ErrorCode.TIMEOUT);
}
};
/**
* Something errorred, so inactivate, fire error callback and clean up
* @param {goog.net.ErrorCode} errorCode The error code.
* @param {Error} err The error object.
* @private
*/
goog.net.XhrIo.prototype.error_ = function(errorCode, err) {
this.active_ = false;
if (this.xhr_) {
this.inAbort_ = true;
this.xhr_.abort(); // Ensures XHR isn't hung (FF)
this.inAbort_ = false;
}
this.lastError_ = err;
this.lastErrorCode_ = errorCode;
this.dispatchErrors_();
this.cleanUpXhr_();
};
/**
* Dispatches COMPLETE and ERROR in case of an error. This ensures that we do
* not dispatch multiple error events.
* @private
*/
goog.net.XhrIo.prototype.dispatchErrors_ = function() {
if (!this.errorDispatched_) {
this.errorDispatched_ = true;
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.ERROR);
}
};
/**
* Abort the current XMLHttpRequest
* @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -
* defaults to ABORT.
*/
goog.net.XhrIo.prototype.abort = function(opt_failureCode) {
if (this.xhr_ && this.active_) {
goog.log.fine(this.logger_, this.formatMsg_('Aborting'));
this.active_ = false;
this.inAbort_ = true;
this.xhr_.abort();
this.inAbort_ = false;
this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.ABORT);
this.cleanUpXhr_();
}
};
/**
* Nullifies all callbacks to reduce risks of leaks.
* @override
* @protected
*/
goog.net.XhrIo.prototype.disposeInternal = function() {
if (this.xhr_) {
// We explicitly do not call xhr_.abort() unless active_ is still true.
// This is to avoid unnecessarily aborting a successful request when
// dispose() is called in a callback triggered by a complete response, but
// in which browser cleanup has not yet finished.
// (See http://b/issue?id=1684217.)
if (this.active_) {
this.active_ = false;
this.inAbort_ = true;
this.xhr_.abort();
this.inAbort_ = false;
}
this.cleanUpXhr_(true);
}
goog.net.XhrIo.base(this, 'disposeInternal');
};
/**
* Internal handler for the XHR object's readystatechange event. This method
* checks the status and the readystate and fires the correct callbacks.
* If the request has ended, the handlers are cleaned up and the XHR object is
* nullified.
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChange_ = function() {
if (this.isDisposed()) {
// This method is the target of an untracked goog.Timer.callOnce().
return;
}
if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) {
// Were not being called from within a call to this.xhr_.send
// this.xhr_.abort, or this.xhr_.open, so this is an entry point
this.onReadyStateChangeEntryPoint_();
} else {
this.onReadyStateChangeHelper_();
}
};
/**
* Used to protect the onreadystatechange handler entry point. Necessary
* as {#onReadyStateChange_} maybe called from within send or abort, this
* method is only called when {#onReadyStateChange_} is called as an
* entry point.
* {@see #protectEntryPoints}
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() {
this.onReadyStateChangeHelper_();
};
/**
* Helper for {@link #onReadyStateChange_}. This is used so that
* entry point calls to {@link #onReadyStateChange_} can be routed through
* {@link #onReadyStateChangeEntryPoint_}.
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {
if (!this.active_) {
// can get called inside abort call
return;
}
if (typeof goog == 'undefined') {
// NOTE(user): If goog is undefined then the callback has occurred as the
// application is unloading and will error. Thus we let it silently fail.
} else if (
this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] &&
this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE &&
this.getStatus() == 2) {
// NOTE(user): In IE if send() errors on a *local* request the readystate
// is still changed to COMPLETE. We need to ignore it and allow the
// try/catch around send() to pick up the error.
goog.log.fine(
this.logger_,
this.formatMsg_('Local request error detected and ignored'));
} else {
// In IE when the response has been cached we sometimes get the callback
// from inside the send call and this usually breaks code that assumes that
// XhrIo is asynchronous. If that is the case we delay the callback
// using a timer.
if (this.inSend_ &&
this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) {
goog.Timer.callOnce(this.onReadyStateChange_, 0, this);
return;
}
this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);
// readyState indicates the transfer has finished
if (this.isComplete()) {
goog.log.fine(this.logger_, this.formatMsg_('Request complete'));
this.active_ = false;
try {
// Call the specific callbacks for success or failure. Only call the
// success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED)
if (this.isSuccess()) {
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.SUCCESS);
} else {
this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;
this.lastError_ =
this.getStatusText() + ' [' + this.getStatus() + ']';
this.dispatchErrors_();
}
} finally {
this.cleanUpXhr_();
}
}
}
};
/**
* Internal handler for the XHR object's onprogress event. Fires both a generic
* PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to
* allow specific binding for each XHR progress event.
* @param {!ProgressEvent} e XHR progress event.
* @param {boolean=} opt_isDownload Whether the current progress event is from a
* download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS
* event should be dispatched.
* @private
*/
goog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) {
goog.asserts.assert(
e.type === goog.net.EventType.PROGRESS,
'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.');
this.dispatchEvent(
goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS));
this.dispatchEvent(
goog.net.XhrIo.buildProgressEvent_(
e, opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS :
goog.net.EventType.UPLOAD_PROGRESS));
};
/**
* Creates a representation of the native ProgressEvent. IE doesn't support
* constructing ProgressEvent via "new", and the alternatives (e.g.,
* ProgressEvent.initProgressEvent) are non-standard or deprecated.
* @param {!ProgressEvent} e XHR progress event.
* @param {!goog.net.EventType} eventType The type of the event.
* @return {!ProgressEvent} The progress event.
* @private
*/
goog.net.XhrIo.buildProgressEvent_ = function(e, eventType) {
return /** @type {!ProgressEvent} */ ({
type: eventType,
lengthComputable: e.lengthComputable,
loaded: e.loaded,
total: e.total
});
};
/**
* Remove the listener to protect against leaks, and nullify the XMLHttpRequest
* object.
* @param {boolean=} opt_fromDispose If this is from the dispose (don't want to
* fire any events).
* @private
*/
goog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) {
if (this.xhr_) {
// Cancel any pending timeout event handler.
this.cleanUpTimeoutTimer_();
// Save reference so we can mark it as closed after the READY event. The
// READY event may trigger another request, thus we must nullify this.xhr_
var xhr = this.xhr_;
var clearedOnReadyStateChange =
this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?
goog.nullFunction :
null;
this.xhr_ = null;
this.xhrOptions_ = null;
if (!opt_fromDispose) {
this.dispatchEvent(goog.net.EventType.READY);
}
try {
// NOTE(user): Not nullifying in FireFox can still leak if the callbacks
// are defined in the same scope as the instance of XhrIo. But, IE doesn't
// allow you to set the onreadystatechange to NULL so nullFunction is
// used.
xhr.onreadystatechange = clearedOnReadyStateChange;
} catch (e) {
// This seems to occur with a Gears HTTP request. Delayed the setting of
// this onreadystatechange until after READY is sent out and catching the
// error to see if we can track down the problem.
goog.log.error(
this.logger_,
'Problem encountered resetting onreadystatechange: ' + e.message);
}
}
};
/**
* Make sure the timeout timer isn't running.
* @private
*/
goog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() {
if (this.xhr_ && this.useXhr2Timeout_) {
this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null;
}
if (goog.isNumber(this.timeoutId_)) {
goog.Timer.clear(this.timeoutId_);
this.timeoutId_ = null;
}
};
/**
* @return {boolean} Whether there is an active request.
*/
goog.net.XhrIo.prototype.isActive = function() {
return !!this.xhr_;
};
/**
* @return {boolean} Whether the request has completed.
*/
goog.net.XhrIo.prototype.isComplete = function() {
return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;
};
/**
* @return {boolean} Whether the request completed with a success.
*/
goog.net.XhrIo.prototype.isSuccess = function() {
var status = this.getStatus();
// A zero status code is considered successful for local files.
return goog.net.HttpStatus.isSuccess(status) ||
status === 0 && !this.isLastUriEffectiveSchemeHttp_();
};
/**
* @return {boolean} whether the effective scheme of the last URI that was
* fetched was 'http' or 'https'.
* @private
*/
goog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() {
var scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));
return goog.net.XhrIo.HTTP_SCHEME_PATTERN.test(scheme);
};
/**
* Get the readystate from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*.
*/
goog.net.XhrIo.prototype.getReadyState = function() {
return this.xhr_ ?
/** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :
goog.net.XmlHttp.ReadyState
.UNINITIALIZED;
};
/**
* Get the status from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {number} Http status.
*/
goog.net.XhrIo.prototype.getStatus = function() {
/**
* IE doesn't like you checking status until the readystate is greater than 2
* (i.e. it is receiving or complete). The try/catch is used for when the
* page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.
* @preserveTry
*/
try {
return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?
this.xhr_.status :
-1;
} catch (e) {
return -1;
}
};
/**
* Get the status text from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {string} Status text.
*/
goog.net.XhrIo.prototype.getStatusText = function() {
/**
* IE doesn't like you checking status until the readystate is greater than 2
* (i.e. it is receiving or complete). The try/catch is used for when the
* page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.
* @preserveTry
*/
try {
return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?
this.xhr_.statusText :
'';
} catch (e) {
goog.log.fine(this.logger_, 'Can not get status: ' + e.message);
return '';
}
};
/**
* Get the last Uri that was requested
* @return {string} Last Uri.
*/
goog.net.XhrIo.prototype.getLastUri = function() {
return String(this.lastUri_);
};
/**
* Get the response text from the Xhr object
* Will only return correct result when called from the context of a callback.
* @return {string} Result from the server, or '' if no result available.
*/
goog.net.XhrIo.prototype.getResponseText = function() {
/** @preserveTry */
try {
return this.xhr_ ? this.xhr_.responseText : '';
} catch (e) {
// http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute
// states that responseText should return '' (and responseXML null)
// when the state is not LOADING or DONE. Instead, IE can
// throw unexpected exceptions, for example when a request is aborted
// or no data is available yet.
goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message);
return '';
}
};
/**
* Get the response body from the Xhr object. This property is only available
* in IE since version 7 according to MSDN:
* http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx
* Will only return correct result when called from the context of a callback.
*
* One option is to construct a VBArray from the returned object and convert
* it to a JavaScript array using the toArray method:
* {@code (new window['VBArray'](xhrIo.getResponseBody())).toArray()}
* This will result in an array of numbers in the range of [0..255]
*
* Another option is to use the VBScript CStr method to convert it into a
* string as outlined in http://stackoverflow.com/questions/1919972
*
* @return {Object} Binary result from the server or null if not available.
*/
goog.net.XhrIo.prototype.getResponseBody = function() {
/** @preserveTry */
try {
if (this.xhr_ && 'responseBody' in this.xhr_) {
return this.xhr_['responseBody'];
}
} catch (e) {
// IE can throw unexpected exceptions, for example when a request is aborted
// or no data is yet available.
goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message);
}
return null;
};
/**
* Get the response XML from the Xhr object
* Will only return correct result when called from the context of a callback.
* @return {Document} The DOM Document representing the XML file, or null
* if no result available.
*/
goog.net.XhrIo.prototype.getResponseXml = function() {
/** @preserveTry */
try {
return this.xhr_ ? this.xhr_.responseXML : null;
} catch (e) {
goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message);
return null;
}
};
/**
* Get the response and evaluates it as JSON from the Xhr object
* Will only return correct result when called from the context of a callback
* @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for
* stripping of the response before parsing. This needs to be set only if
* your backend server prepends the same prefix string to the JSON response.
* @return {Object|undefined} JavaScript object.
*/
goog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {
if (!this.xhr_) {
return undefined;
}
var responseText = this.xhr_.responseText;
if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {
responseText = responseText.substring(opt_xssiPrefix.length);
}
return goog.json.parse(responseText);
};
/**
* Get the response as the type specificed by {@link #setResponseType}. At time
* of writing, this is only directly supported in very recent versions of WebKit
* (10.0.612.1 dev and later). If the field is not supported directly, we will
* try to emulate it.
*
* Emulating the response means following the rules laid out at
* http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute
*
* On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only
* response types of DEFAULT or TEXT may be used, and the response returned will
* be the text response.
*
* On browsers with Mozilla's draft support for array buffers (Firefox 4, 5),
* only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the
* response returned will be either the text response or the Mozilla
* implementation of the array buffer response.
*
* On browsers will full support, any valid response type supported by the
* browser may be used, and the response provided by the browser will be
* returned.
*
* @return {*} The response.
*/
goog.net.XhrIo.prototype.getResponse = function() {
/** @preserveTry */
try {
if (!this.xhr_) {
return null;
}
if ('response' in this.xhr_) {
return this.xhr_.response;
}
switch (this.responseType_) {
case goog.net.XhrIo.ResponseType.DEFAULT:
case goog.net.XhrIo.ResponseType.TEXT:
return this.xhr_.responseText;
// DOCUMENT and BLOB don't need to be handled here because they are
// introduced in the same spec that adds the .response field, and would
// have been caught above.
// ARRAY_BUFFER needs an implementation for Firefox 4, where it was
// implemented using a draft spec rather than the final spec.
case goog.net.XhrIo.ResponseType.ARRAY_BUFFER:
if ('mozResponseArrayBuffer' in this.xhr_) {
return this.xhr_.mozResponseArrayBuffer;
}
}
// Fell through to a response type that is not supported on this browser.
goog.log.error(
this.logger_, 'Response type ' + this.responseType_ + ' is not ' +
'supported on this browser');
return null;
} catch (e) {
goog.log.fine(this.logger_, 'Can not get response: ' + e.message);
return null;
}
};
/**
* Get the value of the response-header with the given name from the Xhr object
* Will only return correct result when called from the context of a callback
* and the request has completed
* @param {string} key The name of the response-header to retrieve.
* @return {string|undefined} The value of the response-header named key.
*/
goog.net.XhrIo.prototype.getResponseHeader = function(key) {
return this.xhr_ && this.isComplete() ? this.xhr_.getResponseHeader(key) :
undefined;
};
/**
* Gets the text of all the headers in the response.
* Will only return correct result when called from the context of a callback
* and the request has completed.
* @return {string} The value of the response headers or empty string.
*/
goog.net.XhrIo.prototype.getAllResponseHeaders = function() {
return this.xhr_ && this.isComplete() ? this.xhr_.getAllResponseHeaders() :
'';
};
/**
* Returns all response headers as a key-value map.
* Multiple values for the same header key can be combined into one,
* separated by a comma and a space.
* Note that the native getResponseHeader method for retrieving a single header
* does a case insensitive match on the header name. This method does not
* include any case normalization logic, it will just return a key-value
* representation of the headers.
* See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method
* @return {!Object<string, string>} An object with the header keys as keys
* and header values as values.
*/
goog.net.XhrIo.prototype.getResponseHeaders = function() {
var headersObject = {};
var headersArray = this.getAllResponseHeaders().split('\r\n');
for (var i = 0; i < headersArray.length; i++) {
if (goog.string.isEmptyOrWhitespace(headersArray[i])) {
continue;
}
var keyValue = goog.string.splitLimit(headersArray[i], ': ', 2);
if (headersObject[keyValue[0]]) {
headersObject[keyValue[0]] += ', ' + keyValue[1];
} else {
headersObject[keyValue[0]] = keyValue[1];
}
}
return headersObject;
};
/**
* Get the last error message
* @return {goog.net.ErrorCode} Last error code.
*/
goog.net.XhrIo.prototype.getLastErrorCode = function() {
return this.lastErrorCode_;
};
/**
* Get the last error message
* @return {string} Last error message.
*/
goog.net.XhrIo.prototype.getLastError = function() {
return goog.isString(this.lastError_) ? this.lastError_ :
String(this.lastError_);
};
/**
* Adds the last method, status and URI to the message. This is used to add
* this information to the logging calls.
* @param {string} msg The message text that we want to add the extra text to.
* @return {string} The message with the extra text appended.
* @private
*/
goog.net.XhrIo.prototype.formatMsg_ = function(msg) {
return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' +
this.getStatus() + ']';
};
// Register the xhr handler as an entry point, so that
// it can be monitored for exception handling, etc.
goog.debug.entryPointRegistry.register(
/**
* @param {function(!Function): !Function} transformer The transforming
* function.
*/
function(transformer) {
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =
transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);
});
| cbetheridge/simpleclassroom | static/third-party/closure-library/closure/goog/net/xhrio.js | JavaScript | mit | 43,124 |
package ranrotb
// Call with seed and it will return a closure
// which will return pseudo-random numbers on
// consecutive calls
// Note: seed could be uint32(time.Now().Unix())
func rrbRand(seed uint32) func() uint32 {
var lo, hi uint32
// In Go ^ is the bitwise complement operator
// In C this would be the tilde (~)
lo, hi = seed, ^seed
return func() uint32 {
hi = (hi << 16) + (lo >> 16)
hi += lo
lo += hi
return hi
}
}
| n1ghtmare/Algorithm-Implementations | Ranrot-B-Pseudo_Random_Number_Generator/Go/jcla1/ranrotb_prng.go | GO | mit | 443 |
package ru.atom.model.dao;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.atom.model.data.Match;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public class MatchDao implements Dao<Match> {
private static final Logger log = LogManager.getLogger(MatchDao.class);
@Override
public List<Match> getAll() {
throw new NotImplementedException();
}
@Override
public List<Match> getAllWhere(String... hqlConditions) {
throw new NotImplementedException();
}
@Override
public void insert(Match match) {
}
}
| Bragaman/atom | lecture6/source/src/main/java/ru/atom/model/dao/MatchDao.java | Java | mit | 737 |
/**
* Copyright MaDgIK Group 2010 - 2015.
*/
package madgik.exareme.master.engine.rmi;
/**
* @author heraldkllapi
*/
public class OptimizerConstants {
public static boolean USE_SKETCH = false;
public static int MAX_TABLE_PARTS = 2;
}
| XristosMallios/cache | exareme-master/src/main/java/madgik/exareme/master/engine/rmi/OptimizerConstants.java | Java | mit | 248 |
'use strict';
const Code = require('code');
const Constants = require('../../../../../../client/pages/admin/statuses/search/constants');
const FluxConstant = require('flux-constant');
const Lab = require('lab');
const Proxyquire = require('proxyquire');
const lab = exports.lab = Lab.script();
const stub = {
ApiActions: {
get: function () {
stub.ApiActions.get.mock.apply(null, arguments);
},
post: function () {
stub.ApiActions.post.mock.apply(null, arguments);
}
},
Store: {
dispatch: function () {
stub.Store.dispatch.mock.apply(null, arguments);
}
},
ReactRouter: {
browserHistory: {
push: () => {},
replace: () => {}
}
}
};
const Actions = Proxyquire('../../../../../../client/pages/admin/statuses/search/actions', {
'../../../../actions/api': stub.ApiActions,
'./store': stub.Store,
'react-router': stub.ReactRouter
});
lab.experiment('Admin Statuses Search Actions', () => {
lab.test('it calls ApiActions.get from getResults', (done) => {
stub.ApiActions.get.mock = function (url, data, store, typeReq, typeRes, callback) {
Code.expect(url).to.be.a.string();
Code.expect(data).to.be.an.object();
Code.expect(store).to.be.an.object();
Code.expect(typeReq).to.be.an.instanceof(FluxConstant);
Code.expect(typeRes).to.be.an.instanceof(FluxConstant);
Code.expect(callback).to.not.exist();
done();
};
Actions.getResults({});
});
lab.test('it calls browserHistory.push from changeSearchQuery', (done) => {
const scrollTo = global.window.scrollTo;
global.window.scrollTo = function () {
global.window.scrollTo = scrollTo;
done();
};
stub.ReactRouter.browserHistory.push = function (config) {
stub.ReactRouter.browserHistory.push = () => {};
Code.expect(config.pathname).to.be.a.string();
Code.expect(config.query).to.be.an.object();
};
Actions.changeSearchQuery({});
});
lab.test('it calls dispatch from showCreateNew', (done) => {
stub.Store.dispatch.mock = function (action) {
if (action.type === Constants.SHOW_CREATE_NEW) {
done();
}
};
Actions.showCreateNew();
});
lab.test('it calls dispatch from hideCreateNew', (done) => {
stub.Store.dispatch.mock = function (action) {
if (action.type === Constants.HIDE_CREATE_NEW) {
done();
}
};
Actions.hideCreateNew();
});
lab.test('it calls ApiActions.post from createNew (success)', (done) => {
stub.Store.dispatch.mock = () => {};
stub.ReactRouter.browserHistory.replace = function (location) {
stub.ReactRouter.browserHistory.replace = () => {};
Code.expect(location).to.be.an.object();
done();
};
stub.ApiActions.post.mock = function (url, data, store, typeReq, typeRes, callback) {
Code.expect(url).to.be.a.string();
Code.expect(data).to.be.an.object();
Code.expect(store).to.be.an.object();
Code.expect(typeReq).to.be.an.instanceof(FluxConstant);
Code.expect(typeRes).to.be.an.instanceof(FluxConstant);
Code.expect(callback).to.exist();
callback(null, {});
};
Actions.createNew({});
});
lab.test('it calls ApiActions.post from createNew (failure)', (done) => {
stub.ApiActions.post.mock = function (url, data, store, typeReq, typeRes, callback) {
Code.expect(url).to.be.a.string();
Code.expect(data).to.be.an.object();
Code.expect(store).to.be.an.object();
Code.expect(typeReq).to.be.an.instanceof(FluxConstant);
Code.expect(typeRes).to.be.an.instanceof(FluxConstant);
Code.expect(callback).to.exist();
callback(new Error('sorry pal'));
done();
};
Actions.createNew({});
});
});
| fahidRM/aqua-couch-test | test/client/pages/admin/statuses/search/actions.js | JavaScript | mit | 4,225 |
version https://git-lfs.github.com/spec/v1
oid sha256:3e7e8daeb7e94086c854616e881862ffc0555684031d339b30c0b67afa82b530
size 492
| yogeshsaroya/new-cdnjs | ajax/libs/bootstrap-datepicker/1.2.0-rc.1/js/locales/bootstrap-datepicker.et.min.js | JavaScript | mit | 128 |
import { getCell, getColumnByCell, getRowIdentity } from './util';
import ElCheckbox from 'element-ui/packages/checkbox';
export default {
components: {
ElCheckbox
},
props: {
store: {
required: true
},
context: {},
layout: {
required: true
},
rowClassName: [String, Function],
rowStyle: [Object, Function],
fixed: String,
highlight: Boolean
},
render(h) {
const columnsHidden = this.columns.map((column, index) => this.isColumnHidden(index));
return (
<table
class="el-table__body"
cellspacing="0"
cellpadding="0"
border="0">
<colgroup>
{
this._l(this.columns, column =>
<col
name={ column.id }
width={ column.realWidth || column.width }
/>)
}
</colgroup>
<tbody>
{
this._l(this.data, (row, $index) =>
[<tr
style={ this.rowStyle ? this.getRowStyle(row, $index) : null }
key={ this.table.rowKey ? this.getKeyOfRow(row, $index) : $index }
on-dblclick={ ($event) => this.handleDoubleClick($event, row) }
on-click={ ($event) => this.handleClick($event, row) }
on-contextmenu={ ($event) => this.handleContextMenu($event, row) }
on-mouseenter={ _ => this.handleMouseEnter($index) }
on-mouseleave={ _ => this.handleMouseLeave() }
class={ [this.getRowClass(row, $index)] }>
{
this._l(this.columns, (column, cellIndex) =>
<td
class={ [column.id, column.align, column.className || '', columnsHidden[cellIndex] ? 'is-hidden' : '' ] }
on-mouseenter={ ($event) => this.handleCellMouseEnter($event, row) }
on-mouseleave={ this.handleCellMouseLeave }>
{
column.renderCell.call(this._renderProxy, h, { row, column, $index, store: this.store, _self: this.context || this.table.$vnode.context }, columnsHidden[cellIndex])
}
</td>
)
}
{
!this.fixed && this.layout.scrollY && this.layout.gutterWidth ? <td class="gutter" /> : ''
}
</tr>,
this.store.states.expandRows.indexOf(row) > -1
? (<tr>
<td colspan={ this.columns.length } class="el-table__expanded-cell">
{ this.table.renderExpanded ? this.table.renderExpanded(h, { row, $index, store: this.store }) : ''}
</td>
</tr>)
: ''
]
)
}
</tbody>
</table>
);
},
watch: {
'store.states.hoverRow'(newVal, oldVal) {
if (!this.store.states.isComplex) return;
const el = this.$el;
if (!el) return;
const rows = el.querySelectorAll('tbody > tr');
const oldRow = rows[oldVal];
const newRow = rows[newVal];
if (oldRow) {
oldRow.classList.remove('hover-row');
}
if (newRow) {
newRow.classList.add('hover-row');
}
},
'store.states.currentRow'(newVal, oldVal) {
if (!this.highlight) return;
const el = this.$el;
if (!el) return;
const data = this.store.states.data;
const rows = el.querySelectorAll('tbody > tr');
const oldRow = rows[data.indexOf(oldVal)];
const newRow = rows[data.indexOf(newVal)];
if (oldRow) {
oldRow.classList.remove('current-row');
} else if (rows) {
[].forEach.call(rows, row => row.classList.remove('current-row'));
}
if (newRow) {
newRow.classList.add('current-row');
}
}
},
computed: {
table() {
return this.$parent;
},
data() {
return this.store.states.data;
},
columnsCount() {
return this.store.states.columns.length;
},
leftFixedCount() {
return this.store.states.fixedColumns.length;
},
rightFixedCount() {
return this.store.states.rightFixedColumns.length;
},
columns() {
return this.store.states.columns;
}
},
data() {
return {
tooltipDisabled: true
};
},
methods: {
getKeyOfRow(row, index) {
const rowKey = this.table.rowKey;
if (rowKey) {
return getRowIdentity(row, rowKey);
}
return index;
},
isColumnHidden(index) {
if (this.fixed === true || this.fixed === 'left') {
return index >= this.leftFixedCount;
} else if (this.fixed === 'right') {
return index < this.columnsCount - this.rightFixedCount;
} else {
return (index < this.leftFixedCount) || (index >= this.columnsCount - this.rightFixedCount);
}
},
getRowStyle(row, index) {
const rowStyle = this.rowStyle;
if (typeof rowStyle === 'function') {
return rowStyle.call(null, row, index);
}
return rowStyle;
},
getRowClass(row, index) {
const classes = [];
const rowClassName = this.rowClassName;
if (typeof rowClassName === 'string') {
classes.push(rowClassName);
} else if (typeof rowClassName === 'function') {
classes.push(rowClassName.call(null, row, index) || '');
}
return classes.join(' ');
},
handleCellMouseEnter(event, row) {
const table = this.table;
const cell = getCell(event);
if (cell) {
const column = getColumnByCell(table, cell);
const hoverState = table.hoverState = {cell, column, row};
table.$emit('cell-mouse-enter', hoverState.row, hoverState.column, hoverState.cell, event);
}
// 判断是否text-overflow, 如果是就显示tooltip
const cellChild = event.target.querySelector('.cell');
this.tooltipDisabled = cellChild.scrollWidth <= cellChild.offsetWidth;
},
handleCellMouseLeave(event) {
const cell = getCell(event);
if (!cell) return;
const oldHoverState = this.table.hoverState;
this.table.$emit('cell-mouse-leave', oldHoverState.row, oldHoverState.column, oldHoverState.cell, event);
},
handleMouseEnter(index) {
this.store.commit('setHoverRow', index);
},
handleMouseLeave() {
this.store.commit('setHoverRow', null);
},
handleContextMenu(event, row) {
this.handleEvent(event, row, 'contextmenu');
},
handleDoubleClick(event, row) {
this.handleEvent(event, row, 'dblclick');
},
handleClick(event, row) {
this.store.commit('setCurrentRow', row);
this.handleEvent(event, row, 'click');
},
handleEvent(event, row, name) {
const table = this.table;
const cell = getCell(event);
let column;
if (cell) {
column = getColumnByCell(table, cell);
if (column) {
table.$emit(`cell-${name}`, row, column, cell, event);
}
}
table.$emit(`row-${name}`, row, event, column);
},
handleExpandClick(row) {
this.store.commit('toggleRowExpanded', row);
}
}
};
| imyzf/element | packages/table/src/table-body.js | JavaScript | mit | 7,259 |
using System;
using NBitcoin;
namespace Stratis.Bitcoin.Features.BlockStore.Pruning
{
/// <summary>
/// This service starts an async loop task that periodically deletes from the blockstore.
/// <para>
/// If the height of the node's block store is more than <see cref="PruneBlockStoreService.MaxBlocksToKeep"/>, the node will
/// be pruned, leaving a margin of <see cref="PruneBlockStoreService.MaxBlocksToKeep"/> in the block database.
/// </para>
/// <para>
/// For example if the block store's height is 5000, the node will be pruned up to height 4000, meaning that 1000 blocks will be kept on disk.
/// </para>
/// </summary>
public interface IPruneBlockStoreService : IDisposable
{
/// <summary>
/// This is the header of where the node has been pruned up to.
/// <para>
/// It should be noted that deleting (pruning) blocks from the repository only removes the reference, it does not decrease the actual size on disk.
/// </para>
/// </summary>
ChainedHeader PrunedUpToHeaderTip { get; }
/// <summary>
/// Starts an async loop task that periodically deletes from the blockstore.
/// </summary>
void Initialize();
/// <summary>
/// Delete blocks continuously from the back of the store.
/// </summary>
void PruneBlocks();
}
}
| Neurosploit/StratisBitcoinFullNode | src/Stratis.Bitcoin.Features.BlockStore/Pruning/IPruneBlockStoreService.cs | C# | mit | 1,414 |
var searchData=
[
['w',['w',['../structedda_1_1dist_1_1GMMTuple.html#a3f52857178189dcb76b5132a60c0a50a',1,'edda::dist::GMMTuple']]],
['weights',['weights',['../classedda_1_1dist_1_1JointGMM.html#a479a4af061d7414da3a2b42df3f2e87f',1,'edda::dist::JointGMM']]],
['width',['width',['../structBMPImage.html#a35875dd635eb414965fd87e169b8fb25',1,'BMPImage']]]
];
| GRAVITYLab/edda | html/search/variables_15.js | JavaScript | mit | 362 |
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
// support friendly urls for files within the application
$path = $request->path();
if(strpos($path, 'sites/') !== FALSE) {
if(strpos($path, '.html') === FALSE) {
$file = app()->basePath('public/'.$path.'.html');
if(file_exists($file)) {
return file_get_contents($file);
}
}
}
return parent::render($request, $e);
}
}
| OnekO/respond | app/Exceptions/Handler.php | PHP | mit | 1,610 |
package org.spongycastle;
/**
* The Bouncy Castle License
*
* Copyright (c) 2000-2015 The Legion Of The Bouncy Castle Inc. (http://www.bouncycastle.org)
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
public class LICENSE
{
public static String licenseText =
"Copyright (c) 2000-2015 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) "
+ System.getProperty("line.separator")
+ System.getProperty("line.separator")
+ "Permission is hereby granted, free of charge, to any person obtaining a copy of this software "
+ System.getProperty("line.separator")
+ "and associated documentation files (the \"Software\"), to deal in the Software without restriction, "
+ System.getProperty("line.separator")
+ "including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, "
+ System.getProperty("line.separator")
+ "and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,"
+ System.getProperty("line.separator")
+ "subject to the following conditions:"
+ System.getProperty("line.separator")
+ System.getProperty("line.separator")
+ "The above copyright notice and this permission notice shall be included in all copies or substantial"
+ System.getProperty("line.separator")
+ "portions of the Software."
+ System.getProperty("line.separator")
+ System.getProperty("line.separator")
+ "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,"
+ System.getProperty("line.separator")
+ "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR"
+ System.getProperty("line.separator")
+ "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE"
+ System.getProperty("line.separator")
+ "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR"
+ System.getProperty("line.separator")
+ "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER"
+ System.getProperty("line.separator")
+ "DEALINGS IN THE SOFTWARE.";
public static void main(
String[] args)
{
System.out.println(licenseText);
}
}
| savichris/spongycastle | core/src/main/java/org/spongycastle/LICENSE.java | Java | mit | 3,397 |
<?php
namespace Kanboard\Controller;
use Kanboard\Core\ExternalTask\ExternalTaskException;
/**
* Class ExternalTaskViewController
*
* @package Kanboard\Controller
* @author Frederic Guillot
*/
class ExternalTaskViewController extends BaseController
{
public function show()
{
try {
$task = $this->getTask();
$taskProvider = $this->externalTaskManager->getProvider($task['external_provider']);
$externalTask = $taskProvider->fetch($task['external_uri'], $task['project_id']);
$this->response->html($this->template->render($taskProvider->getViewTemplate(), array(
'task' => $task,
'external_task' => $externalTask,
)));
} catch (ExternalTaskException $e) {
$this->response->html('<div class="alert alert-error">'.$e->getMessage().'</div>');
}
}
}
| libin/kanboard | app/Controller/ExternalTaskViewController.php | PHP | mit | 895 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing.Drawing2D
{
/**
* Various custom line cap types
*/
internal enum CustomLineCapType
{
Default = 0,
AdjustableArrowCap = 1
}
}
| dotnet-bot/corefx | src/System.Drawing.Common/src/System/Drawing/Drawing2D/CustomLineCapType.cs | C# | mit | 396 |
var Data = {};
Data.matrix = {
valueName: 'Wert',
stakeholdersName : 'Berührungs​gruppe',
negativeCriteriaName : 'Negativ-Kriterien',
values : [
'Menschen​würde',
'Solidarität',
'Ökologische Nachhaltigkeit',
'Soziale Gerechtigkeit',
'Demokratische Mitbestimmung & Transparenz'
],
stakeholders : [
{
shortcode : 'A',
name: 'Lieferant​Innen',
values: [
{
shortcode : 'A1',
shortcodeSlug : 'a1',
title: 'Ethisches Beschaffungsmanagement',
content: 'Aktive Auseinandersetzung mit den Risiken zugekaufter Produkte / Dienstleistungen, Berücksichtigung sozialer und ökologischer Aspekte bei der Auswahl von LieferantInnen und DienstleistungsnehmerInnen.',
points: 90,
soleProprietorship: true
}
]
},
{
shortcode : 'B',
name: 'Geldgeber​Innen',
values: [
{
shortcode : 'B1',
shortcodeSlug : 'b1',
title: 'Ethisches Finanzmanagement',
content: 'Berücksichtigung sozialer und ökologischer Aspekte bei der Auswahl der Finanzdienstleistungen; gemeinwohlorienterte Veranlagung und Finanzierung',
points: 30,
soleProprietorship: true
}
]
},
{
shortcode : 'C',
name: 'Mitarbeiter​Innen inklusive Eigentümer​Innen',
values: [
{
shortcode : 'C1',
shortcodeSlug : 'c1',
title: 'Arbeitsplatz​qualität und Gleichstellung',
content: 'Mitarbeiter​orientierte Organisations-kultur und –strukturen, Faire Beschäftigungs- und Entgeltpolitik, Arbeitsschutz und Gesundheits​förderung einschließlich Work-Life-Balance/flexible Arbeitszeiten, Gleichstellung und Diversität',
points: 90,
soleProprietorship: true
},
{
shortcode : 'C2',
shortcodeSlug : 'c2',
title: 'Gerechte Verteilung der Erwerbsarbeit',
content: 'Abbau von Überstunden, Verzicht auf All-inclusive-Verträge, Reduktion der Regelarbeitszeit, Beitrag zur Reduktion der Arbeitslosigkeit',
points: 50,
soleProprietorship: true
},
{
shortcode : 'C3',
shortcodeSlug : 'c3',
title: 'Förderung ökologischen Verhaltens der Mitarbeiter​Innen',
content: 'Aktive Förderung eines nachhaltigen Lebensstils der MitarbeiterInnen (Mobilität, Ernährung), Weiterbildung und Bewusstsein schaffende Maßnahmen, nachhaltige Organisationskultur',
points: 30,
soleProprietorship: true
},
{
shortcode : 'C4',
shortcodeSlug : 'c4',
title: 'Gerechte Verteilung des Einkommens',
content: 'Geringe innerbetriebliche Einkommens​spreizung (netto), Einhaltung von Mindest​einkommen und Höchst​einkommen',
points: 60,
soleProprietorship: false
},
{
shortcode : 'C5',
shortcodeSlug : 'c5',
title: 'Inner​betriebliche Demokratie und Transparenz',
content: 'Umfassende innerbetriebliche Transparenz, Wahl der Führungskräfte durch die Mitarbeiter, konsensuale Mitbestimmung bei Grundsatz- und Rahmen​entscheidungen, Übergabe Eigentum an MitarbeiterInnen. Z.B. Soziokratie',
points: 90,
soleProprietorship: false
}
]
},
{
shortcode : 'D',
name: 'KundInnen / Produkte / Dienst​leistungen / Mit​unternehmen',
values: [
{
shortcode : 'D1',
shortcodeSlug : 'd1',
title: 'Ethische Kunden​beziehung',
content: 'Ethischer Umgang mit KundInnen, KundInnen​orientierung/ - mitbestimmung, gemeinsame Produkt​entwicklung, hohe Servicequalität, hohe Produkt​transparenz',
points: 50,
soleProprietorship: true
},
{
shortcode : 'D2',
shortcodeSlug : 'd2',
title: 'Solidarität mit Mit​unternehmen',
content: 'Weitergabe von Information, Know-how, Arbeitskräften, Aufträgen, zinsfreien Krediten; Beteiligung an kooperativem Marketing und kooperativer Krisenbewältigung',
points: 70,
soleProprietorship: true
},
{
shortcode : 'D3',
shortcodeSlug : 'd3',
title: 'Ökologische Gestaltung der Produkte und Dienst​leistungen',
content: 'Angebot ökologisch höherwertiger Produkte / Dienstleistungen; Bewusstsein schaffende Maßnahmen; Berücksichtigung ökologischer Aspekte bei der KundInnenwahl',
points: 90,
soleProprietorship: true
},
{
shortcode : 'D4',
shortcodeSlug : 'd4',
title: 'Soziale Gestaltung der Produkte und Dienst​leistungen',
content: 'Informationen / Produkten / Dienstleistungen für benachteiligte KundInnen-Gruppen. Unterstützung förderungs​würdiger Marktstrukturen.',
points: 30,
soleProprietorship: true
},
{
shortcode : 'D5',
shortcodeSlug : 'd5',
title: 'Erhöhung der sozialen und ökologischen Branchen​standards',
content: 'Vorbildwirkung, Entwicklung von höheren Standards mit MitbewerberInnen, Lobbying',
points: 30,
soleProprietorship: true
}
]
},
{
shortcode : 'E',
name: 'Gesell​schaftliches Umfeld:',
explanation: 'Region, Souverän, zukünftige Generationen, Zivil​gesellschaft, Mitmenschen und Natur',
values: [
{
shortcode : 'E1',
shortcodeSlug : 'e1',
title: 'Sinn und Gesell​schaftliche Wirkung der Produkte / Dienst​leistungen',
content: 'P/DL decken den Grundbedarf oder dienen der Entwicklung der Menschen / der Gemeinschaft / der Erde und generieren positiven Nutzen.',
points: 50,
soleProprietorship: true
},
{
shortcode : 'E2',
shortcodeSlug : 'e2',
title: 'Beitrag zum Gemeinwesen',
content: 'Gegenseitige Unterstützung und Kooperation durch Finanzmittel, Dienstleistungen, Produkte, Logistik, Zeit, Know-How, Wissen, Kontakte, Einfluss',
points: 40,
soleProprietorship: true
},
{
shortcode : 'E3',
shortcodeSlug : 'e3',
title: 'Reduktion ökologischer Auswirkungen',
content: 'Reduktion der Umwelt​auswirkungen auf ein zukunftsfähiges Niveau: Ressourcen, Energie & Klima, Emissionen, Abfälle etc.',
points: 70,
soleProprietorship: true
},
{
shortcode : 'E4',
shortcodeSlug : 'e4',
title: 'Gemeinwohl​orientierte Gewinn-Verteilung',
content: 'Sinkende / keine Gewinn​ausschüttung an Externe, Ausschüttung an Mitarbeiter, Stärkung des Eigenkapitals, sozial-ökologische Investitionen',
points: 60,
soleProprietorship: false
},
{
shortcode : 'E5',
shortcodeSlug : 'e5',
title: 'Gesellschaft​liche Transparenz und Mitbestimmung',
content: 'Gemeinwohl- oder Nachhaltigkeits​bericht, Mitbestimmung von regionalen und zivilgesell​schaftlichen Berührungs​gruppen',
points: 30,
soleProprietorship: true
}
]
}
],
negativeCriteria : [
{
values: [
{
shortcode : 'N1',
shortcodeSlug : 'n1',
titleShort: 'Verletzung der ILO-Arbeitsnormen / Menschenrechte',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N2',
shortcodeSlug : 'n2',
titleShort: 'Menschen​unwürdige Produkte, z.B. Tretminen, Atomstrom, GMO',
title: 'Menschenunwürdige Produkte und Dienstleistungen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N3',
shortcodeSlug : 'n3',
titleShort: 'Beschaffung bei / Kooperation mit Unternehmen, welche die Menschenwürde verletzen',
title: 'Menschenunwürdige Produkte und Dienstbeschaffung bei bzt. Kooperation mit Unternehmen, welche die Menschenwürde verletzen',
points: -150,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N4',
shortcodeSlug : 'n4',
titleShort: 'Feindliche Übernahme',
title: 'Feindliche Übernahme',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N5',
shortcodeSlug : 'n5',
titleShort: 'Sperrpatente',
title: 'Sperrpatente',
points: -100,
soleProprietorship: true
},
{
shortcode : 'N6',
shortcodeSlug : 'n6',
titleShort: 'Dumping​preise',
title: 'Dumpingpreise',
points: -200,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N7',
shortcodeSlug : 'n7',
titleShort: 'Illegitime Umweltbelastungen',
title: 'Illegitime Umweltbelastungen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N8',
shortcodeSlug : 'n8',
titleShort: 'Verstöße gegen Umweltauflagen',
title: 'Verstöße gegen Umweltauflagen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N9',
shortcodeSlug : 'n9',
titleShort: 'Geplante Obsoleszenz (kurze Lebensdauer der Produkte)',
title: 'Geplante Obsoleszenz',
points: -100,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N10',
shortcodeSlug : 'n10',
titleShort: 'Arbeits​rechtliches Fehlverhalten seitens des Unternehmens',
title: 'Arbeitsrechtliches Fehlverhalten seitens des Unternehmens',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N11',
shortcodeSlug : 'n11',
titleShort: 'Arbeitsplatz​abbau oder Standortverlagerung bei Gewinn',
title: 'Arbeitsplatzabbau oder Standortverlagerung trotz Gewinn',
points: -150,
soleProprietorship: true
},
{
shortcode : 'N12',
shortcodeSlug : 'n12',
titleShort: 'Umgehung der Steuerpflicht',
title: 'Arbeitsplatzabbau oder Standortverlagerung trotz Gewinn',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N13',
shortcodeSlug : 'n13',
titleShort: 'Keine unangemessene Verzinsung für nicht mitarbeitende Gesellschafter',
title: 'Keine unangemessene Verzinsung für nicht mitarbeitende Gesellschafter',
points: -200,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N14',
shortcodeSlug : 'n14',
titleShort: 'Nicht​offenlegung aller Beteiligungen und Töchter',
title: 'Nichtoffenlegung aller Beteiligungen und Töchter',
points: -100,
soleProprietorship: true
},
{
shortcode : 'N15',
shortcodeSlug : 'n15',
titleShort: 'Verhinderung eines Betriebsrats',
title: 'Verhinderung eines Betriebsrats',
points: -150,
soleProprietorship: true
},
{
shortcode : 'N16',
shortcodeSlug : 'n16',
titleShort: 'Nicht​offenlegung aller Finanzflüsse an Lobbies / Eintragung in das EU-Lobbyregister',
title: 'Nichtoffenlegung aller Finanzflüsse an Lobbyisten und Lobby-Organisationen / Nichteintragung ins Lobby-Register der EU',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N17',
shortcodeSlug : 'n17',
titleShort: 'Exzessive Einkommensspreizung',
title: 'Exzessive Einkommensspreizung',
points: -100,
soleProprietorship: true
}
]
}
]
};
exports.Data = Data;
| sinnwerkstatt/common-good-online-balance | ecg_balancing/templates/ecg_balancing/dustjs/gwoe-matrix-data_en.js | JavaScript | mit | 15,425 |
package org.apache.cordova.facebook;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookDialogException;
import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.FacebookSdk;
import com.facebook.FacebookServiceException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.share.ShareApi;
import com.facebook.share.Sharer;
import com.facebook.share.model.GameRequestContent;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.model.ShareOpenGraphObject;
import com.facebook.share.model.ShareOpenGraphAction;
import com.facebook.share.model.ShareOpenGraphContent;
import com.facebook.share.model.AppInviteContent;
import com.facebook.share.widget.GameRequestDialog;
import com.facebook.share.widget.MessageDialog;
import com.facebook.share.widget.ShareDialog;
import com.facebook.share.widget.AppInviteDialog;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class ConnectPlugin extends CordovaPlugin {
private static final int INVALID_ERROR_CODE = -2; //-1 is FacebookRequestError.INVALID_ERROR_CODE
private static final String PUBLISH_PERMISSION_PREFIX = "publish";
private static final String MANAGE_PERMISSION_PREFIX = "manage";
@SuppressWarnings("serial")
private static final Set<String> OTHER_PUBLISH_PERMISSIONS = new HashSet<String>() {
{
add("ads_management");
add("create_event");
add("rsvp_event");
}
};
private final String TAG = "ConnectPlugin";
private CallbackManager callbackManager;
private AppEventsLogger logger;
private CallbackContext loginContext = null;
private CallbackContext showDialogContext = null;
private CallbackContext graphContext = null;
private String graphPath;
private ShareDialog shareDialog;
private GameRequestDialog gameRequestDialog;
private AppInviteDialog appInviteDialog;
private MessageDialog messageDialog;
@Override
protected void pluginInitialize() {
FacebookSdk.sdkInitialize(cordova.getActivity().getApplicationContext());
// create callbackManager
callbackManager = CallbackManager.Factory.create();
// create AppEventsLogger
logger = AppEventsLogger.newLogger(cordova.getActivity().getApplicationContext());
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(final LoginResult loginResult) {
GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject jsonObject, GraphResponse response) {
if (response.getError() != null) {
if (graphContext != null) {
graphContext.error(getFacebookRequestErrorResponse(response.getError()));
} else if (loginContext != null) {
loginContext.error(getFacebookRequestErrorResponse(response.getError()));
}
return;
}
// If this login comes after doing a new permission request
// make the outstanding graph call
if (graphContext != null) {
makeGraphCall();
return;
}
Log.d(TAG, "returning login object " + jsonObject.toString());
loginContext.success(getResponse());
loginContext = null;
}
}).executeAsync();
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, loginContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, loginContext);
}
});
shareDialog = new ShareDialog(cordova.getActivity());
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
@Override
public void onSuccess(Sharer.Result result) {
if (showDialogContext != null) {
showDialogContext.success(result.getPostId());
showDialogContext = null;
}
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, showDialogContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, showDialogContext);
}
});
messageDialog = new MessageDialog(cordova.getActivity());
messageDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
@Override
public void onSuccess(Sharer.Result result) {
if (showDialogContext != null) {
showDialogContext.success();
showDialogContext = null;
}
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, showDialogContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, showDialogContext);
}
});
gameRequestDialog = new GameRequestDialog(cordova.getActivity());
gameRequestDialog.registerCallback(callbackManager, new FacebookCallback<GameRequestDialog.Result>() {
@Override
public void onSuccess(GameRequestDialog.Result result) {
if (showDialogContext != null) {
try {
JSONObject json = new JSONObject();
json.put("requestId", result.getRequestId());
json.put("recipientsIds", new JSONArray(result.getRequestRecipients()));
showDialogContext.success(json);
showDialogContext = null;
} catch (JSONException ex) {
showDialogContext.success();
showDialogContext = null;
}
}
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, showDialogContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, showDialogContext);
}
});
appInviteDialog = new AppInviteDialog(cordova.getActivity());
appInviteDialog.registerCallback(callbackManager, new FacebookCallback<AppInviteDialog.Result>() {
@Override
public void onSuccess(AppInviteDialog.Result result) {
if (showDialogContext != null) {
try {
JSONObject json = new JSONObject();
Bundle bundle = result.getData();
for (String key : bundle.keySet()) {
json.put(key, wrapObject(bundle.get(key)));
}
showDialogContext.success(json);
showDialogContext = null;
} catch (JSONException e) {
showDialogContext.success();
showDialogContext = null;
}
}
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, showDialogContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, showDialogContext);
}
});
}
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
// Developers can observe how frequently users activate their app by logging an app activation event.
AppEventsLogger.activateApp(cordova.getActivity());
}
@Override
public void onPause(boolean multitasking) {
super.onPause(multitasking);
AppEventsLogger.deactivateApp(cordova.getActivity());
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Log.d(TAG, "activity result in plugin: requestCode(" + requestCode + "), resultCode(" + resultCode + ")");
callbackManager.onActivityResult(requestCode, resultCode, intent);
}
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("login")) {
executeLogin(args, callbackContext);
return true;
} else if (action.equals("logout")) {
if (hasAccessToken()) {
LoginManager.getInstance().logOut();
callbackContext.success();
} else {
callbackContext.error("No valid session found, must call init and login before logout.");
}
return true;
} else if (action.equals("getLoginStatus")) {
callbackContext.success(getResponse());
return true;
} else if (action.equals("getAccessToken")) {
if (hasAccessToken()) {
callbackContext.success(AccessToken.getCurrentAccessToken().getToken());
} else {
// Session not open
callbackContext.error("Session not open.");
}
return true;
} else if (action.equals("logEvent")) {
executeLogEvent(args, callbackContext);
return true;
} else if (action.equals("logPurchase")) {
/*
* While calls to logEvent can be made to register purchase events,
* there is a helper method that explicitly takes a currency indicator.
*/
if (args.length() != 2) {
callbackContext.error("Invalid arguments");
return true;
}
int value = args.getInt(0);
String currency = args.getString(1);
logger.logPurchase(BigDecimal.valueOf(value), Currency.getInstance(currency));
callbackContext.success();
return true;
} else if (action.equals("showDialog")) {
executeDialog(args, callbackContext);
return true;
} else if (action.equals("graphApi")) {
executeGraph(args, callbackContext);
return true;
} else if (action.equals("appInvite")) {
executeAppInvite(args, callbackContext);
return true;
} else if (action.equals("activateApp")) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
AppEventsLogger.activateApp(cordova.getActivity());
}
});
return true;
}
return false;
}
private void executeAppInvite(JSONArray args, CallbackContext callbackContext) {
String url = null;
String picture = null;
JSONObject parameters;
try {
parameters = args.getJSONObject(0);
} catch (JSONException e) {
parameters = new JSONObject();
}
if (parameters.has("url")) {
try {
url = parameters.getString("url");
} catch (JSONException e) {
Log.e(TAG, "Non-string 'url' parameter provided to dialog");
callbackContext.error("Incorrect 'url' parameter");
return;
}
} else {
callbackContext.error("Missing required 'url' parameter");
return;
}
if (parameters.has("picture")) {
try {
picture = parameters.getString("picture");
} catch (JSONException e) {
Log.e(TAG, "Non-string 'picture' parameter provided to dialog");
callbackContext.error("Incorrect 'picture' parameter");
return;
}
}
if (AppInviteDialog.canShow()) {
AppInviteContent.Builder builder = new AppInviteContent.Builder();
builder.setApplinkUrl(url);
if (picture != null) {
builder.setPreviewImageUrl(picture);
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
cordova.setActivityResultCallback(this);
appInviteDialog.show(builder.build());
} else {
callbackContext.error("Unable to show dialog");
}
}
private void executeDialog(JSONArray args, CallbackContext callbackContext) throws JSONException {
Map<String, String> params = new HashMap<String, String>();
String method = null;
JSONObject parameters;
try {
parameters = args.getJSONObject(0);
} catch (JSONException e) {
parameters = new JSONObject();
}
Iterator<String> iter = parameters.keys();
while (iter.hasNext()) {
String key = iter.next();
if (key.equals("method")) {
try {
method = parameters.getString(key);
} catch (JSONException e) {
Log.w(TAG, "Nonstring method parameter provided to dialog");
}
} else {
try {
params.put(key, parameters.getString(key));
} catch (JSONException e) {
// Need to handle JSON parameters
Log.w(TAG, "Non-string parameter provided to dialog discarded");
}
}
}
if (method == null) {
callbackContext.error("No method provided");
} else if (method.equalsIgnoreCase("apprequests")) {
if (!GameRequestDialog.canShow()) {
callbackContext.error("Cannot show dialog");
return;
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
GameRequestContent.Builder builder = new GameRequestContent.Builder();
if (params.containsKey("message"))
builder.setMessage(params.get("message"));
if (params.containsKey("to"))
builder.setTo(params.get("to"));
if (params.containsKey("data"))
builder.setData(params.get("data"));
if (params.containsKey("title"))
builder.setTitle(params.get("title"));
if (params.containsKey("objectId"))
builder.setObjectId(params.get("objectId"));
if (params.containsKey("actionType")) {
try {
final GameRequestContent.ActionType actionType = GameRequestContent.ActionType.valueOf(params.get("actionType"));
builder.setActionType(actionType);
} catch (IllegalArgumentException e) {
Log.w(TAG, "Discarding invalid argument actionType");
}
}
if (params.containsKey("filters")) {
try {
final GameRequestContent.Filters filters = GameRequestContent.Filters.valueOf(params.get("filters"));
builder.setFilters(filters);
} catch (IllegalArgumentException e) {
Log.w(TAG, "Discarding invalid argument filters");
}
}
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
gameRequestDialog.show(builder.build());
} else if (method.equalsIgnoreCase("share") || method.equalsIgnoreCase("feed")) {
if (!ShareDialog.canShow(ShareLinkContent.class)) {
callbackContext.error("Cannot show dialog");
return;
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
ShareLinkContent content = buildContent(params);
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
shareDialog.show(content);
} else if (method.equalsIgnoreCase("share_open_graph")) {
if (!ShareDialog.canShow(ShareOpenGraphContent.class)) {
callbackContext.error("Cannot show dialog");
return;
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
if (!params.containsKey("action")) {
callbackContext.error("Missing required parameter 'action'");
}
if (!params.containsKey("object")) {
callbackContext.error("Missing required parameter 'object'.");
}
ShareOpenGraphObject.Builder objectBuilder = new ShareOpenGraphObject.Builder();
JSONObject jObject = new JSONObject(params.get("object"));
Iterator<?> objectKeys = jObject.keys();
String objectType = "";
while ( objectKeys.hasNext() ) {
String key = (String)objectKeys.next();
String value = jObject.getString(key);
objectBuilder.putString(key, value);
if (key.equals("og:type"))
objectType = value;
}
if (objectType.equals("")) {
callbackContext.error("Missing required object parameter 'og:type'");
}
ShareOpenGraphAction.Builder actionBuilder = new ShareOpenGraphAction.Builder();
actionBuilder.setActionType(params.get("action"));
if (params.containsKey("action_properties")) {
JSONObject jActionProperties = new JSONObject(params.get("action_properties"));
Iterator<?> actionKeys = jActionProperties.keys();
while ( actionKeys.hasNext() ) {
String actionKey = (String)actionKeys.next();
actionBuilder.putString(actionKey, jActionProperties.getString(actionKey));
}
}
actionBuilder.putObject(objectType, objectBuilder.build());
ShareOpenGraphContent.Builder content = new ShareOpenGraphContent.Builder()
.setPreviewPropertyName(objectType)
.setAction(actionBuilder.build());
shareDialog.show(content.build());
} else if (method.equalsIgnoreCase("send")) {
if (!MessageDialog.canShow(ShareLinkContent.class)) {
callbackContext.error("Cannot show dialog");
return;
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
ShareLinkContent.Builder builder = new ShareLinkContent.Builder();
if(params.containsKey("link"))
builder.setContentUrl(Uri.parse(params.get("link")));
if(params.containsKey("caption"))
builder.setContentTitle(params.get("caption"));
if(params.containsKey("picture"))
builder.setImageUrl(Uri.parse(params.get("picture")));
if(params.containsKey("description"))
builder.setContentDescription(params.get("description"));
messageDialog.show(builder.build());
} else {
callbackContext.error("Unsupported dialog method.");
}
}
private void executeGraph(JSONArray args, CallbackContext callbackContext) throws JSONException {
graphContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
graphContext.sendPluginResult(pr);
graphPath = args.getString(0);
JSONArray arr = args.getJSONArray(1);
final Set<String> permissions = new HashSet<String>(arr.length());
for (int i = 0; i < arr.length(); i++) {
permissions.add(arr.getString(i));
}
if (permissions.size() == 0) {
makeGraphCall();
return;
}
boolean publishPermissions = false;
boolean readPermissions = false;
String declinedPermission = null;
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken.getPermissions().containsAll(permissions)) {
makeGraphCall();
return;
}
Set<String> declined = accessToken.getDeclinedPermissions();
// Figure out if we have all permissions
for (String permission : permissions) {
if (declined.contains(permission)) {
declinedPermission = permission;
break;
}
if (isPublishPermission(permission)) {
publishPermissions = true;
} else {
readPermissions = true;
}
// Break if we have a mixed bag, as this is an error
if (publishPermissions && readPermissions) {
break;
}
}
if (declinedPermission != null) {
graphContext.error("This request needs declined permission: " + declinedPermission);
}
if (publishPermissions && readPermissions) {
graphContext.error("Cannot ask for both read and publish permissions.");
return;
}
cordova.setActivityResultCallback(this);
LoginManager loginManager = LoginManager.getInstance();
// Check for write permissions, the default is read (empty)
if (publishPermissions) {
// Request new publish permissions
loginManager.logInWithPublishPermissions(cordova.getActivity(), permissions);
} else {
// Request new read permissions
loginManager.logInWithReadPermissions(cordova.getActivity(), permissions);
}
}
private void executeLogEvent(JSONArray args, CallbackContext callbackContext) throws JSONException {
if (args.length() == 0) {
// Not enough parameters
callbackContext.error("Invalid arguments");
return;
}
String eventName = args.getString(0);
if (args.length() == 1) {
logger.logEvent(eventName);
callbackContext.success();
return;
}
// Arguments is greater than 1
JSONObject params = args.getJSONObject(1);
Bundle parameters = new Bundle();
Iterator<String> iter = params.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
// Try get a String
String value = params.getString(key);
parameters.putString(key, value);
} catch (JSONException e) {
// Maybe it was an int
Log.w(TAG, "Type in AppEvent parameters was not String for key: " + key);
try {
int value = params.getInt(key);
parameters.putInt(key, value);
} catch (JSONException e2) {
// Nope
Log.e(TAG, "Unsupported type in AppEvent parameters for key: " + key);
}
}
}
if (args.length() == 2) {
logger.logEvent(eventName, parameters);
callbackContext.success();
}
if (args.length() == 3) {
double value = args.getDouble(2);
logger.logEvent(eventName, value, parameters);
callbackContext.success();
}
}
private void executeLogin(JSONArray args, CallbackContext callbackContext) throws JSONException {
Log.d(TAG, "login FB");
// Get the permissions
Set<String> permissions = new HashSet<String>(args.length());
for (int i = 0; i < args.length(); i++) {
permissions.add(args.getString(i));
}
// Set a pending callback to cordova
loginContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
loginContext.sendPluginResult(pr);
// Check if the active session is open
if (!hasAccessToken()) {
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
// Create the request
LoginManager.getInstance().logInWithReadPermissions(cordova.getActivity(), permissions);
return;
}
// Reauthorize flow
boolean publishPermissions = false;
boolean readPermissions = false;
// Figure out if this will be a read or publish reauthorize
if (permissions.size() == 0) {
// No permissions, read
readPermissions = true;
}
// Loop through the permissions to see what
// is being requested
for (String permission : permissions) {
if (isPublishPermission(permission)) {
publishPermissions = true;
} else {
readPermissions = true;
}
// Break if we have a mixed bag, as this is an error
if (publishPermissions && readPermissions) {
break;
}
}
if (publishPermissions && readPermissions) {
loginContext.error("Cannot ask for both read and publish permissions.");
loginContext = null;
return;
}
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
// Check for write permissions, the default is read (empty)
if (publishPermissions) {
// Request new publish permissions
LoginManager.getInstance().logInWithPublishPermissions(cordova.getActivity(), permissions);
} else {
// Request new read permissions
LoginManager.getInstance().logInWithReadPermissions(cordova.getActivity(), permissions);
}
}
private ShareLinkContent buildContent(Map<String, String> paramBundle) {
ShareLinkContent.Builder builder = new ShareLinkContent.Builder();
if (paramBundle.containsKey("caption"))
builder.setContentTitle(paramBundle.get("caption"));
if (paramBundle.containsKey("description"))
builder.setContentDescription(paramBundle.get("description"));
if (paramBundle.containsKey("href"))
builder.setContentUrl(Uri.parse(paramBundle.get("href")));
if (paramBundle.containsKey("picture"))
builder.setImageUrl(Uri.parse(paramBundle.get("picture")));
return builder.build();
}
// Simple active session check
private boolean hasAccessToken() {
return AccessToken.getCurrentAccessToken() != null;
}
private void handleError(FacebookException exception, CallbackContext context) {
if (exception.getMessage() != null) {
Log.e(TAG, exception.toString());
}
String errMsg = "Facebook error: " + exception.getMessage();
int errorCode = INVALID_ERROR_CODE;
// User clicked "x"
if (exception instanceof FacebookOperationCanceledException) {
errMsg = "User cancelled dialog";
errorCode = 4201;
} else if (exception instanceof FacebookDialogException) {
// Dialog error
errMsg = "Dialog error: " + exception.getMessage();
}
if (context != null) {
context.error(getErrorResponse(exception, errMsg, errorCode));
} else {
Log.e(TAG, "Error already sent so no context, msg: " + errMsg + ", code: " + errorCode);
}
}
private void makeGraphCall() {
//If you're using the paging URLs they will be URLEncoded, let's decode them.
try {
graphPath = URLDecoder.decode(graphPath, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String[] urlParts = graphPath.split("\\?");
String graphAction = urlParts[0];
GraphRequest graphRequest = GraphRequest.newGraphPathRequest(AccessToken.getCurrentAccessToken(), graphAction, new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
if (graphContext != null) {
if (response.getError() != null) {
graphContext.error(getFacebookRequestErrorResponse(response.getError()));
} else {
graphContext.success(response.getJSONObject());
}
graphPath = null;
graphContext = null;
}
}
});
Bundle params = graphRequest.getParameters();
if (urlParts.length > 1) {
String[] queries = urlParts[1].split("&");
for (String query : queries) {
int splitPoint = query.indexOf("=");
if (splitPoint > 0) {
String key = query.substring(0, splitPoint);
String value = query.substring(splitPoint + 1, query.length());
params.putString(key, value);
}
}
}
graphRequest.setParameters(params);
graphRequest.executeAsync();
}
/*
* Checks for publish permissions
*/
private boolean isPublishPermission(String permission) {
return permission != null &&
(permission.startsWith(PUBLISH_PERMISSION_PREFIX) ||
permission.startsWith(MANAGE_PERMISSION_PREFIX) ||
OTHER_PUBLISH_PERMISSIONS.contains(permission));
}
/**
* Create a Facebook Response object that matches the one for the Javascript SDK
* @return JSONObject - the response object
*/
public JSONObject getResponse() {
String response;
final AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (hasAccessToken()) {
Date today = new Date();
long expiresTimeInterval = (accessToken.getExpires().getTime() - today.getTime()) / 1000L;
response = "{"
+ "\"status\": \"connected\","
+ "\"authResponse\": {"
+ "\"accessToken\": \"" + accessToken.getToken() + "\","
+ "\"expiresIn\": \"" + Math.max(expiresTimeInterval, 0) + "\","
+ "\"session_key\": true,"
+ "\"sig\": \"...\","
+ "\"userID\": \"" + accessToken.getUserId() + "\""
+ "}"
+ "}";
} else {
response = "{"
+ "\"status\": \"unknown\""
+ "}";
}
try {
return new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
return new JSONObject();
}
public JSONObject getFacebookRequestErrorResponse(FacebookRequestError error) {
String response = "{"
+ "\"errorCode\": \"" + error.getErrorCode() + "\","
+ "\"errorType\": \"" + error.getErrorType() + "\","
+ "\"errorMessage\": \"" + error.getErrorMessage() + "\"";
if (error.getErrorUserMessage() != null) {
response += ",\"errorUserMessage\": \"" + error.getErrorUserMessage() + "\"";
}
if (error.getErrorUserTitle() != null) {
response += ",\"errorUserTitle\": \"" + error.getErrorUserTitle() + "\"";
}
response += "}";
try {
return new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
return new JSONObject();
}
public JSONObject getErrorResponse(Exception error, String message, int errorCode) {
if (error instanceof FacebookServiceException) {
return getFacebookRequestErrorResponse(((FacebookServiceException) error).getRequestError());
}
String response = "{";
if (error instanceof FacebookDialogException) {
errorCode = ((FacebookDialogException) error).getErrorCode();
}
if (errorCode != INVALID_ERROR_CODE) {
response += "\"errorCode\": \"" + errorCode + "\",";
}
if (message == null) {
message = error.getMessage();
}
response += "\"errorMessage\": \"" + message + "\"}";
try {
return new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
return new JSONObject();
}
/**
* Wraps the given object if necessary.
*
* If the object is null or , returns {@link #JSONObject.NULL}.
* If the object is a {@code JSONArray} or {@code JSONObject}, no wrapping is necessary.
* If the object is {@code JSONObject.NULL}, no wrapping is necessary.
* If the object is an array or {@code Collection}, returns an equivalent {@code JSONArray}.
* If the object is a {@code Map}, returns an equivalent {@code JSONObject}.
* If the object is a primitive wrapper type or {@code String}, returns the object.
* Otherwise if the object is from a {@code java} package, returns the result of {@code toString}.
* If wrapping fails, returns null.
*/
private static Object wrapObject(Object o) {
if (o == null) {
return JSONObject.NULL;
}
if (o instanceof JSONArray || o instanceof JSONObject) {
return o;
}
if (o.equals(JSONObject.NULL)) {
return o;
}
try {
if (o instanceof Collection) {
return new JSONArray((Collection) o);
} else if (o.getClass().isArray()) {
return new JSONArray(o);
}
if (o instanceof Map) {
return new JSONObject((Map) o);
}
if (o instanceof Boolean ||
o instanceof Byte ||
o instanceof Character ||
o instanceof Double ||
o instanceof Float ||
o instanceof Integer ||
o instanceof Long ||
o instanceof Short ||
o instanceof String) {
return o;
}
if (o.getClass().getPackage().getName().startsWith("java.")) {
return o.toString();
}
} catch (Exception ignored) {
}
return null;
}
}
| CONDACORE/fahndo-app | plugins/cordova-plugin-facebook4/src/android/ConnectPlugin.java | Java | mit | 37,503 |
<?php
/***************************************************************************\
* SPIP, Systeme de publication pour l'internet *
* *
* Copyright (c) 2001-2011 *
* Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James *
* *
* Ce programme est un logiciel libre distribue sous licence GNU/GPL. *
* Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. *
\***************************************************************************/
if (!defined('_ECRIRE_INC_VERSION')) return;
// Donne la liste des champs/tables ou l'on sait chercher/remplacer
// avec un poids pour le score
// http://doc.spip.org/@liste_des_champs
function liste_des_champs() {
return
pipeline('rechercher_liste_des_champs',
array(
'article' => array(
'surtitre' => 5, 'titre' => 8, 'soustitre' => 5, 'chapo' => 3,
'texte' => 1, 'ps' => 1, 'nom_site' => 1, 'url_site' => 1,
'descriptif' => 4
),
'breve' => array(
'titre' => 8, 'texte' => 2, 'lien_titre' => 1, 'lien_url' => 1
),
'rubrique' => array(
'titre' => 8, 'descriptif' => 5, 'texte' => 1
),
'site' => array(
'nom_site' => 5, 'url_site' => 1, 'descriptif' => 3
),
'mot' => array(
'titre' => 8, 'texte' => 1, 'descriptif' => 5
),
'auteur' => array(
'nom' => 5, 'bio' => 1, 'email' => 1, 'nom_site' => 1, 'url_site' => 1, 'login' => 1
),
'forum' => array(
'titre' => 3, 'texte' => 1, 'auteur' => 2, 'email_auteur' => 2, 'nom_site' => 1, 'url_site' => 1
),
'document' => array(
'titre' => 3, 'descriptif' => 1, 'fichier' => 1
),
'syndic_article' => array(
'titre' => 5, 'descriptif' => 1
),
'signature' => array(
'nom_email' => 2, 'ad_email' => 4,
'nom_site' => 2, 'url_site' => 4,
'message' => 1
)
)
);
}
// Recherche des auteurs et mots-cles associes
// en ne regardant que le titre ou le nom
// http://doc.spip.org/@liste_des_jointures
function liste_des_jointures() {
return
pipeline('rechercher_liste_des_jointures',
array(
'article' => array(
'auteur' => array('nom' => 10),
'mot' => array('titre' => 3),
'document' => array('titre' => 2, 'descriptif' => 1)
),
'breve' => array(
'mot' => array('titre' => 3),
'document' => array('titre' => 2, 'descriptif' => 1)
),
'rubrique' => array(
'mot' => array('titre' => 3),
'document' => array('titre' => 2, 'descriptif' => 1)
),
'document' => array(
'mot' => array('titre' => 3)
)
)
);
}
// Effectue une recherche sur toutes les tables de la base de donnees
// options :
// - toutvoir pour eviter autoriser(voir)
// - flags pour eviter les flags regexp par defaut (UimsS)
// - champs pour retourner les champs concernes
// - score pour retourner un score
// On peut passer les tables, ou une chaine listant les tables souhaitees
// http://doc.spip.org/@recherche_en_base
function recherche_en_base($recherche='', $tables=NULL, $options=array(), $serveur='') {
include_spip('base/abstract_sql');
if (!is_array($tables)) {
$liste = liste_des_champs();
if (is_string($tables)
AND $tables != '') {
$toutes = array();
foreach(explode(',', $tables) as $t)
if (isset($liste[$t]))
$toutes[$t] = $liste[$t];
$tables = $toutes;
unset($toutes);
} else
$tables = $liste;
}
include_spip('inc/autoriser');
// options par defaut
$options = array_merge(array(
'preg_flags' => 'UimsS',
'toutvoir' => false,
'champs' => false,
'score' => false,
'matches' => false,
'jointures' => false
),
$options
);
$results = array();
if (!strlen($recherche) OR !count($tables))
return array();
include_spip('inc/charsets');
$recherche = translitteration($recherche);
$is_preg = false;
if (substr($recherche,0,1)=='/' AND substr($recherche,-1,1)=='/'){
// c'est une preg
$preg = $recherche.$options['preg_flags'];
$is_preg = true;
}
else
$preg = '/'.str_replace('/', '\\/', $recherche).'/' . $options['preg_flags'];
// Si la chaine est inactive, on va utiliser LIKE pour aller plus vite
// ou si l'expression reguliere est invalide
if (!$is_preg
OR (@preg_match($preg,'')===FALSE) ) {
$methode = 'LIKE';
$u = $GLOBALS['meta']['pcre_u'];
// eviter les parentheses et autres caractères qui interferent avec pcre par la suite (dans le preg_match_all) s'il y a des reponses
$recherche = str_replace(
array('(',')','?','[', ']', '+', '*', '/'),
array('\(','\)','[?]', '\[', '\]', '\+', '\*', '\/'),
$recherche);
$recherche_mod = $recherche;
// echapper les % et _
$q = str_replace(array('%','_'), array('\%', '\_'), trim($recherche));
// les expressions entre " " sont un mot a chercher tel quel
// -> on remplace les espaces par un _ et on enleve les guillemets
if (preg_match(',["][^"]+["],Uims',$q,$matches)){
foreach($matches as $match){
// corriger le like dans le $q
$word = preg_replace(",\s+,Uims","_",$match);
$word = trim($word,'"');
$q = str_replace($match,$word,$q);
// corriger la regexp
$word = preg_replace(",\s+,Uims","[\s]",$match);
$word = trim($word,'"');
$recherche_mod = str_replace($match,$word,$recherche_mod);
}
}
$q = sql_quote(
"%"
. preg_replace(",\s+,".$u, "%", $q)
. "%"
);
$preg = '/'.preg_replace(",\s+,".$u, ".+", trim($recherche_mod)).'/' . $options['preg_flags'];
} else {
$methode = 'REGEXP';
$q = sql_quote(substr($recherche,1,-1));
}
$jointures = $options['jointures']
? liste_des_jointures()
: array();
foreach ($tables as $table => $champs) {
$requete = array(
"SELECT"=>array(),
"FROM"=>array(),
"WHERE"=>array(),
"GROUPBY"=>array(),
"ORDERBY"=>array(),
"LIMIT"=>"",
"HAVING"=>array()
);
$_id_table = id_table_objet($table);
$requete['SELECT'][] = "t.".$_id_table;
$a = array();
// Recherche fulltext
foreach ($champs as $champ => $poids) {
if (is_array($champ)){
spip_log("requetes imbriquees interdites");
} else {
if (strpos($champ,".")===FALSE)
$champ = "t.$champ";
$requete['SELECT'][] = $champ;
$a[] = $champ.' '.$methode.' '.$q;
}
}
if ($a) $requete['WHERE'][] = join(" OR ", $a);
$requete['FROM'][] = table_objet_sql($table).' AS t';
$s = sql_select(
$requete['SELECT'], $requete['FROM'], $requete['WHERE'],
implode(" ",$requete['GROUPBY']),
$requete['ORDERBY'], $requete['LIMIT'],
$requete['HAVING'], $serveur
);
while ($t = sql_fetch($s,$serveur)) {
$id = intval($t[$_id_table]);
if ($options['toutvoir']
OR autoriser('voir', $table, $id)) {
// indiquer les champs concernes
$champs_vus = array();
$score = 0;
$matches = array();
$vu = false;
foreach ($champs as $champ => $poids) {
$champ = explode('.',$champ);
$champ = end($champ);
if ($n =
($options['score'] || $options['matches'])
? preg_match_all($preg, translitteration_rapide($t[$champ]), $regs, PREG_SET_ORDER)
: preg_match($preg, translitteration_rapide($t[$champ]))
) {
$vu = true;
if ($options['champs'])
$champs_vus[$champ] = $t[$champ];
if ($options['score'])
$score += $n * $poids;
if ($options['matches'])
$matches[$champ] = $regs;
if (!$options['champs']
AND !$options['score']
AND !$options['matches'])
break;
}
}
if ($vu) {
if (!isset($results[$table]))
$results[$table] = array();
$results[$table][$id] = array();
if ($champs_vus)
$results[$table][$id]['champs'] = $champs_vus;
if ($score)
$results[$table][$id]['score'] = $score;
if ($matches)
$results[$table][$id]['matches'] = $matches;
}
}
}
// Gerer les donnees associees
if (isset($jointures[$table])
AND $joints = recherche_en_base(
$recherche,
$jointures[$table],
array_merge($options, array('jointures' => false))
)
) {
foreach ($joints as $table_liee => $ids_trouves) {
if (!$rechercher_joints = charger_fonction("rechercher_joints_${table}_${table_liee}","inc",true)){
$cle_depart = id_table_objet($table);
$cle_arrivee = id_table_objet($table_liee);
$table_sql = preg_replace('/^spip_/', '', table_objet_sql($table));
$table_liee_sql = preg_replace('/^spip_/', '', table_objet_sql($table_liee));
if ($table_liee == 'document')
$s = sql_select("id_objet as $cle_depart, $cle_arrivee", "spip_documents_liens", array("objet='$table'",sql_in('id_'.${table_liee}, array_keys($ids_trouves))), '','','','',$serveur);
else
$s = sql_select("$cle_depart,$cle_arrivee", "spip_${table_liee_sql}_${table_sql}", sql_in('id_'.${table_liee}, array_keys($ids_trouves)), '','','','',$serveur);
}
else
list($cle_depart,$cle_arrivee,$s) = $rechercher_joints($table,$table_liee,array_keys($ids_trouves), $serveur);
while ($t = is_array($s)?array_shift($s):sql_fetch($s)) {
$id = $t[$cle_depart];
$joint = $ids_trouves[$t[$cle_arrivee]];
if (!isset($results[$table]))
$results[$table] = array();
if (!isset($results[$table][$id]))
$results[$table][$id] = array();
if ($joint['score'])
$results[$table][$id]['score'] += $joint['score'];
if ($joint['champs'])
foreach($joint['champs'] as $c => $val)
$results[$table][$id]['champs'][$table_liee.'.'.$c] = $val;
if ($joint['matches'])
foreach($joint['matches'] as $c => $val)
$results[$table][$id]['matches'][$table_liee.'.'.$c] = $val;
}
}
}
}
return $results;
}
// Effectue une recherche sur toutes les tables de la base de donnees
// http://doc.spip.org/@remplace_en_base
function remplace_en_base($recherche='', $remplace=NULL, $tables=NULL, $options=array()) {
include_spip('inc/modifier');
// options par defaut
$options = array_merge(array(
'preg_flags' => 'UimsS',
'toutmodifier' => false
),
$options
);
$options['champs'] = true;
if (!is_array($tables))
$tables = liste_des_champs();
$results = recherche_en_base($recherche, $tables, $options);
$preg = '/'.str_replace('/', '\\/', $recherche).'/' . $options['preg_flags'];
foreach ($results as $table => $r) {
$_id_table = id_table_objet($table);
foreach ($r as $id => $x) {
if ($options['toutmodifier']
OR autoriser('modifier', $table, $id)) {
$modifs = array();
foreach ($x['champs'] as $key => $val) {
if ($key == $_id_table) next;
$repl = preg_replace($preg, $remplace, $val);
if ($repl <> $val)
$modifs[$key] = $repl;
}
if ($modifs)
modifier_contenu($table, $id,
array(
'champs' => array_keys($modifs),
),
$modifs);
}
}
}
}
?>
| eyeswebcrea/cheminee-mario.com | spip/ecrire/inc/rechercher.php | PHP | mit | 10,890 |
<?php
/**
* Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
* CC-BY License - http://creativecommons.org/licenses/by/3.0/
*/
$aConfig = array(
/**
* Main Section.
*/
'title' => 'Organizations',
'version_from' => '8.0.1',
'version_to' => '8.0.2',
'vendor' => 'BoonEx',
'compatible_with' => array(
'8.0.0.A8'
),
/**
* 'home_dir' and 'home_uri' - should be unique. Don't use spaces in 'home_uri' and the other special chars.
*/
'home_dir' => 'boonex/organizations/updates/update_8.0.1_8.0.2/',
'home_uri' => 'orgs_update_801_802',
'module_dir' => 'boonex/organizations/',
'module_uri' => 'orgs',
'db_prefix' => 'bx_organizations_',
'class_prefix' => 'BxOrgs',
/**
* Installation/Uninstallation Section.
*/
'install' => array(
'execute_sql' => 1,
'update_files' => 1,
'update_languages' => 1,
'clear_db_cache' => 1,
),
/**
* Category for language keys.
*/
'language_category' => 'Organizations',
);
| camperjz/trident | modules/boonex/organizations/updates/8.0.1_8.0.2/install/config.php | PHP | mit | 1,044 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest.Azure.Authentication.Properties;
namespace Microsoft.Rest.Azure.Authentication
{
/// <summary>
/// Settings for authentication with an Azure or Azure Stack service using Active Directory.
/// </summary>
public sealed class ActiveDirectoryServiceSettings
{
private Uri _authenticationEndpoint;
private static readonly ActiveDirectoryServiceSettings AzureSettings = new ActiveDirectoryServiceSettings
{
AuthenticationEndpoint= new Uri("https://login.windows.net/"),
TokenAudience = new Uri("https://management.core.windows.net/"),
ValidateAuthority = true
};
private static readonly ActiveDirectoryServiceSettings AzureChinaSettings = new ActiveDirectoryServiceSettings
{
AuthenticationEndpoint= new Uri("https://login.chinacloudapi.cn/"),
TokenAudience = new Uri("https://management.core.chinacloudapi.cn/"),
ValidateAuthority = true
};
/// <summary>
/// Gets the serviceSettings for authentication with Azure
/// </summary>
public static ActiveDirectoryServiceSettings Azure { get { return AzureSettings; } }
/// <summary>
/// Gets the serviceSettings for authentication with Azure China
/// </summary>
public static ActiveDirectoryServiceSettings AzureChina { get { return AzureChinaSettings; } }
/// <summary>
/// Gets or sets the ActiveDirectory Endpoint for the Azure Environment
/// </summary>
public Uri AuthenticationEndpoint
{
get { return _authenticationEndpoint; }
set { _authenticationEndpoint = EnsureTrailingSlash(value); }
}
/// <summary>
/// Gets or sets the Token audience for an endpoint
/// </summary>
public Uri TokenAudience { get; set; }
/// <summary>
/// Gets or sets a value that determines whether the authentication endpoint should be validated with Azure AD
/// </summary>
public bool ValidateAuthority { get; set; }
private static Uri EnsureTrailingSlash(Uri authenticationEndpoint)
{
if (authenticationEndpoint == null)
{
throw new ArgumentNullException("authenticationEndpoint");
}
UriBuilder builder = new UriBuilder(authenticationEndpoint);
if (!string.IsNullOrEmpty(builder.Query))
{
throw new ArgumentOutOfRangeException(Resources.AuthenticationEndpointContainsQuery);
}
var path = builder.Path;
if (string.IsNullOrWhiteSpace(path))
{
path = "/";
}
else if (!path.EndsWith("/", StringComparison.Ordinal))
{
path = path + "/";
}
builder.Path = path;
return builder.Uri;
}
}
}
| colemickens/autorest | ClientRuntimes/CSharp/ClientRuntime.Azure.Authentication/ActiveDirectoryServiceSettings.cs | C# | mit | 3,207 |
# frozen_string_literal: true
module ActiveSupport
module NumberHelper
class NumberToRoundedConverter < NumberConverter # :nodoc:
self.namespace = :precision
self.validate_float = true
def convert
helper = RoundingHelper.new(options)
rounded_number = helper.round(number)
if precision = options[:precision]
if options[:significant] && precision > 0
digits = helper.digit_count(rounded_number)
precision -= digits
precision = 0 if precision < 0 # don't let it be negative
end
formatted_string =
if BigDecimal === rounded_number && rounded_number.finite?
s = rounded_number.to_s("F")
s << "0".freeze * precision
a, b = s.split(".".freeze, 2)
a << ".".freeze
a << b[0, precision]
else
"%00.#{precision}f" % rounded_number
end
else
formatted_string = rounded_number
end
delimited_number = NumberToDelimitedConverter.convert(formatted_string, options)
format_number(delimited_number)
end
private
def calculate_rounded_number(multiplier)
(number / BigDecimal.new(multiplier.to_f.to_s)).round * multiplier
end
def digit_count(number)
number.zero? ? 1 : (Math.log10(absolute_number(number)) + 1).floor
end
def strip_insignificant_zeros
options[:strip_insignificant_zeros]
end
def format_number(number)
if strip_insignificant_zeros
escaped_separator = Regexp.escape(options[:separator])
number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, "")
else
number
end
end
end
end
end
| felipecvo/rails | activesupport/lib/active_support/number_helper/number_to_rounded_converter.rb | Ruby | mit | 1,873 |
/**
* Module dependencies.
*/
var finalhandler = require('finalhandler');
var flatten = require('./utils').flatten;
var Router = require('./router');
var methods = require('methods');
var middleware = require('./middleware/init');
var query = require('./middleware/query');
var debug = require('debug')('express:application');
var View = require('./view');
var http = require('http');
var compileETag = require('./utils').compileETag;
var compileQueryParser = require('./utils').compileQueryParser;
var compileTrust = require('./utils').compileTrust;
var deprecate = require('depd')('express');
var merge = require('utils-merge');
var resolve = require('path').resolve;
var slice = Array.prototype.slice;
/**
* Application prototype.
*/
var app = exports = module.exports = {};
/**
* Initialize the server.
*
* - setup default configuration
* - setup default middleware
* - setup route reflection methods
*
* @api private
*/
app.init = function(){
this.cache = {};
this.settings = {};
this.engines = {};
this.defaultConfiguration();
};
/**
* Initialize application configuration.
*
* @api private
*/
app.defaultConfiguration = function(){
// default settings
this.enable('x-powered-by');
this.set('etag', 'weak');
var env = process.env.NODE_ENV || 'development';
this.set('env', env);
this.set('query parser', 'extended');
this.set('subdomain offset', 2);
this.set('trust proxy', false);
debug('booting in %s mode', env);
// inherit protos
this.on('mount', function(parent){
this.request.__proto__ = parent.request;
this.response.__proto__ = parent.response;
this.engines.__proto__ = parent.engines;
this.settings.__proto__ = parent.settings;
});
// setup locals
this.locals = Object.create(null);
// top-most app is mounted at /
this.mountpath = '/';
// default locals
this.locals.settings = this.settings;
// default configuration
this.set('view', View);
this.set('views', resolve('views'));
this.set('jsonp callback name', 'callback');
if (env === 'production') {
this.enable('view cache');
}
Object.defineProperty(this, 'router', {
get: function() {
throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');
}
});
};
/**
* lazily adds the base router if it has not yet been added.
*
* We cannot add the base router in the defaultConfiguration because
* it reads app settings which might be set after that has run.
*
* @api private
*/
app.lazyrouter = function() {
if (!this._router) {
this._router = new Router({
caseSensitive: this.enabled('case sensitive routing'),
strict: this.enabled('strict routing')
});
this._router.use(query(this.get('query parser fn')));
this._router.use(middleware.init(this));
}
};
/**
* Dispatch a req, res pair into the application. Starts pipeline processing.
*
* If no _done_ callback is provided, then default error handlers will respond
* in the event of an error bubbling through the stack.
*
* @api private
*/
app.handle = function(req, res, done) {
var router = this._router;
// final handler
done = done || finalhandler(req, res, {
env: this.get('env'),
onerror: logerror.bind(this)
});
// no routes
if (!router) {
debug('no routes defined on app');
done();
return;
}
router.handle(req, res, done);
};
/**
* Proxy `Router#use()` to add middleware to the app router.
* See Router#use() documentation for details.
*
* If the _fn_ parameter is an express app, then it will be
* mounted at the _route_ specified.
*
* @api public
*/
app.use = function use(fn) {
var offset = 0;
var path = '/';
// default path to '/'
// disambiguate app.use([fn])
if (typeof fn !== 'function') {
var arg = fn;
while (Array.isArray(arg) && arg.length !== 0) {
arg = arg[0];
}
// first arg is the path
if (typeof arg !== 'function') {
offset = 1;
path = fn;
}
}
var fns = flatten(slice.call(arguments, offset));
if (fns.length === 0) {
throw new TypeError('app.use() requires middleware functions');
}
// setup router
this.lazyrouter();
var router = this._router;
fns.forEach(function (fn) {
// non-express app
if (!fn || !fn.handle || !fn.set) {
return router.use(path, fn);
}
debug('.use app under %s', path);
fn.mountpath = path;
fn.parent = this;
// restore .app property on req and res
router.use(path, function mounted_app(req, res, next) {
var orig = req.app;
fn.handle(req, res, function (err) {
req.__proto__ = orig.request;
res.__proto__ = orig.response;
next(err);
});
});
// mounted an app
fn.emit('mount', this);
}, this);
return this;
};
/**
* Proxy to the app `Router#route()`
* Returns a new `Route` instance for the _path_.
*
* Routes are isolated middleware stacks for specific paths.
* See the Route api docs for details.
*
* @api public
*/
app.route = function(path){
this.lazyrouter();
return this._router.route(path);
};
/**
* Register the given template engine callback `fn`
* as `ext`.
*
* By default will `require()` the engine based on the
* file extension. For example if you try to render
* a "foo.jade" file Express will invoke the following internally:
*
* app.engine('jade', require('jade').__express);
*
* For engines that do not provide `.__express` out of the box,
* or if you wish to "map" a different extension to the template engine
* you may use this method. For example mapping the EJS template engine to
* ".html" files:
*
* app.engine('html', require('ejs').renderFile);
*
* In this case EJS provides a `.renderFile()` method with
* the same signature that Express expects: `(path, options, callback)`,
* though note that it aliases this method as `ejs.__express` internally
* so if you're using ".ejs" extensions you dont need to do anything.
*
* Some template engines do not follow this convention, the
* [Consolidate.js](https://github.com/tj/consolidate.js)
* library was created to map all of node's popular template
* engines to follow this convention, thus allowing them to
* work seamlessly within Express.
*
* @param {String} ext
* @param {Function} fn
* @return {app} for chaining
* @api public
*/
app.engine = function(ext, fn){
if ('function' != typeof fn) throw new Error('callback function required');
if ('.' != ext[0]) ext = '.' + ext;
this.engines[ext] = fn;
return this;
};
/**
* Proxy to `Router#param()` with one added api feature. The _name_ parameter
* can be an array of names.
*
* See the Router#param() docs for more details.
*
* @param {String|Array} name
* @param {Function} fn
* @return {app} for chaining
* @api public
*/
app.param = function(name, fn){
this.lazyrouter();
if (Array.isArray(name)) {
name.forEach(function(key) {
this.param(key, fn);
}, this);
return this;
}
this._router.param(name, fn);
return this;
};
/**
* Assign `setting` to `val`, or return `setting`'s value.
*
* app.set('foo', 'bar');
* app.get('foo');
* // => "bar"
*
* Mounted servers inherit their parent server's settings.
*
* @param {String} setting
* @param {*} [val]
* @return {Server} for chaining
* @api public
*/
app.set = function(setting, val){
if (arguments.length === 1) {
// app.get(setting)
return this.settings[setting];
}
// set value
this.settings[setting] = val;
// trigger matched settings
switch (setting) {
case 'etag':
debug('compile etag %s', val);
this.set('etag fn', compileETag(val));
break;
case 'query parser':
debug('compile query parser %s', val);
this.set('query parser fn', compileQueryParser(val));
break;
case 'trust proxy':
debug('compile trust proxy %s', val);
this.set('trust proxy fn', compileTrust(val));
break;
}
return this;
};
/**
* Return the app's absolute pathname
* based on the parent(s) that have
* mounted it.
*
* For example if the application was
* mounted as "/admin", which itself
* was mounted as "/blog" then the
* return value would be "/blog/admin".
*
* @return {String}
* @api private
*/
app.path = function(){
return this.parent
? this.parent.path() + this.mountpath
: '';
};
/**
* Check if `setting` is enabled (truthy).
*
* app.enabled('foo')
* // => false
*
* app.enable('foo')
* app.enabled('foo')
* // => true
*
* @param {String} setting
* @return {Boolean}
* @api public
*/
app.enabled = function(setting){
return !!this.set(setting);
};
/**
* Check if `setting` is disabled.
*
* app.disabled('foo')
* // => true
*
* app.enable('foo')
* app.disabled('foo')
* // => false
*
* @param {String} setting
* @return {Boolean}
* @api public
*/
app.disabled = function(setting){
return !this.set(setting);
};
/**
* Enable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @api public
*/
app.enable = function(setting){
return this.set(setting, true);
};
/**
* Disable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @api public
*/
app.disable = function(setting){
return this.set(setting, false);
};
/**
* Delegate `.VERB(...)` calls to `router.VERB(...)`.
*/
methods.forEach(function(method){
app[method] = function(path){
if ('get' == method && 1 == arguments.length) return this.set(path);
this.lazyrouter();
var route = this._router.route(path);
route[method].apply(route, slice.call(arguments, 1));
return this;
};
});
/**
* Special-cased "all" method, applying the given route `path`,
* middleware, and callback to _every_ HTTP method.
*
* @param {String} path
* @param {Function} ...
* @return {app} for chaining
* @api public
*/
app.all = function(path){
this.lazyrouter();
var route = this._router.route(path);
var args = slice.call(arguments, 1);
methods.forEach(function(method){
route[method].apply(route, args);
});
return this;
};
// del -> delete alias
app.del = deprecate.function(app.d | wenjoy/homePage | node_modules/node-captcha/node_modules/canvas/node_modules/mocha/node_modules/mkdirp/node_modules/mock-fs/node_modules/rewire/node_modules/expect.js/node_modules/serve/node_modules/less-middleware/node_modules/express/lib/application.js | JavaScript | mit | 10,240 |
#!/usr/bin/env python
class PivotFilter(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {
'AutoFilter': 'AutoFilter',
'EvaluationOrder': 'int',
'FieldIndex': 'int',
'FilterType': 'str',
'MeasureFldIndex': 'int',
'MemberPropertyFieldIndex': 'int',
'Name': 'str',
'Value1': 'str',
'Value2': 'str'
}
self.attributeMap = {
'AutoFilter': 'AutoFilter','EvaluationOrder': 'EvaluationOrder','FieldIndex': 'FieldIndex','FilterType': 'FilterType','MeasureFldIndex': 'MeasureFldIndex','MemberPropertyFieldIndex': 'MemberPropertyFieldIndex','Name': 'Name','Value1': 'Value1','Value2': 'Value2'}
self.AutoFilter = None # AutoFilter
self.EvaluationOrder = None # int
self.FieldIndex = None # int
self.FilterType = None # str
self.MeasureFldIndex = None # int
self.MemberPropertyFieldIndex = None # int
self.Name = None # str
self.Value1 = None # str
self.Value2 = None # str
| aspose-cells/Aspose.Cells-for-Cloud | SDKs/Aspose.Cells-Cloud-SDK-for-Python/asposecellscloud/models/PivotFilter.py | Python | mit | 1,456 |
class Service::Presently < Service
string :subdomain, :group_name, :username
password :password
white_list :subdomain, :group_name, :username
def receive_push
repository = payload['repository']['name']
prefix = (data['group_name'].nil? || data['group_name'] == '') ? '' : "b #{data['group_name']} "
payload['commits'].each do |commit|
status = "#{prefix}[#{repository}] #{commit['author']['name']} - #{commit['message']}"
status = status[0...137] + '...' if status.length > 140
paste = "\"Commit #{commit['id']}\":#{commit['url']}\n\n"
paste << "#{commit['message']}\n\n"
%w(added modified removed).each do |kind|
commit[kind].each do |filename|
paste << "* *#{kind.capitalize}* '#{filename}'\n"
end
end
http.url_prefix = "https://#{data['subdomain']}.presently.com"
http.basic_auth(data['username'], data['password'])
http_post "/api/twitter/statuses/update.xml",
'status' => status,
'source' => 'GitHub',
'paste_format' => 'textile',
'paste_text' => paste
end
end
end
| marko-asplund/github-services | services/presently.rb | Ruby | mit | 1,116 |
#include "ofApp.h"
#include "ofAppGlutWindow.h"
int main() {
ofAppGlutWindow window;
ofSetupOpenGL(&window, 512, 512, OF_WINDOW);
ofRunApp(new ofApp());
}
| Giladx/BlindSelfPortrait | EraserLine/src/main.cpp | C++ | mit | 159 |
require_relative '../executor.rb'
require_relative '../../thumbnail_generator.rb'
class GenerateThumbnailJob < Tabula::Background::Job
# args: (:file, :output_dir, :thumbnail_sizes, :page_index_job_uuid)
def perform
file_id = options[:file_id]
upload_id = self.uuid
filepath = options[:filepath]
output_dir = options[:output_dir]
thumbnail_sizes = options[:thumbnail_sizes]
generator = JPedalThumbnailGenerator.new(filepath, output_dir, thumbnail_sizes)
generator.add_observer(self, :at)
generator.generate_thumbnails!
end
end
| mr-justin/tabula | lib/tabula_job_executor/jobs/generate_thumbnails.rb | Ruby | mit | 570 |
Experiment(description='No with centred periodic',
data_dir='../data/tsdlr/',
max_depth=8,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=9,
sd=4,
max_jobs=600,
verbose=False,
make_predictions=False,
skip_complete=True,
results_dir='../results/2013-09-07/',
iters=250,
base_kernels='StepTanh,CenPer,Cos,Lin,SE,Const,MT5,IMT3Lin',
zero_mean=True,
random_seed=1,
period_heuristic=5,
subset=True,
subset_size=250,
full_iters=0,
bundle_size=5)
| jamesrobertlloyd/gpss-research | experiments/2013-09-07.py | Python | mit | 710 |
import { noop as css } from '../../helpers/noop-template'
const styles = css`
[data-nextjs-dialog] {
display: flex;
flex-direction: column;
width: 100%;
margin-right: auto;
margin-left: auto;
outline: none;
background: white;
border-radius: var(--size-gap);
box-shadow: 0 var(--size-gap-half) var(--size-gap-double)
rgba(0, 0, 0, 0.25);
max-height: calc(100% - 56px);
overflow-y: hidden;
}
@media (max-height: 812px) {
[data-nextjs-dialog-overlay] {
max-height: calc(100% - 15px);
}
}
@media (min-width: 576px) {
[data-nextjs-dialog] {
max-width: 540px;
box-shadow: 0 var(--size-gap) var(--size-gap-quad) rgba(0, 0, 0, 0.25);
}
}
@media (min-width: 768px) {
[data-nextjs-dialog] {
max-width: 720px;
}
}
@media (min-width: 992px) {
[data-nextjs-dialog] {
max-width: 960px;
}
}
[data-nextjs-dialog-banner] {
position: relative;
}
[data-nextjs-dialog-banner].banner-warning {
border-color: var(--color-ansi-yellow);
}
[data-nextjs-dialog-banner].banner-error {
border-color: var(--color-ansi-red);
}
[data-nextjs-dialog-banner]::after {
z-index: 2;
content: '';
position: absolute;
top: 0;
right: 0;
width: 100%;
/* banner width: */
border-top-width: var(--size-gap-half);
border-bottom-width: 0;
border-top-style: solid;
border-bottom-style: solid;
border-top-color: inherit;
border-bottom-color: transparent;
}
[data-nextjs-dialog-content] {
overflow-y: auto;
border: none;
margin: 0;
/* calc(padding + banner width offset) */
padding: calc(var(--size-gap-double) + var(--size-gap-half))
var(--size-gap-double);
height: 100%;
display: flex;
flex-direction: column;
}
[data-nextjs-dialog-content] > [data-nextjs-dialog-header] {
flex-shrink: 0;
margin-bottom: var(--size-gap-double);
}
[data-nextjs-dialog-content] > [data-nextjs-dialog-body] {
position: relative;
flex: 1 1 auto;
}
`
export { styles }
| flybayer/next.js | packages/react-dev-overlay/src/internal/components/Dialog/styles.ts | TypeScript | mit | 2,088 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace Dnn.Modules.ResourceManager.Services.Dto
{
using System.Runtime.Serialization;
/// <summary>
/// Represents a request for folder details.
/// </summary>
public class FolderDetailsRequest
{
/// <summary>
/// Gets or sets the id of the folder.
/// </summary>
[DataMember(Name = "folderId")]
public int FolderId { get; set; }
/// <summary>
/// Gets or sets the name of the folder.
/// </summary>
[DataMember(Name = "folderName")]
public string FolderName { get; set; }
/// <summary>
/// Gets or sets the <see cref="FolderPermissions"/>.
/// </summary>
[DataMember(Name = "permissions")]
public FolderPermissions Permissions { get; set; }
}
}
| dnnsoftware/Dnn.Platform | DNN Platform/Modules/ResourceManager/Services/Dto/FolderDetailsRequest.cs | C# | mit | 1,005 |
<div class="container-fluid">
<div class="row">
<div class="col-xs-6 col-xs-offset-3">
<div class="page-header" style="border:none;margin: 0px;">
<h1><?= $this->slogan ?></h1>
</div>
</div>
</div>
<div class="row" style="margin-bottom: 2em;">
<div class="col-xs-6 col-xs-offset-3">
<form action="/user/register_submit" method="post">
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="请您输入用户名">
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" placeholder="请您输入密码">
</div>
<button type="submit" class="col-xs-12 col-sm-12 btn btn-success">注册</button>
</form>
<br/> <br/> <br/>
<a href="/user/login" class="col-xs-4 col-sm-4 btn btn-link">登入</a>
<span class="col-xs-4 col-sm-4 "></span>
<a href="#" class="col-xs-4 col-sm-4 btn btn-link">忘记密码?</a>
</div>
</div>
</div> | tecshuttle/tiegan | application/views_dev/user/register.php | PHP | mit | 1,180 |
require 'ruboto/util/toast'
# Services are complicated and don't really make sense unless you
# show the interaction between the Service and other parts of your
# app.
# For now, just take a look at the explanation and example in
# online:
# http://developer.android.com/reference/android/app/Service.html
class SampleService
def onStartCommand(intent, flags, startId)
toast 'Hello from the service'
android.app.Service::START_NOT_STICKY
end
end
| lucasallan/ruboto | assets/samples/sample_service.rb | Ruby | mit | 459 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Measure
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @namespace
*/
namespace Zend\Measure;
/**
* Class for handling torque conversions
*
* @uses Zend\Measure\Abstract
* @category Zend
* @package Zend_Measure
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Torque extends AbstractMeasure
{
const STANDARD = 'NEWTON_METER';
const DYNE_CENTIMETER = 'DYNE_CENTIMETER';
const GRAM_CENTIMETER = 'GRAM_CENTIMETER';
const KILOGRAM_CENTIMETER = 'KILOGRAM_CENTIMETER';
const KILOGRAM_METER = 'KILOGRAM_METER';
const KILONEWTON_METER = 'KILONEWTON_METER';
const KILOPOND_METER = 'KILOPOND_METER';
const MEGANEWTON_METER = 'MEGANEWTON_METER';
const MICRONEWTON_METER = 'MICRONEWTON_METER';
const MILLINEWTON_METER = 'MILLINEWTON_METER';
const NEWTON_CENTIMETER = 'NEWTON_CENTIMETER';
const NEWTON_METER = 'NEWTON_METER';
const OUNCE_FOOT = 'OUNCE_FOOT';
const OUNCE_INCH = 'OUNCE_INCH';
const POUND_FOOT = 'POUND_FOOT';
const POUNDAL_FOOT = 'POUNDAL_FOOT';
const POUND_INCH = 'POUND_INCH';
/**
* Calculations for all torque units
*
* @var array
*/
protected $_units = array(
'DYNE_CENTIMETER' => array('0.0000001', 'dyncm'),
'GRAM_CENTIMETER' => array('0.0000980665', 'gcm'),
'KILOGRAM_CENTIMETER' => array('0.0980665', 'kgcm'),
'KILOGRAM_METER' => array('9.80665', 'kgm'),
'KILONEWTON_METER' => array('1000', 'kNm'),
'KILOPOND_METER' => array('9.80665', 'kpm'),
'MEGANEWTON_METER' => array('1000000', 'MNm'),
'MICRONEWTON_METER' => array('0.000001', 'µNm'),
'MILLINEWTON_METER' => array('0.001', 'mNm'),
'NEWTON_CENTIMETER' => array('0.01', 'Ncm'),
'NEWTON_METER' => array('1', 'Nm'),
'OUNCE_FOOT' => array('0.084738622', 'ozft'),
'OUNCE_INCH' => array(array('' => '0.084738622', '/' => '12'), 'ozin'),
'POUND_FOOT' => array(array('' => '0.084738622', '*' => '16'), 'lbft'),
'POUNDAL_FOOT' => array('0.0421401099752144', 'plft'),
'POUND_INCH' => array(array('' => '0.084738622', '/' => '12', '*' => '16'), 'lbin'),
'STANDARD' => 'NEWTON_METER'
);
}
| dynamicguy/gpweb | src/vendor/zend/library/Zend/Measure/Torque.php | PHP | mit | 3,276 |
const DOUBLE_QUOTE_STRING_STATE = 'double-quote-string-state';
const SINGLE_QUOTE_STRING_STATE = 'single-quote-string-state';
const LINE_COMMENT_STATE = 'line-comment-state';
const BLOCK_COMMENT_STATE = 'block-comment-state';
const ETC_STATE = 'etc-state';
function extractComments(str) {
let state = ETC_STATE;
let i = 0;
const comments = [];
let currentComment = null;
while (i + 1 < str.length) {
if (state === ETC_STATE && str[i] === '/' && str[i + 1] === '/') {
state = LINE_COMMENT_STATE;
currentComment = {
type: 'LineComment',
range: [i]
};
i += 2;
continue;
}
if (state === LINE_COMMENT_STATE && str[i] === '\n') {
state = ETC_STATE;
currentComment.range.push(i);
comments.push(currentComment);
currentComment = null;
i += 1;
continue;
}
if (state === ETC_STATE && str[i] === '/' && str[i + 1] === '*') {
state = BLOCK_COMMENT_STATE;
currentComment = {
type: 'BlockComment',
range: [i]
};
i += 2;
continue;
}
if (state === BLOCK_COMMENT_STATE && str[i] === '*' && str[i + 1] === '/') {
state = ETC_STATE;
currentComment.range.push(i + 2);
comments.push(currentComment);
currentComment = null;
i += 2;
continue;
}
if (state === ETC_STATE && str[i] === '"') {
state = DOUBLE_QUOTE_STRING_STATE;
i += 1;
continue;
}
if (
state === DOUBLE_QUOTE_STRING_STATE &&
str[i] === '"' &&
(str[i - 1] !== '\\' || str[i - 2] === '\\') // ignore previous backslash unless it's escaped
) {
state = ETC_STATE;
i += 1;
continue;
}
if (state === ETC_STATE && str[i] === "'") {
state = SINGLE_QUOTE_STRING_STATE;
i += 1;
continue;
}
if (
state === SINGLE_QUOTE_STRING_STATE &&
str[i] === "'" &&
(str[i - 1] !== '\\' || str[i - 2] === '\\') // ignore previous backslash unless it's escaped
) {
state = ETC_STATE;
i += 1;
continue;
}
i += 1;
}
if (currentComment !== null && currentComment.type === 'LineComment') {
if (str[i] === '\n') {
currentComment.range.push(str.length - 1);
} else {
currentComment.range.push(str.length);
}
comments.push(currentComment);
}
return comments.map((comment) => {
const start = comment.range[0] + 2;
const end =
comment.type === 'LineComment' ? comment.range[1] : comment.range[1] - 2;
const raw = str.slice(start, end);
// removing the leading asterisks from the value is necessary for jsdoc-style comments
let value = raw;
if (comment.type === 'BlockComment') {
value = value
.split('\n')
.map((x) => x.replace(/^\s*\*/, ''))
.join('\n')
.trimRight();
}
return {
...comment,
raw,
value
};
});
}
module.exports = extractComments;
| glenngillen/dotfiles | .vscode/extensions/juanblanco.solidity-0.0.120/node_modules/solidity-comments-extractor/index.js | JavaScript | mit | 2,960 |
/*
* The MIT License
*
* Copyright (c) 2015 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package picard.analysis;
import htsjdk.samtools.reference.ReferenceSequence;
import htsjdk.samtools.reference.ReferenceSequenceFile;
import htsjdk.samtools.reference.ReferenceSequenceFileFactory;
import htsjdk.samtools.util.SequenceUtil;
import htsjdk.samtools.util.StringUtil;
import java.io.File;
/** Utilities to calculate GC Bias
* Created by kbergin on 9/23/15.
*/
public class GcBiasUtils {
/////////////////////////////////////////////////////////////////////////////
// Calculates GC as a number from 0 to 100 in the specified window.
// If the window includes more than five no-calls then -1 is returned.
/////////////////////////////////////////////////////////////////////////////
public static int calculateGc(final byte[] bases, final int startIndex, final int endIndex, final CalculateGcState state) {
if (state.init) {
state.init = false;
state.gcCount = 0;
state.nCount = 0;
for (int i = startIndex; i < endIndex; ++i) {
final byte base = bases[i];
if (SequenceUtil.basesEqual(base, (byte)'G') || SequenceUtil.basesEqual(base, (byte)'C')) ++state.gcCount;
else if (SequenceUtil.basesEqual(base, (byte)'N')) ++state.nCount;
}
} else {
final byte newBase = bases[endIndex - 1];
if (SequenceUtil.basesEqual(newBase, (byte)'G') || SequenceUtil.basesEqual(newBase, (byte)'C')) ++state.gcCount;
else if (newBase == 'N') ++state.nCount;
if (SequenceUtil.basesEqual(state.priorBase, (byte)'G') || SequenceUtil.basesEqual(state.priorBase, (byte)'C')) --state.gcCount;
else if (SequenceUtil.basesEqual(state.priorBase, (byte)'N')) --state.nCount;
}
state.priorBase = bases[startIndex];
if (state.nCount > 4) return -1;
else return (state.gcCount * 100) / (endIndex - startIndex);
}
/////////////////////////////////////////////////////////////////////////////
// Calculate number of 100bp windows in the refBases passed in that fall into
// each gc content bin (0-100% gc)
/////////////////////////////////////////////////////////////////////////////
public static int[] calculateRefWindowsByGc(final int windows, final File referenceSequence, final int windowSize) {
final ReferenceSequenceFile refFile = ReferenceSequenceFileFactory.getReferenceSequenceFile(referenceSequence);
ReferenceSequence ref;
final int [] windowsByGc = new int [windows];
while ((ref = refFile.nextSequence()) != null) {
final byte[] refBases = ref.getBases();
StringUtil.toUpperCase(refBases);
final int refLength = refBases.length;
final int lastWindowStart = refLength - windowSize;
final CalculateGcState state = new GcBiasUtils().new CalculateGcState();
for (int i = 1; i < lastWindowStart; ++i) {
final int windowEnd = i + windowSize;
final int gcBin = calculateGc(refBases, i, windowEnd, state);
if (gcBin != -1) windowsByGc[gcBin]++;
}
}
return windowsByGc;
}
/////////////////////////////////////////////////////////////////////////////
// Calculate all the GC values for all windows
/////////////////////////////////////////////////////////////////////////////
public static byte [] calculateAllGcs(final byte[] refBases, final int lastWindowStart, final int windowSize) {
final CalculateGcState state = new GcBiasUtils().new CalculateGcState();
final int refLength = refBases.length;
final byte[] gc = new byte[refLength + 1];
for (int i = 1; i < lastWindowStart; ++i) {
final int windowEnd = i + windowSize;
final int windowGc = calculateGc(refBases, i, windowEnd, state);
gc[i] = (byte) windowGc;
}
return gc;
}
/////////////////////////////////////////////////////////////////////////////
// Keeps track of current GC calculation state
/////////////////////////////////////////////////////////////////////////////
class CalculateGcState {
boolean init = true;
int nCount;
int gcCount;
byte priorBase;
}
}
| annkupi/picard | src/main/java/picard/analysis/GcBiasUtils.java | Java | mit | 5,467 |
var util = require('util');
/**
* @class Recorder
* @param {{retention: <Number>}} [options]
*/
var Recorder = function(options) {
this._records = [];
this._options = _.defaults(options || {}, {
retention: 300, // seconds
recordMaxSize: 200, // nb records
jsonMaxSize: 50,
format: '[{date} {level}] {message}'
});
};
Recorder.prototype = {
/**
* @returns {String}
*/
getFormattedRecords: function() {
return _.map(this.getRecords(), function(record) {
return this._recordFormatter(record);
}, this).join('\n');
},
/**
* @returns {{date: {Date}, messages: *[], context: {Object}}[]}
*/
getRecords: function() {
return this._records;
},
/**
* @param {*[]} messages
* @param {Object} context
*/
addRecord: function(messages, context) {
var record = {
date: this._getDate(),
messages: messages,
context: context
};
this._records.push(record);
this._cleanupRecords();
},
flushRecords: function() {
this._records = [];
},
/**
* @private
*/
_cleanupRecords: function() {
var retention = this._options.retention;
var recordMaxSize = this._options.recordMaxSize;
if (retention > 0) {
var retentionTime = this._getDate() - (retention * 1000);
this._records = _.filter(this._records, function(record) {
return record.date > retentionTime;
});
}
if (recordMaxSize > 0 && this._records.length > recordMaxSize) {
this._records = this._records.slice(-recordMaxSize);
}
},
/**
* @param {{date: {Date}, messages: *[], context: {Object}}} record
* @returns {String}
* @private
*/
_recordFormatter: function(record) {
var log = this._options.format;
_.each({
date: record.date.toISOString(),
level: record.context.level.name,
message: this._messageFormatter(record.messages)
}, function(value, key) {
var pattern = new RegExp('{' + key + '}', 'g');
log = log.replace(pattern, value);
});
return log;
},
/**
* @param {*[]} messages
* @returns {String}
* @private
*/
_messageFormatter: function(messages) {
var clone = _.toArray(messages);
var index, value, encoded;
for (index = 0; index < clone.length; index++) {
encoded = value = clone[index];
if (_.isString(value) && 0 === index) {
// about console.log and util.format substitution,
// see https://developers.google.com/web/tools/chrome-devtools/debug/console/console-write#string-substitution-and-formatting
// and https://nodejs.org/api/util.html#util_util_format_format
value = value.replace(/%[idfoO]/g, '%s');
} else if (value instanceof RegExp) {
value = value.toString();
} else if (value instanceof Date) {
value = value.toISOString();
} else if (_.isObject(value) && value._class) {
value = '[' + value._class + (value._id && value._id.id ? ':' + value._id.id : '') + ']';
} else if (_.isObject(value) && /^\[object ((?!Object).)+\]$/.test(value.toString())) {
value = value.toString();
}
try {
if (_.isString(value) || _.isNumber(value)) {
encoded = value;
} else {
encoded = JSON.stringify(value);
if (encoded.length > this._options.jsonMaxSize) {
encoded = encoded.slice(0, this._options.jsonMaxSize - 4) + '…' + encoded[encoded.length - 1];
}
}
} catch (e) {
if (_.isUndefined(value)) {
encoded = 'undefined';
} else if (_.isNull(value)) {
encoded = 'null';
} else {
encoded = '[unknown]'
}
}
clone[index] = encoded;
}
return util.format.apply(util.format, clone);
},
/**
* @returns {Date}
* @private
*/
_getDate: function() {
return new Date();
}
};
module.exports = Recorder;
| njam/CM | client-vendor/source/logger/handlers/recorder.js | JavaScript | mit | 3,930 |
using ElectronicObserver.Utility.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicObserver.Data.ShipGroup
{
[DataContract(Name = "ExpressionManager")]
public sealed class ExpressionManager : DataStorage, ICloneable
{
[DataMember]
public List<ExpressionList> Expressions { get; set; }
[IgnoreDataMember]
private Expression<Func<ShipData, bool>> predicate;
[IgnoreDataMember]
private Expression expression;
public ExpressionManager() : base()
{
Initialize();
}
public override void Initialize()
{
Expressions = new List<ExpressionList>();
predicate = null;
expression = null;
}
public ExpressionList this[int index]
{
get { return Expressions[index]; }
set { Expressions[index] = value; }
}
public void Compile()
{
Expression ex = null;
var paramex = Expression.Parameter(typeof(ShipData), "ship");
foreach (var exlist in Expressions)
{
if (!exlist.Enabled)
continue;
if (ex == null)
{
ex = exlist.Compile(paramex);
}
else
{
if (exlist.ExternalAnd)
{
ex = Expression.AndAlso(ex, exlist.Compile(paramex));
}
else
{
ex = Expression.OrElse(ex, exlist.Compile(paramex));
}
}
}
if (ex == null)
{
ex = Expression.Constant(true, typeof(bool)); //:-P
}
predicate = Expression.Lambda<Func<ShipData, bool>>(ex, paramex);
expression = ex;
}
public IEnumerable<ShipData> GetResult(IEnumerable<ShipData> list)
{
if (predicate == null)
throw new InvalidOperationException("式がコンパイルされていません。");
return list.AsQueryable().Where(predicate).AsEnumerable();
}
public bool IsAvailable => predicate != null;
public override string ToString()
{
if (Expressions == null)
return "(なし)";
StringBuilder sb = new StringBuilder();
foreach (var ex in Expressions)
{
if (!ex.Enabled)
continue;
else if (sb.Length == 0)
sb.Append(ex.ToString());
else
sb.AppendFormat(" {0} {1}", ex.ExternalAnd ? "かつ" : "または", ex.ToString());
}
if (sb.Length == 0)
sb.Append("(なし)");
return sb.ToString();
}
public string ToExpressionString()
{
return expression.ToString();
}
public ExpressionManager Clone()
{
var clone = (ExpressionManager)MemberwiseClone();
clone.Expressions = Expressions?.Select(e => e.Clone()).ToList();
clone.predicate = null;
clone.expression = null;
return clone;
}
object ICloneable.Clone()
{
return Clone();
}
}
}
| CAWAS/ElectronicObserverExtended | ElectronicObserver/Data/ShipGroup/ExpressionManager.cs | C# | mit | 2,741 |
import pprint
import test.test_support
import unittest
import test.test_set
try:
uni = unicode
except NameError:
def uni(x):
return x
# list, tuple and dict subclasses that do or don't overwrite __repr__
class list2(list):
pass
class list3(list):
def __repr__(self):
return list.__repr__(self)
class tuple2(tuple):
pass
class tuple3(tuple):
def __repr__(self):
return tuple.__repr__(self)
class dict2(dict):
pass
class dict3(dict):
def __repr__(self):
return dict.__repr__(self)
class QueryTestCase(unittest.TestCase):
def setUp(self):
self.a = range(100)
self.b = range(200)
self.a[-12] = self.b
def test_basic(self):
# Verify .isrecursive() and .isreadable() w/o recursion
pp = pprint.PrettyPrinter()
for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, uni("yaddayadda"),
self.a, self.b):
# module-level convenience functions
self.assertFalse(pprint.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pprint.isreadable(safe),
"expected isreadable for %r" % (safe,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pp.isreadable(safe),
"expected isreadable for %r" % (safe,))
def test_knotted(self):
# Verify .isrecursive() and .isreadable() w/ recursion
# Tie a knot.
self.b[67] = self.a
# Messy dict.
self.d = {}
self.d[0] = self.d[1] = self.d[2] = self.d
pp = pprint.PrettyPrinter()
for icky in self.a, self.b, self.d, (self.d, self.d):
self.assertTrue(pprint.isrecursive(icky), "expected isrecursive")
self.assertFalse(pprint.isreadable(icky), "expected not isreadable")
self.assertTrue(pp.isrecursive(icky), "expected isrecursive")
self.assertFalse(pp.isreadable(icky), "expected not isreadable")
# Break the cycles.
self.d.clear()
del self.a[:]
del self.b[:]
for safe in self.a, self.b, self.d, (self.d, self.d):
# module-level convenience functions
self.assertFalse(pprint.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pprint.isreadable(safe),
"expected isreadable for %r" % (safe,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pp.isreadable(safe),
"expected isreadable for %r" % (safe,))
def test_unreadable(self):
# Not recursive but not readable anyway
pp = pprint.PrettyPrinter()
for unreadable in type(3), pprint, pprint.isrecursive:
# module-level convenience functions
self.assertFalse(pprint.isrecursive(unreadable),
"expected not isrecursive for %r" % (unreadable,))
self.assertFalse(pprint.isreadable(unreadable),
"expected not isreadable for %r" % (unreadable,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(unreadable),
"expected not isrecursive for %r" % (unreadable,))
self.assertFalse(pp.isreadable(unreadable),
"expected not isreadable for %r" % (unreadable,))
def test_same_as_repr(self):
# Simple objects, small containers and classes that overwrite __repr__
# For those the result should be the same as repr().
# Ahem. The docs don't say anything about that -- this appears to
# be testing an implementation quirk. Starting in Python 2.5, it's
# not true for dicts: pprint always sorts dicts by key now; before,
# it sorted a dict display if and only if the display required
# multiple lines. For that reason, dicts with more than one element
# aren't tested here.
for simple in (0, 0L, 0+0j, 0.0, "", uni(""),
(), tuple2(), tuple3(),
[], list2(), list3(),
{}, dict2(), dict3(),
self.assertTrue, pprint,
-6, -6L, -6-6j, -1.5, "x", uni("x"), (3,), [3], {3: 6},
(1,2), [3,4], {5: 6},
tuple2((1,2)), tuple3((1,2)), tuple3(range(100)),
[3,4], list2([3,4]), list3([3,4]), list3(range(100)),
dict2({5: 6}), dict3({5: 6}),
range(10, -11, -1)
):
native = repr(simple)
for function in "pformat", "saferepr":
f = getattr(pprint, function)
got = f(simple)
self.assertEqual(native, got,
"expected %s got %s from pprint.%s" %
(native, got, function))
def test_basic_line_wrap(self):
# verify basic line-wrapping operation
o = {'RPM_cal': 0,
'RPM_cal2': 48059,
'Speed_cal': 0,
'controldesk_runtime_us': 0,
'main_code_runtime_us': 0,
'read_io_runtime_us': 0,
'write_io_runtime_us': 43690}
exp = """\
{'RPM_cal': 0,
'RPM_cal2': 48059,
'Speed_cal': 0,
'controldesk_runtime_us': 0,
'main_code_runtime_us': 0,
'read_io_runtime_us': 0,
'write_io_runtime_us': 43690}"""
for type in [dict, dict2]:
self.assertEqual(pprint.pformat(type(o)), exp)
o = range(100)
exp = '[%s]' % ',\n '.join(map(str, o))
for type in [list, list2]:
self.assertEqual(pprint.pformat(type(o)), exp)
o = tuple(range(100))
exp = '(%s)' % ',\n '.join(map(str, o))
for type in [tuple, tuple2]:
self.assertEqual(pprint.pformat(type(o)), exp)
# indent parameter
o = range(100)
exp = '[ %s]' % ',\n '.join(map(str, o))
for type in [list, list2]:
self.assertEqual(pprint.pformat(type(o), indent=4), exp)
def test_nested_indentations(self):
o1 = list(range(10))
o2 = dict(first=1, second=2, third=3)
o = [o1, o2]
expected = """\
[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
{ 'first': 1,
'second': 2,
'third': 3}]"""
self.assertEqual(pprint.pformat(o, indent=4, width=42), expected)
def test_sorted_dict(self):
# Starting in Python 2.5, pprint sorts dict displays by key regardless
# of how small the dictionary may be.
# Before the change, on 32-bit Windows pformat() gave order
# 'a', 'c', 'b' here, so this test failed.
d = {'a': 1, 'b': 1, 'c': 1}
self.assertEqual(pprint.pformat(d), "{'a': 1, 'b': 1, 'c': 1}")
self.assertEqual(pprint.pformat([d, d]),
"[{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 1}]")
# The next one is kind of goofy. The sorted order depends on the
# alphabetic order of type names: "int" < "str" < "tuple". Before
# Python 2.5, this was in the test_same_as_repr() test. It's worth
# keeping around for now because it's one of few tests of pprint
# against a crazy mix of types.
self.assertEqual(pprint.pformat({"xy\tab\n": (3,), 5: [[]], (): {}}),
r"{5: [[]], 'xy\tab\n': (3,), (): {}}")
def test_subclassing(self):
o = {'names with spaces': 'should be presented using repr()',
'others.should.not.be': 'like.this'}
exp = """\
{'names with spaces': 'should be presented using repr()',
others.should.not.be: like.this}"""
self.assertEqual(DottedPrettyPrinter().pformat(o), exp)
def test_set_reprs(self):
self.assertEqual(pprint.pformat(set()), 'set()')
self.assertEqual(pprint.pformat(set(range(3))), 'set([0, 1, 2])')
self.assertEqual(pprint.pformat(frozenset()), 'frozenset()')
self.assertEqual(pprint.pformat(frozenset(range(3))), 'frozenset([0, 1, 2])')
cube_repr_tgt = """\
{frozenset([]): frozenset([frozenset([2]), frozenset([0]), frozenset([1])]),
frozenset([0]): frozenset([frozenset(),
frozenset([0, 2]),
frozenset([0, 1])]),
frozenset([1]): frozenset([frozenset(),
frozenset([1, 2]),
frozenset([0, 1])]),
frozenset([2]): frozenset([frozenset(),
frozenset([1, 2]),
frozenset([0, 2])]),
frozenset([1, 2]): frozenset([frozenset([2]),
frozenset([1]),
frozenset([0, 1, 2])]),
frozenset([0, 2]): frozenset([frozenset([2]),
frozenset([0]),
frozenset([0, 1, 2])]),
frozenset([0, 1]): frozenset([frozenset([0]),
frozenset([1]),
frozenset([0, 1, 2])]),
frozenset([0, 1, 2]): frozenset([frozenset([1, 2]),
frozenset([0, 2]),
frozenset([0, 1])])}"""
cube = test.test_set.cube(3)
# XXX issues of dictionary order, and for the case below,
# order of items in the frozenset([...]) representation.
# Whether we get precisely cube_repr_tgt or not is open
# to implementation-dependent choices (this test probably
# fails horribly in CPython if we tweak the dict order too).
got = pprint.pformat(cube)
if test.test_support.check_impl_detail(cpython=True):
self.assertEqual(got, cube_repr_tgt)
else:
self.assertEqual(eval(got), cube)
cubo_repr_tgt = """\
{frozenset([frozenset([0, 2]), frozenset([0])]): frozenset([frozenset([frozenset([0,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
1])]),
frozenset([frozenset(),
frozenset([0])]),
frozenset([frozenset([2]),
frozenset([0,
2])])]),
frozenset([frozenset([0, 1]), frozenset([1])]): frozenset([frozenset([frozenset([0,
1]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
1])]),
frozenset([frozenset([1]),
frozenset([1,
2])]),
frozenset([frozenset(),
frozenset([1])])]),
frozenset([frozenset([1, 2]), frozenset([1])]): frozenset([frozenset([frozenset([1,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([2]),
frozenset([1,
2])]),
frozenset([frozenset(),
frozenset([1])]),
frozenset([frozenset([1]),
frozenset([0,
1])])]),
frozenset([frozenset([1, 2]), frozenset([2])]): frozenset([frozenset([frozenset([1,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([1]),
frozenset([1,
2])]),
frozenset([frozenset([2]),
frozenset([0,
2])]),
frozenset([frozenset(),
frozenset([2])])]),
frozenset([frozenset([]), frozenset([0])]): frozenset([frozenset([frozenset([0]),
frozenset([0,
1])]),
frozenset([frozenset([0]),
frozenset([0,
2])]),
frozenset([frozenset(),
frozenset([1])]),
frozenset([frozenset(),
frozenset([2])])]),
frozenset([frozenset([]), frozenset([1])]): frozenset([frozenset([frozenset(),
frozenset([0])]),
frozenset([frozenset([1]),
frozenset([1,
2])]),
frozenset([frozenset(),
frozenset([2])]),
frozenset([frozenset([1]),
frozenset([0,
1])])]),
frozenset([frozenset([2]), frozenset([])]): frozenset([frozenset([frozenset([2]),
frozenset([1,
2])]),
frozenset([frozenset(),
frozenset([0])]),
frozenset([frozenset(),
frozenset([1])]),
frozenset([frozenset([2]),
frozenset([0,
2])])]),
frozenset([frozenset([0, 1, 2]), frozenset([0, 1])]): frozenset([frozenset([frozenset([1,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
1])]),
frozenset([frozenset([1]),
frozenset([0,
1])])]),
frozenset([frozenset([0]), frozenset([0, 1])]): frozenset([frozenset([frozenset(),
frozenset([0])]),
frozenset([frozenset([0,
1]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
2])]),
frozenset([frozenset([1]),
frozenset([0,
1])])]),
frozenset([frozenset([2]), frozenset([0, 2])]): frozenset([frozenset([frozenset([0,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([2]),
frozenset([1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
2])]),
frozenset([frozenset(),
frozenset([2])])]),
frozenset([frozenset([0, 1, 2]), frozenset([0, 2])]): frozenset([frozenset([frozenset([1,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0,
1]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
2])]),
frozenset([frozenset([2]),
frozenset([0,
2])])]),
frozenset([frozenset([1, 2]), frozenset([0, 1, 2])]): frozenset([frozenset([frozenset([0,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0,
1]),
frozenset([0,
1,
2])]),
frozenset([frozenset([2]),
frozenset([1,
2])]),
frozenset([frozenset([1]),
frozenset([1,
2])])])}"""
cubo = test.test_set.linegraph(cube)
got = pprint.pformat(cubo)
if test.test_support.check_impl_detail(cpython=True):
self.assertEqual(got, cubo_repr_tgt)
else:
self.assertEqual(eval(got), cubo)
def test_depth(self):
nested_tuple = (1, (2, (3, (4, (5, 6)))))
nested_dict = {1: {2: {3: {4: {5: {6: 6}}}}}}
nested_list = [1, [2, [3, [4, [5, [6, []]]]]]]
self.assertEqual(pprint.pformat(nested_tuple), repr(nested_tuple))
self.assertEqual(pprint.pformat(nested_dict), repr(nested_dict))
self.assertEqual(pprint.pformat(nested_list), repr(nested_list))
lv1_tuple = '(1, (...))'
lv1_dict = '{1: {...}}'
lv1_list = '[1, [...]]'
self.assertEqual(pprint.pformat(nested_tuple, depth=1), lv1_tuple)
self.assertEqual(pprint.pformat(nested_dict, depth=1), lv1_dict)
self.assertEqual(pprint.pformat(nested_list, depth=1), lv1_list)
class DottedPrettyPrinter(pprint.PrettyPrinter):
def format(self, object, context, maxlevels, level):
if isinstance(object, str):
if ' ' in object:
return repr(object), 1, 0
else:
return object, 0, 0
else:
return pprint.PrettyPrinter.format(
self, object, context, maxlevels, level)
def test_main():
test.test_support.run_unittest(QueryTestCase)
if __name__ == "__main__":
test_main()
| bussiere/pypyjs | website/demo/home/rfk/repos/pypy/lib-python/2.7/test/test_pprint.py | Python | mit | 25,311 |
# frozen_string_literal: true
require "active_support/core_ext/hash/indifferent_access"
require "active_support/core_ext/string/filters"
require "concurrent/map"
require "set"
module ActiveRecord
module Core
extend ActiveSupport::Concern
FILTERED = "[FILTERED]" # :nodoc:
included do
##
# :singleton-method:
#
# Accepts a logger conforming to the interface of Log4r which is then
# passed on to any new database connections made and which can be
# retrieved on both a class and instance level by calling +logger+.
mattr_accessor :logger, instance_writer: false
##
# :singleton-method:
#
# Specifies if the methods calling database queries should be logged below
# their relevant queries. Defaults to false.
mattr_accessor :verbose_query_logs, instance_writer: false, default: false
##
# Contains the database configuration - as is typically stored in config/database.yml -
# as an ActiveRecord::DatabaseConfigurations object.
#
# For example, the following database.yml...
#
# development:
# adapter: sqlite3
# database: db/development.sqlite3
#
# production:
# adapter: sqlite3
# database: db/production.sqlite3
#
# ...would result in ActiveRecord::Base.configurations to look like this:
#
# #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[
# #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",
# @spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>,
# #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="production",
# @spec_name="primary", @config={"adapter"=>"mysql2", "database"=>"db/production.sqlite3"}>
# ]>
def self.configurations=(config)
@@configurations = ActiveRecord::DatabaseConfigurations.new(config)
end
self.configurations = {}
# Returns fully resolved ActiveRecord::DatabaseConfigurations object
def self.configurations
@@configurations
end
##
# :singleton-method:
# Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling
# dates and times from the database. This is set to :utc by default.
mattr_accessor :default_timezone, instance_writer: false, default: :utc
##
# :singleton-method:
# Specifies the format to use when dumping the database schema with Rails'
# Rakefile. If :sql, the schema is dumped as (potentially database-
# specific) SQL statements. If :ruby, the schema is dumped as an
# ActiveRecord::Schema file which can be loaded into any database that
# supports migrations. Use :ruby if you want to have different database
# adapters for, e.g., your development and test environments.
mattr_accessor :schema_format, instance_writer: false, default: :ruby
##
# :singleton-method:
# Specifies if an error should be raised if the query has an order being
# ignored when doing batch queries. Useful in applications where the
# scope being ignored is error-worthy, rather than a warning.
mattr_accessor :error_on_ignored_order, instance_writer: false, default: false
# :singleton-method:
# Specify the behavior for unsafe raw query methods. Values are as follows
# deprecated - Warnings are logged when unsafe raw SQL is passed to
# query methods.
# disabled - Unsafe raw SQL passed to query methods results in
# UnknownAttributeReference exception.
mattr_accessor :allow_unsafe_raw_sql, instance_writer: false, default: :deprecated
##
# :singleton-method:
# Specify whether or not to use timestamps for migration versions
mattr_accessor :timestamped_migrations, instance_writer: false, default: true
##
# :singleton-method:
# Specify whether schema dump should happen at the end of the
# db:migrate rails command. This is true by default, which is useful for the
# development environment. This should ideally be false in the production
# environment where dumping schema is rarely needed.
mattr_accessor :dump_schema_after_migration, instance_writer: false, default: true
##
# :singleton-method:
# Specifies which database schemas to dump when calling db:structure:dump.
# If the value is :schema_search_path (the default), any schemas listed in
# schema_search_path are dumped. Use :all to dump all schemas regardless
# of schema_search_path, or a string of comma separated schemas for a
# custom list.
mattr_accessor :dump_schemas, instance_writer: false, default: :schema_search_path
##
# :singleton-method:
# Specify a threshold for the size of query result sets. If the number of
# records in the set exceeds the threshold, a warning is logged. This can
# be used to identify queries which load thousands of records and
# potentially cause memory bloat.
mattr_accessor :warn_on_records_fetched_greater_than, instance_writer: false
mattr_accessor :maintain_test_schema, instance_accessor: false
mattr_accessor :belongs_to_required_by_default, instance_accessor: false
class_attribute :default_connection_handler, instance_writer: false
self.filter_attributes = []
def self.connection_handler
ActiveRecord::RuntimeRegistry.connection_handler || default_connection_handler
end
def self.connection_handler=(handler)
ActiveRecord::RuntimeRegistry.connection_handler = handler
end
self.default_connection_handler = ConnectionAdapters::ConnectionHandler.new
end
module ClassMethods
def initialize_find_by_cache # :nodoc:
@find_by_statement_cache = { true => Concurrent::Map.new, false => Concurrent::Map.new }
end
def inherited(child_class) # :nodoc:
# initialize cache at class definition for thread safety
child_class.initialize_find_by_cache
super
end
def find(*ids) # :nodoc:
# We don't have cache keys for this stuff yet
return super unless ids.length == 1
return super if block_given? ||
primary_key.nil? ||
scope_attributes? ||
columns_hash.include?(inheritance_column)
id = ids.first
return super if StatementCache.unsupported_value?(id)
key = primary_key
statement = cached_find_by_statement(key) { |params|
where(key => params.bind).limit(1)
}
record = statement.execute([id], connection).first
unless record
raise RecordNotFound.new("Couldn't find #{name} with '#{primary_key}'=#{id}",
name, primary_key, id)
end
record
rescue ::RangeError
raise RecordNotFound.new("Couldn't find #{name} with an out of range value for '#{primary_key}'",
name, primary_key)
end
def find_by(*args) # :nodoc:
return super if scope_attributes? || reflect_on_all_aggregations.any?
hash = args.first
return super if !(Hash === hash) || hash.values.any? { |v|
StatementCache.unsupported_value?(v)
}
# We can't cache Post.find_by(author: david) ...yet
return super unless hash.keys.all? { |k| columns_hash.has_key?(k.to_s) }
keys = hash.keys
statement = cached_find_by_statement(keys) { |params|
wheres = keys.each_with_object({}) { |param, o|
o[param] = params.bind
}
where(wheres).limit(1)
}
begin
statement.execute(hash.values, connection).first
rescue TypeError
raise ActiveRecord::StatementInvalid
rescue ::RangeError
nil
end
end
def find_by!(*args) # :nodoc:
find_by(*args) || raise(RecordNotFound.new("Couldn't find #{name}", name))
end
def initialize_generated_modules # :nodoc:
generated_association_methods
end
def generated_association_methods # :nodoc:
@generated_association_methods ||= begin
mod = const_set(:GeneratedAssociationMethods, Module.new)
private_constant :GeneratedAssociationMethods
include mod
mod
end
end
# Returns columns which shouldn't be exposed while calling +#inspect+.
def filter_attributes
if defined?(@filter_attributes)
@filter_attributes
else
superclass.filter_attributes
end
end
# Specifies columns which shouldn't be exposed while calling +#inspect+.
def filter_attributes=(attributes_names)
@filter_attributes = attributes_names.map(&:to_s).to_set
end
# Returns a string like 'Post(id:integer, title:string, body:text)'
def inspect # :nodoc:
if self == Base
super
elsif abstract_class?
"#{super}(abstract)"
elsif !connected?
"#{super} (call '#{super}.connection' to establish a connection)"
elsif table_exists?
attr_list = attribute_types.map { |name, type| "#{name}: #{type.type}" } * ", "
"#{super}(#{attr_list})"
else
"#{super}(Table doesn't exist)"
end
end
# Overwrite the default class equality method to provide support for decorated models.
def ===(object) # :nodoc:
object.is_a?(self)
end
# Returns an instance of <tt>Arel::Table</tt> loaded with the current table name.
#
# class Post < ActiveRecord::Base
# scope :published_and_commented, -> { published.and(arel_table[:comments_count].gt(0)) }
# end
def arel_table # :nodoc:
@arel_table ||= Arel::Table.new(table_name, type_caster: type_caster)
end
def arel_attribute(name, table = arel_table) # :nodoc:
name = attribute_alias(name) if attribute_alias?(name)
table[name]
end
def predicate_builder # :nodoc:
@predicate_builder ||= PredicateBuilder.new(table_metadata)
end
def type_caster # :nodoc:
TypeCaster::Map.new(self)
end
private
def cached_find_by_statement(key, &block)
cache = @find_by_statement_cache[connection.prepared_statements]
cache.compute_if_absent(key) { StatementCache.create(connection, &block) }
end
def relation
relation = Relation.create(self)
if finder_needs_type_condition? && !ignore_default_scope?
relation.where!(type_condition)
relation.create_with!(inheritance_column.to_s => sti_name)
else
relation
end
end
def table_metadata
TableMetadata.new(self, arel_table)
end
end
# New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
# attributes but not yet saved (pass a hash with key names matching the associated table column names).
# In both instances, valid attribute keys are determined by the column names of the associated table --
# hence you can't have attributes that aren't part of the table columns.
#
# ==== Example:
# # Instantiates a single new object
# User.new(first_name: 'Jamie')
def initialize(attributes = nil)
self.class.define_attribute_methods
@attributes = self.class._default_attributes.deep_dup
init_internals
initialize_internals_callback
assign_attributes(attributes) if attributes
yield self if block_given?
_run_initialize_callbacks
end
# Initialize an empty model object from +coder+. +coder+ should be
# the result of previously encoding an Active Record model, using
# #encode_with.
#
# class Post < ActiveRecord::Base
# end
#
# old_post = Post.new(title: "hello world")
# coder = {}
# old_post.encode_with(coder)
#
# post = Post.allocate
# post.init_with(coder)
# post.title # => 'hello world'
def init_with(coder)
coder = LegacyYamlAdapter.convert(self.class, coder)
@attributes = self.class.yaml_encoder.decode(coder)
init_internals
@new_record = coder["new_record"]
self.class.define_attribute_methods
yield self if block_given?
_run_find_callbacks
_run_initialize_callbacks
self
end
##
# Initializer used for instantiating objects that have been read from the
# database. +attributes+ should be an attributes object, and unlike the
# `initialize` method, no assignment calls are made per attribute.
#
# :nodoc:
def init_from_db(attributes)
init_internals
@new_record = false
@attributes = attributes
self.class.define_attribute_methods
yield self if block_given?
_run_find_callbacks
_run_initialize_callbacks
self
end
##
# :method: clone
# Identical to Ruby's clone method. This is a "shallow" copy. Be warned that your attributes are not copied.
# That means that modifying attributes of the clone will modify the original, since they will both point to the
# same attributes hash. If you need a copy of your attributes hash, please use the #dup method.
#
# user = User.first
# new_user = user.clone
# user.name # => "Bob"
# new_user.name = "Joe"
# user.name # => "Joe"
#
# user.object_id == new_user.object_id # => false
# user.name.object_id == new_user.name.object_id # => true
#
# user.name.object_id == user.dup.name.object_id # => false
##
# :method: dup
# Duped objects have no id assigned and are treated as new records. Note
# that this is a "shallow" copy as it copies the object's attributes
# only, not its associations. The extent of a "deep" copy is application
# specific and is therefore left to the application to implement according
# to its need.
# The dup method does not preserve the timestamps (created|updated)_(at|on).
##
def initialize_dup(other) # :nodoc:
@attributes = @attributes.deep_dup
@attributes.reset(self.class.primary_key)
_run_initialize_callbacks
@new_record = true
@destroyed = false
@_start_transaction_state = {}
@transaction_state = nil
super
end
# Populate +coder+ with attributes about this record that should be
# serialized. The structure of +coder+ defined in this method is
# guaranteed to match the structure of +coder+ passed to the #init_with
# method.
#
# Example:
#
# class Post < ActiveRecord::Base
# end
# coder = {}
# Post.new.encode_with(coder)
# coder # => {"attributes" => {"id" => nil, ... }}
def encode_with(coder)
self.class.yaml_encoder.encode(@attributes, coder)
coder["new_record"] = new_record?
coder["active_record_yaml_version"] = 2
end
# Returns true if +comparison_object+ is the same exact object, or +comparison_object+
# is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
#
# Note that new records are different from any other record by definition, unless the
# other record is the receiver itself. Besides, if you fetch existing records with
# +select+ and leave the ID out, you're on your own, this predicate will return false.
#
# Note also that destroying a record preserves its ID in the model instance, so deleted
# models are still comparable.
def ==(comparison_object)
super ||
comparison_object.instance_of?(self.class) &&
!id.nil? &&
comparison_object.id == id
end
alias :eql? :==
# Delegates to id in order to allow two records of the same type and id to work with something like:
# [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
def hash
if id
self.class.hash ^ id.hash
else
super
end
end
# Clone and freeze the attributes hash such that associations are still
# accessible, even on destroyed records, but cloned models will not be
# frozen.
def freeze
@attributes = @attributes.clone.freeze
self
end
# Returns +true+ if the attributes hash has been frozen.
def frozen?
@attributes.frozen?
end
# Allows sort on objects
def <=>(other_object)
if other_object.is_a?(self.class)
to_key <=> other_object.to_key
else
super
end
end
# Returns +true+ if the record is read only. Records loaded through joins with piggy-back
# attributes will be marked as read only since they cannot be saved.
def readonly?
@readonly
end
# Marks this record as read only.
def readonly!
@readonly = true
end
def connection_handler
self.class.connection_handler
end
# Returns the contents of the record as a nicely formatted string.
def inspect
# We check defined?(@attributes) not to issue warnings if the object is
# allocated but not initialized.
inspection = if defined?(@attributes) && @attributes
self.class.attribute_names.collect do |name|
if has_attribute?(name)
if filter_attribute?(name)
"#{name}: #{ActiveRecord::Core::FILTERED}"
else
"#{name}: #{attribute_for_inspect(name)}"
end
end
end.compact.join(", ")
else
"not initialized"
end
"#<#{self.class} #{inspection}>"
end
# Takes a PP and prettily prints this record to it, allowing you to get a nice result from <tt>pp record</tt>
# when pp is required.
def pretty_print(pp)
return super if custom_inspect_method_defined?
pp.object_address_group(self) do
if defined?(@attributes) && @attributes
column_names = self.class.column_names.select { |name| has_attribute?(name) || new_record? }
pp.seplist(column_names, proc { pp.text "," }) do |column_name|
pp.breakable " "
pp.group(1) do
pp.text column_name
pp.text ":"
pp.breakable
if filter_attribute?(column_name)
pp.text ActiveRecord::Core::FILTERED
else
pp.pp read_attribute(column_name)
end
end
end
else
pp.breakable " "
pp.text "not initialized"
end
end
end
# Returns a hash of the given methods with their names as keys and returned values as values.
def slice(*methods)
Hash[methods.flatten.map! { |method| [method, public_send(method)] }].with_indifferent_access
end
private
# +Array#flatten+ will call +#to_ary+ (recursively) on each of the elements of
# the array, and then rescues from the possible +NoMethodError+. If those elements are
# +ActiveRecord::Base+'s, then this triggers the various +method_missing+'s that we have,
# which significantly impacts upon performance.
#
# So we can avoid the +method_missing+ hit by explicitly defining +#to_ary+ as +nil+ here.
#
# See also https://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html
def to_ary
nil
end
def init_internals
@readonly = false
@destroyed = false
@marked_for_destruction = false
@destroyed_by_association = nil
@new_record = true
@_start_transaction_state = {}
@transaction_state = nil
end
def initialize_internals_callback
end
def thaw
if frozen?
@attributes = @attributes.dup
end
end
def custom_inspect_method_defined?
self.class.instance_method(:inspect).owner != ActiveRecord::Base.instance_method(:inspect).owner
end
def filter_attribute?(attribute_name)
self.class.filter_attributes.include?(attribute_name) && !read_attribute(attribute_name).nil?
end
end
end
| baerjam/rails | activerecord/lib/active_record/core.rb | Ruby | mit | 20,695 |
ReactDOM.render(React.createElement(
'div',
null,
React.createElement(Content, null)
), document.getElementById('content')); | azat-co/react-quickly | spare-parts/ch05-es5/logger/js/script.js | JavaScript | mit | 130 |
// Copyright 2019 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <boost/mp11/version.hpp>
#include <boost/version.hpp>
#include <boost/core/lightweight_test.hpp>
int main()
{
BOOST_TEST_EQ( BOOST_MP11_VERSION, BOOST_VERSION );
return boost::report_errors();
}
| davehorton/drachtio-server | deps/boost_1_77_0/libs/mp11/test/version.cpp | C++ | mit | 405 |
export * from './components/ajax-bar/index.js'
export * from './components/avatar/index.js'
export * from './components/badge/index.js'
export * from './components/banner/index.js'
export * from './components/bar/index.js'
export * from './components/breadcrumbs/index.js'
export * from './components/btn/index.js'
export * from './components/btn-dropdown/index.js'
export * from './components/btn-group/index.js'
export * from './components/btn-toggle/index.js'
export * from './components/card/index.js'
export * from './components/carousel/index.js'
export * from './components/chat/index.js'
export * from './components/checkbox/index.js'
export * from './components/chip/index.js'
export * from './components/circular-progress/index.js'
export * from './components/color/index.js'
export * from './components/date/index.js'
export * from './components/dialog/index.js'
export * from './components/drawer/index.js'
export * from './components/editor/index.js'
export * from './components/expansion-item/index.js'
export * from './components/fab/index.js'
export * from './components/field/index.js'
export * from './components/file/index.js'
export * from './components/footer/index.js'
export * from './components/form/index.js'
export * from './components/header/index.js'
export * from './components/icon/index.js'
export * from './components/img/index.js'
export * from './components/infinite-scroll/index.js'
export * from './components/inner-loading/index.js'
export * from './components/input/index.js'
export * from './components/intersection/index.js'
export * from './components/item/index.js'
export * from './components/knob/index.js'
export * from './components/layout/index.js'
export * from './components/markup-table/index.js'
export * from './components/menu/index.js'
export * from './components/no-ssr/index.js'
export * from './components/option-group/index.js'
export * from './components/page/index.js'
export * from './components/page-scroller/index.js'
export * from './components/page-sticky/index.js'
export * from './components/pagination/index.js'
export * from './components/parallax/index.js'
export * from './components/popup-edit/index.js'
export * from './components/popup-proxy/index.js'
export * from './components/linear-progress/index.js'
export * from './components/pull-to-refresh/index.js'
export * from './components/radio/index.js'
export * from './components/range/index.js'
export * from './components/rating/index.js'
export * from './components/resize-observer/index.js'
export * from './components/responsive/index.js'
export * from './components/scroll-area/index.js'
export * from './components/scroll-observer/index.js'
export * from './components/select/index.js'
export * from './components/separator/index.js'
export * from './components/skeleton/index.js'
export * from './components/slide-item/index.js'
export * from './components/slide-transition/index.js'
export * from './components/slider/index.js'
export * from './components/space/index.js'
export * from './components/spinner/index.js'
export * from './components/splitter/index.js'
export * from './components/stepper/index.js'
export * from './components/tab-panels/index.js'
export * from './components/table/index.js'
export * from './components/tabs/index.js'
export * from './components/time/index.js'
export * from './components/timeline/index.js'
export * from './components/toggle/index.js'
export * from './components/toolbar/index.js'
export * from './components/tooltip/index.js'
export * from './components/tree/index.js'
export * from './components/uploader/index.js'
export * from './components/video/index.js'
export * from './components/virtual-scroll/index.js'
| rstoenescu/quasar-framework | ui/src/components.js | JavaScript | mit | 3,696 |
/* */
define(['exports', 'core-js', 'aurelia-pal', 'aurelia-history'], function (exports, _coreJs, _aureliaPal, _aureliaHistory) {
'use strict';
exports.__esModule = true;
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
exports.configure = configure;
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var LinkHandler = (function () {
function LinkHandler() {
_classCallCheck(this, LinkHandler);
}
LinkHandler.prototype.activate = function activate(history) {};
LinkHandler.prototype.deactivate = function deactivate() {};
return LinkHandler;
})();
exports.LinkHandler = LinkHandler;
var DefaultLinkHandler = (function (_LinkHandler) {
_inherits(DefaultLinkHandler, _LinkHandler);
function DefaultLinkHandler() {
var _this = this;
_classCallCheck(this, DefaultLinkHandler);
_LinkHandler.call(this);
this.handler = function (e) {
var _DefaultLinkHandler$getEventInfo = DefaultLinkHandler.getEventInfo(e);
var shouldHandleEvent = _DefaultLinkHandler$getEventInfo.shouldHandleEvent;
var href = _DefaultLinkHandler$getEventInfo.href;
if (shouldHandleEvent) {
e.preventDefault();
_this.history.navigate(href);
}
};
}
DefaultLinkHandler.prototype.activate = function activate(history) {
if (history._hasPushState) {
this.history = history;
_aureliaPal.DOM.addEventListener('click', this.handler, true);
}
};
DefaultLinkHandler.prototype.deactivate = function deactivate() {
_aureliaPal.DOM.removeEventListener('click', this.handler);
};
DefaultLinkHandler.getEventInfo = function getEventInfo(event) {
var info = {
shouldHandleEvent: false,
href: null,
anchor: null
};
var target = DefaultLinkHandler.findClosestAnchor(event.target);
if (!target || !DefaultLinkHandler.targetIsThisWindow(target)) {
return info;
}
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
return info;
}
var href = target.getAttribute('href');
info.anchor = target;
info.href = href;
var hasModifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;
var isRelative = href && !(href.charAt(0) === '#' || /^[a-z]+:/i.test(href));
info.shouldHandleEvent = !hasModifierKey && isRelative;
return info;
};
DefaultLinkHandler.findClosestAnchor = function findClosestAnchor(el) {
while (el) {
if (el.tagName === 'A') {
return el;
}
el = el.parentNode;
}
};
DefaultLinkHandler.targetIsThisWindow = function targetIsThisWindow(target) {
var targetWindow = target.getAttribute('target');
var win = _aureliaPal.PLATFORM.global;
return !targetWindow || targetWindow === win.name || targetWindow === '_self' || targetWindow === 'top' && win === win.top;
};
return DefaultLinkHandler;
})(LinkHandler);
exports.DefaultLinkHandler = DefaultLinkHandler;
function configure(config) {
config.singleton(_aureliaHistory.History, BrowserHistory);
config.transient(LinkHandler, DefaultLinkHandler);
}
var BrowserHistory = (function (_History) {
_inherits(BrowserHistory, _History);
_createClass(BrowserHistory, null, [{
key: 'inject',
value: [LinkHandler],
enumerable: true
}]);
function BrowserHistory(linkHandler) {
_classCallCheck(this, BrowserHistory);
_History.call(this);
this._isActive = false;
this._checkUrlCallback = this._checkUrl.bind(this);
this.location = _aureliaPal.PLATFORM.location;
this.history = _aureliaPal.PLATFORM.history;
this.linkHandler = linkHandler;
}
BrowserHistory.prototype.activate = function activate(options) {
if (this._isActive) {
throw new Error('History has already been activated.');
}
var wantsPushState = !!options.pushState;
this._isActive = true;
this.options = Object.assign({}, { root: '/' }, this.options, options);
this.root = ('/' + this.options.root + '/').replace(rootStripper, '/');
this._wantsHashChange = this.options.hashChange !== false;
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
var eventName = undefined;
if (this._hasPushState) {
eventName = 'popstate';
} else if (this._wantsHashChange) {
eventName = 'hashchange';
}
_aureliaPal.PLATFORM.addEventListener(eventName, this._checkUrlCallback);
if (this._wantsHashChange && wantsPushState) {
var loc = this.location;
var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
if (!this._hasPushState && !atRoot) {
this.fragment = this._getFragment(null, true);
this.location.replace(this.root + this.location.search + '#' + this.fragment);
return true;
} else if (this._hasPushState && atRoot && loc.hash) {
this.fragment = this._getHash().replace(routeStripper, '');
this.history.replaceState({}, _aureliaPal.DOM.title, this.root + this.fragment + loc.search);
}
}
if (!this.fragment) {
this.fragment = this._getFragment();
}
this.linkHandler.activate(this);
if (!this.options.silent) {
return this._loadUrl();
}
};
BrowserHistory.prototype.deactivate = function deactivate() {
_aureliaPal.PLATFORM.removeEventListener('popstate', this._checkUrlCallback);
_aureliaPal.PLATFORM.removeEventListener('hashchange', this._checkUrlCallback);
this._isActive = false;
this.linkHandler.deactivate();
};
BrowserHistory.prototype.navigate = function navigate(fragment) {
var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var _ref$trigger = _ref.trigger;
var trigger = _ref$trigger === undefined ? true : _ref$trigger;
var _ref$replace = _ref.replace;
var replace = _ref$replace === undefined ? false : _ref$replace;
if (fragment && absoluteUrl.test(fragment)) {
this.location.href = fragment;
return true;
}
if (!this._isActive) {
return false;
}
fragment = this._getFragment(fragment || '');
if (this.fragment === fragment && !replace) {
return false;
}
this.fragment = fragment;
var url = this.root + fragment;
if (fragment === '' && url !== '/') {
url = url.slice(0, -1);
}
if (this._hasPushState) {
url = url.replace('//', '/');
this.history[replace ? 'replaceState' : 'pushState']({}, _aureliaPal.DOM.title, url);
} else if (this._wantsHashChange) {
updateHash(this.location, fragment, replace);
} else {
return this.location.assign(url);
}
if (trigger) {
return this._loadUrl(fragment);
}
};
BrowserHistory.prototype.navigateBack = function navigateBack() {
this.history.back();
};
BrowserHistory.prototype.setTitle = function setTitle(title) {
_aureliaPal.DOM.title = title;
};
BrowserHistory.prototype._getHash = function _getHash() {
return this.location.hash.substr(1);
};
BrowserHistory.prototype._getFragment = function _getFragment(fragment, forcePushState) {
var root = undefined;
if (!fragment) {
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
fragment = this.location.pathname + this.location.search;
root = this.root.replace(trailingSlash, '');
if (!fragment.indexOf(root)) {
fragment = fragment.substr(root.length);
}
} else {
fragment = this._getHash();
}
}
return '/' + fragment.replace(routeStripper, '');
};
BrowserHistory.prototype._checkUrl = function _checkUrl() {
var current = this._getFragment();
if (current !== this.fragment) {
this._loadUrl();
}
};
BrowserHistory.prototype._loadUrl = function _loadUrl(fragmentOverride) {
var fragment = this.fragment = this._getFragment(fragmentOverride);
return this.options.routeHandler ? this.options.routeHandler(fragment) : false;
};
return BrowserHistory;
})(_aureliaHistory.History);
exports.BrowserHistory = BrowserHistory;
var routeStripper = /^#?\/*|\s+$/g;
var rootStripper = /^\/+|\/+$/g;
var trailingSlash = /\/$/;
var absoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i;
function updateHash(location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
} else {
location.hash = '#' + fragment;
}
}
}); | mbroadst/aurelia-plunker | jspm_packages/npm/aurelia-history-browser@1.0.0-beta.1/aurelia-history-browser.js | JavaScript | mit | 10,044 |
# CallableSignature
# ===
# A CallableSignature describes how something callable expects to be called.
# Different implementation of this class are used for different types of callables.
#
# @api public
#
class Puppet::Pops::Evaluator::CallableSignature
# Returns the names of the parameters as an array of strings. This does not include the name
# of an optional block parameter.
#
# All implementations are not required to supply names for parameters. They may be used if present,
# to provide user feedback in errors etc. but they are not authoritative about the number of
# required arguments, optional arguments, etc.
#
# A derived class must implement this method.
#
# @return [Array<String>] - an array of names (that may be empty if names are unavailable)
#
# @api public
#
def parameter_names
raise NotImplementedError.new
end
# Returns a PCallableType with the type information, required and optional count, and type information about
# an optional block.
#
# A derived class must implement this method.
#
# @return [Puppet::Pops::Types::PCallableType]
# @api public
#
def type
raise NotImplementedError.new
end
# Returns the expected type for an optional block. The type may be nil, which means that the callable does
# not accept a block. If a type is returned it is one of Callable, Optional[Callable], Variant[Callable,...],
# or Optional[Variant[Callable, ...]]. The Variant type is used when multiple signatures are acceptable.
# The Optional type is used when the block is optional.
#
# @return [Puppet::Pops::Types::PAbstractType, nil] the expected type of a block given as the last parameter in a call.
#
# @api public
#
def block_type
type.block_type
end
# Returns the name of the block parameter if the callable accepts a block.
# @return [String] the name of the block parameter
# A derived class must implement this method.
# @api public
#
def block_name
raise NotImplementedError.new
end
# Returns a range indicating the optionality of a block. One of [0,0] (does not accept block), [0,1] (optional
# block), and [1,1] (block required)
#
# @return [Array(Integer, Integer)] the range of the block parameter
#
def block_range
type.block_range
end
# Returns the range of required/optional argument values as an array of [min, max], where an infinite
# end is given as INFINITY. To test against infinity, use the infinity? method.
#
# @return [Array[Integer, Numeric]] - an Array with [min, max]
#
# @api public
#
def args_range
type.size_range
end
# Returns true if the last parameter captures the rest of the arguments, with a possible cap, as indicated
# by the `args_range` method.
# A derived class must implement this method.
#
# @return [Boolean] true if last parameter captures the rest of the given arguments (up to a possible cap)
# @api public
#
def last_captures_rest?
raise NotImplementedError.new
end
# Returns true if the given x is infinity
# @return [Boolean] true, if given value represents infinity
#
# @api public
#
def infinity?(x)
x == Puppet::Pops::Types::INFINITY
end
end
| jorgemancheno/boxen | vendor/bundle/ruby/2.0.0/gems/puppet-3.6.1/lib/puppet/pops/evaluator/callable_signature.rb | Ruby | mit | 3,208 |
/**
* Copyright (c) 2015-present, Alibaba Group Holding Limited.
* All rights reserved.
*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @providesModule ReactNavigatorNavigationBarStylesAndroid
*/
'use strict';
import buildStyleInterpolator from './polyfills/buildStyleInterpolator';
import merge from './polyfills/merge';
// Android Material Design
var NAV_BAR_HEIGHT = 56;
var TITLE_LEFT = 72;
var BUTTON_SIZE = 24;
var TOUCH_TARGT_SIZE = 48;
var BUTTON_HORIZONTAL_MARGIN = 16;
var BUTTON_EFFECTIVE_MARGIN = BUTTON_HORIZONTAL_MARGIN - (TOUCH_TARGT_SIZE - BUTTON_SIZE) / 2;
var NAV_ELEMENT_HEIGHT = NAV_BAR_HEIGHT;
var BASE_STYLES = {
Title: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
alignItems: 'flex-start',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
marginLeft: TITLE_LEFT,
},
LeftButton: {
position: 'absolute',
top: 0,
left: BUTTON_EFFECTIVE_MARGIN,
overflow: 'hidden',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
},
RightButton: {
position: 'absolute',
top: 0,
right: BUTTON_EFFECTIVE_MARGIN,
overflow: 'hidden',
alignItems: 'flex-end',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
},
};
// There are 3 stages: left, center, right. All previous navigation
// items are in the left stage. The current navigation item is in the
// center stage. All upcoming navigation items are in the right stage.
// Another way to think of the stages is in terms of transitions. When
// we move forward in the navigation stack, we perform a
// right-to-center transition on the new navigation item and a
// center-to-left transition on the current navigation item.
var Stages = {
Left: {
Title: merge(BASE_STYLES.Title, { opacity: 0 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 0 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 0 }),
},
Center: {
Title: merge(BASE_STYLES.Title, { opacity: 1 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 1 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 1 }),
},
Right: {
Title: merge(BASE_STYLES.Title, { opacity: 0 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 0 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 0 }),
},
};
var opacityRatio = 100;
function buildSceneInterpolators(startStyles, endStyles) {
return {
Title: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.Title.opacity,
to: endStyles.Title.opacity,
min: 0,
max: 1,
},
left: {
type: 'linear',
from: startStyles.Title.left,
to: endStyles.Title.left,
min: 0,
max: 1,
extrapolate: true,
},
}),
LeftButton: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.LeftButton.opacity,
to: endStyles.LeftButton.opacity,
min: 0,
max: 1,
round: opacityRatio,
},
left: {
type: 'linear',
from: startStyles.LeftButton.left,
to: endStyles.LeftButton.left,
min: 0,
max: 1,
},
}),
RightButton: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.RightButton.opacity,
to: endStyles.RightButton.opacity,
min: 0,
max: 1,
round: opacityRatio,
},
left: {
type: 'linear',
from: startStyles.RightButton.left,
to: endStyles.RightButton.left,
min: 0,
max: 1,
extrapolate: true,
},
}),
};
}
var Interpolators = {
// Animating *into* the center stage from the right
RightToCenter: buildSceneInterpolators(Stages.Right, Stages.Center),
// Animating out of the center stage, to the left
CenterToLeft: buildSceneInterpolators(Stages.Center, Stages.Left),
// Both stages (animating *past* the center stage)
RightToLeft: buildSceneInterpolators(Stages.Right, Stages.Left),
};
module.exports = {
General: {
NavBarHeight: NAV_BAR_HEIGHT,
StatusBarHeight: 0,
TotalNavHeight: NAV_BAR_HEIGHT,
},
Interpolators,
Stages,
};
| typesettin/NativeCMS | node_modules/react-web/Libraries/Navigator/NavigatorNavigationBarStylesAndroid.js | JavaScript | mit | 4,250 |
package net.anotheria.moskito.webui.threads.api;
import net.anotheria.anoplass.api.APIFactory;
import net.anotheria.anoplass.api.APIFinder;
import net.anotheria.anoprise.metafactory.ServiceFactory;
/**
* TODO comment this class
*
* @author lrosenberg
* @since 14.02.13 11:46
*/
public class ThreadAPIFactory implements APIFactory<ThreadAPI>, ServiceFactory<ThreadAPI> {
@Override
public ThreadAPI createAPI() {
return new ThreadAPIImpl();
}
@Override
public ThreadAPI create() {
APIFinder.addAPIFactory(ThreadAPI.class, this);
return APIFinder.findAPI(ThreadAPI.class);
}
}
| esmakula/moskito | moskito-webui/src/main/java/net/anotheria/moskito/webui/threads/api/ThreadAPIFactory.java | Java | mit | 594 |
require "spec_helper"
require "hamster/sorted_set"
describe Hamster::SortedSet do
describe "#disjoint?" do
[
[[], [], true],
[["A"], [], true],
[[], ["A"], true],
[["A"], ["A"], false],
[%w[A B C], ["B"], false],
[["B"], %w[A B C], false],
[%w[A B C], %w[D E], true],
[%w[F G H I], %w[A B C], true],
[%w[A B C], %w[A B C], false],
[%w[A B C], %w[A B C D], false],
[%w[D E F G], %w[A B C], true],
].each do |a, b, expected|
context "for #{a.inspect} and #{b.inspect}" do
it "returns #{expected}" do
Hamster.sorted_set(*a).disjoint?(Hamster.sorted_set(*b)).should be(expected)
end
end
end
end
end | dzjuck/hamster | spec/lib/hamster/sorted_set/disjoint_spec.rb | Ruby | mit | 715 |
require 'spec_helper'
describe Locomotive::Liquid::Tags::Extends do
before(:each) do
@home = FactoryGirl.build(:page, :raw_template => 'Hello world')
@home.send :serialize_template
@home.instance_variable_set(:@template, nil)
@site = FactoryGirl.build(:site)
@site.stubs(:pages).returns([@home])
end
it 'works' do
page = FactoryGirl.build(:page, :slug => 'sub_page_1', :parent => @home)
parse('parent', page).render.should == 'Hello world'
end
it 'looks for the index with the right locale' do
::Mongoid::Fields::I18n.with_locale 'fr' do
@home.raw_template = 'Bonjour le monde'
@home.send :serialize_template
end
@site.pages.expects(:where).with('fullpath.fr' => 'index').returns([@home])
::Mongoid::Fields::I18n.with_locale 'fr' do
page = FactoryGirl.build(:page, :slug => 'sub_page_1', :parent => @home)
parse('index', page).render.should == 'Bonjour le monde'
end
end
context '#errors' do
it 'raises an error if the source page does not exist' do
lambda {
@site.pages.expects(:where).with('fullpath.en' => 'foo').returns([])
parse('foo')
}.should raise_error(Locomotive::Liquid::PageNotFound, "Page with fullpath 'foo' was not found")
end
it 'raises an error if the source page is not translated' do
lambda {
::Mongoid::Fields::I18n.with_locale 'fr' do
page = FactoryGirl.build(:page, :slug => 'sub_page_1', :parent => @home)
parse('parent', page)
end
}.should raise_error(Locomotive::Liquid::PageNotTranslated, "Page with fullpath 'parent' was not translated")
end
end
def parse(source = 'index', page = nil)
page ||= @home
Liquid::Template.parse("{% extends #{source} %}", { :site => @site, :page => page })
end
end
| Vinagility/engine_old | spec/lib/locomotive/liquid/tags/extends_spec.rb | Ruby | mit | 1,826 |
(function () {
'use strict';
/** This directive is used to render out the current variant tabs and properties and exposes an API for other directives to consume */
function tabbedContentDirective($timeout, $filter, contentEditingHelper, contentTypeHelper) {
function link($scope, $element) {
var appRootNode = $element[0];
// Directive for cached property groups.
var propertyGroupNodesDictionary = {};
var scrollableNode = appRootNode.closest(".umb-scrollable");
$scope.activeTabAlias = null;
$scope.tabs = [];
$scope.$watchCollection('content.tabs', (newValue) => {
contentTypeHelper.defineParentAliasOnGroups(newValue);
contentTypeHelper.relocateDisorientedGroups(newValue);
// make a collection with only tabs and not all groups
$scope.tabs = $filter("filter")(newValue, (tab) => {
return tab.type === contentTypeHelper.TYPE_TAB;
});
if ($scope.tabs.length > 0) {
// if we have tabs and some groups that doesn't belong to a tab we need to render those on an "Other" tab.
contentEditingHelper.registerGenericTab(newValue);
$scope.setActiveTab($scope.tabs[0]);
scrollableNode.removeEventListener("scroll", onScroll);
scrollableNode.removeEventListener("mousewheel", cancelScrollTween);
// only trigger anchor scroll when there are no tabs
} else {
scrollableNode.addEventListener("scroll", onScroll);
scrollableNode.addEventListener("mousewheel", cancelScrollTween);
}
});
function onScroll(event) {
var viewFocusY = scrollableNode.scrollTop + scrollableNode.clientHeight * .5;
for(var i in $scope.content.tabs) {
var group = $scope.content.tabs[i];
var node = propertyGroupNodesDictionary[group.id];
if (!node) {
return;
}
if (viewFocusY >= node.offsetTop && viewFocusY <= node.offsetTop + node.clientHeight) {
setActiveAnchor(group);
return;
}
}
}
function setActiveAnchor(tab) {
if (tab.active !== true) {
var i = $scope.content.tabs.length;
while(i--) {
$scope.content.tabs[i].active = false;
}
tab.active = true;
}
}
function getActiveAnchor() {
var i = $scope.content.tabs.length;
while(i--) {
if ($scope.content.tabs[i].active === true)
return $scope.content.tabs[i];
}
return false;
}
function getScrollPositionFor(id) {
if (propertyGroupNodesDictionary[id]) {
return propertyGroupNodesDictionary[id].offsetTop - 20;// currently only relative to closest relatively positioned parent
}
return null;
}
function scrollTo(id) {
var y = getScrollPositionFor(id);
if (getScrollPositionFor !== null) {
var viewportHeight = scrollableNode.clientHeight;
var from = scrollableNode.scrollTop;
var to = Math.min(y, scrollableNode.scrollHeight - viewportHeight);
var animeObject = {_y: from};
$scope.scrollTween = anime({
targets: animeObject,
_y: to,
easing: 'easeOutExpo',
duration: 200 + Math.min(Math.abs(to-from)/viewportHeight*100, 400),
update: () => {
scrollableNode.scrollTo(0, animeObject._y);
}
});
}
}
function jumpTo(id) {
var y = getScrollPositionFor(id);
if (getScrollPositionFor !== null) {
cancelScrollTween();
scrollableNode.scrollTo(0, y);
}
}
function cancelScrollTween() {
if($scope.scrollTween) {
$scope.scrollTween.pause();
}
}
$scope.registerPropertyGroup = function(element, appAnchor) {
propertyGroupNodesDictionary[appAnchor] = element;
};
$scope.setActiveTab = function(tab) {
$scope.activeTabAlias = tab.alias;
$scope.tabs.forEach(tab => tab.active = false);
tab.active = true;
};
$scope.$on("editors.apps.appChanged", function($event, $args) {
// if app changed to this app, then we want to scroll to the current anchor
if($args.app.alias === "umbContent" && $scope.tabs.length === 0) {
var activeAnchor = getActiveAnchor();
$timeout(jumpTo.bind(null, [activeAnchor.id]));
}
});
$scope.$on("editors.apps.appAnchorChanged", function($event, $args) {
if($args.app.alias === "umbContent") {
setActiveAnchor($args.anchor);
scrollTo($args.anchor.id);
}
});
//ensure to unregister from all dom-events
$scope.$on('$destroy', function () {
cancelScrollTween();
scrollableNode.removeEventListener("scroll", onScroll);
scrollableNode.removeEventListener("mousewheel", cancelScrollTween);
});
}
function controller($scope) {
//expose the property/methods for other directives to use
this.content = $scope.content;
if($scope.contentNodeModel) {
$scope.defaultVariant = _.find($scope.contentNodeModel.variants, variant => {
// defaultVariant will never have segment. Wether it has a language or not depends on the setup.
return !variant.segment && ((variant.language && variant.language.isDefault) || (!variant.language));
});
}
$scope.unlockInvariantValue = function(property) {
property.unlockInvariantValue = !property.unlockInvariantValue;
};
$scope.$watch("tabbedContentForm.$dirty",
function (newValue, oldValue) {
if (newValue === true) {
$scope.content.isDirty = true;
}
}
);
$scope.propertyEditorDisabled = function (property) {
if (property.unlockInvariantValue) {
return false;
}
var contentLanguage = $scope.content.language;
var canEditCulture = !contentLanguage ||
// If the property culture equals the content culture it can be edited
property.culture === contentLanguage.culture ||
// A culture-invariant property can only be edited by the default language variant
(property.culture == null && contentLanguage.isDefault);
var canEditSegment = property.segment === $scope.content.segment;
return !canEditCulture || !canEditSegment;
}
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/content/umb-tabbed-content.html',
controller: controller,
link: link,
scope: {
content: "=", // in this context the content is the variant model.
contentNodeModel: "=?", //contentNodeModel is the content model for the node,
contentApp: "=?" // contentApp is the origin app model for this view
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbTabbedContent', tabbedContentDirective);
})();
| umbraco/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbtabbedcontent.directive.js | JavaScript | mit | 8,522 |
#include "time_alias_reflection.h"
#include <bond/core/bond.h>
#include <bond/stream/output_buffer.h>
using namespace examples::time;
int main()
{
Example obj, obj2;
using namespace boost::gregorian;
using namespace boost::posix_time;
// In the generated code we use boost::posix_time_ptime::ptime to represent
// the type alias 'time' (see makefile.inc for code gen flags).
obj.when = ptime(date(2016, 1, 29));
obj.bdays["bill"] = ptime(from_string("1955/10/28"));
bond::OutputBuffer output;
bond::CompactBinaryWriter<bond::OutputBuffer> writer(output);
// Serialize the object
Serialize(obj, writer);
bond::CompactBinaryReader<bond::InputBuffer> reader(output.GetBuffer());
// De-serialize the object
Deserialize(reader, obj2);
std::string followingSunday = to_simple_string(
first_day_of_the_week_after(Sunday).get_date(obj2.when.date()));
BOOST_ASSERT(obj == obj2);
return 0;
}
| upsoft/bond | examples/cpp/core/time_alias/time_alias.cpp | C++ | mit | 971 |
<?php
/**
*
*/
namespace Mvc5\Plugin\Gem;
interface Copy
extends Gem
{
/**
* @return object
*/
function config();
}
| devosc/mvc5 | src/Plugin/Gem/Copy.php | PHP | mit | 142 |
<?php
defined('C5_EXECUTE') or die(_("Access Denied."));
Loader::block('page_list');
$previewMode = true;
$nh = Loader::helper('navigation');
$controller = new PageListBlockController($b);
$_REQUEST['num'] = ($_REQUEST['num'] > 0) ? $_REQUEST['num'] : 0;
$_REQUEST['cThis'] = ($_REQUEST['cParentID'] == $controller->cID) ? '1' : '0';
$_REQUEST['cParentID'] = ($_REQUEST['cParentID'] == 'OTHER') ? $_REQUEST['cParentIDValue'] : $_REQUEST['cParentID'];
$controller->num = $_REQUEST['num'];
$controller->cParentID = $_REQUEST['cParentID'];
$controller->cThis = $_REQUEST['cThis'];
$controller->orderBy = $_REQUEST['orderBy'];
$controller->ctID = $_REQUEST['ctID'];
$controller->rss = $_REQUEST['rss'];
$controller->displayFeaturedOnly = $_REQUEST['displayFeaturedOnly'];
$cArray = $controller->getPages();
//echo var_dump($cArray);
require(dirname(__FILE__) . '/../view.php');
exit; | markdev/markandkitty | concrete/blocks/date_nav/tools/preview_pane.php | PHP | mit | 898 |
# frozen_string_literal: true
class AvatarUploader < GitlabUploader
include UploaderHelper
include RecordsUploads::Concern
include ObjectStorage::Concern
prepend ObjectStorage::Extension::RecordsUploads
MIME_WHITELIST = %w[image/png image/jpeg image/gif image/bmp image/tiff image/vnd.microsoft.icon].freeze
def exists?
model.avatar.file && model.avatar.file.present?
end
def move_to_store
false
end
def move_to_cache
false
end
def absolute_path
self.class.absolute_path(upload)
end
def mounted_as
super || 'avatar'
end
def content_type_whitelist
MIME_WHITELIST
end
private
def dynamic_segment
File.join(model.class.underscore, mounted_as.to_s, model.id.to_s)
end
end
| mmkassem/gitlabhq | app/uploaders/avatar_uploader.rb | Ruby | mit | 746 |
<?php
namespace Bolt\Tests\Controller\Backend;
use Bolt\Storage\Entity;
use Bolt\Tests\Controller\ControllerUnitTest;
use Symfony\Component\Form\FormView;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Class to test correct operation of src/Controller/Backend/Users.
*
* @author Ross Riley <riley.ross@gmail.com>
* @author Gawain Lynch <gawain.lynch@gmail.com>
**/
class UsersTest extends ControllerUnitTest
{
public function testAdmin()
{
$this->setRequest(Request::create('/bolt/users'));
$response = $this->controller()->admin();
$context = $response->getContext();
$this->assertNotNull($context['context']['users']);
$this->assertNotNull($context['context']['sessions']);
}
public function testEdit()
{
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
$this->setRequest(Request::create('/bolt/users/edit/1'));
// This one should redirect because of permission failure
$response = $this->controller()->edit($this->getRequest(), 1);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Now we allow the permsission check to return true
$perms = $this->getMockPermissions();
$perms->expects($this->any())
->method('isAllowedToManipulate')
->will($this->returnValue(true));
$this->setService('permissions', $perms);
$response = $this->controller()->edit($this->getRequest(), 1);
$context = $response->getContext();
$this->assertEquals('edit', $context['context']['kind']);
$this->assertInstanceOf(FormView::class, $context['context']['form']);
$this->assertEquals('Admin', $context['context']['displayname']);
// Test that an empty user gives a create form
$this->setRequest(Request::create('/bolt/users/edit'));
$response = $this->controller()->edit($this->getRequest(), null);
$context = $response->getContext();
$this->assertEquals('create', $context['context']['kind']);
}
public function testUserEditPost()
{
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
$perms = $this->getMockPermissions();
$perms->expects($this->any())
->method('isAllowedToManipulate')
->will($this->returnValue(true));
$this->setService('permissions', $perms);
// Symfony forms need a CSRF token so we have to mock this too
$this->removeCSRF();
// Update the display name via a POST request
$this->setRequest(Request::create(
'/bolt/useredit/1',
'POST',
[
'user_edit' => [
'username' => $user['username'],
'email' => $user['email'],
'displayname' => 'Admin Test',
'_token' => 'xyz',
],
]
));
$response = $this->controller()->edit($this->getRequest(), 1);
$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
}
public function testFirst()
{
// Symfony forms need a CSRF token so we have to mock this too
$this->removeCSRF();
// Because we have users in the database this should exit at first attempt
$this->setRequest(Request::create('/bolt/userfirst'));
$response = $this->controller()->first($this->getRequest());
$this->assertEquals('/bolt', $response->getTargetUrl());
// Now we delete the users
$this->getService('db')->executeQuery('DELETE FROM bolt_users;');
$this->getService('users')->users = [];
$this->setRequest(Request::create('/bolt/userfirst'));
$response = $this->controller()->first($this->getRequest());
$context = $response->getContext();
$this->assertEquals('create', $context['context']['kind']);
// This block attempts to create the user
$request = Request::create(
'/bolt/userfirst',
'POST',
[
'user_new' => [
'username' => 'admin',
'email' => 'test@example.com',
'displayname' => 'Admin',
'password' => [
'first' => 'password',
'second' => 'password',
],
'_token' => 'xyz',
],
]
);
$this->setRequest($request);
$this->getService('request_stack')->push($request);
$response = $this->controller()->first($this->getRequest());
$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertEquals('/bolt', $response->getTargetUrl());
}
public function testModifyBadCsrf()
{
// First test should exit/redirect with no anti CSRF token
$this->setRequest(Request::create('/bolt/user/disable/2'));
$response = $this->controller()->modify('disable', 1);
$info = $this->getFlashBag()->get('error');
$this->assertRegExp('/Something went wrong/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
}
public function testModifyValidCsrf()
{
// Now we mock the CSRF token to validate
$this->removeCSRF();
$currentuser = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($currentuser));
// This request should fail because the user doesnt exist.
$this->setRequest(Request::create('/bolt/user/disable/2'));
$response = $this->controller()->modify('disable', 42);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$err = $this->getFlashBag()->get('error');
$this->assertRegExp('/No such user/', $err[0]);
// This check will fail because we are operating on the current user
$this->setRequest(Request::create('/bolt/user/disable/1'));
$response = $this->controller()->modify('disable', 1);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$err = $this->getFlashBag()->get('error');
$this->assertRegExp('/yourself/', $err[0]);
// We add a new user that isn't the current user and now perform operations.
$this->addNewUser($this->getApp(), 'editor', 'Editor', 'editor');
$editor = $this->getService('users')->getUser('editor');
// And retry the operation that will work now
$this->setRequest(Request::create('/bolt/user/disable/2'));
$response = $this->controller()->modify('disable', $editor['id']);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/is disabled/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Now try to enable the user
$this->setRequest(Request::create('/bolt/user/enable/2'));
$response = $this->controller()->modify('enable', $editor['id']);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/is enabled/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Try a non-existent action, make sure we get an error
$this->setRequest(Request::create('/bolt/user/enhance/2'));
$response = $this->controller()->modify('enhance', $editor['id']);
$info = $this->getFlashBag()->get('error');
$this->assertRegExp('/No such action/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Now we run a delete action
$this->setRequest(Request::create('/bolt/user/delete/2'));
$response = $this->controller()->modify('delete', $editor['id']);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/is deleted/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Finally we mock the permsission check to return false and check
// we get a priileges error.
$this->addNewUser($this->getApp(), 'editor', 'Editor', 'editor');
$editor = $this->getService('users')->getUser('editor');
$perms = $this->getMockPermissions();
$perms->expects($this->any())
->method('isAllowedToManipulate')
->will($this->returnValue(false));
$this->setService('permissions', $perms);
$this->setRequest(Request::create('/bolt/user/disable/' . $editor['id']));
$response = $this->controller()->modify('disable', $editor['id']);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$err = $this->getFlashBag()->get('error');
$this->assertRegExp('/right privileges/', $err[0]);
}
public function testModifyFailures()
{
// We add a new user that isn't the current user and now perform operations.
$this->addNewUser($this->getApp(), 'editor', 'Editor', 'editor');
// Now we mock the CSRF token to validate
$this->removeCSRF();
$users = $this->getMockUsers(['setEnabled', 'deleteUser']);
$users->expects($this->any())
->method('setEnabled')
->will($this->returnValue(false));
$users->expects($this->any())
->method('deleteUser')
->will($this->returnValue(false));
$this->setService('users', $users);
// Setup the current user
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
// This mocks a failure and ensures the error is reported
$this->setRequest(Request::create('/bolt/user/disable/2'));
$response = $this->controller()->modify('disable', 2);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/could not be disabled/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$this->setRequest(Request::create('/bolt/user/enable/2'));
$response = $this->controller()->modify('enable', 2);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/could not be enabled/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$this->setRequest(Request::create('/bolt/user/delete/2'));
$response = $this->controller()->modify('delete', 2);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/could not be deleted/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
}
public function testProfile()
{
// Symfony forms need a CSRF token so we have to mock this too
$this->removeCSRF();
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
$this->setRequest(Request::create('/bolt/profile'));
$response = $this->controller()->profile($this->getRequest());
$context = $response->getContext();
$this->assertEquals('@bolt/edituser/edituser.twig', $response->getTemplate());
$this->assertEquals('profile', $context['context']['kind']);
// Now try a POST to update the profile
$this->setRequest(Request::create(
'/bolt/profile',
'POST',
[
'user_profile' => [
'email' => $user['email'],
'displayname' => 'Admin Test',
'_token' => 'xyz',
],
]
));
$this->controller()->profile($this->getRequest());
$this->assertNotEmpty($this->getFlashBag()->get('success'));
}
public function testUsernameEditKillsSession()
{
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
// Symfony forms need a CSRF token so we have to mock this too
$this->removeCSRF();
$perms = $this->getMockPermissions();
$perms->expects($this->any())
->method('isAllowedToManipulate')
->will($this->returnValue(true));
$this->setService('permissions', $perms);
// Update the display name via a POST request
$this->setRequest(Request::create(
'/bolt/users/edit/1',
'POST',
[
'user_edit' => [
'username' => 'admin2',
'email' => $user['email'],
'displayname' => $user['displayname'],
'_token' => 'xyz',
],
]
));
$response = $this->controller()->edit($this->getRequest(), 1);
$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertEquals('/bolt/login', $response->getTargetUrl());
}
public function testViewRoles()
{
$this->setRequest(Request::create('/bolt/roles'));
$response = $this->controller()->viewRoles();
$context = $response->getContext();
$this->assertEquals('@bolt/roles/roles.twig', $response->getTemplate());
$this->assertNotEmpty($context['context']['global_permissions']);
$this->assertNotEmpty($context['context']['effective_permissions']);
}
/**
* @return \Bolt\Controller\Backend\Users
*/
protected function controller()
{
return $this->getService('controller.backend.users');
}
}
| GawainLynch/bolt | tests/phpunit/unit/Controller/Backend/UsersTest.php | PHP | mit | 13,704 |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript'; // used as value and is provided at runtime
import {locateSymbols} from './locate_symbol';
import {findTightestNode, getClassDeclFromDecoratorProp, getPropertyAssignmentFromValue} from './ts_utils';
import {AstResult, Span} from './types';
import {extractAbsoluteFilePath} from './utils';
/**
* Convert Angular Span to TypeScript TextSpan. Angular Span has 'start' and
* 'end' whereas TS TextSpan has 'start' and 'length'.
* @param span Angular Span
*/
function ngSpanToTsTextSpan(span: Span): ts.TextSpan {
return {
start: span.start,
length: span.end - span.start,
};
}
/**
* Attempts to get the definition of a file whose URL is specified in a property assignment in a
* directive decorator.
* Currently applies to `templateUrl` and `styleUrls` properties.
*/
function getUrlFromProperty(
urlNode: ts.StringLiteralLike,
tsLsHost: Readonly<ts.LanguageServiceHost>): ts.DefinitionInfoAndBoundSpan|undefined {
// Get the property assignment node corresponding to the `templateUrl` or `styleUrls` assignment.
// These assignments are specified differently; `templateUrl` is a string, and `styleUrls` is
// an array of strings:
// {
// templateUrl: './template.ng.html',
// styleUrls: ['./style.css', './other-style.css']
// }
// `templateUrl`'s property assignment can be found from the string literal node;
// `styleUrls`'s property assignment can be found from the array (parent) node.
//
// First search for `templateUrl`.
let asgn = getPropertyAssignmentFromValue(urlNode, 'templateUrl');
if (!asgn) {
// `templateUrl` assignment not found; search for `styleUrls` array assignment.
asgn = getPropertyAssignmentFromValue(urlNode.parent, 'styleUrls');
if (!asgn) {
// Nothing found, bail.
return;
}
}
// If the property assignment is not a property of a class decorator, don't generate definitions
// for it.
if (!getClassDeclFromDecoratorProp(asgn)) {
return;
}
// Extract url path specified by the url node, which is relative to the TypeScript source file
// the url node is defined in.
const url = extractAbsoluteFilePath(urlNode);
// If the file does not exist, bail. It is possible that the TypeScript language service host
// does not have a `fileExists` method, in which case optimistically assume the file exists.
if (tsLsHost.fileExists && !tsLsHost.fileExists(url)) return;
const templateDefinitions: ts.DefinitionInfo[] = [{
kind: ts.ScriptElementKind.externalModuleName,
name: url,
containerKind: ts.ScriptElementKind.unknown,
containerName: '',
// Reading the template is expensive, so don't provide a preview.
textSpan: {start: 0, length: 0},
fileName: url,
}];
return {
definitions: templateDefinitions,
textSpan: {
// Exclude opening and closing quotes in the url span.
start: urlNode.getStart() + 1,
length: urlNode.getWidth() - 2,
},
};
}
/**
* Traverse the template AST and look for the symbol located at `position`, then
* return its definition and span of bound text.
* @param info
* @param position
*/
export function getDefinitionAndBoundSpan(
info: AstResult, position: number): ts.DefinitionInfoAndBoundSpan|undefined {
const symbols = locateSymbols(info, position);
if (!symbols.length) {
return;
}
const seen = new Set<string>();
const definitions: ts.DefinitionInfo[] = [];
for (const symbolInfo of symbols) {
const {symbol} = symbolInfo;
// symbol.definition is really the locations of the symbol. There could be
// more than one. No meaningful info could be provided without any location.
const {kind, name, container, definition: locations} = symbol;
if (!locations || !locations.length) {
continue;
}
const containerKind =
container ? container.kind as ts.ScriptElementKind : ts.ScriptElementKind.unknown;
const containerName = container ? container.name : '';
for (const {fileName, span} of locations) {
const textSpan = ngSpanToTsTextSpan(span);
// In cases like two-way bindings, a request for the definitions of an expression may return
// two of the same definition:
// [(ngModel)]="prop"
// ^^^^ -- one definition for the property binding, one for the event binding
// To prune duplicate definitions, tag definitions with unique location signatures and ignore
// definitions whose locations have already been seen.
const signature = `${textSpan.start}:${textSpan.length}@${fileName}`;
if (seen.has(signature)) continue;
definitions.push({
kind: kind as ts.ScriptElementKind,
name,
containerKind,
containerName,
textSpan: ngSpanToTsTextSpan(span),
fileName: fileName,
});
seen.add(signature);
}
}
return {
definitions,
textSpan: symbols[0].span,
};
}
/**
* Gets an Angular-specific definition in a TypeScript source file.
*/
export function getTsDefinitionAndBoundSpan(
sf: ts.SourceFile, position: number,
tsLsHost: Readonly<ts.LanguageServiceHost>): ts.DefinitionInfoAndBoundSpan|undefined {
const node = findTightestNode(sf, position);
if (!node) return;
switch (node.kind) {
case ts.SyntaxKind.StringLiteral:
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
// Attempt to extract definition of a URL in a property assignment.
return getUrlFromProperty(node as ts.StringLiteralLike, tsLsHost);
default:
return undefined;
}
}
| blesh/angular | packages/language-service/src/definitions.ts | TypeScript | mit | 5,793 |
<?php defined('BX_DOL') or die('hack attempt');
/**
* Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
* CC-BY License - http://creativecommons.org/licenses/by/3.0/
*
* @defgroup Accounts Accounts
* @ingroup DolphinModules
*
* @{
*/
class BxAccntConfig extends BxBaseModGeneralConfig
{
protected $_oDb;
protected $_aHtmlIds;
/**
* Constructor
*/
public function __construct($aModule)
{
parent::__construct($aModule);
$this->CNF = array (
// page URIs
'URL_MANAGE_ADMINISTRATION' => 'page.php?i=accounts-administration',
// objects
'OBJECT_MENU_MANAGE_TOOLS' => 'bx_accounts_menu_manage_tools', //manage menu in content administration tools
'OBJECT_GRID_ADMINISTRATION' => 'bx_accounts_administration',
'OBJECT_GRID_MODERATION' => 'bx_accounts_moderation',
// some language keys
'T' => array (
'grid_action_err_delete' => '_bx_accnt_grid_action_err_delete',
'grid_action_err_perform' => '_bx_accnt_grid_action_err_perform',
'filter_item_active' => '_bx_accnt_grid_filter_item_title_adm_active',
'filter_item_pending' => '_bx_accnt_grid_filter_item_title_adm_pending',
'filter_item_suspended' => '_bx_accnt_grid_filter_item_title_adm_suspended',
'filter_item_select_one_filter1' => '_bx_accnt_grid_filter_item_title_adm_select_one_filter1',
)
);
$this->_aObjects = array(
'alert' => $this->_sName,
);
$this->_aJsClass = array(
'manage_tools' => 'BxAccntManageTools'
);
$this->_aJsObjects = array(
'manage_tools' => 'oBxAccntManageTools'
);
$this->_aGridObjects = array(
'moderation' => $this->CNF['OBJECT_GRID_MODERATION'],
'administration' => $this->CNF['OBJECT_GRID_ADMINISTRATION'],
);
$sHtmlPrefix = str_replace('_', '-', $this->_sName);
$this->_aHtmlIds = array(
'profile' => $sHtmlPrefix . '-profile-',
'profile_more_popup' => $sHtmlPrefix . '-profile-more-popup-',
);
}
public function init(&$oDb)
{
$this->_oDb = &$oDb;
}
public function getHtmlIds($sKey = '')
{
if(empty($sKey))
return $this->_aHtmlIds;
return isset($this->_aHtmlIds[$sKey]) ? $this->_aHtmlIds[$sKey] : '';
}
}
/** @} */
| camperjz/trident | modules/boonex/accounts/updates/8.0.1_8.0.2/source/classes/BxAccntConfig.php | PHP | mit | 2,465 |
<?php
use Automattic\Jetpack\Sync\Functions;
require_once dirname( __FILE__ ) . '/class.json-api-site-jetpack-base.php';
require_once dirname( __FILE__ ) . '/class.json-api-post-jetpack.php';
// this code runs on Jetpack (.org) sites
class Jetpack_Site extends Abstract_Jetpack_Site {
protected function get_mock_option( $name ) {
return get_option( 'jetpack_'.$name );
}
protected function get_constant( $name ) {
if ( defined( $name) ) {
return constant( $name );
}
return null;
}
protected function main_network_site() {
return network_site_url();
}
protected function wp_version() {
global $wp_version;
return $wp_version;
}
protected function max_upload_size() {
return wp_max_upload_size();
}
protected function wp_memory_limit() {
return wp_convert_hr_to_bytes( WP_MEMORY_LIMIT );
}
protected function wp_max_memory_limit() {
return wp_convert_hr_to_bytes( WP_MAX_MEMORY_LIMIT );
}
protected function is_main_network() {
return Jetpack::is_multi_network();
}
public function is_multisite() {
return (bool) is_multisite();
}
public function is_single_user_site() {
return (bool) Jetpack::is_single_user_site();
}
protected function is_version_controlled() {
return Functions::is_version_controlled();
}
protected function file_system_write_access() {
return Functions::file_system_write_access();
}
protected function current_theme_supports( $feature_name ) {
return current_theme_supports( $feature_name );
}
protected function get_theme_support( $feature_name ) {
return get_theme_support( $feature_name );
}
public function get_updates() {
return (array) Jetpack::get_updates();
}
function get_id() {
return $this->platform->token->blog_id;
}
function has_videopress() {
// TODO - this only works on wporg site - need to detect videopress option for remote Jetpack site on WPCOM
$videopress = Jetpack_Options::get_option( 'videopress', array() );
if ( isset( $videopress['blog_id'] ) && $videopress['blog_id'] > 0 ) {
return true;
}
return false;
}
function upgraded_filetypes_enabled() {
return true;
}
function is_mapped_domain() {
return true;
}
function get_unmapped_url() {
// Fallback to the home URL since all Jetpack sites don't have an unmapped *.wordpress.com domain.
return $this->get_url();
}
function is_redirect() {
return false;
}
function is_following() {
return false;
}
function has_wordads() {
return Jetpack::is_module_active( 'wordads' );
}
function get_frame_nonce() {
return false;
}
function get_jetpack_frame_nonce() {
return false;
}
function is_headstart_fresh() {
return false;
}
function allowed_file_types() {
$allowed_file_types = array();
// https://codex.wordpress.org/Uploading_Files
$mime_types = get_allowed_mime_types();
foreach ( $mime_types as $type => $mime_type ) {
$extras = explode( '|', $type );
foreach ( $extras as $extra ) {
$allowed_file_types[] = $extra;
}
}
return $allowed_file_types;
}
/**
* Return site's privacy status.
*
* @return boolean Is site private?
*/
function is_private() {
return (int) $this->get_atomic_cloud_site_option( 'blog_public' ) === -1;
}
/**
* Return site's coming soon status.
*
* @return boolean Is site "Coming soon"?
*/
function is_coming_soon() {
return $this->is_private() && (int) $this->get_atomic_cloud_site_option( 'wpcom_coming_soon' ) === 1;
}
/**
* Return site's launch status.
*
* @return string|boolean Launch status ('launched', 'unlaunched', or false).
*/
function get_launch_status() {
return $this->get_atomic_cloud_site_option( 'launch-status' );
}
function get_atomic_cloud_site_option( $option ) {
if ( ! jetpack_is_atomic_site() ) {
return false;
}
$jetpack = Jetpack::init();
if ( ! method_exists( $jetpack, 'get_cloud_site_options' ) ) {
return false;
}
$result = $jetpack->get_cloud_site_options( [ $option ] );
if ( ! array_key_exists( $option, $result ) ) {
return false;
}
return $result[ $option ];
}
function get_plan() {
return false;
}
function get_subscribers_count() {
return 0; // special magic fills this in on the WPCOM side
}
function get_capabilities() {
return false;
}
function get_locale() {
return get_bloginfo( 'language' );
}
/**
* The flag indicates that the site has Jetpack installed
*
* @return bool
*/
public function is_jetpack() {
return true;
}
/**
* The flag indicates that the site is connected to WP.com via Jetpack Connection
*
* @return bool
*/
public function is_jetpack_connection() {
return true;
}
public function get_jetpack_version() {
return JETPACK__VERSION;
}
function get_ak_vp_bundle_enabled() {}
function get_jetpack_seo_front_page_description() {
return Jetpack_SEO_Utils::get_front_page_meta_description();
}
function get_jetpack_seo_title_formats() {
return Jetpack_SEO_Titles::get_custom_title_formats();
}
function get_verification_services_codes() {
return get_option( 'verification_services_codes', null );
}
function get_podcasting_archive() {
return null;
}
function is_connected_site() {
return true;
}
function is_wpforteams_site() {
return false;
}
function current_user_can( $role ) {
return current_user_can( $role );
}
/**
* Check if full site editing should be considered as currently active. Full site editing
* requires the FSE plugin to be installed and activated, as well the current
* theme to be FSE compatible. The plugin can also be explicitly disabled via the
* a8c_disable_full_site_editing filter.
*
* @since 7.7.0
*
* @return bool true if full site editing is currently active.
*/
function is_fse_active() {
if ( ! Jetpack::is_plugin_active( 'full-site-editing/full-site-editing-plugin.php' ) ) {
return false;
}
return function_exists( '\A8C\FSE\is_full_site_editing_active' ) && \A8C\FSE\is_full_site_editing_active();
}
/**
* Check if site should be considered as eligible for full site editing. Full site editing
* requires the FSE plugin to be installed and activated. For this method to return true
* the current theme does not need to be FSE compatible. The plugin can also be explicitly
* disabled via the a8c_disable_full_site_editing filter.
*
* @since 8.1.0
*
* @return bool true if site is eligible for full site editing
*/
public function is_fse_eligible() {
if ( ! Jetpack::is_plugin_active( 'full-site-editing/full-site-editing-plugin.php' ) ) {
return false;
}
return function_exists( '\A8C\FSE\is_site_eligible_for_full_site_editing' ) && \A8C\FSE\is_site_eligible_for_full_site_editing();
}
/**
* Check if site should be considered as eligible for use of the core Site Editor.
* The Site Editor requires the FSE plugin to be installed and activated.
* The plugin can be explicitly enabled via the a8c_enable_core_site_editor filter.
*
* @return bool true if site is eligible for the Site Editor
*/
public function is_core_site_editor_enabled() {
if ( ! Jetpack::is_plugin_active( 'full-site-editing/full-site-editing-plugin.php' ) ) {
return false;
}
return function_exists( '\A8C\FSE\is_site_editor_active' ) && \A8C\FSE\is_site_editor_active();
}
/**
* Return the last engine used for an import on the site.
*
* This option is not used in Jetpack.
*/
function get_import_engine() {
return null;
}
/**
* Post functions
*/
function wrap_post( $post, $context ) {
return new Jetpack_Post( $this, $post, $context );
}
}
| pjhooker/monferratopaesaggi | trunk/wp-content/plugins/jetpack/sal/class.json-api-site-jetpack.php | PHP | mit | 7,587 |
# Copyright (c) 2005 Zed A. Shaw
# You can redistribute it and/or modify it under the same terms as Ruby.
#
# Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html
# for more information.
require 'test/testhelp'
include Mongrel
class URIClassifierTest < Test::Unit::TestCase
def test_uri_finding
uri_classifier = URIClassifier.new
uri_classifier.register("/test", 1)
script_name, path_info, value = uri_classifier.resolve("/test")
assert_equal 1, value
assert_equal "/test", script_name
end
def test_root_handler_only
uri_classifier = URIClassifier.new
uri_classifier.register("/", 1)
script_name, path_info, value = uri_classifier.resolve("/test")
assert_equal 1, value
assert_equal "/", script_name
assert_equal "/test", path_info
end
def test_uri_prefix_ops
test = "/pre/fix/test"
prefix = "/pre"
uri_classifier = URIClassifier.new
uri_classifier.register(prefix,1)
script_name, path_info, value = uri_classifier.resolve(prefix)
script_name, path_info, value = uri_classifier.resolve(test)
assert_equal 1, value
assert_equal prefix, script_name
assert_equal test[script_name.length .. -1], path_info
assert uri_classifier.inspect
assert_equal prefix, uri_classifier.uris[0]
end
def test_not_finding
test = "/cant/find/me"
uri_classifier = URIClassifier.new
uri_classifier.register(test, 1)
script_name, path_info, value = uri_classifier.resolve("/nope/not/here")
assert_nil script_name
assert_nil path_info
assert_nil value
end
def test_exceptions
uri_classifier = URIClassifier.new
uri_classifier.register("/test", 1)
failed = false
begin
uri_classifier.register("/test", 1)
rescue => e
failed = true
end
assert failed
failed = false
begin
uri_classifier.register("", 1)
rescue => e
failed = true
end
assert failed
end
def test_register_unregister
uri_classifier = URIClassifier.new
100.times do
uri_classifier.register("/stuff", 1)
value = uri_classifier.unregister("/stuff")
assert_equal 1, value
end
uri_classifier.register("/things",1)
script_name, path_info, value = uri_classifier.resolve("/things")
assert_equal 1, value
uri_classifier.unregister("/things")
script_name, path_info, value = uri_classifier.resolve("/things")
assert_nil value
end
def test_uri_branching
uri_classifier = URIClassifier.new
uri_classifier.register("/test", 1)
uri_classifier.register("/test/this",2)
script_name, path_info, handler = uri_classifier.resolve("/test")
script_name, path_info, handler = uri_classifier.resolve("/test/that")
assert_equal "/test", script_name, "failed to properly find script off branch portion of uri"
assert_equal "/that", path_info
assert_equal 1, handler, "wrong result for branching uri"
end
def test_all_prefixing
tests = ["/test","/test/that","/test/this"]
uri = "/test/this/that"
uri_classifier = URIClassifier.new
current = ""
uri.each_byte do |c|
current << c.chr
uri_classifier.register(current, c)
end
# Try to resolve everything with no asserts as a fuzzing
tests.each do |prefix|
current = ""
prefix.each_byte do |c|
current << c.chr
script_name, path_info, handler = uri_classifier.resolve(current)
assert script_name
assert path_info
assert handler
end
end
# Assert that we find stuff
tests.each do |t|
script_name, path_info, handler = uri_classifier.resolve(t)
assert handler
end
# Assert we don't find stuff
script_name, path_info, handler = uri_classifier.resolve("chicken")
assert_nil handler
assert_nil script_name
assert_nil path_info
end
# Verifies that a root mounted ("/") handler resolves
# such that path info matches the original URI.
# This is needed to accommodate real usage of handlers.
def test_root_mounted
uri_classifier = URIClassifier.new
root = "/"
path = "/this/is/a/test"
uri_classifier.register(root, 1)
script_name, path_info, handler = uri_classifier.resolve(root)
assert_equal 1, handler
assert_equal root, path_info
assert_equal root, script_name
script_name, path_info, handler = uri_classifier.resolve(path)
assert_equal path, path_info
assert_equal root, script_name
assert_equal 1, handler
end
# Verifies that a root mounted ("/") handler
# is the default point, doesn't matter the order we use
# to register the URIs
def test_classifier_order
tests = ["/before", "/way_past"]
root = "/"
path = "/path"
uri_classifier = URIClassifier.new
uri_classifier.register(path, 1)
uri_classifier.register(root, 2)
tests.each do |uri|
script_name, path_info, handler = uri_classifier.resolve(uri)
assert_equal root, script_name, "#{uri} did not resolve to #{root}"
assert_equal uri, path_info
assert_equal 2, handler
end
end
if ENV['BENCHMARK']
# Eventually we will have a suite of benchmarks instead of lamely installing a test
def test_benchmark
# This URI set should favor a TST. Both versions increase linearly until you hit 14
# URIs, then the TST flattens out.
@uris = %w(
/
/dag /dig /digbark /dog /dogbark /dog/bark /dug /dugbarking /puppy
/c /cat /cat/tree /cat/tree/mulberry /cats /cot /cot/tree/mulberry /kitty /kittycat
# /eag /eig /eigbark /eog /eogbark /eog/bark /eug /eugbarking /iuppy
# /f /fat /fat/tree /fat/tree/mulberry /fats /fot /fot/tree/mulberry /jitty /jittyfat
# /gag /gig /gigbark /gog /gogbark /gog/bark /gug /gugbarking /kuppy
# /h /hat /hat/tree /hat/tree/mulberry /hats /hot /hot/tree/mulberry /litty /littyhat
# /ceag /ceig /ceigbark /ceog /ceogbark /ceog/cbark /ceug /ceugbarking /ciuppy
# /cf /cfat /cfat/ctree /cfat/ctree/cmulberry /cfats /cfot /cfot/ctree/cmulberry /cjitty /cjittyfat
# /cgag /cgig /cgigbark /cgog /cgogbark /cgog/cbark /cgug /cgugbarking /ckuppy
# /ch /chat /chat/ctree /chat/ctree/cmulberry /chats /chot /chot/ctree/cmulberry /citty /cittyhat
)
@requests = %w(
/
/dig
/digging
/dogging
/dogbarking/
/puppy/barking
/c
/cat
/cat/shrub
/cat/tree
/cat/tree/maple
/cat/tree/mulberry/tree
/cat/tree/oak
/cats/
/cats/tree
/cod
/zebra
)
@classifier = URIClassifier.new
@uris.each do |uri|
@classifier.register(uri, 1)
end
puts "#{@uris.size} URIs / #{@requests.size * 10000} requests"
Benchmark.bm do |x|
x.report do
# require 'ruby-prof'
# profile = RubyProf.profile do
10000.times do
@requests.each do |request|
@classifier.resolve(request)
end
end
# end
# File.open("profile.html", 'w') { |file| RubyProf::GraphHtmlPrinter.new(profile).print(file, 0) }
end
end
end
end
end
| claudiobm/ClockingIT-In-CapellaDesign | vendor/gems/mongrel-1.1.5/test/test_uriclassifier.rb | Ruby | mit | 7,361 |
require 'uri'
module Idobata::Hook
class PivotalTracker
module Helper
filters = [
::HTML::Pipeline::MarkdownFilter
]
filters << ::HTML::Pipeline::SyntaxHighlightFilter if defined?(Linguist) # This filter doesn't work on heroku
Pipeline = ::HTML::Pipeline.new(filters, gfm: true, base_url: 'https://www.pivotaltracker.com/')
def md(source)
result = Pipeline.call(source)
result[:output].to_s.html_safe
end
def new_value(kind)
new_values(kind).first
end
def new_values(kind)
payload.changes.select {|change| change.kind == kind.to_s }.map(&:new_values).compact
end
def download_url(attachment)
download_url = URI.parse(attachment.download_url)
# XXX Current API returns only path info.
unless download_url.host
download_url.scheme = 'https'
download_url.host = 'www.pivotaltracker.com'
end
download_url.query = {inline: true}.to_param unless download_url.query
download_url.to_s
end
end
end
end
| SuzukiMasashi/idobata-hooks | lib/hooks/pivotal_tracker/helper.rb | Ruby | mit | 1,098 |
import { __decorate } from 'tslib';
import { NgModule } from '@angular/core';
import { ANGULARTICS2_TOKEN, RouterlessTracking, Angulartics2, Angulartics2OnModule } from 'angulartics2';
var Angulartics2RouterlessModule_1;
let Angulartics2RouterlessModule = Angulartics2RouterlessModule_1 = class Angulartics2RouterlessModule {
static forRoot(settings = {}) {
return {
ngModule: Angulartics2RouterlessModule_1,
providers: [
{ provide: ANGULARTICS2_TOKEN, useValue: { settings } },
RouterlessTracking,
Angulartics2,
],
};
}
};
Angulartics2RouterlessModule = Angulartics2RouterlessModule_1 = __decorate([
NgModule({
imports: [Angulartics2OnModule],
})
], Angulartics2RouterlessModule);
export { Angulartics2RouterlessModule };
//# sourceMappingURL=angulartics2-routerlessmodule.js.map
| cdnjs/cdnjs | ajax/libs/angulartics2/8.3.0/routerlessmodule/fesm2015/angulartics2-routerlessmodule.js | JavaScript | mit | 907 |
/*******************************************************************************
* Copyright (c) 2012 David A Carlson.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David A Carlson (XMLmodeling.com) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.cts2.codesystem.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntry;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryDirectory;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryList;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryListEntry;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryMsg;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntrySummary;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemFactory;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemPackage;
import org.openhealthtools.mdht.cts2.codesystem.DocumentRoot;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
*
* @generated
*/
public class CodeSystemFactoryImpl extends EFactoryImpl implements CodeSystemFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public static CodeSystemFactory init() {
try {
CodeSystemFactory theCodeSystemFactory = (CodeSystemFactory) EPackage.Registry.INSTANCE.getEFactory("http://schema.omg.org/spec/CTS2/1.0/CodeSystem");
if (theCodeSystemFactory != null) {
return theCodeSystemFactory;
}
} catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new CodeSystemFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY:
return createCodeSystemCatalogEntry();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_DIRECTORY:
return createCodeSystemCatalogEntryDirectory();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_LIST:
return createCodeSystemCatalogEntryList();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_LIST_ENTRY:
return createCodeSystemCatalogEntryListEntry();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_MSG:
return createCodeSystemCatalogEntryMsg();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_SUMMARY:
return createCodeSystemCatalogEntrySummary();
case CodeSystemPackage.DOCUMENT_ROOT:
return createDocumentRoot();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntry createCodeSystemCatalogEntry() {
CodeSystemCatalogEntryImpl codeSystemCatalogEntry = new CodeSystemCatalogEntryImpl();
return codeSystemCatalogEntry;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryDirectory createCodeSystemCatalogEntryDirectory() {
CodeSystemCatalogEntryDirectoryImpl codeSystemCatalogEntryDirectory = new CodeSystemCatalogEntryDirectoryImpl();
return codeSystemCatalogEntryDirectory;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryList createCodeSystemCatalogEntryList() {
CodeSystemCatalogEntryListImpl codeSystemCatalogEntryList = new CodeSystemCatalogEntryListImpl();
return codeSystemCatalogEntryList;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryListEntry createCodeSystemCatalogEntryListEntry() {
CodeSystemCatalogEntryListEntryImpl codeSystemCatalogEntryListEntry = new CodeSystemCatalogEntryListEntryImpl();
return codeSystemCatalogEntryListEntry;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryMsg createCodeSystemCatalogEntryMsg() {
CodeSystemCatalogEntryMsgImpl codeSystemCatalogEntryMsg = new CodeSystemCatalogEntryMsgImpl();
return codeSystemCatalogEntryMsg;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntrySummary createCodeSystemCatalogEntrySummary() {
CodeSystemCatalogEntrySummaryImpl codeSystemCatalogEntrySummary = new CodeSystemCatalogEntrySummaryImpl();
return codeSystemCatalogEntrySummary;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public DocumentRoot createDocumentRoot() {
DocumentRootImpl documentRoot = new DocumentRootImpl();
return documentRoot;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemPackage getCodeSystemPackage() {
return (CodeSystemPackage) getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @deprecated
* @generated
*/
@Deprecated
public static CodeSystemPackage getPackage() {
return CodeSystemPackage.eINSTANCE;
}
} // CodeSystemFactoryImpl
| drbgfc/mdht | cts2/plugins/org.openhealthtools.mdht.cts2.core/src/org/openhealthtools/mdht/cts2/codesystem/impl/CodeSystemFactoryImpl.java | Java | epl-1.0 | 5,866 |
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.concepts.lang;
public interface Acceptor<I> {
/**
*
* @param input
* @return true if input is accepted.
*/
boolean isAcceptable(I input);
}
| xiaohanz/softcontroller | opendaylight/sal/yang-prototype/concepts-lang/src/main/java/org/opendaylight/controller/concepts/lang/Acceptor.java | Java | epl-1.0 | 516 |
/*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.git.exception;
/**
* @author Yossi Balan (yossi.balan@sap.com)
*/
public class GitInvalidRefNameException extends GitException {
/**
* Construct a new GitInvalidRefNameException based on message
*
* @param message
* error message
*/
public GitInvalidRefNameException(String message) {
super(message);
}
/**
* Construct a new GitInvalidRefNameException based on cause
*
* @param cause
* cause exception
*/
public GitInvalidRefNameException(Throwable cause) {
super(cause);
}
/**
* Construct a new GitInvalidRefNameException based on message and cause
*
* @param message
* error message
* @param cause
* cause exception
*/
public GitInvalidRefNameException(String message, Throwable cause) {
super(message, cause);
}
}
| kaloyan-raev/che | wsagent/che-core-api-git/src/main/java/org/eclipse/che/api/git/exception/GitInvalidRefNameException.java | Java | epl-1.0 | 1,446 |
/*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.javaee.jaxws;
import org.jboss.forge.addon.javaee.JavaEEFacet;
import org.jboss.forge.addon.projects.Project;
/**
* If installed, this {@link Project} supports features from the JAX-WS specification.
*
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*/
public interface JAXWSFacet extends JavaEEFacet
{
}
| agoncal/core | javaee/api/src/main/java/org/jboss/forge/addon/javaee/jaxws/JAXWSFacet.java | Java | epl-1.0 | 550 |
package io.liveoak.scripts.resourcetriggered.interceptor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import io.liveoak.common.DefaultResourceErrorResponse;
import io.liveoak.scripts.objects.Util;
import io.liveoak.scripts.objects.impl.exception.LiveOakException;
import io.liveoak.scripts.resourcetriggered.manager.ResourceScriptManager;
import io.liveoak.spi.Application;
import io.liveoak.spi.ResourceErrorResponse;
import io.liveoak.spi.ResourcePath;
import io.liveoak.spi.ResourceRequest;
import io.liveoak.spi.ResourceResponse;
import io.liveoak.spi.container.interceptor.DefaultInterceptor;
import io.liveoak.spi.container.interceptor.InboundInterceptorContext;
import io.liveoak.spi.container.interceptor.OutboundInterceptorContext;
import org.dynjs.exception.ThrowException;
/**
* @author <a href="mailto:mwringe@redhat.com">Matt Wringe</a>
*/
public class ScriptInterceptor extends DefaultInterceptor {
Map<String, ResourceScriptManager> managers;
private static final String DYNJS_ERROR_PREFIX = "Error: ";
public ScriptInterceptor() {
managers = new HashMap<>();
}
@Override
public void onInbound(InboundInterceptorContext context) throws Exception {
try {
String applicationName = getApplicationName(context.request());
ResourceScriptManager manager = managers.get(applicationName);
if (manager != null) {
Object reply = manager.executeScripts(context.request());
if (reply instanceof ResourceRequest) {
context.forward((ResourceRequest) reply);
} else if (reply instanceof ResourceResponse) {
context.replyWith((ResourceResponse) reply);
} else {
context.forward();
}
} else {
context.forward();
}
} catch (Exception e) {
e.printStackTrace();
String message = "Error processing request";
if (e.getMessage() != null && !e.getMessage().equals(DYNJS_ERROR_PREFIX)) {
message = e.getMessage();
if (message.startsWith(DYNJS_ERROR_PREFIX)) {
message = message.substring(DYNJS_ERROR_PREFIX.length());
context.replyWith(new DefaultResourceErrorResponse(context.request(), ResourceErrorResponse.ErrorType.INTERNAL_ERROR, message));
return;
}
} else if (e instanceof ThrowException) {
Object value = ((ThrowException)e).getValue();
if (value instanceof LiveOakException) {
context.replyWith(Util.getErrorResponse(context.request(), (LiveOakException)value));
return;
}
}
context.replyWith(new DefaultResourceErrorResponse(context.request(), ResourceErrorResponse.ErrorType.INTERNAL_ERROR, "Error processing script"));
}
}
@Override
public void onOutbound(OutboundInterceptorContext context) throws Exception {
try {
String applicationName = getApplicationName(context.response().inReplyTo());
ResourceScriptManager manager = managers.get(applicationName);
if (manager != null) {
Object reply = manager.executeScripts(context.response());
if (reply instanceof ResourceResponse) {
context.forward((ResourceResponse) reply);
} else {
context.forward();
}
} else {
context.forward();
}
} catch (Exception e) {
e.printStackTrace();
String message = "Error processing response";
//TODO: remove the "Error: " check here, its because DynJS for some reason uses a crappy empty error message.
if (e.getMessage() != null && !e.getMessage().equals(DYNJS_ERROR_PREFIX)) {
message = e.getMessage();
if (message.startsWith(DYNJS_ERROR_PREFIX)) {
message = message.substring(DYNJS_ERROR_PREFIX.length());
}
} else if (e instanceof ThrowException) {
Object value = ((ThrowException)e).getValue();
if (value instanceof LiveOakException) {
context.forward(Util.getErrorResponse(context.response().inReplyTo(), (LiveOakException)value));
return;
}
}
context.forward(new DefaultResourceErrorResponse(context.response().inReplyTo(), ResourceErrorResponse.ErrorType.INTERNAL_ERROR, "Error processing script"));
}
}
@Override
public void onComplete(UUID requestId) {
//currently do nothing.
}
private String getApplicationName(ResourceRequest request) {
//TODO: once we have the application actually being added to the requestContext remove getting the name from the ResourcePath
List<ResourcePath.Segment> resourcePaths = request.resourcePath().segments();
String applicationName = "/";
if (resourcePaths.size() > 0) {
applicationName = resourcePaths.get(0).name();
}
// TODO: This is proper way to check, but application is currently not set
Application application = request.requestContext().application();
if (application != null) {
applicationName = application.id();
}
return applicationName;
}
public void addManager(String applicationName, ResourceScriptManager manager) {
managers.put(applicationName, manager);
}
public void removeManager(String applicationName) {
managers.remove(applicationName);
}
}
| liveoak-io/liveoak | modules/scripts/src/main/java/io/liveoak/scripts/resourcetriggered/interceptor/ScriptInterceptor.java | Java | epl-1.0 | 5,830 |
define(['events', 'libraryBrowser', 'imageLoader', 'listView', 'emby-itemscontainer'], function (events, libraryBrowser, imageLoader, listView) {
return function (view, params, tabContent) {
var self = this;
var data = {};
function getPageData(context) {
var key = getSavedQueryKey(context);
var pageData = data[key];
if (!pageData) {
pageData = data[key] = {
query: {
SortBy: "Album,SortName",
SortOrder: "Ascending",
IncludeItemTypes: "Audio",
Recursive: true,
Fields: "AudioInfo,ParentId",
Limit: 100,
StartIndex: 0,
ImageTypeLimit: 1,
EnableImageTypes: "Primary"
}
};
pageData.query.ParentId = params.topParentId;
libraryBrowser.loadSavedQueryValues(key, pageData.query);
}
return pageData;
}
function getQuery(context) {
return getPageData(context).query;
}
function getSavedQueryKey(context) {
if (!context.savedQueryKey) {
context.savedQueryKey = libraryBrowser.getSavedQueryKey('songs');
}
return context.savedQueryKey;
}
function reloadItems(page) {
Dashboard.showLoadingMsg();
var query = getQuery(page);
ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) {
// Scroll back up so they can see the results from the beginning
window.scrollTo(0, 0);
updateFilterControls(page);
var pagingHtml = LibraryBrowser.getQueryPagingHtml({
startIndex: query.StartIndex,
limit: query.Limit,
totalRecordCount: result.TotalRecordCount,
showLimit: false,
updatePageSizeSetting: false,
addLayoutButton: false,
sortButton: false,
filterButton: false
});
var html = listView.getListViewHtml({
items: result.Items,
action: 'playallfromhere',
smallIcon: true
});
var i, length;
var elems = tabContent.querySelectorAll('.paging');
for (i = 0, length = elems.length; i < length; i++) {
elems[i].innerHTML = pagingHtml;
}
function onNextPageClick() {
query.StartIndex += query.Limit;
reloadItems(tabContent);
}
function onPreviousPageClick() {
query.StartIndex -= query.Limit;
reloadItems(tabContent);
}
elems = tabContent.querySelectorAll('.btnNextPage');
for (i = 0, length = elems.length; i < length; i++) {
elems[i].addEventListener('click', onNextPageClick);
}
elems = tabContent.querySelectorAll('.btnPreviousPage');
for (i = 0, length = elems.length; i < length; i++) {
elems[i].addEventListener('click', onPreviousPageClick);
}
var itemsContainer = tabContent.querySelector('.itemsContainer');
itemsContainer.innerHTML = html;
imageLoader.lazyChildren(itemsContainer);
libraryBrowser.saveQueryValues(getSavedQueryKey(page), query);
Dashboard.hideLoadingMsg();
});
}
self.showFilterMenu = function () {
require(['components/filterdialog/filterdialog'], function (filterDialogFactory) {
var filterDialog = new filterDialogFactory({
query: getQuery(tabContent),
mode: 'songs'
});
Events.on(filterDialog, 'filterchange', function () {
getQuery(tabContent).StartIndex = 0;
reloadItems(tabContent);
});
filterDialog.show();
});
}
function updateFilterControls(tabContent) {
}
function initPage(tabContent) {
tabContent.querySelector('.btnFilter').addEventListener('click', function () {
self.showFilterMenu();
});
tabContent.querySelector('.btnSort').addEventListener('click', function (e) {
libraryBrowser.showSortMenu({
items: [{
name: Globalize.translate('OptionTrackName'),
id: 'Name'
},
{
name: Globalize.translate('OptionAlbum'),
id: 'Album,SortName'
},
{
name: Globalize.translate('OptionAlbumArtist'),
id: 'AlbumArtist,Album,SortName'
},
{
name: Globalize.translate('OptionArtist'),
id: 'Artist,Album,SortName'
},
{
name: Globalize.translate('OptionDateAdded'),
id: 'DateCreated,SortName'
},
{
name: Globalize.translate('OptionDatePlayed'),
id: 'DatePlayed,SortName'
},
{
name: Globalize.translate('OptionPlayCount'),
id: 'PlayCount,SortName'
},
{
name: Globalize.translate('OptionReleaseDate'),
id: 'PremiereDate,AlbumArtist,Album,SortName'
},
{
name: Globalize.translate('OptionRuntime'),
id: 'Runtime,AlbumArtist,Album,SortName'
}],
callback: function () {
getQuery(tabContent).StartIndex = 0;
reloadItems(tabContent);
},
query: getQuery(tabContent),
button: e.target
});
});
}
self.getCurrentViewStyle = function () {
return getPageData(tabContent).view;
};
initPage(tabContent);
self.renderTab = function () {
reloadItems(tabContent);
updateFilterControls(tabContent);
};
self.destroy = function () {
};
};
}); | 7illusions/Emby | MediaBrowser.WebDashboard/dashboard-ui/scripts/songs.js | JavaScript | gpl-2.0 | 7,309 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* 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 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
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "common/config-manager.h"
#include "engines/advancedDetector.h"
#include "base/plugins.h"
#include "tucker/detection.h"
static const PlainGameDescriptor tuckerGames[] = {
{ "tucker", "Bud Tucker in Double Trouble" },
{ nullptr, nullptr }
};
static const ADGameDescription tuckerGameDescriptions[] = {
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "f1e42a95972643462b9c3c2ea79d6683", 543),
Common::FR_FRA,
Common::kPlatformDOS,
Tucker::kGameFlagNoSubtitles,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "9c1ddeafc5283b90d1a284bd0924831c", 462),
Common::EN_ANY,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "1b3ea79d8528ea3c7df83dd0ed345e37", 525),
Common::ES_ESP,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobrgr.txt", "4df9eb65722418d1a1723508115b146c", 552),
Common::DE_DEU,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "5f85285bbc23ce57cbc164021ee1f23c", 525),
Common::PL_POL,
Common::kPlatformDOS,
0,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "e548994877ff31ca304f6352ce022a8e", 497),
Common::CZ_CZE,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{ // Russian fan translation
"tucker",
"",
AD_ENTRY1s("infobrgr.txt", "4b5a315e449a7f9eaf2025ec87466cd8", 552),
Common::RU_RUS,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"Demo",
AD_ENTRY1s("infobar.txt", "010b055de42097b140d5bcb6e95a5c7c", 203),
Common::EN_ANY,
Common::kPlatformDOS,
ADGF_DEMO | Tucker::kGameFlagDemo,
GUIO1(GUIO_NOMIDI)
},
AD_TABLE_END_MARKER
};
static const ADGameDescription tuckerDemoGameDescription = {
"tucker",
"Non-Interactive Demo",
AD_ENTRY1(0, 0),
Common::EN_ANY,
Common::kPlatformDOS,
ADGF_DEMO | Tucker::kGameFlagDemo | Tucker::kGameFlagIntroOnly,
GUIO1(GUIO_NOMIDI)
};
class TuckerMetaEngineDetection : public AdvancedMetaEngineDetection {
public:
TuckerMetaEngineDetection() : AdvancedMetaEngineDetection(tuckerGameDescriptions, sizeof(ADGameDescription), tuckerGames) {
_md5Bytes = 512;
}
const char *getEngineId() const override {
return "tucker";
}
const char *getName() const override {
return "Bud Tucker in Double Trouble";
}
const char *getOriginalCopyright() const override {
return "Bud Tucker in Double Trouble (C) Merit Studios";
}
ADDetectedGame fallbackDetect(const FileMap &allFiles, const Common::FSList &fslist) const override {
for (Common::FSList::const_iterator d = fslist.begin(); d != fslist.end(); ++d) {
Common::FSList audiofslist;
if (d->isDirectory() && d->getName().equalsIgnoreCase("audio") && d->getChildren(audiofslist, Common::FSNode::kListFilesOnly)) {
for (Common::FSList::const_iterator f = audiofslist.begin(); f != audiofslist.end(); ++f) {
if (!f->isDirectory() && f->getName().equalsIgnoreCase("demorolc.raw")) {
return ADDetectedGame(&tuckerDemoGameDescription);
}
}
}
}
return ADDetectedGame();
}
};
REGISTER_PLUGIN_STATIC(TUCKER_DETECTION, PLUGIN_TYPE_ENGINE_DETECTION, TuckerMetaEngineDetection);
| somaen/scummvm | engines/tucker/detection.cpp | C++ | gpl-2.0 | 4,298 |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
namespace Lib.JSON
{
/// <summary>
/// Specifies the type of Json token.
/// </summary>
public enum JsonToken
{
/// <summary>
/// This is returned by the <see cref="JsonReader"/> if a <see cref="JsonReader.Read"/> method has not been called.
/// </summary>
None,
/// <summary>
/// An object start token.
/// </summary>
StartObject,
/// <summary>
/// An array start token.
/// </summary>
StartArray,
/// <summary>
/// A constructor start token.
/// </summary>
StartConstructor,
/// <summary>
/// An object property name.
/// </summary>
PropertyName,
/// <summary>
/// A comment.
/// </summary>
Comment,
/// <summary>
/// Raw JSON.
/// </summary>
Raw,
/// <summary>
/// An integer.
/// </summary>
Integer,
/// <summary>
/// A float.
/// </summary>
Float,
/// <summary>
/// A string.
/// </summary>
String,
/// <summary>
/// A boolean.
/// </summary>
Boolean,
/// <summary>
/// A null token.
/// </summary>
Null,
/// <summary>
/// An undefined token.
/// </summary>
Undefined,
/// <summary>
/// An object end token.
/// </summary>
EndObject,
/// <summary>
/// An array end token.
/// </summary>
EndArray,
/// <summary>
/// A constructor end token.
/// </summary>
EndConstructor,
/// <summary>
/// A Date.
/// </summary>
Date,
/// <summary>
/// Byte data.
/// </summary>
Bytes
}
} | MyvarHD/OpenIDE | OpenIDE/OpenIDE.Library/Base/JSON/JsonToken.cs | C# | gpl-2.0 | 2,797 |
var armorSetPvPSuperior = new armorSetObject("pvpsuperior");
armorSetPvPSuperior.slotsArray = new Array();
t = 0;
armorSetPvPSuperior.slotsArray[t] = "head"; t++;
armorSetPvPSuperior.slotsArray[t] = "shoulder"; t++;
armorSetPvPSuperior.slotsArray[t] = "chest"; t++;
armorSetPvPSuperior.slotsArray[t] = "hands"; t++;
armorSetPvPSuperior.slotsArray[t] = "legs"; t++;
armorSetPvPSuperior.slotsArray[t] = "feet"; t++;
armorSetPvPSuperior.slotsNumber = armorSetPvPSuperior.slotsArray.length;
armorSetPvPSuperior.statsArray = new Array();
armorSetPvPSuperior.itemNameArray = new Array();
armorSetPvPSuperior.setNameArray = new Array();
t = 0;
armorSetPvPSuperior.setNamesArray = new Array();
x = 0;
armorSetPvPSuperior.setNamesArray[x] = "Refuge"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Pursuance"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Arcanum"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Redoubt"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Investiture"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Guard"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Stormcaller"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Dreadgear"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Battlearmor"; x++;
classCounter = 0;
//DONT LOCALIZE ABOVE THIS COMMENT LINE
//LOCALIZE EVERYTHING BELOW THIS COMMENT LINE
//druid begin
var sanctuaryBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power<br>\
(4) Set: Increases your movement speed by 15% while in Bear, Cat, or Travel Form. Only active outdoors.<br>\
(6) Set: +20 Stamina\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Refuge (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Dragonhide Shoulders<br>\
Lieutenant Commander\'s Dragonhide Headguard<br>\
Knight-Captain\'s Dragonhide Leggings<br>\
Knight-Captain\'s Dragonhide Chestpiece<br>\
Knight-Lieutenant\'s Dragonhide Treads<br>\
Knight-Lieutenant\'s Dragonhide Grips<br>\
</span>'+ sanctuaryBlue, '<span class = "myYellow">\
Champion\'s Refuge (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Dragonhide Treads<br>\
Blood Guard\'s Dragonhide Grips<br>\
Legionnaire\'s Dragonhide Chestpiece<br>\
Legionnaire\'s Dragonhide Leggings<br>\
Champion\'s Dragonhide Headguard<br>\
Champion\'s Dragonhide Shoulders<br>\
</span>'+ sanctuaryBlue];
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dragonhide Headguard', '<span class = "myBlue">\
Champion\'s Dragonhide Headguard'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
198 Armor<br>\
+16 Strength<br>\
+12 Agility<br>\
+16 Stamina<br>\
+16 Intellect<br>\
+8 Spirit<br>\
Classes: Druid<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dragonhide Shoulders', '<span class = "myBlue">\
Champion\'s Dragonhide Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
206 Armor<br>\
+12 Strength<br>\
+6 Agility<br>\
+12 Stamina<br>\
+12 Intellect<br>\
+6 Spirit<br>\
Classes: Druid<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dragonhide Chestpiece', '<span class = "myBlue">\
Legionnaire\'s Dragonhide Chestpiece'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
218 Armor<br>\
+13 Strength<br>\
+12 Agility<br>\
+13 Stamina<br>\
+12 Intellect<br>\
Classes: Druid<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 15.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dragonhide Grips', '<span class = "myBlue">\
Blood Guard\'s Dragonhide Grips'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
115 Armor<br>\
+13 Strength<br>\
+10 Agility<br>\
+12 Stamina<br>\
+9 Intellect<br>\
Classes: Druid<br>\
Durability 35/35<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Slightly increases your stealth detection.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dragonhide Leggings', '<span class = "myBlue">\
Legionnaire\'s Dragonhide Leggings'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
215 Armor<br>\
+12 Strength<br>\
+12 Agility<br>\
+12 Stamina<br>\
+12 Intellect<br>\
+5 Spirit<br>\
Classes: Druid<br>\
Durability 75/75<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 14.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dragonhide Treads', '<span class = "myBlue">\
Blood Guard\'s Dragonhide Treads'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
126 Armor<br>\
+13 Strength<br>\
+6 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
+6 Spirit<br>\
Classes: Druid<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.</span>\
<p>';
//druid end
classCounter++;
//hunter begin
var pursuitBlue = '<span class = "myGreen">\
(2) Set: +20 Agility.<br>\
(4) Set: Reduces the cooldown of your Concussive Shot by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Pursuance (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Chain Shoulders<br>\
Lieutenant Commander\'s Chain Helm<br>\
Knight-Captain\'s Chain Legguards<br>\
Knight-Captain\'s Chain Hauberk<br>\
Knight-Lieutenant\'s Chain Greaves<br>\
Knight-Lieutenant\'s Chain Vices<br>\
</span>'+ pursuitBlue, '<span class = "myYellow">\
Champion\'s Pursuance (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Chain Greaves<br>\
Blood Guard\'s Chain Vices<br>\
Legionnaire\'s Chain Hauberk<br>\
Legionnaire\'s Chain Legguards<br>\
Champion\'s Chain Helm<br>\
Champion\'s Chain Shoulders<br>\
</span>'+ pursuitBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Chain Helm', '<span class = "myBlue">\
Champion\'s Chain Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
337 Armor<br>\
+18 Agility<br>\
+14 Stamina<br>\
+9 Intellect<br>\
Classes: Hunter<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Chain Shoulders', '<span class = "myBlue">\
Champion\'s Chain Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
311 Armor<br>\
+18 Agility<br>\
+13 Stamina<br>\
Classes: Hunter<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Chain Hauberk', '<span class = "myBlue">\
Legionnaire\'s Chain Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
398 Armor<br>\
+16 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
Classes: Hunter<br>\
Durability 120/120<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Chain Vices', '<span class = "myBlue">\
Blood Guard\'s Chain Vices'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
242 Armor<br>\
+18 Agility<br>\
+16 Stamina<br>\
Classes: Hunter<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage done by your Multi-Shot by 4%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Chain Legguards', '<span class = "myBlue">\
Legionnaire\'s Chain Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
348 Armor<br>\
+16 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
Classes: Hunter<br>\
Durability 90/90<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Chain Greaves', '<span class = "myBlue">\
Blood Guard\'s Chain Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
266 Armor<br>\
+20 Agility<br>\
+19 Stamina<br>\
Classes: Hunter<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 7\
<span class = "myGreen">\
</span>\
<p>';
//hunter end
classCounter++;
//mage begin
var regaliaBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the cooldown of your Blink spell by 1.5 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Arcanum (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Silk Mantle<br>\
Lieutenant Commander\'s Silk Cowl<br>\
Knight-Captain\'s Silk Legguards<br>\
Knight-Captain\'s Silk Tunic<br>\
Knight-Lieutenant\'s Silk Walkers<br>\
Knight-Lieutenant\'s Silk Handwraps<br>\
</span>'+ regaliaBlue, '<span class = "myYellow">\
Champion\'s Arcanum (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Silk Walkers<br>\
Blood Guard\'s Silk Handwraps<br>\
Legionnaire\'s Silk Tunic<br>\
Legionnaire\'s Silk Legguards<br>\
Champion\'s Silk Cowl<br>\
Champion\'s Silk Mantle<br>\
</span>'+ regaliaBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Silk Cowl', '<span class = "myBlue">\
Champion\'s Silk Cowl'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
141 Armor<br>\
+19 Stamina<br>\
+18 Intellect<br>\
+6 Spirit<br>\
Classes: Mage<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Silk Mantle', '<span class = "myBlue">\
Champion\'s Silk Mantle'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
135 Armor<br>\
+14 Stamina<br>\
+11 Intellect<br>\
+4 Spirit<br>\
Classes: Mage<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equp: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Silk Tunic', '<span class = "myBlue">\
Legionnaires\'s Silk Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
156 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
+5 Spirit<br>\
Classes: Mage<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Silk Handwraps', '<span class = "myBlue">\
Blood Guard\'s Silk Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
98 Armor<br>\
+12 Stamina<br>\
+10 Intellect<br>\
Classes: Mage<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage absorbed by your Mana Shield by 285.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Silk Legguards', '<span class = "myBlue">\
Legionnaire\'s Silk Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
144 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
+5 Spirit<br>\
Classes: Mage<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Silk Walkers', '<span class = "myBlue">\
Blood Guard\'s Silk Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
104 Armor<br>\
+15 Stamina<br>\
+10 Intellect<br>\
Classes: Mage<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equip: Improves your chance to hit with spells by 1%.</span>\
<p>';
//mage end
classCounter++;
//paladin begin
var aegisBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the cooldown of your Hammer of Justice by 10 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Redoubt (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Lamellar Shoulders<br>\
Lieutenant Commander\'s Lamellar Headguard<br>\
Knight-Captain\'s Lamellar Leggings<br>\
Knight-Captain\'s Lamellar Breastplate<br>\
Knight-Lieutenant\'s Lamellar Sabatons<br>\
Knight-Lieutenant\'s Lamellar Gauntlets<br>\
</span>'+ aegisBlue, ''];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Lamellar Headguard', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
598 Armor<br>\
+18 Strength<br>\
+19 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Increases damage and healing done by magical spells and effects by up to 26.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Lamellar Shoulders', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
552 Armor<br>\
+14 Strength<br>\
+14 Stamina<br>\
+8 Intellect<br>\
Classes: Paladin<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 20.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Lamellar Breastplate', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
706 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 135/135<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Lamellar Gauntlets', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
429 Armor<br>\
+12 Strength<br>\
+13 Stamina<br>\
Classes: Paladin<br>\
Durability 45/45<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the Holy damage bonus of your Judgement of the Crusader by 10.<br>\
Equip: Improves your chance to get a critical strike by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Lamellar Leggings', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
618 Armor<br>\
+18 Strength<br>\
+17 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Lamellar Sabatons', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
472 Armor<br>\
+12 Strength<br>\
+12 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.\
</span>\
<p>';
//Paladin end
classCounter++;
//priest begin
var raimentBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Increases the duration of your Psychic Scream spell by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Investiture (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Satin Mantle<br>\
Lieutenant Commander\'s Satin Hood<br>\
Knight-Captain\'s Satin Legguards<br>\
Knight-Captain\'s Satin Tunic<br>\
Knight-Lieutenant\'s Satin Walkers<br>\
Knight-Lieutenant\'s Satin Handwraps<br>\
</span>'+ raimentBlue, '<span class = "myYellow">\
Champion\'s Investiture (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Satin Walkers<br>\
Blood Guard\'s Satin Handwraps<br>\
Legionnaire\'s Satin Tunic<br>\
Legionnaire\'s Satin Legguards<br>\
Champion\'s Satin Hood<br>\
Champion\'s Satin Mantle<br>\
</span>'+ raimentBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Satin Hood', '<span class = "myBlue">\
Champion\'s Satin Hood'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
131 Armor<br>\
+20 Stamina<br>\
+18 Intellect<br>\
Classes: Priest<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Satin Mantle', '<span class = "myBlue">\
Champion\'s Satin Mantle'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
115 Armor<br>\
+14 Stamina<br>\
+12 Intellect<br>\
Classes: Priest<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 16.<br>\
Equip: Restores 6 mana per 5 sec.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Satin Tunic', '<span class = "myBlue">\
Legionnaire\'s Satin Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
156 Armor<br>\
+19 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Satin Handwraps', '<span class = "myBlue">\
Blood Guard\'s Satin Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
98 Armor<br>\
+12 Stamina<br>\
+5 Intellect<br>\
Classes: Priest<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Gives you a 50% chance to avoid interruption caused by damage while casting Mind Blast.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Satin Legguards', '<span class = "myBlue">\
Legionnaire\'s Satin Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
144 Armor<br>\
+19 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Satin Walkers', '<span class = "myBlue">\
Blood Guard\'s Satin Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
64 Armor<br>\
+17 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.</span>\
<p>';
//priest end
classCounter++;
//rogue begin
var vestmentsBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Reduces the cooldown of your Gouge ability by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Guard (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Leather Helm<br>\
Lieutenant Commander\'s Leather Shoulders<br>\
Knight-Captain\'s Leather Legguards<br>\
Knight-Captain\'s Leather Chestpiece<br>\
Knight-Lieutenant\'s Leather Walkers<br>\
Knight-Lieutenant\'s Leather Grips<br>\
</span>'+ vestmentsBlue, '<span class = "myYellow">\
Champion\'s Guard (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Leather Walkers<br>\
Blood Guard\'s Leather Grips<br>\
Legionnaire\'s Leather Chestpiece<br>\
Legionnaire\'s Leather Legguards<br>\
Champion\'s Leather Helm<br>\
Champion\'s Leather Shoulders<br>\
</span>'+ vestmentsBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Leather Helm', '<span class = "myBlue">\
Champion\'s Leather Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
238 Armor<br>\
+23 Stamina<br>\
Classes: Rogue<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: +36 Attack Power.<br>\
Equip: Improves your chance to hit by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Leather Shoulders', '<span class = "myBlue">\
Champion\'s Leather Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
196 Armor<br>\
+17 Stamina<br>\
Classes: Rogue<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: +22 Attack Power.<br>\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Leather Chestpiece', '<span class = "myBlue">\
Legionnaire\'s Leather Chestpiece'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
248 Armor<br>\
+22 Stamina<br>\
Classes: Rogue<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.<br>\
Equip: +34 Attack Power.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Leather Grips', '<span class = "myBlue">\
Blood Guard\'s Leather Grips'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
155 Armor<br>\
+18 Stamina<br>\
Classes: Rogue<br>\
Durability 35/35<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: +20 Attack Power.<br>\
Equip: Improves your chance to get a critical strike by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Leather Legguards', '<span class = "myBlue">\
Legionnaire\'s Leather Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
225 Armor<br>\
+22 Stamina<br>\
Classes: Rogue<br>\
Durability 75/75<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.<br>\
Equip: +34 Attack Power.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Leather Walkers', '<span class = "myBlue">\
Blood Guard\'s Leather Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
166 Armor<br>\
+18 Stamina<br>\
Classes: Rogue<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the duration of your Sprint ability by 3 sec.<br>\
Equip: +28 Attack Power.\
</span>\
<p>';
//Rogue end
classCounter++;
//shaman begin
var earthshakerBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Improves your chance to get a critical strike with all Shock spells by 2%.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['', '<span class = "myYellow">\
Champion\'s Stormcaller (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Mail Greaves<br>\
Blood Guard\'s Mail Vices<br>\
Legionnaire\'s Mail Hauberk<br>\
Legionnaire\'s Mail Legguards<br>\
Champion\'s Mail Headguard<br>\
Champion\'s Mail Pauldrons<br>\
</span>'+ earthshakerBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Champion\'s Mail Headguard'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
337 Armor<br>\
+6 Strength<br>\
+24 Stamina<br>\
+16 Intellect<br>\
Classes: Shaman<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Champion\'s Mail Pauldrons'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
311 Armor<br>\
+5 Strength<br>\
+16 Stamina<br>\
+10 Intellect<br>\
Classes: Shaman<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Legionnaire\'s Mail Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
398 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
+18 Intellect<br>\
Classes: Shaman<br>\
Durability 120/120<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Blood Guard\'s Mail Vices'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
242 Armor<br>\
+15 Stamina<br>\
+9 Intellect<br>\
Classes: Shaman<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 13.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Legionnaire\'s Mail Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
348 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
Classes: Shaman<br>\
Durability 90/90<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Blood Guard\'s Mail Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
266 Armor<br>\
+13 Strength<br>\
+14 Stamina<br>\
+12 Intellect<br>\
Classes: Shaman<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the speed of your Ghost Wolf ability by 15%.</span>\
<p>';
//Shaman end
classCounter++;
//warlock begin
var threadsBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the casting time of your Immolate spell by 0.2 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Dreadgear (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Dreadweave Spaulders<br>\
Lieutenant Commander\'s Dreadweave Cowl<br>\
Knight-Captain\'s Dreadweave Legguards<br>\
Knight-Captain\'s Dreadweave Tunic<br>\
Knight-Lieutenant\'s Dreadweave Walkers<br>\
Knight-Lieutenant\'s Dreadweave Handwraps<br>\
</span>'+ threadsBlue, '<span class = "myYellow">\
Champion\'s Dreadgear (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Dreadweave Walkers<br>\
Blood Guard\'s Dreadweave Handwraps<br>\
Legionnaire\'s Dreadweave Tunic<br>\
Legionnaire\'s Dreadweave Legguards<br>\
Champion\'s Dreadweave Cowl<br>\
Champion\'s Dreadweave Spaulders<br>\
</span>'+ threadsBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dreadweave Cowl', '<span class = "myBlue">\
Champion\'s Dreadweave Cowl'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
81 Armor<br>\
+21 Stamina<br>\
+18 Intellect<br>\
Classes: Warlock<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dreadweave Spaulders', '<span class = "myBlue">\
Champion\'s Dreadweave Spaulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
75 Armor<br>\
+17 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 12.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dreadweave Tunic', '<span class = "myBlue">\
Legionnaire\'s Dreadweave Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
96 Armor<br>\
+20 Stamina<br>\
+20 Intellect<br>\
Classes: Warlock<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dreadweave Handwraps', '<span class = "myBlue">\
Blood Guard\'s Dreadweave Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
58 Armor<br>\
+14 Stamina<br>\
+4 Intellect<br>\
Classes: Warlock<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage dealt and health regained by your Death Coil spell by 8%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dreadweave Legguards', '<span class = "myBlue">\
Legionnaire\'s Dreadweave Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
84 Armor<br>\
+21 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 28.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dreadweave Walkers', '<span class = "myBlue">\
Blood Guard\'s Dreadweave Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
64 Armor<br>\
+17 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
//Warlock end
classCounter++;
//warrior begin
var battlegearBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Reduces the cooldown of your Intercept ability by 5 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Battlearmor (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Plate Shoulders<br>\
Lieutenant Commander\'s Plate Helm<br>\
Knight-Captain\'s Plate Leggings<br>\
Knight-Captain\'s Plate Hauberk<br>\
Knight-Lieutenant\'s Plate Greaves<br>\
Knight-Lieutenant\'s Plate Gauntlets<br>\
</span>'+ battlegearBlue, '<span class = "myYellow">\
Champion\'s Battlearmor (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Plate Greaves<br>\
Blood Guard\'s Plate Gauntlets<br>\
Legionnaire\'s Plate Hauberk<br>\
Legionnaire\'s Plate Leggings<br>\
Champion\'s Plate Helm<br>\
Champion\'s Plate Shoulders<br>\
</span>'+ battlegearBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Plate Helm', '<span class = "myBlue">\
Champion\'s Plate Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
598 Armor<br>\
+21 Strength<br>\
+24 Stamina<br>\
Classes: Warrior<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Plate Shoulders', '<span class = "myBlue">\
Champion\'s Plate Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
552 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
Classes: Warrior<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Plate Hauberk', '<span class = "myBlue">\
Legionnaire\'s Plate Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
706 Armor<br>\
+21 Strength<br>\
+23 Stamina<br>\
Classes: Warrior<br>\
Durability 135/135<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Plate Gauntlets', '<span class = "myBlue">\
Blood Guard\'s Plate Gauntlets'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
429 Armor<br>\
+17 Strength<br>\
+17 Stamina<br>\
Classes: Warrior<br>\
Durability 45/45<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Hamstring Rage cost reduced by 3.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Plate Leggings', '<span class = "myBlue">\
Legionnaire\'s Plate Leggings'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
618 Armor<br>\
+12 Strength<br>\
+17 Stamina<br>\
Classes: Warrior<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant Plate Greaves', '<span class = "myBlue">\
Blood Guard\'s Plate Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
472 Armor<br>\
+10 Strength<br>\
+9 Agility<br>\
+23 Stamina<br>\
Classes: Warrior<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 7\
<span class = "myGreen">\
</span>\
<p>';
//Warrior end
armorSetsArray[theArmorSetCounter] = armorSetPvPSuperior;
armorSetsValues[theArmorSetCounter] = "pvpsuperior";
theArmorSetCounter++;
| borgotech/Infinity_MaNGOS | sql/Tools & Optional/Websites/I_CSwowd/pvpmini/shared/wow-com/includes-client/armorsets/en/pvpsuperior.js | JavaScript | gpl-2.0 | 49,796 |
<?php
/**
* The Footer widget areas.
*
* @package Pilcrow
* @since Pilcrow 1.0
*/
?>
<?php
/* The footer widget area is triggered if any of the areas
* have widgets. So let's check that first.
*
* If none of the sidebars have widgets, then let's bail early.
*/
if ( ! is_active_sidebar( 'sidebar-4' )
&& ! is_active_sidebar( 'sidebar-5' )
)
return;
// If we get this far, we have widgets. Let's do this.
?>
<div id="footer-widget-area" role="complementary">
<?php if ( is_active_sidebar( 'sidebar-4' ) ) : ?>
<div id="first" class="widget-area">
<ul class="xoxo sidebar-list">
<?php dynamic_sidebar( 'sidebar-4' ); ?>
</ul>
</div><!-- #first .widget-area -->
<?php endif; ?>
<?php if ( is_active_sidebar( 'sidebar-5' ) ) : ?>
<div id="second" class="widget-area">
<ul class="xoxo sidebar-list">
<?php dynamic_sidebar( 'sidebar-5' ); ?>
</ul>
</div><!-- #second .widget-area -->
<?php endif; ?>
</div><!-- #footer-widget-area -->
| mearleycf/boltgun2 | wp-content/themes/pilcrow/sidebar-footer.php | PHP | gpl-2.0 | 1,009 |
var _ = require('../util')
var config = require('../config')
var Dep = require('./dep')
var arrayMethods = require('./array')
var arrayKeys = Object.getOwnPropertyNames(arrayMethods)
require('./object')
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*
* @param {Array|Object} value
* @constructor
*/
function Observer (value) {
this.value = value
this.active = true
this.deps = []
_.define(value, '__ob__', this)
if (_.isArray(value)) {
var augment = config.proto && _.hasProto
? protoAugment
: copyAugment
augment(value, arrayMethods, arrayKeys)
this.observeArray(value)
} else {
this.walk(value)
}
}
// Static methods
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*
* @param {*} value
* @param {Vue} [vm]
* @return {Observer|undefined}
* @static
*/
Observer.create = function (value, vm) {
var ob
if (
value &&
value.hasOwnProperty('__ob__') &&
value.__ob__ instanceof Observer
) {
ob = value.__ob__
} else if (
_.isObject(value) &&
!Object.isFrozen(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (ob && vm) {
ob.addVm(vm)
}
return ob
}
/**
* Set the target watcher that is currently being evaluated.
*
* @param {Watcher} watcher
*/
Observer.setTarget = function (watcher) {
Dep.target = watcher
}
// Instance methods
var p = Observer.prototype
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object. Properties prefixed with `$` or `_`
* and accessor properties are ignored.
*
* @param {Object} obj
*/
p.walk = function (obj) {
var keys = Object.keys(obj)
var i = keys.length
var key, prefix
while (i--) {
key = keys[i]
prefix = key.charCodeAt(0)
if (prefix !== 0x24 && prefix !== 0x5F) { // skip $ or _
this.convert(key, obj[key])
}
}
}
/**
* Try to carete an observer for a child value,
* and if value is array, link dep to the array.
*
* @param {*} val
* @return {Dep|undefined}
*/
p.observe = function (val) {
return Observer.create(val)
}
/**
* Observe a list of Array items.
*
* @param {Array} items
*/
p.observeArray = function (items) {
var i = items.length
while (i--) {
this.observe(items[i])
}
}
/**
* Convert a property into getter/setter so we can emit
* the events when the property is accessed/changed.
*
* @param {String} key
* @param {*} val
*/
p.convert = function (key, val) {
var ob = this
var childOb = ob.observe(val)
var dep = new Dep()
if (childOb) {
childOb.deps.push(dep)
}
Object.defineProperty(ob.value, key, {
enumerable: true,
configurable: true,
get: function () {
if (ob.active) {
dep.depend()
}
return val
},
set: function (newVal) {
if (newVal === val) return
// remove dep from old value
var oldChildOb = val && val.__ob__
if (oldChildOb) {
oldChildOb.deps.$remove(dep)
}
val = newVal
// add dep to new value
var newChildOb = ob.observe(newVal)
if (newChildOb) {
newChildOb.deps.push(dep)
}
dep.notify()
}
})
}
/**
* Notify change on all self deps on an observer.
* This is called when a mutable value mutates. e.g.
* when an Array's mutating methods are called, or an
* Object's $add/$delete are called.
*/
p.notify = function () {
var deps = this.deps
for (var i = 0, l = deps.length; i < l; i++) {
deps[i].notify()
}
}
/**
* Add an owner vm, so that when $add/$delete mutations
* happen we can notify owner vms to proxy the keys and
* digest the watchers. This is only called when the object
* is observed as an instance's root $data.
*
* @param {Vue} vm
*/
p.addVm = function (vm) {
(this.vms || (this.vms = [])).push(vm)
}
/**
* Remove an owner vm. This is called when the object is
* swapped out as an instance's $data object.
*
* @param {Vue} vm
*/
p.removeVm = function (vm) {
this.vms.$remove(vm)
}
// helpers
/**
* Augment an target Object or Array by intercepting
* the prototype chain using __proto__
*
* @param {Object|Array} target
* @param {Object} proto
*/
function protoAugment (target, src) {
target.__proto__ = src
}
/**
* Augment an target Object or Array by defining
* hidden properties.
*
* @param {Object|Array} target
* @param {Object} proto
*/
function copyAugment (target, src, keys) {
var i = keys.length
var key
while (i--) {
key = keys[i]
_.define(target, key, src[key])
}
}
module.exports = Observer
| jumpcakes/plunkett | wp-content/themes/genesis-sample/assets/js/bower_components/vue/src/observer/index.js | JavaScript | gpl-2.0 | 4,867 |
<?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
*
* http://www.lockon.co.jp/
*
* 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 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
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
namespace Eccube\Controller;
use Eccube\Application;
use Eccube\Entity\BlocPosition;
class BlockController
{
public function index(Application $app)
{
$position = $app['request']->get('position');
$blocks = array();
if ($app['eccube.layout']) {
foreach ($app['eccube.layout']->getBlocPositions() as $blocPositions) {
if ($blocPositions->getTargetId() == constant("Eccube\Entity\BlocPosition::" . $position)) {
$blocks[] = $blocPositions->getBloc();
}
}
}
return $app['twig']->render('block.twig', array(
'blocks' => $blocks,
));
}
}
| ohtacky/ECCUBE3 | src/Eccube/Controller/BlockController.php | PHP | gpl-2.0 | 1,549 |
<?php
/**
* @file quiz.api.php
* Hooks provided by Quiz module.
*
* These entity types provided by Quiz also have entity API hooks. There are a
* few additional Quiz specific hooks defined in this file.
*
* quiz (settings for quiz nodes)
* quiz_result (quiz attempt/result)
* quiz_result_answer (answer to a specific question in a quiz result)
* quiz_question (generic settings for question nodes)
* quiz_question_relationship (relationship from quiz to question)
*
* So for example
*
* hook_quiz_result_presave($quiz_result)
* - Runs before a result is saved to the DB.
* hook_quiz_question_relationship_insert($quiz_question_relationship)
* - Runs when a new question is added to a quiz.
*
* You can also use Rules to build conditional actions based off of these
* events.
*
* Enjoy :)
*/
/**
* Implements hook_quiz_begin().
*
* Fired when a new quiz result is created.
*
* @deprecated
*
* Use hook_quiz_result_insert().
*/
function hook_quiz_begin($quiz, $result_id) {
}
/**
* Implements hook_quiz_finished().
*
* Fired after the last question is submitted.
*
* @deprecated
*
* Use hook_quiz_result_update().
*/
function hook_quiz_finished($quiz, $score, $data) {
}
/**
* Implements hook_quiz_scored().
*
* Fired when a quiz is evaluated.
*
* @deprecated
*
* Use hook_quiz_result_update().
*/
function hook_quiz_scored($quiz, $score, $result_id) {
}
/**
* Implements hook_quiz_question_info().
*
* Define a new question type. The question provider must extend QuizQuestion,
* and the response provider must extend QuizQuestionResponse. See those classes
* for additional implementation details.
*/
function hook_quiz_question_info() {
return array(
'long_answer' => array(
'name' => t('Example question type'),
'description' => t('An example question type that does something.'),
'question provider' => 'ExampleAnswerQuestion',
'response provider' => 'ExampleAnswerResponse',
'module' => 'quiz_question',
),
);
}
/**
* Expose a feedback option to Quiz so that Quiz administrators can choose when
* to show it to Quiz takers.
*
* @return array
* An array of feedback options keyed by machine name.
*/
function hook_quiz_feedback_options() {
return array(
'percentile' => t('Percentile'),
);
}
/**
* Allow modules to alter the quiz feedback options.
*
* @param array $review_options
* An array of review options keyed by a machine name.
*/
function hook_quiz_feedback_options_alter(&$review_options) {
// Change label.
$review_options['quiz_feedback'] = t('General feedback from the Quiz.');
// Disable showing correct answer.
unset($review_options['solution']);
}
/**
* Allow modules to define feedback times.
*
* Feedback times are configurable by Rules.
*
* @return array
* An array of feedback times keyed by machine name.
*/
function hook_quiz_feedback_times() {
return array(
'2_weeks_later' => t('Two weeks after finishing'),
);
}
/**
* Allow modules to alter the feedback times.
*
* @param array $feedback_times
*/
function hook_quiz_feedback_times_alter(&$feedback_times) {
// Change label.
$feedback_times['end'] = t('At the end of a quiz');
// Do not allow question feedback.
unset($feedback_times['question']);
}
/**
* Allow modules to alter the feedback labels.
*
* These are the labels that are displayed to the user, so instead of
* "Answer feedback" you may want to display something more learner-friendly.
*
* @param $feedback_labels
* An array keyed by the feedback option. Default keys are the keys from
* quiz_get_feedback_options().
*/
function hook_quiz_feedback_labels_alter(&$feedback_labels) {
$feedback_labels['solution'] = t('The answer you should have chosen.');
}
/**
* Implements hook_quiz_access().
*
* Control access to Quizzes.
*
* @see quiz_quiz_access() for default access implementations.
*
* Modules may implement Quiz access control hooks to block access to a Quiz or
* display a non-blocking message. Blockers are keyed by a blocker name, and
* must be an array keyed by 'success' and 'message'.
*/
function hook_quiz_access($op, $quiz, $account) {
if ($op == 'take') {
$today = date('l');
if ($today == 'Monday') {
return array(
'monday' => array(
'success' => FALSE,
'message' => t('You cannot take quizzes on Monday.'),
),
);
}
else {
return array(
'not_monday' => array(
'success' => TRUE,
'message' => t('It is not Monday so you may take quizzes.'),
),
);
}
}
}
/**
* Implements hook_quiz_access_alter().
*
* Alter the access blockers for a Quiz.
*
*/
function hook_quiz_access_alter(&$hooks, $op, $quiz, $account) {
if ($op == 'take') {
unset($hooks['monday']);
}
}
| bondjimbond/bcelnapps | sites/all/modules/quiz/quiz.api.php | PHP | gpl-2.0 | 4,847 |
--TEST--
Bug #67215 (php-cgi work with opcache, may be segmentation fault happen)
--INI--
opcache.enable=1
opcache.enable_cli=1
opcache.file_update_protection=0
--SKIPIF--
<?php require_once('skipif.inc'); ?>
--FILE--
<?php
$file_c = __DIR__ . "/bug67215.c.php";
$file_p = __DIR__ . "/bug67215.p.php";
file_put_contents($file_c, "<?php require \"$file_p\"; class c extends p {} ?>");
file_put_contents($file_p, '<?php class p { protected $var = ""; } ?>');
require $file_c;
$a = new c();
require $file_c;
?>
--CLEAN--
<?php
$file_c = __DIR__ . "/bug67215.c.php";
$file_p = __DIR__ . "/bug67215.p.php";
unlink($file_c);
unlink($file_p);
?>
--EXPECTF--
Fatal error: Cannot redeclare class c in %sbug67215.c.php on line %d
| neonatura/crotalus | php/ext/opcache/tests/bug67215.phpt | PHP | gpl-2.0 | 721 |
// Example taken from http://bl.ocks.org/mbostock/3883245
jQuery( document ).ready(function() {
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 620 - margin.left - margin.right,
height = 330 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
var svg = d3.select(".core-commits-vizualization").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.tsv(Drupal.settings.ppcc.data, function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
});
| DmitryDrozdik/ppdorg | docroot/sites/all/modules/custom/ppgetstat/ppcc/plugins/content_types/ppcc_visualization.js | JavaScript | gpl-2.0 | 1,739 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.6 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2015
* $Id$
*
*/
class CRM_Report_Form_Event_ParticipantListing extends CRM_Report_Form_Event {
protected $_summary = NULL;
protected $_contribField = FALSE;
protected $_lineitemField = FALSE;
protected $_groupFilter = TRUE;
protected $_tagFilter = TRUE;
protected $_balance = FALSE;
protected $activeCampaigns;
protected $_customGroupExtends = array(
'Participant',
'Contact',
'Individual',
'Event',
);
public $_drilldownReport = array('event/income' => 'Link to Detail Report');
/**
*/
/**
*/
public function __construct() {
$this->_autoIncludeIndexedFieldsAsOrderBys = 1;
// Check if CiviCampaign is a) enabled and b) has active campaigns
$config = CRM_Core_Config::singleton();
$campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
if ($campaignEnabled) {
$getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
$this->activeCampaigns = $getCampaigns['campaigns'];
asort($this->activeCampaigns);
}
$this->_columns = array(
'civicrm_contact' => array(
'dao' => 'CRM_Contact_DAO_Contact',
'fields' => array_merge(array(
// CRM-17115 - to avoid changing report output at this stage re-instate
// old field name for sort name
'sort_name_linked' => array(
'title' => ts('Participant Name'),
'required' => TRUE,
'no_repeat' => TRUE,
'dbAlias' => 'contact_civireport.sort_name',
)),
$this->getBasicContactFields(),
array(
'age_at_event' => array(
'title' => ts('Age at Event'),
'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, event_civireport.start_date)',
),
)
),
'grouping' => 'contact-fields',
'order_bys' => array(
'sort_name' => array(
'title' => ts('Last Name, First Name'),
'default' => '1',
'default_weight' => '0',
'default_order' => 'ASC',
),
'first_name' => array(
'name' => 'first_name',
'title' => ts('First Name'),
),
'gender_id' => array(
'name' => 'gender_id',
'title' => ts('Gender'),
),
'birth_date' => array(
'name' => 'birth_date',
'title' => ts('Birth Date'),
),
'age_at_event' => array(
'name' => 'age_at_event',
'title' => ts('Age at Event'),
),
'contact_type' => array(
'title' => ts('Contact Type'),
),
'contact_sub_type' => array(
'title' => ts('Contact Subtype'),
),
),
'filters' => array(
'sort_name' => array(
'title' => ts('Participant Name'),
'operator' => 'like',
),
'gender_id' => array(
'title' => ts('Gender'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
),
'birth_date' => array(
'title' => ts('Birth Date'),
'operatorType' => CRM_Report_Form::OP_DATE,
),
'contact_type' => array(
'title' => ts('Contact Type'),
),
'contact_sub_type' => array(
'title' => ts('Contact Subtype'),
),
),
),
'civicrm_email' => array(
'dao' => 'CRM_Core_DAO_Email',
'fields' => array(
'email' => array(
'title' => ts('Email'),
'no_repeat' => TRUE,
),
),
'grouping' => 'contact-fields',
'filters' => array(
'email' => array(
'title' => ts('Participant E-mail'),
'operator' => 'like',
),
),
),
'civicrm_address' => array(
'dao' => 'CRM_Core_DAO_Address',
'fields' => array(
'street_address' => NULL,
'city' => NULL,
'postal_code' => NULL,
'state_province_id' => array(
'title' => ts('State/Province'),
),
'country_id' => array(
'title' => ts('Country'),
),
),
'grouping' => 'contact-fields',
),
'civicrm_participant' => array(
'dao' => 'CRM_Event_DAO_Participant',
'fields' => array(
'participant_id' => array('title' => 'Participant ID'),
'participant_record' => array(
'name' => 'id',
'no_display' => TRUE,
'required' => TRUE,
),
'event_id' => array(
'default' => TRUE,
'type' => CRM_Utils_Type::T_STRING,
),
'status_id' => array(
'title' => ts('Status'),
'default' => TRUE,
),
'role_id' => array(
'title' => ts('Role'),
'default' => TRUE,
),
'fee_currency' => array(
'required' => TRUE,
'no_display' => TRUE,
),
'participant_fee_level' => NULL,
'participant_fee_amount' => NULL,
'participant_register_date' => array('title' => ts('Registration Date')),
'total_paid' => array(
'title' => ts('Total Paid'),
'dbAlias' => 'SUM(ft.total_amount)',
'type' => 1024,
),
'balance' => array(
'title' => ts('Balance'),
'dbAlias' => 'participant_civireport.fee_amount - SUM(ft.total_amount)',
'type' => 1024,
),
),
'grouping' => 'event-fields',
'filters' => array(
'event_id' => array(
'name' => 'event_id',
'title' => ts('Event'),
'operatorType' => CRM_Report_Form::OP_ENTITYREF,
'type' => CRM_Utils_Type::T_INT,
'attributes' => array(
'entity' => 'event',
'select' => array('minimumInputLength' => 0),
),
),
'sid' => array(
'name' => 'status_id',
'title' => ts('Participant Status'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'),
),
'rid' => array(
'name' => 'role_id',
'title' => ts('Participant Role'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Event_PseudoConstant::participantRole(),
),
'participant_register_date' => array(
'title' => 'Registration Date',
'operatorType' => CRM_Report_Form::OP_DATE,
),
'fee_currency' => array(
'title' => ts('Fee Currency'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
'default' => NULL,
'type' => CRM_Utils_Type::T_STRING,
),
),
'order_bys' => array(
'participant_register_date' => array(
'title' => ts('Registration Date'),
'default_weight' => '1',
'default_order' => 'ASC',
),
'event_id' => array(
'title' => ts('Event'),
'default_weight' => '1',
'default_order' => 'ASC',
),
),
),
'civicrm_phone' => array(
'dao' => 'CRM_Core_DAO_Phone',
'fields' => array(
'phone' => array(
'title' => ts('Phone'),
'default' => TRUE,
'no_repeat' => TRUE,
),
),
'grouping' => 'contact-fields',
),
'civicrm_event' => array(
'dao' => 'CRM_Event_DAO_Event',
'fields' => array(
'event_type_id' => array('title' => ts('Event Type')),
'event_start_date' => array('title' => ts('Event Start Date')),
),
'grouping' => 'event-fields',
'filters' => array(
'eid' => array(
'name' => 'event_type_id',
'title' => ts('Event Type'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_OptionGroup::values('event_type'),
),
'event_start_date' => array(
'title' => ts('Event Start Date'),
'operatorType' => CRM_Report_Form::OP_DATE,
),
),
'order_bys' => array(
'event_type_id' => array(
'title' => ts('Event Type'),
'default_weight' => '2',
'default_order' => 'ASC',
),
'event_start_date' => array(
'title' => ts('Event Start Date'),
),
),
),
'civicrm_contribution' => array(
'dao' => 'CRM_Contribute_DAO_Contribution',
'fields' => array(
'contribution_id' => array(
'name' => 'id',
'no_display' => TRUE,
'required' => TRUE,
'csv_display' => TRUE,
'title' => ts('Contribution ID'),
),
'financial_type_id' => array('title' => ts('Financial Type')),
'receive_date' => array('title' => ts('Payment Date')),
'contribution_status_id' => array('title' => ts('Contribution Status')),
'payment_instrument_id' => array('title' => ts('Payment Type')),
'contribution_source' => array(
'name' => 'source',
'title' => ts('Contribution Source'),
),
'currency' => array(
'required' => TRUE,
'no_display' => TRUE,
),
'trxn_id' => NULL,
'fee_amount' => array('title' => ts('Transaction Fee')),
'net_amount' => NULL,
),
'grouping' => 'contrib-fields',
'filters' => array(
'receive_date' => array(
'title' => 'Payment Date',
'operatorType' => CRM_Report_Form::OP_DATE,
),
'financial_type_id' => array(
'title' => ts('Financial Type'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Contribute_PseudoConstant::financialType(),
),
'currency' => array(
'title' => ts('Contribution Currency'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
'default' => NULL,
'type' => CRM_Utils_Type::T_STRING,
),
'payment_instrument_id' => array(
'title' => ts('Payment Type'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Contribute_PseudoConstant::paymentInstrument(),
),
'contribution_status_id' => array(
'title' => ts('Contribution Status'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
'default' => NULL,
),
),
),
'civicrm_line_item' => array(
'dao' => 'CRM_Price_DAO_LineItem',
'grouping' => 'priceset-fields',
'filters' => array(
'price_field_value_id' => array(
'name' => 'price_field_value_id',
'title' => ts('Fee Level'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => $this->getPriceLevels(),
),
),
),
);
$this->_options = array(
'blank_column_begin' => array(
'title' => ts('Blank column at the Begining'),
'type' => 'checkbox',
),
'blank_column_end' => array(
'title' => ts('Blank column at the End'),
'type' => 'select',
'options' => array(
'' => '-select-',
1 => ts('One'),
2 => ts('Two'),
3 => ts('Three'),
),
),
);
// CRM-17115 avoid duplication of sort_name - would be better to standardise name
// & behaviour across reports but trying for no change at this point.
$this->_columns['civicrm_contact']['fields']['sort_name']['no_display'] = TRUE;
// If we have active campaigns add those elements to both the fields and filters
if ($campaignEnabled && !empty($this->activeCampaigns)) {
$this->_columns['civicrm_participant']['fields']['campaign_id'] = array(
'title' => ts('Campaign'),
'default' => 'false',
);
$this->_columns['civicrm_participant']['filters']['campaign_id'] = array(
'title' => ts('Campaign'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => $this->activeCampaigns,
);
$this->_columns['civicrm_participant']['order_bys']['campaign_id'] = array(
'title' => ts('Campaign'),
);
}
$this->_currencyColumn = 'civicrm_participant_fee_currency';
parent::__construct();
}
/**
* Searches database for priceset values.
*
* @return array
*/
public function getPriceLevels() {
$query = "
SELECT CONCAT(cv.label, ' (', ps.title, ')') label, cv.id
FROM civicrm_price_field_value cv
LEFT JOIN civicrm_price_field cf
ON cv.price_field_id = cf.id
LEFT JOIN civicrm_price_set_entity ce
ON ce.price_set_id = cf.price_set_id
LEFT JOIN civicrm_price_set ps
ON ce.price_set_id = ps.id
WHERE ce.entity_table = 'civicrm_event'
ORDER BY cv.label
";
$dao = CRM_Core_DAO::executeQuery($query);
$elements = array();
while ($dao->fetch()) {
$elements[$dao->id] = "$dao->label\n";
}
return $elements;
}
public function preProcess() {
parent::preProcess();
}
public function select() {
$select = array();
$this->_columnHeaders = array();
//add blank column at the Start
if (array_key_exists('options', $this->_params) &&
!empty($this->_params['options']['blank_column_begin'])
) {
$select[] = " '' as blankColumnBegin";
$this->_columnHeaders['blankColumnBegin']['title'] = '_ _ _ _';
}
foreach ($this->_columns as $tableName => $table) {
if ($tableName == 'civicrm_line_item') {
$this->_lineitemField = TRUE;
}
if (array_key_exists('fields', $table)) {
foreach ($table['fields'] as $fieldName => $field) {
if (!empty($field['required']) ||
!empty($this->_params['fields'][$fieldName])
) {
if ($tableName == 'civicrm_contribution') {
$this->_contribField = TRUE;
}
if ($fieldName == 'total_paid' || $fieldName == 'balance') {
$this->_balance = TRUE;
}
$alias = "{$tableName}_{$fieldName}";
$select[] = "{$field['dbAlias']} as $alias";
$this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
$this->_columnHeaders["{$tableName}_{$fieldName}"]['no_display'] = CRM_Utils_Array::value('no_display', $field);
$this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
$this->_selectAliases[] = $alias;
}
}
}
}
//add blank column at the end
$blankcols = CRM_Utils_Array::value('blank_column_end', $this->_params);
if ($blankcols) {
for ($i = 1; $i <= $blankcols; $i++) {
$select[] = " '' as blankColumnEnd_{$i}";
$this->_columnHeaders["blank_{$i}"]['title'] = "_ _ _ _";
}
}
$this->_select = "SELECT " . implode(', ', $select) . " ";
}
/**
* @param $fields
* @param $files
* @param $self
*
* @return array
*/
public static function formRule($fields, $files, $self) {
$errors = $grouping = array();
return $errors;
}
public function from() {
$this->_from = "
FROM civicrm_participant {$this->_aliases['civicrm_participant']}
LEFT JOIN civicrm_event {$this->_aliases['civicrm_event']}
ON ({$this->_aliases['civicrm_event']}.id = {$this->_aliases['civicrm_participant']}.event_id ) AND
{$this->_aliases['civicrm_event']}.is_template = 0
LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
ON ({$this->_aliases['civicrm_participant']}.contact_id = {$this->_aliases['civicrm_contact']}.id )
{$this->_aclFrom}
LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
{$this->_aliases['civicrm_address']}.is_primary = 1
LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
{$this->_aliases['civicrm_email']}.is_primary = 1)
LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
{$this->_aliases['civicrm_phone']}.is_primary = 1
";
if ($this->_contribField) {
$this->_from .= "
LEFT JOIN civicrm_participant_payment pp
ON ({$this->_aliases['civicrm_participant']}.id = pp.participant_id)
LEFT JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
ON (pp.contribution_id = {$this->_aliases['civicrm_contribution']}.id)
";
}
if ($this->_lineitemField) {
$this->_from .= "
LEFT JOIN civicrm_line_item line_item_civireport
ON line_item_civireport.entity_table = 'civicrm_participant' AND
line_item_civireport.entity_id = {$this->_aliases['civicrm_participant']}.id AND
line_item_civireport.qty > 0
";
}
if ($this->_balance) {
$this->_from .= "
LEFT JOIN civicrm_entity_financial_trxn eft
ON (eft.entity_id = {$this->_aliases['civicrm_contribution']}.id)
LEFT JOIN civicrm_financial_account fa
ON (fa.account_type_code = 'AR')
LEFT JOIN civicrm_financial_trxn ft
ON (ft.id = eft.financial_trxn_id AND eft.entity_table = 'civicrm_contribution') AND
(ft.to_financial_account_id != fa.id)
";
}
}
public function where() {
$clauses = array();
foreach ($this->_columns as $tableName => $table) {
if (array_key_exists('filters', $table)) {
foreach ($table['filters'] as $fieldName => $field) {
$clause = NULL;
if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
$relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
$from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
$to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
if ($relative || $from || $to) {
$clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
}
}
else {
$op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
if ($fieldName == 'rid') {
$value = CRM_Utils_Array::value("{$fieldName}_value", $this->_params);
if (!empty($value)) {
$operator = '';
if ($op == 'notin') {
$operator = 'NOT';
}
$regexp = "[[:cntrl:]]*" . implode('[[:>:]]*|[[:<:]]*', $value) . "[[:cntrl:]]*";
$clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
}
$op = NULL;
}
if ($op) {
$clause = $this->whereClause($field,
$op,
CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
);
}
}
if (!empty($clause)) {
$clauses[] = $clause;
}
}
}
}
if (empty($clauses)) {
$this->_where = "WHERE {$this->_aliases['civicrm_participant']}.is_test = 0 ";
}
else {
$this->_where = "WHERE {$this->_aliases['civicrm_participant']}.is_test = 0 AND " .
implode(' AND ', $clauses);
}
if ($this->_aclWhere) {
$this->_where .= " AND {$this->_aclWhere} ";
}
}
public function groupBy() {
$this->_groupBy = "GROUP BY {$this->_aliases['civicrm_participant']}.id";
}
public function postProcess() {
// get ready with post process params
$this->beginPostProcess();
// get the acl clauses built before we assemble the query
$this->buildACLClause($this->_aliases['civicrm_contact']);
// build query
$sql = $this->buildQuery(TRUE);
// build array of result based on column headers. This method also allows
// modifying column headers before using it to build result set i.e $rows.
$rows = array();
$this->buildRows($sql, $rows);
// format result set.
$this->formatDisplay($rows);
// assign variables to templates
$this->doTemplateAssignment($rows);
// do print / pdf / instance stuff if needed
$this->endPostProcess($rows);
}
/**
* @param $rows
* @param $entryFound
* @param $row
* @param int $rowId
* @param $rowNum
* @param $types
*
* @return bool
*/
private function _initBasicRow(&$rows, &$entryFound, $row, $rowId, $rowNum, $types) {
if (!array_key_exists($rowId, $row)) {
return FALSE;
}
$value = $row[$rowId];
if ($value) {
$rows[$rowNum][$rowId] = $types[$value];
}
$entryFound = TRUE;
}
/**
* Alter display of rows.
*
* Iterate through the rows retrieved via SQL and make changes for display purposes,
* such as rendering contacts as links.
*
* @param array $rows
* Rows generated by SQL, with an array for each row.
*/
public function alterDisplay(&$rows) {
$entryFound = FALSE;
$eventType = CRM_Core_OptionGroup::values('event_type');
$financialTypes = CRM_Contribute_PseudoConstant::financialType();
$contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
$paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument();
foreach ($rows as $rowNum => $row) {
// make count columns point to detail report
// convert display name to links
if (array_key_exists('civicrm_participant_event_id', $row)) {
$eventId = $row['civicrm_participant_event_id'];
if ($eventId) {
$rows[$rowNum]['civicrm_participant_event_id'] = CRM_Event_PseudoConstant::event($eventId, FALSE);
$url = CRM_Report_Utils_Report::getNextUrl('event/income',
'reset=1&force=1&id_op=in&id_value=' . $eventId,
$this->_absoluteUrl, $this->_id, $this->_drilldownReport
);
$rows[$rowNum]['civicrm_participant_event_id_link'] = $url;
$rows[$rowNum]['civicrm_participant_event_id_hover'] = ts("View Event Income Details for this Event");
}
$entryFound = TRUE;
}
// handle event type id
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_event_event_type_id', $rowNum, $eventType);
// handle participant status id
if (array_key_exists('civicrm_participant_status_id', $row)) {
$statusId = $row['civicrm_participant_status_id'];
if ($statusId) {
$rows[$rowNum]['civicrm_participant_status_id'] = CRM_Event_PseudoConstant::participantStatus($statusId, FALSE, 'label');
}
$entryFound = TRUE;
}
// handle participant role id
if (array_key_exists('civicrm_participant_role_id', $row)) {
$roleId = $row['civicrm_participant_role_id'];
if ($roleId) {
$roles = explode(CRM_Core_DAO::VALUE_SEPARATOR, $roleId);
$roleId = array();
foreach ($roles as $role) {
$roleId[$role] = CRM_Event_PseudoConstant::participantRole($role, FALSE);
}
$rows[$rowNum]['civicrm_participant_role_id'] = implode(', ', $roleId);
}
$entryFound = TRUE;
}
// Handel value seperator in Fee Level
if (array_key_exists('civicrm_participant_participant_fee_level', $row)) {
$feeLevel = $row['civicrm_participant_participant_fee_level'];
if ($feeLevel) {
CRM_Event_BAO_Participant::fixEventLevel($feeLevel);
$rows[$rowNum]['civicrm_participant_participant_fee_level'] = $feeLevel;
}
$entryFound = TRUE;
}
// Convert display name to link
$displayName = CRM_Utils_Array::value('civicrm_contact_sort_name_linked', $row);
$cid = CRM_Utils_Array::value('civicrm_contact_id', $row);
$id = CRM_Utils_Array::value('civicrm_participant_participant_record', $row);
if ($displayName && $cid && $id) {
$url = CRM_Report_Utils_Report::getNextUrl('contact/detail',
"reset=1&force=1&id_op=eq&id_value=$cid",
$this->_absoluteUrl, $this->_id, $this->_drilldownReport
);
$viewUrl = CRM_Utils_System::url("civicrm/contact/view/participant",
"reset=1&id=$id&cid=$cid&action=view&context=participant"
);
$contactTitle = ts('View Contact Details');
$participantTitle = ts('View Participant Record');
$rows[$rowNum]['civicrm_contact_sort_name_linked'] = "<a title='$contactTitle' href=$url>$displayName</a>";
if ($this->_outputMode !== 'csv') {
$rows[$rowNum]['civicrm_contact_sort_name_linked'] .=
"<span style='float: right;'><a title='$participantTitle' href=$viewUrl>" .
ts('View') . "</a></span>";
}
$entryFound = TRUE;
}
// Handle country id
if (array_key_exists('civicrm_address_country_id', $row)) {
$countryId = $row['civicrm_address_country_id'];
if ($countryId) {
$rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($countryId, TRUE);
}
$entryFound = TRUE;
}
// Handle state/province id
if (array_key_exists('civicrm_address_state_province_id', $row)) {
$provinceId = $row['civicrm_address_state_province_id'];
if ($provinceId) {
$rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($provinceId, TRUE);
}
$entryFound = TRUE;
}
// Handle employer id
if (array_key_exists('civicrm_contact_employer_id', $row)) {
$employerId = $row['civicrm_contact_employer_id'];
if ($employerId) {
$rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact::displayName($employerId);
$url = CRM_Utils_System::url('civicrm/contact/view',
'reset=1&cid=' . $employerId, $this->_absoluteUrl
);
$rows[$rowNum]['civicrm_contact_employer_id_link'] = $url;
$rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for this Contact.');
}
}
// Convert campaign_id to campaign title
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_participant_campaign_id', $rowNum, $this->activeCampaigns);
// handle contribution status
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_contribution_status_id', $rowNum, $contributionStatus);
// handle payment instrument
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_payment_instrument_id', $rowNum, $paymentInstruments);
// handle financial type
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_financial_type_id', $rowNum, $financialTypes);
$entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'event/participantListing', 'View Event Income Details') ? TRUE : $entryFound;
// display birthday in the configured custom format
if (array_key_exists('civicrm_contact_birth_date', $row)) {
$birthDate = $row['civicrm_contact_birth_date'];
if ($birthDate) {
$rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
}
$entryFound = TRUE;
}
// skip looking further in rows, if first row itself doesn't
// have the column we need
if (!$entryFound) {
break;
}
}
}
}
| glocalcoop/activist-network | wp-content/plugins/civicrm/civicrm/CRM/Report/Form/Event/ParticipantListing.php | PHP | gpl-2.0 | 30,656 |
<?php
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// REPORTE: Formato de salida de Solicitud de Pago
// ORGANISMO: MINISTERIO DEL PODER POPULAR PARA LA INFRAESTRUCTURA.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
session_start();
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
if(!array_key_exists("la_logusr",$_SESSION))
{
print "<script language=JavaScript>";
print "close();";
print "opener.document.form1.submit();";
print "</script>";
}
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_insert_seguridad($as_titulo)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_insert_seguridad
// Access: private
// Arguments: as_titulo // Título del reporte
// Description: función que guarda la seguridad de quien generó el reporte
// Creado Por: Ing. Yesenia Moreno/ Ing. Luis Lang
// Fecha Creación: 11/03/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
global $io_fun_cxp;
$ls_descripcion="Generó el Reporte ".$as_titulo;
$lb_valido=$io_fun_cxp->uf_load_seguridad_reporte("CXP","sigesp_cxp_p_solicitudpago.php",$ls_descripcion);
return $lb_valido;
}
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_encabezado_pagina($as_titulo,$as_numsol,$ad_fecregsol,&$io_pdf)
{
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_encabezado_pagina
// Access: private
// Arguments: as_titulo // Título del Reporte
// as_numsol // numero de la solicitud
// ad_fecregsol // fecha de registro de la solicitud
// io_pdf // Instancia de objeto pdf
// Description: Función que imprime los encabezados por página
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 11/03/2007
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_encabezado=$io_pdf->openObject();
$io_pdf->saveState();
$io_pdf->setStrokeColor(0,0,0);
$io_pdf->line(20,40,590,40);
$io_pdf->line(480,655,480,700);
$io_pdf->line(480,677,590,677);
$io_pdf->Rectangle(105,655,485,45);
$io_pdf->addJpegFromFile('../../shared/imagebank/banner_minfra.jpg',20,708,570,50); // Agregar Banner.
$io_pdf->addJpegFromFile('../../shared/imagebank/'.$_SESSION["ls_logo"],20,655,$_SESSION["ls_width"],$_SESSION["ls_height"]); // Agregar Logo
$li_tm=$io_pdf->getTextWidth(11,$as_titulo);
$tm=285-($li_tm/2);
$io_pdf->addText($tm,673,12,$as_titulo); // Agregar el título
$io_pdf->addText(485,685,9,"<b>No.</b> ".$as_numsol); // Agregar el título
$io_pdf->addText(485,663,9,"<b>Fecha</b> ".$ad_fecregsol); // Agregar el título
$io_pdf->addText(540,770,7,date("d/m/Y")); // Agregar la Fecha
$io_pdf->addText(546,764,6,date("h:i a")); // Agregar la Hora
// cuadro inferior
$io_pdf->Rectangle(20,60,570,70);
$io_pdf->line(20,73,590,73);
$io_pdf->line(20,117,590,117);
$io_pdf->line(130,60,130,130);
$io_pdf->line(240,60,240,130);
$io_pdf->line(380,60,380,130);
$io_pdf->addText(40,122,7,"ELABORADO POR"); // Agregar el título
$io_pdf->addText(42,63,7,"FIRMA / SELLO"); // Agregar el título
$io_pdf->addText(157,122,7,"VERIFICADO POR"); // Agregar el título
$io_pdf->addText(145,63,7,"FIRMA / SELLO / FECHA"); // Agregar el título
$io_pdf->addText(275,122,7,"AUTORIZADO POR"); // Agregar el título
$io_pdf->addText(257,63,7,"ADMINISTRACIÓN Y FINANZAS"); // Agregar el título
$io_pdf->addText(440,122,7,"CONTRALORIA INTERNA"); // Agregar el título
$io_pdf->addText(445,63,7,"FIRMA / SELLO / FECHA"); // Agregar el título
$io_pdf->restoreState();
$io_pdf->closeObject();
$io_pdf->addObject($io_encabezado,'all');
}// end function uf_print_encabezado_pagina
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_cabecera($as_numsol,$as_codigo,$as_nombre,$as_denfuefin,$ad_fecemisol,$as_consol,$as_obssol,
$ai_monsol,$as_monto,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_cabecera
// Access: private
// Arguments: as_numsol // Numero de la Solicitud de Pago
// as_codigo // Codigo del Proveedor / Beneficiario
// as_nombre // Nombre del Proveedor / Beneficiario
// as_denfuefin // Denominacion de la fuente de financiamiento
// ad_fecemisol // Fecha de Emision de la Solicitud
// as_consol // Concepto de la Solicitud
// as_obssol // Observaciones de la Solicitud
// ai_monsol // Monto de la Solicitud
// as_monto // Monto de la Solicitud en letras
// io_pdf // Instancia de objeto pdf
// Description: función que imprime la cabecera
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 17/05/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$la_data[1]=array('titulo'=>'<b>Beneficiario</b>');
$la_data[2]=array('titulo'=>" ".$as_nombre);
$la_columnas=array('titulo'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'left','width'=>570))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
$la_data[1]=array('titulo'=>'<b> Concepto: </b>'.$as_consol);
$la_columnas=array('titulo'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'left','width'=>570))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
$la_data[1]=array('titulo'=>'<b>Monto en Letras: </b>'.$as_monto,);
$la_columnas=array('titulo'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'left','width'=>570))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
global $ls_tiporeporte;
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$la_data[1]=array('titulo'=>'<b>'.$ls_titulo.'</b>','contenido'=>$ai_monsol,);
$la_columnas=array('titulo'=>'',
'contenido'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>400), // Justificación y ancho de la columna
'contenido'=>array('justification'=>'center','width'=>170))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
}// end function uf_print_cabecera
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_detalle_recepcion($la_data,$ai_totsubtot,$ai_tottot,$ai_totcar,$ai_totded,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle
// Access: private
// Arguments: la_data // arreglo de información
// ai_totsubtot // acumulado del subtotal
// ai_tottot // acumulado del total
// ai_totcar // acumulado de los cargos
// ai_totded // acumulado de las deducciones
// io_pdf // Instancia de objeto pdf
// Description: función que imprime el detalle
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 20/05/2006
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
global $ls_tiporeporte;
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$io_pdf->ezSetDy(-2);
$la_datatit[1]=array('numrecdoc'=>'<b>Factura</b>','fecemisol'=>'<b>Fecha</b>','subtotdoc'=>'<b>Monto</b>',
'moncardoc'=>'<b>Cargos</b>','mondeddoc'=>'<b>Deducciones</b>','montotdoc'=>'<b>Total</b>');
$la_columnas=array('numrecdoc'=>'','fecemisol'=>'','subtotdoc'=>'','moncardoc'=>'','mondeddoc'=>'','montotdoc'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol2'=>array(0.9,0.9,0.9), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('numrecdoc'=>array('justification'=>'center','width'=>130), // Justificación y ancho de la columna
'fecemisol'=>array('justification'=>'center','width'=>70), // Justificación y ancho de la columna
'subtotdoc'=>array('justification'=>'center','width'=>92), // Justificación y ancho de la columna
'moncardoc'=>array('justification'=>'center','width'=>92), // Justificación y ancho de la columna
'mondeddoc'=>array('justification'=>'center','width'=>92), // Justificación y ancho de la columna
'montotdoc'=>array('justification'=>'center','width'=>92))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatit,$la_columnas,'<b>RECEPCIONES DE DOCUMENTOS</b>',$la_config);
$la_columnas=array('numrecdoc'=>'','fecemisol'=>'','subtotdoc'=>'','moncardoc'=>'','mondeddoc'=>'','montotdoc'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('numrecdoc'=>array('justification'=>'center','width'=>130), // Justificación y ancho de la columna
'fecemisol'=>array('justification'=>'left','width'=>70), // Justificación y ancho de la columna
'subtotdoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'moncardoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'mondeddoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'montotdoc'=>array('justification'=>'right','width'=>92))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
$la_datatot[1]=array('numrecdoc'=>'<b>Totales '.$ls_titulo.'</b>','subtotdoc'=>$ai_totsubtot,
'moncardoc'=>$ai_totcar,'mondeddoc'=>$ai_totded,'montotdoc'=>$ai_tottot);
$la_columnas=array('numrecdoc'=>'','subtotdoc'=>'','moncardoc'=>'','mondeddoc'=>'','montotdoc'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('numrecdoc'=>array('justification'=>'right','width'=>200), // Justificación y ancho de la columna
'subtotdoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'moncardoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'mondeddoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'montotdoc'=>array('justification'=>'right','width'=>92))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_detalle
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_detalle_spg($aa_data,$ai_totpre,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle_cuentas
// Access: private
// Arguments: aa_data // arreglo de información
// ai_totpre // monto total de presupuesto
// io_pdf // Instancia de objeto pdf
// Description: función que imprime el detalle presupuestario
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 27/04/2006
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_pdf->ezSetDy(-5);
global $ls_estmodest;
global $ls_tiporeporte;
if($ls_estmodest==1)
{
$ls_titcuentas="Estructura Presupuestaria";
}
else
{
$ls_titcuentas="Estructura Programatica";
}
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$io_pdf->ezSetDy(-2);
$la_datasercon= array(array('estpro'=>"<b>".$ls_titcuentas."</b>",
'spg_cuenta'=>"<b>Cuenta</b>",
'denominacion'=>"<b>Denominación</b>",
'monto'=>"<b>Total ".$ls_titulo."</b>"));
$la_columna=array('estpro'=>'','spg_cuenta'=>'','denominacion'=>'','monto'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los titulos
'showLines'=>1, // Mostrar Lineas
'shaded'=>2, // Sombra entre lineas
'shadeCol2'=>array(0.9,0.9,0.9), // Sombra entre lineas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Minimo de la tabla
'xOrientation'=>'center', // Orientacion de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness'=>0.5,
'cols'=>array('estpro'=>array('justification'=>'center','width'=>165),
'spg_cuenta'=>array('justification'=>'center','width'=>84),
'denominacion'=>array('justification'=>'center','width'=>236),
'monto'=>array('justification'=>'center','width'=>85))); // Justificacion y ancho de la columna
$io_pdf->ezTable($la_datasercon,$la_columna,'<b>DETALLE PRESUPUESTARIO</b>',$la_config);
unset($la_datasercon);
unset($la_columna);
unset($la_config);
$la_columnas=array('codestpro'=>'','spg_cuenta'=>'','denominacion'=>'','monto'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('codestpro'=>array('justification'=>'center','width'=>165), // Justificación y ancho de la columna
'spg_cuenta'=>array('justification'=>'center','width'=>84), // Justificación y ancho de la columna
'denominacion'=>array('justification'=>'left','width'=>236), // Justificación y ancho de la columna
'monto'=>array('justification'=>'right','width'=>85))); // Justificación y ancho de la columna
$io_pdf->ezTable($aa_data,$la_columnas,'',$la_config);
$la_datatot[1]=array('titulo'=>'<b>Totales '.$ls_titulo.'</b>','totpre'=>$ai_totpre);
$la_columnas=array('titulo'=>'','totpre'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>485), // Justificación y ancho de la columna
'totpre'=>array('justification'=>'right','width'=>85))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_detalle
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_detalle_scg($aa_data,$ai_totdeb,$ai_tothab,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle_cuentas
// Access: private
// Arguments: aa_data // arreglo de información
// si_totdeb // total monto debe
// si_tothab // total monto haber
// io_pdf // Instancia de objeto pdf
// Description: función que imprime el detalle contable
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 27/05/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_pdf->ezSetDy(-5);
global $ls_tiporeporte;
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$io_pdf->ezSetDy(-2);
$la_data[1]=array('sc_cuenta'=>'<b>Cuenta</b>','denominacion'=>'<b>Denominacion</b>','mondeb'=>'<b>Debe</b>','monhab'=>'<b>Haber</b>');
$la_columnas=array('sc_cuenta'=>'','denominacion'=>'','mondeb'=>'','monhab'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre lineas
'shadeCol2'=>array(0.9,0.9,0.9), // Sombra entre lineas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('sc_cuenta'=>array('justification'=>'center','width'=>90), // Justificación y ancho de la columna
'denominacion'=>array('justification'=>'center','width'=>300), // Justificación y ancho de la columna
'mondeb'=>array('justification'=>'center','width'=>90), // Justificación y ancho de la columna
'monhab'=>array('justification'=>'center','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'<b>DETALLE CONTABLE</b>',$la_config);
unset($la_datatit);
unset($la_columnas);
unset($la_config);
$la_columnas=array('sc_cuenta'=>'','denominacion'=>'','mondeb'=>'','monhab'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre lineas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('sc_cuenta'=>array('justification'=>'center','width'=>90), // Justificación y ancho de la columna
'denominacion'=>array('justification'=>'left','width'=>300), // Justificación y ancho de la columna
'mondeb'=>array('justification'=>'right','width'=>90), // Justificación y ancho de la columna
'monhab'=>array('justification'=>'right','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($aa_data,$la_columnas,'',$la_config);
$la_datatot[1]=array('titulo'=>'<b>Totales '.$ls_titulo.'</b>','totdeb'=>$ai_totdeb,'tothab'=>$ai_tothab);
$la_columnas=array('titulo'=>'','totdeb'=>'','tothab'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>390), // Justificación y ancho de la columna
'totdeb'=>array('justification'=>'right','width'=>90), // Justificación y ancho de la columna
'tothab'=>array('justification'=>'right','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_detalle
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_total_bsf($ai_monsolaux,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle_cuentas
// Access: private
// Arguments: ai_monsolaux // Monto Auxiliar en Bs.F.
// io_pdf // Instancia de objeto pdf
// Description: Funcion que imprime el monto total de la solicitud en Bs.F.
// Creado Por: Ing. Luis Anibal Lang
// Fecha Creación: 26/09/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_pdf->ezSetDy(-5);
$la_datatot[1]=array('titulo'=>'<b>Total Bs.F.</b>','monto'=>$ai_monsolaux);
$la_columnas=array('titulo'=>'<b>Factura</b>',
'monto'=>'<b>Total</b>');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>0, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>480), // Justificación y ancho de la columna
'monto'=>array('justification'=>'right','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_total_bsf
//-----------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------- Instancia de las clases ------------------------------------------------
require_once("../../shared/ezpdf/class.ezpdf.php");
require_once("../../shared/class_folder/class_funciones.php");
$io_funciones=new class_funciones();
require_once("../class_folder/class_funciones_cxp.php");
$io_fun_cxp=new class_funciones_cxp();
$ls_estmodest=$_SESSION["la_empresa"]["estmodest"];
//Instancio a la clase de conversión de numeros a letras.
include("../../shared/class_folder/class_numero_a_letra.php");
$numalet= new class_numero_a_letra();
//imprime numero con los valore por defecto
//cambia a minusculas
$numalet->setMayusculas(1);
//cambia a femenino
$numalet->setGenero(1);
//cambia moneda
$numalet->setMoneda("Bolivares");
//cambia prefijo
$numalet->setPrefijo("***");
//cambia sufijo
$numalet->setSufijo("***");
if($ls_estmodest==1)
{
$ls_titcuentas="Estructura Presupuestaria";
}
else
{
$ls_titcuentas="Estructura Programatica";
}
//---------------------------------------------------- Parámetros del encabezado -----------------------------------------------
$ls_titulo="<b>SOLICITUD DE ORDEN DE PAGO</b>";
//-------------------------------------------------- Parámetros para Filtar el Reporte -----------------------------------------
$ls_numsol=$io_fun_cxp->uf_obtenervalor_get("numsol","");
$ls_tiporeporte=$io_fun_cxp->uf_obtenervalor_get("tiporeporte",0);
global $ls_tiporeporte;
require_once("../../shared/ezpdf/class.ezpdf.php");
if($ls_tiporeporte==1)
{
require_once("sigesp_cxp_class_reportbsf.php");
$io_report=new sigesp_cxp_class_reportbsf();
}
else
{
require_once("sigesp_cxp_class_report.php");
$io_report=new sigesp_cxp_class_report();
}
//--------------------------------------------------------------------------------------------------------------------------------
$lb_valido=uf_insert_seguridad($ls_titulo); // Seguridad de Reporte
if($lb_valido)
{
$lb_valido=$io_report->uf_select_solicitud($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido==false) // Existe algún error ó no hay registros
{
print("<script language=JavaScript>");
print(" alert('No hay nada que Reportar');");
print(" close();");
print("</script>");
}
else // Imprimimos el reporte
{
error_reporting(E_ALL);
set_time_limit(1800);
$io_pdf=new Cezpdf('LETTER','portrait'); // Instancia de la clase PDF
$io_pdf->selectFont('../../shared/ezpdf/fonts/Helvetica.afm'); // Seleccionamos el tipo de letra
$io_pdf->ezSetCmMargins(5,5,3.3,3); // Configuración de los margenes en centímetros
$io_pdf->ezStartPageNumbers(570,47,8,'','',1); // Insertar el número de página
$li_totrow=$io_report->DS->getRowCount("numsol");
for($li_i=1;$li_i<=$li_totrow;$li_i++)
{
$ls_numsol=$io_report->DS->data["numsol"][$li_i];
$ls_codpro=$io_report->DS->data["cod_pro"][$li_i];
$ls_cedbene=$io_report->DS->data["ced_bene"][$li_i];
$ls_denfuefin=$io_report->DS->data["denfuefin"][$li_i];
$ls_nombre=$io_report->DS->data["nombre"][$li_i];
$ld_fecemisol=$io_report->DS->data["fecemisol"][$li_i];
$ls_consol=$io_report->DS->data["consol"][$li_i];
$ls_obssol=$io_report->DS->data["obssol"][$li_i];
$li_monsol=$io_report->DS->data["monsol"][$li_i];
$numalet->setNumero($li_monsol);
$ls_monto= $numalet->letra();
$li_monsol=number_format($li_monsol,2,",",".");
$ld_fecemisol=$io_funciones->uf_convertirfecmostrar($ld_fecemisol);
if($ls_codpro!="----------")
{
$ls_codigo=$ls_codpro;
}
else
{
$ls_codigo=$ls_cedbene;
}
/* if($ls_tiporeporte==0)
{
$li_monsolaux=$io_report->DS->data["monsolaux"][$li_i];
$li_monsolaux=number_format($li_monsolaux,2,",",".");
}
*/ uf_print_encabezado_pagina($ls_titulo,$ls_numsol,$ld_fecemisol,&$io_pdf);
uf_print_cabecera($ls_numsol,$ls_codigo,$ls_nombre,$ls_denfuefin,$ld_fecemisol,$ls_consol,$ls_obssol,$li_monsol,$ls_monto,&$io_pdf);
////////////////////////// GRID RECEPCIONES DE DOCUMENTOS //////////////////////////////////////
$io_report->ds_detalle->reset_ds();
$lb_valido=$io_report->uf_select_rec_doc_solicitud($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido)
{
$li_totrowdet=$io_report->ds_detalle_rec->getRowCount("numrecdoc");
$la_data="";
$li_totsubtot=0;
$li_tottot=0;
$li_totcar=0;
$li_totded=0;
for($li_s=1;$li_s<=$li_totrowdet;$li_s++)
{
$ls_numrecdoc=trim($io_report->ds_detalle_rec->data["numrecdoc"][$li_s]);
$ld_fecemidoc=trim($io_report->ds_detalle_rec->data["fecemidoc"][$li_s]);
$ls_numdoccomspg=$io_report->ds_detalle_rec->data["numdoccomspg"][$li_s];
$li_mondeddoc=$io_report->ds_detalle_rec->data["mondeddoc"][$li_s];
$li_moncardoc=$io_report->ds_detalle_rec->data["moncardoc"][$li_s];
$li_montotdoc=$io_report->ds_detalle_rec->data["montotdoc"][$li_s];
$li_subtotdoc=($li_montotdoc-$li_moncardoc+$li_mondeddoc);
$li_totsubtot=$li_totsubtot + $li_subtotdoc;
$li_tottot=$li_tottot + $li_montotdoc;
$li_totcar=$li_totcar + $li_moncardoc;
$li_totded=$li_totded + $li_mondeddoc;
$ld_fecemidoc=$io_funciones->uf_convertirfecmostrar($ld_fecemidoc);
$li_mondeddoc=number_format($li_mondeddoc,2,",",".");
$li_moncardoc=number_format($li_moncardoc,2,",",".");
$li_montotdoc=number_format($li_montotdoc,2,",",".");
$li_subtotdoc=number_format($li_subtotdoc,2,",",".");
$la_data[$li_s]=array('numrecdoc'=>$ls_numrecdoc,'fecemisol'=>$ld_fecemidoc,'mondeddoc'=>$li_mondeddoc,
'moncardoc'=>$li_moncardoc,'montotdoc'=>$li_montotdoc,'subtotdoc'=>$li_subtotdoc);
}
$li_totsubtot=number_format($li_totsubtot,2,",",".");
$li_tottot=number_format($li_tottot,2,",",".");
$li_totcar=number_format($li_totcar,2,",",".");
$li_totded=number_format($li_totded,2,",",".");
uf_print_detalle_recepcion($la_data,$li_totsubtot,$li_tottot,$li_totcar,$li_totded,&$io_pdf);
unset($la_data);
////////////////////////// GRID RECEPCIONES DE DOCUMENTOS //////////////////////////////////////
////////////////////////// GRID DETALLE PRESUPUESTARIO //////////////////////////////////////
$lb_valido=$io_report->uf_select_detalle_spg($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido)
{
$li_totrowspg=$io_report->ds_detalle_spg->getRowCount("codestpro");
$la_data="";
$li_totpre=0;
for($li_s=1;$li_s<=$li_totrowspg;$li_s++)
{
$ls_codestpro = trim($io_report->ds_detalle_spg->data["codestpro"][$li_s]);
$ls_spgcuenta = trim($io_report->ds_detalle_spg->data["spg_cuenta"][$li_s]);
$ls_denominacion = $io_report->ds_detalle_spg->data["denominacion"][$li_s];
$li_monto = $io_report->ds_detalle_spg->data["monto"][$li_s];
$li_totpre = $li_totpre+$li_monto;
$li_monto=number_format($li_monto,2,",",".");
$io_fun_cxp->uf_formatoprogramatica($ls_codestpro,&$ls_programatica);
$la_data[$li_s]=array('codestpro'=>$ls_programatica,'spg_cuenta'=>$ls_spgcuenta,
'denominacion'=>$ls_denominacion,'monto'=>$li_monto);
}
$li_totpre=number_format($li_totpre,2,",",".");
uf_print_detalle_spg($la_data,$li_totpre,&$io_pdf);
unset($la_data);
}
////////////////////////// GRID DETALLE PRESUPUESTARIO //////////////////////////////////////
////////////////////////// GRID DETALLE CONTABLE //////////////////////////////////////
$lb_valido=$io_report->uf_select_detalle_scg($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido)
{
$li_totrowscg=$io_report->ds_detalle_scg->getRowCount("sc_cuenta");
$la_data="";
$li_totdeb=0;
$li_tothab=0;
for($li_s=1;$li_s<=$li_totrowscg;$li_s++)
{
$ls_sccuenta=trim($io_report->ds_detalle_scg->data["sc_cuenta"][$li_s]);
$ls_debhab=trim($io_report->ds_detalle_scg->data["debhab"][$li_s]);
$ls_denominacion=trim($io_report->ds_detalle_scg->data["denominacion"][$li_s]);
$li_monto=$io_report->ds_detalle_scg->data["monto"][$li_s];
if($ls_debhab=="D")
{
$li_montodebe=$li_monto;
$li_montohab="";
$li_totdeb=$li_totdeb+$li_montodebe;
$li_montodebe=number_format($li_montodebe,2,",",".");
}
else
{
$li_montodebe="";
$li_montohab=$li_monto;
$li_tothab=$li_tothab+$li_montohab;
$li_montohab=number_format($li_montohab,2,",",".");
}
$la_data[$li_s]=array('sc_cuenta'=>$ls_sccuenta,'denominacion'=>$ls_denominacion,
'mondeb'=>$li_montodebe,'monhab'=>$li_montohab);
}
$li_totdeb=number_format($li_totdeb,2,",",".");
$li_tothab=number_format($li_tothab,2,",",".");
uf_print_detalle_scg($la_data,$li_totdeb,$li_tothab,&$io_pdf);
unset($la_data);
}
}
}
}
/* if($ls_tiporeporte==0)
{
uf_print_total_bsf($li_monsolaux,&$io_pdf);
}
*/ if($lb_valido) // Si no ocurrio ningún error
{
$io_pdf->ezStopPageNumbers(1,1); // Detenemos la impresión de los números de página
$io_pdf->ezStream(); // Mostramos el reporte
}
else // Si hubo algún error
{
print("<script language=JavaScript>");
print(" alert('Ocurrio un error al generar el reporte. Intente de Nuevo');");
print(" close();");
print("</script>");
}
}
?>
| ArrozAlba/huayra | cxp/reportes/sigesp_cxp_rfs_solicitudes_minfra.php | PHP | gpl-2.0 | 37,861 |
/*
This file is part of Warzone 2100.
Copyright (C) 2007 Giel van Schijndel
Copyright (C) 2007-2015 Warzone 2100 Project
Warzone 2100 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.
Warzone 2100 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 Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
$Revision$
$Id$
$HeadURL$
*/
/** \file
* Functions to convert between different Unicode Transformation Formats (UTF for short)
*/
#include "utf.h"
#include <assert.h>
#include <stdlib.h>
#if defined(LIB_COMPILE)
# define ASSERT(expr, ...) (assert(expr))
# define debug(part, ...) ((void)0)
#else
# include "debug.h"
#endif
// Assert that non-starting octets are of the form 10xxxxxx
#define ASSERT_NON_START_OCTET(octet) \
assert((octet & 0xC0) == 0x80 && "invalid non-start UTF-8 octet")
// Assert that starting octets are either of the form 0xxxxxxx (ASCII) or 11xxxxxx
#define ASSERT_START_OCTECT(octet) \
assert((octet & 0x80) == 0x00 || (octet & 0xC0) == 0xC0 || !"invalid starting UTF-8 octet")
// Assert that hexadect (16bit sequence) 1 of UTF-16 surrogate pair sequences are of the form 110110XXXXXXXXXX
#define ASSERT_START_HEXADECT(hexadect) \
assert(((hexadect) & 0xD800) == 0xD800 && "invalid first UTF-16 hexadect")
// Assert that hexadect (16bit sequence) 2 of UTF-16 surrogate pair sequences are of the form 110111XXXXXXXXXX
#define ASSERT_FINAL_HEXADECT(hexadect) \
assert(((hexadect) & 0xDC00) == 0xDC00 && "invalid first UTF-16 hexadect")
utf_32_char UTF8DecodeChar(const char *utf8_char, const char **next_char)
{
utf_32_char decoded = '\0';
*next_char = utf8_char;
ASSERT_START_OCTECT(*utf8_char);
// first octect: 0xxxxxxx: 7 bit (ASCII)
if ((*utf8_char & 0x80) == 0x00)
{
// 1 byte long encoding
decoded = *((*next_char)++);
}
// first octect: 110xxxxx: 11 bit
else if ((*utf8_char & 0xe0) == 0xc0)
{
// 2 byte long encoding
ASSERT_NON_START_OCTET(utf8_char[1]);
decoded = (*((*next_char)++) & 0x1f) << 6;
decoded |= (*((*next_char)++) & 0x3f) << 0;
}
// first octect: 1110xxxx: 16 bit
else if ((*utf8_char & 0xf0) == 0xe0)
{
// 3 byte long encoding
ASSERT_NON_START_OCTET(utf8_char[1]);
ASSERT_NON_START_OCTET(utf8_char[2]);
decoded = (*((*next_char)++) & 0x0f) << 12;
decoded |= (*((*next_char)++) & 0x3f) << 6;
decoded |= (*((*next_char)++) & 0x3f) << 0;
}
// first octect: 11110xxx: 21 bit
else if ((*utf8_char & 0xf8) == 0xf0)
{
// 4 byte long encoding
ASSERT_NON_START_OCTET(utf8_char[1]);
ASSERT_NON_START_OCTET(utf8_char[2]);
ASSERT_NON_START_OCTET(utf8_char[3]);
decoded = (*((*next_char)++) & 0x07) << 18;
decoded |= (*((*next_char)++) & 0x3f) << 12;
decoded |= (*((*next_char)++) & 0x3f) << 6;
decoded |= (*((*next_char)++) & 0x3f) << 0;
}
else
{
// apparently this character uses more than 21 bit
// this decoder is not developed to cope with those
// characters so error out
ASSERT(!"out-of-range UTF-8 character", "this UTF-8 character is too large (> 21bits) for this UTF-8 decoder and too large to be a valid Unicode codepoint");
}
return decoded;
}
size_t UTF8CharacterCount(const char *utf8_string)
{
size_t length = 0;
while (*utf8_string != '\0')
{
UTF8DecodeChar(utf8_string, &utf8_string);
++length;
}
return length;
}
size_t UTF16CharacterCount(const uint16_t *utf16)
{
size_t length = 0;
while (*utf16)
{
UTF16DecodeChar(utf16, &utf16);
++length;
}
return length;
}
static size_t unicode_utf8_char_length(const utf_32_char unicode_char)
{
// an ASCII character, which uses 7 bit at most, which is one byte in UTF-8
if (unicode_char < 0x00000080)
{
return 1; // stores 7 bits
}
else if (unicode_char < 0x00000800)
{
return 2; // stores 11 bits
}
else if (unicode_char < 0x00010000)
{
return 3; // stores 16 bits
}
/* This encoder can deal with < 0x00200000, but Unicode only ranges
* from 0x0 to 0x10FFFF. Thus we don't accept anything else.
*/
else if (unicode_char < 0x00110000)
{
return 4; // stores 21 bits
}
/* Apparently this character lies outside the 0x0 - 0x10FFFF
* Unicode range, so don't accept it.
*/
ASSERT(!"out-of-range Unicode codepoint", "This Unicode codepoint is too large (%u > 0x10FFFF) to be a valid Unicode codepoint", (unsigned int)unicode_char);
// Dummy value to prevent warnings about missing return from function
return 0;
}
char *UTF8CharacterAtOffset(const char *utf8_string, size_t index)
{
while (*utf8_string != '\0'
&& index != 0)
{
// Move to the next character
UTF8DecodeChar(utf8_string, &utf8_string);
--index;
}
if (*utf8_string == '\0')
{
return NULL;
}
return (char *)utf8_string;
}
/** Encodes a single Unicode character to a UTF-8 encoded string.
*
* \param unicode_char A UTF-32 encoded Unicode codepoint that will be encoded
* into UTF-8. This should be a valid Unicode codepoint
* (i.e. ranging from 0x0 to 0x10FFFF inclusive).
* \param out_char Points to the position in a buffer where the UTF-8
* encoded character can be stored.
*
* \return A pointer pointing to the first byte <em>after</em> the encoded
* UTF-8 sequence. This can be used as the \c out_char parameter for a
* next invocation of encode_utf8_char().
*/
static char *encode_utf8_char(const utf_32_char unicode_char, char *out_char)
{
char *next_char = out_char;
// 7 bits
if (unicode_char < 0x00000080)
{
*(next_char++) = unicode_char;
}
// 11 bits
else if (unicode_char < 0x00000800)
{
// 0xc0 provides the counting bits: 110
// then append the 5 most significant bits
*(next_char++) = 0xc0 | (unicode_char >> 6);
// Put the next 6 bits in a byte of their own
*(next_char++) = 0x80 | (unicode_char & 0x3f);
}
// 16 bits
else if (unicode_char < 0x00010000)
{
// 0xe0 provides the counting bits: 1110
// then append the 4 most significant bits
*(next_char++) = 0xe0 | (unicode_char >> 12);
// Put the next 12 bits in two bytes of their own
*(next_char++) = 0x80 | ((unicode_char >> 6) & 0x3f);
*(next_char++) = 0x80 | (unicode_char & 0x3f);
}
// 21 bits
/* This encoder can deal with < 0x00200000, but Unicode only ranges
* from 0x0 to 0x10FFFF. Thus we don't accept anything else.
*/
else if (unicode_char < 0x00110000)
{
// 0xf0 provides the counting bits: 11110
// then append the 3 most significant bits
*(next_char++) = 0xf0 | (unicode_char >> 18);
// Put the next 18 bits in three bytes of their own
*(next_char++) = 0x80 | ((unicode_char >> 12) & 0x3f);
*(next_char++) = 0x80 | ((unicode_char >> 6) & 0x3f);
*(next_char++) = 0x80 | (unicode_char & 0x3f);
}
else
{
/* Apparently this character lies outside the 0x0 - 0x10FFFF
* Unicode range, so don't accept it.
*/
ASSERT(!"out-of-range Unicode codepoint", "This Unicode codepoint is too large (%u > 0x10FFFF) to be a valid Unicode codepoint", (unsigned int)unicode_char);
}
return next_char;
}
utf_32_char UTF16DecodeChar(const utf_16_char *utf16_char, const utf_16_char **next_char)
{
utf_32_char decoded;
*next_char = utf16_char;
// Are we dealing with a surrogate pair
if (*utf16_char >= 0xD800
&& *utf16_char <= 0xDFFF)
{
ASSERT_START_HEXADECT(utf16_char[0]);
ASSERT_FINAL_HEXADECT(utf16_char[1]);
decoded = (*((*next_char)++) & 0x3ff) << 10;
decoded |= *((*next_char)++) & 0x3ff;
decoded += 0x10000;
}
// Not a surrogate pair, so it's a valid Unicode codepoint right away
else
{
decoded = *((*next_char)++);
}
return decoded;
}
/** Encodes a single Unicode character to a UTF-16 encoded string.
*
* \param unicode_char A UTF-32 encoded Unicode codepoint that will be encoded
* into UTF-16. This should be a valid Unicode codepoint
* (i.e. ranging from 0x0 to 0x10FFFF inclusive).
* \param out_char Points to the position in a buffer where the UTF-16
* encoded character can be stored.
*
* \return A pointer pointing to the first byte <em>after</em> the encoded
* UTF-16 sequence. This can be used as the \c out_char parameter for a
* next invocation of encode_utf16_char().
*/
static utf_16_char *encode_utf16_char(const utf_32_char unicode_char, utf_16_char *out_char)
{
utf_16_char *next_char = out_char;
// 16 bits
if (unicode_char < 0x10000)
{
*(next_char++) = unicode_char;
}
else if (unicode_char < 0x110000)
{
const utf_16_char v = unicode_char - 0x10000;
*(next_char++) = 0xD800 | (v >> 10);
*(next_char++) = 0xDC00 | (v & 0x3ff);
ASSERT_START_HEXADECT(out_char[0]);
ASSERT_FINAL_HEXADECT(out_char[1]);
}
else
{
/* Apparently this character lies outside the 0x0 - 0x10FFFF
* Unicode range, and UTF-16 cannot cope with that, so error
* out.
*/
ASSERT(!"out-of-range Unicode codepoint", "This Unicode codepoint is too large (%u > 0x10FFFF) to be a valid Unicode codepoint", (unsigned int)unicode_char);
}
return next_char;
}
static size_t utf16_utf8_buffer_length(const utf_16_char *unicode_string)
{
const utf_16_char *curChar = unicode_string;
// Determine length of string (in octets) when encoded in UTF-8
size_t length = 0;
while (*curChar)
{
length += unicode_utf8_char_length(UTF16DecodeChar(curChar, &curChar));
}
return length;
}
char *UTF16toUTF8(const utf_16_char *unicode_string, size_t *nbytes)
{
const utf_16_char *curChar;
const size_t utf8_length = utf16_utf8_buffer_length(unicode_string);
// Allocate memory to hold the UTF-8 encoded string (plus a terminating nul char)
char *utf8_string = (char *)malloc(utf8_length + 1);
char *curOutPos = utf8_string;
if (utf8_string == NULL)
{
debug(LOG_ERROR, "Out of memory");
return NULL;
}
curChar = unicode_string;
while (*curChar)
{
curOutPos = encode_utf8_char(UTF16DecodeChar(curChar, &curChar), curOutPos);
}
// Terminate the string with a nul character
utf8_string[utf8_length] = '\0';
// Set the number of bytes allocated
if (nbytes)
{
*nbytes = utf8_length + 1;
}
return utf8_string;
}
static size_t utf8_as_utf16_buf_size(const char *utf8_string)
{
const char *curChar = utf8_string;
size_t length = 0;
while (*curChar != '\0')
{
const utf_32_char unicode_char = UTF8DecodeChar(curChar, &curChar);
if (unicode_char < 0x10000)
{
length += 1;
}
else if (unicode_char < 0x110000)
{
length += 2;
}
else
{
/* Apparently this character lies outside the 0x0 - 0x10FFFF
* Unicode range, and UTF-16 cannot cope with that, so error
* out.
*/
ASSERT(!"out-of-range Unicode codepoint", "This Unicode codepoint too large (%u > 0x10FFFF) for the UTF-16 encoding", (unsigned int)unicode_char);
}
}
return length;
}
utf_16_char *UTF8toUTF16(const char *utf8_string, size_t *nbytes)
{
const char *curChar = utf8_string;
const size_t unicode_length = utf8_as_utf16_buf_size(utf8_string);
// Allocate memory to hold the UTF-16 encoded string (plus a terminating nul)
utf_16_char *unicode_string = (utf_16_char *)malloc(sizeof(utf_16_char) * (unicode_length + 1));
utf_16_char *curOutPos = unicode_string;
if (unicode_string == NULL)
{
debug(LOG_ERROR, "Out of memory");
return NULL;
}
while (*curChar != '\0')
{
curOutPos = encode_utf16_char(UTF8DecodeChar(curChar, &curChar), curOutPos);
}
// Terminate the string with a nul
unicode_string[unicode_length] = '\0';
// Set the number of bytes allocated
if (nbytes)
{
*nbytes = sizeof(utf_16_char) * (unicode_length + 1);
}
return unicode_string;
}
utf_16_char *UTF16CharacterAtOffset(const utf_16_char *utf16_string, size_t index)
{
while (*utf16_string != '\0'
&& index != 0)
{
// Move to the next character
UTF16DecodeChar(utf16_string, &utf16_string);
--index;
}
if (*utf16_string == '\0')
{
return NULL;
}
return (utf_16_char *)utf16_string;
}
static size_t utf32_utf8_buffer_length(const utf_32_char *unicode_string)
{
const utf_32_char *curChar;
// Determine length of string (in octets) when encoded in UTF-8
size_t length = 0;
for (curChar = unicode_string; *curChar != '\0'; ++curChar)
{
length += unicode_utf8_char_length(*curChar);
}
return length;
}
char *UTF32toUTF8(const utf_32_char *unicode_string, size_t *nbytes)
{
const utf_32_char *curChar;
const size_t utf8_length = utf32_utf8_buffer_length(unicode_string);
// Allocate memory to hold the UTF-8 encoded string (plus a terminating nul char)
char *utf8_string = (char *)malloc(utf8_length + 1);
char *curOutPos = utf8_string;
if (utf8_string == NULL)
{
debug(LOG_ERROR, "Out of memory");
return NULL;
}
for (curChar = unicode_string; *curChar != 0; ++curChar)
{
curOutPos = encode_utf8_char(*curChar, curOutPos);
}
// Terminate the string with a nul character
utf8_string[utf8_length] = '\0';
// Set the number of bytes allocated
if (nbytes)
{
*nbytes = utf8_length + 1;
}
return utf8_string;
}
utf_32_char *UTF8toUTF32(const char *utf8_string, size_t *nbytes)
{
const char *curChar = utf8_string;
const size_t unicode_length = UTF8CharacterCount(utf8_string);
// Allocate memory to hold the UTF-32 encoded string (plus a terminating nul)
utf_32_char *unicode_string = (utf_32_char *)malloc(sizeof(utf_32_char) * (unicode_length + 1));
utf_32_char *curOutPos = unicode_string;
if (unicode_string == NULL)
{
debug(LOG_ERROR, "Out of memory");
return NULL;
}
while (*curChar != '\0')
{
*(curOutPos++) = UTF8DecodeChar(curChar, &curChar);
}
// Terminate the string with a nul
unicode_string[unicode_length] = '\0';
// Set the number of bytes allocated
if (nbytes)
{
*nbytes = sizeof(utf_32_char) * (unicode_length + 1);
}
return unicode_string;
}
| skiz/warzone2100 | lib/framework/utf.cpp | C++ | gpl-2.0 | 14,247 |
// PR c++/39866
// { dg-options "-std=c++0x" }
struct A {
A& operator=(const A&) = delete; // { dg-bogus "" }
void operator=(int) {} // { dg-message "" }
void operator=(char) {} // { dg-message "" }
};
struct B {};
int main()
{
A a;
a = B(); // { dg-error "no match" }
a = 1.0; // { dg-error "ambiguous" }
}
| ccompiler4pic32/pic32-gcc | gcc/testsuite/g++.dg/cpp0x/defaulted14.C | C++ | gpl-2.0 | 326 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.