repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
sfshine/actor-platform | actor-apps/app-web/src/app/actions/DialogActionCreators.js | 1753 | import ActorClient from 'utils/ActorClient';
import ActorAppDispatcher from 'dispatcher/ActorAppDispatcher';
import ActorAppConstants from 'constants/ActorAppConstants';
const ActionTypes = ActorAppConstants.ActionTypes;
const DialogActionCreators = {
setDialogs(dialogs) {
ActorAppDispatcher.dispatch({
type: ActionTypes.DIALOGS_CHANGED,
dialogs: dialogs
});
},
selectDialogPeer(peer) {
ActorAppDispatcher.dispatch({
type: ActionTypes.SELECT_DIALOG_PEER,
peer: peer
});
},
selectDialogPeerUser(userId) {
if (userId === ActorClient.getUid()) {
console.warn('You can\'t chat with yourself');
} else {
this.selectDialogPeer({
type: ActorAppConstants.PeerTypes.USER,
id: userId
});
}
},
createSelectedDialogInfoChanged(info) {
ActorAppDispatcher.dispatch({
type: ActionTypes.SELECTED_DIALOG_INFO_CHANGED,
info: info
});
},
onConversationOpen(peer) {
ActorClient.onConversationOpen(peer);
},
onConversationClosed(peer) {
ActorClient.onConversationClosed(peer);
},
onDialogsEnd() {
ActorClient.onDialogsEnd();
},
onChatEnd(peer) {
ActorClient.onChatEnd(peer);
},
leaveGroup(groupId) {
ActorClient
.leaveGroup(groupId)
.then(() => {
ActorAppDispatcher.dispatch({
type: ActionTypes.LEFT_GROUP,
groupId: groupId
});
});
},
kickMember(userId, groupId) {
ActorClient.kickMember(userId, groupId);
},
changeNotificationsEnabled(peer, isEnabled) {
ActorAppDispatcher.dispatch({
type: ActionTypes.NOTIFICATION_CHANGE,
peer: peer,
isEnabled: isEnabled
});
}
};
export default DialogActionCreators;
| mit |
rolandzwaga/DefinitelyTyped | types/react-virtualized/dist/es/WindowScroller.d.ts | 2630 | import { Validator, Requireable, PureComponent } from "react";
/**
* Specifies the number of miliseconds during which to disable pointer events while a scroll is in progress.
* This improves performance and makes scrolling smoother.
*/
export const IS_SCROLLING_TIMEOUT = 150;
export type WindowScrollerChildProps = {
height: number;
width: number;
isScrolling: boolean;
scrollTop: number;
onChildScroll: () => void;
};
export type WindowScrollerProps = {
/**
* Function responsible for rendering children.
* This function should implement the following signature:
* ({ height, isScrolling, scrollLeft, scrollTop, width }) => PropTypes.element
*/
children: (
params: {
onChildScroll: (params: { scrollTop: number }) => void;
registerChild: (params?: Element) => void;
height: number;
isScrolling: boolean;
scrollLeft: number;
scrollTop: number;
width: number;
}
) => React.ReactNode;
/** Callback to be invoked on-resize: ({ height, width }) */
onResize?: (params: { height: number; width: number }) => void;
/** Callback to be invoked on-scroll: ({ scrollLeft, scrollTop }) */
onScroll?: (params: { scrollLeft: number; scrollTop: number }) => void;
/** Element to attach scroll event listeners. Defaults to window. */
scrollElement?: typeof window | Element;
/**
* Wait this amount of time after the last scroll event before resetting child `pointer-events`.
*/
scrollingResetTimeInterval?: number;
/** Height used for server-side rendering */
serverHeight?: number;
/** Width used for server-side rendering */
serverWidth?: number;
/**
* PLEASE NOTE
* The [key: string]: any; line is here on purpose
* This is due to the need of force re-render of PureComponent
* Check the following link if you want to know more
* https://github.com/bvaughn/react-virtualized#pass-thru-props
*/
[key: string]: any;
};
export type WindowScrollerState = {
height: number;
width: number;
isScrolling: boolean;
scrollLeft: number;
scrollTop: number;
};
export class WindowScroller extends PureComponent<
WindowScrollerProps,
WindowScrollerState
> {
static defaultProps: {
onResize: () => void;
onScroll: () => void;
scrollingResetTimeInterval: typeof IS_SCROLLING_TIMEOUT;
scrollElement: Window | undefined;
serverHeight: 0;
serverWidth: 0;
};
updatePosition(scrollElement?: HTMLElement): void;
}
| mit |
extend1994/cdnjs | ajax/libs/bootstrap-table/1.15.2/locale/bootstrap-table-es-CR.js | 23475 | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) :
typeof define === 'function' && define.amd ? define(['jquery'], factory) :
(global = global || self, factory(global.jQuery));
}(this, function ($) { 'use strict';
$ = $ && $.hasOwnProperty('default') ? $['default'] : $;
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var O = 'object';
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global_1 =
// eslint-disable-next-line no-undef
check(typeof globalThis == O && globalThis) ||
check(typeof window == O && window) ||
check(typeof self == O && self) ||
check(typeof commonjsGlobal == O && commonjsGlobal) ||
// eslint-disable-next-line no-new-func
Function('return this')();
var fails = function (exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
// Thank's IE8 for his funny defineProperty
var descriptors = !fails(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);
// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
var f = NASHORN_BUG ? function propertyIsEnumerable(V) {
var descriptor = getOwnPropertyDescriptor(this, V);
return !!descriptor && descriptor.enumerable;
} : nativePropertyIsEnumerable;
var objectPropertyIsEnumerable = {
f: f
};
var createPropertyDescriptor = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
var toString = {}.toString;
var classofRaw = function (it) {
return toString.call(it).slice(8, -1);
};
var split = ''.split;
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var indexedObject = fails(function () {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins
return !Object('z').propertyIsEnumerable(0);
}) ? function (it) {
return classofRaw(it) == 'String' ? split.call(it, '') : Object(it);
} : Object;
// `RequireObjectCoercible` abstract operation
// https://tc39.github.io/ecma262/#sec-requireobjectcoercible
var requireObjectCoercible = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
// toObject with fallback for non-array-like ES3 strings
var toIndexedObject = function (it) {
return indexedObject(requireObjectCoercible(it));
};
var isObject = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
// `ToPrimitive` abstract operation
// https://tc39.github.io/ecma262/#sec-toprimitive
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
var toPrimitive = function (input, PREFERRED_STRING) {
if (!isObject(input)) return input;
var fn, val;
if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
throw TypeError("Can't convert object to primitive value");
};
var hasOwnProperty = {}.hasOwnProperty;
var has = function (it, key) {
return hasOwnProperty.call(it, key);
};
var document = global_1.document;
// typeof document.createElement is 'object' in old IE
var EXISTS = isObject(document) && isObject(document.createElement);
var documentCreateElement = function (it) {
return EXISTS ? document.createElement(it) : {};
};
// Thank's IE8 for his funny defineProperty
var ie8DomDefine = !descriptors && !fails(function () {
return Object.defineProperty(documentCreateElement('div'), 'a', {
get: function () { return 7; }
}).a != 7;
});
var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
var f$1 = descriptors ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
O = toIndexedObject(O);
P = toPrimitive(P, true);
if (ie8DomDefine) try {
return nativeGetOwnPropertyDescriptor(O, P);
} catch (error) { /* empty */ }
if (has(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]);
};
var objectGetOwnPropertyDescriptor = {
f: f$1
};
var anObject = function (it) {
if (!isObject(it)) {
throw TypeError(String(it) + ' is not an object');
} return it;
};
var nativeDefineProperty = Object.defineProperty;
// `Object.defineProperty` method
// https://tc39.github.io/ecma262/#sec-object.defineproperty
var f$2 = descriptors ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (ie8DomDefine) try {
return nativeDefineProperty(O, P, Attributes);
} catch (error) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
var objectDefineProperty = {
f: f$2
};
var hide = descriptors ? function (object, key, value) {
return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
var setGlobal = function (key, value) {
try {
hide(global_1, key, value);
} catch (error) {
global_1[key] = value;
} return value;
};
var shared = createCommonjsModule(function (module) {
var SHARED = '__core-js_shared__';
var store = global_1[SHARED] || setGlobal(SHARED, {});
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: '3.1.3',
mode: 'global',
copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
});
});
var functionToString = shared('native-function-to-string', Function.toString);
var WeakMap = global_1.WeakMap;
var nativeWeakMap = typeof WeakMap === 'function' && /native code/.test(functionToString.call(WeakMap));
var id = 0;
var postfix = Math.random();
var uid = function (key) {
return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
};
var keys = shared('keys');
var sharedKey = function (key) {
return keys[key] || (keys[key] = uid(key));
};
var hiddenKeys = {};
var WeakMap$1 = global_1.WeakMap;
var set, get, has$1;
var enforce = function (it) {
return has$1(it) ? get(it) : set(it, {});
};
var getterFor = function (TYPE) {
return function (it) {
var state;
if (!isObject(it) || (state = get(it)).type !== TYPE) {
throw TypeError('Incompatible receiver, ' + TYPE + ' required');
} return state;
};
};
if (nativeWeakMap) {
var store = new WeakMap$1();
var wmget = store.get;
var wmhas = store.has;
var wmset = store.set;
set = function (it, metadata) {
wmset.call(store, it, metadata);
return metadata;
};
get = function (it) {
return wmget.call(store, it) || {};
};
has$1 = function (it) {
return wmhas.call(store, it);
};
} else {
var STATE = sharedKey('state');
hiddenKeys[STATE] = true;
set = function (it, metadata) {
hide(it, STATE, metadata);
return metadata;
};
get = function (it) {
return has(it, STATE) ? it[STATE] : {};
};
has$1 = function (it) {
return has(it, STATE);
};
}
var internalState = {
set: set,
get: get,
has: has$1,
enforce: enforce,
getterFor: getterFor
};
var redefine = createCommonjsModule(function (module) {
var getInternalState = internalState.get;
var enforceInternalState = internalState.enforce;
var TEMPLATE = String(functionToString).split('toString');
shared('inspectSource', function (it) {
return functionToString.call(it);
});
(module.exports = function (O, key, value, options) {
var unsafe = options ? !!options.unsafe : false;
var simple = options ? !!options.enumerable : false;
var noTargetGet = options ? !!options.noTargetGet : false;
if (typeof value == 'function') {
if (typeof key == 'string' && !has(value, 'name')) hide(value, 'name', key);
enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');
}
if (O === global_1) {
if (simple) O[key] = value;
else setGlobal(key, value);
return;
} else if (!unsafe) {
delete O[key];
} else if (!noTargetGet && O[key]) {
simple = true;
}
if (simple) O[key] = value;
else hide(O, key, value);
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, 'toString', function toString() {
return typeof this == 'function' && getInternalState(this).source || functionToString.call(this);
});
});
var path = global_1;
var aFunction = function (variable) {
return typeof variable == 'function' ? variable : undefined;
};
var getBuiltIn = function (namespace, method) {
return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global_1[namespace])
: path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method];
};
var ceil = Math.ceil;
var floor = Math.floor;
// `ToInteger` abstract operation
// https://tc39.github.io/ecma262/#sec-tointeger
var toInteger = function (argument) {
return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
};
var min = Math.min;
// `ToLength` abstract operation
// https://tc39.github.io/ecma262/#sec-tolength
var toLength = function (argument) {
return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};
var max = Math.max;
var min$1 = Math.min;
// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(length, length).
var toAbsoluteIndex = function (index, length) {
var integer = toInteger(index);
return integer < 0 ? max(integer + length, 0) : min$1(integer, length);
};
// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIndexedObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) {
if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
var arrayIncludes = {
// `Array.prototype.includes` method
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
includes: createMethod(true),
// `Array.prototype.indexOf` method
// https://tc39.github.io/ecma262/#sec-array.prototype.indexof
indexOf: createMethod(false)
};
var indexOf = arrayIncludes.indexOf;
var objectKeysInternal = function (object, names) {
var O = toIndexedObject(object);
var i = 0;
var result = [];
var key;
for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~indexOf(result, key) || result.push(key);
}
return result;
};
// IE8- don't enum bug keys
var enumBugKeys = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
var hiddenKeys$1 = enumBugKeys.concat('length', 'prototype');
// `Object.getOwnPropertyNames` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertynames
var f$3 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return objectKeysInternal(O, hiddenKeys$1);
};
var objectGetOwnPropertyNames = {
f: f$3
};
var f$4 = Object.getOwnPropertySymbols;
var objectGetOwnPropertySymbols = {
f: f$4
};
// all object keys, includes non-enumerable and symbols
var ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
var keys = objectGetOwnPropertyNames.f(anObject(it));
var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
};
var copyConstructorProperties = function (target, source) {
var keys = ownKeys(source);
var defineProperty = objectDefineProperty.f;
var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
};
var replacement = /#|\.prototype\./;
var isForced = function (feature, detection) {
var value = data[normalize(feature)];
return value == POLYFILL ? true
: value == NATIVE ? false
: typeof detection == 'function' ? fails(detection)
: !!detection;
};
var normalize = isForced.normalize = function (string) {
return String(string).replace(replacement, '.').toLowerCase();
};
var data = isForced.data = {};
var NATIVE = isForced.NATIVE = 'N';
var POLYFILL = isForced.POLYFILL = 'P';
var isForced_1 = isForced;
var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.noTargetGet - prevent calling a getter on target
*/
var _export = function (options, source) {
var TARGET = options.target;
var GLOBAL = options.global;
var STATIC = options.stat;
var FORCED, target, key, targetProperty, sourceProperty, descriptor;
if (GLOBAL) {
target = global_1;
} else if (STATIC) {
target = global_1[TARGET] || setGlobal(TARGET, {});
} else {
target = (global_1[TARGET] || {}).prototype;
}
if (target) for (key in source) {
sourceProperty = source[key];
if (options.noTargetGet) {
descriptor = getOwnPropertyDescriptor$1(target, key);
targetProperty = descriptor && descriptor.value;
} else targetProperty = target[key];
FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
// contained in target
if (!FORCED && targetProperty !== undefined) {
if (typeof sourceProperty === typeof targetProperty) continue;
copyConstructorProperties(sourceProperty, targetProperty);
}
// add a flag to not completely full polyfills
if (options.sham || (targetProperty && targetProperty.sham)) {
hide(sourceProperty, 'sham', true);
}
// extend global
redefine(target, key, sourceProperty, options);
}
};
// `IsArray` abstract operation
// https://tc39.github.io/ecma262/#sec-isarray
var isArray = Array.isArray || function isArray(arg) {
return classofRaw(arg) == 'Array';
};
// `ToObject` abstract operation
// https://tc39.github.io/ecma262/#sec-toobject
var toObject = function (argument) {
return Object(requireObjectCoercible(argument));
};
var createProperty = function (object, key, value) {
var propertyKey = toPrimitive(key);
if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value));
else object[propertyKey] = value;
};
var nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () {
// Chrome 38 Symbol has incorrect toString conversion
// eslint-disable-next-line no-undef
return !String(Symbol());
});
var Symbol$1 = global_1.Symbol;
var store$1 = shared('wks');
var wellKnownSymbol = function (name) {
return store$1[name] || (store$1[name] = nativeSymbol && Symbol$1[name]
|| (nativeSymbol ? Symbol$1 : uid)('Symbol.' + name));
};
var SPECIES = wellKnownSymbol('species');
// `ArraySpeciesCreate` abstract operation
// https://tc39.github.io/ecma262/#sec-arrayspeciescreate
var arraySpeciesCreate = function (originalArray, length) {
var C;
if (isArray(originalArray)) {
C = originalArray.constructor;
// cross-realm fallback
if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
else if (isObject(C)) {
C = C[SPECIES];
if (C === null) C = undefined;
}
} return new (C === undefined ? Array : C)(length === 0 ? 0 : length);
};
var SPECIES$1 = wellKnownSymbol('species');
var arrayMethodHasSpeciesSupport = function (METHOD_NAME) {
return !fails(function () {
var array = [];
var constructor = array.constructor = {};
constructor[SPECIES$1] = function () {
return { foo: 1 };
};
return array[METHOD_NAME](Boolean).foo !== 1;
});
};
var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded';
var IS_CONCAT_SPREADABLE_SUPPORT = !fails(function () {
var array = [];
array[IS_CONCAT_SPREADABLE] = false;
return array.concat()[0] !== array;
});
var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');
var isConcatSpreadable = function (O) {
if (!isObject(O)) return false;
var spreadable = O[IS_CONCAT_SPREADABLE];
return spreadable !== undefined ? !!spreadable : isArray(O);
};
var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT;
// `Array.prototype.concat` method
// https://tc39.github.io/ecma262/#sec-array.prototype.concat
// with adding support of @@isConcatSpreadable and @@species
_export({ target: 'Array', proto: true, forced: FORCED }, {
concat: function concat(arg) { // eslint-disable-line no-unused-vars
var O = toObject(this);
var A = arraySpeciesCreate(O, 0);
var n = 0;
var i, k, length, len, E;
for (i = -1, length = arguments.length; i < length; i++) {
E = i === -1 ? O : arguments[i];
if (isConcatSpreadable(E)) {
len = toLength(E.length);
if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
} else {
if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
createProperty(A, n++, E);
}
}
A.length = n;
return A;
}
});
/**
* Bootstrap Table Spanish (Costa Rica) translation
* Author: Dennis Hernández (http://djhvscf.github.io/Blog/)
*/
$.fn.bootstrapTable.locales['es-CR'] = {
formatLoadingMessage: function formatLoadingMessage() {
return 'Cargando, por favor espere';
},
formatRecordsPerPage: function formatRecordsPerPage(pageNumber) {
return "".concat(pageNumber, " registros por p\xE1gina");
},
formatShowingRows: function formatShowingRows(pageFrom, pageTo, totalRows, totalNotFiltered) {
if (totalNotFiltered !== undefined && totalNotFiltered > 0 && totalNotFiltered > totalRows) {
return "Mostrando de ".concat(pageFrom, " a ").concat(pageTo, " registros de ").concat(totalRows, " registros en total (filtered from ").concat(totalNotFiltered, " total rows)");
}
return "Mostrando de ".concat(pageFrom, " a ").concat(pageTo, " registros de ").concat(totalRows, " registros en total");
},
formatSRPaginationPreText: function formatSRPaginationPreText() {
return 'previous page';
},
formatSRPaginationPageText: function formatSRPaginationPageText(page) {
return "to page ".concat(page);
},
formatSRPaginationNextText: function formatSRPaginationNextText() {
return 'next page';
},
formatDetailPagination: function formatDetailPagination(totalRows) {
return "Showing ".concat(totalRows, " rows");
},
formatClearSearch: function formatClearSearch() {
return 'Limpiar búsqueda';
},
formatSearch: function formatSearch() {
return 'Buscar';
},
formatNoMatches: function formatNoMatches() {
return 'No se encontraron registros';
},
formatPaginationSwitch: function formatPaginationSwitch() {
return 'Hide/Show pagination';
},
formatPaginationSwitchDown: function formatPaginationSwitchDown() {
return 'Show pagination';
},
formatPaginationSwitchUp: function formatPaginationSwitchUp() {
return 'Hide pagination';
},
formatRefresh: function formatRefresh() {
return 'Refrescar';
},
formatToggle: function formatToggle() {
return 'Alternar';
},
formatToggleOn: function formatToggleOn() {
return 'Show card view';
},
formatToggleOff: function formatToggleOff() {
return 'Hide card view';
},
formatColumns: function formatColumns() {
return 'Columnas';
},
formatColumnsToggleAll: function formatColumnsToggleAll() {
return 'Toggle all';
},
formatFullscreen: function formatFullscreen() {
return 'Fullscreen';
},
formatAllRows: function formatAllRows() {
return 'Todo';
},
formatAutoRefresh: function formatAutoRefresh() {
return 'Auto Refresh';
},
formatExport: function formatExport() {
return 'Export data';
},
formatJumpTo: function formatJumpTo() {
return 'GO';
},
formatAdvancedSearch: function formatAdvancedSearch() {
return 'Advanced search';
},
formatAdvancedCloseButton: function formatAdvancedCloseButton() {
return 'Close';
}
};
$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['es-CR']);
}));
| mit |
sevoku/oxyplot | Source/Examples/WPF/ExportDemo/IShell.cs | 410 | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="IShell.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace ExportDemo {
public interface IShell {}
} | mit |
3meng/Windows-universal-samples | xaml_listview/SamplesPane.xaml.cs | 1587 | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace ListViewSample
{
public sealed partial class SamplesPane : UserControl
{
public SamplesPane()
{
this.InitializeComponent();
}
private void NavigateToOptimized(object sender, RoutedEventArgs e)
{
((Frame)Window.Current.Content).Navigate(typeof(SimpleListViewSample));
}
private void NavigateToOptimizedGrid(object sender, RoutedEventArgs e)
{
((Frame)Window.Current.Content).Navigate(typeof(SimpleGridViewSample));
}
private void NavigateToMasterDetailSelection(object sender, RoutedEventArgs e)
{
((Frame)Window.Current.Content).Navigate(typeof(MasterDetailSelection));
}
private void NavigateToEdgeTappedListView(object sender, RoutedEventArgs e)
{
((Frame)Window.Current.Content).Navigate(typeof(TapOnTheEdgeSample));
}
private void NavigateToHome(object sender, RoutedEventArgs e)
{
((Frame)Window.Current.Content).Navigate(typeof(MainPage));
}
}
}
| mit |
como-quesito/angular-xeditable | starter/app.js | 268 | var app = angular.module("app", ["xeditable"]);
app.run(function(editableOptions) {
editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});
app.controller('Ctrl', function($scope) {
$scope.user = {
name: 'awesome user'
};
}); | mit |
JoeMarion/JoeMarion.github.io | MakingitMarions/vendor/bundle/gems/maruku-0.7.0/lib/maruku/maruku.rb | 296 | # The public interface for Maruku.
#
# @example Render a document fragment
# Maruku.new("## Header ##").to_html
# # => "<h2 id='header'>header</h2>"
class Maruku < MaRuKu::MDDocument
def initialize(s = nil, meta = {})
super()
self.attributes.merge! meta
parse_doc(s) if s
end
end
| mit |
maxwhale/app | Public/static/js/easyui/plugins/jquery.progressbar.js | 2171 | /**
* jQuery EasyUI 1.4.2
*
* Copyright (c) 2009-2015 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt
* To use it on other terms please contact us at [email protected]
*
*/
(function($){
function _1(_2){
$(_2).addClass("progressbar");
$(_2).html("<div class=\"progressbar-text\"></div><div class=\"progressbar-value\"><div class=\"progressbar-text\"></div></div>");
$(_2).bind("_resize",function(e,_3){
if($(this).hasClass("easyui-fluid")||_3){
_4(_2);
}
return false;
});
return $(_2);
};
function _4(_5,_6){
var _7=$.data(_5,"progressbar").options;
var _8=$.data(_5,"progressbar").bar;
if(_6){
_7.width=_6;
}
_8._size(_7);
_8.find("div.progressbar-text").css("width",_8.width());
_8.find("div.progressbar-text,div.progressbar-value").css({height:_8.height()+"px",lineHeight:_8.height()+"px"});
};
$.fn.progressbar=function(_9,_a){
if(typeof _9=="string"){
var _b=$.fn.progressbar.methods[_9];
if(_b){
return _b(this,_a);
}
}
_9=_9||{};
return this.each(function(){
var _c=$.data(this,"progressbar");
if(_c){
$.extend(_c.options,_9);
}else{
_c=$.data(this,"progressbar",{options:$.extend({},$.fn.progressbar.defaults,$.fn.progressbar.parseOptions(this),_9),bar:_1(this)});
}
$(this).progressbar("setValue",_c.options.value);
_4(this);
});
};
$.fn.progressbar.methods={options:function(jq){
return $.data(jq[0],"progressbar").options;
},resize:function(jq,_d){
return jq.each(function(){
_4(this,_d);
});
},getValue:function(jq){
return $.data(jq[0],"progressbar").options.value;
},setValue:function(jq,_e){
if(_e<0){
_e=0;
}
if(_e>100){
_e=100;
}
return jq.each(function(){
var _f=$.data(this,"progressbar").options;
var _10=_f.text.replace(/{value}/,_e);
var _11=_f.value;
_f.value=_e;
$(this).find("div.progressbar-value").width(_e+"%");
$(this).find("div.progressbar-text").html(_10);
if(_11!=_e){
_f.onChange.call(this,_e,_11);
}
});
}};
$.fn.progressbar.parseOptions=function(_12){
return $.extend({},$.parser.parseOptions(_12,["width","height","text",{value:"number"}]));
};
$.fn.progressbar.defaults={width:"auto",height:22,value:0,text:"{value}%",onChange:function(_13,_14){
}};
})(jQuery);
| gpl-2.0 |
wiki1210/yokozuna | wp-content/plugins/facebook/admin/settings-debug.php | 16339 | <?php
/**
* Summarize the plugin configuration on a single page
*
* @since 1.1.6
*/
class Facebook_Settings_Debugger {
/**
* Page identifier
*
* @since 1.1.6
* @var string
*/
const PAGE_SLUG = 'facebook-debug';
/**
* HTML span noting a feature exists
*
* @since 1.1.6
* @var string
*/
const EXISTS = '<span class="feature-present">✓</span>';
/**
* HTML span noting a feature does not exist
*
* @since 1.1.6
* @var string
*/
const DOES_NOT_EXIST = '<span class="feature-not-present">X</span>';
/**
* Reference the social plugin by name
*
* @since 1.1.6
* @return string social plugin name
*/
public static function social_plugin_name() {
return __( 'Debugger', 'facebook' );
}
/**
* Navigate to the debugger page through the Facebook top-level menu item
*
* @since 1.1.6
* @uses add_submenu_page()
* @param string $parent_slug Facebook top-level menu item slug
* @return string submenu hook suffix
*/
public static function add_submenu_item( $parent_slug ) {
$hook_suffix = add_submenu_page(
$parent_slug,
self::social_plugin_name(),
self::social_plugin_name(),
'manage_options',
self::PAGE_SLUG,
array( 'Facebook_Settings_Debugger', 'content' )
);
if ( $hook_suffix ) {
add_action( 'load-' . $hook_suffix, array( 'Facebook_Settings_Debugger', 'onload' ) );
}
return $hook_suffix;
}
/**
* Load scripts and other setup functions on page load
*/
public static function onload() {
add_action( 'admin_enqueue_scripts', array( 'Facebook_Settings_Debugger', 'enqueue_scripts' ) );
}
/**
* Enqueue scripts and styles
*
* @since 1.1.6
*/
public static function enqueue_scripts() {
wp_enqueue_style( self::PAGE_SLUG, plugins_url( 'static/css/admin/debug' . ( ( defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ) ? '' : '.min' ) . '.css', dirname( __FILE__ ) ), array(), '1.1.6' );
}
/**
* Page content
*
* @since 1.1.6
*/
public static function content() {
global $facebook_loader;
if ( ! class_exists( 'Facebook_Settings' ) )
require_once( dirname(__FILE__) . '/settings.php' );
echo '<div class="wrap">';
echo '<header><h2>' . esc_html( self::social_plugin_name() ) . '</h2></header>';
// only show users if app credentials stored
if ( $facebook_loader->app_access_token_exists() ) {
self::users_section();
self::post_to_page_section();
}
self::enabled_features_by_view_type();
self::widgets_section();
self::server_info();
echo '</div>';
Facebook_Settings::stats_beacon();
}
/**
* Get all users with edit_posts capabilities broken out into Facebook-permissioned users and non-Facebook permissioned users
*
* @since 1.1.6
*/
public static function get_all_wordpress_facebook_users() {
if ( ! class_exists( 'Facebook_User' ) )
require_once( dirname( dirname( __FILE__ ) ) . '/facebook-user.php' );
// fb => [], wp => []
$users = Facebook_User::get_wordpress_users_associated_with_facebook_accounts();
$users_with_app_permissions = array();
if ( ! empty( $users['fb'] ) ) {
if ( ! class_exists( 'Facebook_WP_Extend' ) )
require_once( dirname( dirname( __FILE__ ) ) . '/includes/facebook-php-sdk/class-facebook-wp.php' );
foreach ( $users['fb'] as $user ) {
if ( ! isset( $user->fb_data['fb_uid'] ) ) {
$users['wp'][] = $user;
continue;
}
$facebook_user_permissions = Facebook_WP_Extend::get_permissions_by_facebook_user_id( $user->fb_data['fb_uid'] );
if ( ! is_array( $facebook_user_permissions ) || ! isset( $facebook_user_permissions['installed'] ) ) {
$users['wp'][] = $user;
continue;
}
$user->fb_data['permissions'] = $facebook_user_permissions;
unset( $facebook_user_permissions );
$users_with_app_permissions[] = $user;
}
}
$users['fb'] = $users_with_app_permissions;
return $users;
}
/**
* Detail site users and their association with Facebook
*
* @since 1.1.6
*/
public static function users_section() {
global $wpdb;
$users = self::get_all_wordpress_facebook_users();
// should only happen if errors
if ( empty( $users['fb'] ) && empty( $users['wp'] ) )
return;
echo '<section id="debug-users"><header><h3>' . esc_html( __( 'Authors' ) ) . '</h3></header>';
if ( ! empty( $users['fb'] ) ) {
echo '<table><caption>' . esc_html( __( 'Connected to Facebook', 'facebook' ) ) . '</caption><colgroup><col><col span="2" class="permissions"></colgroup><thead><tr><th>' . esc_html( __( 'Name' ) ) . '</th><th title="' . esc_attr( __( 'Facebook account', 'facebook' ) ) . '"></th><th>' . esc_html( __( 'Post to timeline', 'facebook' ) ) . '</th><th>' . esc_html( __( 'Manage pages', 'facebook' ) ) . '</th></tr></thead><tbody>';
foreach( $users['fb'] as $user ) {
echo '<tr><th><a href="' . esc_url( get_author_posts_url( $user->id ) ) . '">' . esc_html( $user->display_name ) . '</a></th>';
echo '<td><a class="facebook-icon" href="' . esc_url( 'https://www.facebook.com/' . ( isset( $user->fb_data['username'] ) ? $user->fb_data['username'] : 'profile.php?' . http_build_query( array( 'id' => $user->fb_data['fb_uid'] ) ) ), array( 'http', 'https' ) ) . '"></a></td>';
echo '<td>';
if ( isset( $user->fb_data['permissions']['publish_stream'] ) && $user->fb_data['permissions']['publish_stream'] )
echo self::EXISTS;
else
echo self::DOES_NOT_EXIST;
echo '</td>';
echo '<td>';
if ( isset( $user->fb_data['permissions']['manage_pages'] ) && $user->fb_data['permissions']['manage_pages'] )
echo self::EXISTS;
else
echo self::DOES_NOT_EXIST;
echo '</td></tr>';
}
echo '</tbody></table>';
}
if ( ! empty( $users['wp'] ) ) {
// last 90 days
$where = ' AND ' . $wpdb->prepare( 'post_date > %s', date( 'Y-m-d H:i:s', time() - 90*24*60*60 ) );
$public_post_types = get_post_types( array( 'public' => true ) );
if ( is_array( $public_post_types ) && ! empty( $public_post_types ) ) {
$public_post_types = array_values( $public_post_types );
$where .= ' AND post_type';
if ( count( $public_post_types ) === 1 ) {
$where .= $wpdb->prepare( ' = %s', $public_post_types[0] );
} else {
$s = '';
foreach( $public_post_types as $post_type ) {
$s .= "'" . $wpdb->escape( $post_type ) . "',";
}
$where .= ' IN (' . rtrim( $s, ',' ) . ')';
unset( $s );
}
}
$public_states = get_post_stati( array( 'public' => true ) );
if ( is_array( $public_states ) && ! empty( $public_states ) ) {
$public_states = array_values( $public_states );
$where .= ' AND post_status';
if ( count( $public_states ) === 1 ) {
$where .= $wpdb->prepare( ' = %s', $public_states[0] );
} else {
$s = '';
foreach( $public_states as $state ) {
$s .= "'" . $wpdb->escape( $state ) . "',";
}
$where .= ' IN (' . rtrim( $s, ',' ) . ')';
unset( $s );
}
}
unset( $public_states );
echo '<table><caption>' . esc_html( __( 'Not connected to Facebook', 'facebook' ) ) . '</caption><thead><th>' . esc_html( __( 'Name' ) ) . '</th><th><abbr title="' . esc_attr( sprintf( __( 'Number of published posts in the last %u days', 'facebook' ), 90 ) ) . '">' . esc_html( _x( '# of recent posts', 'recent articles. used as a table column header', 'facebook' ) ) . '</abbr></th></thead><tbody>';
foreach( $users['wp'] as $user ) {
echo '<tr><th><a href="' . esc_url( get_author_posts_url( $user->id ) ) . '">' . esc_html( $user->display_name ) . '</a></th>';
echo '<td>' . $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = %d $where", $user->id ) ) . '</td>';
echo '</tr>';
}
echo '</tbody></table>';
}
echo '</section>';
}
/**
* Display the currently associated Facebook page, if one exists.
*
* @since 1.1.6
*/
public static function post_to_page_section() {
if ( ! class_exists( 'Facebook_Social_Publisher_Settings' ) )
require_once( dirname( __FILE__ ) . '/settings-social-publisher.php' );
$post_to_page = get_option( Facebook_Social_Publisher_Settings::OPTION_PUBLISH_TO_PAGE );
if ( ! ( is_array( $post_to_page ) && isset( $post_to_page['id'] ) && isset( $post_to_page['name'] ) && isset( $post_to_page['access_token'] ) ) )
return;
echo '<section id="debug-page"><header><h3>' . esc_html( __( 'Facebook Page', 'facebook' ) ) . '</h3></header>';
echo '<p>' . sprintf( esc_html( _x( 'Publishing to %s.', 'publishing to a page name on Facebook.com', 'facebook' ) ), '<a href="' . esc_url( 'https://www.facebook.com/' . $post_to_page['id'], array( 'http', 'https' ) ) . '">' . esc_html( $post_to_page['name'] ) . '</a>' );
if ( isset( $post_to_page['set_by_user'] ) ) {
$current_user = wp_get_current_user();
if ( $current_user->ID == $post_to_page['set_by_user'] ) {
echo ' ' . esc_html( __( 'Saved by you.', 'facebook' ) );
} else {
$setter = get_userdata( $post_to_page['set_by_user'] );
if ( $setter ) {
echo ' ' . esc_html( sprintf( _x( 'Saved by %s.', 'saved by person name', 'facebook' ), $setter->display_name ) );
}
unset( $setter );
}
unset( $current_user );
}
echo '</p>';
echo '</section>';
}
/**
* Which features are enabled for the site on each major view type?
*
* @since 1.1.6
*/
public static function enabled_features_by_view_type() {
if ( ! class_exists( 'Facebook_Social_Plugin_Settings' ) )
require_once( dirname( __FILE__ ) . '/settings-social-plugin.php' );
$views = Facebook_Social_Plugin_Settings::get_show_on_choices( 'all' );
if ( ! is_array( $views ) || empty( $views ) )
return;
echo '<section id="debug-social-plugins"><header><h3>' . esc_html( __( 'Social Plugins', 'facebook' ) ) . '</h3></header>';
echo '<table><caption>' . esc_html( _x( 'Features enabled by view type', 'software features available based on different classifications website view', 'facebook' ) ) . '</caption>';
$features = array(
'like' => array(
'name' => __( 'Like Button', 'facebook' ),
'url' => 'https://developers.facebook.com/docs/reference/plugins/like/'
),
'send' => array(
'name' => __( 'Send Button', 'facebook' ),
'url' => 'https://developers.facebook.com/docs/reference/plugins/send/'
),
'follow' => array(
'name' => __( 'Follow Button', 'facebook' ),
'url' => 'https://developers.facebook.com/docs/reference/plugins/follow/'
),
'recommendations_bar' => array(
'name' => __( 'Recommendations Bar', 'facebook' ),
'url' => 'https://developers.facebook.com/docs/reference/plugins/recommendationsbar/'
),
'comments' => array(
'name' => __( 'Comments Box', 'facebook' ),
'url' => 'https://developers.facebook.com/docs/reference/plugins/comments/'
)
);
echo '<thead><tr><th>' . esc_html( __( 'View', 'facebook' ) ) . '</th>';
foreach ( $features as $slug => $properties ) {
echo '<th>';
if ( isset( $properties['url'] ) )
echo '<a href="' . esc_url( $properties['url'], array( 'http', 'https' ) ) . '">' . esc_html( $properties['name'] ) . '</a>';
else
echo esc_html( $properties['name'] );
echo '</th>';
}
echo '</tr></thead><tbody>';
foreach( $views as $view ) {
echo '<tr><th>' . $view . '</th>';
$view_features = get_option( 'facebook_' . $view . '_features' );
if ( ! is_array( $view_features ) )
$view_features = array();
foreach( $features as $feature => $properties ) {
echo '<td>';
if ( isset( $view_features[$feature] ) )
echo self::EXISTS;
else
echo ' ';
echo '</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
echo '</section>';
}
/**
* Widgets enabled for the site
*
* @since 1.1.6
*/
public static function widgets_section() {
if ( ! class_exists( 'Facebook_Settings' ) )
require_once( dirname(__FILE__) . '/settings.php' );
$active_widgets = Facebook_Settings::get_active_widgets();
if ( ! is_array( $active_widgets ) || empty( $active_widgets ) )
return;
$all_widgets = array(
'activity-feed' => array(
'name' => __( 'Activity Feed', 'facebook' ),
'url' => 'https://developers.facebook.com/docs/reference/plugins/activity/'
),
'like' => array(
'name' => __( 'Like Button', 'facebook' ),
'url' => 'https://developers.facebook.com/docs/reference/plugins/like/'
),
'recommendations' => array(
'name' => __( 'Recommendations Box', 'facebook' ),
'url' => 'https://developers.facebook.com/docs/reference/plugins/recommendations/'
),
'send' => array(
'name' => __( 'Send Button', 'facebook' ),
'url' => 'https://developers.facebook.com/docs/reference/plugins/send/'
),
'follow' => array(
'name' => __( 'Follow Button', 'facebook' ),
'url' => 'https://developers.facebook.com/docs/reference/plugins/follow/'
)
);
echo '<section id="debug-widgets"><header><h3>' . esc_html( __( 'Widgets' ) ) . '</h3></header>';
echo '<table><thead><tr><th>' . esc_html( _x( 'Widget name', 'name of a page component', 'facebook' ) ) . '</th><th>' . esc_html( __( 'Active', 'facebook' ) ) . '</th></tr></thead><tbody>';
foreach( $all_widgets as $slug => $widget ) {
echo '<tr><th><a href="' . esc_url( $widget['url'], array( 'http', 'https' ) ) . '">' . esc_html( $widget['name'] ) . '</a></th><td>';
if ( in_array( $slug , $active_widgets ) )
echo self::EXISTS;
else
echo ' ';
echo '</td></tr>';
}
echo '</tbody></table></section>';
}
/**
* How does the site communicate with Facebook?
*
* @since 1.1.6
*/
public static function server_info() {
echo '<section id="debug-server"><header><h3>' . esc_html( __( 'Server configuration', 'facebook' ) ) . '</h3></header><table><thead><th>' . esc_html( __( 'Feature', 'facebook' ) ) . '</th><th>' . esc_html( _x( 'Info', 'Information', 'facebook' ) ) . '</th></thead><tbody>';
// PHP version
echo '<tr><th>' . esc_html( sprintf( _x( '%s version', 'software version', 'facebook' ), 'PHP' ) ) . '</th><td>';
// PHP > 5.2.7
if ( defined( 'PHP_MAJOR_VERSION' ) && defined( 'PHP_MINOR_VERSION' ) && defined( 'PHP_RELEASE_VERSION' ) )
echo esc_html( PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION );
else
esc_html( phpversion() );
echo '</td></tr>';
// WordPress version
echo '<tr><th>' . esc_html( sprintf( _x( '%s version', 'software version', 'facebook' ), 'WordPress' ) ) . '</th><td>' . esc_html( get_bloginfo( 'version' ) ) . '</td></tr>';
if ( isset( $_SERVER['SERVER_SOFTWARE'] ) )
echo '<tr><th>' . esc_html( __( 'Server software', 'facebook' ) ) . '</th><td>' . esc_html( $_SERVER['SERVER_SOFTWARE'] ) . '</td></tr>';
// WP_HTTP connection for SSL
echo '<tr id="debug-server-http">';
echo '<th>' . sprintf( esc_html( _x( '%s connection method', 'server-to-server connection', 'facebook' ) ), '<a href="http://codex.wordpress.org/HTTP_API">WP_HTTP</a>' ) . '</th><td>';
$http_obj = _wp_http_get_object();
$http_transport = $http_obj->_get_first_available_transport( array( 'ssl' => true ) );
if ( is_string( $http_transport ) && strlen( $http_transport ) > 8 ) {
$http_transport = strtolower( substr( $http_transport, 8 ) );
if ( $http_transport === 'curl' ) {
echo '<a href="http://php.net/manual/book.curl.php">cURL</a>';
$curl_version = curl_version();
if ( isset( $curl_version['version'] ) )
echo ' ' . esc_html( $curl_version['version'] );
if ( isset( $curl_version['ssl_version'] ) ) {
echo '; ';
$ssl_version = $curl_version['ssl_version'];
if ( strlen( $curl_version['ssl_version'] ) > 8 && substr_compare( $ssl_version, 'OpenSSL/', 0, 8 ) === 0 )
echo '<a href="http://openssl.org/">OpenSSL</a>/' . esc_html( substr( $ssl_version, 8 ) );
else
echo esc_html( $ssl_version );
unset( $ssl_version );
}
unset( $curl_version );
} else if ( $http_transport === 'streams' ) {
echo '<a href="http://www.php.net/manual/book.stream.php">Stream</a>';
} else if ( $http_transport === 'fsockopen' ) {
echo '<a href="http://php.net/manual/function.fsockopen.php">fsockopen</a>';
} else {
echo $http_transport;
}
} else {
echo __( 'none available', 'facebook' );
}
echo '</td></tr>';
unset( $http_transport );
unset( $http_obj );
echo '</table></section>';
}
}
?> | gpl-2.0 |
weibocom/opendcp | jupiter/vendor/github.com/rackspace/gophercloud/rackspace/autoscale/v1/webhooks/results.go | 2627 | package webhooks
import (
"github.com/mitchellh/mapstructure"
"github.com/rackspace/gophercloud"
"github.com/rackspace/gophercloud/pagination"
)
type webhookResult struct {
gophercloud.Result
}
// Extract interprets any webhookResult as a Webhook, if possible.
func (r webhookResult) Extract() (*Webhook, error) {
if r.Err != nil {
return nil, r.Err
}
var response struct {
Webhook Webhook `mapstructure:"webhook"`
}
err := mapstructure.Decode(r.Body, &response)
return &response.Webhook, err
}
// CreateResult represents the result of a create operation.
type CreateResult struct {
webhookResult
}
// Extract extracts a slice of Webhooks from a CreateResult. Multiple webhooks
// can be created in a single operation, so the result of a create is always a
// list of webhooks.
func (res CreateResult) Extract() ([]Webhook, error) {
if res.Err != nil {
return nil, res.Err
}
return commonExtractWebhooks(res.Body)
}
// GetResult temporarily contains the response from a Get call.
type GetResult struct {
webhookResult
}
// UpdateResult represents the result of an update operation.
type UpdateResult struct {
gophercloud.ErrResult
}
// DeleteResult represents the result of a delete operation.
type DeleteResult struct {
gophercloud.ErrResult
}
// Webhook represents a webhook associted with a scaling policy.
type Webhook struct {
// UUID for the webhook.
ID string `mapstructure:"id" json:"id"`
// Name of the webhook.
Name string `mapstructure:"name" json:"name"`
// Links associated with the webhook, including the capability URL.
Links []gophercloud.Link `mapstructure:"links" json:"links"`
// Metadata associated with the webhook.
Metadata map[string]string `mapstructure:"metadata" json:"metadata"`
}
// WebhookPage is the page returned by a pager when traversing over a collection
// of webhooks.
type WebhookPage struct {
pagination.SinglePageBase
}
// IsEmpty returns true if a page contains no Webhook results.
func (page WebhookPage) IsEmpty() (bool, error) {
hooks, err := ExtractWebhooks(page)
if err != nil {
return true, err
}
return len(hooks) == 0, nil
}
// ExtractWebhooks interprets the results of a single page from a List() call,
// producing a slice of Webhooks.
func ExtractWebhooks(page pagination.Page) ([]Webhook, error) {
return commonExtractWebhooks(page.(WebhookPage).Body)
}
func commonExtractWebhooks(body interface{}) ([]Webhook, error) {
var response struct {
Webhooks []Webhook `mapstructure:"webhooks"`
}
err := mapstructure.Decode(body, &response)
if err != nil {
return nil, err
}
return response.Webhooks, err
}
| gpl-2.0 |
jcrosales/lemerywebsite | wp-content/plugins/the-events-calendar/views/modules/meta/map.php | 507 | <?php
/**
* Single Event Meta (Map) Template
*
* Override this template in your own theme by creating a file at:
* [your-theme]/tribe-events/modules/meta/details.php
*
* @package TribeEventsCalendar
*/
$map = apply_filters( 'tribe_event_meta_venue_map', tribe_get_embedded_map() );
if ( empty( $map ) ) return;
?>
<div class="tribe-events-venue-map">
<?php
do_action( 'tribe_events_single_meta_map_section_start' );
echo $map;
do_action( 'tribe_events_single_meta_map_section_end' );
?>
</div> | gpl-2.0 |
diegoacuna/wiki-parques-nacionales | includes/MimeMagic.php | 34503 | <?php
/**
* Module defining helper functions for detecting and dealing with mime types.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
*/
/**
* Defines a set of well known mime types
* This is used as a fallback to mime.types files.
* An extensive list of well known mime types is provided by
* the file mime.types in the includes directory.
*
* This list concatenated with mime.types is used to create a mime <-> ext
* map. Each line contains a mime type followed by a space separated list of
* extensions. If multiple extensions for a single mime type exist or if
* multiple mime types exist for a single extension then in most cases
* MediaWiki assumes that the first extension following the mime type is the
* canonical extension, and the first time a mime type appears for a certain
* extension is considered the canonical mime type.
*
* (Note that appending $wgMimeTypeFile to the end of MM_WELL_KNOWN_MIME_TYPES
* sucks because you can't redefine canonical types. This could be fixed by
* appending MM_WELL_KNOWN_MIME_TYPES behind $wgMimeTypeFile, but who knows
* what will break? In practice this probably isn't a problem anyway -- Bryan)
*/
define('MM_WELL_KNOWN_MIME_TYPES', <<<END_STRING
application/ogg ogx ogg ogm ogv oga spx
application/pdf pdf
application/vnd.oasis.opendocument.chart odc
application/vnd.oasis.opendocument.chart-template otc
application/vnd.oasis.opendocument.database odb
application/vnd.oasis.opendocument.formula odf
application/vnd.oasis.opendocument.formula-template otf
application/vnd.oasis.opendocument.graphics odg
application/vnd.oasis.opendocument.graphics-template otg
application/vnd.oasis.opendocument.image odi
application/vnd.oasis.opendocument.image-template oti
application/vnd.oasis.opendocument.presentation odp
application/vnd.oasis.opendocument.presentation-template otp
application/vnd.oasis.opendocument.spreadsheet ods
application/vnd.oasis.opendocument.spreadsheet-template ots
application/vnd.oasis.opendocument.text odt
application/vnd.oasis.opendocument.text-master otm
application/vnd.oasis.opendocument.text-template ott
application/vnd.oasis.opendocument.text-web oth
application/x-javascript js
application/x-shockwave-flash swf
audio/midi mid midi kar
audio/mpeg mpga mpa mp2 mp3
audio/x-aiff aif aiff aifc
audio/x-wav wav
audio/ogg oga spx ogg
image/x-bmp bmp
image/gif gif
image/jpeg jpeg jpg jpe
image/png png
image/svg+xml svg
image/svg svg
image/tiff tiff tif
image/vnd.djvu djvu
image/x.djvu djvu
image/x-djvu djvu
image/x-portable-pixmap ppm
image/x-xcf xcf
text/plain txt
text/html html htm
video/ogg ogv ogm ogg
video/mpeg mpg mpeg
END_STRING
);
/**
* Defines a set of well known mime info entries
* This is used as a fallback to mime.info files.
* An extensive list of well known mime types is provided by
* the file mime.info in the includes directory.
*/
define('MM_WELL_KNOWN_MIME_INFO', <<<END_STRING
application/pdf [OFFICE]
application/vnd.oasis.opendocument.chart [OFFICE]
application/vnd.oasis.opendocument.chart-template [OFFICE]
application/vnd.oasis.opendocument.database [OFFICE]
application/vnd.oasis.opendocument.formula [OFFICE]
application/vnd.oasis.opendocument.formula-template [OFFICE]
application/vnd.oasis.opendocument.graphics [OFFICE]
application/vnd.oasis.opendocument.graphics-template [OFFICE]
application/vnd.oasis.opendocument.image [OFFICE]
application/vnd.oasis.opendocument.image-template [OFFICE]
application/vnd.oasis.opendocument.presentation [OFFICE]
application/vnd.oasis.opendocument.presentation-template [OFFICE]
application/vnd.oasis.opendocument.spreadsheet [OFFICE]
application/vnd.oasis.opendocument.spreadsheet-template [OFFICE]
application/vnd.oasis.opendocument.text [OFFICE]
application/vnd.oasis.opendocument.text-template [OFFICE]
application/vnd.oasis.opendocument.text-master [OFFICE]
application/vnd.oasis.opendocument.text-web [OFFICE]
text/javascript application/x-javascript [EXECUTABLE]
application/x-shockwave-flash [MULTIMEDIA]
audio/midi [AUDIO]
audio/x-aiff [AUDIO]
audio/x-wav [AUDIO]
audio/mp3 audio/mpeg [AUDIO]
application/ogg audio/ogg video/ogg [MULTIMEDIA]
image/x-bmp image/x-ms-bmp image/bmp [BITMAP]
image/gif [BITMAP]
image/jpeg [BITMAP]
image/png [BITMAP]
image/svg+xml [DRAWING]
image/tiff [BITMAP]
image/vnd.djvu [BITMAP]
image/x-xcf [BITMAP]
image/x-portable-pixmap [BITMAP]
text/plain [TEXT]
text/html [TEXT]
video/ogg [VIDEO]
video/mpeg [VIDEO]
unknown/unknown application/octet-stream application/x-empty [UNKNOWN]
END_STRING
);
/**
* Implements functions related to mime types such as detection and mapping to
* file extension.
*
* Instances of this class are stateless, there only needs to be one global instance
* of MimeMagic. Please use MimeMagic::singleton() to get that instance.
*/
class MimeMagic {
/**
* Mapping of media types to arrays of mime types.
* This is used by findMediaType and getMediaType, respectively
*/
var $mMediaTypes = null;
/** Map of mime type aliases
*/
var $mMimeTypeAliases = null;
/** map of mime types to file extensions (as a space separated list)
*/
var $mMimeToExt = null;
/** map of file extensions types to mime types (as a space separated list)
*/
var $mExtToMime = null;
/** IEContentAnalyzer instance
*/
var $mIEAnalyzer;
/** The singleton instance
*/
private static $instance;
/** True if the fileinfo extension has been loaded
*/
private static $extensionLoaded = false;
/** Initializes the MimeMagic object. This is called by MimeMagic::singleton().
*
* This constructor parses the mime.types and mime.info files and build internal mappings.
*/
function __construct() {
/**
* --- load mime.types ---
*/
global $wgMimeTypeFile, $IP, $wgLoadFileinfoExtension;
$types = MM_WELL_KNOWN_MIME_TYPES;
if ( $wgMimeTypeFile == 'includes/mime.types' ) {
$wgMimeTypeFile = "$IP/$wgMimeTypeFile";
}
if ( $wgLoadFileinfoExtension && !self::$extensionLoaded ) {
self::$extensionLoaded = true;
wfDl( 'fileinfo' );
}
if ( $wgMimeTypeFile ) {
if ( is_file( $wgMimeTypeFile ) and is_readable( $wgMimeTypeFile ) ) {
wfDebug( __METHOD__ . ": loading mime types from $wgMimeTypeFile\n" );
$types .= "\n";
$types .= file_get_contents( $wgMimeTypeFile );
} else {
wfDebug( __METHOD__ . ": can't load mime types from $wgMimeTypeFile\n" );
}
} else {
wfDebug( __METHOD__ . ": no mime types file defined, using build-ins only.\n" );
}
$types = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $types );
$types = str_replace( "\t", " ", $types );
$this->mMimeToExt = array();
$this->mToMime = array();
$lines = explode( "\n", $types );
foreach ( $lines as $s ) {
$s = trim( $s );
if ( empty( $s ) ) {
continue;
}
if ( strpos( $s, '#' ) === 0 ) {
continue;
}
$s = strtolower( $s );
$i = strpos( $s, ' ' );
if ( $i === false ) {
continue;
}
$mime = substr( $s, 0, $i );
$ext = trim( substr( $s, $i+1 ) );
if ( empty( $ext ) ) {
continue;
}
if ( !empty( $this->mMimeToExt[$mime] ) ) {
$this->mMimeToExt[$mime] .= ' ' . $ext;
} else {
$this->mMimeToExt[$mime] = $ext;
}
$extensions = explode( ' ', $ext );
foreach ( $extensions as $e ) {
$e = trim( $e );
if ( empty( $e ) ) {
continue;
}
if ( !empty( $this->mExtToMime[$e] ) ) {
$this->mExtToMime[$e] .= ' ' . $mime;
} else {
$this->mExtToMime[$e] = $mime;
}
}
}
/**
* --- load mime.info ---
*/
global $wgMimeInfoFile;
if ( $wgMimeInfoFile == 'includes/mime.info' ) {
$wgMimeInfoFile = "$IP/$wgMimeInfoFile";
}
$info = MM_WELL_KNOWN_MIME_INFO;
if ( $wgMimeInfoFile ) {
if ( is_file( $wgMimeInfoFile ) and is_readable( $wgMimeInfoFile ) ) {
wfDebug( __METHOD__ . ": loading mime info from $wgMimeInfoFile\n" );
$info .= "\n";
$info .= file_get_contents( $wgMimeInfoFile );
} else {
wfDebug( __METHOD__ . ": can't load mime info from $wgMimeInfoFile\n" );
}
} else {
wfDebug( __METHOD__ . ": no mime info file defined, using build-ins only.\n" );
}
$info = str_replace( array( "\r\n", "\n\r", "\n\n", "\r\r", "\r" ), "\n", $info );
$info = str_replace( "\t", " ", $info );
$this->mMimeTypeAliases = array();
$this->mMediaTypes = array();
$lines = explode( "\n", $info );
foreach ( $lines as $s ) {
$s = trim( $s );
if ( empty( $s ) ) {
continue;
}
if ( strpos( $s, '#' ) === 0 ) {
continue;
}
$s = strtolower( $s );
$i = strpos( $s, ' ' );
if ( $i === false ) {
continue;
}
#print "processing MIME INFO line $s<br>";
$match = array();
if ( preg_match( '!\[\s*(\w+)\s*\]!', $s, $match ) ) {
$s = preg_replace( '!\[\s*(\w+)\s*\]!', '', $s );
$mtype = trim( strtoupper( $match[1] ) );
} else {
$mtype = MEDIATYPE_UNKNOWN;
}
$m = explode( ' ', $s );
if ( !isset( $this->mMediaTypes[$mtype] ) ) {
$this->mMediaTypes[$mtype] = array();
}
foreach ( $m as $mime ) {
$mime = trim( $mime );
if ( empty( $mime ) ) {
continue;
}
$this->mMediaTypes[$mtype][] = $mime;
}
if ( count( $m ) > 1 ) {
$main = $m[0];
for ( $i = 1; $i < count( $m ); $i += 1 ) {
$mime = $m[$i];
$this->mMimeTypeAliases[$mime] = $main;
}
}
}
}
/**
* Get an instance of this class
* @return MimeMagic
*/
public static function &singleton() {
if ( self::$instance === null ) {
self::$instance = new MimeMagic;
}
return self::$instance;
}
/**
* Returns a list of file extensions for a given mime type as a space
* separated string or null if the mime type was unrecognized. Resolves
* mime type aliases.
*
* @param $mime string
* @return string|null
*/
public function getExtensionsForType( $mime ) {
$mime = strtolower( $mime );
// Check the mime-to-ext map
if ( isset( $this->mMimeToExt[$mime] ) ) {
return $this->mMimeToExt[$mime];
}
// Resolve the mime type to the canonical type
if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
$mime = $this->mMimeTypeAliases[$mime];
if ( isset( $this->mMimeToExt[$mime] ) ) {
return $this->mMimeToExt[$mime];
}
}
return null;
}
/**
* Returns a list of mime types for a given file extension as a space
* separated string or null if the extension was unrecognized.
*
* @param $ext string
* @return string|null
*/
public function getTypesForExtension( $ext ) {
$ext = strtolower( $ext );
$r = isset( $this->mExtToMime[$ext] ) ? $this->mExtToMime[$ext] : null;
return $r;
}
/**
* Returns a single mime type for a given file extension or null if unknown.
* This is always the first type from the list returned by getTypesForExtension($ext).
*
* @param $ext string
* @return string|null
*/
public function guessTypesForExtension( $ext ) {
$m = $this->getTypesForExtension( $ext );
if ( is_null( $m ) ) {
return null;
}
// TODO: Check if this is needed; strtok( $m, ' ' ) should be sufficient
$m = trim( $m );
$m = preg_replace( '/\s.*$/', '', $m );
return $m;
}
/**
* Tests if the extension matches the given mime type. Returns true if a
* match was found, null if the mime type is unknown, and false if the
* mime type is known but no matches where found.
*
* @param $extension string
* @param $mime string
* @return bool|null
*/
public function isMatchingExtension( $extension, $mime ) {
$ext = $this->getExtensionsForType( $mime );
if ( !$ext ) {
return null; // Unknown mime type
}
$ext = explode( ' ', $ext );
$extension = strtolower( $extension );
return in_array( $extension, $ext );
}
/**
* Returns true if the mime type is known to represent an image format
* supported by the PHP GD library.
*
* @param $mime string
*
* @return bool
*/
public function isPHPImageType( $mime ) {
// As defined by imagegetsize and image_type_to_mime
static $types = array(
'image/gif', 'image/jpeg', 'image/png',
'image/x-bmp', 'image/xbm', 'image/tiff',
'image/jp2', 'image/jpeg2000', 'image/iff',
'image/xbm', 'image/x-xbitmap',
'image/vnd.wap.wbmp', 'image/vnd.xiff',
'image/x-photoshop',
'application/x-shockwave-flash',
);
return in_array( $mime, $types );
}
/**
* Returns true if the extension represents a type which can
* be reliably detected from its content. Use this to determine
* whether strict content checks should be applied to reject
* invalid uploads; if we can't identify the type we won't
* be able to say if it's invalid.
*
* @todo Be more accurate when using fancy mime detector plugins;
* right now this is the bare minimum getimagesize() list.
* @return bool
*/
function isRecognizableExtension( $extension ) {
static $types = array(
// Types recognized by getimagesize()
'gif', 'jpeg', 'jpg', 'png', 'swf', 'psd',
'bmp', 'tiff', 'tif', 'jpc', 'jp2',
'jpx', 'jb2', 'swc', 'iff', 'wbmp',
'xbm',
// Formats we recognize magic numbers for
'djvu', 'ogx', 'ogg', 'ogv', 'oga', 'spx',
'mid', 'pdf', 'wmf', 'xcf', 'webm', 'mkv', 'mka',
'webp',
// XML formats we sure hope we recognize reliably
'svg',
);
return in_array( strtolower( $extension ), $types );
}
/**
* Improves a mime type using the file extension. Some file formats are very generic,
* so their mime type is not very meaningful. A more useful mime type can be derived
* by looking at the file extension. Typically, this method would be called on the
* result of guessMimeType().
*
* Currently, this method does the following:
*
* If $mime is "unknown/unknown" and isRecognizableExtension( $ext ) returns false,
* return the result of guessTypesForExtension($ext).
*
* If $mime is "application/x-opc+zip" and isMatchingExtension( $ext, $mime )
* gives true, return the result of guessTypesForExtension($ext).
*
* @param string $mime the mime type, typically guessed from a file's content.
* @param string $ext the file extension, as taken from the file name
*
* @return string the mime type
*/
public function improveTypeFromExtension( $mime, $ext ) {
if ( $mime === 'unknown/unknown' ) {
if ( $this->isRecognizableExtension( $ext ) ) {
wfDebug( __METHOD__ . ': refusing to guess mime type for .' .
"$ext file, we should have recognized it\n" );
} else {
// Not something we can detect, so simply
// trust the file extension
$mime = $this->guessTypesForExtension( $ext );
}
}
elseif ( $mime === 'application/x-opc+zip' ) {
if ( $this->isMatchingExtension( $ext, $mime ) ) {
// A known file extension for an OPC file,
// find the proper mime type for that file extension
$mime = $this->guessTypesForExtension( $ext );
} else {
wfDebug( __METHOD__ . ": refusing to guess better type for $mime file, " .
".$ext is not a known OPC extension.\n" );
$mime = 'application/zip';
}
}
if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
$mime = $this->mMimeTypeAliases[$mime];
}
wfDebug( __METHOD__ . ": improved mime type for .$ext: $mime\n" );
return $mime;
}
/**
* Mime type detection. This uses detectMimeType to detect the mime type
* of the file, but applies additional checks to determine some well known
* file formats that may be missed or misinterpreted by the default mime
* detection (namely XML based formats like XHTML or SVG, as well as ZIP
* based formats like OPC/ODF files).
*
* @param string $file the file to check
* @param $ext Mixed: the file extension, or true (default) to extract it from the filename.
* Set it to false to ignore the extension. DEPRECATED! Set to false, use
* improveTypeFromExtension($mime, $ext) later to improve mime type.
*
* @return string the mime type of $file
*/
public function guessMimeType( $file, $ext = true ) {
if ( $ext ) { // TODO: make $ext default to false. Or better, remove it.
wfDebug( __METHOD__ . ": WARNING: use of the \$ext parameter is deprecated. " .
"Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
}
$mime = $this->doGuessMimeType( $file, $ext );
if( !$mime ) {
wfDebug( __METHOD__ . ": internal type detection failed for $file (.$ext)...\n" );
$mime = $this->detectMimeType( $file, $ext );
}
if ( isset( $this->mMimeTypeAliases[$mime] ) ) {
$mime = $this->mMimeTypeAliases[$mime];
}
wfDebug( __METHOD__ . ": guessed mime type of $file: $mime\n" );
return $mime;
}
/**
* Guess the mime type from the file contents.
*
* @param string $file
* @param mixed $ext
* @return bool|string
*/
private function doGuessMimeType( $file, $ext ) { // TODO: remove $ext param
// Read a chunk of the file
wfSuppressWarnings();
// @todo FIXME: Shouldn't this be rb?
$f = fopen( $file, 'rt' );
wfRestoreWarnings();
if( !$f ) {
return 'unknown/unknown';
}
$head = fread( $f, 1024 );
fseek( $f, -65558, SEEK_END );
$tail = fread( $f, 65558 ); // 65558 = maximum size of a zip EOCDR
fclose( $f );
wfDebug( __METHOD__ . ": analyzing head and tail of $file for magic numbers.\n" );
// Hardcode a few magic number checks...
$headers = array(
// Multimedia...
'MThd' => 'audio/midi',
'OggS' => 'application/ogg',
// Image formats...
// Note that WMF may have a bare header, no magic number.
"\x01\x00\x09\x00" => 'application/x-msmetafile', // Possibly prone to false positives?
"\xd7\xcd\xc6\x9a" => 'application/x-msmetafile',
'%PDF' => 'application/pdf',
'gimp xcf' => 'image/x-xcf',
// Some forbidden fruit...
'MZ' => 'application/octet-stream', // DOS/Windows executable
"\xca\xfe\xba\xbe" => 'application/octet-stream', // Mach-O binary
"\x7fELF" => 'application/octet-stream', // ELF binary
);
foreach ( $headers as $magic => $candidate ) {
if ( strncmp( $head, $magic, strlen( $magic ) ) == 0 ) {
wfDebug( __METHOD__ . ": magic header in $file recognized as $candidate\n" );
return $candidate;
}
}
/* Look for WebM and Matroska files */
if ( strncmp( $head, pack( "C4", 0x1a, 0x45, 0xdf, 0xa3 ), 4 ) == 0 ) {
$doctype = strpos( $head, "\x42\x82" );
if ( $doctype ) {
// Next byte is datasize, then data (sizes larger than 1 byte are very stupid muxers)
$data = substr( $head, $doctype+3, 8 );
if ( strncmp( $data, "matroska", 8 ) == 0 ) {
wfDebug( __METHOD__ . ": recognized file as video/x-matroska\n" );
return "video/x-matroska";
} elseif ( strncmp( $data, "webm", 4 ) == 0 ) {
wfDebug( __METHOD__ . ": recognized file as video/webm\n" );
return "video/webm";
}
}
wfDebug( __METHOD__ . ": unknown EBML file\n" );
return "unknown/unknown";
}
/* Look for WebP */
if ( strncmp( $head, "RIFF", 4 ) == 0 && strncmp( substr( $head, 8, 8), "WEBPVP8 ", 8 ) == 0 ) {
wfDebug( __METHOD__ . ": recognized file as image/webp\n" );
return "image/webp";
}
/**
* Look for PHP. Check for this before HTML/XML... Warning: this is a
* heuristic, and won't match a file with a lot of non-PHP before. It
* will also match text files which could be PHP. :)
*
* @todo FIXME: For this reason, the check is probably useless -- an attacker
* could almost certainly just pad the file with a lot of nonsense to
* circumvent the check in any case where it would be a security
* problem. On the other hand, it causes harmful false positives (bug
* 16583). The heuristic has been cut down to exclude three-character
* strings like "<? ", but should it be axed completely?
*/
if ( ( strpos( $head, '<?php' ) !== false ) ||
( strpos( $head, "<\x00?\x00p\x00h\x00p" ) !== false ) ||
( strpos( $head, "<\x00?\x00 " ) !== false ) ||
( strpos( $head, "<\x00?\x00\n" ) !== false ) ||
( strpos( $head, "<\x00?\x00\t" ) !== false ) ||
( strpos( $head, "<\x00?\x00=" ) !== false ) ) {
wfDebug( __METHOD__ . ": recognized $file as application/x-php\n" );
return 'application/x-php';
}
/**
* look for XML formats (XHTML and SVG)
*/
$xml = new XmlTypeCheck( $file );
if ( $xml->wellFormed ) {
global $wgXMLMimeTypes;
if ( isset( $wgXMLMimeTypes[$xml->getRootElement()] ) ) {
return $wgXMLMimeTypes[$xml->getRootElement()];
} else {
return 'application/xml';
}
}
/**
* look for shell scripts
*/
$script_type = null;
# detect by shebang
if ( substr( $head, 0, 2) == "#!" ) {
$script_type = "ASCII";
} elseif ( substr( $head, 0, 5) == "\xef\xbb\xbf#!" ) {
$script_type = "UTF-8";
} elseif ( substr( $head, 0, 7) == "\xfe\xff\x00#\x00!" ) {
$script_type = "UTF-16BE";
} elseif ( substr( $head, 0, 7 ) == "\xff\xfe#\x00!" ) {
$script_type = "UTF-16LE";
}
if ( $script_type ) {
if ( $script_type !== "UTF-8" && $script_type !== "ASCII" ) {
// Quick and dirty fold down to ASCII!
$pack = array( 'UTF-16BE' => 'n*', 'UTF-16LE' => 'v*' );
$chars = unpack( $pack[$script_type], substr( $head, 2 ) );
$head = '';
foreach( $chars as $codepoint ) {
if( $codepoint < 128 ) {
$head .= chr( $codepoint );
} else {
$head .= '?';
}
}
}
$match = array();
if ( preg_match( '%/?([^\s]+/)(\w+)%', $head, $match ) ) {
$mime = "application/x-{$match[2]}";
wfDebug( __METHOD__ . ": shell script recognized as $mime\n" );
return $mime;
}
}
// Check for ZIP variants (before getimagesize)
if ( strpos( $tail, "PK\x05\x06" ) !== false ) {
wfDebug( __METHOD__ . ": ZIP header present in $file\n" );
return $this->detectZipType( $head, $tail, $ext );
}
wfSuppressWarnings();
$gis = getimagesize( $file );
wfRestoreWarnings();
if( $gis && isset( $gis['mime'] ) ) {
$mime = $gis['mime'];
wfDebug( __METHOD__ . ": getimagesize detected $file as $mime\n" );
return $mime;
}
// Also test DjVu
$deja = new DjVuImage( $file );
if( $deja->isValid() ) {
wfDebug( __METHOD__ . ": detected $file as image/vnd.djvu\n" );
return 'image/vnd.djvu';
}
return false;
}
/**
* Detect application-specific file type of a given ZIP file from its
* header data. Currently works for OpenDocument and OpenXML types...
* If can't tell, returns 'application/zip'.
*
* @param string $header some reasonably-sized chunk of file header
* @param $tail String: the tail of the file
* @param $ext Mixed: the file extension, or true to extract it from the filename.
* Set it to false (default) to ignore the extension. DEPRECATED! Set to false,
* use improveTypeFromExtension($mime, $ext) later to improve mime type.
*
* @return string
*/
function detectZipType( $header, $tail = null, $ext = false ) {
if( $ext ) { # TODO: remove $ext param
wfDebug( __METHOD__ . ": WARNING: use of the \$ext parameter is deprecated. " .
"Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
}
$mime = 'application/zip';
$opendocTypes = array(
'chart-template',
'chart',
'formula-template',
'formula',
'graphics-template',
'graphics',
'image-template',
'image',
'presentation-template',
'presentation',
'spreadsheet-template',
'spreadsheet',
'text-template',
'text-master',
'text-web',
'text' );
// http://lists.oasis-open.org/archives/office/200505/msg00006.html
$types = '(?:' . implode( '|', $opendocTypes ) . ')';
$opendocRegex = "/^mimetype(application\/vnd\.oasis\.opendocument\.$types)/";
$openxmlRegex = "/^\[Content_Types\].xml/";
if ( preg_match( $opendocRegex, substr( $header, 30 ), $matches ) ) {
$mime = $matches[1];
wfDebug( __METHOD__ . ": detected $mime from ZIP archive\n" );
} elseif ( preg_match( $openxmlRegex, substr( $header, 30 ) ) ) {
$mime = "application/x-opc+zip";
# TODO: remove the block below, as soon as improveTypeFromExtension is used everywhere
if ( $ext !== true && $ext !== false ) {
/** This is the mode used by getPropsFromPath
* These mime's are stored in the database, where we don't really want
* x-opc+zip, because we use it only for internal purposes
*/
if ( $this->isMatchingExtension( $ext, $mime) ) {
/* A known file extension for an OPC file,
* find the proper mime type for that file extension
*/
$mime = $this->guessTypesForExtension( $ext );
} else {
$mime = "application/zip";
}
}
wfDebug( __METHOD__ . ": detected an Open Packaging Conventions archive: $mime\n" );
} elseif ( substr( $header, 0, 8 ) == "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" &&
($headerpos = strpos( $tail, "PK\x03\x04" ) ) !== false &&
preg_match( $openxmlRegex, substr( $tail, $headerpos + 30 ) ) ) {
if ( substr( $header, 512, 4) == "\xEC\xA5\xC1\x00" ) {
$mime = "application/msword";
}
switch( substr( $header, 512, 6) ) {
case "\xEC\xA5\xC1\x00\x0E\x00":
case "\xEC\xA5\xC1\x00\x1C\x00":
case "\xEC\xA5\xC1\x00\x43\x00":
$mime = "application/vnd.ms-powerpoint";
break;
case "\xFD\xFF\xFF\xFF\x10\x00":
case "\xFD\xFF\xFF\xFF\x1F\x00":
case "\xFD\xFF\xFF\xFF\x22\x00":
case "\xFD\xFF\xFF\xFF\x23\x00":
case "\xFD\xFF\xFF\xFF\x28\x00":
case "\xFD\xFF\xFF\xFF\x29\x00":
case "\xFD\xFF\xFF\xFF\x10\x02":
case "\xFD\xFF\xFF\xFF\x1F\x02":
case "\xFD\xFF\xFF\xFF\x22\x02":
case "\xFD\xFF\xFF\xFF\x23\x02":
case "\xFD\xFF\xFF\xFF\x28\x02":
case "\xFD\xFF\xFF\xFF\x29\x02":
$mime = "application/vnd.msexcel";
break;
}
wfDebug( __METHOD__ . ": detected a MS Office document with OPC trailer\n" );
} else {
wfDebug( __METHOD__ . ": unable to identify type of ZIP archive\n" );
}
return $mime;
}
/**
* Internal mime type detection. Detection is done using an external
* program, if $wgMimeDetectorCommand is set. Otherwise, the fileinfo
* extension and mime_content_type are tried (in this order), if they
* are available. If the detections fails and $ext is not false, the mime
* type is guessed from the file extension, using guessTypesForExtension.
*
* If the mime type is still unknown, getimagesize is used to detect the
* mime type if the file is an image. If no mime type can be determined,
* this function returns 'unknown/unknown'.
*
* @param string $file the file to check
* @param $ext Mixed: the file extension, or true (default) to extract it from the filename.
* Set it to false to ignore the extension. DEPRECATED! Set to false, use
* improveTypeFromExtension($mime, $ext) later to improve mime type.
*
* @return string the mime type of $file
*/
private function detectMimeType( $file, $ext = true ) {
global $wgMimeDetectorCommand;
if ( $ext ) { # TODO: make $ext default to false. Or better, remove it.
wfDebug( __METHOD__ . ": WARNING: use of the \$ext parameter is deprecated. Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
}
$m = null;
if ( $wgMimeDetectorCommand ) {
// @todo FIXME: Use wfShellExec
$fn = wfEscapeShellArg( $file );
$m = `$wgMimeDetectorCommand $fn`;
} elseif ( function_exists( "finfo_open" ) && function_exists( "finfo_file" ) ) {
# This required the fileinfo extension by PECL,
# see http://pecl.php.net/package/fileinfo
# This must be compiled into PHP
#
# finfo is the official replacement for the deprecated
# mime_content_type function, see below.
#
# If you may need to load the fileinfo extension at runtime, set
# $wgLoadFileinfoExtension in LocalSettings.php
$mime_magic_resource = finfo_open( FILEINFO_MIME ); /* return mime type ala mimetype extension */
if ( $mime_magic_resource ) {
$m = finfo_file( $mime_magic_resource, $file );
finfo_close( $mime_magic_resource );
} else {
wfDebug( __METHOD__ . ": finfo_open failed on ".FILEINFO_MIME."!\n" );
}
} elseif ( function_exists( "mime_content_type" ) ) {
# NOTE: this function is available since PHP 4.3.0, but only if
# PHP was compiled with --with-mime-magic or, before 4.3.2, with --enable-mime-magic.
#
# On Windows, you must set mime_magic.magicfile in php.ini to point to the mime.magic file bundled with PHP;
# sometimes, this may even be needed under linus/unix.
#
# Also note that this has been DEPRECATED in favor of the fileinfo extension by PECL, see above.
# see http://www.php.net/manual/en/ref.mime-magic.php for details.
$m = mime_content_type( $file );
} else {
wfDebug( __METHOD__ . ": no magic mime detector found!\n" );
}
if ( $m ) {
# normalize
$m = preg_replace( '![;, ].*$!', '', $m ); #strip charset, etc
$m = trim( $m );
$m = strtolower( $m );
if ( strpos( $m, 'unknown' ) !== false ) {
$m = null;
} else {
wfDebug( __METHOD__ . ": magic mime type of $file: $m\n" );
return $m;
}
}
// If desired, look at extension as a fallback.
if ( $ext === true ) {
$i = strrpos( $file, '.' );
$ext = strtolower( $i ? substr( $file, $i + 1 ) : '' );
}
if ( $ext ) {
if( $this->isRecognizableExtension( $ext ) ) {
wfDebug( __METHOD__ . ": refusing to guess mime type for .$ext file, we should have recognized it\n" );
} else {
$m = $this->guessTypesForExtension( $ext );
if ( $m ) {
wfDebug( __METHOD__ . ": extension mime type of $file: $m\n" );
return $m;
}
}
}
// Unknown type
wfDebug( __METHOD__ . ": failed to guess mime type for $file!\n" );
return 'unknown/unknown';
}
/**
* Determine the media type code for a file, using its mime type, name and
* possibly its contents.
*
* This function relies on the findMediaType(), mapping extensions and mime
* types to media types.
*
* @todo analyse file if need be
* @todo look at multiple extension, separately and together.
*
* @param string $path full path to the image file, in case we have to look at the contents
* (if null, only the mime type is used to determine the media type code).
* @param string $mime mime type. If null it will be guessed using guessMimeType.
*
* @return (int?string?) a value to be used with the MEDIATYPE_xxx constants.
*/
function getMediaType( $path = null, $mime = null ) {
if( !$mime && !$path ) {
return MEDIATYPE_UNKNOWN;
}
// If mime type is unknown, guess it
if( !$mime ) {
$mime = $this->guessMimeType( $path, false );
}
// Special code for ogg - detect if it's video (theora),
// else label it as sound.
if ( $mime == 'application/ogg' && file_exists( $path ) ) {
// Read a chunk of the file
$f = fopen( $path, "rt" );
if ( !$f ) return MEDIATYPE_UNKNOWN;
$head = fread( $f, 256 );
fclose( $f );
$head = strtolower( $head );
// This is an UGLY HACK, file should be parsed correctly
if ( strpos( $head, 'theora' ) !== false ) return MEDIATYPE_VIDEO;
elseif ( strpos( $head, 'vorbis' ) !== false ) return MEDIATYPE_AUDIO;
elseif ( strpos( $head, 'flac' ) !== false ) return MEDIATYPE_AUDIO;
elseif ( strpos( $head, 'speex' ) !== false ) return MEDIATYPE_AUDIO;
else return MEDIATYPE_MULTIMEDIA;
}
// Check for entry for full mime type
if( $mime ) {
$type = $this->findMediaType( $mime );
if ( $type !== MEDIATYPE_UNKNOWN ) {
return $type;
}
}
// Check for entry for file extension
if ( $path ) {
$i = strrpos( $path, '.' );
$e = strtolower( $i ? substr( $path, $i + 1 ) : '' );
// TODO: look at multi-extension if this fails, parse from full path
$type = $this->findMediaType( '.' . $e );
if ( $type !== MEDIATYPE_UNKNOWN ) {
return $type;
}
}
// Check major mime type
if ( $mime ) {
$i = strpos( $mime, '/' );
if ( $i !== false ) {
$major = substr( $mime, 0, $i );
$type = $this->findMediaType( $major );
if ( $type !== MEDIATYPE_UNKNOWN ) {
return $type;
}
}
}
if( !$type ) {
$type = MEDIATYPE_UNKNOWN;
}
return $type;
}
/**
* Returns a media code matching the given mime type or file extension.
* File extensions are represented by a string starting with a dot (.) to
* distinguish them from mime types.
*
* This function relies on the mapping defined by $this->mMediaTypes
* @access private
* @return int|string
*/
function findMediaType( $extMime ) {
if ( strpos( $extMime, '.' ) === 0 ) {
// If it's an extension, look up the mime types
$m = $this->getTypesForExtension( substr( $extMime, 1 ) );
if ( !$m ) {
return MEDIATYPE_UNKNOWN;
}
$m = explode( ' ', $m );
} else {
// Normalize mime type
if ( isset( $this->mMimeTypeAliases[$extMime] ) ) {
$extMime = $this->mMimeTypeAliases[$extMime];
}
$m = array( $extMime );
}
foreach ( $m as $mime ) {
foreach ( $this->mMediaTypes as $type => $codes ) {
if ( in_array( $mime, $codes, true ) ) {
return $type;
}
}
}
return MEDIATYPE_UNKNOWN;
}
/**
* Get the MIME types that various versions of Internet Explorer would
* detect from a chunk of the content.
*
* @param string $fileName the file name (unused at present)
* @param string $chunk the first 256 bytes of the file
* @param string $proposed the MIME type proposed by the server
* @return Array
*/
public function getIEMimeTypes( $fileName, $chunk, $proposed ) {
$ca = $this->getIEContentAnalyzer();
return $ca->getRealMimesFromData( $fileName, $chunk, $proposed );
}
/**
* Get a cached instance of IEContentAnalyzer
*
* @return IEContentAnalyzer
*/
protected function getIEContentAnalyzer() {
if ( is_null( $this->mIEAnalyzer ) ) {
$this->mIEAnalyzer = new IEContentAnalyzer;
}
return $this->mIEAnalyzer;
}
}
| gpl-2.0 |
YouDiSN/OpenJDK-Research | jdk9/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/LoaderDelegate.java | 3140 | /*
* Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.jshell.execution;
import jdk.jshell.spi.ExecutionControl.ClassBytecodes;
import jdk.jshell.spi.ExecutionControl.ClassInstallException;
import jdk.jshell.spi.ExecutionControl.EngineTerminationException;
import jdk.jshell.spi.ExecutionControl.InternalException;
import jdk.jshell.spi.ExecutionControl.NotImplementedException;
/**
* This interface specifies the loading specific subset of
* {@link jdk.jshell.spi.ExecutionControl}. For use in encapsulating the
* {@link java.lang.ClassLoader} implementation.
*
* @since 9
*/
public interface LoaderDelegate {
/**
* Attempts to load new classes.
*
* @param cbcs the class name and bytecodes to load
* @throws ClassInstallException exception occurred loading the classes,
* some or all were not loaded
* @throws NotImplementedException if not implemented
* @throws EngineTerminationException the execution engine has terminated
*/
void load(ClassBytecodes[] cbcs)
throws ClassInstallException, NotImplementedException, EngineTerminationException;
/**
* Notify that classes have been redefined.
*
* @param cbcs the class names and bytecodes that have been redefined
*/
public void classesRedefined(ClassBytecodes[] cbcs);
/**
* Adds the path to the execution class path.
*
* @param path the path to add
* @throws EngineTerminationException the execution engine has terminated
* @throws InternalException an internal problem occurred
*/
void addToClasspath(String path)
throws EngineTerminationException, InternalException;
/**
* Finds the class with the specified binary name.
*
* @param name the binary name of the class
* @return the Class Object
* @throws ClassNotFoundException if the class could not be found
*/
Class<?> findClass(String name) throws ClassNotFoundException;
}
| gpl-2.0 |
atosatto/ansible | lib/ansible/playbook/conditional.py | 10551 | # (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import ast
import re
from jinja2.compiler import generate
from jinja2.exceptions import UndefinedError
from ansible.errors import AnsibleError, AnsibleUndefinedVariable
from ansible.module_utils.six import text_type
from ansible.module_utils._text import to_native
from ansible.playbook.attribute import FieldAttribute
from ansible.template import Templar
from ansible.template.safe_eval import safe_eval
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
DEFINED_REGEX = re.compile(r'(hostvars\[.+\]|[\w_]+)\s+(not\s+is|is|is\s+not)\s+(defined|undefined)')
LOOKUP_REGEX = re.compile(r'lookup\s*\(')
VALID_VAR_REGEX = re.compile("^[_A-Za-z][_a-zA-Z0-9]*$")
class Conditional:
'''
This is a mix-in class, to be used with Base to allow the object
to be run conditionally when a condition is met or skipped.
'''
_when = FieldAttribute(isa='list', default=[])
def __init__(self, loader=None):
# when used directly, this class needs a loader, but we want to
# make sure we don't trample on the existing one if this class
# is used as a mix-in with a playbook base class
if not hasattr(self, '_loader'):
if loader is None:
raise AnsibleError("a loader must be specified when using Conditional() directly")
else:
self._loader = loader
super(Conditional, self).__init__()
def _validate_when(self, attr, name, value):
if not isinstance(value, list):
setattr(self, name, [ value ])
def _get_attr_when(self):
'''
Override for the 'tags' getattr fetcher, used from Base.
'''
when = self._attributes['when']
if when is None:
when = []
if hasattr(self, '_get_parent_attribute'):
when = self._get_parent_attribute('when', extend=True, prepend=True)
return when
def extract_defined_undefined(self, conditional):
results = []
cond = conditional
m = DEFINED_REGEX.search(cond)
while m:
results.append(m.groups())
cond = cond[m.end():]
m = DEFINED_REGEX.search(cond)
return results
def evaluate_conditional(self, templar, all_vars):
'''
Loops through the conditionals set on this object, returning
False if any of them evaluate as such.
'''
# since this is a mix-in, it may not have an underlying datastructure
# associated with it, so we pull it out now in case we need it for
# error reporting below
ds = None
if hasattr(self, '_ds'):
ds = getattr(self, '_ds')
try:
# this allows for direct boolean assignments to conditionals "when: False"
if isinstance(self.when, bool):
return self.when
for conditional in self.when:
if not self._check_conditional(conditional, templar, all_vars):
return False
except Exception as e:
raise AnsibleError(
"The conditional check '%s' failed. The error was: %s" % (to_native(conditional), to_native(e)), obj=ds
)
return True
def _check_conditional(self, conditional, templar, all_vars):
'''
This method does the low-level evaluation of each conditional
set on this object, using jinja2 to wrap the conditionals for
evaluation.
'''
original = conditional
if conditional is None or conditional == '':
return True
# pull the "bare" var out, which allows for nested conditionals
# and things like:
# - assert:
# that:
# - item
# with_items:
# - 1 == 1
if conditional in all_vars and VALID_VAR_REGEX.match(conditional):
conditional = all_vars[conditional]
if templar._clean_data(conditional) != conditional:
display.warning('when statements should not include jinja2 '
'templating delimiters such as {{ }} or {%% %%}. '
'Found: %s' % conditional)
# make sure the templar is using the variables specified with this method
templar.set_available_variables(variables=all_vars)
try:
# if the conditional is "unsafe", disable lookups
disable_lookups = hasattr(conditional, '__UNSAFE__')
conditional = templar.template(conditional, disable_lookups=disable_lookups)
if not isinstance(conditional, text_type) or conditional == "":
return conditional
# update the lookups flag, as the string returned above may now be unsafe
# and we don't want future templating calls to do unsafe things
disable_lookups |= hasattr(conditional, '__UNSAFE__')
# First, we do some low-level jinja2 parsing involving the AST format of the
# statement to ensure we don't do anything unsafe (using the disable_lookup flag above)
class CleansingNodeVisitor(ast.NodeVisitor):
def generic_visit(self, node, inside_call=False, inside_yield=False):
if isinstance(node, ast.Call):
inside_call = True
elif isinstance(node, ast.Yield):
inside_yield = True
elif isinstance(node, ast.Str):
if disable_lookups:
if inside_call and node.s.startswith("__"):
# calling things with a dunder is generally bad at this point...
raise AnsibleError(
"Invalid access found in the conditional: '%s'" % conditional
)
elif inside_yield:
# we're inside a yield, so recursively parse and traverse the AST
# of the result to catch forbidden syntax from executing
parsed = ast.parse(node.s, mode='exec')
cnv = CleansingNodeVisitor()
cnv.visit(parsed)
# iterate over all child nodes
for child_node in ast.iter_child_nodes(node):
self.generic_visit(
child_node,
inside_call=inside_call,
inside_yield=inside_yield
)
try:
e = templar.environment.overlay()
e.filters.update(templar._get_filters())
e.tests.update(templar._get_tests())
res = e._parse(conditional, None, None)
res = generate(res, e, None, None)
parsed = ast.parse(res, mode='exec')
cnv = CleansingNodeVisitor()
cnv.visit(parsed)
except Exception as e:
raise AnsibleError("Invalid conditional detected: %s" % to_native(e))
# and finally we generate and template the presented string and look at the resulting string
presented = "{%% if %s %%} True {%% else %%} False {%% endif %%}" % conditional
val = templar.template(presented, disable_lookups=disable_lookups).strip()
if val == "True":
return True
elif val == "False":
return False
else:
raise AnsibleError("unable to evaluate conditional: %s" % original)
except (AnsibleUndefinedVariable, UndefinedError) as e:
# the templating failed, meaning most likely a variable was undefined. If we happened
# to be looking for an undefined variable, return True, otherwise fail
try:
# first we extract the variable name from the error message
var_name = re.compile(r"'(hostvars\[.+\]|[\w_]+)' is undefined").search(str(e)).groups()[0]
# next we extract all defined/undefined tests from the conditional string
def_undef = self.extract_defined_undefined(conditional)
# then we loop through these, comparing the error variable name against
# each def/undef test we found above. If there is a match, we determine
# whether the logic/state mean the variable should exist or not and return
# the corresponding True/False
for (du_var, logic, state) in def_undef:
# when we compare the var names, normalize quotes because something
# like hostvars['foo'] may be tested against hostvars["foo"]
if var_name.replace("'", '"') == du_var.replace("'", '"'):
# the should exist is a xor test between a negation in the logic portion
# against the state (defined or undefined)
should_exist = ('not' in logic) != (state == 'defined')
if should_exist:
return False
else:
return True
# as nothing above matched the failed var name, re-raise here to
# trigger the AnsibleUndefinedVariable exception again below
raise
except Exception as new_e:
raise AnsibleUndefinedVariable(
"error while evaluating conditional (%s): %s" % (original, e)
)
| gpl-3.0 |
yclas/yclas | oc/vendor/authorize/lib/net/authorize/api/contract/v1/GetAUJobDetailsResponse.php | 1376 | <?php
namespace net\authorize\api\contract\v1;
/**
* Class representing GetAUJobDetailsResponse
*/
class GetAUJobDetailsResponse extends ANetApiResponseType
{
/**
* @property integer $totalNumInResultSet
*/
private $totalNumInResultSet = null;
/**
* @property \net\authorize\api\contract\v1\ListOfAUDetailsType $auDetails
*/
private $auDetails = null;
/**
* Gets as totalNumInResultSet
*
* @return integer
*/
public function getTotalNumInResultSet()
{
return $this->totalNumInResultSet;
}
/**
* Sets a new totalNumInResultSet
*
* @param integer $totalNumInResultSet
* @return self
*/
public function setTotalNumInResultSet($totalNumInResultSet)
{
$this->totalNumInResultSet = $totalNumInResultSet;
return $this;
}
/**
* Gets as auDetails
*
* @return \net\authorize\api\contract\v1\ListOfAUDetailsType
*/
public function getAuDetails()
{
return $this->auDetails;
}
/**
* Sets a new auDetails
*
* @param \net\authorize\api\contract\v1\ListOfAUDetailsType $auDetails
* @return self
*/
public function setAuDetails(\net\authorize\api\contract\v1\ListOfAUDetailsType $auDetails)
{
$this->auDetails = $auDetails;
return $this;
}
}
| gpl-3.0 |
sestrella/ansible | lib/ansible/plugins/inventory/aws_ec2.py | 30217 | # Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
name: aws_ec2
plugin_type: inventory
short_description: EC2 inventory source
requirements:
- boto3
- botocore
extends_documentation_fragment:
- inventory_cache
- constructed
- aws_credentials
description:
- Get inventory hosts from Amazon Web Services EC2.
- Uses a YAML configuration file that ends with C(aws_ec2.(yml|yaml)).
notes:
- If no credentials are provided and the control node has an associated IAM instance profile then the
role will be used for authentication.
author:
- Sloane Hertel (@s-hertel)
options:
plugin:
description: Token that ensures this is a source file for the plugin.
required: True
choices: ['aws_ec2']
iam_role_arn:
description: The ARN of the IAM role to assume to perform the inventory lookup. You should still provide AWS
credentials with enough privilege to perform the AssumeRole action.
version_added: '2.9'
regions:
description:
- A list of regions in which to describe EC2 instances.
- If empty (the default) default this will include all regions, except possibly restricted ones like us-gov-west-1 and cn-north-1.
type: list
default: []
hostnames:
description:
- A list in order of precedence for hostname variables.
- You can use the options specified in U(http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html#options).
- To use tags as hostnames use the syntax tag:Name=Value to use the hostname Name_Value, or tag:Name to use the value of the Name tag.
type: list
default: []
filters:
description:
- A dictionary of filter value pairs.
- Available filters are listed here U(http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html#options).
type: dict
default: {}
include_extra_api_calls:
description:
- Add two additional API calls for every instance to include 'persistent' and 'events' host variables.
- Spot instances may be persistent and instances may have associated events.
type: bool
default: False
version_added: '2.8'
strict_permissions:
description:
- By default if a 403 (Forbidden) error code is encountered this plugin will fail.
- You can set this option to False in the inventory config file which will allow 403 errors to be gracefully skipped.
type: bool
default: True
use_contrib_script_compatible_sanitization:
description:
- By default this plugin is using a general group name sanitization to create safe and usable group names for use in Ansible.
This option allows you to override that, in efforts to allow migration from the old inventory script and
matches the sanitization of groups when the script's ``replace_dash_in_groups`` option is set to ``False``.
To replicate behavior of ``replace_dash_in_groups = True`` with constructed groups,
you will need to replace hyphens with underscores via the regex_replace filter for those entries.
- For this to work you should also turn off the TRANSFORM_INVALID_GROUP_CHARS setting,
otherwise the core engine will just use the standard sanitization on top.
- This is not the default as such names break certain functionality as not all characters are valid Python identifiers
which group names end up being used as.
type: bool
default: False
version_added: '2.8'
'''
EXAMPLES = '''
# Minimal example using environment vars or instance role credentials
# Fetch all hosts in us-east-1, the hostname is the public DNS if it exists, otherwise the private IP address
plugin: aws_ec2
regions:
- us-east-1
# Example using filters, ignoring permission errors, and specifying the hostname precedence
plugin: aws_ec2
boto_profile: aws_profile
# Populate inventory with instances in these regions
regions:
- us-east-1
- us-east-2
filters:
# All instances with their `Environment` tag set to `dev`
tag:Environment: dev
# All dev and QA hosts
tag:Environment:
- dev
- qa
instance.group-id: sg-xxxxxxxx
# Ignores 403 errors rather than failing
strict_permissions: False
# Note: I(hostnames) sets the inventory_hostname. To modify ansible_host without modifying
# inventory_hostname use compose (see example below).
hostnames:
- tag:Name=Tag1,Name=Tag2 # Return specific hosts only
- tag:CustomDNSName
- dns-name
- private-ip-address
# Example using constructed features to create groups and set ansible_host
plugin: aws_ec2
regions:
- us-east-1
- us-west-1
# keyed_groups may be used to create custom groups
strict: False
keyed_groups:
# Add e.g. x86_64 hosts to an arch_x86_64 group
- prefix: arch
key: 'architecture'
# Add hosts to tag_Name_Value groups for each Name/Value tag pair
- prefix: tag
key: tags
# Add hosts to e.g. instance_type_z3_tiny
- prefix: instance_type
key: instance_type
# Create security_groups_sg_abcd1234 group for each SG
- key: 'security_groups|json_query("[].group_id")'
prefix: 'security_groups'
# Create a group for each value of the Application tag
- key: tags.Application
separator: ''
# Create a group per region e.g. aws_region_us_east_2
- key: placement.region
prefix: aws_region
# Create a group (or groups) based on the value of a custom tag "Role" and add them to a metagroup called "project"
- key: tags['Role']
prefix: foo
parent_group: "project"
# Set individual variables with compose
compose:
# Use the private IP address to connect to the host
# (note: this does not modify inventory_hostname, which is set via I(hostnames))
ansible_host: private_ip_address
'''
import re
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_native, to_text
from ansible.module_utils.ec2 import ansible_dict_to_boto3_filter_list, boto3_tag_list_to_ansible_dict
from ansible.module_utils.ec2 import camel_dict_to_snake_dict
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable
from ansible.utils.display import Display
try:
import boto3
import botocore
except ImportError:
raise AnsibleError('The ec2 dynamic inventory plugin requires boto3 and botocore.')
display = Display()
# The mappings give an array of keys to get from the filter name to the value
# returned by boto3's EC2 describe_instances method.
instance_meta_filter_to_boto_attr = {
'group-id': ('Groups', 'GroupId'),
'group-name': ('Groups', 'GroupName'),
'network-interface.attachment.instance-owner-id': ('OwnerId',),
'owner-id': ('OwnerId',),
'requester-id': ('RequesterId',),
'reservation-id': ('ReservationId',),
}
instance_data_filter_to_boto_attr = {
'affinity': ('Placement', 'Affinity'),
'architecture': ('Architecture',),
'availability-zone': ('Placement', 'AvailabilityZone'),
'block-device-mapping.attach-time': ('BlockDeviceMappings', 'Ebs', 'AttachTime'),
'block-device-mapping.delete-on-termination': ('BlockDeviceMappings', 'Ebs', 'DeleteOnTermination'),
'block-device-mapping.device-name': ('BlockDeviceMappings', 'DeviceName'),
'block-device-mapping.status': ('BlockDeviceMappings', 'Ebs', 'Status'),
'block-device-mapping.volume-id': ('BlockDeviceMappings', 'Ebs', 'VolumeId'),
'client-token': ('ClientToken',),
'dns-name': ('PublicDnsName',),
'host-id': ('Placement', 'HostId'),
'hypervisor': ('Hypervisor',),
'iam-instance-profile.arn': ('IamInstanceProfile', 'Arn'),
'image-id': ('ImageId',),
'instance-id': ('InstanceId',),
'instance-lifecycle': ('InstanceLifecycle',),
'instance-state-code': ('State', 'Code'),
'instance-state-name': ('State', 'Name'),
'instance-type': ('InstanceType',),
'instance.group-id': ('SecurityGroups', 'GroupId'),
'instance.group-name': ('SecurityGroups', 'GroupName'),
'ip-address': ('PublicIpAddress',),
'kernel-id': ('KernelId',),
'key-name': ('KeyName',),
'launch-index': ('AmiLaunchIndex',),
'launch-time': ('LaunchTime',),
'monitoring-state': ('Monitoring', 'State'),
'network-interface.addresses.private-ip-address': ('NetworkInterfaces', 'PrivateIpAddress'),
'network-interface.addresses.primary': ('NetworkInterfaces', 'PrivateIpAddresses', 'Primary'),
'network-interface.addresses.association.public-ip': ('NetworkInterfaces', 'PrivateIpAddresses', 'Association', 'PublicIp'),
'network-interface.addresses.association.ip-owner-id': ('NetworkInterfaces', 'PrivateIpAddresses', 'Association', 'IpOwnerId'),
'network-interface.association.public-ip': ('NetworkInterfaces', 'Association', 'PublicIp'),
'network-interface.association.ip-owner-id': ('NetworkInterfaces', 'Association', 'IpOwnerId'),
'network-interface.association.allocation-id': ('ElasticGpuAssociations', 'ElasticGpuId'),
'network-interface.association.association-id': ('ElasticGpuAssociations', 'ElasticGpuAssociationId'),
'network-interface.attachment.attachment-id': ('NetworkInterfaces', 'Attachment', 'AttachmentId'),
'network-interface.attachment.instance-id': ('InstanceId',),
'network-interface.attachment.device-index': ('NetworkInterfaces', 'Attachment', 'DeviceIndex'),
'network-interface.attachment.status': ('NetworkInterfaces', 'Attachment', 'Status'),
'network-interface.attachment.attach-time': ('NetworkInterfaces', 'Attachment', 'AttachTime'),
'network-interface.attachment.delete-on-termination': ('NetworkInterfaces', 'Attachment', 'DeleteOnTermination'),
'network-interface.availability-zone': ('Placement', 'AvailabilityZone'),
'network-interface.description': ('NetworkInterfaces', 'Description'),
'network-interface.group-id': ('NetworkInterfaces', 'Groups', 'GroupId'),
'network-interface.group-name': ('NetworkInterfaces', 'Groups', 'GroupName'),
'network-interface.ipv6-addresses.ipv6-address': ('NetworkInterfaces', 'Ipv6Addresses', 'Ipv6Address'),
'network-interface.mac-address': ('NetworkInterfaces', 'MacAddress'),
'network-interface.network-interface-id': ('NetworkInterfaces', 'NetworkInterfaceId'),
'network-interface.owner-id': ('NetworkInterfaces', 'OwnerId'),
'network-interface.private-dns-name': ('NetworkInterfaces', 'PrivateDnsName'),
# 'network-interface.requester-id': (),
'network-interface.requester-managed': ('NetworkInterfaces', 'Association', 'IpOwnerId'),
'network-interface.status': ('NetworkInterfaces', 'Status'),
'network-interface.source-dest-check': ('NetworkInterfaces', 'SourceDestCheck'),
'network-interface.subnet-id': ('NetworkInterfaces', 'SubnetId'),
'network-interface.vpc-id': ('NetworkInterfaces', 'VpcId'),
'placement-group-name': ('Placement', 'GroupName'),
'platform': ('Platform',),
'private-dns-name': ('PrivateDnsName',),
'private-ip-address': ('PrivateIpAddress',),
'product-code': ('ProductCodes', 'ProductCodeId'),
'product-code.type': ('ProductCodes', 'ProductCodeType'),
'ramdisk-id': ('RamdiskId',),
'reason': ('StateTransitionReason',),
'root-device-name': ('RootDeviceName',),
'root-device-type': ('RootDeviceType',),
'source-dest-check': ('SourceDestCheck',),
'spot-instance-request-id': ('SpotInstanceRequestId',),
'state-reason-code': ('StateReason', 'Code'),
'state-reason-message': ('StateReason', 'Message'),
'subnet-id': ('SubnetId',),
'tag': ('Tags',),
'tag-key': ('Tags',),
'tag-value': ('Tags',),
'tenancy': ('Placement', 'Tenancy'),
'virtualization-type': ('VirtualizationType',),
'vpc-id': ('VpcId',),
}
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
NAME = 'aws_ec2'
def __init__(self):
super(InventoryModule, self).__init__()
self.group_prefix = 'aws_ec2_'
# credentials
self.boto_profile = None
self.aws_secret_access_key = None
self.aws_access_key_id = None
self.aws_security_token = None
self.iam_role_arn = None
def _compile_values(self, obj, attr):
'''
:param obj: A list or dict of instance attributes
:param attr: A key
:return The value(s) found via the attr
'''
if obj is None:
return
temp_obj = []
if isinstance(obj, list) or isinstance(obj, tuple):
for each in obj:
value = self._compile_values(each, attr)
if value:
temp_obj.append(value)
else:
temp_obj = obj.get(attr)
has_indexes = any([isinstance(temp_obj, list), isinstance(temp_obj, tuple)])
if has_indexes and len(temp_obj) == 1:
return temp_obj[0]
return temp_obj
def _get_boto_attr_chain(self, filter_name, instance):
'''
:param filter_name: The filter
:param instance: instance dict returned by boto3 ec2 describe_instances()
'''
allowed_filters = sorted(list(instance_data_filter_to_boto_attr.keys()) + list(instance_meta_filter_to_boto_attr.keys()))
if filter_name not in allowed_filters:
raise AnsibleError("Invalid filter '%s' provided; filter must be one of %s." % (filter_name,
allowed_filters))
if filter_name in instance_data_filter_to_boto_attr:
boto_attr_list = instance_data_filter_to_boto_attr[filter_name]
else:
boto_attr_list = instance_meta_filter_to_boto_attr[filter_name]
instance_value = instance
for attribute in boto_attr_list:
instance_value = self._compile_values(instance_value, attribute)
return instance_value
def _get_credentials(self):
'''
:return A dictionary of boto client credentials
'''
boto_params = {}
for credential in (('aws_access_key_id', self.aws_access_key_id),
('aws_secret_access_key', self.aws_secret_access_key),
('aws_session_token', self.aws_security_token)):
if credential[1]:
boto_params[credential[0]] = credential[1]
return boto_params
def _get_connection(self, credentials, region='us-east-1'):
try:
connection = boto3.session.Session(profile_name=self.boto_profile).client('ec2', region, **credentials)
except (botocore.exceptions.ProfileNotFound, botocore.exceptions.PartialCredentialsError) as e:
if self.boto_profile:
try:
connection = boto3.session.Session(profile_name=self.boto_profile).client('ec2', region)
except (botocore.exceptions.ProfileNotFound, botocore.exceptions.PartialCredentialsError) as e:
raise AnsibleError("Insufficient credentials found: %s" % to_native(e))
else:
raise AnsibleError("Insufficient credentials found: %s" % to_native(e))
return connection
def _boto3_assume_role(self, credentials, region):
"""
Assume an IAM role passed by iam_role_arn parameter
:return: a dict containing the credentials of the assumed role
"""
iam_role_arn = self.iam_role_arn
try:
sts_connection = boto3.session.Session(profile_name=self.boto_profile).client('sts', region, **credentials)
sts_session = sts_connection.assume_role(RoleArn=iam_role_arn, RoleSessionName='ansible_aws_ec2_dynamic_inventory')
return dict(
aws_access_key_id=sts_session['Credentials']['AccessKeyId'],
aws_secret_access_key=sts_session['Credentials']['SecretAccessKey'],
aws_session_token=sts_session['Credentials']['SessionToken']
)
except botocore.exceptions.ClientError as e:
raise AnsibleError("Unable to assume IAM role: %s" % to_native(e))
def _boto3_conn(self, regions):
'''
:param regions: A list of regions to create a boto3 client
Generator that yields a boto3 client and the region
'''
credentials = self._get_credentials()
iam_role_arn = self.iam_role_arn
if not regions:
try:
# as per https://boto3.amazonaws.com/v1/documentation/api/latest/guide/ec2-example-regions-avail-zones.html
client = self._get_connection(credentials)
resp = client.describe_regions()
regions = [x['RegionName'] for x in resp.get('Regions', [])]
except botocore.exceptions.NoRegionError:
# above seems to fail depending on boto3 version, ignore and lets try something else
pass
# fallback to local list hardcoded in boto3 if still no regions
if not regions:
session = boto3.Session()
regions = session.get_available_regions('ec2')
# I give up, now you MUST give me regions
if not regions:
raise AnsibleError('Unable to get regions list from available methods, you must specify the "regions" option to continue.')
for region in regions:
connection = self._get_connection(credentials, region)
try:
if iam_role_arn is not None:
assumed_credentials = self._boto3_assume_role(credentials, region)
else:
assumed_credentials = credentials
connection = boto3.session.Session(profile_name=self.boto_profile).client('ec2', region, **assumed_credentials)
except (botocore.exceptions.ProfileNotFound, botocore.exceptions.PartialCredentialsError) as e:
if self.boto_profile:
try:
connection = boto3.session.Session(profile_name=self.boto_profile).client('ec2', region)
except (botocore.exceptions.ProfileNotFound, botocore.exceptions.PartialCredentialsError) as e:
raise AnsibleError("Insufficient credentials found: %s" % to_native(e))
else:
raise AnsibleError("Insufficient credentials found: %s" % to_native(e))
yield connection, region
def _get_instances_by_region(self, regions, filters, strict_permissions):
'''
:param regions: a list of regions in which to describe instances
:param filters: a list of boto3 filter dictionaries
:param strict_permissions: a boolean determining whether to fail or ignore 403 error codes
:return A list of instance dictionaries
'''
all_instances = []
for connection, region in self._boto3_conn(regions):
try:
# By default find non-terminated/terminating instances
if not any([f['Name'] == 'instance-state-name' for f in filters]):
filters.append({'Name': 'instance-state-name', 'Values': ['running', 'pending', 'stopping', 'stopped']})
paginator = connection.get_paginator('describe_instances')
reservations = paginator.paginate(Filters=filters).build_full_result().get('Reservations')
instances = []
for r in reservations:
new_instances = r['Instances']
for instance in new_instances:
instance.update(self._get_reservation_details(r))
if self.get_option('include_extra_api_calls'):
instance.update(self._get_event_set_and_persistence(connection, instance['InstanceId'], instance.get('SpotInstanceRequestId')))
instances.extend(new_instances)
except botocore.exceptions.ClientError as e:
if e.response['ResponseMetadata']['HTTPStatusCode'] == 403 and not strict_permissions:
instances = []
else:
raise AnsibleError("Failed to describe instances: %s" % to_native(e))
except botocore.exceptions.BotoCoreError as e:
raise AnsibleError("Failed to describe instances: %s" % to_native(e))
all_instances.extend(instances)
return sorted(all_instances, key=lambda x: x['InstanceId'])
def _get_reservation_details(self, reservation):
return {
'OwnerId': reservation['OwnerId'],
'RequesterId': reservation.get('RequesterId', ''),
'ReservationId': reservation['ReservationId']
}
def _get_event_set_and_persistence(self, connection, instance_id, spot_instance):
host_vars = {'Events': '', 'Persistent': False}
try:
kwargs = {'InstanceIds': [instance_id]}
host_vars['Events'] = connection.describe_instance_status(**kwargs)['InstanceStatuses'][0].get('Events', '')
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
if not self.get_option('strict_permissions'):
pass
else:
raise AnsibleError("Failed to describe instance status: %s" % to_native(e))
if spot_instance:
try:
kwargs = {'SpotInstanceRequestIds': [spot_instance]}
host_vars['Persistent'] = bool(
connection.describe_spot_instance_requests(**kwargs)['SpotInstanceRequests'][0].get('Type') == 'persistent'
)
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
if not self.get_option('strict_permissions'):
pass
else:
raise AnsibleError("Failed to describe spot instance requests: %s" % to_native(e))
return host_vars
def _get_tag_hostname(self, preference, instance):
tag_hostnames = preference.split('tag:', 1)[1]
if ',' in tag_hostnames:
tag_hostnames = tag_hostnames.split(',')
else:
tag_hostnames = [tag_hostnames]
tags = boto3_tag_list_to_ansible_dict(instance.get('Tags', []))
for v in tag_hostnames:
if '=' in v:
tag_name, tag_value = v.split('=')
if tags.get(tag_name) == tag_value:
return to_text(tag_name) + "_" + to_text(tag_value)
else:
tag_value = tags.get(v)
if tag_value:
return to_text(tag_value)
return None
def _get_hostname(self, instance, hostnames):
'''
:param instance: an instance dict returned by boto3 ec2 describe_instances()
:param hostnames: a list of hostname destination variables in order of preference
:return the preferred identifer for the host
'''
if not hostnames:
hostnames = ['dns-name', 'private-dns-name']
hostname = None
for preference in hostnames:
if 'tag' in preference:
if not preference.startswith('tag:'):
raise AnsibleError("To name a host by tags name_value, use 'tag:name=value'.")
hostname = self._get_tag_hostname(preference, instance)
else:
hostname = self._get_boto_attr_chain(preference, instance)
if hostname:
break
if hostname:
if ':' in to_text(hostname):
return self._sanitize_group_name((to_text(hostname)))
else:
return to_text(hostname)
def _query(self, regions, filters, strict_permissions):
'''
:param regions: a list of regions to query
:param filters: a list of boto3 filter dictionaries
:param hostnames: a list of hostname destination variables in order of preference
:param strict_permissions: a boolean determining whether to fail or ignore 403 error codes
'''
return {'aws_ec2': self._get_instances_by_region(regions, filters, strict_permissions)}
def _populate(self, groups, hostnames):
for group in groups:
group = self.inventory.add_group(group)
self._add_hosts(hosts=groups[group], group=group, hostnames=hostnames)
self.inventory.add_child('all', group)
def _add_hosts(self, hosts, group, hostnames):
'''
:param hosts: a list of hosts to be added to a group
:param group: the name of the group to which the hosts belong
:param hostnames: a list of hostname destination variables in order of preference
'''
for host in hosts:
hostname = self._get_hostname(host, hostnames)
host = camel_dict_to_snake_dict(host, ignore_list=['Tags'])
host['tags'] = boto3_tag_list_to_ansible_dict(host.get('tags', []))
# Allow easier grouping by region
host['placement']['region'] = host['placement']['availability_zone'][:-1]
if not hostname:
continue
self.inventory.add_host(hostname, group=group)
for hostvar, hostval in host.items():
self.inventory.set_variable(hostname, hostvar, hostval)
# Use constructed if applicable
strict = self.get_option('strict')
# Composed variables
self._set_composite_vars(self.get_option('compose'), host, hostname, strict=strict)
# Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group
self._add_host_to_composed_groups(self.get_option('groups'), host, hostname, strict=strict)
# Create groups based on variable values and add the corresponding hosts to it
self._add_host_to_keyed_groups(self.get_option('keyed_groups'), host, hostname, strict=strict)
def _set_credentials(self):
'''
:param config_data: contents of the inventory config file
'''
self.boto_profile = self.get_option('aws_profile')
self.aws_access_key_id = self.get_option('aws_access_key')
self.aws_secret_access_key = self.get_option('aws_secret_key')
self.aws_security_token = self.get_option('aws_security_token')
self.iam_role_arn = self.get_option('iam_role_arn')
if not self.boto_profile and not (self.aws_access_key_id and self.aws_secret_access_key):
session = botocore.session.get_session()
try:
credentials = session.get_credentials().get_frozen_credentials()
except AttributeError:
pass
else:
self.aws_access_key_id = credentials.access_key
self.aws_secret_access_key = credentials.secret_key
self.aws_security_token = credentials.token
if not self.boto_profile and not (self.aws_access_key_id and self.aws_secret_access_key):
raise AnsibleError("Insufficient boto credentials found. Please provide them in your "
"inventory configuration file or set them as environment variables.")
def verify_file(self, path):
'''
:param loader: an ansible.parsing.dataloader.DataLoader object
:param path: the path to the inventory config file
:return the contents of the config file
'''
if super(InventoryModule, self).verify_file(path):
if path.endswith(('aws_ec2.yml', 'aws_ec2.yaml')):
return True
display.debug("aws_ec2 inventory filename must end with 'aws_ec2.yml' or 'aws_ec2.yaml'")
return False
def parse(self, inventory, loader, path, cache=True):
super(InventoryModule, self).parse(inventory, loader, path)
self._read_config_data(path)
if self.get_option('use_contrib_script_compatible_sanitization'):
self._sanitize_group_name = self._legacy_script_compatible_group_sanitization
self._set_credentials()
# get user specifications
regions = self.get_option('regions')
filters = ansible_dict_to_boto3_filter_list(self.get_option('filters'))
hostnames = self.get_option('hostnames')
strict_permissions = self.get_option('strict_permissions')
cache_key = self.get_cache_key(path)
# false when refresh_cache or --flush-cache is used
if cache:
# get the user-specified directive
cache = self.get_option('cache')
# Generate inventory
cache_needs_update = False
if cache:
try:
results = self._cache[cache_key]
except KeyError:
# if cache expires or cache file doesn't exist
cache_needs_update = True
if not cache or cache_needs_update:
results = self._query(regions, filters, strict_permissions)
self._populate(results, hostnames)
# If the cache has expired/doesn't exist or if refresh_inventory/flush cache is used
# when the user is using caching, update the cached inventory
if cache_needs_update or (not cache and self.get_option('cache')):
self._cache[cache_key] = results
@staticmethod
def _legacy_script_compatible_group_sanitization(name):
# note that while this mirrors what the script used to do, it has many issues with unicode and usability in python
regex = re.compile(r"[^A-Za-z0-9\_\-]")
return regex.sub('_', name)
| gpl-3.0 |
rcarrillocruz/ansible | test/units/modules/network/ios/test_ios_config.py | 6051 | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.compat.tests.mock import patch
from ansible.modules.network.ios import ios_config
from .ios_module import TestIosModule, load_fixture, set_module_args
class TestIosConfigModule(TestIosModule):
module = ios_config
def setUp(self):
self.mock_get_config = patch('ansible.modules.network.ios.ios_config.get_config')
self.get_config = self.mock_get_config.start()
self.mock_load_config = patch('ansible.modules.network.ios.ios_config.load_config')
self.load_config = self.mock_load_config.start()
self.mock_run_commands = patch('ansible.modules.network.ios.ios_config.run_commands')
self.run_commands = self.mock_run_commands.start()
def tearDown(self):
self.mock_get_config.stop()
self.mock_load_config.stop()
self.mock_run_commands.stop()
def load_fixtures(self, commands=None):
config_file = 'ios_config_config.cfg'
self.get_config.return_value = load_fixture(config_file)
self.load_config.return_value = None
def test_ios_config_unchanged(self):
src = load_fixture('ios_config_config.cfg')
set_module_args(dict(src=src))
self.execute_module()
def test_ios_config_src(self):
src = load_fixture('ios_config_src.cfg')
set_module_args(dict(src=src))
commands = ['hostname foo', 'interface GigabitEthernet0/0',
'no ip address']
self.execute_module(changed=True, commands=commands)
def test_ios_config_backup(self):
set_module_args(dict(backup=True))
result = self.execute_module()
self.assertIn('__backup__', result)
def test_ios_config_save(self):
self.run_commands.return_value = "Hostname foo"
set_module_args(dict(save=True))
self.execute_module(changed=True)
self.assertEqual(self.run_commands.call_count, 2)
self.assertEqual(self.get_config.call_count, 0)
self.assertEqual(self.load_config.call_count, 0)
args = self.run_commands.call_args[0][1]
self.assertIn('copy running-config startup-config\r', args)
def test_ios_config_lines_wo_parents(self):
set_module_args(dict(lines=['hostname foo']))
commands = ['hostname foo']
self.execute_module(changed=True, commands=commands)
def test_ios_config_lines_w_parents(self):
set_module_args(dict(lines=['shutdown'], parents=['interface GigabitEthernet0/0']))
commands = ['interface GigabitEthernet0/0', 'shutdown']
self.execute_module(changed=True, commands=commands)
def test_ios_config_before(self):
set_module_args(dict(lines=['hostname foo'], before=['test1', 'test2']))
commands = ['test1', 'test2', 'hostname foo']
self.execute_module(changed=True, commands=commands, sort=False)
def test_ios_config_after(self):
set_module_args(dict(lines=['hostname foo'], after=['test1', 'test2']))
commands = ['hostname foo', 'test1', 'test2']
self.execute_module(changed=True, commands=commands, sort=False)
def test_ios_config_before_after_no_change(self):
set_module_args(dict(lines=['hostname router'],
before=['test1', 'test2'],
after=['test3', 'test4']))
self.execute_module()
def test_ios_config_config(self):
config = 'hostname localhost'
set_module_args(dict(lines=['hostname router'], config=config))
commands = ['hostname router']
self.execute_module(changed=True, commands=commands)
def test_ios_config_replace_block(self):
lines = ['description test string', 'test string']
parents = ['interface GigabitEthernet0/0']
set_module_args(dict(lines=lines, replace='block', parents=parents))
commands = parents + lines
self.execute_module(changed=True, commands=commands)
def test_ios_config_force(self):
lines = ['hostname router']
set_module_args(dict(lines=lines, force=True))
self.execute_module(changed=True, commands=lines)
def test_ios_config_match_none(self):
lines = ['ip address 1.2.3.4 255.255.255.0', 'description test string']
parents = ['interface GigabitEthernet0/0']
set_module_args(dict(lines=lines, parents=parents, match='none'))
commands = parents + lines
self.execute_module(changed=True, commands=commands, sort=False)
def test_ios_config_match_strict(self):
lines = ['ip address 1.2.3.4 255.255.255.0', 'description test string',
'shutdown']
parents = ['interface GigabitEthernet0/0']
set_module_args(dict(lines=lines, parents=parents, match='strict'))
commands = parents + ['shutdown']
self.execute_module(changed=True, commands=commands, sort=False)
def test_ios_config_match_exact(self):
lines = ['ip address 1.2.3.4 255.255.255.0', 'description test string',
'shutdown']
parents = ['interface GigabitEthernet0/0']
set_module_args(dict(lines=lines, parents=parents, match='exact'))
commands = parents + lines
self.execute_module(changed=True, commands=commands, sort=False)
| gpl-3.0 |
Zeipt/Mycely_fdroid | platforms/android/assets/www/jxcore/node_modules/sodium/lib/keys/box-key.js | 942 | /**
* Created by bmf on 11/2/13.
*/
/* jslint node: true */
'use strict';
var util = require('util');
var binding = require('../../build/Release/sodium');
var KeyPair = require('./keypair');
var Box = function BoxKey(publicKey, secretKey, encoding) {
var self = this;
KeyPair.call(this);
self.init({
publicKeySize : binding.crypto_box_PUBLICKEYBYTES,
secretKeySize : binding.crypto_box_SECRETKEYBYTES,
publicKey : publicKey,
secretKey : secretKey,
type: 'BoxKey'
});
self.generate = function() {
var keys = binding.crypto_box_keypair();
self.secretKey.set(keys.secretKey);
self.publicKey.set(keys.publicKey);
};
if( !publicKey || !secretKey ||
!self.isValid({ 'publicKey': publicKey, 'secretKey': secretKey }) ) {
// Generate the keys
self.generate();
}
};
util.inherits(Box, KeyPair);
module.exports = Box; | agpl-3.0 |
eripahle/framework | Samples/Imaging/Detection (Blobs)/Properties/Resources.Designer.cs | 3216 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SampleApp.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SampleApp.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap demo {
get {
object obj = ResourceManager.GetObject("demo", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| lgpl-2.1 |
GabeLoins/airpal | src/main/resources/assets/javascripts/app.js | 246 | /**
* App Bootstrap
*/
import 'es6-shim';
import 'whatwg-fetch';
import AirpalApp from './components/AirpalApp.jsx';
import React from 'react';
// Start the main app
React.render(
<AirpalApp />,
document.querySelector('.js-react-app')
);
| apache-2.0 |
Saltarelle/SaltarelleCompiler | Runtime/CoreLib.Tests/Core/Reflection/TypeSystemTests.cs | 3496 | using NUnit.Framework;
namespace CoreLib.Tests.Core.Reflection {
[TestFixture]
public class TypeSystemTests : CoreLibTestBase {
[Test]
public void CastToSerializableTypeIsANoOp() {
SourceVerifier.AssertSourceCorrect(@"
using System;
using System.Runtime.CompilerServices;
[Serializable]
sealed class R {}
public class C {
private void M() {
object o = null;
// BEGIN
var v1 = (R)o;
// END
}
}",
@" var v1 = o;
");
}
[Test]
public void CastToImportedInterfaceIsANoOp() {
SourceVerifier.AssertSourceCorrect(@"
using System;
using System.Runtime.CompilerServices;
[Imported]
interface I {}
public class C {
private void M() {
object o = null;
// BEGIN
var v1 = (I)o;
// END
}
}",
@" var v1 = o;
");
}
[Test]
public void CastToImportedGenericClassIsANoOp() {
SourceVerifier.AssertSourceCorrect(@"
using System;
using System.Runtime.CompilerServices;
[Imported]
class C1<T> {}
public class C {
private void M() {
object o = null;
// BEGIN
var v1 = (C1<int>)o;
// END
}
}",
@" var v1 = o;
");
}
[Test]
public void CastBetweenTypesWithTheSameScriptNameIsANoOp() {
SourceVerifier.AssertSourceCorrect(@"
using System;
using System.Runtime.CompilerServices;
[ScriptName(""X"")]
class C1 {}
[ScriptName(""X"")]
class C2 : C1 {}
public class C {
private void M() {
C1 o = null;
// BEGIN
var v1 = (C2)o;
var v2 = o as C2;
var v3 = o is C2;
// END
}
}",
@" var v1 = o;
var v2 = o;
var v3 = ss.isValue(o);
");
}
[Test]
public void ComparingObjectToNullIsCallToIsNullOrUndefined() {
SourceVerifier.AssertSourceCorrect(@"
using System;
public class C {
private void M() {
object o = null;
// BEGIN
var v1 = o == null;
var v2 = null == o;
var v3 = o != null;
var v4 = null != o;
// END
}
}",
@" var v1 = ss.isNullOrUndefined(o);
var v2 = ss.isNullOrUndefined(o);
var v3 = ss.isValue(o);
var v4 = ss.isValue(o);
");
}
[Test]
public void ComparingWithLiteralStringIsNotCallToIsNullOrUndefined() {
SourceVerifier.AssertSourceCorrect(@"
using System;
public class C {
private void M() {
object o = null;
// BEGIN
var v1 = o == ""X"";
var v2 = ""X"" == o;
var v3 = o != ""X"";
var v4 = ""X"" != o;
// END
}
}",
@" var v1 = o === 'X';
var v2 = 'X' === o;
var v3 = o !== 'X';
var v4 = 'X' !== o;
");
}
[Test]
public void ComparingObjectsIsCallToReferenceEquals() {
SourceVerifier.AssertSourceCorrect(@"
using System;
public class C {
private void M() {
object o1 = null, o2 = null;
// BEGIN
var v1 = o1 == o2;
var v2 = o1 != o2;
// END
}
}",
@" var v1 = ss.referenceEquals(o1, o2);
var v2 = !ss.referenceEquals(o1, o2);
");
}
[Test]
public void ConvertingDynamicToBoolUsesDoubleNegation() {
SourceVerifier.AssertSourceCorrect(@"
using System;
public class C {
private void M() {
dynamic d = null;
// BEGIN
bool b = d;
// END
}
}",
@" var b = !!d;
");
}
[Test]
public void DefaultValueOfNullable() {
SourceVerifier.AssertSourceCorrect(@"
using System;
public class C {
private void M() {
// BEGIN
decimal? v1 = default(decimal?);
decimal? v2 = null;
// END
}
}",
@" var v1 = null;
var v2 = null;
");
}
[Test]
public void DefaultValueOfStruct() {
SourceVerifier.AssertSourceCorrect(@"
using System;
public class C {
private void M() {
// BEGIN
var v = default(TimeSpan);
// END
}
}",
@" var v = ss.getDefaultValue(ss.TimeSpan);
");
}
}
} | apache-2.0 |
freebsd/phabricator | src/applications/policy/__tests__/PhabricatorPolicyTestObject.php | 1547 | <?php
/**
* Configurable test object for implementing Policy unit tests.
*/
final class PhabricatorPolicyTestObject
extends Phobject
implements
PhabricatorPolicyInterface,
PhabricatorExtendedPolicyInterface {
private $phid;
private $capabilities = array();
private $policies = array();
private $automaticCapabilities = array();
private $extendedPolicies = array();
public function setPHID($phid) {
$this->phid = $phid;
return $this;
}
public function getPHID() {
return $this->phid;
}
public function getCapabilities() {
return $this->capabilities;
}
public function getPolicy($capability) {
return idx($this->policies, $capability);
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
$auto = idx($this->automaticCapabilities, $capability, array());
return idx($auto, $viewer->getPHID());
}
public function setCapabilities(array $capabilities) {
$this->capabilities = $capabilities;
return $this;
}
public function setPolicies(array $policy_map) {
$this->policies = $policy_map;
return $this;
}
public function setAutomaticCapabilities(array $auto_map) {
$this->automaticCapabilities = $auto_map;
return $this;
}
public function setExtendedPolicies(array $extended_policies) {
$this->extendedPolicies = $extended_policies;
return $this;
}
public function getExtendedPolicy($capability, PhabricatorUser $viewer) {
return idx($this->extendedPolicies, $capability, array());
}
}
| apache-2.0 |
graydon/rust | src/test/ui/span/E0493.rs | 270 | struct Foo {
a: u32
}
impl Drop for Foo {
fn drop(&mut self) {}
}
struct Bar {
a: u32
}
impl Drop for Bar {
fn drop(&mut self) {}
}
const F : Foo = (Foo { a : 0 }, Foo { a : 1 }).1;
//~^ destructors cannot be evaluated at compile-time
fn main() {
}
| apache-2.0 |
surydana/xssprotect | test/com/blogspot/radialmind/html/NoXMLTest.java | 1843 | /**
* Copyright 2007 Gerard Toonstra
*
* Licensed under the terms of the Apache Software License v2
*
* This file is part of the XSS Protect library
*/
package com.blogspot.radialmind.html;
import java.io.StringReader;
import java.io.StringWriter;
import junit.framework.TestCase;
public class NoXMLTest extends TestCase implements IHTMLFilter {
String html = "<html><head>\n<title>test</title>\n</head>\n<body><img src=\"http://images.google.com\"></body></html>\n";
public void testWithXMLConversion() {
StringReader reader = new StringReader( html );
StringWriter writer = new StringWriter();
try {
HTMLParser.process( reader, writer, this, true );
String buffer = new String( writer.toString() );
System.out.println( buffer );
assertEquals( buffer, "<html><head><title>test</title></head><body><img src=\"http://images.google.com\"/></body></html>" );
} catch (HandlingException e) {
e.printStackTrace();
fail( e.getMessage() );
}
}
public void testXMLConversion() {
StringReader reader = new StringReader( html );
StringWriter writer = new StringWriter();
try {
HTMLParser.process( reader, writer, this, false );
String buffer = new String( writer.toString() );
System.out.println( buffer );
assertEquals( buffer, "<html><head><title>test</title></head><body><img src=\"http://images.google.com\"></body></html>" );
} catch (HandlingException e) {
e.printStackTrace();
fail( e.getMessage() );
}
}
public boolean filterAttribute(String tagName, String attrName, String attrValue) {
return false;
}
public boolean filterTag(String tagName) {
return false;
}
public String modifyAttributeValue(String tagName, String attrName, String value) {
return value;
}
public String modifyNodeText(String tagName, String text) {
return text;
}
}
| apache-2.0 |
Nogrod/jint | Jint.Tests.Ecma/TestCases/ch15/15.5/15.5.4/15.5.4.20/15.5.4.20-4-3.js | 324 | /// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.5/15.5.4/15.5.4.20/15.5.4.20-4-3.js
* @description String.prototype.trim handles whitepace and lineterminators (\u0009abc)
*/
function testcase() {
if ("\u0009abc".trim() === "abc") {
return true;
}
}
runTestCase(testcase);
| bsd-2-clause |
honestegg/jint | Jint.Tests.Ecma/TestCases/ch15/15.12/15.12.2/15.12.2-2-3.js | 1864 | /// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.12/15.12.2/15.12.2-2-3.js
* @description JSON.parse - parsing an object where property name ends with a null character
*/
function testcase() {
var result = true;
var nullChars = new Array();
nullChars[0] = '\"\u0000\"';
nullChars[1] = '\"\u0001\"';
nullChars[2] = '\"\u0002\"';
nullChars[3] = '\"\u0003\"';
nullChars[4] = '\"\u0004\"';
nullChars[5] = '\"\u0005\"';
nullChars[6] = '\"\u0006\"';
nullChars[7] = '\"\u0007\"';
nullChars[8] = '\"\u0008\"';
nullChars[9] = '\"\u0009\"';
nullChars[10] = '\"\u000A\"';
nullChars[11] = '\"\u000B\"';
nullChars[12] = '\"\u000C\"';
nullChars[13] = '\"\u000D\"';
nullChars[14] = '\"\u000E\"';
nullChars[15] = '\"\u000F\"';
nullChars[16] = '\"\u0010\"';
nullChars[17] = '\"\u0011\"';
nullChars[18] = '\"\u0012\"';
nullChars[19] = '\"\u0013\"';
nullChars[20] = '\"\u0014\"';
nullChars[21] = '\"\u0015\"';
nullChars[22] = '\"\u0016\"';
nullChars[23] = '\"\u0017\"';
nullChars[24] = '\"\u0018\"';
nullChars[25] = '\"\u0019\"';
nullChars[26] = '\"\u001A\"';
nullChars[27] = '\"\u001B\"';
nullChars[28] = '\"\u001C\"';
nullChars[29] = '\"\u001D\"';
nullChars[30] = '\"\u001E\"';
nullChars[31] = '\"\u001F\"';
for (var index in nullChars) {
try {
var obj = JSON.parse('{' + "name" + nullChars[index] + ' : "John" } ');
result = (result && false);
} catch (e) {
result = (result && (e instanceof SyntaxError));
}
}
return result;
}
runTestCase(testcase);
| bsd-2-clause |
chewett/d3 | test/test-exports.js | 378 | var tape = require("tape"),
d3 = require("../");
module.exports = function(moduleName) {
var module = require(moduleName);
tape("d3 exports everything from " + moduleName, function(test) {
for (var symbol in module) {
if (symbol !== "version") {
test.equal(symbol in d3, true, moduleName + " export " + symbol);
}
}
test.end();
});
};
| bsd-3-clause |
eonezhang/sagan | sagan-site/src/test/java/sagan/blog/support/BlogControllerTests.java | 2906 | package sagan.blog.support;
import sagan.blog.Post;
import sagan.blog.PostMovedException;
import sagan.support.DateFactory;
import java.util.Collections;
import java.util.Locale;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.web.servlet.view.RedirectView;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.*;
public class BlogControllerTests {
@Mock
private BlogService blogService;
private BlogController blogController;
private DateFactory dateFactory = new DateFactory();
private Locale defaultLocale;
private ExtendedModelMap model = new ExtendedModelMap();
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
PageImpl<Post> page = new PageImpl<>(Collections.<Post> emptyList(), new PageRequest(1, 1), 1);
given(blogService.getPublishedPostsByDate(anyInt(), any(Pageable.class))).willReturn(page);
given(blogService.getPublishedPostsByDate(anyInt(), anyInt(), any(Pageable.class))).willReturn(page);
given(blogService.getPublishedPostsByDate(anyInt(), anyInt(), anyInt(), any(Pageable.class))).willReturn(
page);
blogController = new BlogController(blogService, dateFactory);
defaultLocale = Locale.getDefault();
Locale.setDefault(Locale.US);
}
@After
public void tearDown() {
Locale.setDefault(defaultLocale);
}
@Test
public void titleForBlogYearPage() throws Exception {
blogController.listPublishedPostsForYear(2013, 1, model);
String title = (String) model.get("title");
assertThat(title, equalTo("Archive for 2013"));
}
@Test
public void titleForBlogYearMonthPage() throws Exception {
blogController.listPublishedPostsForYearAndMonth(2013, 1, 1, model);
String title = (String) model.get("title");
assertThat(title, equalTo("Archive for January 2013"));
}
@Test
public void titleForBlogYearMonthDayPage() throws Exception {
blogController.listPublishedPostsForDate(2011, 3, 23, 1, model);
String title = (String) model.get("title");
assertThat(title, equalTo("Archive for March 23, 2011"));
}
@Test
public void handleBlogPostMovedExceptionRedirects() {
String publicSlug = "slug";
RedirectView result = blogController.handle(new PostMovedException(publicSlug));
assertThat(result.getUrl(), equalTo("/blog/" + publicSlug));
}
}
| bsd-3-clause |
Probo-Demos/drupal8 | core/modules/system/src/Tests/Form/StubForm.php | 1006 | <?php
/**
* @file
* Contains \Drupal\system\Tests\Form\StubForm.
*/
namespace Drupal\system\Tests\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides a stub form for testing purposes.
*/
class StubForm extends FormBase {
/**
* The form array.
*
* @var array
*/
protected $form;
/**
* The form ID.
*
* @var string
*/
protected $formId;
/**
* Constructs a StubForm.
*
* @param string $form_id
* The form ID.
* @param array $form
* The form array.
*/
public function __construct($form_id, $form) {
$this->formId = $form_id;
$this->form = $form;
}
/**
* {@inheritdoc}
*/
public function getFormId() {
$this->formId;
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
return $this->form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
}
}
| gpl-2.0 |
jtourt/kanboard | tests/units/Analytic/UserDistributionAnalyticTest.php | 3059 | <?php
require_once __DIR__.'/../Base.php';
use Kanboard\Model\TaskCreationModel;
use Kanboard\Model\ProjectModel;
use Kanboard\Model\ProjectUserRoleModel;
use Kanboard\Model\UserModel;
use Kanboard\Analytic\UserDistributionAnalytic;
use Kanboard\Core\Security\Role;
class UserDistributionAnalyticTest extends Base
{
public function testBuild()
{
$projectModel = new ProjectModel($this->container);
$projectUserRoleModel = new ProjectUserRoleModel($this->container);
$userModel = new UserModel($this->container);
$userDistributionModel = new UserDistributionAnalytic($this->container);
$this->assertEquals(1, $projectModel->create(array('name' => 'test1')));
$this->assertEquals(2, $projectModel->create(array('name' => 'test1')));
$this->assertEquals(2, $userModel->create(array('username' => 'user1')));
$this->assertEquals(3, $userModel->create(array('username' => 'user2')));
$this->assertEquals(4, $userModel->create(array('username' => 'user3')));
$this->assertEquals(5, $userModel->create(array('username' => 'user4')));
$this->assertTrue($projectUserRoleModel->addUser(1, 2, Role::PROJECT_MEMBER));
$this->assertTrue($projectUserRoleModel->addUser(1, 3, Role::PROJECT_MEMBER));
$this->assertTrue($projectUserRoleModel->addUser(1, 4, Role::PROJECT_MEMBER));
$this->assertTrue($projectUserRoleModel->addUser(1, 5, Role::PROJECT_MEMBER));
$this->createTasks(0, 10, 1);
$this->createTasks(2, 30, 1);
$this->createTasks(3, 40, 1);
$this->createTasks(4, 10, 1);
$this->createTasks(5, 10, 1);
$expected = array(
array(
'user' => 'Unassigned',
'nb_tasks' => 10,
'percentage' => 10.0,
),
array(
'user' => 'user1',
'nb_tasks' => 30,
'percentage' => 30.0,
),
array(
'user' => 'user2',
'nb_tasks' => 40,
'percentage' => 40.0,
),
array(
'user' => 'user3',
'nb_tasks' => 10,
'percentage' => 10.0,
),
array(
'user' => 'user4',
'nb_tasks' => 10,
'percentage' => 10.0,
)
);
$this->assertEquals($expected, $userDistributionModel->build(1));
}
private function createTasks($user_id, $nb_active, $nb_inactive)
{
$taskCreationModel = new TaskCreationModel($this->container);
for ($i = 0; $i < $nb_active; $i++) {
$this->assertNotFalse($taskCreationModel->create(array('project_id' => 1, 'title' => 'test', 'owner_id' => $user_id, 'is_active' => 1)));
}
for ($i = 0; $i < $nb_inactive; $i++) {
$this->assertNotFalse($taskCreationModel->create(array('project_id' => 1, 'title' => 'test', 'owner_id' => $user_id, 'is_active' => 0)));
}
}
}
| mit |
rajansingh10/corefx | src/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs | 172889 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// DataflowBlock.cs
//
//
// Common functionality for ITargetBlock, ISourceBlock, and IPropagatorBlock.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security;
using System.Threading.Tasks.Dataflow.Internal;
using System.Threading.Tasks.Dataflow.Internal.Threading;
namespace System.Threading.Tasks.Dataflow
{
/// <summary>
/// Provides a set of static (Shared in Visual Basic) methods for working with dataflow blocks.
/// </summary>
public static class DataflowBlock
{
#region LinkTo
/// <summary>Links the <see cref="ISourceBlock{TOutput}"/> to the specified <see cref="ITargetBlock{TOutput}"/>.</summary>
/// <param name="source">The source from which to link.</param>
/// <param name="target">The <see cref="ITargetBlock{TOutput}"/> to which to connect the source.</param>
/// <returns>An IDisposable that, upon calling Dispose, will unlink the source from the target.</returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="target"/> is null (Nothing in Visual Basic).</exception>
public static IDisposable LinkTo<TOutput>(
this ISourceBlock<TOutput> source,
ITargetBlock<TOutput> target)
{
// Validate arguments
if (source == null) throw new ArgumentNullException("source");
if (target == null) throw new ArgumentNullException("target");
Contract.EndContractBlock();
// This method exists purely to pass default DataflowLinkOptions
// to increase usability of the "90%" case.
return source.LinkTo(target, DataflowLinkOptions.Default);
}
/// <summary>Links the <see cref="ISourceBlock{TOutput}"/> to the specified <see cref="ITargetBlock{TOutput}"/> using the specified filter.</summary>
/// <param name="source">The source from which to link.</param>
/// <param name="target">The <see cref="ITargetBlock{TOutput}"/> to which to connect the source.</param>
/// <param name="predicate">The filter a message must pass in order for it to propagate from the source to the target.</param>
/// <returns>An IDisposable that, upon calling Dispose, will unlink the source from the target.</returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="target"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="predicate"/> is null (Nothing in Visual Basic).</exception>
public static IDisposable LinkTo<TOutput>(
this ISourceBlock<TOutput> source,
ITargetBlock<TOutput> target,
Predicate<TOutput> predicate)
{
// All argument validation handled by delegated method.
return LinkTo(source, target, DataflowLinkOptions.Default, predicate);
}
/// <summary>Links the <see cref="ISourceBlock{TOutput}"/> to the specified <see cref="ITargetBlock{TOutput}"/> using the specified filter.</summary>
/// <param name="source">The source from which to link.</param>
/// <param name="target">The <see cref="ITargetBlock{TOutput}"/> to which to connect the source.</param>
/// <param name="predicate">The filter a message must pass in order for it to propagate from the source to the target.</param>
/// <param name="linkOptions">The options to use to configure the link.</param>
/// <returns>An IDisposable that, upon calling Dispose, will unlink the source from the target.</returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="target"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="linkOptions"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="predicate"/> is null (Nothing in Visual Basic).</exception>
public static IDisposable LinkTo<TOutput>(
this ISourceBlock<TOutput> source,
ITargetBlock<TOutput> target,
DataflowLinkOptions linkOptions,
Predicate<TOutput> predicate)
{
// Validate arguments
if (source == null) throw new ArgumentNullException("source");
if (target == null) throw new ArgumentNullException("target");
if (linkOptions == null) throw new ArgumentNullException("linkOptions");
if (predicate == null) throw new ArgumentNullException("predicate");
Contract.EndContractBlock();
// Create the filter, which links to the real target, and then
// link the real source to this intermediate filter.
var filter = new FilteredLinkPropagator<TOutput>(source, target, predicate);
return source.LinkTo(filter, linkOptions);
}
/// <summary>Provides a synchronous filter for use in filtered LinkTos.</summary>
/// <typeparam name="T">Specifies the type of data being filtered.</typeparam>
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
[DebuggerTypeProxy(typeof(FilteredLinkPropagator<>.DebugView))]
private sealed class FilteredLinkPropagator<T> : IPropagatorBlock<T, T>, IDebuggerDisplay
{
/// <summary>The source connected with this filter.</summary>
private readonly ISourceBlock<T> _source;
/// <summary>The target with which this block is associated.</summary>
private readonly ITargetBlock<T> _target;
/// <summary>The predicate provided by the user.</summary>
private readonly Predicate<T> _userProvidedPredicate;
/// <summary>Initializes the filter passthrough.</summary>
/// <param name="source">The source connected to this filter.</param>
/// <param name="target">The target to which filtered messages should be passed.</param>
/// <param name="predicate">The predicate to run for each messsage.</param>
internal FilteredLinkPropagator(ISourceBlock<T> source, ITargetBlock<T> target, Predicate<T> predicate)
{
Contract.Requires(source != null, "Filtered link requires a source to filter on.");
Contract.Requires(target != null, "Filtered link requires a target to filter to.");
Contract.Requires(predicate != null, "Filtered link requires a predicate to filter with.");
// Store the arguments
_source = source;
_target = target;
_userProvidedPredicate = predicate;
}
/// <summary>Runs the user-provided predicate over an item in the correct execution context.</summary>
/// <param name="item">The item to evaluate.</param>
/// <returns>true if the item passed the filter; otherwise, false.</returns>
private bool RunPredicate(T item)
{
Contract.Requires(_userProvidedPredicate != null, "User-provided predicate is required.");
return _userProvidedPredicate(item); // avoid state object allocation if execution context isn't needed
}
/// <summary>Manually closes over state necessary in FilteredLinkPropagator.</summary>
private sealed class PredicateContextState
{
/// <summary>The input to be filtered.</summary>
internal readonly T Input;
/// <summary>The predicate function.</summary>
internal readonly Predicate<T> Predicate;
/// <summary>The result of the filtering operation.</summary>
internal bool Output;
/// <summary>Initializes the predicate state.</summary>
/// <param name="input">The input to be filtered.</param>
/// <param name="predicate">The predicate function.</param>
internal PredicateContextState(T input, Predicate<T> predicate)
{
Contract.Requires(predicate != null, "A predicate with which to filter is required.");
this.Input = input;
this.Predicate = predicate;
}
/// <summary>Runs the predicate function over the input and stores the result into the output.</summary>
internal void Run()
{
Contract.Requires(Predicate != null, "Non-null predicate required");
Output = Predicate(Input);
}
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' />
DataflowMessageStatus ITargetBlock<T>.OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, Boolean consumeToAccept)
{
// Validate arguments. Some targets may have a null source, but FilteredLinkPropagator
// is an internal target that should only ever have source non-null.
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader");
if (source == null) throw new ArgumentNullException("source");
Contract.EndContractBlock();
// Run the filter.
bool passedFilter = RunPredicate(messageValue);
// If the predicate matched, pass the message along to the real target.
if (passedFilter)
{
return _target.OfferMessage(messageHeader, messageValue, this, consumeToAccept);
}
// Otherwise, decline.
else return DataflowMessageStatus.Declined;
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' />
T ISourceBlock<T>.ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target, out Boolean messageConsumed)
{
// This message should have only made it to the target if it passes the filter, so we shouldn't need to check again.
// The real source will also be doing verifications, so we don't need to validate args here.
Debug.Assert(messageHeader.IsValid, "Only valid messages may be consumed.");
return _source.ConsumeMessage(messageHeader, this, out messageConsumed);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' />
bool ISourceBlock<T>.ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target)
{
// This message should have only made it to the target if it passes the filter, so we shouldn't need to check again.
// The real source will also be doing verifications, so we don't need to validate args here.
Debug.Assert(messageHeader.IsValid, "Only valid messages may be consumed.");
return _source.ReserveMessage(messageHeader, this);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' />
void ISourceBlock<T>.ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<T> target)
{
// This message should have only made it to the target if it passes the filter, so we shouldn't need to check again.
// The real source will also be doing verifications, so we don't need to validate args here.
Debug.Assert(messageHeader.IsValid, "Only valid messages may be consumed.");
_source.ReleaseReservation(messageHeader, this);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
Task IDataflowBlock.Completion { get { return _source.Completion; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' />
void IDataflowBlock.Complete() { _target.Complete(); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' />
void IDataflowBlock.Fault(Exception exception) { _target.Fault(exception); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' />
IDisposable ISourceBlock<T>.LinkTo(ITargetBlock<T> target, DataflowLinkOptions linkOptions) { throw new NotSupportedException(SR.NotSupported_MemberNotNeeded); }
/// <summary>The data to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
var displaySource = _source as IDebuggerDisplay;
var displayTarget = _target as IDebuggerDisplay;
return string.Format("{0} Source=\"{1}\", Target=\"{2}\"",
Common.GetNameForDebugger(this),
displaySource != null ? displaySource.Content : _source,
displayTarget != null ? displayTarget.Content : _target);
}
}
/// <summary>Gets the data to display in the debugger display attribute for this instance.</summary>
object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } }
/// <summary>Provides a debugger type proxy for a filter.</summary>
private sealed class DebugView
{
/// <summary>The filter.</summary>
private readonly FilteredLinkPropagator<T> _filter;
/// <summary>Initializes the debug view.</summary>
/// <param name="filter">The filter to view.</param>
public DebugView(FilteredLinkPropagator<T> filter)
{
Contract.Requires(filter != null, "Need a filter with which to construct the debug view.");
_filter = filter;
}
/// <summary>The linked target for this filter.</summary>
public ITargetBlock<T> LinkedTarget { get { return _filter._target; } }
}
}
#endregion
#region Post and SendAsync
/// <summary>Posts an item to the <see cref="T:System.Threading.Tasks.Dataflow.ITargetBlock`1"/>.</summary>
/// <typeparam name="TInput">Specifies the type of data accepted by the target block.</typeparam>
/// <param name="target">The target block.</param>
/// <param name="item">The item being offered to the target.</param>
/// <returns>true if the item was accepted by the target block; otherwise, false.</returns>
/// <remarks>
/// This method will return once the target block has decided to accept or decline the item,
/// but unless otherwise dictated by special semantics of the target block, it does not wait
/// for the item to actually be processed (for example, <see cref="T:System.Threading.Tasks.Dataflow.ActionBlock`1"/>
/// will return from Post as soon as it has stored the posted item into its input queue). From the perspective
/// of the block's processing, Post is asynchronous. For target blocks that support postponing offered messages,
/// or for blocks that may do more processing in their Post implementation, consider using
/// <see cref="T:System.Threading.Tasks.Dataflow.DataflowBlock.SendAsync">SendAsync</see>,
/// which will return immediately and will enable the target to postpone the posted message and later consume it
/// after SendAsync returns.
/// </remarks>
public static Boolean Post<TInput>(this ITargetBlock<TInput> target, TInput item)
{
if (target == null) throw new ArgumentNullException("target");
return target.OfferMessage(Common.SingleMessageHeader, item, source: null, consumeToAccept: false) == DataflowMessageStatus.Accepted;
}
/// <summary>Asynchronously offers a message to the target message block, allowing for postponement.</summary>
/// <typeparam name="TInput">Specifies the type of the data to post to the target.</typeparam>
/// <param name="target">The target to which to post the data.</param>
/// <param name="item">The item being offered to the target.</param>
/// <returns>
/// A <see cref="System.Threading.Tasks.Task{Boolean}"/> that represents the asynchronous send. If the target
/// accepts and consumes the offered element during the call to SendAsync, upon return
/// from the call the resulting <see cref="System.Threading.Tasks.Task{Boolean}"/> will be completed and its <see cref="System.Threading.Tasks.Task{Boolean}.Result">Result</see>
/// property will return true. If the target declines the offered element during the call, upon return from the call the resulting <see cref="System.Threading.Tasks.Task{Boolean}"/> will
/// be completed and its <see cref="System.Threading.Tasks.Task{Boolean}.Result">Result</see> property will return false. If the target
/// postpones the offered element, the element will be buffered until such time that the target consumes or releases it, at which
/// point the Task will complete, with its <see cref="System.Threading.Tasks.Task{Boolean}.Result"/> indicating whether the message was consumed. If the target
/// never attempts to consume or release the message, the returned task will never complete.
/// </returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="target"/> is null (Nothing in Visual Basic).</exception>
public static Task<Boolean> SendAsync<TInput>(this ITargetBlock<TInput> target, TInput item)
{
return SendAsync<TInput>(target, item, CancellationToken.None);
}
/// <summary>Asynchronously offers a message to the target message block, allowing for postponement.</summary>
/// <typeparam name="TInput">Specifies the type of the data to post to the target.</typeparam>
/// <param name="target">The target to which to post the data.</param>
/// <param name="item">The item being offered to the target.</param>
/// <param name="cancellationToken">The cancellation token with which to request cancellation of the send operation.</param>
/// <returns>
/// <para>
/// A <see cref="System.Threading.Tasks.Task{Boolean}"/> that represents the asynchronous send. If the target
/// accepts and consumes the offered element during the call to SendAsync, upon return
/// from the call the resulting <see cref="System.Threading.Tasks.Task{Boolean}"/> will be completed and its <see cref="System.Threading.Tasks.Task{Boolean}.Result">Result</see>
/// property will return true. If the target declines the offered element during the call, upon return from the call the resulting <see cref="System.Threading.Tasks.Task{Boolean}"/> will
/// be completed and its <see cref="System.Threading.Tasks.Task{Boolean}.Result">Result</see> property will return false. If the target
/// postpones the offered element, the element will be buffered until such time that the target consumes or releases it, at which
/// point the Task will complete, with its <see cref="System.Threading.Tasks.Task{Boolean}.Result"/> indicating whether the message was consumed. If the target
/// never attempts to consume or release the message, the returned task will never complete.
/// </para>
/// <para>
/// If cancellation is requested before the target has successfully consumed the sent data,
/// the returned task will complete in the Canceled state and the data will no longer be available to the target.
/// </para>
/// </returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="target"/> is null (Nothing in Visual Basic).</exception>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static Task<Boolean> SendAsync<TInput>(this ITargetBlock<TInput> target, TInput item, CancellationToken cancellationToken)
{
// Validate arguments. No validation necessary for item.
if (target == null) throw new ArgumentNullException("target");
Contract.EndContractBlock();
// Fast path check for cancellation
if (cancellationToken.IsCancellationRequested)
return Common.CreateTaskFromCancellation<Boolean>(cancellationToken);
SendAsyncSource<TInput> source;
// Fast path: try to offer the item synchronously. This first try is done
// without any form of cancellation, and thus consumeToAccept can be the better-performing "false".
try
{
switch (target.OfferMessage(Common.SingleMessageHeader, item, source: null, consumeToAccept: false))
{
// If the message is immediately accepted, return a cached completed task with a true result
case DataflowMessageStatus.Accepted:
return Common.CompletedTaskWithTrueResult;
// If the target is declining permanently, return a cached completed task with a false result
case DataflowMessageStatus.DecliningPermanently:
return Common.CompletedTaskWithFalseResult;
#if DEBUG
case DataflowMessageStatus.Postponed:
Debug.Assert(false, "A message should never be postponed when no source has been provided");
break;
case DataflowMessageStatus.NotAvailable:
Debug.Assert(false, "The message should never be missed, as it's offered to only this one target");
break;
#endif
}
// Slow path: the target did not accept the synchronous post, nor did it decline it.
// Create a source for the send, launch the offering, and return the representative task.
// This ctor attempts to register a cancellation notification which would throw if the
// underlying CTS has been disposed of. Therefore, keep it inside the try/catch block.
source = new SendAsyncSource<TInput>(target, item, cancellationToken);
}
catch (Exception exc)
{
// If the target throws from OfferMessage, return a faulted task
Common.StoreDataflowMessageValueIntoExceptionData(exc, item);
return Common.CreateTaskFromException<Boolean>(exc);
}
Debug.Assert(source != null, "The SendAsyncSource instance must have been constructed.");
source.OfferToTarget(); // synchronous to preserve message ordering
return source.Task;
}
/// <summary>
/// Provides a source used by SendAsync that will buffer a single message and signal when it's been accepted or declined.
/// </summary>
/// <remarks>This source must only be passed to a single target, and must only be used once.</remarks>
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
[DebuggerTypeProxy(typeof(SendAsyncSource<>.DebugView))]
private sealed class SendAsyncSource<TOutput> : TaskCompletionSource<Boolean>, ISourceBlock<TOutput>, IDebuggerDisplay
{
/// <summary>The target to offer to.</summary>
private readonly ITargetBlock<TOutput> _target;
/// <summary>The buffered message.</summary>
private readonly TOutput _messageValue;
/// <summary>CancellationToken used to cancel the send.</summary>
private CancellationToken _cancellationToken;
/// <summary>Registration with the cancellation token.</summary>
private CancellationTokenRegistration _cancellationRegistration;
/// <summary>The cancellation/completion state of the source.</summary>
private int _cancellationState; // one of the CANCELLATION_STATE_* constant values, defaulting to NONE
// Cancellation states:
// _cancellationState starts out as NONE, and will remain that way unless a CancellationToken
// is provided in the initial OfferToTarget call. As such, unless a token is provided,
// all synchronization related to cancellation will be avoided. Once a token is provided,
// the state transitions to REGISTERED. If cancellation then is requested or if the target
// calls back to consume the message, the state will transition to COMPLETING prior to
// actually committing the action; if it can't transition to COMPLETING, then the action doesn't
// take effect (e.g. if cancellation raced with the target consuming, such that the cancellation
// action was able to transition to COMPLETING but the consumption wasn't, then ConsumeMessage
// would return false indicating that the message could not be consumed). The only additional
// complication here is around reservations. If a target reserves a message, _cancellationState
// transitions to RESERVED. A subsequent ConsumeMessage call can successfully transition from
// RESERVED to COMPLETING, but cancellation can't; cancellation can only transition from REGISTERED
// to COMPLETING. If the reservation on the message is instead released, _cancellationState
// will transition back to REGISTERED.
/// <summary>No cancellation registration is used.</summary>
private const int CANCELLATION_STATE_NONE = 0;
/// <summary>A cancellation token has been registered.</summary>
private const int CANCELLATION_STATE_REGISTERED = 1;
/// <summary>The message has been reserved. Only used if a cancellation token is in play.</summary>
private const int CANCELLATION_STATE_RESERVED = 2;
/// <summary>Completion is now in progress. Only used if a cancellation token is in play.</summary>
private const int CANCELLATION_STATE_COMPLETING = 3;
/// <summary>Initializes the source.</summary>
/// <param name="target">The target to offer to.</param>
/// <param name="messageValue">The message to offer and buffer.</param>
/// <param name="cancellationToken">The cancellation token with which to cancel the send.</param>
internal SendAsyncSource(ITargetBlock<TOutput> target, TOutput messageValue, CancellationToken cancellationToken)
{
Contract.Requires(target != null, "A valid target to send to is required.");
_target = target;
_messageValue = messageValue;
// If a cancelable CancellationToken is used, update our cancellation state
// and register with the token. Only if CanBeCanceled is true due we want
// to pay the subsequent costs around synchronization between cancellation
// requests and the target coming back to consume the message.
if (cancellationToken.CanBeCanceled)
{
_cancellationToken = cancellationToken;
_cancellationState = CANCELLATION_STATE_REGISTERED;
try
{
_cancellationRegistration = cancellationToken.Register(
_cancellationCallback, new WeakReference<SendAsyncSource<TOutput>>(this));
}
catch
{
// Suppress finalization. Finalization is only required if the target drops a reference
// to the source before the source has completed, and we'll never offer to the target.
GC.SuppressFinalize(this);
// Propagate the exception
throw;
}
}
}
/// <summary>Finalizer that completes the returned task if all references to this source are dropped.</summary>
~SendAsyncSource()
{
// CompleteAsDeclined uses synchronization, which is dangerous for a finalizer
// during shutdown or appdomain unload.
if (!Environment.HasShutdownStarted)
{
CompleteAsDeclined(runAsync: true);
}
}
/// <summary>Completes the source in an "Accepted" state.</summary>
/// <param name="runAsync">true to accept asynchronously; false to accept synchronously.</param>
private void CompleteAsAccepted(bool runAsync)
{
RunCompletionAction(state =>
{
try { ((SendAsyncSource<TOutput>)state).TrySetResult(true); }
catch (ObjectDisposedException) { }
}, this, runAsync);
}
/// <summary>Completes the source in an "Declined" state.</summary>
/// <param name="runAsync">true to decline asynchronously; false to decline synchronously.</param>
private void CompleteAsDeclined(bool runAsync)
{
RunCompletionAction(state =>
{
// The try/catch for ObjectDisposedException handles the case where the
// user disposes of the returned task before we're done with it.
try { ((SendAsyncSource<TOutput>)state).TrySetResult(false); }
catch (ObjectDisposedException) { }
}, this, runAsync);
}
/// <summary>Completes the source in faulted state.</summary>
/// <param name="exception">The exception with which to fault.</param>
/// <param name="runAsync">true to fault asynchronously; false to fault synchronously.</param>
private void CompleteAsFaulted(Exception exception, bool runAsync)
{
RunCompletionAction(state =>
{
var tuple = (Tuple<SendAsyncSource<TOutput>, Exception>)state;
try { tuple.Item1.TrySetException(tuple.Item2); }
catch (ObjectDisposedException) { }
}, Tuple.Create<SendAsyncSource<TOutput>, Exception>(this, exception), runAsync);
}
/// <summary>Completes the source in canceled state.</summary>
/// <param name="runAsync">true to fault asynchronously; false to fault synchronously.</param>
private void CompleteAsCanceled(bool runAsync)
{
RunCompletionAction(state =>
{
try { ((SendAsyncSource<TOutput>)state).TrySetCanceled(); }
catch (ObjectDisposedException) { }
}, this, runAsync);
}
/// <summary>Executes a completion action.</summary>
/// <param name="completionAction">The action to execute, passed the state.</param>
/// <param name="completionActionState">The state to pass into the delegate.</param>
/// <param name="runAsync">true to execute the action asynchronously; false to execute it synchronously.</param>
/// <remarks>
/// async should be true if this is being called on a path that has the target on the stack, e.g.
/// the target is calling to ConsumeMessage. We don't want to block the target indefinitely
/// with any synchronous continuations off of the returned send async task.
/// </remarks>
[SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly")]
private void RunCompletionAction(Action<object> completionAction, object completionActionState, bool runAsync)
{
Contract.Requires(completionAction != null, "Completion action to run is required.");
// Suppress finalization. Finalization is only required if the target drops a reference
// to the source before the source has completed, and here we're completing the source.
GC.SuppressFinalize(this);
// Dispose of the cancellation registration if there is one
if (_cancellationState != CANCELLATION_STATE_NONE)
{
Debug.Assert(_cancellationRegistration != default(CancellationTokenRegistration),
"If we're not in NONE, we must have a cancellation token we've registered with.");
_cancellationRegistration.Dispose();
}
// If we're meant to run asynchronously, launch a task.
if (runAsync)
{
System.Threading.Tasks.Task.Factory.StartNew(
completionAction, completionActionState,
CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default);
}
// Otherwise, execute directly.
else
{
completionAction(completionActionState);
}
}
/// <summary>Offers the message to the target asynchronously.</summary>
private void OfferToTargetAsync()
{
System.Threading.Tasks.Task.Factory.StartNew(
state => ((SendAsyncSource<TOutput>)state).OfferToTarget(), this,
CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default);
}
/// <summary>Cached delegate used to cancel a send in response to a cancellation request.</summary>
private readonly static Action<object> _cancellationCallback = CancellationHandler;
/// <summary>Attempts to cancel the source passed as state in response to a cancellation request.</summary>
/// <param name="state">
/// A weak reference to the SendAsyncSource. A weak reference is used to prevent the source
/// from being rooted in a long-lived token.
/// </param>
private static void CancellationHandler(object state)
{
SendAsyncSource<TOutput> source = Common.UnwrapWeakReference<SendAsyncSource<TOutput>>(state);
if (source != null)
{
Debug.Assert(source._cancellationState != CANCELLATION_STATE_NONE,
"If cancellation is in play, we must have already moved out of the NONE state.");
// Try to reserve completion, and if we can, complete as canceled. Note that we can only
// achieve cancellation when in the REGISTERED state, and not when in the RESERVED state,
// as if a target has reserved the message, we must allow the message to be consumed successfully.
if (source._cancellationState == CANCELLATION_STATE_REGISTERED && // fast check to avoid the interlocked if we can
Interlocked.CompareExchange(ref source._cancellationState, CANCELLATION_STATE_COMPLETING, CANCELLATION_STATE_REGISTERED) == CANCELLATION_STATE_REGISTERED)
{
// We've reserved completion, so proceed to cancel the task.
source.CompleteAsCanceled(true);
}
}
}
/// <summary>Offers the message to the target synchronously.</summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal void OfferToTarget()
{
try
{
// Offer the message to the target. If there's no cancellation in play, we can just allow the target
// to accept the message directly. But if a CancellationToken is in use, the target needs to come
// back to us to get the data; that way, we can ensure we don't race between returning a canceled task but
// successfully completing the send.
bool consumeToAccept = _cancellationState != CANCELLATION_STATE_NONE;
switch (_target.OfferMessage(
Common.SingleMessageHeader, _messageValue, this, consumeToAccept: consumeToAccept))
{
// If the message is immediately accepted, complete the task as accepted
case DataflowMessageStatus.Accepted:
if (!consumeToAccept)
{
// Cancellation wasn't in use, and the target accepted the message directly,
// so complete the task as accepted.
CompleteAsAccepted(runAsync: false);
}
else
{
// If cancellation is in use, then since the target accepted,
// our state better reflect that we're completing.
Debug.Assert(_cancellationState == CANCELLATION_STATE_COMPLETING,
"The message was accepted, so we should have started completion.");
}
break;
// If the message is immediately declined, complete the task as declined
case DataflowMessageStatus.Declined:
case DataflowMessageStatus.DecliningPermanently:
CompleteAsDeclined(runAsync: false);
break;
#if DEBUG
case DataflowMessageStatus.NotAvailable:
Debug.Assert(false, "The message should never be missed, as it's offered to only this one target");
break;
// If the message was postponed, the source may or may not be complete yet. Nothing to validate.
// Treat an improper DataflowMessageStatus as postponed and do nothing.
#endif
}
}
// A faulty target might throw from OfferMessage. If that happens,
// we'll try to fault the returned task. A really faulty target might
// both throw from OfferMessage and call ConsumeMessage,
// in which case it's possible we might not be able to propagate the exception
// out to the caller through the task if ConsumeMessage wins the race,
// which is likely if the exception doesn't occur until after ConsumeMessage is
// called. If that happens, we just eat the exception.
catch (Exception exc)
{
Common.StoreDataflowMessageValueIntoExceptionData(exc, _messageValue);
CompleteAsFaulted(exc, runAsync: false);
}
}
/// <summary>Called by the target to consume the buffered message.</summary>
TOutput ISourceBlock<TOutput>.ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target, out Boolean messageConsumed)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader");
if (target == null) throw new ArgumentNullException("target");
Contract.EndContractBlock();
// If the task has already completed, there's nothing to consume. This could happen if
// cancellation was already requested and completed the task as a result.
if (Task.IsCompleted)
{
messageConsumed = false;
return default(TOutput);
}
// If the message being asked for is not the same as the one that's buffered,
// something is wrong. Complete as having failed to transfer the message.
bool validMessage = (messageHeader.Id == Common.SINGLE_MESSAGE_ID);
if (validMessage)
{
int curState = _cancellationState;
Debug.Assert(
curState == CANCELLATION_STATE_NONE || curState == CANCELLATION_STATE_REGISTERED ||
curState == CANCELLATION_STATE_RESERVED || curState == CANCELLATION_STATE_COMPLETING,
"The current cancellation state is not valid.");
// If we're not dealing with cancellation, then if we're currently registered or reserved, try to transition
// to completing. If we're able to, allow the message to be consumed, and we're done. At this point, we
// support transitioning out of REGISTERED or RESERVED.
if (curState == CANCELLATION_STATE_NONE || // no synchronization necessary if there's no cancellation
(curState != CANCELLATION_STATE_COMPLETING && // fast check to avoid unnecessary synchronization
Interlocked.CompareExchange(ref _cancellationState, CANCELLATION_STATE_COMPLETING, curState) == curState))
{
CompleteAsAccepted(runAsync: true);
messageConsumed = true;
return _messageValue;
}
}
// Consumption failed
messageConsumed = false;
return default(TOutput);
}
/// <summary>Called by the target to reserve the buffered message.</summary>
bool ISourceBlock<TOutput>.ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader");
if (target == null) throw new ArgumentNullException("target");
Contract.EndContractBlock();
// If the task has already completed, such as due to cancellation, there's nothing to reserve.
if (Task.IsCompleted) return false;
// As long as the message is the one being requested and cancellation hasn't been requested, allow it to be reserved.
bool reservable = (messageHeader.Id == Common.SINGLE_MESSAGE_ID);
return reservable &&
(_cancellationState == CANCELLATION_STATE_NONE || // avoid synchronization when cancellation is not in play
Interlocked.CompareExchange(ref _cancellationState, CANCELLATION_STATE_RESERVED, CANCELLATION_STATE_REGISTERED) == CANCELLATION_STATE_REGISTERED);
}
/// <summary>Called by the target to release a reservation on the buffered message.</summary>
void ISourceBlock<TOutput>.ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader");
if (target == null) throw new ArgumentNullException("target");
Contract.EndContractBlock();
// If this is not the message we posted, bail
if (messageHeader.Id != Common.SINGLE_MESSAGE_ID)
throw new InvalidOperationException(SR.InvalidOperation_MessageNotReservedByTarget);
// If the task has already completed, there's nothing to release.
if (Task.IsCompleted) return;
// If a cancellation token is being used, revert our state back to registered. In the meantime
// cancellation could have been requested, so check to see now if cancellation was requested
// and process it if it was.
if (_cancellationState != CANCELLATION_STATE_NONE)
{
if (Interlocked.CompareExchange(ref _cancellationState, CANCELLATION_STATE_REGISTERED, CANCELLATION_STATE_RESERVED) != CANCELLATION_STATE_RESERVED)
throw new InvalidOperationException(SR.InvalidOperation_MessageNotReservedByTarget);
if (_cancellationToken.IsCancellationRequested)
CancellationHandler(new WeakReference<SendAsyncSource<TOutput>>(this)); // same code as registered with the CancellationToken
}
// Start the process over by reoffering the message asynchronously.
OfferToTargetAsync();
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
Task IDataflowBlock.Completion { get { return Task; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' />
IDisposable ISourceBlock<TOutput>.LinkTo(ITargetBlock<TOutput> target, DataflowLinkOptions linkOptions) { throw new NotSupportedException(SR.NotSupported_MemberNotNeeded); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' />
void IDataflowBlock.Complete() { throw new NotSupportedException(SR.NotSupported_MemberNotNeeded); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' />
void IDataflowBlock.Fault(Exception exception) { throw new NotSupportedException(SR.NotSupported_MemberNotNeeded); }
/// <summary>The data to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
var displayTarget = _target as IDebuggerDisplay;
return string.Format("{0} Message={1}, Target=\"{2}\"",
Common.GetNameForDebugger(this),
_messageValue,
displayTarget != null ? displayTarget.Content : _target);
}
}
/// <summary>Gets the data to display in the debugger display attribute for this instance.</summary>
object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } }
/// <summary>Provides a debugger type proxy for the source.</summary>
private sealed class DebugView
{
/// <summary>The source.</summary>
private readonly SendAsyncSource<TOutput> _source;
/// <summary>Initializes the debug view.</summary>
/// <param name="source">The source to view.</param>
public DebugView(SendAsyncSource<TOutput> source)
{
Contract.Requires(source != null, "Need a source with which to construct the debug view.");
_source = source;
}
/// <summary>The target to which we're linked.</summary>
public ITargetBlock<TOutput> Target { get { return _source._target; } }
/// <summary>The message buffered by the source.</summary>
public TOutput Message { get { return _source._messageValue; } }
/// <summary>The Task represented the posting of the message.</summary>
public Task<bool> Completion { get { return _source.Task; } }
}
}
#endregion
#region TryReceive, ReceiveAsync, and Receive
#region TryReceive
/// <summary>
/// Attempts to synchronously receive an item from the <see cref="T:System.Threading.Tasks.Dataflow.ISourceBlock`1"/>.
/// </summary>
/// <param name="source">The source from which to receive.</param>
/// <param name="item">The item received from the source.</param>
/// <returns>true if an item could be received; otherwise, false.</returns>
/// <remarks>
/// This method does not wait until the source has an item to provide.
/// It will return whether or not an element was available.
/// </remarks>
public static bool TryReceive<TOutput>(this IReceivableSourceBlock<TOutput> source, out TOutput item)
{
if (source == null) throw new ArgumentNullException("source");
Contract.EndContractBlock();
return source.TryReceive(null, out item);
}
#endregion
#region ReceiveAsync
/// <summary>Asynchronously receives a value from the specified source.</summary>
/// <typeparam name="TOutput">Specifies the type of data contained in the source.</typeparam>
/// <param name="source">The source from which to asynchronously receive.</param>
/// <returns>
/// A <see cref="System.Threading.Tasks.Task{TOutput}"/> that represents the asynchronous receive operation. When an item is successfully received from the source,
/// the returned task will be completed and its <see cref="System.Threading.Tasks.Task{TOutput}.Result">Result</see> will return the received item. If an item cannot be retrieved,
/// because the source is empty and completed, the returned task will be canceled.
/// </returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source"/> is null (Nothing in Visual Basic).</exception>
public static Task<TOutput> ReceiveAsync<TOutput>(
this ISourceBlock<TOutput> source)
{
// Argument validation handled by target method
return ReceiveAsync(source, Common.InfiniteTimeSpan, CancellationToken.None);
}
/// <summary>Asynchronously receives a value from the specified source.</summary>
/// <typeparam name="TOutput">Specifies the type of data contained in the source.</typeparam>
/// <param name="source">The source from which to asynchronously receive.</param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> which may be used to cancel the receive operation.</param>
/// <returns>
/// A <see cref="System.Threading.Tasks.Task{TOutput}"/> that represents the asynchronous receive operation. When an item is successfully received from the source,
/// the returned task will be completed and its <see cref="System.Threading.Tasks.Task{TOutput}.Result">Result</see> will return the received item. If an item cannot be retrieved,
/// either because cancellation is requested or the source is empty and completed, the returned task will be canceled.
/// </returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source"/> is null (Nothing in Visual Basic).</exception>
public static Task<TOutput> ReceiveAsync<TOutput>(
this ISourceBlock<TOutput> source, CancellationToken cancellationToken)
{
// Argument validation handled by target method
return ReceiveAsync(source, Common.InfiniteTimeSpan, cancellationToken);
}
/// <summary>Asynchronously receives a value from the specified source.</summary>
/// <typeparam name="TOutput">Specifies the type of data contained in the source.</typeparam>
/// <param name="source">The source from which to asynchronously receive.</param>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely.</param>
/// <returns>
/// A <see cref="System.Threading.Tasks.Task{TOutput}"/> that represents the asynchronous receive operation. When an item is successfully received from the source,
/// the returned task will be completed and its <see cref="System.Threading.Tasks.Task{TOutput}.Result">Result</see> will return the received item. If an item cannot be retrieved,
/// either because the timeout expires or the source is empty and completed, the returned task will be canceled.
/// </returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// timeout is a negative number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than <see cref="System.Int32.MaxValue"/>.
/// </exception>
public static Task<TOutput> ReceiveAsync<TOutput>(
this ISourceBlock<TOutput> source, TimeSpan timeout)
{
// Argument validation handled by target method
return ReceiveAsync(source, timeout, CancellationToken.None);
}
/// <summary>Asynchronously receives a value from the specified source.</summary>
/// <typeparam name="TOutput">Specifies the type of data contained in the source.</typeparam>
/// <param name="source">The source from which to asynchronously receive.</param>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> which may be used to cancel the receive operation.</param>
/// <returns>
/// A <see cref="System.Threading.Tasks.Task{TOutput}"/> that represents the asynchronous receive operation. When an item is successfully received from the source,
/// the returned task will be completed and its <see cref="System.Threading.Tasks.Task{TOutput}.Result">Result</see> will return the received item. If an item cannot be retrieved,
/// either because the timeout expires, cancellation is requested, or the source is empty and completed, the returned task will be canceled.
/// </returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// timeout is a negative number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than <see cref="System.Int32.MaxValue"/>.
/// </exception>
public static Task<TOutput> ReceiveAsync<TOutput>(
this ISourceBlock<TOutput> source, TimeSpan timeout, CancellationToken cancellationToken)
{
// Validate arguments
if (source == null) throw new ArgumentNullException("source");
if (!Common.IsValidTimeout(timeout)) throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
// Return the task representing the core receive operation
return ReceiveCore(source, true, timeout, cancellationToken);
}
#endregion
#region Receive
/// <summary>Synchronously receives an item from the source.</summary>
/// <typeparam name="TOutput">Specifies the type of data contained in the source.</typeparam>
/// <param name="source">The source from which to receive.</param>
/// <returns>The received item.</returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">No item could be received from the source.</exception>
public static TOutput Receive<TOutput>(
this ISourceBlock<TOutput> source)
{
// Argument validation handled by target method
return Receive(source, Common.InfiniteTimeSpan, CancellationToken.None);
}
/// <summary>Synchronously receives an item from the source.</summary>
/// <typeparam name="TOutput">Specifies the type of data contained in the source.</typeparam>
/// <param name="source">The source from which to receive.</param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> which may be used to cancel the receive operation.</param>
/// <returns>The received item.</returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">No item could be received from the source.</exception>
/// <exception cref="System.OperationCanceledException">The operation was canceled before an item was received from the source.</exception>
/// <remarks>
/// If the source successfully offered an item that was received by this operation, it will be returned, even if a concurrent cancellation request occurs.
/// </remarks>
public static TOutput Receive<TOutput>(
this ISourceBlock<TOutput> source, CancellationToken cancellationToken)
{
// Argument validation handled by target method
return Receive(source, Common.InfiniteTimeSpan, cancellationToken);
}
/// <summary>Synchronously receives an item from the source.</summary>
/// <typeparam name="TOutput">Specifies the type of data contained in the source.</typeparam>
/// <param name="source">The source from which to receive.</param>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely.</param>
/// <returns>The received item.</returns>
/// <exception cref="System.ArgumentOutOfRangeException">
/// timeout is a negative number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than <see cref="System.Int32.MaxValue"/>.
/// </exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="source"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">No item could be received from the source.</exception>
/// <exception cref="System.TimeoutException">The specified timeout expired before an item was received from the source.</exception>
/// <remarks>
/// If the source successfully offered an item that was received by this operation, it will be returned, even if a concurrent timeout occurs.
/// </remarks>
public static TOutput Receive<TOutput>(
this ISourceBlock<TOutput> source, TimeSpan timeout)
{
// Argument validation handled by target method
return Receive(source, timeout, CancellationToken.None);
}
/// <summary>Synchronously receives an item from the source.</summary>
/// <typeparam name="TOutput">Specifies the type of data contained in the source.</typeparam>
/// <param name="source">The source from which to receive.</param>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> which may be used to cancel the receive operation.</param>
/// <returns>The received item.</returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// timeout is a negative number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than <see cref="System.Int32.MaxValue"/>.
/// </exception>
/// <exception cref="System.InvalidOperationException">No item could be received from the source.</exception>
/// <exception cref="System.TimeoutException">The specified timeout expired before an item was received from the source.</exception>
/// <exception cref="System.OperationCanceledException">The operation was canceled before an item was received from the source.</exception>
/// <remarks>
/// If the source successfully offered an item that was received by this operation, it will be returned, even if a concurrent timeout or cancellation request occurs.
/// </remarks>
[SuppressMessage("Microsoft.Usage", "CA2200:RethrowToPreserveStackDetails")]
public static TOutput Receive<TOutput>(
this ISourceBlock<TOutput> source, TimeSpan timeout, CancellationToken cancellationToken)
{
// Validate arguments
if (source == null) throw new ArgumentNullException("source");
if (!Common.IsValidTimeout(timeout)) throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
// Do fast path checks for both cancellation and data already existing.
cancellationToken.ThrowIfCancellationRequested();
TOutput fastCheckedItem;
var receivableSource = source as IReceivableSourceBlock<TOutput>;
if (receivableSource != null && receivableSource.TryReceive(null, out fastCheckedItem))
{
return fastCheckedItem;
}
// Get a TCS to represent the receive operation and wait for it to complete.
// If it completes successfully, return the result. Otherwise, throw the
// original inner exception representing the cause. This could be an OCE.
Task<TOutput> task = ReceiveCore(source, false, timeout, cancellationToken);
try
{
return task.GetAwaiter().GetResult(); // block until the result is available
}
catch
{
// Special case cancellation in order to ensure the exception contains the token.
// The public TrySetCanceled, used by ReceiveCore, is parameterless and doesn't
// accept the token to use. Thus the exception that we're catching here
// won't contain the cancellation token we want propagated.
if (task.IsCanceled) cancellationToken.ThrowIfCancellationRequested();
// If we get here, propagate the original exception.
throw;
}
}
#endregion
#region Shared by Receive and ReceiveAsync
/// <summary>Receives an item from the source.</summary>
/// <typeparam name="TOutput">Specifies the type of data contained in the source.</typeparam>
/// <param name="source">The source from which to receive.</param>
/// <param name="attemptTryReceive">Whether to first attempt using TryReceive to get a value from the source.</param>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> which may be used to cancel the receive operation.</param>
/// <returns>A Task for the receive operation.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static Task<TOutput> ReceiveCore<TOutput>(
this ISourceBlock<TOutput> source, bool attemptTryReceive, TimeSpan timeout, CancellationToken cancellationToken)
{
Contract.Requires(source != null, "Need a source from which to receive.");
// If cancellation has been requested, we're done before we've even started, cancel this receive.
if (cancellationToken.IsCancellationRequested)
{
return Common.CreateTaskFromCancellation<TOutput>(cancellationToken);
}
if (attemptTryReceive)
{
// If we're able to directly and immediately receive an item, use that item to complete the receive.
var receivableSource = source as IReceivableSourceBlock<TOutput>;
if (receivableSource != null)
{
try
{
TOutput fastCheckedItem;
if (receivableSource.TryReceive(null, out fastCheckedItem))
{
return Task.FromResult<TOutput>(fastCheckedItem);
}
}
catch (Exception exc)
{
return Common.CreateTaskFromException<TOutput>(exc);
}
}
}
int millisecondsTimeout = (int)timeout.TotalMilliseconds;
if (millisecondsTimeout == 0)
{
return Common.CreateTaskFromException<TOutput>(ReceiveTarget<TOutput>.CreateExceptionForTimeout());
}
return ReceiveCoreByLinking<TOutput>(source, millisecondsTimeout, cancellationToken);
}
/// <summary>The reason for a ReceiveCoreByLinking call failing.</summary>
private enum ReceiveCoreByLinkingCleanupReason
{
/// <summary>The Receive operation completed successfully, obtaining a value from the source.</summary>
Success = 0,
/// <summary>The timer expired before a value could be received.</summary>
Timer = 1,
/// <summary>The cancellation token had cancellation requested before a value could be received.</summary>
Cancellation = 2,
/// <summary>The source completed before a value could be received.</summary>
SourceCompletion = 3,
/// <summary>An error occurred while linking up the target.</summary>
SourceProtocolError = 4,
/// <summary>An error during cleanup after completion for another reason.</summary>
ErrorDuringCleanup = 5
}
/// <summary>Cancels a CancellationTokenSource passed as the object state argument.</summary>
private static readonly Action<object> _cancelCts = state => ((CancellationTokenSource)state).Cancel();
/// <summary>Receives an item from the source by linking a temporary target from it.</summary>
/// <typeparam name="TOutput">Specifies the type of data contained in the source.</typeparam>
/// <param name="source">The source from which to receive.</param>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or -1 to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> which may be used to cancel the receive operation.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static Task<TOutput> ReceiveCoreByLinking<TOutput>(ISourceBlock<TOutput> source, int millisecondsTimeout, CancellationToken cancellationToken)
{
// Create a target to link from the source
var target = new ReceiveTarget<TOutput>();
// Keep cancellation registrations inside the try/catch in case the underlying CTS is disposed in which case an exception is thrown
try
{
// Create a cancellation token that will be canceled when either the provided token
// is canceled or the source block completes.
if (cancellationToken.CanBeCanceled)
{
target._externalCancellationToken = cancellationToken;
target._regFromExternalCancellationToken = cancellationToken.Register(_cancelCts, target._cts);
}
// We need to cleanup if one of a few things happens:
// - The target completes successfully due to receiving data.
// - The user-specified timeout occurs, such that we should bail on the receive.
// - The cancellation token has cancellation requested, such that we should bail on the receive.
// - The source completes, since it won't send any more data.
// Note that there's a potential race here, in that the cleanup delegate could be executed
// from the timer before the timer variable is set, but that's ok, because then timer variable
// will just show up as null in the cleanup and there will be nothing to dispose (nor will anything
// need to be disposed, since it's the timer that fired. Timer.Dispose is also thread-safe to be
// called multiple times concurrently.)
if (millisecondsTimeout > 0)
{
target._timer = new Timer(
ReceiveTarget<TOutput>.CachedLinkingTimerCallback, target,
millisecondsTimeout, Timeout.Infinite);
}
if (target._cts.Token.CanBeCanceled)
{
target._cts.Token.Register(
ReceiveTarget<TOutput>.CachedLinkingCancellationCallback, target); // we don't have to cleanup this registration, as this cts is short-lived
}
// Link the target to the source
IDisposable unlink = source.LinkTo(target, DataflowLinkOptions.UnlinkAfterOneAndPropagateCompletion);
target._unlink = unlink;
// If completion has started, there is a chance it started after we linked.
// In that case, we must dispose of the unlinker.
// If completion started before we linked, the cleanup code will try to unlink.
// So we are racing to dispose of the unlinker.
if (Volatile.Read(ref target._cleanupReserved))
{
IDisposable disposableUnlink = Interlocked.CompareExchange(ref target._unlink, null, unlink);
if (disposableUnlink != null) disposableUnlink.Dispose();
}
}
catch (Exception exception)
{
target._receivedException = exception;
target.TryCleanupAndComplete(ReceiveCoreByLinkingCleanupReason.SourceProtocolError);
// If we lose the race here, we may end up eating this exception.
}
return target.Task;
}
/// <summary>Provides a TaskCompletionSource that is also a dataflow target for use in ReceiveCore.</summary>
/// <typeparam name="T">Specifies the type of data offered to the target.</typeparam>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
private sealed class ReceiveTarget<T> : TaskCompletionSource<T>, ITargetBlock<T>, IDebuggerDisplay
{
/// <summary>Cached delegate used in ReceiveCoreByLinking on the created timer. Passed the ReceiveTarget as the argument.</summary>
/// <remarks>The C# compiler will not cache this delegate by default due to it being a generic method on a non-generic class.</remarks>
internal readonly static TimerCallback CachedLinkingTimerCallback = state =>
{
var receiveTarget = (ReceiveTarget<T>)state;
receiveTarget.TryCleanupAndComplete(ReceiveCoreByLinkingCleanupReason.Timer);
};
/// <summary>Cached delegate used in ReceiveCoreByLinking on the cancellation token. Passed the ReceiveTarget as the state argument.</summary>
/// <remarks>The C# compiler will not cache this delegate by default due to it being a generic method on a non-generic class.</remarks>
internal readonly static Action<object> CachedLinkingCancellationCallback = state =>
{
var receiveTarget = (ReceiveTarget<T>)state;
receiveTarget.TryCleanupAndComplete(ReceiveCoreByLinkingCleanupReason.Cancellation);
};
/// <summary>The received value if we accepted a value from the source.</summary>
private T _receivedValue;
/// <summary>The cancellation token source representing both external and internal cancellation.</summary>
internal readonly CancellationTokenSource _cts = new CancellationTokenSource();
/// <summary>Indicates a code path is already on route to complete the target. 0 is false, 1 is true.</summary>
internal bool _cleanupReserved; // must only be accessed under IncomingLock
/// <summary>The external token that cancels the internal token.</summary>
internal CancellationToken _externalCancellationToken;
/// <summary>The registration on the external token that cancels the internal token.</summary>
internal CancellationTokenRegistration _regFromExternalCancellationToken;
/// <summary>The timer that fires when the timeout has been exceeded.</summary>
internal Timer _timer;
/// <summary>The unlinker from removing this target from the source from which we're receiving.</summary>
internal IDisposable _unlink;
/// <summary>The received exception if an error occurred.</summary>
internal Exception _receivedException;
/// <summary>Gets the sync obj used to synchronize all activity on this target.</summary>
internal object IncomingLock { get { return _cts; } }
/// <summary>Initializes the target.</summary>
internal ReceiveTarget() { }
/// <summary>Offers a message to be used to complete the TaskCompletionSource.</summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
DataflowMessageStatus ITargetBlock<T>.OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, Boolean consumeToAccept)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader");
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, "consumeToAccept");
Contract.EndContractBlock();
DataflowMessageStatus status = DataflowMessageStatus.NotAvailable;
// If we're already one our way to being done, don't accept anything.
// This is a fast-path check prior to taking the incoming lock;
// _cleanupReserved only ever goes from false to true.
if (Volatile.Read(ref _cleanupReserved)) return DataflowMessageStatus.DecliningPermanently;
lock (IncomingLock)
{
// Check again now that we've taken the lock
if (_cleanupReserved) return DataflowMessageStatus.DecliningPermanently;
try
{
// Accept the message if possible and complete this task with the message's value.
bool consumed = true;
T acceptedValue = consumeToAccept ? source.ConsumeMessage(messageHeader, this, out consumed) : messageValue;
if (consumed)
{
status = DataflowMessageStatus.Accepted;
_receivedValue = acceptedValue;
_cleanupReserved = true;
}
}
catch (Exception exc)
{
// An error occurred. Take ourselves out of the game.
status = DataflowMessageStatus.DecliningPermanently;
Common.StoreDataflowMessageValueIntoExceptionData(exc, messageValue);
_receivedException = exc;
_cleanupReserved = true;
}
}
// Do any cleanup outside of the lock. The right to cleanup was reserved above for these cases.
if (status == DataflowMessageStatus.Accepted)
{
CleanupAndComplete(ReceiveCoreByLinkingCleanupReason.Success);
}
else if (status == DataflowMessageStatus.DecliningPermanently) // should only be the case if an error occurred
{
CleanupAndComplete(ReceiveCoreByLinkingCleanupReason.SourceProtocolError);
}
return status;
}
/// <summary>
/// Attempts to reserve the right to cleanup and complete, and if successfully,
/// continues to cleanup and complete.
/// </summary>
/// <param name="reason">The reason we're completing and cleaning up.</param>
/// <returns>true if successful in completing; otherwise, false.</returns>
internal bool TryCleanupAndComplete(ReceiveCoreByLinkingCleanupReason reason)
{
// If cleanup was already reserved, bail.
if (Volatile.Read(ref _cleanupReserved)) return false;
// Atomically using IncomingLock try to reserve the completion routine.
lock (IncomingLock)
{
if (_cleanupReserved) return false;
_cleanupReserved = true;
}
// We've reserved cleanup and completion, so do it.
CleanupAndComplete(reason);
return true;
}
/// <summary>Cleans up the target for completion.</summary>
/// <param name="reason">The reason we're completing and cleaning up.</param>
/// <remarks>This method must only be called once on this instance.</remarks>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
private void CleanupAndComplete(ReceiveCoreByLinkingCleanupReason reason)
{
Common.ContractAssertMonitorStatus(IncomingLock, held: false);
Debug.Assert(Volatile.Read(ref _cleanupReserved), "Should only be called once by whomever reserved the right.");
// Unlink from the source. If we're cleaning up because the source
// completed, this is unnecessary, as the source should have already
// emptied out its target registry, or at least be in the process of doing so.
// We are racing with the linking code - only one can dispose of the unlinker.
IDisposable unlink = _unlink;
if (reason != ReceiveCoreByLinkingCleanupReason.SourceCompletion && unlink != null)
{
IDisposable disposableUnlink = Interlocked.CompareExchange(ref _unlink, null, unlink);
if (disposableUnlink != null)
{
// If an error occurs, fault the target and override the reason to
// continue executing, i.e. do the remaining cleanup without completing
// the target the way we originally intended to.
try
{
disposableUnlink.Dispose(); // must not be holding IncomingLock, or could deadlock
}
catch (Exception exc)
{
_receivedException = exc;
reason = ReceiveCoreByLinkingCleanupReason.SourceProtocolError;
}
}
}
// Cleanup the timer. (Even if we're here because of the timer firing, we still
// want to aggressively dispose of the timer.)
if (_timer != null) _timer.Dispose();
// Cancel the token everyone is listening to. We also want to unlink
// from the user-provided cancellation token to prevent a leak.
// We do *not* dispose of the cts itself here, as there could be a race
// with the code registering this cleanup delegate with cts; not disposing
// is ok, though, because there's no resources created by the CTS
// that needs to be cleaned up since we're not using the wait handle.
// This is also why we don't use CreateLinkedTokenSource, as that combines
// both disposing of the token source and disposal of the connection link
// into a single dispose operation.
// if we're here because of cancellation, no need to cancel again
if (reason != ReceiveCoreByLinkingCleanupReason.Cancellation)
{
// if the source complete without receiving a value, we check the cancellation one more time
if (reason == ReceiveCoreByLinkingCleanupReason.SourceCompletion &&
(_externalCancellationToken.IsCancellationRequested || _cts.IsCancellationRequested))
{
reason = ReceiveCoreByLinkingCleanupReason.Cancellation;
}
_cts.Cancel();
}
_regFromExternalCancellationToken.Dispose();
// No need to dispose of the cts, either, as we're not accessing its WaitHandle
// nor was it created as a linked token source. Disposing it could also be dangerous
// if other code tries to access it after we dispose of it... best to leave it available.
// Complete the task based on the reason
switch (reason)
{
// Task final state: RanToCompletion
case ReceiveCoreByLinkingCleanupReason.Success:
System.Threading.Tasks.Task.Factory.StartNew(state =>
{
// Complete with the received value
var target = (ReceiveTarget<T>)state;
try { target.TrySetResult(target._receivedValue); }
catch (ObjectDisposedException) { /* benign race if returned task is already disposed */ }
}, this, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
break;
// Task final state: Canceled
case ReceiveCoreByLinkingCleanupReason.Cancellation:
System.Threading.Tasks.Task.Factory.StartNew(state =>
{
// Complete as canceled
var target = (ReceiveTarget<T>)state;
try { target.TrySetCanceled(); }
catch (ObjectDisposedException) { /* benign race if returned task is already disposed */ }
}, this, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
break;
default:
Debug.Assert(false, "Invalid linking cleanup reason specified.");
goto case ReceiveCoreByLinkingCleanupReason.Cancellation;
// Task final state: Faulted
case ReceiveCoreByLinkingCleanupReason.SourceCompletion:
if (_receivedException == null) _receivedException = CreateExceptionForSourceCompletion();
goto case ReceiveCoreByLinkingCleanupReason.SourceProtocolError;
case ReceiveCoreByLinkingCleanupReason.Timer:
if (_receivedException == null) _receivedException = CreateExceptionForTimeout();
goto case ReceiveCoreByLinkingCleanupReason.SourceProtocolError;
case ReceiveCoreByLinkingCleanupReason.SourceProtocolError:
case ReceiveCoreByLinkingCleanupReason.ErrorDuringCleanup:
Debug.Assert(_receivedException != null, "We need an exception with which to fault the task.");
System.Threading.Tasks.Task.Factory.StartNew(state =>
{
// Complete with the received exception
var target = (ReceiveTarget<T>)state;
try { target.TrySetException(target._receivedException ?? new Exception()); }
catch (ObjectDisposedException) { /* benign race if returned task is already disposed */ }
}, this, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
break;
}
}
/// <summary>Creates an exception to use when a source completed before receiving a value.</summary>
/// <returns>The initialized exception.</returns>
internal static Exception CreateExceptionForSourceCompletion()
{
return Common.InitializeStackTrace(new InvalidOperationException(SR.InvalidOperation_DataNotAvailableForReceive));
}
/// <summary>Creates an exception to use when a timeout occurs before receiving a value.</summary>
/// <returns>The initialized exception.</returns>
internal static Exception CreateExceptionForTimeout()
{
return Common.InitializeStackTrace(new TimeoutException());
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' />
void IDataflowBlock.Complete()
{
TryCleanupAndComplete(ReceiveCoreByLinkingCleanupReason.SourceCompletion);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' />
void IDataflowBlock.Fault(Exception exception) { ((IDataflowBlock)this).Complete(); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
Task IDataflowBlock.Completion { get { throw new NotSupportedException(SR.NotSupported_MemberNotNeeded); } }
/// <summary>The data to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
return string.Format("{0} IsCompleted={1}",
Common.GetNameForDebugger(this), base.Task.IsCompleted);
}
}
/// <summary>Gets the data to display in the debugger display attribute for this instance.</summary>
object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } }
}
#endregion
#endregion
#region OutputAvailableAsync
/// <summary>
/// Provides a <see cref="System.Threading.Tasks.Task{TResult}"/>
/// that asynchronously monitors the source for available output.
/// </summary>
/// <typeparam name="TOutput">Specifies the type of data contained in the source.</typeparam>
/// <param name="source">The source to monitor.</param>
/// <returns>
/// A <see cref="System.Threading.Tasks.Task{Boolean}"/> that informs of whether and when
/// more output is available. When the task completes, if its <see cref="System.Threading.Tasks.Task{Boolean}.Result"/> is true, more output
/// is available in the source (though another consumer of the source may retrieve the data).
/// If it returns false, more output is not and will never be available, due to the source
/// completing prior to output being available.
/// </returns>
public static Task<bool> OutputAvailableAsync<TOutput>(this ISourceBlock<TOutput> source)
{
return OutputAvailableAsync<TOutput>(source, CancellationToken.None);
}
/// <summary>
/// Provides a <see cref="System.Threading.Tasks.Task{TResult}"/>
/// that asynchronously monitors the source for available output.
/// </summary>
/// <typeparam name="TOutput">Specifies the type of data contained in the source.</typeparam>
/// <param name="source">The source to monitor.</param>
/// <param name="cancellationToken">The cancellation token with which to cancel the asynchronous operation.</param>
/// <returns>
/// A <see cref="System.Threading.Tasks.Task{Boolean}"/> that informs of whether and when
/// more output is available. When the task completes, if its <see cref="System.Threading.Tasks.Task{Boolean}.Result"/> is true, more output
/// is available in the source (though another consumer of the source may retrieve the data).
/// If it returns false, more output is not and will never be available, due to the source
/// completing prior to output being available.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
public static Task<bool> OutputAvailableAsync<TOutput>(
this ISourceBlock<TOutput> source, CancellationToken cancellationToken)
{
// Validate arguments
if (source == null) throw new ArgumentNullException("source");
Contract.EndContractBlock();
// Fast path for cancellation
if (cancellationToken.IsCancellationRequested)
return Common.CreateTaskFromCancellation<bool>(cancellationToken);
// In a method like this, normally we would want to check source.Completion.IsCompleted
// and avoid linking completely by simply returning a completed task. However,
// some blocks that are completed still have data available, like WriteOnceBlock,
// which completes as soon as it gets a value and stores that value forever.
// As such, OutputAvailableAsync must link from the source so that the source
// can push data to us if it has it, at which point we can immediately unlink.
// Create a target task that will complete when it's offered a message (but it won't accept the message)
var target = new OutputAvailableAsyncTarget<TOutput>();
try
{
// Link from the source. If the source propagates a message during or immediately after linking
// such that our target is already completed, just return its task.
target._unlinker = source.LinkTo(target, DataflowLinkOptions.UnlinkAfterOneAndPropagateCompletion);
// If the task is already completed (an exception may have occurred, or the source may have propagated
// a message to the target during LinkTo or soon thereafter), just return the task directly.
if (target.Task.IsCompleted)
{
return target.Task;
}
// If cancellation could be requested, hook everything up to be notified of cancellation requests.
if (cancellationToken.CanBeCanceled)
{
// When cancellation is requested, unlink the target from the source and cancel the target.
target._ctr = cancellationToken.Register(OutputAvailableAsyncTarget<TOutput>.s_cancelAndUnlink, target);
}
// We can't return the task directly, as the source block will be completing the task synchronously,
// and thus any synchronous continuations would run as part of the source block's call. We don't have to worry
// about cancellation, as we've coded cancellation to complete the task asynchronously, and with the continuation
// set as NotOnCanceled, so the continuation will be canceled immediately when the antecedent is canceled, which
// will thus be asynchronously from the cancellation token source's cancellation call.
return target.Task.ContinueWith(
OutputAvailableAsyncTarget<TOutput>.s_handleCompletion, target,
CancellationToken.None, Common.GetContinuationOptions() | TaskContinuationOptions.NotOnCanceled, TaskScheduler.Default);
}
catch (Exception exc)
{
// Source.LinkTo could throw, as could cancellationToken.Register if cancellation was already requested
// such that it synchronously invokes the source's unlinker IDisposable, which could throw.
target.TrySetException(exc);
// Undo the link from the source to the target
target.AttemptThreadSafeUnlink();
// Return the now faulted task
return target.Task;
}
}
/// <summary>Provides a target used in OutputAvailableAsync operations.</summary>
/// <typeparam name="T">Specifies the type of data in the data source being checked.</typeparam>
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
private sealed class OutputAvailableAsyncTarget<T> : TaskCompletionSource<bool>, ITargetBlock<T>, IDebuggerDisplay
{
/// <summary>
/// Cached continuation delegate that unregisters from cancellation and
/// marshals the antecedent's result to the return value.
/// </summary>
internal readonly static Func<Task<bool>, object, bool> s_handleCompletion = (antecedent, state) =>
{
var target = state as OutputAvailableAsyncTarget<T>;
Debug.Assert(target != null, "Expected non-null target");
target._ctr.Dispose();
return antecedent.GetAwaiter().GetResult();
};
/// <summary>
/// Cached delegate that cancels the target and unlinks the target from the source.
/// Expects an OutputAvailableAsyncTarget as the state argument.
/// </summary>
internal readonly static Action<object> s_cancelAndUnlink = CancelAndUnlink;
/// <summary>Cancels the target and unlinks the target from the source.</summary>
/// <param name="state">An OutputAvailableAsyncTarget.</param>
private static void CancelAndUnlink(object state)
{
var target = state as OutputAvailableAsyncTarget<T>;
Debug.Assert(target != null, "Expected a non-null target");
// Cancel asynchronously so that we're not completing the task as part of the cts.Cancel() call,
// since synchronous continuations off that task would then run as part of Cancel.
// Take advantage of this task and unlink from there to avoid doing the interlocked operation synchronously.
System.Threading.Tasks.Task.Factory.StartNew(tgt =>
{
var thisTarget = (OutputAvailableAsyncTarget<T>)tgt;
thisTarget.TrySetCanceled();
thisTarget.AttemptThreadSafeUnlink();
},
target, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default);
}
/// <summary>Disposes of _unlinker if the target has been linked.</summary>
internal void AttemptThreadSafeUnlink()
{
// A race is possible. Therefore use an interlocked operation.
IDisposable cachedUnlinker = _unlinker;
if (cachedUnlinker != null && Interlocked.CompareExchange(ref _unlinker, null, cachedUnlinker) == cachedUnlinker)
{
cachedUnlinker.Dispose();
}
}
/// <summary>The IDisposable used to unlink this target from its source.</summary>
internal IDisposable _unlinker;
/// <summary>The registration used to unregister this target from the cancellation token.</summary>
internal CancellationTokenRegistration _ctr;
/// <summary>Completes the task when offered a message (but doesn't consume the message).</summary>
DataflowMessageStatus ITargetBlock<T>.OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, Boolean consumeToAccept)
{
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader");
if (source == null) throw new ArgumentNullException("source");
Contract.EndContractBlock();
TrySetResult(true);
return DataflowMessageStatus.DecliningPermanently;
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' />
void IDataflowBlock.Complete()
{
TrySetResult(false);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' />
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException("exception");
Contract.EndContractBlock();
TrySetResult(false);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
Task IDataflowBlock.Completion { get { throw new NotSupportedException(SR.NotSupported_MemberNotNeeded); } }
/// <summary>The data to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
return string.Format("{0} IsCompleted={1}",
Common.GetNameForDebugger(this), base.Task.IsCompleted);
}
}
/// <summary>Gets the data to display in the debugger display attribute for this instance.</summary>
object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } }
}
#endregion
#region Encapsulate
/// <summary>Encapsulates a target and a source into a single propagator.</summary>
/// <typeparam name="TInput">Specifies the type of input expected by the target.</typeparam>
/// <typeparam name="TOutput">Specifies the type of output produced by the source.</typeparam>
/// <param name="target">The target to encapsulate.</param>
/// <param name="source">The source to encapsulate.</param>
/// <returns>The encapsulated target and source.</returns>
/// <remarks>
/// This method does not in any way connect the target to the source. It creates a
/// propagator block whose target methods delegate to the specified target and whose
/// source methods delegate to the specified source. Any connection between the target
/// and the source is left for the developer to explicitly provide. The propagator's
/// <see cref="IDataflowBlock"/> implementation delegates to the specified source.
/// </remarks>
public static IPropagatorBlock<TInput, TOutput> Encapsulate<TInput, TOutput>(
ITargetBlock<TInput> target, ISourceBlock<TOutput> source)
{
if (target == null) throw new ArgumentNullException("target");
if (source == null) throw new ArgumentNullException("source");
Contract.EndContractBlock();
return new EncapsulatingPropagator<TInput, TOutput>(target, source);
}
/// <summary>Provides a dataflow block that encapsulates a target and a source to form a single propagator.</summary>
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
[DebuggerTypeProxy(typeof(EncapsulatingPropagator<,>.DebugView))]
private sealed class EncapsulatingPropagator<TInput, TOutput> : IPropagatorBlock<TInput, TOutput>, IReceivableSourceBlock<TOutput>, IDebuggerDisplay
{
/// <summary>The target half.</summary>
private ITargetBlock<TInput> _target;
/// <summary>The source half.</summary>
private ISourceBlock<TOutput> _source;
public EncapsulatingPropagator(ITargetBlock<TInput> target, ISourceBlock<TOutput> source)
{
Contract.Requires(target != null, "The target should never be null; this should be checked by all internal usage.");
Contract.Requires(source != null, "The source should never be null; this should be checked by all internal usage.");
_target = target;
_source = source;
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' />
public void Complete()
{
_target.Complete();
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' />
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException("exception");
Contract.EndContractBlock();
_target.Fault(exception);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' />
public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, bool consumeToAccept)
{
return _target.OfferMessage(messageHeader, messageValue, source, consumeToAccept);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
public Task Completion { get { return _source.Completion; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' />
public IDisposable LinkTo(ITargetBlock<TOutput> target, DataflowLinkOptions linkOptions)
{
return _source.LinkTo(target, linkOptions);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' />
public bool TryReceive(Predicate<TOutput> filter, out TOutput item)
{
var receivableSource = _source as IReceivableSourceBlock<TOutput>;
if (receivableSource != null) return receivableSource.TryReceive(filter, out item);
item = default(TOutput);
return false;
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' />
public bool TryReceiveAll(out IList<TOutput> items)
{
var receivableSource = _source as IReceivableSourceBlock<TOutput>;
if (receivableSource != null) return receivableSource.TryReceiveAll(out items);
items = default(IList<TOutput>);
return false;
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' />
public TOutput ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target, out Boolean messageConsumed)
{
return _source.ConsumeMessage(messageHeader, target, out messageConsumed);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' />
public bool ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
{
return _source.ReserveMessage(messageHeader, target);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' />
public void ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
{
_source.ReleaseReservation(messageHeader, target);
}
/// <summary>The data to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
var displayTarget = _target as IDebuggerDisplay;
var displaySource = _source as IDebuggerDisplay;
return string.Format("{0} Target=\"{1}\", Source=\"{2}\"",
Common.GetNameForDebugger(this),
displayTarget != null ? displayTarget.Content : _target,
displaySource != null ? displaySource.Content : _source);
}
}
/// <summary>Gets the data to display in the debugger display attribute for this instance.</summary>
object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } }
/// <summary>A debug view for the propagator.</summary>
private sealed class DebugView
{
/// <summary>The propagator being debugged.</summary>
private readonly EncapsulatingPropagator<TInput, TOutput> _propagator;
/// <summary>Initializes the debug view.</summary>
/// <param name="propagator">The propagator being debugged.</param>
public DebugView(EncapsulatingPropagator<TInput, TOutput> propagator)
{
Contract.Requires(propagator != null, "Need a block with which to construct the debug view.");
_propagator = propagator;
}
/// <summary>The target.</summary>
public ITargetBlock<TInput> Target { get { return _propagator._target; } }
/// <summary>The source.</summary>
public ISourceBlock<TOutput> Source { get { return _propagator._source; } }
}
}
#endregion
#region Choose
#region Choose<T1,T2>
/// <summary>Monitors two dataflow sources, invoking the provided handler for whichever source makes data available first.</summary>
/// <typeparam name="T1">Specifies type of data contained in the first source.</typeparam>
/// <typeparam name="T2">Specifies type of data contained in the second source.</typeparam>
/// <param name="source1">The first source.</param>
/// <param name="action1">The handler to execute on data from the first source.</param>
/// <param name="source2">The second source.</param>
/// <param name="action2">The handler to execute on data from the second source.</param>
/// <returns>
/// <para>
/// A <see cref="System.Threading.Tasks.Task{Int32}"/> that represents the asynchronous choice.
/// If both sources are completed prior to the choice completing,
/// the resulting task will be canceled. When one of the sources has data available and successfully propagates
/// it to the choice, the resulting task will complete when the handler completes: if the handler throws an exception,
/// the task will end in the <see cref="System.Threading.Tasks.TaskStatus.Faulted"/> state containing the unhandled exception, otherwise the task
/// will end with its <see cref="System.Threading.Tasks.Task{Int32}.Result"/> set to either 0 or 1 to
/// represent the first or second source, respectively.
/// </para>
/// <para>
/// This method will only consume an element from one of the two data sources, never both.
/// </para>
/// </returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source1"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="action1"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="source2"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="action2"/> is null (Nothing in Visual Basic).</exception>
public static Task<Int32> Choose<T1, T2>(
ISourceBlock<T1> source1, Action<T1> action1,
ISourceBlock<T2> source2, Action<T2> action2)
{
// All argument validation is handled by the delegated method
return Choose(source1, action1, source2, action2, DataflowBlockOptions.Default);
}
/// <summary>Monitors two dataflow sources, invoking the provided handler for whichever source makes data available first.</summary>
/// <typeparam name="T1">Specifies type of data contained in the first source.</typeparam>
/// <typeparam name="T2">Specifies type of data contained in the second source.</typeparam>
/// <param name="source1">The first source.</param>
/// <param name="action1">The handler to execute on data from the first source.</param>
/// <param name="source2">The second source.</param>
/// <param name="action2">The handler to execute on data from the second source.</param>
/// <param name="dataflowBlockOptions">The options with which to configure this choice.</param>
/// <returns>
/// <para>
/// A <see cref="System.Threading.Tasks.Task{Int32}"/> that represents the asynchronous choice.
/// If both sources are completed prior to the choice completing, or if the CancellationToken
/// provided as part of <paramref name="dataflowBlockOptions"/> is canceled prior to the choice completing,
/// the resulting task will be canceled. When one of the sources has data available and successfully propagates
/// it to the choice, the resulting task will complete when the handler completes: if the handler throws an exception,
/// the task will end in the <see cref="System.Threading.Tasks.TaskStatus.Faulted"/> state containing the unhandled exception, otherwise the task
/// will end with its <see cref="System.Threading.Tasks.Task{Int32}.Result"/> set to either 0 or 1 to
/// represent the first or second source, respectively.
/// </para>
/// <para>
/// This method will only consume an element from one of the two data sources, never both.
/// If cancellation is requested after an element has been received, the cancellation request will be ignored,
/// and the relevant handler will be allowed to execute.
/// </para>
/// </returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source1"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="action1"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="source2"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="action2"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception>
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
public static Task<Int32> Choose<T1, T2>(
ISourceBlock<T1> source1, Action<T1> action1,
ISourceBlock<T2> source2, Action<T2> action2,
DataflowBlockOptions dataflowBlockOptions)
{
// Validate arguments
if (source1 == null) throw new ArgumentNullException("source1");
if (action1 == null) throw new ArgumentNullException("action1");
if (source2 == null) throw new ArgumentNullException("source2");
if (action2 == null) throw new ArgumentNullException("action2");
if (dataflowBlockOptions == null) throw new ArgumentNullException("dataflowBlockOptions");
// Delegate to the shared implementation
return ChooseCore<T1, T2, VoidResult>(source1, action1, source2, action2, null, null, dataflowBlockOptions);
}
#endregion
#region Choose<T1,T2,T3>
/// <summary>Monitors three dataflow sources, invoking the provided handler for whichever source makes data available first.</summary>
/// <typeparam name="T1">Specifies type of data contained in the first source.</typeparam>
/// <typeparam name="T2">Specifies type of data contained in the second source.</typeparam>
/// <typeparam name="T3">Specifies type of data contained in the third source.</typeparam>
/// <param name="source1">The first source.</param>
/// <param name="action1">The handler to execute on data from the first source.</param>
/// <param name="source2">The second source.</param>
/// <param name="action2">The handler to execute on data from the second source.</param>
/// <param name="source3">The third source.</param>
/// <param name="action3">The handler to execute on data from the third source.</param>
/// <returns>
/// <para>
/// A <see cref="System.Threading.Tasks.Task{Int32}"/> that represents the asynchronous choice.
/// If all sources are completed prior to the choice completing,
/// the resulting task will be canceled. When one of the sources has data available and successfully propagates
/// it to the choice, the resulting task will complete when the handler completes: if the handler throws an exception,
/// the task will end in the <see cref="System.Threading.Tasks.TaskStatus.Faulted"/> state containing the unhandled exception, otherwise the task
/// will end with its <see cref="System.Threading.Tasks.Task{Int32}.Result"/> set to the 0-based index of the source.
/// </para>
/// <para>
/// This method will only consume an element from one of the data sources, never more than one.
/// </para>
/// </returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source1"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="action1"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="source2"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="action2"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="source3"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="action3"/> is null (Nothing in Visual Basic).</exception>
public static Task<Int32> Choose<T1, T2, T3>(
ISourceBlock<T1> source1, Action<T1> action1,
ISourceBlock<T2> source2, Action<T2> action2,
ISourceBlock<T3> source3, Action<T3> action3)
{
// All argument validation is handled by the delegated method
return Choose(source1, action1, source2, action2, source3, action3, DataflowBlockOptions.Default);
}
/// <summary>Monitors three dataflow sources, invoking the provided handler for whichever source makes data available first.</summary>
/// <typeparam name="T1">Specifies type of data contained in the first source.</typeparam>
/// <typeparam name="T2">Specifies type of data contained in the second source.</typeparam>
/// <typeparam name="T3">Specifies type of data contained in the third source.</typeparam>
/// <param name="source1">The first source.</param>
/// <param name="action1">The handler to execute on data from the first source.</param>
/// <param name="source2">The second source.</param>
/// <param name="action2">The handler to execute on data from the second source.</param>
/// <param name="source3">The third source.</param>
/// <param name="action3">The handler to execute on data from the third source.</param>
/// <param name="dataflowBlockOptions">The options with which to configure this choice.</param>
/// <returns>
/// <para>
/// A <see cref="System.Threading.Tasks.Task{Int32}"/> that represents the asynchronous choice.
/// If all sources are completed prior to the choice completing, or if the CancellationToken
/// provided as part of <paramref name="dataflowBlockOptions"/> is canceled prior to the choice completing,
/// the resulting task will be canceled. When one of the sources has data available and successfully propagates
/// it to the choice, the resulting task will complete when the handler completes: if the handler throws an exception,
/// the task will end in the <see cref="System.Threading.Tasks.TaskStatus.Faulted"/> state containing the unhandled exception, otherwise the task
/// will end with its <see cref="System.Threading.Tasks.Task{Int32}.Result"/> set to the 0-based index of the source.
/// </para>
/// <para>
/// This method will only consume an element from one of the data sources, never more than one.
/// If cancellation is requested after an element has been received, the cancellation request will be ignored,
/// and the relevant handler will be allowed to execute.
/// </para>
/// </returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source1"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="action1"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="source2"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="action2"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="source3"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="action3"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception>
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
public static Task<Int32> Choose<T1, T2, T3>(
ISourceBlock<T1> source1, Action<T1> action1,
ISourceBlock<T2> source2, Action<T2> action2,
ISourceBlock<T3> source3, Action<T3> action3,
DataflowBlockOptions dataflowBlockOptions)
{
// Validate arguments
if (source1 == null) throw new ArgumentNullException("source1");
if (action1 == null) throw new ArgumentNullException("action1");
if (source2 == null) throw new ArgumentNullException("source2");
if (action2 == null) throw new ArgumentNullException("action2");
if (source3 == null) throw new ArgumentNullException("source3");
if (action3 == null) throw new ArgumentNullException("action3");
if (dataflowBlockOptions == null) throw new ArgumentNullException("dataflowBlockOptions");
// Delegate to the shared implementation
return ChooseCore<T1, T2, T3>(source1, action1, source2, action2, source3, action3, dataflowBlockOptions);
}
#endregion
#region Choose Shared
/// <summary>Monitors dataflow sources, invoking the provided handler for whichever source makes data available first.</summary>
/// <typeparam name="T1">Specifies type of data contained in the first source.</typeparam>
/// <typeparam name="T2">Specifies type of data contained in the second source.</typeparam>
/// <typeparam name="T3">Specifies type of data contained in the third source.</typeparam>
/// <param name="source1">The first source.</param>
/// <param name="action1">The handler to execute on data from the first source.</param>
/// <param name="source2">The second source.</param>
/// <param name="action2">The handler to execute on data from the second source.</param>
/// <param name="source3">The third source.</param>
/// <param name="action3">The handler to execute on data from the third source.</param>
/// <param name="dataflowBlockOptions">The options with which to configure this choice.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
private static Task<Int32> ChooseCore<T1, T2, T3>(
ISourceBlock<T1> source1, Action<T1> action1,
ISourceBlock<T2> source2, Action<T2> action2,
ISourceBlock<T3> source3, Action<T3> action3,
DataflowBlockOptions dataflowBlockOptions)
{
Contract.Requires(source1 != null && action1 != null, "The first source and action should not be null.");
Contract.Requires(source2 != null && action2 != null, "The second source and action should not be null.");
Contract.Requires((source3 == null) == (action3 == null), "The third action should be null iff the third source is null.");
Contract.Requires(dataflowBlockOptions != null, "Options are required.");
bool hasThirdSource = source3 != null; // In the future, if we want higher arities on Choose, we can simply add more such checks on additional arguments
// Early cancellation check and bail out
if (dataflowBlockOptions.CancellationToken.IsCancellationRequested)
return Common.CreateTaskFromCancellation<Int32>(dataflowBlockOptions.CancellationToken);
// Fast path: if any of the sources already has data available that can be received immediately.
Task<int> resultTask;
try
{
TaskScheduler scheduler = dataflowBlockOptions.TaskScheduler;
if (TryChooseFromSource(source1, action1, 0, scheduler, out resultTask) ||
TryChooseFromSource(source2, action2, 1, scheduler, out resultTask) ||
(hasThirdSource && TryChooseFromSource(source3, action3, 2, scheduler, out resultTask)))
{
return resultTask;
}
}
catch (Exception exc)
{
// In case TryReceive in TryChooseFromSource erroneously throws
return Common.CreateTaskFromException<int>(exc);
}
// Slow path: link up to all of the sources. Separated out to avoid a closure on the fast path.
return ChooseCoreByLinking(source1, action1, source2, action2, source3, action3, dataflowBlockOptions);
}
/// <summary>
/// Tries to remove data from a receivable source and schedule an action to process that received item.
/// </summary>
/// <typeparam name="T">Specifies the type of data to process.</typeparam>
/// <param name="source">The source from which to receive the data.</param>
/// <param name="action">The action to run for the received data.</param>
/// <param name="branchId">The branch ID associated with this source/action pair.</param>
/// <param name="scheduler">The scheduler to use to process the action.</param>
/// <param name="task">The task created for processing the received item.</param>
/// <returns>true if this try attempt satisfies the choose operation; otherwise, false.</returns>
private static bool TryChooseFromSource<T>(
ISourceBlock<T> source, Action<T> action, int branchId, TaskScheduler scheduler,
out Task<int> task)
{
// Validate arguments
Contract.Requires(source != null, "Expected a non-null source");
Contract.Requires(action != null, "Expected a non-null action");
Contract.Requires(branchId >= 0, "Expected a valid branch ID (> 0)");
Contract.Requires(scheduler != null, "Expected a non-null scheduler");
// Try to receive from the source. If we can't, bail.
T result;
var receivableSource = source as IReceivableSourceBlock<T>;
if (receivableSource == null || !receivableSource.TryReceive(out result))
{
task = null;
return false;
}
// We successfully received an item. Launch a task to process it.
task = Task.Factory.StartNew(ChooseTarget<T>.s_processBranchFunction,
Tuple.Create<Action<T>, T, int>(action, result, branchId),
CancellationToken.None, Common.GetCreationOptionsForTask(), scheduler);
return true;
}
/// <summary>Monitors dataflow sources, invoking the provided handler for whichever source makes data available first.</summary>
/// <typeparam name="T1">Specifies type of data contained in the first source.</typeparam>
/// <typeparam name="T2">Specifies type of data contained in the second source.</typeparam>
/// <typeparam name="T3">Specifies type of data contained in the third source.</typeparam>
/// <param name="source1">The first source.</param>
/// <param name="action1">The handler to execute on data from the first source.</param>
/// <param name="source2">The second source.</param>
/// <param name="action2">The handler to execute on data from the second source.</param>
/// <param name="source3">The third source.</param>
/// <param name="action3">The handler to execute on data from the third source.</param>
/// <param name="dataflowBlockOptions">The options with which to configure this choice.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
private static Task<Int32> ChooseCoreByLinking<T1, T2, T3>(
ISourceBlock<T1> source1, Action<T1> action1,
ISourceBlock<T2> source2, Action<T2> action2,
ISourceBlock<T3> source3, Action<T3> action3,
DataflowBlockOptions dataflowBlockOptions)
{
Contract.Requires(source1 != null && action1 != null, "The first source and action should not be null.");
Contract.Requires(source2 != null && action2 != null, "The second source and action should not be null.");
Contract.Requires((source3 == null) == (action3 == null), "The third action should be null iff the third source is null.");
Contract.Requires(dataflowBlockOptions != null, "Options are required.");
bool hasThirdSource = source3 != null; // In the future, if we want higher arities on Choose, we can simply add more such checks on additional arguments
// Create object to act as both completion marker and sync obj for targets.
var boxedCompleted = new StrongBox<Task>();
// Set up teardown cancellation. We will request cancellation when a) the supplied options token
// has cancellation requested or b) when we actually complete somewhere in order to tear down
// the rest of our configured set up.
CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(dataflowBlockOptions.CancellationToken, CancellationToken.None);
// Set up the branches.
TaskScheduler scheduler = dataflowBlockOptions.TaskScheduler;
var branchTasks = new Task<int>[hasThirdSource ? 3 : 2];
branchTasks[0] = CreateChooseBranch(boxedCompleted, cts, scheduler, 0, source1, action1);
branchTasks[1] = CreateChooseBranch(boxedCompleted, cts, scheduler, 1, source2, action2);
if (hasThirdSource)
{
branchTasks[2] = CreateChooseBranch(boxedCompleted, cts, scheduler, 2, source3, action3);
}
// Asynchronously wait for all branches to complete, then complete
// a task to be returned to the caller.
var result = new TaskCompletionSource<int>();
Task.Factory.ContinueWhenAll(branchTasks, tasks =>
{
// Process the outcome of all branches. At most one will have completed
// successfully, returning its branch ID. Others may have faulted,
// in which case we need to propagate their exceptions, regardless
// of whether a branch completed successfully. Others may have been
// canceled (or run but found they were not needed), and those
// we just ignore.
List<Exception> exceptions = null;
int successfulBranchId = -1;
foreach (Task<int> task in tasks)
{
switch (task.Status)
{
case TaskStatus.Faulted:
Common.AddException(ref exceptions, task.Exception, unwrapInnerExceptions: true);
break;
case TaskStatus.RanToCompletion:
int resultBranchId = task.Result;
if (resultBranchId >= 0)
{
Debug.Assert(resultBranchId < tasks.Length, "Expected a valid branch ID");
Debug.Assert(successfulBranchId == -1, "There should be at most one successful branch.");
successfulBranchId = resultBranchId;
}
else Debug.Assert(resultBranchId == -1, "Expected -1 as a signal of a non-successful branch");
break;
}
}
// If we found any exceptions, fault the Choose task. Otherwise, if any branch completed
// successfully, store its result, or if cancellation was request
if (exceptions != null)
{
result.TrySetException(exceptions);
}
else if (successfulBranchId >= 0)
{
result.TrySetResult(successfulBranchId);
}
else
{
result.TrySetCanceled();
}
// By now we know that all of the tasks have completed, so there
// can't be any more use of the CancellationTokenSource.
cts.Dispose();
}, CancellationToken.None, Common.GetContinuationOptions(), TaskScheduler.Default);
return result.Task;
}
/// <summary>Creates a target for a branch of a Choose.</summary>
/// <typeparam name="T">Specifies the type of data coming through this branch.</typeparam>
/// <param name="boxedCompleted">A strong box around the completed Task from any target. Also sync obj for access to the targets.</param>
/// <param name="cts">The CancellationTokenSource used to issue tear down / cancellation requests.</param>
/// <param name="scheduler">The TaskScheduler on which to scheduler work.</param>
/// <param name="branchId">The ID of this branch, used to complete the resultTask.</param>
/// <param name="source">The source with which this branch is associated.</param>
/// <param name="action">The action to run for a single element received from the source.</param>
/// <returns>A task representing the branch.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static Task<int> CreateChooseBranch<T>(
StrongBox<Task> boxedCompleted, CancellationTokenSource cts,
TaskScheduler scheduler,
int branchId, ISourceBlock<T> source, Action<T> action)
{
// If the cancellation token is already canceled, there is no need to create and link a target.
// Instead, directly return a canceled task.
if (cts.IsCancellationRequested)
return Common.CreateTaskFromCancellation<int>(cts.Token);
// Proceed with creating and linking a hidden target. Also get the source's completion task,
// as we need it to know when the source completes. Both of these operations
// could throw an exception if the block is faulty.
var target = new ChooseTarget<T>(boxedCompleted, cts.Token);
IDisposable unlink;
try
{
unlink = source.LinkTo(target, DataflowLinkOptions.UnlinkAfterOneAndPropagateCompletion);
}
catch (Exception exc)
{
cts.Cancel();
return Common.CreateTaskFromException<int>(exc);
}
// The continuation task below is implicitly capturing the right execution context,
// as CreateChooseBranch is called synchronously from Choose, so we
// don't need to additionally capture and marshal an ExecutionContext.
return target.Task.ContinueWith(completed =>
{
try
{
// If the target ran to completion, i.e. it got a message,
// cancel the other branch(es) and proceed with the user callback.
if (completed.Status == TaskStatus.RanToCompletion)
{
// Cancel the cts to trigger completion of the other branches.
cts.Cancel();
// Proceed with the user callback.
action(completed.Result);
// Return the ID of our branch to indicate.
return branchId;
}
return -1;
}
finally
{
// Unlink from the source. This could throw if the block is faulty,
// in which case our branch's task will fault. If this
// does throw, it'll end up propagating instead of the
// original action's exception if there was one.
unlink.Dispose();
}
}, CancellationToken.None, Common.GetContinuationOptions(), scheduler);
}
/// <summary>Provides a dataflow target used by Choose to receive data from a single source.</summary>
/// <typeparam name="T">Specifies the type of data offered to this target.</typeparam>
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
private sealed class ChooseTarget<T> : TaskCompletionSource<T>, ITargetBlock<T>, IDebuggerDisplay
{
/// <summary>
/// Delegate used to invoke the action for a branch when that branch is activated
/// on the fast path.
/// </summary>
internal static readonly Func<object, int> s_processBranchFunction = state =>
{
Tuple<Action<T>, T, int> actionResultBranch = (Tuple<Action<T>, T, int>)state;
actionResultBranch.Item1(actionResultBranch.Item2);
return actionResultBranch.Item3;
};
/// <summary>
/// A wrapper for the task that represents the completed branch of this choice.
/// The wrapper is also the sync object used to protect all choice branch's access to shared state.
/// </summary>
private StrongBox<Task> _completed;
/// <summary>Initializes the target.</summary>
/// <param name="completed">The completed wrapper shared between all choice branches.</param>
/// <param name="cancellationToken">The cancellation token used to cancel this target.</param>
internal ChooseTarget(StrongBox<Task> completed, CancellationToken cancellationToken)
{
Contract.Requires(completed != null, "Requires a shared target to complete.");
_completed = completed;
// Handle async cancellation by canceling the target without storing it into _completed.
// _completed must only be set to a RanToCompletion task for a successful branch.
Common.WireCancellationToComplete(cancellationToken, base.Task,
state =>
{
var thisChooseTarget = (ChooseTarget<T>)state;
lock (thisChooseTarget._completed) thisChooseTarget.TrySetCanceled();
}, this);
}
/// <summary>Called when this choice branch is being offered a message.</summary>
public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, Boolean consumeToAccept)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader");
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, "consumeToAccept");
Contract.EndContractBlock();
lock (_completed)
{
// If we or another participating choice has already completed, we're done.
if (_completed.Value != null || base.Task.IsCompleted) return DataflowMessageStatus.DecliningPermanently;
// Consume the message from the source if necessary
if (consumeToAccept)
{
bool consumed;
messageValue = source.ConsumeMessage(messageHeader, this, out consumed);
if (!consumed) return DataflowMessageStatus.NotAvailable;
}
// Store the result and signal our success
TrySetResult(messageValue);
_completed.Value = Task;
return DataflowMessageStatus.Accepted;
}
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' />
void IDataflowBlock.Complete()
{
lock (_completed) TrySetCanceled();
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' />
void IDataflowBlock.Fault(Exception exception) { ((IDataflowBlock)this).Complete(); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
Task IDataflowBlock.Completion { get { throw new NotSupportedException(SR.NotSupported_MemberNotNeeded); } }
/// <summary>The data to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
return string.Format("{0} IsCompleted={1}",
Common.GetNameForDebugger(this), base.Task.IsCompleted);
}
}
/// <summary>Gets the data to display in the debugger display attribute for this instance.</summary>
object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } }
}
#endregion
#endregion
#region AsObservable
/// <summary>Creates a new <see cref="System.IObservable{TOutput}"/> abstraction over the <see cref="ISourceBlock{TOutput}"/>.</summary>
/// <typeparam name="TOutput">Specifies the type of data contained in the source.</typeparam>
/// <param name="source">The source to wrap.</param>
/// <returns>An IObservable{TOutput} that enables observers to be subscribed to the source.</returns>
/// <exception cref="System.ArgumentNullException">The <paramref name="source"/> is null (Nothing in Visual Basic).</exception>
public static IObservable<TOutput> AsObservable<TOutput>(this ISourceBlock<TOutput> source)
{
if (source == null) throw new ArgumentNullException("source");
Contract.EndContractBlock();
return SourceObservable<TOutput>.From(source);
}
/// <summary>Cached options for non-greedy processing.</summary>
private static readonly ExecutionDataflowBlockOptions _nonGreedyExecutionOptions = new ExecutionDataflowBlockOptions { BoundedCapacity = 1 };
/// <summary>Provides an IObservable veneer over a source block.</summary>
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
[DebuggerTypeProxy(typeof(SourceObservable<>.DebugView))]
private sealed class SourceObservable<TOutput> : IObservable<TOutput>, IDebuggerDisplay
{
/// <summary>The table that maps source to cached observable.</summary>
/// <remarks>
/// ConditionalWeakTable doesn't do the initialization under a lock, just the publication.
/// This means that if there's a race to create two observables off the same source, we could end
/// up instantiating multiple SourceObservable instances, of which only one will be published.
/// Worst case, we end up with a few additional continuations off of the source's completion task.
/// </remarks>
private static readonly ConditionalWeakTable<ISourceBlock<TOutput>, SourceObservable<TOutput>> _table =
new ConditionalWeakTable<ISourceBlock<TOutput>, SourceObservable<TOutput>>();
/// <summary>Gets an observable to represent the source block.</summary>
/// <param name="source">The source.</param>
/// <returns>The observable.</returns>
internal static IObservable<TOutput> From(ISourceBlock<TOutput> source)
{
Contract.Requires(source != null, "Requires a source for which to retrieve the observable.");
return _table.GetValue(source, s => new SourceObservable<TOutput>(s));
}
/// <summary>Object used to synchronize all subscriptions, unsubscriptions, and propagations.</summary>
private readonly object _SubscriptionLock = new object();
/// <summary>The wrapped source.</summary>
private readonly ISourceBlock<TOutput> _source;
/// <summary>
/// The current target. We use the same target until the number of subscribers
/// drops to 0, at which point we substitute in a new target.
/// </summary>
private ObserversState _observersState;
/// <summary>Initializes the SourceObservable.</summary>
/// <param name="source">The source to wrap.</param>
internal SourceObservable(ISourceBlock<TOutput> source)
{
Contract.Requires(source != null, "The observable requires a source to wrap.");
_source = source;
_observersState = new ObserversState(this);
}
/// <summary>Gets any exceptions from the source block.</summary>
/// <returns>The aggregate exception of all errors, or null if everything completed successfully.</returns>
private AggregateException GetCompletionError()
{
Task sourceCompletionTask = Common.GetPotentiallyNotSupportedCompletionTask(_source);
return sourceCompletionTask != null && sourceCompletionTask.IsFaulted ?
sourceCompletionTask.Exception : null;
}
/// <summary>Subscribes the observer to the source.</summary>
/// <param name="observer">the observer to subscribe.</param>
/// <returns>An IDisposable that may be used to unsubscribe the source.</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
IDisposable IObservable<TOutput>.Subscribe(IObserver<TOutput> observer)
{
// Validate arguments
if (observer == null) throw new ArgumentNullException("observer");
Contract.EndContractBlock();
Common.ContractAssertMonitorStatus(_SubscriptionLock, held: false);
Task sourceCompletionTask = Common.GetPotentiallyNotSupportedCompletionTask(_source);
// Synchronize all observers for this source.
Exception error = null;
lock (_SubscriptionLock)
{
// Fast path for if everything is already done. We need to ensure that both
// the source is complete and that the target has finished propagating data to all observers.
// If there was an error, we grab it here and then we'll complete the observer
// outside of the lock.
if (sourceCompletionTask != null && sourceCompletionTask.IsCompleted &&
_observersState.Target.Completion.IsCompleted)
{
error = GetCompletionError();
}
// Otherwise, we need to subscribe this observer.
else
{
// Hook up the observer. If this is the first observer, link the source to the target.
_observersState.Observers = _observersState.Observers.Add(observer);
if (_observersState.Observers.Count == 1)
{
Debug.Assert(_observersState.Unlinker == null, "The source should not be linked to the target.");
_observersState.Unlinker = _source.LinkTo(_observersState.Target);
if (_observersState.Unlinker == null)
{
_observersState.Observers = ImmutableList<IObserver<TOutput>>.Empty;
return null;
}
}
// Return a disposable that will unlink this observer, and if it's the last
// observer for the source, shut off the pipe to observers.
return Disposables.Create((s, o) => s.Unsubscribe(o), this, observer);
}
}
// Complete the observer.
if (error != null) observer.OnError(error);
else observer.OnCompleted();
return Disposables.Nop;
}
/// <summary>Unsubscribes the observer.</summary>
/// <param name="observer">The observer being unsubscribed.</param>
private void Unsubscribe(IObserver<TOutput> observer)
{
Contract.Requires(observer != null, "Expected an observer.");
Common.ContractAssertMonitorStatus(_SubscriptionLock, held: false);
lock (_SubscriptionLock)
{
ObserversState currentState = _observersState;
Debug.Assert(currentState != null, "Observer state should never be null.");
// If the observer was already unsubscribed (or is otherwise no longer present in our list), bail.
if (!currentState.Observers.Contains(observer)) return;
// If this is the last observer being removed, reset to be ready for future subscribers.
if (currentState.Observers.Count == 1)
{
ResetObserverState();
}
// Otherwise, just remove the observer. Note that we don't remove the observer
// from the current target if this is the last observer. This is done in case the target
// has already taken data from the source: we want that data to end up somewhere,
// and we can't put it back in the source, so we ensure we send it along to the observer.
else
{
currentState.Observers = currentState.Observers.Remove(observer);
}
}
}
/// <summary>Resets the observer state to the original, inactive state.</summary>
/// <returns>The list of active observers prior to the reset.</returns>
private ImmutableList<IObserver<TOutput>> ResetObserverState()
{
Common.ContractAssertMonitorStatus(_SubscriptionLock, held: true);
ObserversState currentState = _observersState;
Debug.Assert(currentState != null, "Observer state should never be null.");
Debug.Assert(currentState.Unlinker != null, "The target should be linked.");
Debug.Assert(currentState.Canceler != null, "The target should have set up continuations.");
// Replace the target with a clean one, unlink and cancel, and return the previous set of observers
ImmutableList<IObserver<TOutput>> currentObservers = currentState.Observers;
_observersState = new ObserversState(this);
currentState.Unlinker.Dispose();
currentState.Canceler.Cancel();
return currentObservers;
}
/// <summary>The data to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
var displaySource = _source as IDebuggerDisplay;
return string.Format("Observers={0}, Block=\"{1}\"",
_observersState.Observers.Count,
displaySource != null ? displaySource.Content : _source);
}
}
/// <summary>Gets the data to display in the debugger display attribute for this instance.</summary>
object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } }
/// <summary>Provides a debugger type proxy for the observable.</summary>
private sealed class DebugView
{
/// <summary>The observable being debugged.</summary>
private readonly SourceObservable<TOutput> _observable;
/// <summary>Initializes the debug view.</summary>
/// <param name="observable">The target being debugged.</param>
public DebugView(SourceObservable<TOutput> observable)
{
Contract.Requires(observable != null, "Need a block with which to construct the debug view.");
_observable = observable;
}
/// <summary>Gets an enumerable of the observers.</summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public IObserver<TOutput>[] Observers { get { return _observable._observersState.Observers.ToArray(); } }
}
/// <summary>State associated with the current target for propagating data to observers.</summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
private sealed class ObserversState
{
/// <summary>The owning SourceObservable.</summary>
internal readonly SourceObservable<TOutput> Observable;
/// <summary>The ActionBlock that consumes data from a source and offers it to targets.</summary>
internal readonly ActionBlock<TOutput> Target;
/// <summary>Used to cancel continuations when they're no longer necessary.</summary>
internal readonly CancellationTokenSource Canceler = new CancellationTokenSource();
/// <summary>
/// A list of the observers currently registered with this target. The list is immutable
/// to enable iteration through the list while the set of observers may be changing.
/// </summary>
internal ImmutableList<IObserver<TOutput>> Observers = ImmutableList<IObserver<TOutput>>.Empty;
/// <summary>Used to unlink the source from this target when the last observer is unsubscribed.</summary>
internal IDisposable Unlinker;
/// <summary>
/// Temporary list to keep track of SendAsync tasks to TargetObservers with back pressure.
/// This field gets instantiated on demand. It gets populated and cleared within an offering cycle.
/// </summary>
private List<Task<bool>> _tempSendAsyncTaskList;
/// <summary>Initializes the target instance.</summary>
/// <param name="observable">The owning observable.</param>
internal ObserversState(SourceObservable<TOutput> observable)
{
Contract.Requires(observable != null, "Observe state must be mapped to a source observable.");
// Set up the target block
Observable = observable;
Target = new ActionBlock<TOutput>((Func<TOutput, Task>)ProcessItemAsync, DataflowBlock._nonGreedyExecutionOptions);
// If the target block fails due to an unexpected exception (e.g. it calls back to the source and the source throws an error),
// we fault currently registered observers and reset the observable.
Target.Completion.ContinueWith(
(t, state) => ((ObserversState)state).NotifyObserversOfCompletion(t.Exception), this,
CancellationToken.None,
Common.GetContinuationOptions(TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously),
TaskScheduler.Default);
// When the source completes, complete the target. Then when the target completes,
// send completion messages to any observers still registered.
Task sourceCompletionTask = Common.GetPotentiallyNotSupportedCompletionTask(Observable._source);
if (sourceCompletionTask != null)
{
sourceCompletionTask.ContinueWith((_1, state1) =>
{
var ti = (ObserversState)state1;
ti.Target.Complete();
ti.Target.Completion.ContinueWith(
(_2, state2) => ((ObserversState)state2).NotifyObserversOfCompletion(), state1,
CancellationToken.None,
Common.GetContinuationOptions(TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.ExecuteSynchronously),
TaskScheduler.Default);
}, this, Canceler.Token, Common.GetContinuationOptions(TaskContinuationOptions.ExecuteSynchronously), TaskScheduler.Default);
}
}
/// <summary>Forwards an item to all currently subscribed observers.</summary>
/// <param name="item">The item to forward.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private Task ProcessItemAsync(TOutput item)
{
Common.ContractAssertMonitorStatus(Observable._SubscriptionLock, held: false);
ImmutableList<IObserver<TOutput>> currentObservers;
lock (Observable._SubscriptionLock) currentObservers = Observers;
try
{
foreach (IObserver<TOutput> observer in currentObservers)
{
// If the observer is our own TargetObserver, we SendAsync() to it
// rather than going through IObserver.OnNext() which allows us to
// continue offering to the remaining observers without blocking.
var targetObserver = observer as TargetObserver<TOutput>;
if (targetObserver != null)
{
Task<bool> sendAsyncTask = targetObserver.SendAsyncToTarget(item);
if (sendAsyncTask.Status != TaskStatus.RanToCompletion)
{
// Ensure the SendAsyncTaskList is instantiated
if (_tempSendAsyncTaskList == null) _tempSendAsyncTaskList = new List<Task<bool>>();
// Add the task to the list
_tempSendAsyncTaskList.Add(sendAsyncTask);
}
}
else
{
observer.OnNext(item);
}
}
// If there are SendAsync tasks to wait on...
if (_tempSendAsyncTaskList != null && _tempSendAsyncTaskList.Count > 0)
{
// Consolidate all SendAsync tasks into one
Task<bool[]> allSendAsyncTasksConsolidated = Task.WhenAll(_tempSendAsyncTaskList);
// Clear the temp SendAsync task list
_tempSendAsyncTaskList.Clear();
// Return the consolidated task
return allSendAsyncTasksConsolidated;
}
}
catch (Exception exc)
{
// Return a faulted task
return Common.CreateTaskFromException<VoidResult>(exc);
}
// All observers accepted normally.
// Return a completed task.
return Common.CompletedTaskWithTrueResult;
}
/// <summary>Notifies all currently registered observers that they should complete.</summary>
/// <param name="targetException">
/// Non-null when an unexpected exception occurs during processing. Faults
/// all subscribed observers and resets the observable back to its original condition.
/// </param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void NotifyObserversOfCompletion(Exception targetException = null)
{
Contract.Requires(Target.Completion.IsCompleted, "The target must have already completed in order to notify of completion.");
Common.ContractAssertMonitorStatus(Observable._SubscriptionLock, held: false);
// Send completion notification to all observers.
ImmutableList<IObserver<TOutput>> currentObservers;
lock (Observable._SubscriptionLock)
{
// Get the currently registered set of observers. Then, if we're being called due to the target
// block failing from an unexpected exception, reset the observer state so that subsequent
// subscribed observers will get a new target block. Finally clear out our observer list.
currentObservers = Observers;
if (targetException != null) Observable.ResetObserverState();
Observers = ImmutableList<IObserver<TOutput>>.Empty;
}
// If there are any observers to complete...
if (currentObservers.Count > 0)
{
// Determine if we should fault or complete the observers
Exception error = targetException ?? Observable.GetCompletionError();
try
{
// Do it.
if (error != null)
{
foreach (IObserver<TOutput> observer in currentObservers) observer.OnError(error);
}
else
{
foreach (IObserver<TOutput> observer in currentObservers) observer.OnCompleted();
}
}
catch (Exception exc)
{
// If an observer throws an exception at this point (which it shouldn't do),
// we have little recourse but to let that exception propagate. Since allowing it to
// propagate here would just result in it getting eaten by the owning task,
// we instead have it propagate on the thread pool.
Common.ThrowAsync(exc);
}
}
}
}
}
#endregion
#region AsObserver
/// <summary>Creates a new <see cref="System.IObserver{TInput}"/> abstraction over the <see cref="ITargetBlock{TInput}"/>.</summary>
/// <typeparam name="TInput">Specifies the type of input accepted by the target block.</typeparam>
/// <param name="target">The target to wrap.</param>
/// <returns>An observer that wraps the target block.</returns>
public static IObserver<TInput> AsObserver<TInput>(this ITargetBlock<TInput> target)
{
if (target == null) throw new ArgumentNullException("target");
Contract.EndContractBlock();
return new TargetObserver<TInput>(target);
}
/// <summary>Provides an observer wrapper for a target block.</summary>
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
private sealed class TargetObserver<TInput> : IObserver<TInput>, IDebuggerDisplay
{
/// <summary>The wrapped target.</summary>
private readonly ITargetBlock<TInput> _target;
/// <summary>Initializes the observer.</summary>
/// <param name="target">The target to wrap.</param>
internal TargetObserver(ITargetBlock<TInput> target)
{
Contract.Requires(target != null, "A target to observe is required.");
_target = target;
}
/// <summary>Sends the value to the observer.</summary>
/// <param name="value">The value to send.</param>
void IObserver<TInput>.OnNext(TInput value)
{
// Send the value asynchronously...
Task<bool> task = SendAsyncToTarget(value);
// And block until it's received.
task.GetAwaiter().GetResult(); // propagate original (non-aggregated) exception
}
/// <summary>Completes the target.</summary>
void IObserver<TInput>.OnCompleted()
{
_target.Complete();
}
/// <summary>Forwards the error to the target.</summary>
/// <param name="error">The exception to forward.</param>
void IObserver<TInput>.OnError(Exception error)
{
_target.Fault(error);
}
/// <summary>Sends a value to the underlying target asynchronously.</summary>
/// <param name="value">The value to send.</param>
/// <returns>A Task{bool} to wait on.</returns>
internal Task<bool> SendAsyncToTarget(TInput value)
{
return _target.SendAsync(value);
}
/// <summary>The data to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
var displayTarget = _target as IDebuggerDisplay;
return string.Format("Block=\"{0}\"",
displayTarget != null ? displayTarget.Content : _target);
}
}
/// <summary>Gets the data to display in the debugger display attribute for this instance.</summary>
object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } }
}
#endregion
#region NullTarget
/// <summary>
/// Gets a target block that synchronously accepts all messages offered to it and drops them.
/// </summary>
/// <typeparam name="TInput">The type of the messages this block can accept.</typeparam>
/// <returns>A <see cref="T:System.Threading.Tasks.Dataflow.ITargetBlock`1"/> that accepts and subsequently drops all offered messages.</returns>
public static ITargetBlock<TInput> NullTarget<TInput>()
{
return new NullTargetBlock<TInput>();
}
/// <summary>
/// Target block that synchronously accepts all messages offered to it and drops them.
/// </summary>
/// <typeparam name="TInput">The type of the messages this block can accept.</typeparam>
private class NullTargetBlock<TInput> : ITargetBlock<TInput>
{
private Task _completion;
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' />
DataflowMessageStatus ITargetBlock<TInput>.OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, Boolean consumeToAccept)
{
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader");
Contract.EndContractBlock();
// If the source requires an explicit synchronous consumption, do it
if (consumeToAccept)
{
if (source == null) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, "consumeToAccept");
bool messageConsumed;
// If the source throws during this call, let the exception propagate back to the source
source.ConsumeMessage(messageHeader, this, out messageConsumed);
if (!messageConsumed) return DataflowMessageStatus.NotAvailable;
}
// Always tell the source the message has been accepted
return DataflowMessageStatus.Accepted;
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' />
void IDataflowBlock.Complete() { } // No-op
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' />
void IDataflowBlock.Fault(Exception exception) { } // No-op
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
Task IDataflowBlock.Completion
{
get { return LazyInitializer.EnsureInitialized(ref _completion, () => new TaskCompletionSource<VoidResult>().Task); }
}
}
#endregion
}
}
| mit |
cake-build/cake | src/Cake.Common.Tests/Unit/Tools/XUnit/XUnitSettingsTests.cs | 1780 | // 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.
using Cake.Common.Tools.XUnit;
using Xunit;
namespace Cake.Common.Tests.Unit.Tools.XUnit
{
public sealed class XUnitSettingsTests
{
public sealed class TheConstructor
{
[Fact]
public void Should_Set_Output_Directory_To_Null_By_Default()
{
// Given, When
var settings = new XUnitSettings();
// Then
Assert.Null(settings.OutputDirectory);
}
[Fact]
public void Should_Disable_XML_Report_By_Default()
{
// Given, When
var settings = new XUnitSettings();
// Then
Assert.False(settings.XmlReport);
}
[Fact]
public void Should_Disable_HTML_Report_By_Default()
{
// Given, When
var settings = new XUnitSettings();
// Then
Assert.False(settings.HtmlReport);
}
[Fact]
public void Should_Enable_Shadow_Copying_By_Default()
{
// Given, When
var settings = new XUnitSettings();
// Then
Assert.True(settings.ShadowCopy);
}
[Fact]
public void Should_Disable_Silent_Mode_By_Default()
{
// Given, When
var settings = new XUnitSettings();
// Then
Assert.False(settings.Silent);
}
}
}
} | mit |
SergeiShemshur/java-design-patterns | model-view-presenter/src/main/java/com/iluwatar/modelviewpresenter/FileSelectorPresenter.java | 1651 | package com.iluwatar.modelviewpresenter;
/**
* Every instance of this class represents the Presenter component in the
* Model-View-Presenter architectural pattern.
*
* It is responsible for reacting to the user's actions and update the View
* component.
*/
public class FileSelectorPresenter {
/**
* The View component that the presenter interacts with.
*/
private FileSelectorView view;
/**
* The Model component that the presenter interacts with.
*/
private FileLoader loader;
/**
* Constructor
*
* @param view
* The view component that the presenter will interact with.
*/
public FileSelectorPresenter(FileSelectorView view) {
this.view = view;
}
/**
* Sets the FileLoader object, to the value given as parameter.
*
* @param loader
* The new FileLoader object(the Model component).
*/
public void setLoader(FileLoader loader) {
this.loader = loader;
}
/**
* Starts the presenter.
*/
public void start() {
view.setPresenter(this);
view.open();
}
/**
* An "event" that fires when the name of the file to be loaded changes.
*/
public void fileNameChanged() {
loader.setFileName(view.getFileName());
}
public void confirmed() {
if (loader.getFileName() == null || loader.getFileName().equals("")) {
view.showMessage("Please give the name of the file first!");
return;
}
if (loader.fileExists()) {
String data = loader.loadData();
view.displayData(data);
}
else {
view.showMessage("The file specified does not exist.");
}
}
/**
* Cancels the file loading process.
*/
public void cancelled() {
view.close();
}
}
| mit |
sherlock221/appframework2_1_0_update | plugins/af.selectBox.js | 11103 | /**
* copyright: 2011 Intel
* description: This script will replace all drop downs with friendly select controls. Users can still interact
* with the old drop down box as normal with javascript, and this will be reflected
*/
/* global af*/
/* global numOnly*/
(function($) {
/*jshint camelcase: false,
validthis:true
*/
"use strict";
function updateOption(prop, oldValue, newValue) {
if (newValue === true) {
if (!this.getAttribute("multiple"))
$.selectBox.updateMaskValue(this.parentNode.id, this.text, this.value);
this.parentNode.value = this.value;
}
return newValue;
}
function updateIndex(prop, oldValue, newValue) {
if (this.options[newValue]) {
if (!this.getAttribute("multiple"))
$.selectBox.updateMaskValue(this.linker, this.options[newValue].value, this.options[newValue].text);
this.value = this.options[newValue].value;
}
return newValue;
}
function destroy(e) {
var el = e.target;
$(el.linker).remove();
delete el.linker;
e.stopPropagation();
}
$.selectBox = {
scroller: null,
currLinker: null,
getOldSelects: function(elID) {
if (!$.os.android || $.os.androidICS) return;
if (!$.fn.scroller) {
window.alert("This library requires af.scroller");
return;
}
var container = elID && document.getElementById(elID) ? document.getElementById(elID) : document;
if (!container) {
window.alert("Could not find container element for af.selectBox " + elID);
return;
}
var sels = container.getElementsByTagName("select");
var that = this;
for (var i = 0; i < sels.length; i++) {
var el = sels[i];
el.style.display = "none";
var fixer = $.create("div", {
className: "afFakeSelect"
});
fixer.get(0).linker = sels[i];
el.linker = fixer.get(0);
fixer.insertAfter(sels[i]);
el.watch("selectedIndex", updateIndex);
for (var j = 0; j < el.options.length; j++) {
var currInd = j;
el.options[j].watch("selected", updateOption);
if (el.options[j].selected)
fixer.html(el.options[j].text);
}
$(el).one("destroy", destroy);
}
that.createHtml();
},
updateDropdown: function(el) {
if (!el) return;
for (var j = 0; j < el.options.length; j++) {
if (el.options[j].selected) el.linker.innerHTML = el.options[j].text;
}
el = null;
},
initDropDown: function(el) {
var that = this;
if (el.disabled) return;
if (!el || !el.options || el.options.length === 0) return;
var htmlTemplate = "";
var foundInd = 0;
var $scr = $("#afSelectBoxfix");
$scr.html("<ul></ul>");
var $list = $scr.find("ul");
for (var j = 0; j < el.options.length; j++) {
var currInd = j;
el.options[j].watch("selected", updateOption);
var checked = (el.options[j].selected) ? "selected" : "";
if (checked) foundInd = j + 1;
var row = $.create("li", {
html: el.options[j].text,
className: checked
});
row.data("ind", j);
$list.append(row);
}
$("#afModalMask").show();
try {
if (foundInd > 0 && el.getAttribute("multiple") !== "multiple") {
var scrollToPos = 0;
var scrollThreshold = numOnly($list.find("li").computedStyle("height"));
var theHeight = numOnly($("#afSelectBoxContainer").computedStyle("height"));
if (foundInd * scrollThreshold >= theHeight) scrollToPos = (foundInd - 1) * -scrollThreshold;
this.scroller.scrollTo({
x: 0,
y: scrollToPos
});
}
} catch (e) {
console.log("error init dropdown" + e);
}
var selClose = $("#afSelectClose").css("display") === "block" ? numOnly($("#afSelectClose").height()) : 0;
$("#afSelectWrapper").height((numOnly($("#afSelectBoxContainer").height()) - selClose) + "px");
},
updateMaskValue: function(linker, value, val2) {
$(linker).html(val2);
},
setDropDownValue: function(el, value) {
if (!el) return;
var $el = $(el);
value = parseInt(value, 10);
if (!el.getAttribute("multiple")) {
el.selectedIndex = value;
$el.find("option").prop("selected", false);
$el.find("option:nth-child(" + (value + 1) + ")").prop("selected", true);
this.scroller.scrollTo({
x: 0,
y: 0
});
this.hideDropDown();
} else {
//multi select
// var myEl = $el.find("option:nth-child(" + (value + 1) + ")").get(0);
var myList = $("#afSelectBoxfix li:nth-child(" + (value + 1) + ")");
if (myList.hasClass("selected")) {
myList.removeClass("selected");
// myEl.selected = false;
} else {
myList.addClass("selected");
// myEl.selected = true;
}
}
$(el).trigger("change");
el = null;
},
hideDropDown: function() {
$("#afModalMask").hide();
$("#afSelectBoxfix").html("");
},
createHtml: function() {
var that = this;
if (document.getElementById("afSelectBoxfix")) {
return;
}
$(document).ready(function() {
$(document).on("click", ".afFakeSelect", function(e) {
if (this.linker.disabled)
return;
that.currLinker = this;
if (this.linker.getAttribute("multiple") === "multiple")
$("#afSelectClose").show();
else
$("#afSelectClose").hide();
that.initDropDown(this.linker);
});
var container = $.create("div", {
id: "afSelectBoxContainer"
});
var modalDiv = $.create("div", {
id: "afSelectBoxfix"
});
var modalWrapper = $.create("div", {
id: "afSelectWrapper"
});
modalWrapper.css("position", "relative");
modalWrapper.append(modalDiv);
var closeDiv = $.create("div", {
id: "afSelectClose",
html: "<a id='afSelectDone'>Done</a> <a id='afSelectCancel'>Cancel</a>"
});
var modalMask = $.create("div", {
id:"afModalMask"
});
var $afui = $("#afui");
container.prepend(closeDiv).append(modalWrapper);
modalMask.append(container);
if ($afui.length > 0) $afui.append(modalMask);
else document.body.appendChild(modalMask.get(0));
that.scroller = $.query("#afSelectBoxfix").scroller({
scroller: false,
verticalScroll: true,
vScrollCSS: "afselectscrollBarV",
hasParent:true
});
$("#afModalMask").on("click",function(e){
var $e=$(e.target);
if($e.closest("#afSelectBoxContainer").length === 0)
that.hideDropDown();
});
$("#afSelectBoxfix").on("click", "li", function(e) {
var $el = $(e.target);
that.setDropDownValue(that.currLinker.linker, $el.data("ind"));
});
$("#afSelectBoxContainer").on("click", "a", function(e) {
if (e.target.id === "afSelectCancel")
return that.hideDropDown();
var $sel = $(that.currLinker.linker);
$sel.find("option").prop("selected", false);
$("#afSelectBoxfix li").each(function(el) {
var $el = $(this);
if ($el.hasClass("selected")) {
var ind = parseInt($el.data("ind"), 10);
$sel.find("option:nth-child(" + (ind + 1) + ")").prop("selected", true);
that.currLinker.innerHTML = $el.html();
}
});
that.hideDropDown();
e.stopPropagation();
e.preventDefault();
return false;
});
});
}
};
//The following is based off Eli Grey's shim
//https://gist.github.com/384583
//We use HTMLElement to not cause problems with other objects
if (!HTMLElement.prototype.watch) {
HTMLElement.prototype.watch = function(prop, handler) {
var oldval = this[prop],
newval = oldval,
getter = function() {
return newval;
},
setter = function(val) {
oldval = newval;
newval = handler.call(this, prop, oldval, val);
return newval;
};
if (delete this[prop]) { // can't watch constants
if (HTMLElement.defineProperty) { // ECMAScript 5
HTMLElement.defineProperty(this, prop, {
get: getter,
set: setter,
enumerable: false,
configurable: true
});
} else if (HTMLElement.prototype.__defineGetter__ && HTMLElement.prototype.__defineSetter__) { // legacy
HTMLElement.prototype.__defineGetter__.call(this, prop, getter);
HTMLElement.prototype.__defineSetter__.call(this, prop, setter);
}
}
};
}
if (!HTMLElement.prototype.unwatch) {
HTMLElement.prototype.unwatch = function(prop) {
var val = this[prop];
delete this[prop]; // remove accessors
this[prop] = val;
};
}
})(af);
| mit |
cdnjs/cdnjs | ajax/libs/ag-grid/9.0.4/lib/widgets/component.js | 8408 | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v9.0.3
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("../utils");
var beanStub_1 = require("../context/beanStub");
var Component = (function (_super) {
__extends(Component, _super);
function Component(template) {
var _this = _super.call(this) || this;
_this.childComponents = [];
_this.annotatedEventListeners = [];
_this.visible = true;
if (template) {
_this.setTemplate(template);
}
return _this;
}
Component.prototype.instantiate = function (context) {
this.instantiateRecurse(this.getGui(), context);
};
Component.prototype.instantiateRecurse = function (parentNode, context) {
var childCount = parentNode.childNodes ? parentNode.childNodes.length : 0;
for (var i = 0; i < childCount; i++) {
var childNode = parentNode.childNodes[i];
var newComponent = context.createComponent(childNode);
if (newComponent) {
this.swapComponentForNode(newComponent, parentNode, childNode);
}
else {
if (childNode.childNodes) {
this.instantiateRecurse(childNode, context);
}
}
}
};
Component.prototype.swapComponentForNode = function (newComponent, parentNode, childNode) {
parentNode.replaceChild(newComponent.getGui(), childNode);
this.childComponents.push(newComponent);
this.swapInComponentForQuerySelectors(newComponent, childNode);
};
Component.prototype.swapInComponentForQuerySelectors = function (newComponent, childNode) {
var metaData = this.__agComponentMetaData;
if (!metaData || !metaData.querySelectors) {
return;
}
var thisNoType = this;
metaData.querySelectors.forEach(function (querySelector) {
if (thisNoType[querySelector.attributeName] === childNode) {
thisNoType[querySelector.attributeName] = newComponent;
}
});
};
Component.prototype.setTemplate = function (template) {
var eGui = utils_1.Utils.loadTemplate(template);
this.setTemplateFromElement(eGui);
};
Component.prototype.setTemplateFromElement = function (element) {
this.eGui = element;
this.eGui.__agComponent = this;
this.addAnnotatedEventListeners();
this.wireQuerySelectors();
};
Component.prototype.attributesSet = function () {
};
Component.prototype.wireQuerySelectors = function () {
var _this = this;
var metaData = this.__agComponentMetaData;
if (!metaData || !metaData.querySelectors) {
return;
}
if (!this.eGui) {
return;
}
var thisNoType = this;
metaData.querySelectors.forEach(function (querySelector) {
var resultOfQuery = _this.eGui.querySelector(querySelector.querySelector);
if (resultOfQuery) {
var backingComponent = resultOfQuery.__agComponent;
if (backingComponent) {
thisNoType[querySelector.attributeName] = backingComponent;
}
else {
thisNoType[querySelector.attributeName] = resultOfQuery;
}
}
else {
// put debug msg in here if query selector fails???
}
});
};
Component.prototype.addAnnotatedEventListeners = function () {
var _this = this;
this.removeAnnotatedEventListeners();
var metaData = this.__agComponentMetaData;
if (!metaData || !metaData.listenerMethods) {
return;
}
if (!this.eGui) {
return;
}
if (!this.annotatedEventListeners) {
this.annotatedEventListeners = [];
}
metaData.listenerMethods.forEach(function (eventListener) {
var listener = _this[eventListener.methodName].bind(_this);
_this.eGui.addEventListener(eventListener.eventName, listener);
_this.annotatedEventListeners.push({ eventName: eventListener.eventName, listener: listener });
});
};
Component.prototype.removeAnnotatedEventListeners = function () {
var _this = this;
if (!this.annotatedEventListeners) {
return;
}
if (!this.eGui) {
return;
}
this.annotatedEventListeners.forEach(function (eventListener) {
_this.eGui.removeEventListener(eventListener.eventName, eventListener.listener);
});
this.annotatedEventListeners = null;
};
Component.prototype.getGui = function () {
return this.eGui;
};
// this method is for older code, that wants to provide the gui element,
// it is not intended for this to be in ag-Stack
Component.prototype.setGui = function (eGui) {
this.eGui = eGui;
};
Component.prototype.queryForHtmlElement = function (cssSelector) {
return this.eGui.querySelector(cssSelector);
};
Component.prototype.queryForHtmlInputElement = function (cssSelector) {
return this.eGui.querySelector(cssSelector);
};
Component.prototype.appendChild = function (newChild) {
if (utils_1.Utils.isNodeOrElement(newChild)) {
this.eGui.appendChild(newChild);
}
else {
var childComponent = newChild;
this.eGui.appendChild(childComponent.getGui());
this.childComponents.push(childComponent);
}
};
Component.prototype.addFeature = function (context, feature) {
context.wireBean(feature);
if (feature.destroy) {
this.addDestroyFunc(feature.destroy.bind(feature));
}
};
Component.prototype.isVisible = function () {
return this.visible;
};
Component.prototype.setVisible = function (visible) {
if (visible !== this.visible) {
this.visible = visible;
utils_1.Utils.addOrRemoveCssClass(this.eGui, 'ag-hidden', !visible);
this.dispatchEvent(Component.EVENT_VISIBLE_CHANGED, { visible: this.visible });
}
};
Component.prototype.addOrRemoveCssClass = function (className, addOrRemove) {
utils_1.Utils.addOrRemoveCssClass(this.eGui, className, addOrRemove);
};
Component.prototype.destroy = function () {
_super.prototype.destroy.call(this);
this.childComponents.forEach(function (childComponent) { return childComponent.destroy(); });
this.childComponents.length = 0;
this.removeAnnotatedEventListeners();
};
Component.prototype.addGuiEventListener = function (event, listener) {
var _this = this;
this.getGui().addEventListener(event, listener);
this.addDestroyFunc(function () { return _this.getGui().removeEventListener(event, listener); });
};
Component.prototype.addCssClass = function (className) {
utils_1.Utils.addCssClass(this.getGui(), className);
};
Component.prototype.removeCssClass = function (className) {
utils_1.Utils.removeCssClass(this.getGui(), className);
};
Component.prototype.getAttribute = function (key) {
var eGui = this.getGui();
if (eGui) {
return eGui.getAttribute(key);
}
else {
return null;
}
};
Component.prototype.getRefElement = function (refName) {
return this.queryForHtmlElement('[ref="' + refName + '"]');
};
return Component;
}(beanStub_1.BeanStub));
Component.EVENT_VISIBLE_CHANGED = 'visibleChanged';
exports.Component = Component;
| mit |
NorfairKing/sus-depot | shared/shared/vim/dotvim/bundle/YouCompleteMe/third_party/ycmd/third_party/OmniSharpServer/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Resolver/OverloadResolutionTests.cs | 13994 | // Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using NUnit.Framework;
namespace ICSharpCode.NRefactory.CSharp.Resolver
{
[TestFixture]
public class OverloadResolutionTests : ResolverTestBase
{
ResolveResult[] MakeArgumentList(params Type[] argumentTypes)
{
return argumentTypes.Select(t => new ResolveResult(compilation.FindType(t))).ToArray();
}
IMethod MakeMethod(params object[] parameterTypesOrDefaultValues)
{
var context = new SimpleTypeResolveContext(compilation.MainAssembly);
return (IMethod)MakeUnresolvedMethod(parameterTypesOrDefaultValues).CreateResolved(context);
}
DefaultUnresolvedMethod MakeUnresolvedMethod(params object[] parameterTypesOrDefaultValues)
{
var m = new DefaultUnresolvedMethod();
m.Name = "Method";
foreach (var typeOrDefaultValue in parameterTypesOrDefaultValues) {
Type type = typeOrDefaultValue as Type;
if (type != null)
m.Parameters.Add(new DefaultUnresolvedParameter(type.ToTypeReference(), string.Empty));
else if (Type.GetTypeCode(typeOrDefaultValue.GetType()) > TypeCode.Object)
m.Parameters.Add(new DefaultUnresolvedParameter(typeOrDefaultValue.GetType().ToTypeReference(), string.Empty) {
DefaultValue = new SimpleConstantValue(typeOrDefaultValue.GetType().ToTypeReference(), typeOrDefaultValue)
});
else
throw new ArgumentException(typeOrDefaultValue.ToString());
}
return m;
}
IMethod MakeParamsMethod(params object[] parameterTypesOrDefaultValues)
{
var m = MakeUnresolvedMethod(parameterTypesOrDefaultValues);
((DefaultUnresolvedParameter)m.Parameters.Last()).IsParams = true;
var context = new SimpleTypeResolveContext(compilation.MainAssembly);
return (IMethod)m.CreateResolved(context);
}
IUnresolvedParameter MakeOptionalParameter(ITypeReference type, string name)
{
return new DefaultUnresolvedParameter(type, name) {
DefaultValue = new SimpleConstantValue(type, null)
};
}
[Test]
public void PreferIntOverUInt()
{
OverloadResolution r = new OverloadResolution(compilation, MakeArgumentList(typeof(ushort)));
var c1 = MakeMethod(typeof(int));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(c1));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeMethod(typeof(uint))));
Assert.IsFalse(r.IsAmbiguous);
Assert.AreSame(c1, r.BestCandidate);
}
[Test]
public void PreferUIntOverLong_FromIntLiteral()
{
ResolveResult[] args = { new ConstantResolveResult(compilation.FindType(KnownTypeCode.Int32), 1) };
OverloadResolution r = new OverloadResolution(compilation, args);
var c1 = MakeMethod(typeof(uint));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(c1));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeMethod(typeof(long))));
Assert.IsFalse(r.IsAmbiguous);
Assert.AreSame(c1, r.BestCandidate);
}
[Test]
public void NullableIntAndNullableUIntIsAmbiguous()
{
OverloadResolution r = new OverloadResolution(compilation, MakeArgumentList(typeof(ushort?)));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeMethod(typeof(int?))));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeMethod(typeof(uint?))));
Assert.AreEqual(OverloadResolutionErrors.AmbiguousMatch, r.BestCandidateErrors);
// then adding a matching overload solves the ambiguity:
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeMethod(typeof(ushort?))));
Assert.AreEqual(OverloadResolutionErrors.None, r.BestCandidateErrors);
Assert.IsNull(r.BestCandidateAmbiguousWith);
}
[Test]
public void ParamsMethodMatchesEmptyArgumentList()
{
OverloadResolution r = new OverloadResolution(compilation, MakeArgumentList());
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeParamsMethod(typeof(int[]))));
Assert.IsTrue(r.BestCandidateIsExpandedForm);
}
[Test]
public void ParamsMethodMatchesOneArgumentInExpandedForm()
{
OverloadResolution r = new OverloadResolution(compilation, MakeArgumentList(typeof(int)));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeParamsMethod(typeof(int[]))));
Assert.IsTrue(r.BestCandidateIsExpandedForm);
}
[Test]
public void ParamsMethodMatchesInUnexpandedForm()
{
OverloadResolution r = new OverloadResolution(compilation, MakeArgumentList(typeof(int[])));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeParamsMethod(typeof(int[]))));
Assert.IsFalse(r.BestCandidateIsExpandedForm);
}
[Test]
public void LessArgumentsPassedToParamsIsBetter()
{
OverloadResolution r = new OverloadResolution(compilation, MakeArgumentList(typeof(int), typeof(int), typeof(int)));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeParamsMethod(typeof(int[]))));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeParamsMethod(typeof(int), typeof(int[]))));
Assert.IsFalse(r.IsAmbiguous);
Assert.AreEqual(2, r.BestCandidate.Parameters.Count);
}
[Test]
public void CallInvalidParamsDeclaration()
{
OverloadResolution r = new OverloadResolution(compilation, MakeArgumentList(typeof(int[,])));
Assert.AreEqual(OverloadResolutionErrors.ArgumentTypeMismatch, r.AddCandidate(MakeParamsMethod(typeof(int))));
Assert.IsFalse(r.BestCandidateIsExpandedForm);
}
[Test]
public void PreferMethodWithoutOptionalParameters()
{
var m1 = MakeMethod();
var m2 = MakeMethod(1);
OverloadResolution r = new OverloadResolution(compilation, MakeArgumentList());
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(m1));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(m2));
Assert.IsFalse(r.IsAmbiguous);
Assert.AreSame(m1, r.BestCandidate);
}
[Test]
public void SkeetEvilOverloadResolution()
{
// http://msmvps.com/blogs/jon_skeet/archive/2010/11/02/evil-code-overload-resolution-workaround.aspx
// static void Foo<T>(T? ignored = default(T?)) where T : struct
var m1 = MakeUnresolvedMethod();
m1.TypeParameters.Add(new DefaultUnresolvedTypeParameter(SymbolKind.Method, 0, "T") { HasValueTypeConstraint = true });
m1.Parameters.Add(MakeOptionalParameter(
NullableType.Create(new TypeParameterReference(SymbolKind.Method, 0)),
"ignored"
));
// class ClassConstraint<T> where T : class {}
var classConstraint = new DefaultUnresolvedTypeDefinition(string.Empty, "ClassConstraint");
classConstraint.TypeParameters.Add(new DefaultUnresolvedTypeParameter(SymbolKind.TypeDefinition, 0, "T") { HasReferenceTypeConstraint = true });
// static void Foo<T>(ClassConstraint<T> ignored = default(ClassConstraint<T>))
// where T : class
var m2 = MakeUnresolvedMethod();
m2.TypeParameters.Add(new DefaultUnresolvedTypeParameter(SymbolKind.Method, 0, "T") { HasReferenceTypeConstraint = true });
m2.Parameters.Add(MakeOptionalParameter(
new ParameterizedTypeReference(classConstraint, new[] { new TypeParameterReference(SymbolKind.Method, 0) }),
"ignored"
));
// static void Foo<T>()
var m3 = MakeUnresolvedMethod();
m3.TypeParameters.Add(new DefaultUnresolvedTypeParameter(SymbolKind.Method, 0, "T"));
ICompilation compilation = TypeSystemHelper.CreateCompilation(classConstraint);
var context = new SimpleTypeResolveContext(compilation.MainAssembly);
IMethod resolvedM1 = (IMethod)m1.CreateResolved(context);
IMethod resolvedM2 = (IMethod)m2.CreateResolved(context);
IMethod resolvedM3 = (IMethod)m3.CreateResolved(context);
// Call: Foo<int>();
OverloadResolution o;
o = new OverloadResolution(compilation, new ResolveResult[0], typeArguments: new[] { compilation.FindType(typeof(int)) });
Assert.AreEqual(OverloadResolutionErrors.None, o.AddCandidate(resolvedM1));
Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(resolvedM2));
Assert.AreSame(resolvedM1, o.BestCandidate);
// Call: Foo<string>();
o = new OverloadResolution(compilation, new ResolveResult[0], typeArguments: new[] { compilation.FindType(typeof(string)) });
Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(resolvedM1));
Assert.AreEqual(OverloadResolutionErrors.None, o.AddCandidate(resolvedM2));
Assert.AreSame(resolvedM2, o.BestCandidate);
// Call: Foo<int?>();
o = new OverloadResolution(compilation, new ResolveResult[0], typeArguments: new[] { compilation.FindType(typeof(int?)) });
Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(resolvedM1));
Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(resolvedM2));
Assert.AreEqual(OverloadResolutionErrors.None, o.AddCandidate(resolvedM3));
Assert.AreSame(resolvedM3, o.BestCandidate);
}
/// <summary>
/// A lambda of the form "() => default(returnType)"
/// </summary>
class MockLambda : LambdaResolveResult
{
IType inferredReturnType;
List<IParameter> parameters = new List<IParameter>();
public MockLambda(IType returnType)
{
this.inferredReturnType = returnType;
}
public override IList<IParameter> Parameters {
get { return parameters; }
}
public override Conversion IsValid(IType[] parameterTypes, IType returnType, CSharpConversions conversions)
{
return conversions.ImplicitConversion(inferredReturnType, returnType);
}
public override bool IsImplicitlyTyped {
get { return false; }
}
public override bool IsAnonymousMethod {
get { return false; }
}
public override bool HasParameterList {
get { return true; }
}
public override bool IsAsync {
get { return false; }
}
public override ResolveResult Body {
get { throw new NotImplementedException(); }
}
public override IType ReturnType {
get { throw new NotImplementedException(); }
}
public override IType GetInferredReturnType(IType[] parameterTypes)
{
return inferredReturnType;
}
}
[Test]
public void BetterConversionByLambdaReturnValue()
{
var m1 = MakeMethod(typeof(Func<long>));
var m2 = MakeMethod(typeof(Func<int>));
// M(() => default(byte));
ResolveResult[] args = {
new MockLambda(compilation.FindType(KnownTypeCode.Byte))
};
OverloadResolution r = new OverloadResolution(compilation, args);
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(m1));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(m2));
Assert.AreSame(m2, r.BestCandidate);
Assert.AreEqual(OverloadResolutionErrors.None, r.BestCandidateErrors);
}
[Test]
public void BetterConversionByLambdaReturnValue_ExpressionTree()
{
var m1 = MakeMethod(typeof(Func<long>));
var m2 = MakeMethod(typeof(Expression<Func<int>>));
// M(() => default(byte));
ResolveResult[] args = {
new MockLambda(compilation.FindType(KnownTypeCode.Byte))
};
OverloadResolution r = new OverloadResolution(compilation, args);
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(m1));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(m2));
Assert.AreSame(m2, r.BestCandidate);
Assert.AreEqual(OverloadResolutionErrors.None, r.BestCandidateErrors);
}
[Test]
public void Lambda_DelegateAndExpressionTreeOverloadsAreAmbiguous()
{
var m1 = MakeMethod(typeof(Func<int>));
var m2 = MakeMethod(typeof(Expression<Func<int>>));
// M(() => default(int));
ResolveResult[] args = {
new MockLambda(compilation.FindType(KnownTypeCode.Int32))
};
OverloadResolution r = new OverloadResolution(compilation, args);
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(m1));
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(m2));
Assert.AreEqual(OverloadResolutionErrors.AmbiguousMatch, r.BestCandidateErrors);
}
[Test, Ignore("Overload Resolution bug")]
public void BetterFunctionMemberIsNotTransitive()
{
string program = @"using System;
class Program
{
static void Method(Action<string> a) {}
static void Method<T>(Func<string, T> a) {}
static void Method(Action<object> a) {}
static void Method<T>(Func<object, T> a) {}
public static void Main(string[] args)
{
$Method(a => a.ToString())$;
}
}";
var rr = Resolve<CSharpInvocationResolveResult>(program);
Assert.AreEqual(OverloadResolutionErrors.AmbiguousMatch, rr.OverloadResolutionErrors);
}
}
}
| gpl-2.0 |
AftonTroll/WordPress-Android | WordPress/src/androidTest/monkeys/playstore-screenshots.py | 6139 | #! /usr/bin/env python
import sys
import os
import time
import settings
from subprocess import Popen, PIPE
from com.dtmilano.android.viewclient import ViewClient
# App actions
def action_login(device, serialno):
print("login")
device.type(settings.username)
device.press('KEYCODE_DPAD_DOWN')
device.type(settings.password)
device.press('KEYCODE_ENTER')
# time to login
time.sleep(10)
# lose focus
device.press('KEYCODE_DPAD_DOWN')
time.sleep(1)
def action_open_my_sites(device, serialno):
print("open my sites")
device.press('KEYCODE_TAB')
for i in range(5):
device.press('KEYCODE_DPAD_LEFT')
# Wait for gravatars to load
time.sleep(2)
def action_open_reader_freshlypressed(device, serialno):
print("open reader")
# Open the reader
for i in range(5):
device.press('KEYCODE_DPAD_LEFT')
device.press('KEYCODE_DPAD_RIGHT')
device.press('KEYCODE_ENTER')
# Wait for the reader to load articles / pictures
time.sleep(5)
def action_open_notifications(device, serialno):
print("open notifications tab")
# Open the reader
for i in range(5):
device.press('KEYCODE_DPAD_LEFT')
for i in range(4):
device.press('KEYCODE_DPAD_RIGHT')
device.press('KEYCODE_ENTER')
time.sleep(5)
def action_open_me(device, serialno):
print("open me tab")
# Open the reader
for i in range(5):
device.press('KEYCODE_DPAD_LEFT')
for i in range(2):
device.press('KEYCODE_DPAD_RIGHT')
device.press('KEYCODE_ENTER')
time.sleep(5)
def action_open_editor_and_type_text(device, serialno):
print("open editor")
# Open My Sites
for i in range(5):
device.press('KEYCODE_DPAD_LEFT')
# Select FAB and open the editor
device.press('KEYCODE_DPAD_DOWN')
device.press('KEYCODE_ENTER')
time.sleep(1)
# Type a sample text (spaces can't be entered via device.type())
for word in settings.example_post_content.split():
device.type(word)
device.press('KEYCODE_SPACE')
# Open virtual keyboard by touching the screen
viewclient = ViewClient(device, serialno)
view = viewclient.findViewWithText(settings.example_post_content)
view.touch()
time.sleep(1)
# Utilities
def lose_focus(serialno):
# tap point 0,0 to lose focus
_adb_shell(serialno, " input tap 0 0")
time.sleep(1)
def take_screenshot(serialno, filename):
os.popen("adb -s '%s' shell /system/bin/screencap -p /sdcard/screenshot.png" % (serialno))
os.popen("adb -s '%s' pull /sdcard/screenshot.png '%s'" % (serialno, filename))
def launch_activity(device, package, activity):
component = package + "/" + activity
FLAG_ACTIVITY_NEW_TASK = 0x10000000
device.startActivity(component=component, flags=FLAG_ACTIVITY_NEW_TASK)
time.sleep(2)
def _adb_shell(serialno, command):
print("adb -s '%s' shell \"%s\"" % (serialno, command))
os.popen("adb -s '%s' shell \"%s\"" % (serialno, command))
def change_lang_settings(serialno, lang):
adb_command = "su -c 'setprop persist.sys.language %s; setprop persist.sys.country %s; stop; start'"
_adb_shell(serialno, adb_command % (lang, lang))
# time to reload
time.sleep(15)
unlock_screen(serialno)
def unlock_screen(serialno):
_adb_shell(serialno, "input keyevent 82")
time.sleep(1)
def reinstall_apk(serialno, packagename, apk):
os.popen("adb -s '%s' uninstall '%s'" % (serialno, packagename))
os.popen("adb -s '%s' install '%s'" % (serialno, apk))
def back(device):
device.press('KEYCODE_BACK')
# Main scenario + screenshots
def run_tests_for_device_and_lang(device, serialno, filename, lang, packagename, apk):
# Install the apk`
reinstall_apk(serialno, packagename, apk)
# Change language setting
change_lang_settings(serialno, lang)
# Launch the app
launch_activity(device, packagename, "org.wordpress.android.ui.WPLaunchActivity")
take_screenshot(serialno, lang + "-login-screen-" + filename)
# Login into the app
action_login(device, serialno)
# Action!
action_open_my_sites(device, serialno)
take_screenshot(serialno, lang + "-1-my-sites-" + filename)
action_open_reader_freshlypressed(device, serialno)
take_screenshot(serialno, lang + "-2-reader-freshlypressed-" + filename)
action_open_me(device, serialno)
take_screenshot(serialno, lang + "-3-me-tab-" + filename)
action_open_notifications(device, serialno)
take_screenshot(serialno, lang + "-4-notifications-" + filename)
#action_open_editor_and_type_text(device, serialno)
#take_screenshot(serialno, lang + "-editor-" + filename)
# Close virtual keyboard and editor
#back(device)
#back(device)
def list_devices():
devices = []
process = Popen("adb devices -l", stdout=PIPE, shell=True)
for line in iter(process.stdout.readline, ''):
split = line.split()
if len(split) <= 1 or split[0] == "List":
continue
devices.append({"name": split[3].replace("model:", ""), "serialno": split[0]})
process.communicate()
return devices
def run_tests_on_device(packagename, apk, serialno, name, lang):
device, serialno = ViewClient.connectToDeviceOrExit(verbose=False, serialno=serialno)
filename = name + ".png"
run_tests_for_device_and_lang(device, serialno, filename, lang, packagename, apk)
def run_tests_on_all_devices(packagename, apk, lang):
devices = list_devices()
if not devices:
print("No device found")
return
for device in devices:
print("Running on %s - language: %s" % (device, lang))
run_tests_on_device(packagename, apk, device["serialno"], device["name"], lang)
def run_tests_on_all_devices_for_all_languages(packagename, apk):
for lang in settings.languages:
run_tests_on_all_devices(packagename, apk, lang)
def main():
if len(sys.argv) < 3:
sys.exit("usage: %s packagename apk" % sys.argv[0])
packagename = sys.argv.pop(1)
apk = sys.argv.pop(1)
run_tests_on_all_devices_for_all_languages(packagename, apk)
main()
| gpl-2.0 |
YouDiSN/OpenJDK-Research | jdk9/jdk/src/jdk.localedata/share/classes/sun/text/resources/ext/FormatData_sv.java | 11341 | /*
* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
/*
* COPYRIGHT AND PERMISSION NOTICE
*
* Copyright (C) 1991-2012 Unicode, Inc. All rights reserved. Distributed under
* the Terms of Use in http://www.unicode.org/copyright.html.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of the Unicode data files and any associated documentation (the "Data
* Files") or Unicode software and any associated documentation (the
* "Software") to deal in the Data Files or Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Data Files or Software, and
* to permit persons to whom the Data Files or Software are furnished to do so,
* provided that (a) the above copyright notice(s) and this permission notice
* appear with all copies of the Data Files or Software, (b) both the above
* copyright notice(s) and this permission notice appear in associated
* documentation, and (c) there is clear notice in each modified Data File or
* in the Software as well as in the documentation associated with the Data
* File(s) or Software that the data or software has been modified.
*
* THE DATA FILES AND SOFTWARE ARE 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR
* CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THE DATA FILES OR SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder shall not
* be used in advertising or otherwise to promote the sale, use or other
* dealings in these Data Files or Software without prior written authorization
* of the copyright holder.
*/
package sun.text.resources.ext;
import sun.util.resources.ParallelListResourceBundle;
public class FormatData_sv extends ParallelListResourceBundle {
/**
* Overrides ParallelListResourceBundle
*/
@Override
protected final Object[][] getContents() {
final String[] rocEras = {
"f\u00f6re R.K.",
"R.K.",
};
return new Object[][] {
{ "MonthNames",
new String[] {
"januari", // january
"februari", // february
"mars", // march
"april", // april
"maj", // may
"juni", // june
"juli", // july
"augusti", // august
"september", // september
"oktober", // october
"november", // november
"december", // december
"" // month 13 if applicable
}
},
{ "MonthNarrows",
new String[] {
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D",
"",
}
},
{ "MonthAbbreviations",
new String[] {
"jan", // abb january
"feb", // abb february
"mar", // abb march
"apr", // abb april
"maj", // abb may
"jun", // abb june
"jul", // abb july
"aug", // abb august
"sep", // abb september
"okt", // abb october
"nov", // abb november
"dec", // abb december
"" // abb month 13 if applicable
}
},
{ "standalone.MonthAbbreviations",
new String[] {
"jan",
"feb",
"mar",
"apr",
"maj",
"jun",
"jul",
"aug",
"sep",
"okt",
"nov",
"dec",
"",
}
},
{ "standalone.MonthNarrows",
new String[] {
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D",
"",
}
},
{ "DayNames",
new String[] {
"s\u00f6ndag", // Sunday
"m\u00e5ndag", // Monday
"tisdag", // Tuesday
"onsdag", // Wednesday
"torsdag", // Thursday
"fredag", // Friday
"l\u00f6rdag" // Saturday
}
},
{ "DayAbbreviations",
new String[] {
"s\u00f6", // abb Sunday
"m\u00e5", // abb Monday
"ti", // abb Tuesday
"on", // abb Wednesday
"to", // abb Thursday
"fr", // abb Friday
"l\u00f6" // abb Saturday
}
},
{ "standalone.DayAbbreviations",
new String[] {
"s\u00f6n",
"m\u00e5n",
"tis",
"ons",
"tor",
"fre",
"l\u00f6r",
}
},
{ "DayNarrows",
new String[] {
"S",
"M",
"T",
"O",
"T",
"F",
"L",
}
},
{ "standalone.DayNames",
new String[] {
"s\u00f6ndag",
"m\u00e5ndag",
"tisdag",
"onsdag",
"torsdag",
"fredag",
"l\u00f6rdag",
}
},
{ "standalone.DayNarrows",
new String[] {
"S",
"M",
"T",
"O",
"T",
"F",
"L",
}
},
{ "Eras",
new String[] {
"f\u00f6re Kristus",
"efter Kristus",
}
},
{ "short.Eras",
new String[] {
"f.Kr.",
"e.Kr.",
}
},
{ "narrow.Eras",
new String[] {
"f.Kr.",
"e.Kr.",
}
},
{ "AmPmMarkers",
new String[] {
"fm", // am marker
"em" // pm marker
}
},
{ "narrow.AmPmMarkers",
new String[] {
"f",
"e",
}
},
{ "NumberPatterns",
new String[] {
"#,##0.###;-#,##0.###", // decimal pattern
"\u00a4 #,##0.00;-\u00a4 #,##0.00", // currency pattern
"#,##0 %" // percent pattern
}
},
{ "NumberElements",
new String[] {
",", // decimal separator
"\u00a0", // group (thousands) separator
";", // list separator
"%", // percent sign
"0", // native 0 digit
"#", // pattern digit
"-", // minus sign
"E", // exponential
"\u2030", // per mille
"\u221e", // infinity
"\ufffd" // NaN
}
},
{ "TimePatterns",
new String[] {
"'kl 'H:mm z", // full time pattern
"HH:mm:ss z", // long time pattern
"HH:mm:ss", // medium time pattern
"HH:mm", // short time pattern
}
},
{ "DatePatterns",
new String[] {
"'den 'd MMMM yyyy", // full date pattern
"'den 'd MMMM yyyy", // long date pattern
"yyyy-MMM-dd", // medium date pattern
"yyyy-MM-dd", // short date pattern
}
},
{ "DateTimePatterns",
new String[] {
"{1} {0}" // date-time pattern
}
},
{ "DateTimePatternChars", "GyMdkHmsSEDFwWahKzZ" },
};
}
}
| gpl-2.0 |
ingagecreative/cg | wp-content/plugins/constant-contact-api/vendor/giggsey/libphonenumber-for-php/src/libphonenumber/geocoding/data/en/8627.php | 172 | <?php
/**
* This file is automatically @generated by {@link GeneratePhonePrefixData}.
* Please don't modify it directly.
*/
return array (
8627 => 'Wuhan, Hubei',
);
| gpl-2.0 |
gargsuchi/services-listener | core/modules/views/src/Plugin/views/display/Block.php | 11993 | <?php
/**
* @file
* Contains \Drupal\views\Plugin\views\display\Block.
*/
namespace Drupal\views\Plugin\views\display;
use Drupal\Component\Utility\String;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\Block\ViewsBlock;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* The plugin that handles a block.
*
* @ingroup views_display_plugins
*
* @ViewsDisplay(
* id = "block",
* title = @Translation("Block"),
* help = @Translation("Display the view as a block."),
* theme = "views_view",
* register_theme = FALSE,
* uses_hook_block = TRUE,
* contextual_links_locations = {"block"},
* admin = @Translation("Block")
* )
*
* @see \Drupal\views\Plugin\block\block\ViewsBlock
* @see \Drupal\views\Plugin\Derivative\ViewsBlock
*/
class Block extends DisplayPluginBase {
/**
* Whether the display allows attachments.
*
* @var bool
*/
protected $usesAttachments = TRUE;
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* Constructs a new Block instance.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityManager = $entity_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity.manager')
);
}
/**
* {@inheritdoc}
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['block_description'] = array('default' => '');
$options['block_category'] = array('default' => 'Lists (Views)');
$options['block_hide_empty'] = array('default' => FALSE);
$options['allow'] = array(
'contains' => array(
'items_per_page' => array('default' => 'items_per_page'),
),
);
return $options;
}
/**
* Returns plugin-specific settings for the block.
*
* @param array $settings
* The settings of the block.
*
* @return array
* An array of block-specific settings to override the defaults provided in
* \Drupal\views\Plugin\Block\ViewsBlock::defaultConfiguration().
*
* @see \Drupal\views\Plugin\Block\ViewsBlock::defaultConfiguration()
*/
public function blockSettings(array $settings) {
$settings['items_per_page'] = 'none';
return $settings;
}
/**
* The display block handler returns the structure necessary for a block.
*/
public function execute() {
// Prior to this being called, the $view should already be set to this
// display, and arguments should be set on the view.
$element = $this->view->render();
if ($this->outputIsEmpty() && $this->getOption('block_hide_empty') && empty($this->view->style_plugin->definition['even empty'])) {
return array();
}
else {
return $element;
}
}
/**
* Provide the summary for page options in the views UI.
*
* This output is returned as an array.
*/
public function optionsSummary(&$categories, &$options) {
parent::optionsSummary($categories, $options);
$categories['block'] = array(
'title' => $this->t('Block settings'),
'column' => 'second',
'build' => array(
'#weight' => -10,
),
);
$block_description = strip_tags($this->getOption('block_description'));
if (empty($block_description)) {
$block_description = $this->t('None');
}
$block_category = String::checkPlain($this->getOption('block_category'));
$options['block_description'] = array(
'category' => 'block',
'title' => $this->t('Block name'),
'value' => views_ui_truncate($block_description, 24),
);
$options['block_category'] = array(
'category' => 'block',
'title' => $this->t('Block category'),
'value' => views_ui_truncate($block_category, 24),
);
$filtered_allow = array_filter($this->getOption('allow'));
$options['allow'] = array(
'category' => 'block',
'title' => $this->t('Allow settings'),
'value' => empty($filtered_allow) ? $this->t('None') : $this->t('Items per page'),
);
$options['block_hide_empty'] = array(
'category' => 'other',
'title' => $this->t('Hide block if the view output is empty'),
'value' => $this->getOption('block_hide_empty') ? $this->t('Hide') : $this->t('Show'),
);
}
/**
* Provide the default form for setting options.
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
switch ($form_state->get('section')) {
case 'block_description':
$form['#title'] .= $this->t('Block admin description');
$form['block_description'] = array(
'#type' => 'textfield',
'#description' => $this->t('This will appear as the name of this block in administer >> structure >> blocks.'),
'#default_value' => $this->getOption('block_description'),
);
break;
case 'block_category':
$form['#title'] .= $this->t('Block category');
$form['block_category'] = array(
'#type' => 'textfield',
'#autocomplete_route_name' => 'block.category_autocomplete',
'#description' => $this->t('The category this block will appear under on the <a href="@href">blocks placement page</a>.', array('@href' => \Drupal::url('block.admin_display'))),
'#default_value' => $this->getOption('block_category'),
);
break;
case 'block_hide_empty':
$form['#title'] .= $this->t('Block empty settings');
$form['block_hide_empty'] = array(
'#title' => $this->t('Hide block if no result/empty text'),
'#type' => 'checkbox',
'#description' => $this->t('Hide the block if there is no result and no empty text and no header/footer which is shown on empty result'),
'#default_value' => $this->getOption('block_hide_empty'),
);
break;
case 'exposed_form_options':
$this->view->initHandlers();
if (!$this->usesExposed() && parent::usesExposed()) {
$form['exposed_form_options']['warning'] = array(
'#weight' => -10,
'#markup' => '<div class="messages messages--warning">' . $this->t('Exposed filters in block displays require "Use AJAX" to be set to work correctly.') . '</div>',
);
}
break;
case 'allow':
$form['#title'] .= $this->t('Allow settings in the block configuration');
$options = array(
'items_per_page' => $this->t('Items per page'),
);
$allow = array_filter($this->getOption('allow'));
$form['allow'] = array(
'#type' => 'checkboxes',
'#default_value' => $allow,
'#options' => $options,
);
break;
}
}
/**
* Perform any necessary changes to the form values prior to storage.
* There is no need for this function to actually store the data.
*/
public function submitOptionsForm(&$form, FormStateInterface $form_state) {
parent::submitOptionsForm($form, $form_state);
$section = $form_state->get('section');
switch ($section) {
case 'block_description':
case 'block_category':
case 'allow':
case 'block_hide_empty':
$this->setOption($section, $form_state->getValue($section));
break;
}
}
/**
* Adds the configuration form elements specific to this views block plugin.
*
* This method allows block instances to override the views items_per_page.
*
* @param \Drupal\views\Plugin\Block\ViewsBlock $block
* The ViewsBlock plugin.
* @param array $form
* The form definition array for the block configuration form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @return array $form
* The renderable form array representing the entire configuration form.
*
* @see \Drupal\views\Plugin\Block\ViewsBlock::blockForm()
*/
public function blockForm(ViewsBlock $block, array &$form, FormStateInterface $form_state) {
$allow_settings = array_filter($this->getOption('allow'));
$block_configuration = $block->getConfiguration();
foreach ($allow_settings as $type => $enabled) {
if (empty($enabled)) {
continue;
}
switch ($type) {
case 'items_per_page':
$form['override']['items_per_page'] = array(
'#type' => 'select',
'#title' => $this->t('Items per block'),
'#options' => array(
'none' => $this->t('@count (default setting)', array('@count' => $this->getPlugin('pager')->getItemsPerPage())),
5 => 5,
10 => 10,
20 => 20,
40 => 40,
),
'#default_value' => $block_configuration['items_per_page'],
);
break;
}
}
return $form;
}
/**
* Handles form validation for the views block configuration form.
*
* @param \Drupal\views\Plugin\Block\ViewsBlock $block
* The ViewsBlock plugin.
* @param array $form
* The form definition array for the block configuration form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @see \Drupal\views\Plugin\Block\ViewsBlock::blockValidate()
*/
public function blockValidate(ViewsBlock $block, array $form, FormStateInterface $form_state) {
}
/**
* Handles form submission for the views block configuration form.
*
* @param \Drupal\views\Plugin\Block\ViewsBlock $block
* The ViewsBlock plugin.
* @param array $form
* The form definition array for the full block configuration form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* * @see \Drupal\views\Plugin\Block\ViewsBlock::blockSubmit()
*/
public function blockSubmit(ViewsBlock $block, $form, FormStateInterface $form_state) {
if ($items_per_page = $form_state->getValue(array('override', 'items_per_page'))) {
$block->setConfigurationValue('items_per_page', $items_per_page);
}
$form_state->unsetValue(array('override', 'items_per_page'));
}
/**
* Allows to change the display settings right before executing the block.
*
* @param \Drupal\views\Plugin\Block\ViewsBlock $block
* The block plugin for views displays.
*/
public function preBlockBuild(ViewsBlock $block) {
$config = $block->getConfiguration();
if ($config['items_per_page'] !== 'none') {
$this->view->setItemsPerPage($config['items_per_page']);
}
}
/**
* Block views use exposed widgets only if AJAX is set.
*/
public function usesExposed() {
if ($this->ajaxEnabled()) {
return parent::usesExposed();
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function remove() {
parent::remove();
if ($this->entityManager->hasDefinition('block')) {
$plugin_id = 'views_block:' . $this->view->storage->id() . '-' . $this->display['id'];
foreach ($this->entityManager->getStorage('block')->loadByProperties(['plugin' => $plugin_id]) as $block) {
$block->delete();
}
}
}
}
| gpl-2.0 |
cccp/xy-VSFilter | src/apps/mplayerc/FileDropTarget.cpp | 2544 | /*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
* 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, 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 GNU Make; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
// FileDropTarget.cpp : implementation file
//
#include "stdafx.h"
#include "mplayerc.h"
#include "FileDropTarget.h"
// CFileDropTarget
//IMPLEMENT_DYNAMIC(CFileDropTarget, COleDropTarget)
CFileDropTarget::CFileDropTarget(CDropTarget* pDropTarget)
: m_pDropTarget(pDropTarget)
{
ASSERT(m_pDropTarget);
}
CFileDropTarget::~CFileDropTarget()
{
}
DROPEFFECT CFileDropTarget::OnDragEnter(CWnd* pWnd, COleDataObject* pDataObject, DWORD dwKeyState, CPoint point)
{
return m_pDropTarget ? m_pDropTarget->OnDragEnter(pDataObject, dwKeyState, point) : DROPEFFECT_NONE;
}
DROPEFFECT CFileDropTarget::OnDragOver(CWnd* pWnd, COleDataObject* pDataObject, DWORD dwKeyState, CPoint point)
{
return m_pDropTarget ? m_pDropTarget->OnDragOver(pDataObject, dwKeyState, point) : DROPEFFECT_NONE;
}
BOOL CFileDropTarget::OnDrop(CWnd* pWnd, COleDataObject* pDataObject, DROPEFFECT dropEffect, CPoint point)
{
return m_pDropTarget ? m_pDropTarget->OnDrop(pDataObject, dropEffect, point) : DROPEFFECT_NONE;
}
DROPEFFECT CFileDropTarget::OnDropEx(CWnd* pWnd, COleDataObject* pDataObject, DROPEFFECT dropDefault, DROPEFFECT dropList, CPoint point)
{
return m_pDropTarget ? m_pDropTarget->OnDropEx(pDataObject, dropDefault, dropList, point) : DROPEFFECT_NONE;
}
void CFileDropTarget::OnDragLeave(CWnd* pWnd)
{
if(m_pDropTarget) m_pDropTarget->OnDragLeave();
}
DROPEFFECT CFileDropTarget::OnDragScroll(CWnd* pWnd, DWORD dwKeyState, CPoint point)
{
return m_pDropTarget ? m_pDropTarget->OnDragScroll(dwKeyState, point) : DROPEFFECT_NONE;
}
BEGIN_MESSAGE_MAP(CFileDropTarget, COleDropTarget)
END_MESSAGE_MAP()
// CFileDropTarget message handlers
| gpl-2.0 |
drcrane/fred | src/freenet/support/compress/TooBigDictionaryException.java | 168 | package freenet.support.compress;
public class TooBigDictionaryException extends InvalidCompressedDataException {
private static final long serialVersionUID = -1L;
}
| gpl-2.0 |
Fusselwurm/ACE3 | addons/reload/CfgMagazines.hpp | 711 | class CfgMagazines {
class CA_Magazine;
class 150Rnd_762x51_Box: CA_Magazine { // Mag for Negev (LMG_Zafir) - 150Rnd_762x54_Box inherits from this
ACE_isBelt = 1;
};
class 100Rnd_65x39_caseless_mag;
class 200Rnd_65x39_cased_Box: 100Rnd_65x39_caseless_mag { // Mag for Stoner (LMG_Mk200)
ACE_isBelt = 1;
};
class 150Rnd_93x64_Mag: CA_Magazine { // Mag for HK121 (MMG_01) [DLC Opfor Heavy Gunner]
ACE_isBelt = 1;
};
class 130Rnd_338_Mag: CA_Magazine { // Mag for LWMMG (MMG_02) [DLC Blufor Heavy Gunner]
ACE_isBelt = 1;
};
class 200Rnd_556x45_Box_F: CA_Magazine { // Mag for M249 SAW (LMG_03) [Tanoa]
ACE_isBelt = 1;
};
};
| gpl-2.0 |
maegibbons/librenms | includes/discovery/os/radlan.inc.php | 214 | <?php
if (!$os)
{
if (strstr($sysDescr, "Neyland 24T")) { $os = "radlan"; } /* Dell Powerconnect 5324 */
if (strstr($sysDescr, "AT-8000")) { $os = "radlan"; } /* Allied Telesis AT-8000 */
}
?> | gpl-3.0 |
tumbl3w33d/ansible | lib/ansible/modules/cloud/digital_ocean/digital_ocean_sshkey_info.py | 2469 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = '''
---
module: digital_ocean_sshkey_info
short_description: Gather information about DigitalOcean SSH keys
description:
- This module can be used to gather information about DigitalOcean SSH keys.
- This module replaces the C(digital_ocean_sshkey_facts) module.
version_added: "2.9"
author: "Patrick Marques (@pmarques)"
extends_documentation_fragment: digital_ocean.documentation
notes:
- Version 2 of DigitalOcean API is used.
requirements:
- "python >= 2.6"
'''
EXAMPLES = '''
- digital_ocean_sshkey_info:
oauth_token: "{{ my_do_key }}"
register: ssh_keys
- set_fact:
pubkey: "{{ item.public_key }}"
loop: "{{ ssh_keys.data|json_query(ssh_pubkey) }}"
vars:
ssh_pubkey: "[?name=='ansible_ctrl']"
- debug:
msg: "{{ pubkey }}"
'''
RETURN = '''
# Digital Ocean API info https://developers.digitalocean.com/documentation/v2/#list-all-keys
data:
description: List of SSH keys on DigitalOcean
returned: success and no resource constraint
type: dict
sample: [
{
"id": 512189,
"fingerprint": "3b:16:bf:e4:8b:00:8b:b8:59:8c:a9:d3:f0:19:45:fa",
"public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQDDHr/jh2Jy4yALcK4JyWbVkPRaWmhck3IgCoeOO3z1e2dBowLh64QAM+Qb72pxekALga2oi4GvT+TlWNhzPH4V example",
"name": "My SSH Public Key"
}
]
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.digital_ocean import DigitalOceanHelper
def core(module):
rest = DigitalOceanHelper(module)
response = rest.get("account/keys")
status_code = response.status_code
json = response.json
if status_code == 200:
module.exit_json(changed=False, data=json['ssh_keys'])
else:
module.fail_json(msg='Error fetching SSH Key information [{0}: {1}]'.format(
status_code, response.json['message']))
def main():
module = AnsibleModule(
argument_spec=DigitalOceanHelper.digital_ocean_argument_spec(),
supports_check_mode=True,
)
core(module)
if __name__ == '__main__':
main()
| gpl-3.0 |
benjaminabel/pelican-plugins | assets/test_assets.py | 3831 | # -*- coding: utf-8 -*-
# from __future__ import unicode_literals
import hashlib
import locale
import os
from codecs import open
from tempfile import mkdtemp
from shutil import rmtree
import unittest
import subprocess
from pelican import Pelican
from pelican.settings import read_settings
from pelican.tests.support import mute, skipIfNoExecutable, module_exists
CUR_DIR = os.path.dirname(__file__)
THEME_DIR = os.path.join(CUR_DIR, 'test_data')
CSS_REF = open(os.path.join(THEME_DIR, 'static', 'css',
'style.min.css')).read()
CSS_HASH = hashlib.md5(CSS_REF).hexdigest()[0:8]
@unittest.skipUnless(module_exists('webassets'), "webassets isn't installed")
@skipIfNoExecutable(['scss', '-v'])
@skipIfNoExecutable(['cssmin', '--version'])
class TestWebAssets(unittest.TestCase):
"""Base class for testing webassets."""
def setUp(self, override=None):
import assets
self.temp_path = mkdtemp(prefix='pelicantests.')
settings = {
'PATH': os.path.join(os.path.dirname(CUR_DIR), 'test_data', 'content'),
'OUTPUT_PATH': self.temp_path,
'PLUGINS': [assets],
'THEME': THEME_DIR,
'LOCALE': locale.normalize('en_US'),
'CACHE_CONTENT': False
}
if override:
settings.update(override)
self.settings = read_settings(override=settings)
pelican = Pelican(settings=self.settings)
mute(True)(pelican.run)()
def tearDown(self):
rmtree(self.temp_path)
def check_link_tag(self, css_file, html_file):
"""Check the presence of `css_file` in `html_file`."""
link_tag = ('<link rel="stylesheet" href="{css_file}">'
.format(css_file=css_file))
html = open(html_file).read()
self.assertRegexpMatches(html, link_tag)
class TestWebAssetsRelativeURLS(TestWebAssets):
"""Test pelican with relative urls."""
def setUp(self):
TestWebAssets.setUp(self, override={'RELATIVE_URLS': True})
def test_jinja2_ext(self):
# Test that the Jinja2 extension was correctly added.
from webassets.ext.jinja2 import AssetsExtension
self.assertIn(AssetsExtension, self.settings['JINJA_ENVIRONMENT']['extensions'])
def test_compilation(self):
# Compare the compiled css with the reference.
gen_file = os.path.join(self.temp_path, 'theme', 'gen',
'style.{0}.min.css'.format(CSS_HASH))
self.assertTrue(os.path.isfile(gen_file))
css_new = open(gen_file).read()
self.assertEqual(css_new, CSS_REF)
def test_template(self):
# Look in the output files for the link tag.
css_file = './theme/gen/style.{0}.min.css'.format(CSS_HASH)
html_files = ['index.html', 'archives.html',
'this-is-a-super-article.html']
for f in html_files:
self.check_link_tag(css_file, os.path.join(self.temp_path, f))
self.check_link_tag(
'../theme/gen/style.{0}.min.css'.format(CSS_HASH),
os.path.join(self.temp_path, 'category/yeah.html'))
class TestWebAssetsAbsoluteURLS(TestWebAssets):
"""Test pelican with absolute urls."""
def setUp(self):
TestWebAssets.setUp(self, override={'RELATIVE_URLS': False,
'SITEURL': 'http://localhost'})
def test_absolute_url(self):
# Look in the output files for the link tag with absolute url.
css_file = ('http://localhost/theme/gen/style.{0}.min.css'
.format(CSS_HASH))
html_files = ['index.html', 'archives.html',
'this-is-a-super-article.html']
for f in html_files:
self.check_link_tag(css_file, os.path.join(self.temp_path, f))
| agpl-3.0 |
havicon/mastodon | app/workers/pubsubhubbub/subscribe_worker.rb | 301 | # frozen_string_literal: true
class Pubsubhubbub::SubscribeWorker
include Sidekiq::Worker
sidekiq_options queue: 'push'
def perform(account_id)
account = Account.find(account_id)
logger.debug "PuSH re-subscribing to #{account.acct}"
::SubscribeService.new.call(account)
end
end
| agpl-3.0 |
sferich888/origin | vendor/github.com/alexbrainman/sspi/schannel/schannel_test.go | 1925 | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build windows
package schannel_test
import (
"fmt"
"io/ioutil"
"net"
"testing"
"github.com/alexbrainman/sspi/schannel"
)
func TestPackageInfo(t *testing.T) {
want := "Microsoft Unified Security Protocol Provider"
if schannel.PackageInfo.Name != want {
t.Fatalf(`invalid Schannel package name of %q, %q is expected.`, schannel.PackageInfo.Name, want)
}
}
func TestSchannel(t *testing.T) {
cred, err := schannel.AcquireClientCredentials()
if err != nil {
t.Fatal(err)
}
defer cred.Release()
conn, err := net.Dial("tcp", "microsoft.com:https")
if err != nil {
t.Fatal(err)
}
defer conn.Close()
client := schannel.NewClientContext(cred, conn)
err = client.Handshake("microsoft.com")
if err != nil {
t.Fatal(err)
}
protoName, major, minor, err := client.ProtocolInfo()
if err != nil {
t.Fatal(err)
}
t.Logf("protocol info: %s %d.%d", protoName, major, minor)
userName, err := client.UserName()
if err != nil {
t.Fatal(err)
}
t.Logf("user name: %q", userName)
authorityName, err := client.AuthorityName()
if err != nil {
t.Fatal(err)
}
t.Logf("authority name: %q", authorityName)
sessionKeySize, sigAlg, sigAlgName, encAlg, encAlgName, err := client.KeyInfo()
if err != nil {
t.Fatal(err)
}
t.Logf("key info: session_key_size=%d signature_alg=%q(%d) encryption_alg=%q(%d)", sessionKeySize, sigAlgName, sigAlg, encAlgName, encAlg)
// TODO: add some code to verify if negotiated connection is suitable (ciper and so on)
_, err = fmt.Fprintf(client, "GET / HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n")
if err != nil {
t.Fatal(err)
}
data, err := ioutil.ReadAll(client)
if err != nil {
t.Fatal(err)
}
t.Logf("web page: %q", data)
err = client.Shutdown()
if err != nil {
t.Fatal(err)
}
}
| apache-2.0 |
CalculatedContent/chef-repo | cookbooks/passenger_apache2/test/cookbooks/passenger_apache2_test/recipes/package.rb | 1158 | #
# Cookbook Name:: passenger_apache2_test
# Recipe:: package
#
# Copyright 2013, Opscode, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
node.set['passenger']['install_method'] = 'package'
node.set['passenger']['package'].delete('version')
node.set['passenger']['package']['name'] = case node['platform_family']
when 'debian'
'libapache2-mod-passenger'
when 'rhel'
'mod_passenger'
end
include_recipe "passenger_apache2::default"
| apache-2.0 |
fengshao0907/nutz | test/org/nutz/aop/asm/test/Aop5.java | 69 | package org.nutz.aop.asm.test;
public abstract class Aop5 {
}
| apache-2.0 |
cevaris/pants | testprojects/maven_layout/provided_patching/three/src/main/java/org/pantsbuild/testproject/provided_patching/Shadow.java | 282 | // Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package org.pantsbuild.testproject.provided_patching;
public class Shadow {
public String getShadowVersion() {
return "Shadow Three";
}
} | apache-2.0 |
lichuqiang/kubernetes | pkg/kubelet/dockershim/libdocker/client.go | 4536 | /*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package libdocker
import (
"time"
dockertypes "github.com/docker/docker/api/types"
dockercontainer "github.com/docker/docker/api/types/container"
dockerimagetypes "github.com/docker/docker/api/types/image"
dockerapi "github.com/docker/docker/client"
"k8s.io/klog"
)
const (
// https://docs.docker.com/engine/reference/api/docker_remote_api/
// docker version should be at least 1.13.1
MinimumDockerAPIVersion = "1.26.0"
// Status of a container returned by ListContainers.
StatusRunningPrefix = "Up"
StatusCreatedPrefix = "Created"
StatusExitedPrefix = "Exited"
// Fake docker endpoint
FakeDockerEndpoint = "fake://"
)
// Interface is an abstract interface for testability. It abstracts the interface of docker client.
type Interface interface {
ListContainers(options dockertypes.ContainerListOptions) ([]dockertypes.Container, error)
InspectContainer(id string) (*dockertypes.ContainerJSON, error)
InspectContainerWithSize(id string) (*dockertypes.ContainerJSON, error)
CreateContainer(dockertypes.ContainerCreateConfig) (*dockercontainer.ContainerCreateCreatedBody, error)
StartContainer(id string) error
StopContainer(id string, timeout time.Duration) error
UpdateContainerResources(id string, updateConfig dockercontainer.UpdateConfig) error
RemoveContainer(id string, opts dockertypes.ContainerRemoveOptions) error
InspectImageByRef(imageRef string) (*dockertypes.ImageInspect, error)
InspectImageByID(imageID string) (*dockertypes.ImageInspect, error)
ListImages(opts dockertypes.ImageListOptions) ([]dockertypes.ImageSummary, error)
PullImage(image string, auth dockertypes.AuthConfig, opts dockertypes.ImagePullOptions) error
RemoveImage(image string, opts dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
ImageHistory(id string) ([]dockerimagetypes.HistoryResponseItem, error)
Logs(string, dockertypes.ContainerLogsOptions, StreamOptions) error
Version() (*dockertypes.Version, error)
Info() (*dockertypes.Info, error)
CreateExec(string, dockertypes.ExecConfig) (*dockertypes.IDResponse, error)
StartExec(string, dockertypes.ExecStartCheck, StreamOptions) error
InspectExec(id string) (*dockertypes.ContainerExecInspect, error)
AttachToContainer(string, dockertypes.ContainerAttachOptions, StreamOptions) error
ResizeContainerTTY(id string, height, width uint) error
ResizeExecTTY(id string, height, width uint) error
GetContainerStats(id string) (*dockertypes.StatsJSON, error)
}
// Get a *dockerapi.Client, either using the endpoint passed in, or using
// DOCKER_HOST, DOCKER_TLS_VERIFY, and DOCKER_CERT path per their spec
func getDockerClient(dockerEndpoint string) (*dockerapi.Client, error) {
if len(dockerEndpoint) > 0 {
klog.Infof("Connecting to docker on %s", dockerEndpoint)
return dockerapi.NewClient(dockerEndpoint, "", nil, nil)
}
return dockerapi.NewClientWithOpts(dockerapi.FromEnv)
}
// ConnectToDockerOrDie creates docker client connecting to docker daemon.
// If the endpoint passed in is "fake://", a fake docker client
// will be returned. The program exits if error occurs. The requestTimeout
// is the timeout for docker requests. If timeout is exceeded, the request
// will be cancelled and throw out an error. If requestTimeout is 0, a default
// value will be applied.
func ConnectToDockerOrDie(dockerEndpoint string, requestTimeout, imagePullProgressDeadline time.Duration,
withTraceDisabled bool, enableSleep bool) Interface {
if dockerEndpoint == FakeDockerEndpoint {
fakeClient := NewFakeDockerClient()
if withTraceDisabled {
fakeClient = fakeClient.WithTraceDisabled()
}
if enableSleep {
fakeClient.EnableSleep = true
}
return fakeClient
}
client, err := getDockerClient(dockerEndpoint)
if err != nil {
klog.Fatalf("Couldn't connect to docker: %v", err)
}
klog.Infof("Start docker client with request timeout=%v", requestTimeout)
return newKubeDockerClient(client, requestTimeout, imagePullProgressDeadline)
}
| apache-2.0 |
felixrieseberg/flynn | Godeps/_workspace/src/github.com/flynn/docker-utils/sum/layer.go | 1954 | package sum
import (
"archive/tar"
"bytes"
"io"
"io/ioutil"
"path"
"github.com/flynn/flynn/Godeps/_workspace/src/github.com/docker/docker/pkg/tarsum"
)
// for existing usage
func SumAllDockerSave(saved io.Reader) (map[string]string, error) {
return SumAllDockerSaveVersioned(saved, tarsum.Version0)
}
// .. this is an all-in-one. I wish this could be an iterator.
func SumAllDockerSaveVersioned(saved io.Reader, v tarsum.Version) (map[string]string, error) {
tarRdr := tar.NewReader(saved)
hashes := map[string]string{}
jsons := map[string][]byte{}
for {
hdr, err := tarRdr.Next()
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
if path.Base(hdr.Name) == "json" {
id := path.Dir(hdr.Name)
jsonBuf, err := ioutil.ReadAll(tarRdr)
if err != nil {
if err == io.EOF {
continue
}
return nil, err
}
jsons[id] = jsonBuf
}
if path.Base(hdr.Name) == "layer.tar" {
id := path.Dir(hdr.Name)
jsonRdr := bytes.NewReader(jsons[id])
delete(jsons, id)
sum, err := SumTarLayerVersioned(tarRdr, jsonRdr, nil, v)
if err != nil {
if err == io.EOF {
continue
}
return nil, err
}
hashes[id] = sum
}
}
return hashes, nil
}
// for existing usage
func SumTarLayer(tarReader io.Reader, json io.Reader, out io.Writer) (string, error) {
return SumTarLayerVersioned(tarReader, json, out, tarsum.Version0)
}
// if out is not nil, then the tar input is written there instead
func SumTarLayerVersioned(tarReader io.Reader, json io.Reader, out io.Writer, v tarsum.Version) (string, error) {
var writer io.Writer = ioutil.Discard
if out != nil {
writer = out
}
ts, err := tarsum.NewTarSum(tarReader, false, v)
if err != nil {
return "", err
}
_, err = io.Copy(writer, ts)
if err != nil {
return "", err
}
var buf []byte
if json != nil {
if buf, err = ioutil.ReadAll(json); err != nil {
return "", err
}
}
return ts.Sum(buf), nil
}
| bsd-3-clause |
githubmoros/myclinicsoft | vendor/google/apiclient-services/src/Google/Service/Dialogflow/GoogleCloudDialogflowV2ListContextsResponse.php | 1394 | <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_Dialogflow_GoogleCloudDialogflowV2ListContextsResponse extends Google_Collection
{
protected $collection_key = 'contexts';
protected $contextsType = 'Google_Service_Dialogflow_GoogleCloudDialogflowV2Context';
protected $contextsDataType = 'array';
public $nextPageToken;
/**
* @param Google_Service_Dialogflow_GoogleCloudDialogflowV2Context
*/
public function setContexts($contexts)
{
$this->contexts = $contexts;
}
/**
* @return Google_Service_Dialogflow_GoogleCloudDialogflowV2Context
*/
public function getContexts()
{
return $this->contexts;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
}
| mit |
retailnext/dalli | test/helper.rb | 923 | $TESTING = true
require 'rubygems'
# require 'simplecov'
# SimpleCov.start
require 'minitest/pride'
require 'minitest/autorun'
require 'mocha/setup'
require 'mini_shoulda'
require 'memcached_mock'
WANT_RAILS_VERSION = ENV['RAILS_VERSION'] || '>= 3.0.0'
gem 'rails', WANT_RAILS_VERSION
require 'rails'
puts "Testing with Rails #{Rails.version}"
require 'dalli'
require 'logger'
Dalli.logger = Logger.new(STDOUT)
Dalli.logger.level = Logger::ERROR
class MiniTest::Spec
include MemcachedMock::Helper
def assert_error(error, regexp=nil, &block)
ex = assert_raises(error, &block)
assert_match(regexp, ex.message, "#{ex.class.name}: #{ex.message}\n#{ex.backtrace.join("\n\t")}")
end
def with_activesupport
require 'active_support/all'
require 'active_support/cache/dalli_store'
yield
end
def with_actionpack
require 'action_dispatch'
require 'action_controller'
yield
end
end
| mit |
jakzale/ogre | Tools/LightwaveConverter/src/lwEnvelope.cpp | 10021 | #include "lwEnvelope.h"
lwKey *lwEnvelope::addKey( float time, float value )
{
lwKey *key = new lwKey(time, value);
keys.insert(lower_bound(keys.begin(), keys.end(), key), key);
return key;
}
/*======================================================================
range()
Given the value v of a periodic function, returns the equivalent value
v2 in the principal interval [lo, hi]. If i isn't NULL, it receives
the number of wavelengths between v and v2.
v2 = v - i * (hi - lo)
For example, range( 3 pi, 0, 2 pi, i ) returns pi, with i = 1.
====================================================================== */
float lwEnvelope::range( float v, float lo, float hi, int *i )
{
float v2, r = hi - lo;
if ( r == 0.0 ) {
if ( i ) *i = 0;
return lo;
}
v2 = lo + v - r * ( float ) floor(( double ) v / r );
if ( i ) *i = -( int )(( v2 - v ) / r + ( v2 > v ? 0.5 : -0.5 ));
return v2;
}
/*======================================================================
hermite()
Calculate the Hermite coefficients.
====================================================================== */
void lwEnvelope::hermite( float t, float *h1, float *h2, float *h3, float *h4 )
{
float t2, t3;
t2 = t * t;
t3 = t * t2;
*h2 = 3.0f * t2 - t3 - t3;
*h1 = 1.0f - *h2;
*h4 = t3 - t2;
*h3 = *h4 - t2 + t;
}
/*======================================================================
bezier()
Interpolate the value of a 1D Bezier curve.
====================================================================== */
float lwEnvelope::bezier( float x0, float x1, float x2, float x3, float t )
{
float a, b, c, t2, t3;
t2 = t * t;
t3 = t2 * t;
c = 3.0f * ( x1 - x0 );
b = 3.0f * ( x2 - x1 ) - c;
a = x3 - x0 - c - b;
return a * t3 + b * t2 + c * t + x0;
}
/*======================================================================
bez2_time()
Find the t for which bezier() returns the input time. The handle
endpoints of a BEZ2 curve represent the control points, and these have
(time, value) coordinates, so time is used as both a coordinate and a
parameter for this curve type.
====================================================================== */
float lwEnvelope::bez2_time( float x0, float x1, float x2, float x3, float time, float *t0, float *t1 )
{
float v, t;
t = *t0 + ( *t1 - *t0 ) * 0.5f;
v = bezier( x0, x1, x2, x3, t );
if ( fabs( time - v ) > .0001f ) {
if ( v > time )
*t1 = t;
else
*t0 = t;
return bez2_time( x0, x1, x2, x3, time, t0, t1 );
}
else
return t;
}
/*
======================================================================
bez2()
Interpolate the value of a BEZ2 curve.
====================================================================== */
float lwEnvelope::bez2( lwKey *key0, lwKey *key1, float time )
{
float x, y, t, t0 = 0.0f, t1 = 1.0f;
if ( key0->shape == ID_BEZ2 )
x = key0->time + key0->param[ 2 ];
else
x = key0->time + ( key1->time - key0->time ) / 3.0f;
t = bez2_time( key0->time, x, key1->time + key1->param[ 0 ], key1->time,
time, &t0, &t1 );
if ( key0->shape == ID_BEZ2 )
y = key0->value + key0->param[ 3 ];
else
y = key0->value + key0->param[ 1 ] / 3.0f;
return bezier( key0->value, y, key1->param[ 1 ] + key1->value, key1->value, t );
}
/*
======================================================================
outgoing()
Return the outgoing tangent to the curve at key0. The value returned
for the BEZ2 case is used when extrapolating a linear pre behavior and
when interpolating a non-BEZ2 span.
====================================================================== */
float lwEnvelope::outgoing( unsigned int key0, unsigned int key1 )
{
float a, b, d, t, tout;
switch ( keys[key0]->shape )
{
case ID_TCB:
a = ( 1.0f - keys[key0]->tension )
* ( 1.0f + keys[key0]->continuity )
* ( 1.0f + keys[key0]->bias );
b = ( 1.0f - keys[key0]->tension )
* ( 1.0f - keys[key0]->continuity )
* ( 1.0f - keys[key0]->bias );
d = keys[key1]->value - keys[key0]->value;
if ( key0 > 0 )
{
t = ( keys[key1]->time - keys[key0]->time ) / ( keys[key1]->time - keys[ key0-1 ]->time );
tout = t * ( a * ( keys[key0]->value - keys[ key0-1 ]->value ) + b * d );
}
else
tout = b * d;
break;
case ID_LINE:
d = keys[key1]->value - keys[key0]->value;
if ( key0 > 0 )
{
t = ( keys[key1]->time - keys[key0]->time ) / ( keys[key1]->time - keys[ key0-1 ]->time );
tout = t * ( keys[key0]->value - keys[ key0-1 ]->value + d );
}
else
tout = d;
break;
case ID_BEZI:
case ID_HERM:
tout = keys[key0]->param[ 1 ];
if ( key0 > 0 )
tout *= ( keys[key1]->time - keys[key0]->time ) / ( keys[key1]->time - keys[ key0-1 ]->time );
break;
case ID_BEZ2:
tout = keys[key0]->param[ 3 ] * ( keys[key1]->time - keys[key0]->time );
if ( fabs( keys[key0]->param[ 2 ] ) > 1e-5f )
tout /= keys[key0]->param[ 2 ];
else
tout *= 1e5f;
break;
case ID_STEP:
default:
tout = 0.0f;
break;
}
return tout;
}
/*======================================================================
incoming()
Return the incoming tangent to the curve at key1. The value returned
for the BEZ2 case is used when extrapolating a linear post behavior.
====================================================================== */
float lwEnvelope::incoming( unsigned int key0, unsigned int key1 )
{
float a, b, d, t, tin;
switch ( keys[key1]->shape )
{
case ID_LINE:
d = keys[key1]->value - keys[key0]->value;
if ( key1 < keys.size()-1 )
{
t = ( keys[key1]->time - keys[key0]->time ) / ( keys[ key1+1 ]->time - keys[key0]->time );
tin = t * ( keys[ key1+1 ]->value - keys[key1]->value + d );
}
else
tin = d;
break;
case ID_TCB:
a = ( 1.0f - keys[key1]->tension )
* ( 1.0f - keys[key1]->continuity )
* ( 1.0f + keys[key1]->bias );
b = ( 1.0f - keys[key1]->tension )
* ( 1.0f + keys[key1]->continuity )
* ( 1.0f - keys[key1]->bias );
d = keys[key1]->value - keys[key0]->value;
if ( key1 < keys.size()-1 ) {
t = ( keys[key1]->time - keys[key0]->time ) / ( keys[ key1+1 ]->time - keys[key0]->time );
tin = t * ( b * ( keys[ key1+1 ]->value - keys[key1]->value ) + a * d );
}
else
tin = a * d;
break;
case ID_BEZI:
case ID_HERM:
tin = keys[key1]->param[ 0 ];
if ( key1 < keys.size()-1 )
tin *= ( keys[key1]->time - keys[key0]->time ) / ( keys[ key1+1 ]->time - keys[key0]->time );
break;
return tin;
case ID_BEZ2:
tin = keys[key1]->param[ 1 ] * ( keys[key1]->time - keys[key0]->time );
if ( fabs( keys[key1]->param[ 0 ] ) > 1e-5f )
tin /= keys[key1]->param[ 0 ];
else
tin *= 1e5f;
break;
case ID_STEP:
default:
tin = 0.0f;
break;
}
return tin;
}
/*======================================================================
evalEnvelope()
Given a list of keys and a time, returns the interpolated value of the
envelope at that time.
====================================================================== */
float lwEnvelope::evaluate( float time )
{
lwKey *key0, *key1, *skey, *ekey;
float t, h1, h2, h3, h4, tin, tout, offset = 0.0f;
int noff;
int key0index, key1index;
/* if there's no key, the value is 0 */
if ( keys.size() == 0 ) return 0.0f;
/* if there's only one key, the value is constant */
if ( keys.size() == 1 ) return keys[0]->value;
/* find the first and last keys */
key0index = 0;
key1index = keys.size()-1;
skey = keys[key0index];
ekey = keys[key1index];
/* use pre-behavior if time is before first key time */
if ( time < skey->time )
{
switch ( behavior[ 0 ] )
{
case BEH_RESET:
return 0.0f;
case BEH_CONSTANT:
return skey->value;
case BEH_REPEAT:
time = range( time, skey->time, ekey->time, NULL );
break;
case BEH_OSCILLATE:
time = range( time, skey->time, ekey->time, &noff );
if ( noff % 2 )
time = ekey->time - skey->time - time;
break;
case BEH_OFFSET:
time = range( time, skey->time, ekey->time, &noff );
offset = noff * ( ekey->value - skey->value );
break;
case BEH_LINEAR:
tout = outgoing( key0index, key0index+1 ) / ( keys[key0index+1]->time - keys[key0index]->time );
return tout * ( time - skey->time ) + skey->value;
}
}
/* use post-behavior if time is after last key time */
else if ( time > ekey->time ) {
switch ( behavior[ 1 ] )
{
case BEH_RESET:
return 0.0f;
case BEH_CONSTANT:
return ekey->value;
case BEH_REPEAT:
time = range( time, skey->time, ekey->time, NULL );
break;
case BEH_OSCILLATE:
time = range( time, skey->time, ekey->time, &noff );
if ( noff % 2 )
time = ekey->time - skey->time - time;
break;
case BEH_OFFSET:
time = range( time, skey->time, ekey->time, &noff );
offset = noff * ( ekey->value - skey->value );
break;
case BEH_LINEAR:
tin = incoming( key1index-1, key1index ) / ( ekey->time - keys[key1index-1]->time );
return tin * ( time - ekey->time ) + ekey->value;
}
}
/* get the endpoints of the interval being evaluated */
key0index = keys.size()-2;
key1index = keys.size()-1;
key0 = keys[key0index];
key1 = keys[key1index];
/* check for singularities first */
if ( time == key0->time )
return key0->value + offset;
else if ( time == key1->time )
return key1->value + offset;
/* get interval length, time in [0, 1] */
t = ( time - key0->time ) / ( key1->time - key0->time );
/* interpolate */
switch ( key1->shape )
{
case ID_TCB:
case ID_BEZI:
case ID_HERM:
tout = outgoing( key0index, key1index );
tin = incoming( key0index, key1index );
hermite( t, &h1, &h2, &h3, &h4 );
return h1 * key0->value + h2 * key1->value + h3 * tout + h4 * tin + offset;
case ID_BEZ2:
return bez2( key0, key1, time ) + offset;
case ID_LINE:
return key0->value + t * ( key1->value - key0->value ) + offset;
case ID_STEP:
return key0->value + offset;
default:
return offset;
}
}
| mit |
mwarren/rubyspec | library/socket/unixsocket/open_spec.rb | 647 | require File.expand_path('../../../../spec_helper', __FILE__)
require File.expand_path('../shared/new', __FILE__)
describe "UNIXSocket.open" do
it_behaves_like :unixsocket_new, :open
platform_is_not :windows do
before :each do
@path = SocketSpecs.socket_path
rm_r @path
@server = UNIXServer.open(@path)
end
after :each do
@server.close
rm_r @path
end
it "opens a unix socket on the specified file and yields it to the block" do
UNIXSocket.send(@method, @path) do |client|
client.addr[0].should == "AF_UNIX"
client.closed?.should == false
end
end
end
end
| mit |
zeropool/duktape | tests/ecmascript/test-dev-bound-functions.js | 2103 | /*===
args: 1 2 3 4
this: [object global]
args: f2 1 2 3
this: this-f2
args: f2 f3 1 2
this: this-f2
===*/
function orig(x,y,z,w) {
print('args:', x, y, z, w);
print('this:', this);
}
var f1, f2, f3, f4;
f1 = orig;
f2 = f1.bind('this-f2', 'f2');
f3 = f2.bind('this-f3', 'f3');
/* Plain function call, 'this' binding will be the global object. */
f1(1, 2, 3, 4);
/* Bound function: bind 'this' to 'this-f2' and prepend 'f1' to argument list:
*
* f2(1, 2, 3)
* --> f1('f2', 1, 2, 3) this='this-f2'
*/
f2(1, 2, 3);
/* Second order bound function: note the behavior of the this binding:
*
* f3(1, 2)
* --> f2('f3', 1, 2) this='this-f3'
* --> f1('f2', 'f3', 1, 2) this='this-f2'
*
* In other words:
*
* - The effective 'this' binding comes from the bound function right before
* the actual non-bound function (not the outermost bound function).
*
* - The argument list to be prepended (for the final non-bound function call)
* can be formed by concatenating the [[BoundArgs]] lists of the bound
* functions, from innermost to outermost. Or alternatively, by starting
* with an empty list, process each bound function from outermost to innermost,
* prepending the [[BoundArgs]].
*/
f3(1, 2);
/*===
args: 1 2 3 4
this: this-f2
args: 1 2 3 4
this: this-f2
===*/
/* Example of [[BoundArgs]] concatenation:
*
* f1 <-- f2, [[BoundArgs]] = [1,2] <-- f3, [[BoundArgs]] = [3,4]
*
* Process from outermost to innermost, prepending [[BoundArgs]]
*
* []
* [3,4] + [] = [3,4] (process f3)
* [1,2] + [3,4] = [1,2,3,4] (process f2)
* [1,2,3,4] (f1 is not bound, finish)
*
* The ultimately effective [[BoundThis]] is the one right before the non-bound
* function, i.e. f2's [[BoundThis]] here.
*
* For a "collapsed" bound function:
*
* [[BoundArgs]] = [1,2,3,4]
* [[BoundThis]] = 'this-f2'
* [[TargetFunction]] = f1
*/
f1 = orig;
f2 = f1.bind('this-f2', 1, 2);
f3 = f2.bind('this-f3', 3, 4);
f4 = f1.bind('this-f2', 1, 2, 3, 4); // equivalent to f3
f3();
f4();
| mit |
Karneck/ACE3 | addons/goggles/RscTitles.hpp | 1244 | class RscTitles{
#include "define.hpp"
class RscACE_Goggles_BaseTitle{
idd = -1;
onLoad = "uiNamespace setVariable ['ACE_Goggles_Display', _this select 0]";
onUnload = "uiNamespace setVariable ['ACE_Goggles_Display', displayNull]";
fadeIn=0.5;
fadeOut=0.5;
movingEnable = false;
duration = 10e10;
name = "RscACE_Goggles_BaseTitle";
class controls;
};
class RscACE_Goggles:RscACE_Goggles_BaseTitle{
idd = 1044;
name = "RscACE_Goggles";
class controls{
class gogglesImage: RscPicture{
idc = 10650;
};
};
};
class RscACE_GogglesEffects:RscACE_Goggles_BaseTitle{
idd = 1045;
onLoad = "uiNamespace setVariable ['ACE_Goggles_DisplayEffects', _this select 0]";
onUnload = "uiNamespace setVariable ['ACE_Goggles_DisplayEffects', displayNull]";
name = "RscACE_GogglesEffects";
fadeIn=0;
fadeOut=0.5;
class controls{
class dirtImage: RscPicture {
idc = 10660;
};
class dustImage: RscPicture {
idc = 10662;
};
};
};
}; | gpl-2.0 |
R3nPi2/Drupal-8-Skeleton | core/modules/media/src/Plugin/media/Source/VideoFile.php | 1004 | <?php
namespace Drupal\media\Plugin\media\Source;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\media\MediaTypeInterface;
/**
* Media source wrapping around a video file.
*
* @see \Drupal\file\FileInterface
*
* @MediaSource(
* id = "video_file",
* label = @Translation("Video file"),
* description = @Translation("Use video files for reusable media."),
* allowed_field_types = {"file"},
* default_thumbnail_filename = "video.png"
* )
*/
class VideoFile extends File {
/**
* {@inheritdoc}
*/
public function createSourceField(MediaTypeInterface $type) {
return parent::createSourceField($type)->set('settings', ['file_extensions' => 'mp4']);
}
/**
* {@inheritdoc}
*/
public function prepareViewDisplay(MediaTypeInterface $type, EntityViewDisplayInterface $display) {
$display->setComponent($this->getSourceFieldDefinition($type)->getName(), [
'type' => 'file_video',
'label' => 'visually_hidden',
]);
}
}
| gpl-2.0 |
johnparker007/mame | src/devices/cpu/clipper/clipper.cpp | 53998 | // license:BSD-3-Clause
// copyright-holders:Patrick Mackinlay
/*
* An implementation of the Fairchild/Intergraph CLIPPER CPU family.
*
* Primary source: http://bitsavers.org/pdf/fairchild/clipper/Clipper_Instruction_Set_Oct85.pdf
*
* TODO:
* - unimplemented C400 instructions (cdb, cnvx[ds]w, loadts, waitd)
* - correct boot logic
* - instruction timing
* - big endian support (not present in the wild)
*/
#include "emu.h"
#include "debugger.h"
#include "clipper.h"
#include "clipperd.h"
#define LOG_GENERAL (1U << 0)
#define LOG_EXCEPTION (1U << 1)
#define LOG_SYSCALLS (1U << 2)
//#define VERBOSE (LOG_GENERAL | LOG_EXCEPTION)
#define VERBOSE (LOG_SYSCALLS)
#include "logmacro.h"
// convenience macros for frequently used instruction fields
#define R1 (m_info.r1)
#define R2 (m_info.r2)
#define BIT31(x) BIT(x, 31)
#define BIT63(x) BIT(x, 63)
// macros for computing and setting condition codes
#define FLAGS(C,V,Z,N) \
m_psw = (m_psw & ~(PSW_C | PSW_V | PSW_Z | PSW_N)) | (((C) << 3) | ((V) << 2) | ((Z) << 1) | ((N) << 0))
#define FLAGS_ADD(op2, op1, result) FLAGS( \
(BIT31(op2) && BIT31(op1)) || (!BIT31(result) && (BIT31(op2) || BIT31(op1))), \
(BIT31(op2) == BIT31(op1)) && (BIT31(result) != BIT31(op2)), \
result == 0, BIT31(result))
#define FLAGS_SUB(op2, op1, result) FLAGS( \
(!BIT31(op2) && BIT31(op1)) || (BIT31(result) && (!BIT31(op2) || BIT31(op1))), \
(BIT31(op2) != BIT31(op1)) && (BIT31(result) != BIT31(op2)), \
result == 0, BIT31(result))
DEFINE_DEVICE_TYPE(CLIPPER_C100, clipper_c100_device, "clipper_c100", "C100 CLIPPER")
DEFINE_DEVICE_TYPE(CLIPPER_C300, clipper_c300_device, "clipper_c300", "C300 CLIPPER")
DEFINE_DEVICE_TYPE(CLIPPER_C400, clipper_c400_device, "clipper_c400", "C400 CLIPPER")
clipper_c100_device::clipper_c100_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock)
: clipper_device(mconfig, CLIPPER_C100, tag, owner, clock, ENDIANNESS_LITTLE, SSW_ID_C1R1)
, m_icammu(*this, "^cammu_i")
, m_dcammu(*this, "^cammu_d")
{
}
clipper_c300_device::clipper_c300_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock)
: clipper_device(mconfig, CLIPPER_C300, tag, owner, clock, ENDIANNESS_LITTLE, SSW_ID_C3R1)
, m_icammu(*this, "^cammu_i")
, m_dcammu(*this, "^cammu_d")
{
}
clipper_c400_device::clipper_c400_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock)
: clipper_device(mconfig, CLIPPER_C400, tag, owner, clock, ENDIANNESS_LITTLE, SSW_ID_C4R4)
, m_db_pc(0)
, m_cammu(*this, "^cammu")
{
}
clipper_device::clipper_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, u32 clock, const endianness_t endianness, const u32 cpuid)
: cpu_device(mconfig, type, tag, owner, clock)
, m_main_config("main", endianness, 32, 32, 0)
, m_io_config("io", endianness, 32, 32, 0)
, m_boot_config("boot", endianness, 32, 32, 0)
, m_icount(0)
, m_psw(endianness == ENDIANNESS_BIG ? PSW_BIG : 0)
, m_ssw(cpuid)
, m_r(m_rs)
, m_ru{0}
, m_rs{0}
, m_f{0}
, m_fp_pc(0)
, m_fp_dst(0)
, m_info{0}
{
}
// rotate helpers to replace MSVC intrinsics
inline u32 rotl32(u32 x, u8 shift)
{
shift &= 31;
return (x << shift) | (x >> ((32 - shift) & 31));
}
inline u32 rotr32(u32 x, u8 shift)
{
shift &= 31;
return (x >> shift) | (x << ((32 - shift) & 31));
}
inline u64 rotl64(u64 x, u8 shift)
{
shift &= 63;
return (x << shift) | (x >> ((64 - shift) & 63));
}
inline u64 rotr64(u64 x, u8 shift)
{
shift &= 63;
return (x >> shift) | (x << ((64 - shift) & 63));
}
void clipper_device::device_start()
{
// configure the cammu address spaces
get_dcammu().set_spaces(space(0), space(1), space(2));
get_icammu().set_spaces(space(0), space(1), space(2));
// set our instruction counter
set_icountptr(m_icount);
// program-visible cpu state
save_item(NAME(m_pc));
save_item(NAME(m_psw));
save_item(NAME(m_ssw));
save_item(NAME(m_ru));
save_item(NAME(m_rs));
save_item(NAME(m_f));
save_item(NAME(m_fp_pc));
save_item(NAME(m_fp_dst));
// non-visible cpu state
save_item(NAME(m_wait));
save_item(NAME(m_nmi));
save_item(NAME(m_irq));
save_item(NAME(m_ivec));
save_item(NAME(m_exception));
state_add(STATE_GENPC, "GENPC", m_pc).noshow();
state_add(STATE_GENPCBASE, "CURPC", m_pc).noshow();
state_add(STATE_GENFLAGS, "GENFLAGS", m_psw).mask(0xf).formatstr("%4s").noshow();
state_add(CLIPPER_PC, "pc", m_pc);
state_add(CLIPPER_PSW, "psw", m_psw);
state_add(CLIPPER_SSW, "ssw", m_ssw);
// integer regsters
for (int i = 0; i < get_ireg_count(); i++)
state_add(CLIPPER_UREG + i, util::string_format("ur%d", i).c_str(), m_ru[i]);
for (int i = 0; i < get_ireg_count(); i++)
state_add(CLIPPER_SREG + i, util::string_format("sr%d", i).c_str(), m_rs[i]);
// floating point registers
for (int i = 0; i < get_freg_count(); i++)
state_add(CLIPPER_FREG + i, util::string_format("f%d", i).c_str(), m_f[i]);
}
void clipper_c400_device::device_start()
{
clipper_device::device_start();
save_item(NAME(m_db_pc));
}
void clipper_device::device_reset()
{
/*
* From C300 documentation, on reset:
* psw: T cleared, BIG set from hardware, others undefined
* ssw: EI, TP, M, U, K, KU, UU, P cleared, ID set from hardware, others undefined
*/
// clear the psw and ssw
set_psw(0);
set_ssw(0);
// FIXME: figure out how to branch to the boot code properly
m_pc = 0x7f100000;
m_wait = false;
m_nmi = CLEAR_LINE;
m_irq = CLEAR_LINE;
m_ivec = 0;
m_exception = 0;
}
void clipper_device::state_string_export(const device_state_entry &entry, std::string &str) const
{
switch (entry.index())
{
case STATE_GENFLAGS:
str = string_format("%c%c%c%c",
PSW(C) ? 'C' : '.',
PSW(V) ? 'V' : '.',
PSW(Z) ? 'Z' : '.',
PSW(N) ? 'N' : '.');
break;
}
}
void clipper_device::execute_run()
{
// check for non-maskable and prioritised interrupts
if (m_nmi)
{
// acknowledge non-maskable interrupt
standard_irq_callback(INPUT_LINE_NMI);
LOGMASKED(LOG_EXCEPTION, "non-maskable interrupt\n");
m_pc = intrap(EXCEPTION_INTERRUPT_BASE, m_pc);
}
else if (SSW(EI) && m_irq)
{
LOGMASKED(LOG_EXCEPTION, "prioritised interrupt vector 0x%02x\n", m_ivec);
// allow equal/higher priority interrupts
if ((m_ivec & IVEC_LEVEL) <= SSW(IL))
{
// acknowledge interrupt
standard_irq_callback(INPUT_LINE_IRQ0);
m_pc = intrap(EXCEPTION_INTERRUPT_BASE + m_ivec * 8, m_pc);
LOGMASKED(LOG_EXCEPTION, "transferring control to vector 0x%02x address 0x%08x\n", m_ivec, m_pc);
}
}
while (m_icount > 0)
{
debugger_instruction_hook(m_pc);
if (m_wait)
{
m_icount = 0;
continue;
}
// fetch and decode an instruction
if (decode_instruction())
{
softfloat_exceptionFlags = 0;
// execute instruction
execute_instruction();
// check floating point exceptions
if (softfloat_exceptionFlags)
fp_exception();
}
if (m_exception)
{
debugger_exception_hook(m_exception);
/*
* For traced instructions which are interrupted or cause traps, the TP
* flag is set by hardware when the interrupt or trap occurs to ensure
* that the trace trap will occur immediately after the interrupt or other
* trap has been serviced.
*/
// FIXME: don't know why/when the trace pending flag is needed
if (PSW(T))
m_ssw |= SSW_TP;
switch (m_exception)
{
// data memory trap group
case EXCEPTION_D_CORRECTED_MEMORY_ERROR:
case EXCEPTION_D_UNCORRECTABLE_MEMORY_ERROR:
case EXCEPTION_D_ALIGNMENT_FAULT:
case EXCEPTION_D_PAGE_FAULT:
case EXCEPTION_D_READ_PROTECT_FAULT:
case EXCEPTION_D_WRITE_PROTECT_FAULT:
// instruction memory trap group
case EXCEPTION_I_CORRECTED_MEMORY_ERROR:
case EXCEPTION_I_UNCORRECTABLE_MEMORY_ERROR:
case EXCEPTION_I_ALIGNMENT_FAULT:
case EXCEPTION_I_PAGE_FAULT:
case EXCEPTION_I_EXECUTE_PROTECT_FAULT:
// illegal operation trap group
case EXCEPTION_ILLEGAL_OPERATION:
case EXCEPTION_PRIVILEGED_INSTRUCTION:
// return address is faulting instruction
m_pc = intrap(m_exception, m_info.pc);
break;
default:
// return address is following instruction
m_pc = intrap(m_exception, m_pc);
break;
}
}
// FIXME: trace trap logic not working properly yet
//else if (PSW(T))
// m_pc = intrap(EXCEPTION_TRACE, m_pc);
// FIXME: some instructions take longer (significantly) than one cycle
// and also the timings are often slower for the C100 and C300
m_icount -= 4;
}
}
void clipper_device::execute_set_input(int inputnum, int state)
{
if (state)
m_wait = false;
switch (inputnum)
{
case INPUT_LINE_IRQ0:
m_irq = state;
break;
case INPUT_LINE_NMI:
m_nmi = state;
break;
}
}
device_memory_interface::space_config_vector clipper_device::memory_space_config() const
{
return space_config_vector {
std::make_pair(0, &m_main_config),
std::make_pair(1, &m_io_config),
std::make_pair(2, &m_boot_config)
};
}
bool clipper_device::memory_translate(int spacenum, int intention, offs_t &address)
{
return ((intention & TRANSLATE_TYPE_MASK) == TRANSLATE_FETCH ? get_icammu() : get_dcammu()).memory_translate(m_ssw, spacenum, intention, address);
}
void clipper_device::set_exception(u16 data)
{
LOGMASKED(LOG_EXCEPTION, "external exception 0x%04x triggered\n", data);
// check if corrected memory errors are masked
if (!SSW(ECM) && (data == EXCEPTION_D_CORRECTED_MEMORY_ERROR || data == EXCEPTION_I_CORRECTED_MEMORY_ERROR))
return;
m_exception = data;
}
/*
* Fetch and decode an instruction and compute an effective address (for
* instructions with addressing modes). The results are contained in the m_info
* structure to simplify passing between here and execute_instruction().
*/
bool clipper_device::decode_instruction()
{
// record the current instruction address
m_info.pc = m_pc;
// fetch and decode the primary parcel
if (!get_icammu().fetch<u16>(m_ssw, m_pc + 0, [this](u16 insn) {
m_info.opcode = insn >> 8;
m_info.subopcode = insn & 0xff;
m_info.r1 = (insn & 0x00f0) >> 4;
m_info.r2 = insn & 0x000f;
}))
return false;
// initialise the other fields
m_info.imm = 0;
m_info.macro = 0;
m_info.address = 0;
// default instruction size is 2 bytes
int size = 2;
if ((m_info.opcode & 0xf8) == 0x38)
{
// fetch 16 bit immediate and sign extend
if (!get_icammu().fetch<s16>(m_ssw, m_pc + 2, [this](s32 v) { m_info.imm = v; }))
return false;
size = 4;
}
else if ((m_info.opcode & 0xd3) == 0x83)
{
// instruction has an immediate operand, either 16 or 32 bit
if (m_info.subopcode & 0x80)
{
// fetch 16 bit immediate and sign extend
if (!get_icammu().fetch<s16>(m_ssw, m_pc + 2, [this](s32 v) { m_info.imm = v; }))
return false;
size = 4;
}
else
{
// fetch 32 bit immediate
if (!get_icammu().fetch<u32>(m_ssw, m_pc + 2, [this](u32 v) { m_info.imm = v; }))
return false;
size = 6;
}
}
else if ((m_info.opcode & 0xc0) == 0x40)
{
// instructions with addresses
if (m_info.opcode & 0x01)
{
// instructions with complex modes
switch (m_info.subopcode & 0xf0)
{
case ADDR_MODE_PC32:
if (!get_icammu().fetch<u32>(m_ssw, m_pc + 2, [this](u32 v) { m_info.address = m_pc + v; }))
return false;
size = 6;
break;
case ADDR_MODE_ABS32:
if (!get_icammu().fetch<u32>(m_ssw, m_pc + 2, [this](u32 v) { m_info.address = v; }))
return false;
size = 6;
break;
case ADDR_MODE_REL32:
if (!get_icammu().fetch<u16>(m_ssw, m_pc + 2, [this](u16 v) { m_info.r2 = v & 0xf; }))
return false;
if (!get_icammu().fetch<u32>(m_ssw, m_pc + 4, [this](u32 v) { m_info.address = m_r[m_info.subopcode & 0xf] + v; }))
return false;
size = 8;
break;
case ADDR_MODE_PC16:
if (!get_icammu().fetch<s16>(m_ssw, m_pc + 2, [this](s16 v) { m_info.address = m_pc + v; }))
return false;
size = 4;
break;
case ADDR_MODE_REL12:
if (!get_icammu().fetch<s16>(m_ssw, m_pc + 2, [this](s16 v) {
m_info.r2 = v & 0xf;
m_info.address = m_r[m_info.subopcode & 0xf] + (v >> 4);
}))
return false;
size = 4;
break;
case ADDR_MODE_ABS16:
if (!get_icammu().fetch<s16>(m_ssw, m_pc + 2, [this](s32 v) { m_info.address = v; }))
return false;
size = 4;
break;
case ADDR_MODE_PCX:
if (!get_icammu().fetch<u16>(m_ssw, m_pc + 2, [this](u16 v) {
m_info.r2 = v & 0xf;
m_info.address = m_pc + m_r[(v >> 4) & 0xf];
}))
return false;
size = 4;
break;
case ADDR_MODE_RELX:
if (!get_icammu().fetch<u16>(m_ssw, m_pc + 2, [this](u16 v) {
m_info.r2 = v & 0xf;
m_info.address = m_r[m_info.subopcode & 0xf] + m_r[(v >> 4) & 0xf];
}))
return false;
size = 4;
break;
default:
m_exception = EXCEPTION_ILLEGAL_OPERATION;
return false;
}
}
else
// relative addressing mode
m_info.address = m_r[m_info.r1];
}
else if ((m_info.opcode & 0xfd) == 0xb4)
{
// macro instructions
if (!get_icammu().fetch<u16>(m_ssw, m_pc + 2, [this](u16 v) { m_info.macro = v; }))
return false;
size = 4;
}
// instruction fetch and decode complete
m_pc = m_pc + size;
return true;
}
void clipper_device::execute_instruction()
{
switch (m_info.opcode)
{
case 0x00: // noop
break;
case 0x10:
// movwp: move word to processor register
// treated as a noop if target ssw in user mode
// R1 == 3 means "fast" mode - avoids pipeline flush
if (R1 == 0)
set_psw(m_r[R2]);
else if (!SSW(U) && (R1 == 1 || R1 == 3))
set_ssw(m_r[R2]);
// FLAGS: CVZN
break;
case 0x11:
// movpw: move processor register to word
switch (R1)
{
case 0: m_r[R2] = m_psw; break;
case 1: m_r[R2] = m_ssw; break;
}
break;
case 0x12:
// calls: call supervisor
m_exception = EXCEPTION_SUPERVISOR_CALL_BASE + (m_info.subopcode & 0x7f) * 8;
if (VERBOSE & LOG_SYSCALLS)
switch (m_info.subopcode & 0x7f)
{
case 0x3b: // execve
LOGMASKED(LOG_SYSCALLS, "execve(\"%s\", [ %s ], envp)\n",
debug_string(m_r[0]), debug_string_array(m_r[1]));
break;
}
break;
case 0x13:
// ret: return from subroutine
get_dcammu().load<u32>(m_ssw, m_r[R2], [this](u32 v) {
m_pc = v;
m_r[R2] += 4;
});
// TRAPS: C,U,A,P,R
break;
case 0x14:
// pushw: push word
get_dcammu().store<u32>(m_ssw, m_r[R1] - 4, m_r[R2]);
m_r[R1] -= 4;
// TRAPS: A,P,W
break;
case 0x16:
// popw: pop word
get_dcammu().load<u32>(m_ssw, m_r[R1], [this](u32 v) {
m_r[R1] += 4;
m_r[R2] = v;
});
// TRAPS: C,U,A,P,R
break;
case 0x20:
// adds: add single floating
set_fp(R2, f32_add(get_fp32(R2), get_fp32(R1)), F_IVUX);
// TRAPS: F_IVUX
break;
case 0x21:
// subs: subtract single floating
set_fp(R2, f32_sub(get_fp32(R2), get_fp32(R1)), F_IVUX);
// TRAPS: F_IVUX
break;
case 0x22:
// addd: add double floating
set_fp(R2, f64_add(get_fp64(R2), get_fp64(R1)), F_IVUX);
// TRAPS: F_IVUX
break;
case 0x23:
// subd: subtract double floating
set_fp(R2, f64_sub(get_fp64(R2), get_fp64(R1)), F_IVUX);
// TRAPS: F_IVUX
break;
case 0x24:
// movs: move single floating
set_fp(R2, get_fp32(R1), F_NONE);
break;
case 0x25:
// cmps: compare single floating
FLAGS(0, 0, f32_eq(get_fp32(R2), get_fp32(R1)), f32_lt(get_fp32(R2), get_fp32(R1)));
// flag unordered
if (softfloat_exceptionFlags & softfloat_flag_invalid)
m_psw |= PSW_Z | PSW_N;
softfloat_exceptionFlags &= F_NONE;
break;
case 0x26:
// movd: move double floating
set_fp(R2, get_fp64(R1), F_NONE);
break;
case 0x27:
// cmpd: compare double floating
FLAGS(0, 0, f64_eq(get_fp64(R2), get_fp64(R1)), f64_lt(get_fp64(R2), get_fp64(R1)));
// flag unordered
if (softfloat_exceptionFlags & softfloat_flag_invalid)
m_psw |= PSW_Z | PSW_N;
softfloat_exceptionFlags &= F_NONE;
break;
case 0x28:
// muls: multiply single floating
set_fp(R2, f32_mul(get_fp32(R2), get_fp32(R1)), F_IVUX);
// TRAPS: F_IVUX
break;
case 0x29:
// divs: divide single floating
set_fp(R2, f32_div(get_fp32(R2), get_fp32(R1)), F_IVDUX);
// TRAPS: F_IVDUX
break;
case 0x2a:
// muld: multiply double floating
set_fp(R2, f64_mul(get_fp64(R2), get_fp64(R1)), F_IVUX);
// TRAPS: F_IVUX
break;
case 0x2b:
// divd: divide double floating
set_fp(R2, f64_div(get_fp64(R2), get_fp64(R1)), F_IVDUX);
// TRAPS: F_IVDUX
break;
case 0x2c:
// movsw: move single floating to word
m_r[R2] = get_fp32(R1).v;
break;
case 0x2d:
// movws: move word to single floating
set_fp(R2, float32_t{ m_r[R1] }, F_NONE);
break;
case 0x2e:
// movdl: move double floating to longword
set_64(R2, get_fp64(R1).v);
break;
case 0x2f:
// movld: move longword to double floating
set_fp(R2, float64_t{ get_64(R1) }, F_NONE);
break;
case 0x30:
// shaw: shift arithmetic word
if (!BIT31(m_r[R1]))
{
// save the bits that will be shifted out plus new sign bit
const s32 v = s32(m_r[R2]) >> (31 - m_r[R1]);
m_r[R2] <<= m_r[R1];
// overflow is set if sign changes during shift
FLAGS(0, v != 0 && v != -1, m_r[R2] == 0, BIT31(m_r[R2]));
}
else
{
m_r[R2] = s32(m_r[R2]) >> -m_r[R1];
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
}
// FLAGS: 0VZN
break;
case 0x31:
// shal: shift arithmetic longword
if (!BIT31(m_r[R1]))
{
// save the bits that will be shifted out plus new sign bit
const s64 v = s64(get_64(R2)) >> (63 - m_r[R1]);
set_64(R2, get_64(R2) << m_r[R1]);
// overflow is set if sign changes during shift
FLAGS(0, v != 0 && v != -1, get_64(R2) == 0, BIT63(get_64(R2)));
}
else
{
set_64(R2, s64(get_64(R2)) >> -m_r[R1]);
FLAGS(0, 0, get_64(R2) == 0, BIT63(get_64(R2)));
}
// FLAGS: 0VZN
break;
case 0x32:
// shlw: shift logical word
if (!BIT31(m_r[R1]))
m_r[R2] <<= m_r[R1];
else
m_r[R2] >>= -m_r[R1];
// FLAGS: 00ZN
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
break;
case 0x33:
// shll: shift logical longword
if (!BIT31(m_r[R1]))
set_64(R2, get_64(R2) << m_r[R1]);
else
set_64(R2, get_64(R2) >> -m_r[R1]);
// FLAGS: 00ZN
FLAGS(0, 0, get_64(R2) == 0, BIT63(get_64(R2)));
break;
case 0x34:
// rotw: rotate word
if (!BIT31(m_r[R1]))
m_r[R2] = rotl32(m_r[R2], m_r[R1]);
else
m_r[R2] = rotr32(m_r[R2], -m_r[R1]);
// FLAGS: 00ZN
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
break;
case 0x35:
// rotl: rotate longword
if (!BIT31(m_r[R1]))
set_64(R2, rotl64(get_64(R2), m_r[R1]));
else
set_64(R2, rotr64(get_64(R2), -m_r[R1]));
// FLAGS: 00ZN
FLAGS(0, 0, get_64(R2) == 0, BIT63(get_64(R2)));
break;
case 0x38:
// shai: shift arithmetic immediate
if (!BIT31(m_info.imm))
{
// save the bits that will be shifted out plus new sign bit
const s32 v = s32(m_r[R2]) >> (31 - m_info.imm);
m_r[R2] <<= m_info.imm;
// overflow is set if sign changes during shift
FLAGS(0, v != 0 && v != -1, m_r[R2] == 0, BIT31(m_r[R2]));
}
else
{
m_r[R2] = s32(m_r[R2]) >> -m_info.imm;
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
}
// FLAGS: 0VZN
// TRAPS: I
break;
case 0x39:
// shali: shift arithmetic longword immediate
if (!BIT31(m_info.imm))
{
// save the bits that will be shifted out plus new sign bit
const s64 v = s64(get_64(R2)) >> (63 - m_info.imm);
set_64(R2, get_64(R2) << m_info.imm);
// overflow is set if sign changes during shift
FLAGS(0, v != 0 && v != -1, get_64(R2) == 0, BIT63(get_64(R2)));
}
else
{
set_64(R2, s64(get_64(R2)) >> -m_info.imm);
FLAGS(0, 0, get_64(R2) == 0, BIT63(get_64(R2)));
}
// FLAGS: 0VZN
// TRAPS: I
break;
case 0x3a:
// shli: shift logical immediate
if (!BIT31(m_info.imm))
m_r[R2] <<= m_info.imm;
else
m_r[R2] >>= -m_info.imm;
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
// FLAGS: 00ZN
// TRAPS: I
break;
case 0x3b:
// shlli: shift logical longword immediate
if (!BIT31(m_info.imm))
set_64(R2, get_64(R2) << m_info.imm);
else
set_64(R2, get_64(R2) >> -m_info.imm);
FLAGS(0, 0, get_64(R2) == 0, BIT63(get_64(R2)));
// FLAGS: 00ZN
// TRAPS: I
break;
case 0x3c:
// roti: rotate immediate
if (!BIT31(m_info.imm))
m_r[R2] = rotl32(m_r[R2], m_info.imm);
else
m_r[R2] = rotr32(m_r[R2], -m_info.imm);
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
// FLAGS: 00ZN
// TRAPS: I
break;
case 0x3d:
// rotli: rotate longword immediate
if (!BIT31(m_info.imm))
set_64(R2, rotl64(get_64(R2), m_info.imm));
else
set_64(R2, rotr64(get_64(R2), -m_info.imm));
FLAGS(0, 0, get_64(R2) == 0, BIT63(get_64(R2)));
// FLAGS: 00ZN
// TRAPS: I
break;
case 0x44:
case 0x45:
// call: call subroutine
if (get_dcammu().store<u32>(m_ssw, m_r[R2] - 4, m_pc))
{
m_pc = m_info.address;
m_r[R2] -= 4;
}
// TRAPS: A,P,W
break;
case 0x48:
case 0x49:
// b*: branch on condition
if (evaluate_branch())
m_pc = m_info.address;
// TRAPS: A,I
break;
case 0x4c:
case 0x4d:
// bf*: branch on floating exception
// FIXME: documentation is not clear, implementation is guesswork
switch (R2)
{
case BF_ANY:
// bfany: floating any exception
if (m_psw & (PSW_FI | PSW_FV | PSW_FD | PSW_FU | PSW_FX))
m_pc = m_info.address;
break;
case BF_BAD:
// bfbad: floating bad result
if (m_psw & (PSW_FI | PSW_FD))
m_pc = m_info.address;
break;
default:
// reserved
// FIXME: not sure if this should trigger an exception?
m_exception = EXCEPTION_ILLEGAL_OPERATION;
break;
}
break;
case 0x60:
case 0x61:
// loadw: load word
get_dcammu().load<u32>(m_ssw, m_info.address, [this](u32 v) { m_r[R2] = v; });
// TRAPS: C,U,A,P,R,I
break;
case 0x62:
case 0x63:
// loada: load address
m_r[R2] = m_info.address;
// TRAPS: I
break;
case 0x64:
case 0x65:
// loads: load single floating
get_dcammu().load<u32>(m_ssw, m_info.address, [this](u32 v) { set_fp(R2, float32_t{ v }, F_NONE); });
// TRAPS: C,U,A,P,R,I
break;
case 0x66:
case 0x67:
// loadd: load double floating
get_dcammu().load<u64>(m_ssw, m_info.address, [this](u64 v) { set_fp(R2, float64_t{ v }, F_NONE); });
// TRAPS: C,U,A,P,R,I
break;
case 0x68:
case 0x69:
// loadb: load byte
get_dcammu().load<s8>(m_ssw, m_info.address, [this](s32 v) { m_r[R2] = v; });
// TRAPS: C,U,A,P,R,I
break;
case 0x6a:
case 0x6b:
// loadbu: load byte unsigned
get_dcammu().load<u8>(m_ssw, m_info.address, [this](u32 v) { m_r[R2] = v; });
// TRAPS: C,U,A,P,R,I
break;
case 0x6c:
case 0x6d:
// loadh: load halfword
get_dcammu().load<s16>(m_ssw, m_info.address, [this](s32 v) { m_r[R2] = v; });
// TRAPS: C,U,A,P,R,I
break;
case 0x6e:
case 0x6f:
// loadhu: load halfword unsigned
get_dcammu().load<u16>(m_ssw, m_info.address, [this](u32 v) { m_r[R2] = v; });
// TRAPS: C,U,A,P,R,I
break;
case 0x70:
case 0x71:
// storw: store word
get_dcammu().store<u32>(m_ssw, m_info.address, m_r[R2]);
// TRAPS: A,P,W,I
break;
case 0x72:
case 0x73:
// tsts: test and set
get_dcammu().modify<u32>(m_ssw, m_info.address, [this](u32 v) {
m_r[R2] = v;
return v | 0x80000000U;
});
// TRAPS: C,U,A,P,R,W,I
break;
case 0x74:
case 0x75:
// stors: store single floating
get_dcammu().store<u32>(m_ssw, m_info.address, get_fp32(R2).v);
// TRAPS: A,P,W,I
break;
case 0x76:
case 0x77:
// stord: store double floating
get_dcammu().store<u64>(m_ssw, m_info.address, get_fp64(R2).v);
// TRAPS: A,P,W,I
break;
case 0x78:
case 0x79:
// storb: store byte
get_dcammu().store<u8>(m_ssw, m_info.address, m_r[R2]);
// TRAPS: A,P,W,I
break;
case 0x7c:
case 0x7d:
// storh: store halfword
get_dcammu().store<u16>(m_ssw, m_info.address, m_r[R2]);
// TRAPS: A,P,W,I
break;
case 0x80:
// addw: add word
{
const u32 result = m_r[R2] + m_r[R1];
FLAGS_ADD(m_r[R2], m_r[R1], result);
m_r[R2] = result;
}
// FLAGS: CVZN
break;
case 0x82:
// addq: add quick
{
const u32 result = m_r[R2] + m_info.r1;
FLAGS_ADD(m_r[R2], m_info.r1, result);
m_r[R2] = result;
}
// FLAGS: CVZN
break;
case 0x83:
// addi: add immediate
{
const u32 result = m_r[R2] + m_info.imm;
FLAGS_ADD(m_r[R2], m_info.imm, result);
m_r[R2] = result;
}
// FLAGS: CVZN
// TRAPS: I
break;
case 0x84:
// movw: move word
m_r[R2] = m_r[R1];
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
// FLAGS: 00ZN
break;
case 0x86:
// loadq: load quick
m_r[R2] = m_info.r1;
FLAGS(0, 0, m_r[R2] == 0, 0);
// FLAGS: 00Z0
break;
case 0x87:
// loadi: load immediate
m_r[R2] = m_info.imm;
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
// FLAGS: 00ZN
// TRAPS: I
break;
case 0x88:
// andw: and word
m_r[R2] &= m_r[R1];
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
// FLAGS: 00ZN
break;
case 0x8b:
// andi: and immediate
m_r[R2] &= m_info.imm;
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
// FLAGS: 00ZN
// TRAPS: I
break;
case 0x8c:
// orw: or word
m_r[R2] |= m_r[R1];
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
// FLAGS: 00ZN
break;
case 0x8f:
// ori: or immediate
m_r[R2] |= m_info.imm;
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
// FLAGS: 00ZN
// TRAPS: I
break;
case 0x90:
// addwc: add word with carry
{
const u32 result = m_r[R2] + m_r[R1] + (PSW(C) ? 1 : 0);
FLAGS_ADD(m_r[R2], m_r[R1], result);
m_r[R2] = result;
}
// FLAGS: CVZN
break;
case 0x91:
// subwc: subtract word with carry
{
const u32 result = m_r[R2] - m_r[R1] - (PSW(C) ? 1 : 0);
FLAGS_SUB(m_r[R2], m_r[R1], result);
m_r[R2] = result;
}
// FLAGS: CVZN
break;
case 0x93:
// negw: negate word
{
const u32 result = -m_r[R1];
FLAGS(
m_r[R1] != 0,
s32(m_r[R1]) == INT32_MIN,
result == 0,
BIT31(result));
m_r[R2] = result;
}
// FLAGS: CVZN
break;
case 0x98:
// mulw: multiply word
{
const s64 product = mul_32x32(m_r[R1], m_r[R2]);
m_r[R2] = s32(product);
FLAGS(0, (u64(product) >> 32) != (BIT31(product) ? ~u32(0) : 0), 0, 0);
// FLAGS: 0V00
}
break;
case 0x99:
// mulwx: multiply word extended
{
const s64 product = mul_32x32(m_r[R1], m_r[R2]);
set_64(R2, product);
FLAGS(0, (u64(product) >> 32) != (BIT31(product) ? ~u32(0) : 0), 0, 0);
// FLAGS: 0V00
}
break;
case 0x9a:
// mulwu: multiply word unsigned
{
const u64 product = mulu_32x32(m_r[R1], m_r[R2]);
m_r[R2] = u32(product);
FLAGS(0, (product >> 32) != 0, 0, 0);
// FLAGS: 0V00
}
break;
case 0x9b:
// mulwux: multiply word unsigned extended
{
const u64 product = mulu_32x32(m_r[R1], m_r[R2]);
set_64(R2, product);
FLAGS(0, (product >> 32) != 0, 0, 0);
// FLAGS: 0V00
}
break;
case 0x9c:
// divw: divide word
if (m_r[R1] != 0)
{
// FLAGS: 0V00
FLAGS(0, s32(m_r[R2]) == INT32_MIN && s32(m_r[R1]) == -1, 0, 0);
m_r[R2] = s32(m_r[R2]) / s32(m_r[R1]);
}
else
// TRAPS: D
m_exception = EXCEPTION_INTEGER_DIVIDE_BY_ZERO;
break;
case 0x9d:
// modw: modulus word
if (m_r[R1] != 0)
{
// FLAGS: 0V00
FLAGS(0, s32(m_r[R2]) == INT32_MIN && s32(m_r[R1]) == -1, 0, 0);
m_r[R2] = s32(m_r[R2]) % s32(m_r[R1]);
}
else
// TRAPS: D
m_exception = EXCEPTION_INTEGER_DIVIDE_BY_ZERO;
break;
case 0x9e:
// divwu: divide word unsigned
if (m_r[R1] != 0)
{
m_r[R2] = m_r[R2] / m_r[R1];
// FLAGS: 0000
FLAGS(0, 0, 0, 0);
}
else
// TRAPS: D
m_exception = EXCEPTION_INTEGER_DIVIDE_BY_ZERO;
break;
case 0x9f:
// modwu: modulus word unsigned
if (m_r[R1] != 0)
{
m_r[R2] = m_r[R2] % m_r[R1];
// FLAGS: 0000
FLAGS(0, 0, 0, 0);
}
else
// TRAPS: D
m_exception = EXCEPTION_INTEGER_DIVIDE_BY_ZERO;
break;
case 0xa0:
// subw: subtract word
{
const u32 result = m_r[R2] - m_r[R1];
FLAGS_SUB(m_r[R2], m_r[R1], result);
m_r[R2] = result;
}
// FLAGS: CVZN
break;
case 0xa2:
// subq: subtract quick
{
const u32 result = m_r[R2] - m_info.r1;
FLAGS_SUB(m_r[R2], m_info.r1, result);
m_r[R2] = result;
}
// FLAGS: CVZN
break;
case 0xa3:
// subi: subtract immediate
{
const u32 result = m_r[R2] - m_info.imm;
FLAGS_SUB(m_r[R2], m_info.imm, result);
m_r[R2] = result;
}
// FLAGS: CVZN
// TRAPS: I
break;
case 0xa4:
// cmpw: compare word
{
const u32 result = m_r[R2] - m_r[R1];
FLAGS_SUB(m_r[R2], m_r[R1], result);
}
// FLAGS: CVZN
break;
case 0xa6:
// cmpq: compare quick
{
const u32 result = m_r[R2] - m_info.r1;
FLAGS_SUB(m_r[R2], m_info.r1, result);
}
// FLAGS: CVZN
break;
case 0xa7:
// cmpi: compare immediate
{
const u32 result = m_r[R2] - m_info.imm;
FLAGS_SUB(m_r[R2], m_info.imm, result);
}
// FLAGS: CVZN
// TRAPS: I
break;
case 0xa8:
// xorw: exclusive or word
m_r[R2] ^= m_r[R1];
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
// FLAGS: 00ZN
break;
case 0xab:
// xori: exclusive or immediate
m_r[R2] ^= m_info.imm;
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
// FLAGS: 00ZN
// TRAPS: I
break;
case 0xac:
// notw: not word
m_r[R2] = ~m_r[R1];
FLAGS(0, 0, m_r[R2] == 0, BIT31(m_r[R2]));
// FLAGS: 00ZN
break;
case 0xae:
// notq: not quick
m_r[R2] = ~R1;
FLAGS(0, 0, 0, 1);
// FLAGS: 0001
break;
case 0xb4:
// unprivileged macro instructions
switch (m_info.subopcode)
{
case 0x00: case 0x01: case 0x02: case 0x03:
case 0x04: case 0x05: case 0x06: case 0x07:
case 0x08: case 0x09: case 0x0a: case 0x0b:
case 0x0c:
// savew0..savew12: push registers rN:r14
// store ri at sp - 4 * (15 - i)
for (int i = R2; i < 15 && !m_exception; i++)
get_dcammu().store<u32>(m_ssw, m_r[15] - 4 * (15 - i), m_r[i]);
// decrement sp after push to allow restart on exceptions
if (!m_exception)
m_r[15] -= 4 * (15 - R2);
// TRAPS: A,P,W
break;
// NOTE: the movc, initc and cmpc macro instructions are implemented in a very basic way because
// at some point they will need to be improved to deal with possible exceptions (e.g. page faults)
// that may occur during execution. The implementation here is intended to allow the instructions
// to be "continued" after such exceptions.
case 0x0d:
// movc: copy r0 bytes from r1 to r2
while (m_r[0])
{
get_dcammu().load<u8>(m_ssw, m_r[1], [this](u8 byte) { get_dcammu().store<u8>(m_ssw, m_r[2], byte); });
if (m_exception)
break;
m_r[0]--;
m_r[1]++;
m_r[2]++;
}
// TRAPS: C,U,P,R,W
break;
case 0x0e:
// initc: initialise r0 bytes at r1 with value in r2
while (m_r[0])
{
if (!get_dcammu().store<u8>(m_ssw, m_r[1], m_r[2]))
break;
m_r[0]--;
m_r[1]++;
m_r[2] = rotr32(m_r[2], 8);
}
// TRAPS: P,W
break;
case 0x0f:
// cmpc: compare r0 bytes at r1 with r2
// set condition codes assuming strings match
FLAGS(0, 0, 1, 0);
while (m_r[0])
{
// read and compare bytes (as signed 32 bit integers)
get_dcammu().load<s8>(m_ssw, m_r[1], [this](s32 byte1)
{
get_dcammu().load<s8>(m_ssw, m_r[2], [this, byte1](s32 byte2)
{
const s32 result = byte2 - byte1;
FLAGS_SUB(byte2, byte1, result);
});
});
// abort on exception or mismatch
if (m_exception || !PSW(Z))
break;
m_r[0]--;
m_r[1]++;
m_r[2]++;
}
// TRAPS: C,U,P,R
break;
case 0x10: case 0x11: case 0x12: case 0x13:
case 0x14: case 0x15: case 0x16: case 0x17:
case 0x18: case 0x19: case 0x1a: case 0x1b:
case 0x1c:
// restwN..restw12: pop registers rN:r14
// load ri from sp + 4 * (i - N)
for (int i = R2; i < 15 && !m_exception; i++)
get_dcammu().load<u32>(m_ssw, m_r[15] + 4 * (i - R2), [this, i](u32 v) { m_r[i] = v; });
// increment sp after pop to allow restart on exceptions
if (!m_exception)
m_r[15] += 4 * (15 - R2);
// TRAPS: C,U,A,P,R
break;
case 0x20: case 0x21: case 0x22: case 0x23:
case 0x24: case 0x25: case 0x26: case 0x27:
// saved0..saved7: push registers fN:f7
// store fi at sp - 8 * (8 - i)
for (int i = m_info.subopcode & 0x7; i < 8 && !m_exception; i++)
get_dcammu().store<u64>(m_ssw, m_r[15] - 8 * (8 - i), get_fp64(i).v);
// decrement sp after push to allow restart on exceptions
if (!m_exception)
m_r[15] -= 8 * (8 - (m_info.subopcode & 0x7));
// TRAPS: A,P,W
break;
case 0x28: case 0x29: case 0x2a: case 0x2b:
case 0x2c: case 0x2d: case 0x2e: case 0x2f:
// restd0..restd7: pop registers fN:f7
// load fi from sp + 8 * (i - N)
for (int i = m_info.subopcode & 0x7; i < 8 && !m_exception; i++)
get_dcammu().load<u64>(m_ssw, m_r[15] + 8 * (i - (m_info.subopcode & 0x7)), [this, i](u64 v) { set_fp(i, float64_t{ v }, F_NONE); });
// increment sp after pop to allow restart on exceptions
if (!m_exception)
m_r[15] += 8 * (8 - (m_info.subopcode & 0x7));
// TRAPS: C,U,A,P,R
break;
case 0x30:
// cnvsw: convert single floating to word
m_fp_pc = m_info.pc;
m_r[m_info.macro & 0xf] = f32_to_i32(get_fp32((m_info.macro >> 4) & 0xf), softfloat_roundingMode, true);
// TRAPS: F_IX
softfloat_exceptionFlags &= F_IX;
break;
case 0x31:
// cnvrsw: convert rounding single floating to word (non-IEEE +0.5/-0.5 rounding)
m_fp_pc = m_info.pc;
if (f32_lt(get_fp32((m_info.macro >> 4) & 0xf), float32_t{ 0 }))
m_r[m_info.macro & 0xf] = f32_to_i32(f32_sub(get_fp32((m_info.macro >> 4) & 0xf),
f32_div(i32_to_f32(1), i32_to_f32(2))), softfloat_round_minMag, true);
else
m_r[m_info.macro & 0xf] = f32_to_i32(f32_add(get_fp32((m_info.macro >> 4) & 0xf),
f32_div(i32_to_f32(1), i32_to_f32(2))), softfloat_round_minMag, true);
// TRAPS: F_IX
softfloat_exceptionFlags &= F_IX;
break;
case 0x32:
// cnvtsw: convert truncating single floating to word
m_fp_pc = m_info.pc;
m_r[m_info.macro & 0xf] = f32_to_i32(get_fp32((m_info.macro >> 4) & 0xf), softfloat_round_minMag, true);
// TRAPS: F_IX
softfloat_exceptionFlags &= F_IX;
break;
case 0x33:
// cnvws: convert word to single floating
set_fp(m_info.macro & 0xf, i32_to_f32(m_r[(m_info.macro >> 4) & 0xf]), F_X);
// TRAPS: F_X
break;
case 0x34:
// cnvdw: convert double floating to word
m_fp_pc = m_info.pc;
m_r[m_info.macro & 0xf] = f64_to_i32(get_fp64((m_info.macro >> 4) & 0xf), softfloat_roundingMode, true);
// TRAPS: F_IX
softfloat_exceptionFlags &= F_IX;
break;
case 0x35:
// cnvrdw: convert rounding double floating to word (non-IEEE +0.5/-0.5 rounding)
m_fp_pc = m_info.pc;
if (f64_lt(get_fp64((m_info.macro >> 4) & 0xf), float64_t{ 0 }))
m_r[m_info.macro & 0xf] = f64_to_i32(f64_sub(get_fp64((m_info.macro >> 4) & 0xf),
f64_div(i32_to_f64(1), i32_to_f64(2))), softfloat_round_minMag, true);
else
m_r[m_info.macro & 0xf] = f64_to_i32(f64_add(get_fp64((m_info.macro >> 4) & 0xf),
f64_div(i32_to_f64(1), i32_to_f64(2))), softfloat_round_minMag, true);
// TRAPS: F_IX
softfloat_exceptionFlags &= F_IX;
break;
case 0x36:
// cnvtdw: convert truncating double floating to word
m_fp_pc = m_info.pc;
m_r[m_info.macro & 0xf] = f64_to_i32(get_fp64((m_info.macro >> 4) & 0xf), softfloat_round_minMag, true);
// TRAPS: F_IX
softfloat_exceptionFlags &= F_IX;
break;
case 0x37:
// cnvwd: convert word to double floating
set_fp(m_info.macro & 0xf, i32_to_f64(m_r[(m_info.macro >> 4) & 0xf]), F_NONE);
break;
case 0x38:
// cnvsd: convert single to double floating
set_fp(m_info.macro & 0xf, f32_to_f64(get_fp32((m_info.macro >> 4) & 0xf)), F_I);
// TRAPS: F_I
break;
case 0x39:
// cnvds: convert double to single floating
set_fp(m_info.macro & 0xf, f64_to_f32(get_fp64((m_info.macro >> 4) & 0xf)), F_IVUX);
// TRAPS: F_IVUX
break;
case 0x3a:
// negs: negate single floating
set_fp(m_info.macro & 0xf, f32_mul(get_fp32((m_info.macro >> 4) & 0xf), i32_to_f32(-1)), F_NONE);
break;
case 0x3b:
// negd: negate double floating
set_fp(m_info.macro & 0xf, f64_mul(get_fp64((m_info.macro >> 4) & 0xf), i32_to_f64(-1)), F_NONE);
break;
case 0x3c:
/*
* This implementation for scalbd and scalbs is a bit opaque, but
* essentially we check if the integer value is within range, and
* directly create a floating constant representing 2^n or NaN
* respectively, which is used as an input to a multiply, producing
* the desired result. While doing an actual multiply is both
* inefficient and unnecessary, it's a tidy way to ensure the
* correct exception flags are set.
*/
// scalbs: scale by, single floating
set_fp(m_info.macro & 0xf, f32_mul(get_fp32(m_info.macro & 0xf),
((s32(m_r[(m_info.macro >> 4) & 0xf]) > -127 && s32(m_r[(m_info.macro >> 4) & 0xf]) < 128)
? float32_t{ u32(s32(m_r[(m_info.macro >> 4) & 0xf]) + 127) << 23 }
: float32_t{ ~u32(0) })), F_IVUX);
// TRAPS: F_IVUX
break;
case 0x3d:
// scalbd: scale by, double floating
set_fp(m_info.macro & 0xf, f64_mul(get_fp64(m_info.macro & 0xf),
(s32(m_r[(m_info.macro >> 4) & 0xf]) > -1023 && s32(m_r[(m_info.macro >> 4) & 0xf]) < 1024)
? float64_t{ u64(s32(m_r[(m_info.macro >> 4) & 0xf]) + 1023) << 52 }
: float64_t{ ~u64(0) }), F_IVUX);
// TRAPS: F_IVUX
break;
case 0x3e:
// trapfn: trap floating unordered
// TRAPS: I
if (PSW(Z) && PSW(N))
m_exception = EXCEPTION_ILLEGAL_OPERATION;
break;
case 0x3f:
// loadfs: load floating status
m_r[(m_info.macro >> 4) & 0xf] = m_fp_pc;
m_f[m_info.macro & 0xf] = m_fp_dst;
m_ssw |= SSW_FRD;
break;
default:
m_exception = EXCEPTION_ILLEGAL_OPERATION;
break;
}
break;
case 0xb6:
// privileged macro instructions
if (!SSW(U))
{
switch (m_info.subopcode)
{
case 0x00:
// movus: move user to supervisor
m_rs[m_info.macro & 0xf] = m_ru[(m_info.macro >> 4) & 0xf];
FLAGS(0, 0, m_rs[m_info.macro & 0xf] == 0, BIT31(m_rs[m_info.macro & 0xf]));
// FLAGS: 00ZN
// TRAPS: S
break;
case 0x01:
// movsu: move supervisor to user
m_ru[m_info.macro & 0xf] = m_rs[(m_info.macro >> 4) & 0xf];
FLAGS(0, 0, m_ru[m_info.macro & 0xf] == 0, BIT31(m_ru[m_info.macro & 0xf]));
// FLAGS: 00ZN
// TRAPS: S
break;
case 0x02:
// saveur: save user registers
for (int i = 0; i < 16 && !m_exception; i++)
get_dcammu().store<u32>(m_ssw, m_rs[(m_info.macro >> 4) & 0xf] - 4 * (i + 1), m_ru[15 - i]);
if (!m_exception)
m_rs[(m_info.macro >> 4) & 0xf] -= 64;
// TRAPS: A,P,W,S
break;
case 0x03:
// restur: restore user registers
for (int i = 0; i < 16 && !m_exception; i++)
get_dcammu().load<u32>(m_ssw, m_rs[(m_info.macro >> 4) & 0xf] + 4 * i, [this, i](u32 v) { m_ru[i] = v; });
if (!m_exception)
m_rs[(m_info.macro >> 4) & 0xf] += 64;
// TRAPS: C,U,A,P,R,S
break;
case 0x04:
// reti: restore psw, ssw and pc from supervisor stack
m_pc = reti();
// TRAPS: S
break;
case 0x05:
// wait: wait for interrupt
m_wait = true;
// TRAPS: S
break;
default:
m_exception = EXCEPTION_ILLEGAL_OPERATION;
break;
}
}
else
m_exception = EXCEPTION_PRIVILEGED_INSTRUCTION;
break;
default:
m_exception = EXCEPTION_ILLEGAL_OPERATION;
break;
}
}
u32 clipper_device::reti()
{
u32 new_psw = 0, new_ssw = 0, new_pc = 0;
// pop the psw, ssw and pc from the supervisor stack
if (!get_dcammu().load<u32>(m_ssw, m_rs[(m_info.macro >> 4) & 0xf] + 0, [&new_psw](u32 v) { new_psw = v; }))
fatalerror("reti unrecoverable fault 0x%04x pop psw address 0x%08x pc 0x%08x\n", m_exception, m_rs[(m_info.macro >> 4) & 0xf] + 0, m_info.pc);
if (!get_dcammu().load<u32>(m_ssw, m_rs[(m_info.macro >> 4) & 0xf] + 4, [&new_ssw](u32 v) { new_ssw = v; }))
fatalerror("reti unrecoverable fault 0x%04x pop ssw address 0x%08x pc 0x%08x\n", m_exception, m_rs[(m_info.macro >> 4) & 0xf] + 4, m_info.pc);
if (!get_dcammu().load<u32>(m_ssw, m_rs[(m_info.macro >> 4) & 0xf] + 8, [&new_pc](u32 v) { new_pc = v; }))
fatalerror("reti unrecoverable fault 0x%04x pop pc address 0x%08x pc 0x%08x\n", m_exception, m_rs[(m_info.macro >> 4) & 0xf] + 8, m_info.pc);
LOGMASKED(LOG_EXCEPTION, "reti r%d ssp 0x%08x pc 0x%08x ssw 0x%08x psw 0x%08x new_pc 0x%08x new_ssw 0x%08x new_psw 0x%08x\n",
(m_info.macro >> 4) & 0xf, m_rs[(m_info.macro >> 4) & 0xf], m_info.pc, m_ssw, m_psw, new_pc, new_ssw, new_psw);
// adjust the stack pointer
m_rs[(m_info.macro >> 4) & 0xf] += 12;
// restore the psw and ssw
set_psw(new_psw);
set_ssw(new_ssw);
// return the restored pc
return new_pc;
}
/*
* Common entry point for transferring control in the event of an interrupt or
* exception. Reading between the lines, it appears this logic was implemented
* using the macro instruction ROM and a special macro instruction (intrap).
*/
u32 clipper_device::intrap(const u16 vector, const u32 old_pc)
{
const u32 old_ssw = m_ssw;
const u32 old_psw = m_psw;
u32 new_pc = 0, new_ssw = 0;
// clear ssw bits to enable supervisor memory access
m_ssw &= ~(SSW_U | SSW_K | SSW_UU | SSW_KU);
// clear exception state
m_exception = 0;
// fetch next pc and ssw from interrupt vector
if (!get_dcammu().load<u32>(m_ssw, vector + 0, [&new_pc](u32 v) { new_pc = v; }))
fatalerror("intrap unrecoverable fault 0x%04x load pc address 0x%08x pc 0x%08x\n", m_exception, vector + 0, old_pc);
if (!get_dcammu().load<u32>(m_ssw, vector + 4, [&new_ssw](u32 v) { new_ssw = v; }))
fatalerror("intrap unrecoverable fault 0x%04x load ssw address 0x%08x pc 0x%08x\n", m_exception, vector + 4, old_pc);
LOGMASKED(LOG_EXCEPTION, "intrap vector 0x%04x pc 0x%08x ssp 0x%08x new_pc 0x%08x new_ssw 0x%08x\n", vector, old_pc, m_rs[15], new_pc, new_ssw);
// derive cts and mts from vector
u32 source = 0;
switch (vector)
{
// data memory trap group
case EXCEPTION_D_CORRECTED_MEMORY_ERROR:
case EXCEPTION_D_UNCORRECTABLE_MEMORY_ERROR:
case EXCEPTION_D_ALIGNMENT_FAULT:
case EXCEPTION_D_PAGE_FAULT:
case EXCEPTION_D_READ_PROTECT_FAULT:
case EXCEPTION_D_WRITE_PROTECT_FAULT:
// instruction memory trap group
case EXCEPTION_I_CORRECTED_MEMORY_ERROR:
case EXCEPTION_I_UNCORRECTABLE_MEMORY_ERROR:
case EXCEPTION_I_ALIGNMENT_FAULT:
case EXCEPTION_I_PAGE_FAULT:
case EXCEPTION_I_EXECUTE_PROTECT_FAULT:
source = (vector & MTS_VMASK) << (MTS_SHIFT - MTS_VSHIFT);
break;
// integer arithmetic trap group
case EXCEPTION_INTEGER_DIVIDE_BY_ZERO:
source = CTS_DIVIDE_BY_ZERO;
break;
// illegal operation trap group
case EXCEPTION_ILLEGAL_OPERATION:
source = CTS_ILLEGAL_OPERATION;
break;
case EXCEPTION_PRIVILEGED_INSTRUCTION:
source = CTS_PRIVILEGED_INSTRUCTION;
break;
// diagnostic trap group
case EXCEPTION_TRACE:
source = CTS_TRACE_TRAP;
break;
}
// push pc, ssw and psw onto supervisor stack
if (!get_dcammu().store<u32>(m_ssw, m_rs[15] - 0x4, old_pc))
fatalerror("intrap unrecoverable fault 0x%04x push pc ssp 0x%08x pc 0x%08x\n", m_exception, m_rs[15] - 0x4, old_pc);
if (!get_dcammu().store<u32>(m_ssw, m_rs[15] - 0x8, old_ssw))
fatalerror("intrap unrecoverable fault 0x%04x push ssw ssp 0x%08x pc 0x%08x\n", m_exception, m_rs[15] - 0x8, old_pc);
if (!get_dcammu().store<u32>(m_ssw, m_rs[15] - 0xc, (old_psw & ~(PSW_CTS | PSW_MTS)) | source))
fatalerror("intrap unrecoverable fault 0x%04x push psw ssp 0x%08x pc 0x%08x\n", m_exception, m_rs[15] - 0xc, old_pc);
// decrement supervisor stack pointer
m_rs[15] -= 12;
// set ssw from vector and previous mode
set_ssw((new_ssw & ~SSW_P) | (old_ssw & SSW_U) << 1);
// clear psw
set_psw(0);
// return new pc from trap vector
return new_pc;
}
u32 clipper_c400_device::intrap(const u16 vector, const u32 old_pc)
{
const u32 old_ssw = m_ssw;
const u32 old_psw = m_psw;
u32 new_pc = 0, new_ssw = 0;
// clear ssw bits to enable supervisor memory access
m_ssw &= ~(SSW_U | SSW_K | SSW_UU | SSW_KU);
// clear exception state
m_exception = 0;
// fetch ssw and pc from interrupt vector (C400 reversed wrt C100/C300)
if (!get_dcammu().load<u32>(m_ssw, vector + 0, [&new_ssw](u32 v) { new_ssw = v; }))
fatalerror("intrap unrecoverable fault 0x%04x load ssw address 0x%08x pc 0x%08x\n", m_exception, vector + 0, old_pc);
if (!get_dcammu().load<u32>(m_ssw, vector + 4, [&new_pc](u32 v) { new_pc = v; }))
fatalerror("intrap unrecoverable fault 0x%04x load pc address 0x%08x pc 0x%08x\n", m_exception, vector + 4, old_pc);
LOGMASKED(LOG_EXCEPTION, "intrap vector 0x%04x pc 0x%08x ssp 0x%08x new_pc 0x%08x new_ssw 0x%08x\n", vector, old_pc, m_rs[15], new_pc, new_ssw);
// derive cts and mts from vector
u32 source = 0;
switch (vector)
{
// data memory trap group
case EXCEPTION_D_CORRECTED_MEMORY_ERROR:
case EXCEPTION_D_UNCORRECTABLE_MEMORY_ERROR:
case EXCEPTION_D_ALIGNMENT_FAULT:
case EXCEPTION_D_PAGE_FAULT:
case EXCEPTION_D_READ_PROTECT_FAULT:
case EXCEPTION_D_WRITE_PROTECT_FAULT:
// instruction memory trap group
case EXCEPTION_I_CORRECTED_MEMORY_ERROR:
case EXCEPTION_I_UNCORRECTABLE_MEMORY_ERROR:
case EXCEPTION_I_ALIGNMENT_FAULT:
case EXCEPTION_I_PAGE_FAULT:
case EXCEPTION_I_EXECUTE_PROTECT_FAULT:
source = (vector & MTS_VMASK) << (MTS_SHIFT - MTS_VSHIFT);
break;
// integer arithmetic trap group
case EXCEPTION_INTEGER_DIVIDE_BY_ZERO:
source = CTS_DIVIDE_BY_ZERO;
break;
// illegal operation trap group
case EXCEPTION_ILLEGAL_OPERATION:
source = CTS_ILLEGAL_OPERATION;
break;
case EXCEPTION_PRIVILEGED_INSTRUCTION:
source = CTS_PRIVILEGED_INSTRUCTION;
break;
// diagnostic trap group
case EXCEPTION_TRACE:
source = CTS_TRACE_TRAP;
break;
}
// push pc, ssw and psw onto supervisor stack
if (!get_dcammu().store<u32>(m_ssw, m_rs[15] - 0x4, old_pc))
fatalerror("intrap unrecoverable fault 0x%04x push pc ssp 0x%08x pc 0x%08x\n", m_exception, m_rs[15] - 0x4, old_pc);
if (!get_dcammu().store<u32>(m_ssw, m_rs[15] - 0x8, old_ssw))
fatalerror("intrap unrecoverable fault 0x%04x push ssw ssp 0x%08x pc 0x%08x\n", m_exception, m_rs[15] - 0x8, old_pc);
if (!get_dcammu().store<u32>(m_ssw, m_rs[15] - 0xc, (old_psw & ~(PSW_CTS | PSW_MTS)) | source))
fatalerror("intrap unrecoverable fault 0x%04x push psw ssp 0x%08x pc 0x%08x\n", m_exception, m_rs[15] - 0xc, old_pc);
// TODO: push pc1
// TODO: push pc2
// push delayed branch pc onto supervisor stack
if (!get_dcammu().store<u32>(m_ssw, m_rs[15] - 0x18, m_db_pc))
fatalerror("intrap unrecoverable fault 0x%04x push db_pc address 0x%08x pc 0x%08x\n", m_exception, m_rs[15] - 0x18, old_pc);
// decrement supervisor stack pointer
m_rs[15] -= 24;
// set ssw from vector and previous mode
set_ssw((new_ssw & ~SSW_P) | (old_ssw & SSW_U) << 1);
// clear psw
set_psw(0);
// return new pc from trap vector
return new_pc;
}
bool clipper_device::evaluate_branch() const
{
switch (m_info.r2)
{
case BRANCH_T:
return true;
case BRANCH_LT:
return (!PSW(V) && !PSW(Z) && !PSW(N))
|| (PSW(V) && !PSW(Z) && PSW(N));
case BRANCH_LE:
return (!PSW(V) && !PSW(N))
|| (PSW(V) && !PSW(Z) && PSW(N));
case BRANCH_EQ:
return PSW(Z) && !PSW(N);
case BRANCH_GT:
return (!PSW(V) && !PSW(Z) && PSW(N))
|| (PSW(V) && !PSW(N));
case BRANCH_GE:
return (PSW(V) && !PSW(N))
|| (!PSW(V) && !PSW(Z) && PSW(N))
|| (PSW(Z) && !PSW(N));
case BRANCH_NE:
return (!PSW(Z))
|| (PSW(Z) && PSW(N));
case BRANCH_LTU:
return (!PSW(C) && !PSW(Z));
case BRANCH_LEU:
return !PSW(C);
case BRANCH_GTU:
return PSW(C);
case BRANCH_GEU:
return PSW(C) || PSW(Z);
case BRANCH_V:
return PSW(V);
case BRANCH_NV:
return !PSW(V);
case BRANCH_N:
return !PSW(Z) && PSW(N);
case BRANCH_NN:
return !PSW(N);
case BRANCH_FN:
return PSW(Z) && PSW(N);
}
return false;
}
void clipper_device::set_psw(const u32 psw)
{
// retain read-only endianness field
m_psw = (m_psw & PSW_BIG) | (psw & ~PSW_BIG);
// set the softfloat rounding mode based on the psw rounding mode
switch (PSW(FR))
{
case FR_0: softfloat_roundingMode = softfloat_round_near_even; break;
case FR_1: softfloat_roundingMode = softfloat_round_max; break;
case FR_2: softfloat_roundingMode = softfloat_round_min; break;
case FR_3: softfloat_roundingMode = softfloat_round_minMag; break;
}
}
void clipper_device::set_ssw(const u32 ssw)
{
// retain read-only id field
m_ssw = (m_ssw & SSW_ID) | (ssw & ~SSW_ID);
// select the register file
m_r = SSW(U) ? m_ru : m_rs;
}
void clipper_device::fp_exception()
{
u16 exception = 0;
/*
* Set the psw floating exception flags, and identify any enabled
* exceptions. The order here is important, but since the documentation
* doesn't explicitly specify, this is a guess. Simply put, exceptions
* are considered in sequence with an increasing order of priority.
*/
if (softfloat_exceptionFlags & softfloat_flag_inexact)
{
m_psw |= PSW_FX;
if (PSW(EFX))
exception = EXCEPTION_FLOATING_INEXACT;
}
if (softfloat_exceptionFlags & softfloat_flag_underflow)
{
m_psw |= PSW_FU;
if (PSW(EFU))
exception = EXCEPTION_FLOATING_UNDERFLOW;
}
if (softfloat_exceptionFlags & softfloat_flag_overflow)
{
m_psw |= PSW_FV;
if (PSW(EFV))
exception = EXCEPTION_FLOATING_OVERFLOW;
}
if (softfloat_exceptionFlags & softfloat_flag_infinite)
{
m_psw |= PSW_FD;
if (PSW(EFD))
exception = EXCEPTION_FLOATING_DIVIDE_BY_ZERO;
}
if (softfloat_exceptionFlags & softfloat_flag_invalid)
{
m_psw |= PSW_FI;
if (PSW(EFI))
exception = EXCEPTION_FLOATING_INVALID_OPERATION;
}
// trigger a floating point exception
if (PSW(EFT) && exception)
m_exception = exception;
}
void clipper_c400_device::execute_instruction()
{
// update delay slot pointer
switch (PSW(DSP))
{
case DSP_S1:
// take delayed branch
m_psw &= ~PSW_DSP;
m_pc = m_db_pc;
return;
case DSP_SALL:
// one delay slot still active
m_psw &= ~PSW_DSP;
m_psw |= DSP_S1;
break;
case DSP_SETUP:
// two delay slots active
m_psw &= ~PSW_DSP;
m_psw |= DSP_SALL;
break;
}
// if executing a delay slot instruction, test for valid type
if (PSW(DSP))
{
switch (m_info.opcode)
{
case 0x13: // ret
case 0x44: // call
case 0x45:
case 0x48: // b*
case 0x49:
case 0x4a: // cdb
case 0x4b:
case 0x4c: // cdbeq
case 0x4d:
case 0x4e: // cdbne
case 0x4f:
case 0x50: // db*
case 0x51:
// TODO: this should throw some kind of illegal instruction trap, not abort
fatalerror("instruction type 0x%02x invalid in branch delay slot pc 0x%08x\n", m_info.opcode, m_info.pc);
default:
break;
}
}
switch (m_info.opcode)
{
case 0x46:
case 0x47:
// loadd2: load double floating double
// TODO: 128-bit load
get_dcammu().load<u64>(m_ssw, m_info.address + 0, [this](u64 v) { set_fp(R2 + 0, float64_t{ v }, F_NONE); });
get_dcammu().load<u64>(m_ssw, m_info.address + 8, [this](u64 v) { set_fp(R2 + 1, float64_t{ v }, F_NONE); });
// TRAPS: C,U,A,P,R,I
break;
case 0x4a:
case 0x4b:
// cdb: compare and delayed branch?
// emulate.h: "cdb is special because it does not support all addressing modes", 2-3 parcels
fatalerror("cdb pc 0x%08x\n", m_info.pc);
case 0x4c:
case 0x4d:
// cdbeq: compare and delayed branch if equal?
if (m_r[R2] == 0)
{
m_psw |= DSP_SETUP;
m_db_pc = m_info.address;
}
break;
case 0x4e:
case 0x4f:
// cdbne: compare and delayed branch if not equal?
if (m_r[R2] != 0)
{
m_psw |= DSP_SETUP;
m_db_pc = m_info.address;
}
break;
case 0x50:
case 0x51:
// db*: delayed branch on condition
if (evaluate_branch())
{
m_psw |= DSP_SETUP;
m_db_pc = m_info.address;
}
break;
case 0xb0:
// abss: absolute value single floating?
if (f32_lt(get_fp32(R1), float32_t{ 0 }))
set_fp(R2, f32_mul(get_fp32(R1), i32_to_f32(-1)), F_IVUX);
else
set_fp(R2, get_fp32(R1), F_IVUX);
break;
case 0xb2:
// absd: absolute value double floating?
if (f64_lt(get_fp64(R1), float64_t{ 0 }))
set_fp(R2, f64_mul(get_fp64(R1), i32_to_f64(-1)), F_IVUX);
else
set_fp(R2, get_fp64(R1), F_IVUX);
break;
case 0xb4:
// unprivileged macro instructions
switch (m_info.subopcode)
{
case 0x44:
// cnvxsw: ??
fatalerror("cnvxsw pc 0x%08x\n", m_info.pc);
case 0x46:
// cnvxdw: ??
fatalerror("cnvxdw pc 0x%08x\n", m_info.pc);
default:
clipper_device::execute_instruction();
break;
}
break;
case 0xb6:
// privileged macro instructions
if (!SSW(U))
{
switch (m_info.subopcode)
{
case 0x07:
// loadts: unknown?
fatalerror("loadts pc 0x%08x\n", m_info.pc);
default:
clipper_device::execute_instruction();
break;
}
}
else
m_exception = EXCEPTION_PRIVILEGED_INSTRUCTION;
break;
case 0xbc:
// waitd:
if (!SSW(U))
; // TODO: don't know what this instruction does
else
m_exception = EXCEPTION_PRIVILEGED_INSTRUCTION;
break;
case 0xc0:
// s*: set register on condition
m_r[R1] = evaluate_branch() ? 1 : 0;
break;
default:
clipper_device::execute_instruction();
break;
}
}
std::unique_ptr<util::disasm_interface> clipper_device::create_disassembler()
{
return std::make_unique<clipper_disassembler>();
}
std::string clipper_device::debug_string(u32 pointer)
{
auto const suppressor(machine().disable_side_effects());
std::string s("");
while (true)
{
char c;
if (!get_dcammu().load<u8>(m_ssw, pointer++, [&c](u8 v) { c = v; }))
break;
if (c == '\0')
break;
s += c;
}
return s;
}
std::string clipper_device::debug_string_array(u32 array_pointer)
{
auto const suppressor(machine().disable_side_effects());
std::string s("");
while (true)
{
u32 string_pointer;
if (!get_dcammu().load<u32>(m_ssw, array_pointer, [&string_pointer](u32 v) { string_pointer = v; }))
break;
if (string_pointer == 0)
break;
if (!s.empty())
s += ", ";
s += '\"' + debug_string(string_pointer) + '\"';
array_pointer += 4;
}
return s;
}
| gpl-2.0 |
eisbear2020/ZI | themes/contrib/bootstrap/src/Annotation/PluginCallback.php | 1818 | <?php
namespace Drupal\bootstrap\Annotation;
use Drupal\bootstrap\Bootstrap;
use Drupal\Component\Annotation\AnnotationInterface;
use Drupal\Component\Annotation\PluginID;
/**
* Defines a Plugin annotation object that just contains an ID.
*
* @Annotation
*
* @ingroup utility
*/
class PluginCallback extends PluginID {
/**
* The plugin ID.
*
* When an annotation is given no key, 'value' is assumed by Doctrine.
*
* @var string
*/
public $value;
/**
* Flag that determines how to add the plugin to a callback array.
*
* @var \Drupal\bootstrap\Annotation\BootstrapConstant
*
* Must be one of the following constants:
* - \Drupal\bootstrap\Bootstrap::CALLBACK_APPEND
* - \Drupal\bootstrap\Bootstrap::CALLBACK_PREPEND
* - \Drupal\bootstrap\Bootstrap::CALLBACK_REPLACE_APPEND
* - \Drupal\bootstrap\Bootstrap::CALLBACK_REPLACE_PREPEND
* Use with @ BootstrapConstant annotation.
*
* @see \Drupal\bootstrap\Bootstrap::addCallback()
*/
public $action = Bootstrap::CALLBACK_APPEND;
/**
* A callback to replace.
*
* @var string
*/
public $replace = FALSE;
/**
* {@inheritdoc}
*/
public function get() {
$definition = parent::get();
$parent_properties = array_keys($definition);
$parent_properties[] = 'value';
// Merge in the defined properties.
$reflection = new \ReflectionClass($this);
foreach ($reflection->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
$name = $property->getName();
if (in_array($name, $parent_properties)) {
continue;
}
$value = $property->getValue($this);
if ($value instanceof AnnotationInterface) {
$value = $value->get();
}
$definition[$name] = $value;
}
return $definition;
}
}
| gpl-2.0 |
vikramaditya91/OpenFOAMVik | src/thermophysicalModels/specie/transport/sutherland/sutherlandTransport.H | 6362 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2013 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::sutherlandTransport
Description
Transport package using Sutherland's formula.
Templated into a given thermodynamics package (needed for thermal
conductivity).
Dynamic viscosity [kg/m.s]
\f[
\mu = A_s \frac{\sqrt{T}}{1 + T_s / T}
\f]
SourceFiles
sutherlandTransportI.H
sutherlandTransport.C
\*---------------------------------------------------------------------------*/
#ifndef sutherlandTransport_H
#define sutherlandTransport_H
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// Forward declaration of friend functions and operators
template<class Thermo> class sutherlandTransport;
template<class Thermo>
inline sutherlandTransport<Thermo> operator+
(
const sutherlandTransport<Thermo>&,
const sutherlandTransport<Thermo>&
);
template<class Thermo>
inline sutherlandTransport<Thermo> operator-
(
const sutherlandTransport<Thermo>&,
const sutherlandTransport<Thermo>&
);
template<class Thermo>
inline sutherlandTransport<Thermo> operator*
(
const scalar,
const sutherlandTransport<Thermo>&
);
template<class Thermo>
inline sutherlandTransport<Thermo> operator==
(
const sutherlandTransport<Thermo>&,
const sutherlandTransport<Thermo>&
);
template<class Thermo>
Ostream& operator<<
(
Ostream&,
const sutherlandTransport<Thermo>&
);
/*---------------------------------------------------------------------------*\
Class sutherlandTransport Declaration
\*---------------------------------------------------------------------------*/
template<class Thermo>
class sutherlandTransport
:
public Thermo
{
// Private data
// Sutherland's coefficients
scalar As_, Ts_;
// Private Member Functions
//- Calculate the Sutherland coefficients
// given two viscosities and temperatures
inline void calcCoeffs
(
const scalar mu1, const scalar T1,
const scalar mu2, const scalar T2
);
public:
// Constructors
//- Construct from components
inline sutherlandTransport
(
const Thermo& t,
const scalar As,
const scalar Ts
);
//- Construct from two viscosities
inline sutherlandTransport
(
const Thermo& t,
const scalar mu1, const scalar T1,
const scalar mu2, const scalar T2
);
//- Construct as named copy
inline sutherlandTransport(const word&, const sutherlandTransport&);
//- Construct from Istream
sutherlandTransport(Istream&);
//- Construct from dictionary
sutherlandTransport(const dictionary& dict);
//- Construct and return a clone
inline autoPtr<sutherlandTransport> clone() const;
// Selector from Istream
inline static autoPtr<sutherlandTransport> New(Istream& is);
// Selector from dictionary
inline static autoPtr<sutherlandTransport> New(const dictionary& dict);
// Member functions
//- Return the instantiated type name
static word typeName()
{
return "sutherland<" + Thermo::typeName() + '>';
}
//- Dynamic viscosity [kg/ms]
inline scalar mu(const scalar p, const scalar T) const;
//- Thermal conductivity [W/mK]
inline scalar kappa(const scalar p, const scalar T) const;
//- Thermal diffusivity of enthalpy [kg/ms]
inline scalar alphah(const scalar p, const scalar T) const;
// Species diffusivity
//inline scalar D(const scalar p, const scalar T) const;
//- Write to Ostream
void write(Ostream& os) const;
// Member operators
inline sutherlandTransport& operator=(const sutherlandTransport&);
inline void operator+=(const sutherlandTransport&);
inline void operator-=(const sutherlandTransport&);
inline void operator*=(const scalar);
// Friend operators
friend sutherlandTransport operator+ <Thermo>
(
const sutherlandTransport&,
const sutherlandTransport&
);
friend sutherlandTransport operator- <Thermo>
(
const sutherlandTransport&,
const sutherlandTransport&
);
friend sutherlandTransport operator* <Thermo>
(
const scalar,
const sutherlandTransport&
);
friend sutherlandTransport operator== <Thermo>
(
const sutherlandTransport&,
const sutherlandTransport&
);
// Ostream Operator
friend Ostream& operator<< <Thermo>
(
Ostream&,
const sutherlandTransport&
);
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "sutherlandTransportI.H"
#ifdef NoRepository
# include "sutherlandTransport.C"
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| gpl-3.0 |
Godin/checkstyle | src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/grammars/SemicolonBetweenImports.java | 295 | package com.puppycrawl.tools.checkstyle.grammars;
import java.util.Arrays;
;
import java.util.ArrayList;
/**
* Compilable by javac, but noncompilable by eclipse due to
* this <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=425140">bug</a>
*/
public class SemicolonBetweenImports
{
}
| lgpl-2.1 |
shlin/SHIH-WebSites | dal/mgt/editor/plugins/autogrow/fckplugin.js | 2347 | /*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Plugin: automatically resizes the editor until a configurable maximun
* height (FCKConfig.AutoGrowMax), based on its contents.
*/
var FCKAutoGrow_Min = window.frameElement.offsetHeight ;
function FCKAutoGrow_Check()
{
var oInnerDoc = FCK.EditorDocument ;
var iFrameHeight, iInnerHeight ;
if ( FCKBrowserInfo.IsIE )
{
iFrameHeight = FCK.EditorWindow.frameElement.offsetHeight ;
iInnerHeight = oInnerDoc.body.scrollHeight ;
}
else
{
iFrameHeight = FCK.EditorWindow.innerHeight ;
iInnerHeight = oInnerDoc.body.offsetHeight ;
}
var iDiff = iInnerHeight - iFrameHeight ;
if ( iDiff != 0 )
{
var iMainFrameSize = window.frameElement.offsetHeight ;
if ( iDiff > 0 && iMainFrameSize < FCKConfig.AutoGrowMax )
{
iMainFrameSize += iDiff ;
if ( iMainFrameSize > FCKConfig.AutoGrowMax )
iMainFrameSize = FCKConfig.AutoGrowMax ;
}
else if ( iDiff < 0 && iMainFrameSize > FCKAutoGrow_Min )
{
iMainFrameSize += iDiff ;
if ( iMainFrameSize < FCKAutoGrow_Min )
iMainFrameSize = FCKAutoGrow_Min ;
}
else
return ;
window.frameElement.height = iMainFrameSize ;
}
}
FCK.AttachToOnSelectionChange( FCKAutoGrow_Check ) ;
function FCKAutoGrow_SetListeners()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return ;
FCK.EditorWindow.attachEvent( 'onscroll', FCKAutoGrow_Check ) ;
FCK.EditorDocument.attachEvent( 'onkeyup', FCKAutoGrow_Check ) ;
}
if ( FCKBrowserInfo.IsIE )
{
// FCKAutoGrow_SetListeners() ;
FCK.Events.AttachEvent( 'OnAfterSetHTML', FCKAutoGrow_SetListeners ) ;
}
function FCKAutoGrow_CheckEditorStatus( sender, status )
{
if ( status == FCK_STATUS_COMPLETE )
FCKAutoGrow_Check() ;
}
FCK.Events.AttachEvent( 'OnStatusChange', FCKAutoGrow_CheckEditorStatus ) ; | unlicense |
LeoYao/voldemort | src/java/voldemort/store/CompositeVersionedPutVoldemortRequest.java | 1794 | /*
* Copyright 2013 LinkedIn, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package voldemort.store;
import voldemort.common.VoldemortOpCode;
import voldemort.server.RequestRoutingType;
import voldemort.versioning.Versioned;
/**
* A class that defines a composite put request containing the key, the
* versioned value, the timeout, routing type and origin time
*
*/
public class CompositeVersionedPutVoldemortRequest<K, V> extends CompositeVoldemortRequest<K, V> {
public CompositeVersionedPutVoldemortRequest(K key, Versioned<V> value, long timeoutInMs) {
super(key, null, null, value, null, timeoutInMs, true, VoldemortOpCode.PUT_OP_CODE);
}
public CompositeVersionedPutVoldemortRequest(K key,
Versioned<V> value,
long timeoutInMs,
long originTimeInMs,
RequestRoutingType routingType) {
super(key,
null,
null,
value,
null,
timeoutInMs,
false,
VoldemortOpCode.PUT_OP_CODE,
originTimeInMs,
routingType);
}
}
| apache-2.0 |
qinqinnb/nutz | src/org/nutz/el/obj/AbstractObj.java | 676 | package org.nutz.el.obj;
import org.nutz.el.ElCache;
import org.nutz.lang.util.Context;
/**
* 对象
* @author juqkai([email protected])
*/
public class AbstractObj implements Elobj{
private String val;
private ElCache ec;
public AbstractObj(String val) {
this.val = val;
}
public String getVal() {
return val;
}
public Object fetchVal(){
Context context = ec.getContext();
if(context != null && context.has(val)){
return context.get(val);
}
return null;
}
public String toString() {
return val;
}
public void setEc(ElCache ec) {
this.ec = ec;
}
}
| apache-2.0 |
wangqianbo/bysj | giraph-core/src/main/java/org/apache/giraph/comm/package-info.java | 904 | /*
* 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 of communication related objects, IPC service.
*/
package org.apache.giraph.comm;
| apache-2.0 |
InMobi/falcon | oozie/src/main/java/org/apache/falcon/oozie/process/PigProcessWorkflowBuilder.java | 3198 | /**
* 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.falcon.oozie.process;
import org.apache.falcon.FalconException;
import org.apache.falcon.entity.EntityUtil;
import org.apache.falcon.entity.v0.cluster.Cluster;
import org.apache.falcon.entity.v0.process.Process;
import org.apache.falcon.oozie.workflow.ACTION;
import org.apache.falcon.oozie.workflow.DELETE;
import org.apache.falcon.oozie.workflow.PIG;
import org.apache.falcon.oozie.workflow.PREPARE;
import org.apache.hadoop.fs.Path;
import java.util.List;
/**
* Builds orchestration workflow for process where engine is pig.
*/
public class PigProcessWorkflowBuilder extends ProcessExecutionWorkflowBuilder {
private static final String ACTION_TEMPLATE = "/action/process/pig-action.xml";
public PigProcessWorkflowBuilder(Process entity) {
super(entity);
}
@Override protected ACTION getUserAction(Cluster cluster, Path buildPath) throws FalconException {
ACTION action = unmarshalAction(ACTION_TEMPLATE);
PIG pigAction = action.getPig();
Path userWfPath = new Path(entity.getWorkflow().getPath());
pigAction.setScript(getStoragePath(userWfPath));
addPrepareDeleteOutputPath(pigAction);
final List<String> paramList = pigAction.getParam();
addInputFeedsAsParams(paramList, cluster);
addOutputFeedsAsParams(paramList, cluster);
propagateEntityProperties(pigAction.getConfiguration(), pigAction.getParam());
if (EntityUtil.isTableStorageType(cluster, entity)) { // adds hive-site.xml in pig classpath
pigAction.getFile().add("${wf:appPath()}/conf/hive-site.xml");
}
addArchiveForCustomJars(cluster, pigAction.getArchive(), entity.getWorkflow().getLib());
return action;
}
private void addPrepareDeleteOutputPath(PIG pigAction) throws FalconException {
List<String> deleteOutputPathList = getPrepareDeleteOutputPathList();
if (deleteOutputPathList.isEmpty()) {
return;
}
final PREPARE prepare = new PREPARE();
final List<DELETE> deleteList = prepare.getDelete();
for (String deletePath : deleteOutputPathList) {
final DELETE delete = new DELETE();
delete.setPath(deletePath);
deleteList.add(delete);
}
if (!deleteList.isEmpty()) {
pigAction.setPrepare(prepare);
}
}
}
| apache-2.0 |
ItsAsbreuk/itsa-cli | project-templates/reactfiber/externals/react-fiber/src/renderers/shared/shared/event/BrowserEventConstants.js | 2969 | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule BrowserEventConstants
*/
'use strict';
var getVendorPrefixedEventName = require('getVendorPrefixedEventName');
/**
* Types of raw signals from the browser caught at the top level.
*
* For events like 'submit' which don't consistently bubble (which we
* trap at a lower node than `document`), binding at `document` would
* cause duplicate events so we don't include them here.
*/
var topLevelTypes = {
topAbort: 'abort',
topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend',
topAnimationIteration: getVendorPrefixedEventName('animationiteration') ||
'animationiteration',
topAnimationStart: getVendorPrefixedEventName('animationstart') ||
'animationstart',
topBlur: 'blur',
topCancel: 'cancel',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topChange: 'change',
topClick: 'click',
topClose: 'close',
topCompositionEnd: 'compositionend',
topCompositionStart: 'compositionstart',
topCompositionUpdate: 'compositionupdate',
topContextMenu: 'contextmenu',
topCopy: 'copy',
topCut: 'cut',
topDoubleClick: 'dblclick',
topDrag: 'drag',
topDragEnd: 'dragend',
topDragEnter: 'dragenter',
topDragExit: 'dragexit',
topDragLeave: 'dragleave',
topDragOver: 'dragover',
topDragStart: 'dragstart',
topDrop: 'drop',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topFocus: 'focus',
topInput: 'input',
topKeyDown: 'keydown',
topKeyPress: 'keypress',
topKeyUp: 'keyup',
topLoadedData: 'loadeddata',
topLoad: 'load',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topMouseDown: 'mousedown',
topMouseMove: 'mousemove',
topMouseOut: 'mouseout',
topMouseOver: 'mouseover',
topMouseUp: 'mouseup',
topPaste: 'paste',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topScroll: 'scroll',
topSeeked: 'seeked',
topSeeking: 'seeking',
topSelectionChange: 'selectionchange',
topStalled: 'stalled',
topSuspend: 'suspend',
topTextInput: 'textInput',
topTimeUpdate: 'timeupdate',
topToggle: 'toggle',
topTouchCancel: 'touchcancel',
topTouchEnd: 'touchend',
topTouchMove: 'touchmove',
topTouchStart: 'touchstart',
topTransitionEnd: getVendorPrefixedEventName('transitionend') ||
'transitionend',
topVolumeChange: 'volumechange',
topWaiting: 'waiting',
topWheel: 'wheel',
};
export type TopLevelTypes = $Enum<typeof topLevelTypes>;
var BrowserEventConstants = {
topLevelTypes,
};
module.exports = BrowserEventConstants;
| bsd-3-clause |
xuebingwu/kpLogo | include/boost/intrusive/any_hook.hpp | 10455 | /////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2013
//
// 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)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTRUSIVE_ANY_HOOK_HPP
#define BOOST_INTRUSIVE_ANY_HOOK_HPP
#if defined(_MSC_VER)
# pragma once
#endif
#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/intrusive_fwd.hpp>
#include <boost/intrusive/detail/any_node_and_algorithms.hpp>
#include <boost/intrusive/options.hpp>
#include <boost/intrusive/detail/generic_hook.hpp>
#include <boost/intrusive/detail/mpl.hpp>
#include <boost/intrusive/pointer_rebind.hpp>
namespace boost {
namespace intrusive {
//! Helper metafunction to define a \c \c any_base_hook that yields to the same
//! type when the same options (either explicitly or implicitly) are used.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class ...Options>
#else
template<class O1 = void, class O2 = void, class O3 = void>
#endif
struct make_any_base_hook
{
/// @cond
typedef typename pack_options
< hook_defaults,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3
#else
Options...
#endif
>::type packed_options;
typedef generic_hook
< any_algorithms<typename packed_options::void_pointer>
, typename packed_options::tag
, packed_options::link_mode
, AnyBaseHookId
> implementation_defined;
/// @endcond
typedef implementation_defined type;
};
//! Derive a class from this hook in order to store objects of that class
//! in an intrusive container.
//!
//! The hook admits the following options: \c tag<>, \c void_pointer<> and
//! \c link_mode<>.
//!
//! \c tag<> defines a tag to identify the node.
//! The same tag value can be used in different classes, but if a class is
//! derived from more than one \c any_base_hook, then each \c any_base_hook needs its
//! unique tag.
//!
//! \c link_mode<> will specify the linking mode of the hook (\c normal_link, \c safe_link).
//!
//! \c void_pointer<> is the pointer type that will be used internally in the hook
//! and the container configured to use this hook.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class ...Options>
#else
template<class O1, class O2, class O3>
#endif
class any_base_hook
: public make_any_base_hook
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
<O1, O2, O3>
#else
<Options...>
#endif
::type
{
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
public:
//! <b>Effects</b>: If link_mode is or \c safe_link
//! initializes the node to an unlinked state.
//!
//! <b>Throws</b>: Nothing.
any_base_hook();
//! <b>Effects</b>: If link_mode is or \c safe_link
//! initializes the node to an unlinked state. The argument is ignored.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Rationale</b>: Providing a copy-constructor
//! makes classes using the hook STL-compliant without forcing the
//! user to do some additional work. \c swap can be used to emulate
//! move-semantics.
any_base_hook(const any_base_hook& );
//! <b>Effects</b>: Empty function. The argument is ignored.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Rationale</b>: Providing an assignment operator
//! makes classes using the hook STL-compliant without forcing the
//! user to do some additional work. \c swap can be used to emulate
//! move-semantics.
any_base_hook& operator=(const any_base_hook& );
//! <b>Effects</b>: If link_mode is \c normal_link, the destructor does
//! nothing (ie. no code is generated). If link_mode is \c safe_link and the
//! object is stored in a container an assertion is raised.
//!
//! <b>Throws</b>: Nothing.
~any_base_hook();
//! <b>Precondition</b>: link_mode must be \c safe_link.
//!
//! <b>Returns</b>: true, if the node belongs to a container, false
//! otherwise. This function can be used to test whether \c container::iterator_to
//! will return a valid iterator.
//!
//! <b>Complexity</b>: Constant
bool is_linked() const;
#endif
};
//! Helper metafunction to define a \c \c any_member_hook that yields to the same
//! type when the same options (either explicitly or implicitly) are used.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class ...Options>
#else
template<class O1 = void, class O2 = void, class O3 = void>
#endif
struct make_any_member_hook
{
/// @cond
typedef typename pack_options
< hook_defaults,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3
#else
Options...
#endif
>::type packed_options;
typedef generic_hook
< any_algorithms<typename packed_options::void_pointer>
, member_tag
, packed_options::link_mode
, NoBaseHookId
> implementation_defined;
/// @endcond
typedef implementation_defined type;
};
//! Store this hook in a class to be inserted
//! in an intrusive container.
//!
//! The hook admits the following options: \c void_pointer<> and
//! \c link_mode<>.
//!
//! \c link_mode<> will specify the linking mode of the hook (\c normal_link or \c safe_link).
//!
//! \c void_pointer<> is the pointer type that will be used internally in the hook
//! and the container configured to use this hook.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class ...Options>
#else
template<class O1, class O2, class O3>
#endif
class any_member_hook
: public make_any_member_hook
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
<O1, O2, O3>
#else
<Options...>
#endif
::type
{
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
public:
//! <b>Effects</b>: If link_mode is or \c safe_link
//! initializes the node to an unlinked state.
//!
//! <b>Throws</b>: Nothing.
any_member_hook();
//! <b>Effects</b>: If link_mode is or \c safe_link
//! initializes the node to an unlinked state. The argument is ignored.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Rationale</b>: Providing a copy-constructor
//! makes classes using the hook STL-compliant without forcing the
//! user to do some additional work. \c swap can be used to emulate
//! move-semantics.
any_member_hook(const any_member_hook& );
//! <b>Effects</b>: Empty function. The argument is ignored.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Rationale</b>: Providing an assignment operator
//! makes classes using the hook STL-compliant without forcing the
//! user to do some additional work. \c swap can be used to emulate
//! move-semantics.
any_member_hook& operator=(const any_member_hook& );
//! <b>Effects</b>: If link_mode is \c normal_link, the destructor does
//! nothing (ie. no code is generated). If link_mode is \c safe_link and the
//! object is stored in a container an assertion is raised.
//!
//! <b>Throws</b>: Nothing.
~any_member_hook();
//! <b>Precondition</b>: link_mode must be \c safe_link.
//!
//! <b>Returns</b>: true, if the node belongs to a container, false
//! otherwise. This function can be used to test whether \c container::iterator_to
//! will return a valid iterator.
//!
//! <b>Complexity</b>: Constant
bool is_linked() const;
#endif
};
/// @cond
namespace detail{
BOOST_INTRUSIVE_INTERNAL_STATIC_BOOL_IS_TRUE(old_proto_value_traits_base_hook, hooktags::is_base_hook)
//!This option setter specifies that the container
//!must use the specified base hook
template<class BasicHook, template <class> class NodeTraits>
struct any_to_some_hook
{
typedef typename BasicHook::template pack<empty>::proto_value_traits old_proto_value_traits;
template<class Base>
struct pack : public Base
{
struct proto_value_traits
{
//proto_value_traits::hooktags::is_base_hook is used by get_value_traits
//to detect base hooks, so mark it in case BasicHook has it.
struct hooktags
{
static const bool is_base_hook = old_proto_value_traits_base_hook_bool_is_true
<old_proto_value_traits>::value;
};
typedef old_proto_value_traits basic_hook_t;
static const bool is_any_hook = true;
template<class VoidPtr>
struct node_traits_from_voidptr
{ typedef NodeTraits<VoidPtr> type; };
};
};
};
} //namespace detail{
/// @endcond
//!This option setter specifies that
//!any hook should behave as an slist hook
template<class BasicHook>
struct any_to_slist_hook
/// @cond
: public detail::any_to_some_hook<BasicHook, any_slist_node_traits>
/// @endcond
{};
//!This option setter specifies that
//!any hook should behave as an list hook
template<class BasicHook>
struct any_to_list_hook
/// @cond
: public detail::any_to_some_hook<BasicHook, any_list_node_traits>
/// @endcond
{};
//!This option setter specifies that
//!any hook should behave as a set hook
template<class BasicHook>
struct any_to_set_hook
/// @cond
: public detail::any_to_some_hook<BasicHook, any_rbtree_node_traits>
/// @endcond
{};
//!This option setter specifies that
//!any hook should behave as an avl_set hook
template<class BasicHook>
struct any_to_avl_set_hook
/// @cond
: public detail::any_to_some_hook<BasicHook, any_avltree_node_traits>
/// @endcond
{};
//!This option setter specifies that any
//!hook should behave as a bs_set hook
template<class BasicHook>
struct any_to_bs_set_hook
/// @cond
: public detail::any_to_some_hook<BasicHook, any_tree_node_traits>
/// @endcond
{};
//!This option setter specifies that any hook
//!should behave as an unordered set hook
template<class BasicHook>
struct any_to_unordered_set_hook
/// @cond
: public detail::any_to_some_hook<BasicHook, any_unordered_node_traits>
/// @endcond
{};
} //namespace intrusive
} //namespace boost
#include <boost/intrusive/detail/config_end.hpp>
#endif //BOOST_INTRUSIVE_ANY_HOOK_HPP
| mit |
thejonanshow/my-boxen | vendor/bundle/ruby/2.3.0/gems/open4-1.3.4/samples/block.rb | 472 | require 'open4'
#
# when using block form the child process is automatically waited using
# waitpid2
#
status =
Open4::popen4("sh") do |pid, stdin, stdout, stderr|
stdin.puts "echo 42.out"
stdin.puts "echo 42.err 1>&2"
stdin.close
puts "pid : #{ pid }"
puts "stdout : #{ stdout.read.strip }"
puts "stderr : #{ stderr.read.strip }"
end
puts "status : #{ status.inspect }"
puts "exitstatus : #{ status.exitstatus }"
| mit |
markogresak/DefinitelyTyped | types/carbon__icons-react/lib/qr-code/32.d.ts | 55 | import { QrCode32 } from "../../";
export = QrCode32;
| mit |
markogresak/DefinitelyTyped | types/carbon__icons-react/lib/logo--openshift/24.d.ts | 69 | import { LogoOpenshift24 } from "../../";
export = LogoOpenshift24;
| mit |
mese79/three.js | test/unit/src/extras/curves/LineCurve3.js | 123 | /**
* @author TristanVALCKE / https://github.com/TristanVALCKE
*/
//Todo
console.warn("Todo: Unit tests of LineCurve3")
| mit |
coolweb/openhab | bundles/action/org.openhab.action.xmpp/src/main/java/org/openhab/action/xmpp/internal/XMPPConnect.java | 9247 | /**
* Copyright (c) 2010-2016, openHAB.org 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.openhab.action.xmpp.internal;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Dictionary;
import javax.net.ssl.SSLContext;
import org.apache.commons.lang.StringUtils;
import org.jivesoftware.smack.AbstractConnectionListener;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.util.DNSUtil;
import org.jivesoftware.smack.util.dns.javax.JavaxResolver;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.geekplace.javapinning.JavaPinning;
/**
* This class provides XMPP access. An account can be configured, which is then
* used for sending and receiving messages.
*
* @author Kai Kreuzer
* @since 0.4.0
*/
public class XMPPConnect implements ManagedService {
static {
// Workaround for SMACK-635. This can be removed once Smack 4.1 (or higher) is used
// See https://igniterealtime.org/issues/browse/SMACK-635
DNSUtil.setDNSResolver(JavaxResolver.getInstance());
}
static private final Logger logger = LoggerFactory.getLogger(XMPPConnect.class);
private static String servername;
private static String proxy;
private static Integer port;
private static String username;
private static String password;
private static String chatroom;
private static String chatnickname;
private static String chatpassword;
private static String[] consoleUsers;
private static SecurityMode securityMode = SecurityMode.disabled;
private static String tlsPin;
private static boolean initialized = false;
private static XMPPConnection connection;
private static MultiUserChat chat;
@Override
@SuppressWarnings("rawtypes")
public void updated(Dictionary config) throws ConfigurationException {
if (config == null) {
return;
}
XMPPConnect.servername = (String) config.get("servername");
XMPPConnect.proxy = (String) config.get("proxy");
String portString = (String) config.get("port");
if (portString != null) {
XMPPConnect.port = Integer.valueOf(portString);
}
XMPPConnect.username = (String) config.get("username");
XMPPConnect.password = (String) config.get("password");
XMPPConnect.chatroom = (String) config.get("chatroom");
XMPPConnect.chatnickname = (String) config.get("chatnickname");
XMPPConnect.chatpassword = (String) config.get("chatpassword");
String securityModeString = (String) config.get("securitymode");
if (securityModeString != null) {
securityMode = SecurityMode.valueOf(securityModeString);
}
XMPPConnect.tlsPin = (String) config.get("tlspin");
String users = (String) config.get("consoleusers");
if (!StringUtils.isEmpty(users)) {
XMPPConnect.consoleUsers = users.split(",");
} else {
XMPPConnect.consoleUsers = new String[0];
}
// check mandatory settings
if (StringUtils.isEmpty(servername)) {
return;
}
if (StringUtils.isEmpty(username)) {
return;
}
if (StringUtils.isEmpty(password)) {
return;
}
// set defaults for optional settings
if (port == null) {
port = 5222;
}
if (StringUtils.isEmpty(chatnickname)) {
chatnickname = "openhab-bot";
}
establishConnection();
}
private static void establishConnection() {
if (servername == null) {
return;
}
ConnectionConfiguration config;
// Create a connection to the jabber server on the given port
if (proxy != null) {
config = new ConnectionConfiguration(servername, port, proxy);
} else {
config = new ConnectionConfiguration(servername, port);
}
config.setSecurityMode(securityMode);
if (tlsPin != null) {
try {
SSLContext sc = JavaPinning.forPin(tlsPin);
config.setCustomSSLContext(sc);
} catch (KeyManagementException | NoSuchAlgorithmException e) {
logger.error("Could not create TLS Pin for XMPP connection", e);
}
}
if (connection != null && connection.isConnected()) {
try {
connection.disconnect();
} catch (NotConnectedException e) {
logger.debug("Already disconnected", e);
}
}
connection = new XMPPTCPConnection(config);
try {
connection.connect();
connection.login(username, password, null);
if (consoleUsers.length > 0) {
ChatManager.getInstanceFor(connection).addChatListener(new XMPPConsole(consoleUsers));
connection.addConnectionListener(new XMPPConnectionListener());
}
logger.info("Connection to XMPP as '{}' has been established. Is secure/encrypted: {}",
connection.getUser(), connection.isSecureConnection());
initialized = true;
} catch (Exception e) {
logger.error("Could not establish connection to XMPP server '" + servername + ":" + port + "': {}",
e.getMessage());
}
}
private static void joinChat() throws NotInitializedException {
if (chatroom == null) {
return;
}
if (!initialized) {
establishConnection();
if (!initialized) {
throw new NotInitializedException();
}
}
chat = new MultiUserChat(connection, chatroom);
try {
if (chatpassword != null) {
chat.join(chatnickname, chatpassword);
} else {
chat.join(chatnickname);
}
logger.info("Successfuly joined chat '{}' with nickname '{}'.", chatroom, chatnickname);
} catch (XMPPException e) {
logger.error("Could not join chat '{}' with nickname '{}': {}", chatroom, chatnickname, e.getMessage());
} catch (SmackException e) {
logger.error("Could not join chat '{}' with nickname '{}': {}", chatroom, chatnickname, e.getMessage());
}
}
/**
* returns the active connection which can be used to send messages
*
* @return the XMPP connection
* @throws NotInitializedException
* if the connection has not been established successfully
*/
public static XMPPConnection getConnection() throws NotInitializedException {
if (!initialized) {
establishConnection();
if (!initialized) {
throw new NotInitializedException();
}
}
return connection;
}
/**
* returns the active chat which can be used to send messages to a room
*
* @return the XMPP connection
* @throws NotInitializedException
* if the chat has not been successfully joined
*/
public static MultiUserChat getChat() throws NotInitializedException {
if (chat == null) {
joinChat();
}
if (!chat.isJoined()) {
joinChat();
if (!chat.isJoined()) {
throw new NotInitializedException();
}
}
return chat;
}
private static class XMPPConnectionListener extends AbstractConnectionListener {
@Override
public void connectionClosed() {
logger.debug("XMPP connection has been closed.");
initialized = false;
}
@Override
public void connectionClosedOnError(Exception e) {
// Log a warning and the *full* exception as the stacktrace could be useful to diagnose
// the issue for uncommon exceptions besides e.g. a broken pipe
logger.warn("XMPP connection has been closed on error: {}", e);
try {
if (!connection.isConnected()) {
initialized = false;
getConnection();
}
logger.info("XMPP re-connection succeeded.");
} catch (NotInitializedException nie) {
logger.error("XMPP re-connection failed, giving up: {}", nie.getMessage());
}
}
}
}
| epl-1.0 |
eyohansa/wesnoth | src/gui/dialogs/game_delete.hpp | 1031 | /*
Copyright (C) 2008 - 2015 by Jörg Hinrichs <[email protected]>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
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.
See the COPYING file for more details.
*/
#ifndef GUI_DIALOGS_DELETE_GAME_HPP_INCLUDED
#define GUI_DIALOGS_DELETE_GAME_HPP_INCLUDED
#include "gui/dialogs/dialog.hpp"
namespace gui2
{
class tgame_delete : public tdialog
{
public:
tgame_delete();
/** The execute function see @ref tdialog for more information. */
static bool execute(CVideo& video)
{
return tgame_delete().show(video);
}
private:
/** Inherited from tdialog, implemented by REGISTER_DIALOG. */
virtual const std::string& window_id() const;
};
}
#endif
| gpl-2.0 |
dmlloyd/openjdk-modules | langtools/test/tools/javac/TryWithResources/TwrAvoidNullCheck.java | 4800 | /*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 7020499
* @summary Verify that try-with-resources desugaring is not generating unnecessary null checks
* @library /tools/lib
* @modules jdk.compiler/com.sun.tools.javac.api
* jdk.compiler/com.sun.tools.javac.code
* jdk.compiler/com.sun.tools.javac.comp
* jdk.compiler/com.sun.tools.javac.main
* jdk.compiler/com.sun.tools.javac.tree
* jdk.compiler/com.sun.tools.javac.util
* @build toolbox.ToolBox toolbox.JavacTask TwrAvoidNullCheck
* @run main TwrAvoidNullCheck
*/
import java.io.IOException;
import java.util.Arrays;
import com.sun.source.util.JavacTask;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.comp.Lower;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCBinary;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.tree.TreeScanner;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Context.Factory;
import com.sun.tools.javac.util.List;
import toolbox.ToolBox;
public class TwrAvoidNullCheck {
public static void main(String... args) throws IOException {
new TwrAvoidNullCheck().run();
}
void run() throws IOException {
run("new Test()", false);
run("null", true);
run("System.getProperty(\"test\") != null ? new Test() : null", true);
}
void run(String resourceSpecification, boolean expected) throws IOException {
String template = "public class Test implements AutoCloseable {\n" +
" void t() {\n" +
" try (Test resource = RESOURCE) { }\n" +
" }\n" +
" public void close() { }\n" +
"}\n";
String code = template.replace("RESOURCE", resourceSpecification);
Context ctx = new Context();
DumpLower.preRegister(ctx);
Iterable<ToolBox.JavaSource> files = Arrays.asList(new ToolBox.JavaSource(code));
JavacTask task = JavacTool.create().getTask(null, null, null, null, null, files, ctx);
task.call();
boolean hasNullCheck = ((DumpLower) DumpLower.instance(ctx)).hasNullCheck;
if (hasNullCheck != expected) {
throw new IllegalStateException("expected: " + expected +
"; actual: " + hasNullCheck +
"; code: " + code);
}
}
static class DumpLower extends Lower {
public static void preRegister(Context ctx) {
ctx.put(lowerKey, new Factory<Lower>() {
@Override
public Lower make(Context c) {
return new DumpLower(c);
}
});
}
public DumpLower(Context context) {
super(context);
}
boolean hasNullCheck;
@Override
public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
List<JCTree> result = super.translateTopLevelClass(env, cdef, make);
new TreeScanner() {
@Override
public void visitBinary(JCBinary tree) {
hasNullCheck |= tree.operator.getSimpleName().contentEquals("!=") &&
"resource".equals(String.valueOf(TreeInfo.name(tree.lhs))) &&
TreeInfo.isNull(tree.rhs);
super.visitBinary(tree);
}
}.scan(result);
return result;
}
}
}
| gpl-2.0 |
R3nPi2/Drupal-8-Skeleton | core/modules/editor/src/Entity/Editor.php | 4176 | <?php
namespace Drupal\editor\Entity;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\editor\EditorInterface;
/**
* Defines the configured text editor entity.
*
* @ConfigEntityType(
* id = "editor",
* label = @Translation("Text Editor"),
* label_collection = @Translation("Text Editors"),
* label_singular = @Translation("text editor"),
* label_plural = @Translation("text editors"),
* label_count = @PluralTranslation(
* singular = "@count text editor",
* plural = "@count text editors",
* ),
* handlers = {
* "access" = "Drupal\editor\EditorAccessControlHandler",
* },
* entity_keys = {
* "id" = "format"
* },
* config_export = {
* "format",
* "editor",
* "settings",
* "image_upload",
* }
* )
*/
class Editor extends ConfigEntityBase implements EditorInterface {
/**
* The machine name of the text format with which this configured text editor
* is associated.
*
* @var string
*
* @see getFilterFormat()
*/
protected $format;
/**
* The name (plugin ID) of the text editor.
*
* @var string
*/
protected $editor;
/**
* The structured array of text editor plugin-specific settings.
*
* @var array
*/
protected $settings = [];
/**
* The structured array of image upload settings.
*
* @var array
*/
protected $image_upload = [];
/**
* The filter format this text editor is associated with.
*
* @var \Drupal\filter\FilterFormatInterface
*/
protected $filterFormat;
/**
* @var \Drupal\Component\Plugin\PluginManagerInterface
*/
protected $editorPluginManager;
/**
* {@inheritdoc}
*/
public function id() {
return $this->format;
}
/**
* {@inheritdoc}
*/
public function __construct(array $values, $entity_type) {
parent::__construct($values, $entity_type);
$plugin = $this->editorPluginManager()->createInstance($this->editor);
$this->settings += $plugin->getDefaultSettings();
}
/**
* {@inheritdoc}
*/
public function label() {
return $this->getFilterFormat()->label();
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
parent::calculateDependencies();
// Create a dependency on the associated FilterFormat.
$this->addDependency('config', $this->getFilterFormat()->getConfigDependencyName());
// @todo use EntityWithPluginCollectionInterface so configuration between
// config entity and dependency on provider is managed automatically.
$definition = $this->editorPluginManager()->createInstance($this->editor)->getPluginDefinition();
$this->addDependency('module', $definition['provider']);
return $this;
}
/**
* {@inheritdoc}
*/
public function hasAssociatedFilterFormat() {
return $this->format !== NULL;
}
/**
* {@inheritdoc}
*/
public function getFilterFormat() {
if (!$this->filterFormat) {
$this->filterFormat = \Drupal::entityTypeManager()->getStorage('filter_format')->load($this->format);
}
return $this->filterFormat;
}
/**
* Returns the editor plugin manager.
*
* @return \Drupal\Component\Plugin\PluginManagerInterface
*/
protected function editorPluginManager() {
if (!$this->editorPluginManager) {
$this->editorPluginManager = \Drupal::service('plugin.manager.editor');
}
return $this->editorPluginManager;
}
/**
* {@inheritdoc}
*/
public function getEditor() {
return $this->editor;
}
/**
* {@inheritdoc}
*/
public function setEditor($editor) {
$this->editor = $editor;
return $this;
}
/**
* {@inheritdoc}
*/
public function getSettings() {
return $this->settings;
}
/**
* {@inheritdoc}
*/
public function setSettings(array $settings) {
$this->settings = $settings;
return $this;
}
/**
* {@inheritdoc}
*/
public function getImageUploadSettings() {
return $this->image_upload;
}
/**
* {@inheritdoc}
*/
public function setImageUploadSettings(array $image_upload_settings) {
$this->image_upload = $image_upload_settings;
return $this;
}
}
| gpl-2.0 |
ironclad88/JustZH | Scripts/Items/Champion Artifacts/Shared/DjinnisRing.cs | 1135 | using System;
namespace Server.Items
{
public class DjinnisRing : SilverRing
{
[Constructable]
public DjinnisRing()
{
this.Attributes.BonusInt = 5;
this.Attributes.SpellDamage = 10;
this.Attributes.CastSpeed = 2;
}
public DjinnisRing(Serial serial)
: base(serial)
{
}
public override int LabelNumber
{
get
{
return 1094927;
}
}// Djinni's Ring [Replica]
public override int InitMinHits
{
get
{
return 150;
}
}
public override int InitMaxHits
{
get
{
return 150;
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | gpl-3.0 |
recci/SuiteCRM | modules/FP_events/metadata/subpanels/default.php | 3082 | <?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
* SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
* Copyright (C) 2011 - 2014 Salesagility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
********************************************************************************/
$module_name='FP_events';
$subpanel_layout = array(
'top_buttons' => array(
array('widget_class' => 'SubPanelTopCreateButton'),
array('widget_class' => 'SubPanelTopSelectButton', 'popup_module' => $module_name),
),
'where' => '',
'list_fields' => array(
'name'=>array(
'vname' => 'LBL_NAME',
'widget_class' => 'SubPanelDetailViewLink',
'width' => '45%',
),
'date_modified'=>array(
'vname' => 'LBL_DATE_MODIFIED',
'width' => '45%',
),
'edit_button'=>array(
'vname' => 'LBL_EDIT_BUTTON',
'widget_class' => 'SubPanelEditButton',
'module' => $module_name,
'width' => '4%',
),
'remove_button'=>array(
'vname' => 'LBL_REMOVE',
'widget_class' => 'SubPanelRemoveButton',
'module' => $module_name,
'width' => '5%',
),
),
);
?> | agpl-3.0 |
GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/@fortawesome/free-solid-svg-icons/faLayerGroup.d.ts | 398 | import { IconDefinition, IconPrefix, IconName } from "@fortawesome/fontawesome-common-types";
export const definition: IconDefinition;
export const faLayerGroup: IconDefinition;
export const prefix: IconPrefix;
export const iconName: IconName;
export const width: number;
export const height: number;
export const ligatures: string[];
export const unicode: string;
export const svgPathData: string; | apache-2.0 |
manipopopo/tensorflow | tensorflow/contrib/autograph/utils/testing.py | 1235 | # Copyright 2017 The TensorFlow 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.
# ==============================================================================
"""Testing utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import imp
from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops
def fake_tf():
"""Creates a fake module that looks like TensorFlow, for testing."""
mod = imp.new_module('tensorflow')
mod_contents = dict()
mod_contents.update(math_ops.__dict__)
mod_contents.update(ops.__dict__)
mod_contents.update(mod.__dict__)
mod.__dict__.update(mod_contents)
return mod
| apache-2.0 |
tejima/OP3PKG | apps/pc_frontend/modules/community/templates/quitError.php | 404 | <?php if ($isAdmin): ?>
<?php $body = __('The administrator doesn\'t leave the %community%.') ?>
<?php else: ?>
<?php $body = __('You haven\'t joined this %community% yet.') ?>
<?php endif; ?>
<?php op_include_box('error', $body, array('title' => __('Errors'))) ?>
<?php use_helper('Javascript') ?>
<?php op_include_line('backLink', link_to_function(__('Back to previous page'), 'history.back()')) ?>
| apache-2.0 |
ilpbox/Orchestra | NodeBox-Muso/typings/node/node.d.ts | 90264 | // Type definitions for Node.js v4.x
// Project: http://nodejs.org/
// Definitions by: Microsoft TypeScript <http://typescriptlang.org>, DefinitelyTyped <https://github.com/borisyankov/DefinitelyTyped>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/************************************************
* *
* Node.js v4.x API *
* *
************************************************/
interface Error {
stack?: string;
}
// compat for TypeScript 1.5.3
// if you use with --target es3 or --target es5 and use below definitions,
// use the lib.es6.d.ts that is bundled with TypeScript 1.5.3.
interface MapConstructor {}
interface WeakMapConstructor {}
interface SetConstructor {}
interface WeakSetConstructor {}
/************************************************
* *
* GLOBAL *
* *
************************************************/
declare var process: NodeJS.Process;
declare var global: NodeJS.Global;
declare var __filename: string;
declare var __dirname: string;
declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;
declare function clearTimeout(timeoutId: NodeJS.Timer): void;
declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;
declare function clearInterval(intervalId: NodeJS.Timer): void;
declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any;
declare function clearImmediate(immediateId: any): void;
interface NodeRequireFunction {
(id: string): any;
}
interface NodeRequire extends NodeRequireFunction {
resolve(id:string): string;
cache: any;
extensions: any;
main: any;
}
declare var require: NodeRequire;
interface NodeModule {
exports: any;
require: NodeRequireFunction;
id: string;
filename: string;
loaded: boolean;
parent: any;
children: any[];
}
declare var module: NodeModule;
// Same as module.exports
declare var exports: any;
declare var SlowBuffer: {
new (str: string, encoding?: string): Buffer;
new (size: number): Buffer;
new (size: Uint8Array): Buffer;
new (array: any[]): Buffer;
prototype: Buffer;
isBuffer(obj: any): boolean;
byteLength(string: string, encoding?: string): number;
concat(list: Buffer[], totalLength?: number): Buffer;
};
// Buffer class
interface Buffer extends NodeBuffer {}
/**
* Raw data is stored in instances of the Buffer class.
* A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.
* Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
*/
declare var Buffer: {
/**
* Allocates a new buffer containing the given {str}.
*
* @param str String to store in buffer.
* @param encoding encoding to use, optional. Default is 'utf8'
*/
new (str: string, encoding?: string): Buffer;
/**
* Allocates a new buffer of {size} octets.
*
* @param size count of octets to allocate.
*/
new (size: number): Buffer;
/**
* Allocates a new buffer containing the given {array} of octets.
*
* @param array The octets to store.
*/
new (array: Uint8Array): Buffer;
/**
* Allocates a new buffer containing the given {array} of octets.
*
* @param array The octets to store.
*/
new (array: any[]): Buffer;
prototype: Buffer;
/**
* Returns true if {obj} is a Buffer
*
* @param obj object to test.
*/
isBuffer(obj: any): obj is Buffer;
/**
* Returns true if {encoding} is a valid encoding argument.
* Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
*
* @param encoding string to test.
*/
isEncoding(encoding: string): boolean;
/**
* Gives the actual byte length of a string. encoding defaults to 'utf8'.
* This is not the same as String.prototype.length since that returns the number of characters in a string.
*
* @param string string to test.
* @param encoding encoding used to evaluate (defaults to 'utf8')
*/
byteLength(string: string, encoding?: string): number;
/**
* Returns a buffer which is the result of concatenating all the buffers in the list together.
*
* If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.
* If the list has exactly one item, then the first item of the list is returned.
* If the list has more than one item, then a new Buffer is created.
*
* @param list An array of Buffer objects to concatenate
* @param totalLength Total length of the buffers when concatenated.
* If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.
*/
concat(list: Buffer[], totalLength?: number): Buffer;
/**
* The same as buf1.compare(buf2).
*/
compare(buf1: Buffer, buf2: Buffer): number;
};
/************************************************
* *
* GLOBAL INTERFACES *
* *
************************************************/
declare module NodeJS {
export interface ErrnoException extends Error {
errno?: number;
code?: string;
path?: string;
syscall?: string;
stack?: string;
}
export interface EventEmitter {
addListener(event: string, listener: Function): EventEmitter;
on(event: string, listener: Function): EventEmitter;
once(event: string, listener: Function): EventEmitter;
removeListener(event: string, listener: Function): EventEmitter;
removeAllListeners(event?: string): EventEmitter;
setMaxListeners(n: number): EventEmitter;
getMaxListeners(): number;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
listenerCount(type: string): number;
}
export interface ReadableStream extends EventEmitter {
readable: boolean;
read(size?: number): string|Buffer;
setEncoding(encoding: string): void;
pause(): void;
resume(): void;
pipe<T extends WritableStream>(destination: T, options?: { end?: boolean; }): T;
unpipe<T extends WritableStream>(destination?: T): void;
unshift(chunk: string): void;
unshift(chunk: Buffer): void;
wrap(oldStream: ReadableStream): ReadableStream;
}
export interface WritableStream extends EventEmitter {
writable: boolean;
write(buffer: Buffer|string, cb?: Function): boolean;
write(str: string, encoding?: string, cb?: Function): boolean;
end(): void;
end(buffer: Buffer, cb?: Function): void;
end(str: string, cb?: Function): void;
end(str: string, encoding?: string, cb?: Function): void;
}
export interface ReadWriteStream extends ReadableStream, WritableStream {}
export interface Process extends EventEmitter {
stdout: WritableStream;
stderr: WritableStream;
stdin: ReadableStream;
argv: string[];
execPath: string;
abort(): void;
chdir(directory: string): void;
cwd(): string;
env: any;
exit(code?: number): void;
getgid(): number;
setgid(id: number): void;
setgid(id: string): void;
getuid(): number;
setuid(id: number): void;
setuid(id: string): void;
version: string;
versions: {
http_parser: string;
node: string;
v8: string;
ares: string;
uv: string;
zlib: string;
openssl: string;
};
config: {
target_defaults: {
cflags: any[];
default_configuration: string;
defines: string[];
include_dirs: string[];
libraries: string[];
};
variables: {
clang: number;
host_arch: string;
node_install_npm: boolean;
node_install_waf: boolean;
node_prefix: string;
node_shared_openssl: boolean;
node_shared_v8: boolean;
node_shared_zlib: boolean;
node_use_dtrace: boolean;
node_use_etw: boolean;
node_use_openssl: boolean;
target_arch: string;
v8_no_strict_aliasing: number;
v8_use_snapshot: boolean;
visibility: string;
};
};
kill(pid:number, signal?: string|number): void;
pid: number;
title: string;
arch: string;
platform: string;
memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; };
nextTick(callback: Function): void;
umask(mask?: number): number;
uptime(): number;
hrtime(time?:number[]): number[];
// Worker
send?(message: any, sendHandle?: any): void;
}
export interface Global {
Array: typeof Array;
ArrayBuffer: typeof ArrayBuffer;
Boolean: typeof Boolean;
Buffer: typeof Buffer;
DataView: typeof DataView;
Date: typeof Date;
Error: typeof Error;
EvalError: typeof EvalError;
Float32Array: typeof Float32Array;
Float64Array: typeof Float64Array;
Function: typeof Function;
GLOBAL: Global;
Infinity: typeof Infinity;
Int16Array: typeof Int16Array;
Int32Array: typeof Int32Array;
Int8Array: typeof Int8Array;
Intl: typeof Intl;
JSON: typeof JSON;
Map: MapConstructor;
Math: typeof Math;
NaN: typeof NaN;
Number: typeof Number;
Object: typeof Object;
Promise: Function;
RangeError: typeof RangeError;
ReferenceError: typeof ReferenceError;
RegExp: typeof RegExp;
Set: SetConstructor;
String: typeof String;
Symbol: Function;
SyntaxError: typeof SyntaxError;
TypeError: typeof TypeError;
URIError: typeof URIError;
Uint16Array: typeof Uint16Array;
Uint32Array: typeof Uint32Array;
Uint8Array: typeof Uint8Array;
Uint8ClampedArray: Function;
WeakMap: WeakMapConstructor;
WeakSet: WeakSetConstructor;
clearImmediate: (immediateId: any) => void;
clearInterval: (intervalId: NodeJS.Timer) => void;
clearTimeout: (timeoutId: NodeJS.Timer) => void;
console: typeof console;
decodeURI: typeof decodeURI;
decodeURIComponent: typeof decodeURIComponent;
encodeURI: typeof encodeURI;
encodeURIComponent: typeof encodeURIComponent;
escape: (str: string) => string;
eval: typeof eval;
global: Global;
isFinite: typeof isFinite;
isNaN: typeof isNaN;
parseFloat: typeof parseFloat;
parseInt: typeof parseInt;
process: Process;
root: Global;
setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any;
setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer;
setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer;
undefined: typeof undefined;
unescape: (str: string) => string;
gc: () => void;
v8debug?: any;
}
export interface Timer {
ref() : void;
unref() : void;
}
}
/**
* @deprecated
*/
interface NodeBuffer {
[index: number]: number;
write(string: string, offset?: number, length?: number, encoding?: string): number;
toString(encoding?: string, start?: number, end?: number): string;
toJSON(): any;
length: number;
equals(otherBuffer: Buffer): boolean;
compare(otherBuffer: Buffer): number;
copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
slice(start?: number, end?: number): Buffer;
writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
readUInt8(offset: number, noAsset?: boolean): number;
readUInt16LE(offset: number, noAssert?: boolean): number;
readUInt16BE(offset: number, noAssert?: boolean): number;
readUInt32LE(offset: number, noAssert?: boolean): number;
readUInt32BE(offset: number, noAssert?: boolean): number;
readInt8(offset: number, noAssert?: boolean): number;
readInt16LE(offset: number, noAssert?: boolean): number;
readInt16BE(offset: number, noAssert?: boolean): number;
readInt32LE(offset: number, noAssert?: boolean): number;
readInt32BE(offset: number, noAssert?: boolean): number;
readFloatLE(offset: number, noAssert?: boolean): number;
readFloatBE(offset: number, noAssert?: boolean): number;
readDoubleLE(offset: number, noAssert?: boolean): number;
readDoubleBE(offset: number, noAssert?: boolean): number;
writeUInt8(value: number, offset: number, noAssert?: boolean): number;
writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
writeInt8(value: number, offset: number, noAssert?: boolean): number;
writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
fill(value: any, offset?: number, end?: number): Buffer;
}
/************************************************
* *
* MODULES *
* *
************************************************/
declare module "buffer" {
export var INSPECT_MAX_BYTES: number;
}
declare module "querystring" {
export interface StringifyOptions {
encodeURIComponent?: Function;
}
export interface ParseOptions {
maxKeys?: number;
decodeURIComponent?: Function;
}
export function stringify<T>(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string;
export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any;
export function parse<T extends {}>(str: string, sep?: string, eq?: string, options?: ParseOptions): T;
export function escape(str: string): string;
export function unescape(str: string): string;
}
declare module "events" {
export class EventEmitter implements NodeJS.EventEmitter {
static EventEmitter: EventEmitter;
static listenerCount(emitter: EventEmitter, event: string): number; // deprecated
static defaultMaxListeners: number;
addListener(event: string, listener: Function): EventEmitter;
on(event: string, listener: Function): EventEmitter;
once(event: string, listener: Function): EventEmitter;
removeListener(event: string, listener: Function): EventEmitter;
removeAllListeners(event?: string): EventEmitter;
setMaxListeners(n: number): EventEmitter;
getMaxListeners(): number;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
listenerCount(type: string): number;
}
}
declare module "http" {
import * as events from "events";
import * as net from "net";
import * as stream from "stream";
export interface RequestOptions {
protocol?: string;
host?: string;
hostname?: string;
family?: number;
port?: number
localAddress?: string;
socketPath?: string;
method?: string;
path?: string;
headers?: { [key: string]: any };
auth?: string;
agent?: Agent|boolean;
}
export interface Server extends events.EventEmitter {
listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server;
listen(port: number, hostname?: string, callback?: Function): Server;
listen(path: string, callback?: Function): Server;
listen(handle: any, listeningListener?: Function): Server;
close(cb?: any): Server;
address(): { port: number; family: string; address: string; };
maxHeadersCount: number;
}
/**
* @deprecated Use IncomingMessage
*/
export interface ServerRequest extends IncomingMessage {
connection: net.Socket;
}
export interface ServerResponse extends events.EventEmitter, stream.Writable {
// Extended base methods
write(buffer: Buffer): boolean;
write(buffer: Buffer, cb?: Function): boolean;
write(str: string, cb?: Function): boolean;
write(str: string, encoding?: string, cb?: Function): boolean;
write(str: string, encoding?: string, fd?: string): boolean;
writeContinue(): void;
writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void;
writeHead(statusCode: number, headers?: any): void;
statusCode: number;
statusMessage: string;
setHeader(name: string, value: string): void;
sendDate: boolean;
getHeader(name: string): string;
removeHeader(name: string): void;
write(chunk: any, encoding?: string): any;
addTrailers(headers: any): void;
// Extended base methods
end(): void;
end(buffer: Buffer, cb?: Function): void;
end(str: string, cb?: Function): void;
end(str: string, encoding?: string, cb?: Function): void;
end(data?: any, encoding?: string): void;
}
export interface ClientRequest extends events.EventEmitter, stream.Writable {
// Extended base methods
write(buffer: Buffer): boolean;
write(buffer: Buffer, cb?: Function): boolean;
write(str: string, cb?: Function): boolean;
write(str: string, encoding?: string, cb?: Function): boolean;
write(str: string, encoding?: string, fd?: string): boolean;
write(chunk: any, encoding?: string): void;
abort(): void;
setTimeout(timeout: number, callback?: Function): void;
setNoDelay(noDelay?: boolean): void;
setSocketKeepAlive(enable?: boolean, initialDelay?: number): void;
// Extended base methods
end(): void;
end(buffer: Buffer, cb?: Function): void;
end(str: string, cb?: Function): void;
end(str: string, encoding?: string, cb?: Function): void;
end(data?: any, encoding?: string): void;
}
export interface IncomingMessage extends events.EventEmitter, stream.Readable {
httpVersion: string;
headers: any;
rawHeaders: string[];
trailers: any;
rawTrailers: any;
setTimeout(msecs: number, callback: Function): NodeJS.Timer;
/**
* Only valid for request obtained from http.Server.
*/
method?: string;
/**
* Only valid for request obtained from http.Server.
*/
url?: string;
/**
* Only valid for response obtained from http.ClientRequest.
*/
statusCode?: number;
/**
* Only valid for response obtained from http.ClientRequest.
*/
statusMessage?: string;
socket: net.Socket;
}
/**
* @deprecated Use IncomingMessage
*/
export interface ClientResponse extends IncomingMessage { }
export interface AgentOptions {
/**
* Keep sockets around in a pool to be used by other requests in the future. Default = false
*/
keepAlive?: boolean;
/**
* When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
* Only relevant if keepAlive is set to true.
*/
keepAliveMsecs?: number;
/**
* Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity
*/
maxSockets?: number;
/**
* Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.
*/
maxFreeSockets?: number;
}
export class Agent {
maxSockets: number;
sockets: any;
requests: any;
constructor(opts?: AgentOptions);
/**
* Destroy any sockets that are currently in use by the agent.
* It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled,
* then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise,
* sockets may hang open for quite a long time before the server terminates them.
*/
destroy(): void;
}
export var METHODS: string[];
export var STATUS_CODES: {
[errorCode: number]: string;
[errorCode: string]: string;
};
export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server;
export function createClient(port?: number, host?: string): any;
export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;
export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest;
export var globalAgent: Agent;
}
declare module "cluster" {
import * as child from "child_process";
import * as events from "events";
export interface ClusterSettings {
exec?: string;
args?: string[];
silent?: boolean;
}
export class Worker extends events.EventEmitter {
id: string;
process: child.ChildProcess;
suicide: boolean;
send(message: any, sendHandle?: any): void;
kill(signal?: string): void;
destroy(signal?: string): void;
disconnect(): void;
}
export var settings: ClusterSettings;
export var isMaster: boolean;
export var isWorker: boolean;
export function setupMaster(settings?: ClusterSettings): void;
export function fork(env?: any): Worker;
export function disconnect(callback?: Function): void;
export var worker: Worker;
export var workers: Worker[];
// Event emitter
export function addListener(event: string, listener: Function): void;
export function on(event: string, listener: Function): any;
export function once(event: string, listener: Function): void;
export function removeListener(event: string, listener: Function): void;
export function removeAllListeners(event?: string): void;
export function setMaxListeners(n: number): void;
export function listeners(event: string): Function[];
export function emit(event: string, ...args: any[]): boolean;
}
declare module "zlib" {
import * as stream from "stream";
export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; }
export interface Gzip extends stream.Transform { }
export interface Gunzip extends stream.Transform { }
export interface Deflate extends stream.Transform { }
export interface Inflate extends stream.Transform { }
export interface DeflateRaw extends stream.Transform { }
export interface InflateRaw extends stream.Transform { }
export interface Unzip extends stream.Transform { }
export function createGzip(options?: ZlibOptions): Gzip;
export function createGunzip(options?: ZlibOptions): Gunzip;
export function createDeflate(options?: ZlibOptions): Deflate;
export function createInflate(options?: ZlibOptions): Inflate;
export function createDeflateRaw(options?: ZlibOptions): DeflateRaw;
export function createInflateRaw(options?: ZlibOptions): InflateRaw;
export function createUnzip(options?: ZlibOptions): Unzip;
export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
export function deflateSync(buf: Buffer, options?: ZlibOptions): any;
export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any;
export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
export function gzipSync(buf: Buffer, options?: ZlibOptions): any;
export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
export function gunzipSync(buf: Buffer, options?: ZlibOptions): any;
export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
export function inflateSync(buf: Buffer, options?: ZlibOptions): any;
export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any;
export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
export function unzipSync(buf: Buffer, options?: ZlibOptions): any;
// Constants
export var Z_NO_FLUSH: number;
export var Z_PARTIAL_FLUSH: number;
export var Z_SYNC_FLUSH: number;
export var Z_FULL_FLUSH: number;
export var Z_FINISH: number;
export var Z_BLOCK: number;
export var Z_TREES: number;
export var Z_OK: number;
export var Z_STREAM_END: number;
export var Z_NEED_DICT: number;
export var Z_ERRNO: number;
export var Z_STREAM_ERROR: number;
export var Z_DATA_ERROR: number;
export var Z_MEM_ERROR: number;
export var Z_BUF_ERROR: number;
export var Z_VERSION_ERROR: number;
export var Z_NO_COMPRESSION: number;
export var Z_BEST_SPEED: number;
export var Z_BEST_COMPRESSION: number;
export var Z_DEFAULT_COMPRESSION: number;
export var Z_FILTERED: number;
export var Z_HUFFMAN_ONLY: number;
export var Z_RLE: number;
export var Z_FIXED: number;
export var Z_DEFAULT_STRATEGY: number;
export var Z_BINARY: number;
export var Z_TEXT: number;
export var Z_ASCII: number;
export var Z_UNKNOWN: number;
export var Z_DEFLATED: number;
export var Z_NULL: number;
}
declare module "os" {
export interface CpuInfo {
model: string;
speed: number;
times: {
user: number;
nice: number;
sys: number;
idle: number;
irq: number;
}
}
export interface NetworkInterfaceInfo {
address: string;
netmask: string;
family: string;
mac: string;
internal: boolean;
}
export function tmpdir(): string;
export function homedir(): string;
export function endianness(): string;
export function hostname(): string;
export function type(): string;
export function platform(): string;
export function arch(): string;
export function release(): string;
export function uptime(): number;
export function loadavg(): number[];
export function totalmem(): number;
export function freemem(): number;
export function cpus(): CpuInfo[];
export function networkInterfaces(): {[index: string]: NetworkInterfaceInfo[]};
export var EOL: string;
}
declare module "https" {
import * as tls from "tls";
import * as events from "events";
import * as http from "http";
export interface ServerOptions {
pfx?: any;
key?: any;
passphrase?: string;
cert?: any;
ca?: any;
crl?: any;
ciphers?: string;
honorCipherOrder?: boolean;
requestCert?: boolean;
rejectUnauthorized?: boolean;
NPNProtocols?: any;
SNICallback?: (servername: string) => any;
}
export interface RequestOptions extends http.RequestOptions{
pfx?: any;
key?: any;
passphrase?: string;
cert?: any;
ca?: any;
ciphers?: string;
rejectUnauthorized?: boolean;
secureProtocol?: string;
}
export interface Agent {
maxSockets: number;
sockets: any;
requests: any;
}
export var Agent: {
new (options?: RequestOptions): Agent;
};
export interface Server extends tls.Server { }
export function createServer(options: ServerOptions, requestListener?: Function): Server;
export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest;
export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest;
export var globalAgent: Agent;
}
declare module "punycode" {
export function decode(string: string): string;
export function encode(string: string): string;
export function toUnicode(domain: string): string;
export function toASCII(domain: string): string;
export var ucs2: ucs2;
interface ucs2 {
decode(string: string): number[];
encode(codePoints: number[]): string;
}
export var version: any;
}
declare module "repl" {
import * as stream from "stream";
import * as events from "events";
export interface ReplOptions {
prompt?: string;
input?: NodeJS.ReadableStream;
output?: NodeJS.WritableStream;
terminal?: boolean;
eval?: Function;
useColors?: boolean;
useGlobal?: boolean;
ignoreUndefined?: boolean;
writer?: Function;
}
export function start(options: ReplOptions): events.EventEmitter;
}
declare module "readline" {
import * as events from "events";
import * as stream from "stream";
export interface Key {
sequence?: string;
name?: string;
ctrl?: boolean;
meta?: boolean;
shift?: boolean;
}
export interface ReadLine extends events.EventEmitter {
setPrompt(prompt: string): void;
prompt(preserveCursor?: boolean): void;
question(query: string, callback: (answer: string) => void): void;
pause(): ReadLine;
resume(): ReadLine;
close(): void;
write(data: string|Buffer, key?: Key): void;
}
export interface Completer {
(line: string): CompleterResult;
(line: string, callback: (err: any, result: CompleterResult) => void): any;
}
export interface CompleterResult {
completions: string[];
line: string;
}
export interface ReadLineOptions {
input: NodeJS.ReadableStream;
output?: NodeJS.WritableStream;
completer?: Completer;
terminal?: boolean;
historySize?: number;
}
export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): ReadLine;
export function createInterface(options: ReadLineOptions): ReadLine;
export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void;
export function moveCursor(stream: NodeJS.WritableStream, dx: number|string, dy: number|string): void;
export function clearLine(stream: NodeJS.WritableStream, dir: number): void;
export function clearScreenDown(stream: NodeJS.WritableStream): void;
}
declare module "vm" {
export interface Context { }
export interface Script {
runInThisContext(): void;
runInNewContext(sandbox?: Context): void;
}
export function runInThisContext(code: string, filename?: string): void;
export function runInNewContext(code: string, sandbox?: Context, filename?: string): void;
export function runInContext(code: string, context: Context, filename?: string): void;
export function createContext(initSandbox?: Context): Context;
export function createScript(code: string, filename?: string): Script;
}
declare module "child_process" {
import * as events from "events";
import * as stream from "stream";
export interface ChildProcess extends events.EventEmitter {
stdin: stream.Writable;
stdout: stream.Readable;
stderr: stream.Readable;
pid: number;
kill(signal?: string): void;
send(message: any, sendHandle?: any): void;
disconnect(): void;
unref(): void;
}
export function spawn(command: string, args?: string[], options?: {
cwd?: string;
stdio?: any;
custom?: any;
env?: any;
detached?: boolean;
}): ChildProcess;
export function exec(command: string, options: {
cwd?: string;
stdio?: any;
customFds?: any;
env?: any;
encoding?: string;
timeout?: number;
maxBuffer?: number;
killSignal?: string;
}, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
export function exec(command: string, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
export function execFile(file: string,
callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
export function execFile(file: string, args?: string[],
callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
export function execFile(file: string, args?: string[], options?: {
cwd?: string;
stdio?: any;
customFds?: any;
env?: any;
encoding?: string;
timeout?: number;
maxBuffer?: number;
killSignal?: string;
}, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
export function fork(modulePath: string, args?: string[], options?: {
cwd?: string;
env?: any;
execPath?: string;
execArgv?: string[];
silent?: boolean;
uid?: number;
gid?: number;
}): ChildProcess;
export function spawnSync(command: string, args?: string[], options?: {
cwd?: string;
input?: string | Buffer;
stdio?: any;
env?: any;
uid?: number;
gid?: number;
timeout?: number;
maxBuffer?: number;
killSignal?: string;
encoding?: string;
}): {
pid: number;
output: string[];
stdout: string | Buffer;
stderr: string | Buffer;
status: number;
signal: string;
error: Error;
};
export function execSync(command: string, options?: {
cwd?: string;
input?: string|Buffer;
stdio?: any;
env?: any;
uid?: number;
gid?: number;
timeout?: number;
maxBuffer?: number;
killSignal?: string;
encoding?: string;
}): string | Buffer;
export function execFileSync(command: string, args?: string[], options?: {
cwd?: string;
input?: string|Buffer;
stdio?: any;
env?: any;
uid?: number;
gid?: number;
timeout?: number;
maxBuffer?: number;
killSignal?: string;
encoding?: string;
}): string | Buffer;
}
declare module "url" {
export interface Url {
href?: string;
protocol?: string;
auth?: string;
hostname?: string;
port?: string;
host?: string;
pathname?: string;
search?: string;
query?: any; // string | Object
slashes?: boolean;
hash?: string;
path?: string;
}
export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url;
export function format(url: Url): string;
export function resolve(from: string, to: string): string;
}
declare module "dns" {
export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string;
export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string;
export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[];
export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[];
}
declare module "net" {
import * as stream from "stream";
export interface Socket extends stream.Duplex {
// Extended base methods
write(buffer: Buffer): boolean;
write(buffer: Buffer, cb?: Function): boolean;
write(str: string, cb?: Function): boolean;
write(str: string, encoding?: string, cb?: Function): boolean;
write(str: string, encoding?: string, fd?: string): boolean;
connect(port: number, host?: string, connectionListener?: Function): void;
connect(path: string, connectionListener?: Function): void;
bufferSize: number;
setEncoding(encoding?: string): void;
write(data: any, encoding?: string, callback?: Function): void;
destroy(): void;
pause(): void;
resume(): void;
setTimeout(timeout: number, callback?: Function): void;
setNoDelay(noDelay?: boolean): void;
setKeepAlive(enable?: boolean, initialDelay?: number): void;
address(): { port: number; family: string; address: string; };
unref(): void;
ref(): void;
remoteAddress: string;
remoteFamily: string;
remotePort: number;
localAddress: string;
localPort: number;
bytesRead: number;
bytesWritten: number;
// Extended base methods
end(): void;
end(buffer: Buffer, cb?: Function): void;
end(str: string, cb?: Function): void;
end(str: string, encoding?: string, cb?: Function): void;
end(data?: any, encoding?: string): void;
}
export var Socket: {
new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket;
};
export interface Server extends Socket {
listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server;
listen(path: string, listeningListener?: Function): Server;
listen(handle: any, listeningListener?: Function): Server;
close(callback?: Function): Server;
address(): { port: number; family: string; address: string; };
maxConnections: number;
connections: number;
}
export function createServer(connectionListener?: (socket: Socket) =>void ): Server;
export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server;
export function connect(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket;
export function connect(port: number, host?: string, connectionListener?: Function): Socket;
export function connect(path: string, connectionListener?: Function): Socket;
export function createConnection(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket;
export function createConnection(port: number, host?: string, connectionListener?: Function): Socket;
export function createConnection(path: string, connectionListener?: Function): Socket;
export function isIP(input: string): number;
export function isIPv4(input: string): boolean;
export function isIPv6(input: string): boolean;
}
declare module "dgram" {
import * as events from "events";
interface RemoteInfo {
address: string;
port: number;
size: number;
}
interface AddressInfo {
address: string;
family: string;
port: number;
}
export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
interface Socket extends events.EventEmitter {
send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void;
bind(port: number, address?: string, callback?: () => void): void;
close(): void;
address(): AddressInfo;
setBroadcast(flag: boolean): void;
setMulticastTTL(ttl: number): void;
setMulticastLoopback(flag: boolean): void;
addMembership(multicastAddress: string, multicastInterface?: string): void;
dropMembership(multicastAddress: string, multicastInterface?: string): void;
}
}
declare module "fs" {
import * as stream from "stream";
import * as events from "events";
interface Stats {
isFile(): boolean;
isDirectory(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
dev: number;
ino: number;
mode: number;
nlink: number;
uid: number;
gid: number;
rdev: number;
size: number;
blksize: number;
blocks: number;
atime: Date;
mtime: Date;
ctime: Date;
birthtime: Date;
}
interface FSWatcher extends events.EventEmitter {
close(): void;
}
export interface ReadStream extends stream.Readable {
close(): void;
}
export interface WriteStream extends stream.Writable {
close(): void;
bytesWritten: number;
}
/**
* Asynchronous rename.
* @param oldPath
* @param newPath
* @param callback No arguments other than a possible exception are given to the completion callback.
*/
export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
/**
* Synchronous rename
* @param oldPath
* @param newPath
*/
export function renameSync(oldPath: string, newPath: string): void;
export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function truncateSync(path: string, len?: number): void;
export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function ftruncateSync(fd: number, len?: number): void;
export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function chownSync(path: string, uid: number, gid: number): void;
export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function fchownSync(fd: number, uid: number, gid: number): void;
export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function lchownSync(path: string, uid: number, gid: number): void;
export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function chmodSync(path: string, mode: number): void;
export function chmodSync(path: string, mode: string): void;
export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function fchmodSync(fd: number, mode: number): void;
export function fchmodSync(fd: number, mode: string): void;
export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function lchmodSync(path: string, mode: number): void;
export function lchmodSync(path: string, mode: string): void;
export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;
export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;
export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;
export function statSync(path: string): Stats;
export function lstatSync(path: string): Stats;
export function fstatSync(fd: number): Stats;
export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function linkSync(srcpath: string, dstpath: string): void;
export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function symlinkSync(srcpath: string, dstpath: string, type?: string): void;
export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void;
export function readlinkSync(path: string): string;
export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void;
export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void;
export function realpathSync(path: string, cache?: { [path: string]: string }): string;
/*
* Asynchronous unlink - deletes the file specified in {path}
*
* @param path
* @param callback No arguments other than a possible exception are given to the completion callback.
*/
export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
/*
* Synchronous unlink - deletes the file specified in {path}
*
* @param path
*/
export function unlinkSync(path: string): void;
/*
* Asynchronous rmdir - removes the directory specified in {path}
*
* @param path
* @param callback No arguments other than a possible exception are given to the completion callback.
*/
export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
/*
* Synchronous rmdir - removes the directory specified in {path}
*
* @param path
*/
export function rmdirSync(path: string): void;
/*
* Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777.
*
* @param path
* @param callback No arguments other than a possible exception are given to the completion callback.
*/
export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
/*
* Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777.
*
* @param path
* @param mode
* @param callback No arguments other than a possible exception are given to the completion callback.
*/
export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
/*
* Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777.
*
* @param path
* @param mode
* @param callback No arguments other than a possible exception are given to the completion callback.
*/
export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
/*
* Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777.
*
* @param path
* @param mode
* @param callback No arguments other than a possible exception are given to the completion callback.
*/
export function mkdirSync(path: string, mode?: number): void;
/*
* Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777.
*
* @param path
* @param mode
* @param callback No arguments other than a possible exception are given to the completion callback.
*/
export function mkdirSync(path: string, mode?: string): void;
export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void;
export function readdirSync(path: string): string[];
export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function closeSync(fd: number): void;
export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;
export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;
export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;
export function openSync(path: string, flags: string, mode?: number): number;
export function openSync(path: string, flags: string, mode?: string): number;
export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function utimesSync(path: string, atime: number, mtime: number): void;
export function utimesSync(path: string, atime: Date, mtime: Date): void;
export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function futimesSync(fd: number, atime: number, mtime: number): void;
export function futimesSync(fd: number, atime: Date, mtime: Date): void;
export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function fsyncSync(fd: number): void;
export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void;
export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void;
export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void;
export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void;
export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void;
export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number;
export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void;
export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number;
/*
* Asynchronous readFile - Asynchronously reads the entire contents of a file.
*
* @param fileName
* @param encoding
* @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.
*/
export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void;
/*
* Asynchronous readFile - Asynchronously reads the entire contents of a file.
*
* @param fileName
* @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer.
* @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.
*/
export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void;
/*
* Asynchronous readFile - Asynchronously reads the entire contents of a file.
*
* @param fileName
* @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer.
* @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.
*/
export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void;
/*
* Asynchronous readFile - Asynchronously reads the entire contents of a file.
*
* @param fileName
* @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.
*/
export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void;
/*
* Synchronous readFile - Synchronously reads the entire contents of a file.
*
* @param fileName
* @param encoding
*/
export function readFileSync(filename: string, encoding: string): string;
/*
* Synchronous readFile - Synchronously reads the entire contents of a file.
*
* @param fileName
* @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer.
*/
export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string;
/*
* Synchronous readFile - Synchronously reads the entire contents of a file.
*
* @param fileName
* @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer.
*/
export function readFileSync(filename: string, options?: { flag?: string; }): Buffer;
export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void;
export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;
export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;
export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void;
export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void;
export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;
export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;
export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void;
export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void;
export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void;
export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void;
export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void;
export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void;
export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher;
export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher;
export function exists(path: string, callback?: (exists: boolean) => void): void;
export function existsSync(path: string): boolean;
/** Constant for fs.access(). File is visible to the calling process. */
export var F_OK: number;
/** Constant for fs.access(). File can be read by the calling process. */
export var R_OK: number;
/** Constant for fs.access(). File can be written by the calling process. */
export var W_OK: number;
/** Constant for fs.access(). File can be executed by the calling process. */
export var X_OK: number;
/** Tests a user's permissions for the file specified by path. */
export function access(path: string, callback: (err: NodeJS.ErrnoException) => void): void;
export function access(path: string, mode: number, callback: (err: NodeJS.ErrnoException) => void): void;
/** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */
export function accessSync(path: string, mode ?: number): void;
export function createReadStream(path: string, options?: {
flags?: string;
encoding?: string;
fd?: number;
mode?: number;
autoClose?: boolean;
}): ReadStream;
export function createWriteStream(path: string, options?: {
flags?: string;
encoding?: string;
fd?: number;
mode?: number;
}): WriteStream;
}
declare module "path" {
/**
* A parsed path object generated by path.parse() or consumed by path.format().
*/
export interface ParsedPath {
/**
* The root of the path such as '/' or 'c:\'
*/
root: string;
/**
* The full directory path such as '/home/user/dir' or 'c:\path\dir'
*/
dir: string;
/**
* The file name including extension (if any) such as 'index.html'
*/
base: string;
/**
* The file extension (if any) such as '.html'
*/
ext: string;
/**
* The file name without extension (if any) such as 'index'
*/
name: string;
}
/**
* Normalize a string path, reducing '..' and '.' parts.
* When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.
*
* @param p string path to normalize.
*/
export function normalize(p: string): string;
/**
* Join all arguments together and normalize the resulting path.
* Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.
*
* @param paths string paths to join.
*/
export function join(...paths: any[]): string;
/**
* Join all arguments together and normalize the resulting path.
* Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.
*
* @param paths string paths to join.
*/
export function join(...paths: string[]): string;
/**
* The right-most parameter is considered {to}. Other parameters are considered an array of {from}.
*
* Starting from leftmost {from} paramter, resolves {to} to an absolute path.
*
* If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.
*
* @param pathSegments string paths to join. Non-string arguments are ignored.
*/
export function resolve(...pathSegments: any[]): string;
/**
* Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.
*
* @param path path to test.
*/
export function isAbsolute(path: string): boolean;
/**
* Solve the relative path from {from} to {to}.
* At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve.
*
* @param from
* @param to
*/
export function relative(from: string, to: string): string;
/**
* Return the directory name of a path. Similar to the Unix dirname command.
*
* @param p the path to evaluate.
*/
export function dirname(p: string): string;
/**
* Return the last portion of a path. Similar to the Unix basename command.
* Often used to extract the file name from a fully qualified path.
*
* @param p the path to evaluate.
* @param ext optionally, an extension to remove from the result.
*/
export function basename(p: string, ext?: string): string;
/**
* Return the extension of the path, from the last '.' to end of string in the last portion of the path.
* If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string
*
* @param p the path to evaluate.
*/
export function extname(p: string): string;
/**
* The platform-specific file separator. '\\' or '/'.
*/
export var sep: string;
/**
* The platform-specific file delimiter. ';' or ':'.
*/
export var delimiter: string;
/**
* Returns an object from a path string - the opposite of format().
*
* @param pathString path to evaluate.
*/
export function parse(pathString: string): ParsedPath;
/**
* Returns a path string from an object - the opposite of parse().
*
* @param pathString path to evaluate.
*/
export function format(pathObject: ParsedPath): string;
export module posix {
export function normalize(p: string): string;
export function join(...paths: any[]): string;
export function resolve(...pathSegments: any[]): string;
export function isAbsolute(p: string): boolean;
export function relative(from: string, to: string): string;
export function dirname(p: string): string;
export function basename(p: string, ext?: string): string;
export function extname(p: string): string;
export var sep: string;
export var delimiter: string;
export function parse(p: string): ParsedPath;
export function format(pP: ParsedPath): string;
}
export module win32 {
export function normalize(p: string): string;
export function join(...paths: any[]): string;
export function resolve(...pathSegments: any[]): string;
export function isAbsolute(p: string): boolean;
export function relative(from: string, to: string): string;
export function dirname(p: string): string;
export function basename(p: string, ext?: string): string;
export function extname(p: string): string;
export var sep: string;
export var delimiter: string;
export function parse(p: string): ParsedPath;
export function format(pP: ParsedPath): string;
}
}
declare module "string_decoder" {
export interface NodeStringDecoder {
write(buffer: Buffer): string;
detectIncompleteChar(buffer: Buffer): number;
}
export var StringDecoder: {
new (encoding: string): NodeStringDecoder;
};
}
declare module "tls" {
import * as crypto from "crypto";
import * as net from "net";
import * as stream from "stream";
var CLIENT_RENEG_LIMIT: number;
var CLIENT_RENEG_WINDOW: number;
export interface TlsOptions {
host?: string;
port?: number;
pfx?: any; //string or buffer
key?: any; //string or buffer
passphrase?: string;
cert?: any;
ca?: any; //string or buffer
crl?: any; //string or string array
ciphers?: string;
honorCipherOrder?: any;
requestCert?: boolean;
rejectUnauthorized?: boolean;
NPNProtocols?: any; //array or Buffer;
SNICallback?: (servername: string) => any;
}
export interface ConnectionOptions {
host?: string;
port?: number;
socket?: net.Socket;
pfx?: any; //string | Buffer
key?: any; //string | Buffer
passphrase?: string;
cert?: any; //string | Buffer
ca?: any; //Array of string | Buffer
rejectUnauthorized?: boolean;
NPNProtocols?: any; //Array of string | Buffer
servername?: string;
}
export interface Server extends net.Server {
// Extended base methods
listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server;
listen(path: string, listeningListener?: Function): Server;
listen(handle: any, listeningListener?: Function): Server;
listen(port: number, host?: string, callback?: Function): Server;
close(): Server;
address(): { port: number; family: string; address: string; };
addContext(hostName: string, credentials: {
key: string;
cert: string;
ca: string;
}): void;
maxConnections: number;
connections: number;
}
export interface ClearTextStream extends stream.Duplex {
authorized: boolean;
authorizationError: Error;
getPeerCertificate(): any;
getCipher: {
name: string;
version: string;
};
address: {
port: number;
family: string;
address: string;
};
remoteAddress: string;
remotePort: number;
}
export interface SecurePair {
encrypted: any;
cleartext: any;
}
export interface SecureContextOptions {
pfx?: any; //string | buffer
key?: any; //string | buffer
passphrase?: string;
cert?: any; // string | buffer
ca?: any; // string | buffer
crl?: any; // string | string[]
ciphers?: string;
honorCipherOrder?: boolean;
}
export interface SecureContext {
context: any;
}
export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server;
export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream;
export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream;
export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream;
export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair;
export function createSecureContext(details: SecureContextOptions): SecureContext;
}
declare module "crypto" {
export interface CredentialDetails {
pfx: string;
key: string;
passphrase: string;
cert: string;
ca: any; //string | string array
crl: any; //string | string array
ciphers: string;
}
export interface Credentials { context?: any; }
export function createCredentials(details: CredentialDetails): Credentials;
export function createHash(algorithm: string): Hash;
export function createHmac(algorithm: string, key: string): Hmac;
export function createHmac(algorithm: string, key: Buffer): Hmac;
interface Hash {
update(data: any, input_encoding?: string): Hash;
digest(encoding: 'buffer'): Buffer;
digest(encoding: string): any;
digest(): Buffer;
}
interface Hmac {
update(data: any, input_encoding?: string): Hmac;
digest(encoding: 'buffer'): Buffer;
digest(encoding: string): any;
digest(): Buffer;
}
export function createCipher(algorithm: string, password: any): Cipher;
export function createCipheriv(algorithm: string, key: any, iv: any): Cipher;
interface Cipher {
update(data: Buffer): Buffer;
update(data: string, input_encoding?: string, output_encoding?: string): string;
final(): Buffer;
final(output_encoding: string): string;
setAutoPadding(auto_padding: boolean): void;
}
export function createDecipher(algorithm: string, password: any): Decipher;
export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher;
interface Decipher {
update(data: Buffer): Buffer;
update(data: string, input_encoding?: string, output_encoding?: string): string;
final(): Buffer;
final(output_encoding: string): string;
setAutoPadding(auto_padding: boolean): void;
}
export function createSign(algorithm: string): Signer;
interface Signer extends NodeJS.WritableStream {
update(data: any): void;
sign(private_key: string, output_format: string): string;
}
export function createVerify(algorith: string): Verify;
interface Verify extends NodeJS.WritableStream {
update(data: any): void;
verify(object: string, signature: string, signature_format?: string): boolean;
}
export function createDiffieHellman(prime_length: number): DiffieHellman;
export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman;
interface DiffieHellman {
generateKeys(encoding?: string): string;
computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string;
getPrime(encoding?: string): string;
getGenerator(encoding: string): string;
getPublicKey(encoding?: string): string;
getPrivateKey(encoding?: string): string;
setPublicKey(public_key: string, encoding?: string): void;
setPrivateKey(public_key: string, encoding?: string): void;
}
export function getDiffieHellman(group_name: string): DiffieHellman;
export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void;
export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void;
export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number) : Buffer;
export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string) : Buffer;
export function randomBytes(size: number): Buffer;
export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void;
export function pseudoRandomBytes(size: number): Buffer;
export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void;
}
declare module "stream" {
import * as events from "events";
export class Stream extends events.EventEmitter {
pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;
}
export interface ReadableOptions {
highWaterMark?: number;
encoding?: string;
objectMode?: boolean;
}
export class Readable extends events.EventEmitter implements NodeJS.ReadableStream {
readable: boolean;
constructor(opts?: ReadableOptions);
_read(size: number): void;
read(size?: number): any;
setEncoding(encoding: string): void;
pause(): void;
resume(): void;
pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;
unpipe<T extends NodeJS.WritableStream>(destination?: T): void;
unshift(chunk: any): void;
wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream;
push(chunk: any, encoding?: string): boolean;
}
export interface WritableOptions {
highWaterMark?: number;
decodeStrings?: boolean;
objectMode?: boolean;
}
export class Writable extends events.EventEmitter implements NodeJS.WritableStream {
writable: boolean;
constructor(opts?: WritableOptions);
_write(chunk: any, encoding: string, callback: Function): void;
write(chunk: any, cb?: Function): boolean;
write(chunk: any, encoding?: string, cb?: Function): boolean;
end(): void;
end(chunk: any, cb?: Function): void;
end(chunk: any, encoding?: string, cb?: Function): void;
}
export interface DuplexOptions extends ReadableOptions, WritableOptions {
allowHalfOpen?: boolean;
}
// Note: Duplex extends both Readable and Writable.
export class Duplex extends Readable implements NodeJS.ReadWriteStream {
writable: boolean;
constructor(opts?: DuplexOptions);
_write(chunk: any, encoding: string, callback: Function): void;
write(chunk: any, cb?: Function): boolean;
write(chunk: any, encoding?: string, cb?: Function): boolean;
end(): void;
end(chunk: any, cb?: Function): void;
end(chunk: any, encoding?: string, cb?: Function): void;
}
export interface TransformOptions extends ReadableOptions, WritableOptions {}
// Note: Transform lacks the _read and _write methods of Readable/Writable.
export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream {
readable: boolean;
writable: boolean;
constructor(opts?: TransformOptions);
_transform(chunk: any, encoding: string, callback: Function): void;
_flush(callback: Function): void;
read(size?: number): any;
setEncoding(encoding: string): void;
pause(): void;
resume(): void;
pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;
unpipe<T extends NodeJS.WritableStream>(destination?: T): void;
unshift(chunk: any): void;
wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream;
push(chunk: any, encoding?: string): boolean;
write(chunk: any, cb?: Function): boolean;
write(chunk: any, encoding?: string, cb?: Function): boolean;
end(): void;
end(chunk: any, cb?: Function): void;
end(chunk: any, encoding?: string, cb?: Function): void;
}
export class PassThrough extends Transform {}
}
declare module "util" {
export interface InspectOptions {
showHidden?: boolean;
depth?: number;
colors?: boolean;
customInspect?: boolean;
}
export function format(format: any, ...param: any[]): string;
export function debug(string: string): void;
export function error(...param: any[]): void;
export function puts(...param: any[]): void;
export function print(...param: any[]): void;
export function log(string: string): void;
export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string;
export function inspect(object: any, options: InspectOptions): string;
export function isArray(object: any): boolean;
export function isRegExp(object: any): boolean;
export function isDate(object: any): boolean;
export function isError(object: any): boolean;
export function inherits(constructor: any, superConstructor: any): void;
export function debuglog(key:string): (msg:string,...param: any[])=>void;
}
declare module "assert" {
function internal (value: any, message?: string): void;
module internal {
export class AssertionError implements Error {
name: string;
message: string;
actual: any;
expected: any;
operator: string;
generatedMessage: boolean;
constructor(options?: {message?: string; actual?: any; expected?: any;
operator?: string; stackStartFunction?: Function});
}
export function fail(actual?: any, expected?: any, message?: string, operator?: string): void;
export function ok(value: any, message?: string): void;
export function equal(actual: any, expected: any, message?: string): void;
export function notEqual(actual: any, expected: any, message?: string): void;
export function deepEqual(actual: any, expected: any, message?: string): void;
export function notDeepEqual(acutal: any, expected: any, message?: string): void;
export function strictEqual(actual: any, expected: any, message?: string): void;
export function notStrictEqual(actual: any, expected: any, message?: string): void;
export function deepStrictEqual(actual: any, expected: any, message?: string): void;
export function notDeepStrictEqual(actual: any, expected: any, message?: string): void;
export var throws: {
(block: Function, message?: string): void;
(block: Function, error: Function, message?: string): void;
(block: Function, error: RegExp, message?: string): void;
(block: Function, error: (err: any) => boolean, message?: string): void;
};
export var doesNotThrow: {
(block: Function, message?: string): void;
(block: Function, error: Function, message?: string): void;
(block: Function, error: RegExp, message?: string): void;
(block: Function, error: (err: any) => boolean, message?: string): void;
};
export function ifError(value: any): void;
}
export = internal;
}
declare module "tty" {
import * as net from "net";
export function isatty(fd: number): boolean;
export interface ReadStream extends net.Socket {
isRaw: boolean;
setRawMode(mode: boolean): void;
}
export interface WriteStream extends net.Socket {
columns: number;
rows: number;
}
}
declare module "domain" {
import * as events from "events";
export class Domain extends events.EventEmitter {
run(fn: Function): void;
add(emitter: events.EventEmitter): void;
remove(emitter: events.EventEmitter): void;
bind(cb: (err: Error, data: any) => any): any;
intercept(cb: (data: any) => any): any;
dispose(): void;
addListener(event: string, listener: Function): Domain;
on(event: string, listener: Function): Domain;
once(event: string, listener: Function): Domain;
removeListener(event: string, listener: Function): Domain;
removeAllListeners(event?: string): Domain;
}
export function create(): Domain;
}
declare module "constants" {
export var E2BIG: number;
export var EACCES: number;
export var EADDRINUSE: number;
export var EADDRNOTAVAIL: number;
export var EAFNOSUPPORT: number;
export var EAGAIN: number;
export var EALREADY: number;
export var EBADF: number;
export var EBADMSG: number;
export var EBUSY: number;
export var ECANCELED: number;
export var ECHILD: number;
export var ECONNABORTED: number;
export var ECONNREFUSED: number;
export var ECONNRESET: number;
export var EDEADLK: number;
export var EDESTADDRREQ: number;
export var EDOM: number;
export var EEXIST: number;
export var EFAULT: number;
export var EFBIG: number;
export var EHOSTUNREACH: number;
export var EIDRM: number;
export var EILSEQ: number;
export var EINPROGRESS: number;
export var EINTR: number;
export var EINVAL: number;
export var EIO: number;
export var EISCONN: number;
export var EISDIR: number;
export var ELOOP: number;
export var EMFILE: number;
export var EMLINK: number;
export var EMSGSIZE: number;
export var ENAMETOOLONG: number;
export var ENETDOWN: number;
export var ENETRESET: number;
export var ENETUNREACH: number;
export var ENFILE: number;
export var ENOBUFS: number;
export var ENODATA: number;
export var ENODEV: number;
export var ENOENT: number;
export var ENOEXEC: number;
export var ENOLCK: number;
export var ENOLINK: number;
export var ENOMEM: number;
export var ENOMSG: number;
export var ENOPROTOOPT: number;
export var ENOSPC: number;
export var ENOSR: number;
export var ENOSTR: number;
export var ENOSYS: number;
export var ENOTCONN: number;
export var ENOTDIR: number;
export var ENOTEMPTY: number;
export var ENOTSOCK: number;
export var ENOTSUP: number;
export var ENOTTY: number;
export var ENXIO: number;
export var EOPNOTSUPP: number;
export var EOVERFLOW: number;
export var EPERM: number;
export var EPIPE: number;
export var EPROTO: number;
export var EPROTONOSUPPORT: number;
export var EPROTOTYPE: number;
export var ERANGE: number;
export var EROFS: number;
export var ESPIPE: number;
export var ESRCH: number;
export var ETIME: number;
export var ETIMEDOUT: number;
export var ETXTBSY: number;
export var EWOULDBLOCK: number;
export var EXDEV: number;
export var WSAEINTR: number;
export var WSAEBADF: number;
export var WSAEACCES: number;
export var WSAEFAULT: number;
export var WSAEINVAL: number;
export var WSAEMFILE: number;
export var WSAEWOULDBLOCK: number;
export var WSAEINPROGRESS: number;
export var WSAEALREADY: number;
export var WSAENOTSOCK: number;
export var WSAEDESTADDRREQ: number;
export var WSAEMSGSIZE: number;
export var WSAEPROTOTYPE: number;
export var WSAENOPROTOOPT: number;
export var WSAEPROTONOSUPPORT: number;
export var WSAESOCKTNOSUPPORT: number;
export var WSAEOPNOTSUPP: number;
export var WSAEPFNOSUPPORT: number;
export var WSAEAFNOSUPPORT: number;
export var WSAEADDRINUSE: number;
export var WSAEADDRNOTAVAIL: number;
export var WSAENETDOWN: number;
export var WSAENETUNREACH: number;
export var WSAENETRESET: number;
export var WSAECONNABORTED: number;
export var WSAECONNRESET: number;
export var WSAENOBUFS: number;
export var WSAEISCONN: number;
export var WSAENOTCONN: number;
export var WSAESHUTDOWN: number;
export var WSAETOOMANYREFS: number;
export var WSAETIMEDOUT: number;
export var WSAECONNREFUSED: number;
export var WSAELOOP: number;
export var WSAENAMETOOLONG: number;
export var WSAEHOSTDOWN: number;
export var WSAEHOSTUNREACH: number;
export var WSAENOTEMPTY: number;
export var WSAEPROCLIM: number;
export var WSAEUSERS: number;
export var WSAEDQUOT: number;
export var WSAESTALE: number;
export var WSAEREMOTE: number;
export var WSASYSNOTREADY: number;
export var WSAVERNOTSUPPORTED: number;
export var WSANOTINITIALISED: number;
export var WSAEDISCON: number;
export var WSAENOMORE: number;
export var WSAECANCELLED: number;
export var WSAEINVALIDPROCTABLE: number;
export var WSAEINVALIDPROVIDER: number;
export var WSAEPROVIDERFAILEDINIT: number;
export var WSASYSCALLFAILURE: number;
export var WSASERVICE_NOT_FOUND: number;
export var WSATYPE_NOT_FOUND: number;
export var WSA_E_NO_MORE: number;
export var WSA_E_CANCELLED: number;
export var WSAEREFUSED: number;
export var SIGHUP: number;
export var SIGINT: number;
export var SIGILL: number;
export var SIGABRT: number;
export var SIGFPE: number;
export var SIGKILL: number;
export var SIGSEGV: number;
export var SIGTERM: number;
export var SIGBREAK: number;
export var SIGWINCH: number;
export var SSL_OP_ALL: number;
export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;
export var SSL_OP_CIPHER_SERVER_PREFERENCE: number;
export var SSL_OP_CISCO_ANYCONNECT: number;
export var SSL_OP_COOKIE_EXCHANGE: number;
export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;
export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;
export var SSL_OP_EPHEMERAL_RSA: number;
export var SSL_OP_LEGACY_SERVER_CONNECT: number;
export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number;
export var SSL_OP_MICROSOFT_SESS_ID_BUG: number;
export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number;
export var SSL_OP_NETSCAPE_CA_DN_BUG: number;
export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number;
export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number;
export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number;
export var SSL_OP_NO_COMPRESSION: number;
export var SSL_OP_NO_QUERY_MTU: number;
export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;
export var SSL_OP_NO_SSLv2: number;
export var SSL_OP_NO_SSLv3: number;
export var SSL_OP_NO_TICKET: number;
export var SSL_OP_NO_TLSv1: number;
export var SSL_OP_NO_TLSv1_1: number;
export var SSL_OP_NO_TLSv1_2: number;
export var SSL_OP_PKCS1_CHECK_1: number;
export var SSL_OP_PKCS1_CHECK_2: number;
export var SSL_OP_SINGLE_DH_USE: number;
export var SSL_OP_SINGLE_ECDH_USE: number;
export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number;
export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number;
export var SSL_OP_TLS_BLOCK_PADDING_BUG: number;
export var SSL_OP_TLS_D5_BUG: number;
export var SSL_OP_TLS_ROLLBACK_BUG: number;
export var ENGINE_METHOD_DSA: number;
export var ENGINE_METHOD_DH: number;
export var ENGINE_METHOD_RAND: number;
export var ENGINE_METHOD_ECDH: number;
export var ENGINE_METHOD_ECDSA: number;
export var ENGINE_METHOD_CIPHERS: number;
export var ENGINE_METHOD_DIGESTS: number;
export var ENGINE_METHOD_STORE: number;
export var ENGINE_METHOD_PKEY_METHS: number;
export var ENGINE_METHOD_PKEY_ASN1_METHS: number;
export var ENGINE_METHOD_ALL: number;
export var ENGINE_METHOD_NONE: number;
export var DH_CHECK_P_NOT_SAFE_PRIME: number;
export var DH_CHECK_P_NOT_PRIME: number;
export var DH_UNABLE_TO_CHECK_GENERATOR: number;
export var DH_NOT_SUITABLE_GENERATOR: number;
export var NPN_ENABLED: number;
export var RSA_PKCS1_PADDING: number;
export var RSA_SSLV23_PADDING: number;
export var RSA_NO_PADDING: number;
export var RSA_PKCS1_OAEP_PADDING: number;
export var RSA_X931_PADDING: number;
export var RSA_PKCS1_PSS_PADDING: number;
export var POINT_CONVERSION_COMPRESSED: number;
export var POINT_CONVERSION_UNCOMPRESSED: number;
export var POINT_CONVERSION_HYBRID: number;
export var O_RDONLY: number;
export var O_WRONLY: number;
export var O_RDWR: number;
export var S_IFMT: number;
export var S_IFREG: number;
export var S_IFDIR: number;
export var S_IFCHR: number;
export var S_IFLNK: number;
export var O_CREAT: number;
export var O_EXCL: number;
export var O_TRUNC: number;
export var O_APPEND: number;
export var F_OK: number;
export var R_OK: number;
export var W_OK: number;
export var X_OK: number;
export var UV_UDP_REUSEADDR: number;
}
| apache-2.0 |
ghedsouza/django | django/utils/dateparse.py | 4167 | """Functions to parse datetime objects."""
# We're using regular expressions rather than time.strptime because:
# - They provide both validation and parsing.
# - They're more flexible for datetimes.
# - The date/datetime/time constructors produce friendlier error messages.
import datetime
import re
from django.utils.timezone import get_fixed_timezone, utc
date_re = re.compile(
r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$'
)
time_re = re.compile(
r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
)
datetime_re = re.compile(
r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
r'[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
r'(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$'
)
standard_duration_re = re.compile(
r'^'
r'(?:(?P<days>-?\d+) (days?, )?)?'
r'((?:(?P<hours>-?\d+):)(?=\d+:\d+))?'
r'(?:(?P<minutes>-?\d+):)?'
r'(?P<seconds>-?\d+)'
r'(?:\.(?P<microseconds>\d{1,6})\d{0,6})?'
r'$'
)
# Support the sections of ISO 8601 date representation that are accepted by
# timedelta
iso8601_duration_re = re.compile(
r'^(?P<sign>[-+]?)'
r'P'
r'(?:(?P<days>\d+(.\d+)?)D)?'
r'(?:T'
r'(?:(?P<hours>\d+(.\d+)?)H)?'
r'(?:(?P<minutes>\d+(.\d+)?)M)?'
r'(?:(?P<seconds>\d+(.\d+)?)S)?'
r')?'
r'$'
)
def parse_date(value):
"""Parse a string and return a datetime.date.
Raise ValueError if the input is well formatted but not a valid date.
Return None if the input isn't well formatted.
"""
match = date_re.match(value)
if match:
kw = {k: int(v) for k, v in match.groupdict().items()}
return datetime.date(**kw)
def parse_time(value):
"""Parse a string and return a datetime.time.
This function doesn't support time zone offsets.
Raise ValueError if the input is well formatted but not a valid time.
Return None if the input isn't well formatted, in particular if it
contains an offset.
"""
match = time_re.match(value)
if match:
kw = match.groupdict()
if kw['microsecond']:
kw['microsecond'] = kw['microsecond'].ljust(6, '0')
kw = {k: int(v) for k, v in kw.items() if v is not None}
return datetime.time(**kw)
def parse_datetime(value):
"""Parse a string and return a datetime.datetime.
This function supports time zone offsets. When the input contains one,
the output uses a timezone with a fixed offset from UTC.
Raise ValueError if the input is well formatted but not a valid datetime.
Return None if the input isn't well formatted.
"""
match = datetime_re.match(value)
if match:
kw = match.groupdict()
if kw['microsecond']:
kw['microsecond'] = kw['microsecond'].ljust(6, '0')
tzinfo = kw.pop('tzinfo')
if tzinfo == 'Z':
tzinfo = utc
elif tzinfo is not None:
offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
offset = 60 * int(tzinfo[1:3]) + offset_mins
if tzinfo[0] == '-':
offset = -offset
tzinfo = get_fixed_timezone(offset)
kw = {k: int(v) for k, v in kw.items() if v is not None}
kw['tzinfo'] = tzinfo
return datetime.datetime(**kw)
def parse_duration(value):
"""Parse a duration string and return a datetime.timedelta.
The preferred format for durations in Django is '%d %H:%M:%S.%f'.
Also supports ISO 8601 representation.
"""
match = standard_duration_re.match(value)
if not match:
match = iso8601_duration_re.match(value)
if match:
kw = match.groupdict()
sign = -1 if kw.pop('sign', '+') == '-' else 1
if kw.get('microseconds'):
kw['microseconds'] = kw['microseconds'].ljust(6, '0')
if kw.get('seconds') and kw.get('microseconds') and kw['seconds'].startswith('-'):
kw['microseconds'] = '-' + kw['microseconds']
kw = {k: float(v) for k, v in kw.items() if v is not None}
return sign * datetime.timedelta(**kw)
| bsd-3-clause |
asifmadnan/arrayfire | src/backend/cuda/orb.hpp | 815 | /*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <af/features.h>
#include <Array.hpp>
using af::features;
namespace cuda
{
template<typename T, typename convAccT>
unsigned orb(Array<float> &x, Array<float> &y, Array<float> &score,
Array<float> &orientation, Array<float> &size,
Array<unsigned> &desc,
const Array<T>& image,
const float fast_thr, const unsigned max_feat,
const float scl_fctr, const unsigned levels,
const bool blur_img);
}
| bsd-3-clause |
ClauStan/StarLight | StarLight/StarLight/cameraclass.cpp | 2272 | ////////////////////////////////////////////////////////////////////////////////
// Filename: cameraclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "cameraclass.h"
CameraClass::CameraClass()
{
m_positionX = 0.0f;
m_positionY = 0.0f;
m_positionZ = 0.0f;
m_rotationX = 0.0f;
m_rotationY = 0.0f;
m_rotationZ = 0.0f;
}
CameraClass::CameraClass(const CameraClass& other)
{
}
CameraClass::~CameraClass()
{
}
void CameraClass::SetPosition(float x, float y, float z)
{
m_positionX = x;
m_positionY = y;
m_positionZ = z;
return;
}
void CameraClass::SetRotation(float x, float y, float z)
{
m_rotationX = x;
m_rotationY = y;
m_rotationZ = z;
return;
}
D3DXVECTOR3 CameraClass::GetPosition()
{
return D3DXVECTOR3(m_positionX, m_positionY, m_positionZ);
}
D3DXVECTOR3 CameraClass::GetRotation()
{
return D3DXVECTOR3(m_rotationX, m_rotationY, m_rotationZ);
}
void CameraClass::Render()
{
D3DXVECTOR3 up, position, lookAt;
float yaw, pitch, roll;
D3DXMATRIX rotationMatrix;
// Setup the vector that points upwards.
up.x = 0.0f;
up.y = 1.0f;
up.z = 0.0f;
// Setup the position of the camera in the world.
position.x = m_positionX;
position.y = m_positionY;
position.z = m_positionZ;
// Setup where the camera is looking by default.
lookAt.x = 0.0f;
lookAt.y = 0.0f;
lookAt.z = 1.0f;
// Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians.
pitch = m_rotationX * 0.0174532925f;
yaw = m_rotationY * 0.0174532925f;
roll = m_rotationZ * 0.0174532925f;
// Create the rotation matrix from the yaw, pitch, and roll values.
D3DXMatrixRotationYawPitchRoll(&rotationMatrix, yaw, pitch, roll);
// Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin.
D3DXVec3TransformCoord(&lookAt, &lookAt, &rotationMatrix);
D3DXVec3TransformCoord(&up, &up, &rotationMatrix);
// Translate the rotated camera position to the location of the viewer.
lookAt = position + lookAt;
// Finally create the view matrix from the three updated vectors.
D3DXMatrixLookAtLH(&m_viewMatrix, &position, &lookAt, &up);
return;
}
void CameraClass::GetViewMatrix(D3DXMATRIX& viewMatrix)
{
viewMatrix = m_viewMatrix;
return;
} | mit |
ralzate/Produccion | vendor/bundle/ruby/2.1.0/gems/fog-ecloud-0.3.0/lib/fog/compute/ecloud/models/memory_usage_detail.rb | 294 | module Fog
module Compute
class Ecloud
class MemoryUsageDetail < Fog::Ecloud::Model
identity :href
attribute :time, :aliases => :Time
attribute :value, :aliases => :Value
def id
href.scan(/\d+/)[0]
end
end
end
end
end
| mit |
andrewpsp/vagrant-aws | lib/vagrant-aws/action/message_not_created.rb | 296 | module VagrantPlugins
module AWS
module Action
class MessageNotCreated
def initialize(app, env)
@app = app
end
def call(env)
env[:ui].info(I18n.t("vagrant_aws.not_created"))
@app.call(env)
end
end
end
end
end
| mit |
beyondplus/cms | resources/views/auth/passwords/email.blade.php | 1896 | @extends('layouts.app')
<!-- Main Content -->
@section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Reset Password</div>
<div class="panel-body">
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
<form class="form-horizontal" role="form" method="POST" action="{{ url('/password/email') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}">
@if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Send Password Reset Link
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
| mit |
ilyhacker/module-zero | src/Abp.Zero.NHibernate/Zero/NHibernate/EntityMappings/ApplicationLanguageTextMap.cs | 520 | using Abp.Localization;
using Abp.NHibernate.EntityMappings;
namespace Abp.Zero.NHibernate.EntityMappings
{
public class ApplicationLanguageTextMap : EntityMap<ApplicationLanguageText, long>
{
public ApplicationLanguageTextMap()
: base("AbpLanguageTexts")
{
Map(x => x.TenantId);
Map(x => x.LanguageName);
Map(x => x.Source);
Map(x => x.Key);
Map(x => x.Value);
this.MapAudited();
}
}
} | mit |
HasanSa/hackathon | node_modules/react-helmet/node_modules/core-js/modules/_set-species.js | 363 | 'use strict';
var global = require('./_global')
, $ = require('./_')
, DESCRIPTORS = require('./_descriptors')
, SPECIES = require('./_wks')('species');
module.exports = function(KEY){
var C = global[KEY];
if(DESCRIPTORS && C && !C[SPECIES])$.setDesc(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
}; | mit |
dyeimys/republico | e2e/app.e2e-spec.ts | 307 | import { CoreUIPage } from './app.po';
describe('core-ui App', function() {
let page: CoreUIPage;
beforeEach(() => {
page = new CoreUIPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('app works!');
});
});
| mit |
gcao/T.js | public/examples/ace-builds/src/mode-vhdl.js | 5365 | /* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2013, Ajax.org B.V.
* 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 Ajax.org B.V. 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 AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/vhdl', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/vhdl_highlight_rules', 'ace/range'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var VHDLHighlightRules = require("./vhdl_highlight_rules").VHDLHighlightRules;
var Range = require("../range").Range;
var Mode = function() {
this.HighlightRules = VHDLHighlightRules;
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "--";
this.$id = "ace/mode/vhdl";
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/vhdl_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var VHDLHighlightRules = function() {
var keywords = "access|after|ailas|all|architecture|assert|attribute|"+
"begin|block|buffer|bus|case|component|configuration|"+
"disconnect|downto|else|elsif|end|entity|file|for|function|"+
"generate|generic|guarded|if|impure|in|inertial|inout|is|"+
"label|linkage|literal|loop|mapnew|next|of|on|open|"+
"others|out|port|process|pure|range|record|reject|"+
"report|return|select|shared|subtype|then|to|transport|"+
"type|unaffected|united|until|wait|when|while|with";
var storageType = "bit|bit_vector|boolean|character|integer|line|natural|"+
"positive|real|register|severity|signal|signed|"+
"std_logic|std_logic_vector|string||text|time|unsigned|"+
"variable";
var storageModifiers = "array|constant";
var keywordOperators = "abs|and|mod|nand|nor|not|rem|rol|ror|sla|sll|sra"+
"srl|xnor|xor";
var builtinConstants = (
"true|false|null"
);
var keywordMapper = this.createKeywordMapper({
"keyword.operator": keywordOperators,
"keyword": keywords,
"constant.language": builtinConstants,
"storage.modifier": storageModifiers,
"storage.type": storageType
}, "identifier", true);
this.$rules = {
"start" : [ {
token : "comment",
regex : "--.*$"
}, {
token : "string", // " string
regex : '".*?"'
}, {
token : "string", // ' string
regex : "'.*?'"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : "keyword", // pre-compiler directives
regex : "\\s*(?:library|package|use)\\b",
}, {
token : keywordMapper,
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "keyword.operator",
regex : "&|\\*|\\+|\\-|\\/|<|=|>|\\||=>|\\*\\*|:=|\\/=|>=|<=|<>"
}, {
token : "punctuation.operator",
regex : "\\'|\\:|\\,|\\;|\\."
},{
token : "paren.lparen",
regex : "[[(]"
}, {
token : "paren.rparen",
regex : "[\\])]"
}, {
token : "text",
regex : "\\s+"
} ],
};
};
oop.inherits(VHDLHighlightRules, TextHighlightRules);
exports.VHDLHighlightRules = VHDLHighlightRules;
});
| mit |
parameshbabu/samples | AllJoyn/Platform/DeviceProviders/WorkItemQueue.cpp | 3501 | //
// Copyright (c) 2015, Microsoft Corporation
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#pragma once
#include "pch.h"
#include "WorkItemQueue.h"
WorkItemQueue::WorkItemQueue()
: m_threadId(0)
{
// Both must be created as manual reset events
m_availableWorkEvent = ::CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, SYNCHRONIZE | EVENT_MODIFY_STATE);
m_quitEvent = ::CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, SYNCHRONIZE | EVENT_MODIFY_STATE);
m_exitEvent = ::CreateEventEx(NULL, NULL, 0, SYNCHRONIZE | EVENT_MODIFY_STATE);
}
WorkItemQueue::~WorkItemQueue()
{
if (NULL != m_availableWorkEvent)
{
::CloseHandle(m_availableWorkEvent);
m_availableWorkEvent = NULL;
}
if (NULL != m_quitEvent)
{
::CloseHandle(m_quitEvent);
m_quitEvent = NULL;
}
if (NULL != m_exitEvent)
{
::CloseHandle(m_exitEvent);
m_exitEvent = NULL;
}
m_threadId = 0;
}
void WorkItemQueue::Start()
{
m_threadId = ::GetCurrentThreadId();
::ResetEvent(m_availableWorkEvent);
::ResetEvent(m_quitEvent);
::ResetEvent(m_exitEvent);
HANDLE eventHandles[] = { m_availableWorkEvent, m_quitEvent };
for (;;)
{
// Wait for either new queued workitems, or a queued quit signal
DWORD waitResult = ::WaitForMultipleObjectsEx(_countof(eventHandles), eventHandles, false, INFINITE, true);
if (waitResult != WAIT_OBJECT_0)
{
break;
}
work_item_function workItem;
{
AutoLock lockScope(&m_queueLock, true);
workItem = m_queue.front();
m_queue.pop();
if (m_queue.empty())
{
::ResetEvent(m_availableWorkEvent);
}
}
workItem();
}
// Empty any workitems remaining in the queue
{
AutoLock lockScope(&m_queueLock, true);
while (!m_queue.empty())
{
m_queue.pop();
}
}
::SetEvent(m_exitEvent);
}
void WorkItemQueue::PostWorkItem(work_item_function workItem)
{
// Ignore further calls after quit request
if (WAIT_OBJECT_0 == WaitForSingleObjectEx(m_quitEvent, 0, false))
return;
AutoLock lockScope(&m_queueLock, true);
m_queue.push(workItem);
::SetEvent(m_availableWorkEvent);
}
void WorkItemQueue::PostQuit()
{
// Ignore further calls after quit request
if (WAIT_OBJECT_0 == WaitForSingleObjectEx(m_quitEvent, 0, false))
return;
// Signal the queue processing thread to quit
::SetEvent(m_quitEvent);
}
void WorkItemQueue::WaitForQuit()
{
if ((0 != m_threadId) && (::GetCurrentThreadId() != m_threadId))
{
::WaitForSingleObjectEx(m_exitEvent, INFINITE, false);
m_threadId = 0;
}
}
| mit |
falcontersama/chatbot | vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php | 1807 | <?php
namespace Illuminate\Foundation\Testing\Concerns;
use PHPUnit_Framework_Constraint_Not as ReverseConstraint;
use Illuminate\Foundation\Testing\Constraints\HasInDatabase;
trait InteractsWithDatabase
{
/**
* Assert that a given where condition exists in the database.
*
* @param string $table
* @param array $data
* @param string $connection
* @return $this
*/
protected function assertDatabaseHas($table, array $data, $connection = null)
{
$this->assertThat(
$table, new HasInDatabase($this->getConnection($connection), $data)
);
return $this;
}
/**
* Assert that a given where condition does not exist in the database.
*
* @param string $table
* @param array $data
* @param string $connection
* @return $this
*/
protected function assertDatabaseMissing($table, array $data, $connection = null)
{
$constraint = new ReverseConstraint(
new HasInDatabase($this->getConnection($connection), $data)
);
$this->assertThat($table, $constraint);
return $this;
}
/**
* Get the database connection.
*
* @param string|null $connection
* @return \Illuminate\Database\Connection
*/
protected function getConnection($connection = null)
{
$database = $this->app->make('db');
$connection = $connection ?: $database->getDefaultConnection();
return $database->connection($connection);
}
/**
* Seed a given database connection.
*
* @param string $class
* @return $this
*/
public function seed($class = 'DatabaseSeeder')
{
$this->artisan('db:seed', ['--class' => $class]);
return $this;
}
}
| mit |
moveable-dev1/rep1 | Latest/wp-content/plugins/gravityforms/includes/api.php | 45628 | <?php
if ( ! class_exists( 'GFForms' ) ) {
die();
}
/**
* API for standard Gravity Forms functionality.
*
* Supports:
* - Forms
* - Entries
*
* @package Gravity Forms
* @subpackage GFAPI
* @since 1.8
* @access public
*/
class GFAPI {
// FORMS ----------------------------------------------------
/**
* Returns the form object for a given Form ID
*
* @since 1.8
* @access public
* @static
*
* @param int $form_id The ID of the Form
*
* @return mixed The form meta array or false
*/
public static function get_form( $form_id ) {
$form_id = absint( $form_id );
$form = GFFormsModel::get_form_meta( $form_id );
if ( ! $form ) {
return false;
}
//loading form columns into meta
$form_info = GFFormsModel::get_form( $form_id, true );
$form['is_active'] = $form_info->is_active;
$form['date_created'] = $form_info->date_created;
$form['is_trash'] = $form_info->is_trash;
return $form;
}
/**
* Returns all the form objects
*
* @since 1.8.11.5
* @access public
* @static
*
* @param bool $active
* @param bool $trash
*
* @return mixed The array of Forms
*/
public static function get_forms( $active = true, $trash = false ) {
$form_ids = GFFormsModel::get_form_ids( $active, $trash );
if ( empty( $form_ids ) ) {
return array();
}
$forms = array();
foreach ( $form_ids as $form_id ) {
$forms[] = GFAPI::get_form( $form_id );
}
return $forms;
}
/**
* Deletes the forms with the given Form IDs
*
* @since 1.8
* @access public
* @static
*
* @param array $form_ids An array of form IDs to delete
*/
public static function delete_forms( $form_ids ) {
GFFormsModel::delete_forms( $form_ids );
}
/**
* Deletes the form with the given Form ID
*
* @since 1.8
* @access public
* @static
*
* @param int $form_id The ID of the Form to delete
*
* @return mixed True for success, or a WP_Error instance
*/
public static function delete_form( $form_id ) {
$form = self::get_form( $form_id );
if ( empty( $form ) ) {
return new WP_Error( 'not_found', sprintf( __( 'Form with id: %s not found', 'gravityforms' ), $form_id ), $form_id );
}
self::delete_forms( array( $form_id ) );
return true;
}
/**
* Updates the forms with an array of form objects
*
* @since 1.8
* @access public
* @static
*
* @param array $forms The Form objects
*
* @return mixed True for success, or a WP_Error instance
*/
public static function update_forms( $forms ) {
foreach ( $forms as $form ) {
$result = self::update_form( $form );
if ( is_wp_error( $result ) ) {
return $result;
}
}
return true;
}
/**
* Updates the form with a given form object.
*
* @since 1.8
* @access public
* @static
*
* @param array $form The Form object
* @param int $form_id Optional. If specified, then the ID in the Form object will be ignored
*
* @return mixed True for success, or a WP_Error instance
*/
public static function update_form( $form, $form_id = null ) {
global $wpdb;
if ( ! $form ) {
return new WP_Error( 'invalid', __( 'Invalid form object', 'gravityforms' ) );
}
$form_table_name = $wpdb->prefix . 'rg_form';
if ( empty( $form_id ) ) {
$form_id = $form['id'];
} else {
// make sure the form object has the right form id
$form['id'] = $form_id;
if ( isset( $form['fields'] ) ) {
foreach ( $form['fields'] as &$field ) {
if ( $field instanceof GF_Field ) {
$field->formId = $form_id;
} else {
$field['formId'] = $form_id;
}
}
}
}
if ( empty( $form_id ) ) {
return new WP_Error( 'missing_form_id', __( 'Missing form id', 'gravityforms' ) );
}
$meta_table_name = GFFormsModel::get_meta_table_name();
if ( intval( $wpdb->get_var( $wpdb->prepare( "SELECT count(0) FROM {$meta_table_name} WHERE form_id=%d", $form_id ) ) ) == 0 ) {
return new WP_Error( 'not_found', __( 'Form not found', 'gravityforms' ) );
}
// Strip confirmations and notifications
$form_display_meta = $form;
unset( $form_display_meta['confirmations'] );
unset( $form_display_meta['notifications'] );
$result = GFFormsModel::update_form_meta( $form_id, $form_display_meta );
if ( false === $result ) {
return new WP_Error( 'error_updating_form', __( 'Error updating form', 'gravityforms' ), $wpdb->last_error );
}
if ( isset( $form['confirmations'] ) && is_array( $form['confirmations'] ) ) {
$result = GFFormsModel::update_form_meta( $form_id, $form['confirmations'], 'confirmations' );
if ( false === $result ) {
return new WP_Error( 'error_updating_confirmations', __( 'Error updating form confirmations', 'gravityforms' ), $wpdb->last_error );
}
}
if ( isset( $form['notifications'] ) && is_array( $form['notifications'] ) ) {
$result = GFFormsModel::update_form_meta( $form_id, $form['notifications'], 'notifications' );
if ( false === $result ) {
return new WP_Error( 'error_updating_notifications', __( 'Error updating form notifications', 'gravityforms' ), $wpdb->last_error );
}
}
//updating form title and is_active flag
$is_active = rgar( $form, 'is_active' ) ? '1' : '0';
$result = $wpdb->query( $wpdb->prepare( "UPDATE {$form_table_name} SET title=%s, is_active=%s WHERE id=%d", $form['title'], $is_active, $form['id'] ) );
if ( false === $result ) {
return new WP_Error( 'error_updating_title', __( 'Error updating title', 'gravityforms' ), $wpdb->last_error );
}
return true;
}
/**
* Updates a form property - a column in the main forms table. e.g. is_trash, is_active, title
*
* @since 1.8.3.15
* @access public
* @static
*
* @param array $form_ids The IDs of the forms to update
* @param array $property_key The name of the column in the database e.g. is_trash, is_active, title
* @param array $value The new value
*
* @return mixed Either a WP_Error instance or the result of the query
*/
public static function update_forms_property( $form_ids, $property_key, $value ) {
global $wpdb;
$table = GFFormsModel::get_form_table_name();
$db_columns = GFFormsModel::get_form_db_columns();
if ( ! in_array( strtolower( $property_key ), $db_columns ) ) {
return new WP_Error( 'property_key_incorrect', __( 'Property key incorrect', 'gravityforms' ) );
}
$value = esc_sql( $value );
if ( ! is_numeric( $value ) ) {
$value = sprintf( "'%s'", $value );
}
$in_str_arr = array_fill( 0, count( $form_ids ), '%d' );
$in_str = join( $in_str_arr, ',' );
$result = $wpdb->query(
$wpdb->prepare(
"
UPDATE $table
SET {$property_key} = {$value}
WHERE id IN ($in_str)
", $form_ids
)
);
return $result;
}
/**
* Updates the property of one form - columns in the main forms table. e.g. is_trash, is_active, title
*
* @since 1.8.3.15
* @access public
* @static
*
* @param array|int $form_id The ID of the forms to update
* @param string $property_key The name of the column in the database e.g. is_trash, is_active, title
* @param string $value The new value
*
* @return mixed Either a WP_Error instance or the result of the query
*/
public static function update_form_property( $form_id, $property_key, $value ) {
return self::update_forms_property( array( $form_id ), $property_key, $value );
}
/**
* Adds multiple form objects.
*
* @since 1.8
* @access public
* @static
*
* @param array $forms The Form objects
*
* @return mixed Either an array of new form IDs or a WP_Error instance
*/
public static function add_forms( $forms ) {
if ( ! $forms || ! is_array( $forms ) ) {
return new WP_Error( 'invalid', __( 'Invalid form objects', 'gravityforms' ) );
}
$form_ids = array();
foreach ( $forms as $form ) {
$result = self::add_form( $form );
if ( is_wp_error( $result ) ) {
return $result;
}
$form_ids[] = $result;
}
return $form_ids;
}
/**
* Adds a new form using the given Form object. Warning, little checking is done to make sure it's a valid Form object.
*
* @since 1.8
* @access public
* @static
*
* @param array $form_meta The Form object
*
* @return mixed Either the new Form ID or a WP_Error instance
*/
public static function add_form( $form_meta ) {
global $wpdb;
if ( ! $form_meta || ! is_array( $form_meta ) ) {
return new WP_Error( 'invalid', __( 'Invalid form object', 'gravityforms' ) );
}
if ( rgar( $form_meta, 'title' ) == '' ) {
return new WP_Error( 'missing_title', __( 'The form title is missing', 'gravityforms' ) );
}
//Making sure title is not duplicate
$title = $form_meta['title'];
$count = 2;
while ( ! RGFormsModel::is_unique_title( $title ) ) {
$title = $form_meta['title'] . "($count)";
$count ++;
}
//inserting form
$form_id = RGFormsModel::insert_form( $title );
//updating form meta
$form_meta['title'] = $title;
//updating object's id property
$form_meta['id'] = $form_id;
if ( isset( $form_meta['confirmations'] ) ) {
$form_meta['confirmations'] = self::set_property_as_key( $form_meta['confirmations'], 'id' );
GFFormsModel::update_form_meta( $form_id, $form_meta['confirmations'], 'confirmations' );
unset( $form_meta['confirmations'] );
}
if ( isset( $form_meta['notifications'] ) ) {
$form_meta['notifications'] = self::set_property_as_key( $form_meta['notifications'], 'id' );
GFFormsModel::update_form_meta( $form_id, $form_meta['notifications'], 'notifications' );
unset( $form_meta['notifications'] );
}
//updating form meta
$result = GFFormsModel::update_form_meta( $form_id, $form_meta );
if ( false === $result ) {
return new WP_Error( 'insert_form_error', __( 'There was a problem while inserting the form', 'gravityforms' ), $wpdb->last_error );
}
return $form_id;
}
/**
* Private.
*
* @since 1.8
* @access private
* @static
* @ignore
*/
private static function set_property_as_key( $array, $property ) {
$new_array = array();
foreach ( $array as $item ) {
$new_array[ $item[ $property ] ] = $item;
}
return $new_array;
}
// ENTRIES ----------------------------------------------------
/**
* Returns an array of Entry objects for the given search criteria. The search criteria array is constructed as follows:
*
* Filter by status
* $search_criteria['status'] = 'active';
*
* Filter by date range
* $search_criteria['start_date'] = $start_date;
* $search_criteria['end_date'] = $end_date;
*
* Filter by any column in the main table
* $search_criteria['field_filters'][] = array("key" => 'currency', value => 'USD');
* $search_criteria['field_filters'][] = array("key" => 'is_read', value => true);
*
* Filter by Field Values
* $search_criteria['field_filters'][] = array('key' => '1', 'value' => 'gquiz159982170');
*
* Filter Operators
* Supported operators for scalar values: is/=, isnot/<>, contains
* $search_criteria['field_filters'][] = array('key' => '1', 'operator' => 'contains', value' => 'Steve');
* Supported operators for array values: in/=, not in/<>/!=
* $search_criteria['field_filters'][] = array('key' => '1', 'operator' => 'not in', value' => array( 'Alex', 'David', 'Dana' );
*
* Filter by a checkbox value (not recommended)
* $search_criteria['field_filters'][] = array('key' => '2.2', 'value' => 'gquiz246fec995');
* note: this will work for checkboxes but it won't work if the checkboxes have been re-ordered - best to use the following examples below
*
* Filter by a checkbox value (recommended)
* $search_criteria['field_filters'][] = array('key' => '2', 'value' => 'gquiz246fec995');
* $search_criteria['field_filters'][] = array('key' => '2', 'operator' => 'not in', value' => array( 'First Choice', 'Third Choice' );
*
* Filter by a global search of values of any form field
* $search_criteria['field_filters'][] = array('value' => $search_value);
* OR
* $search_criteria['field_filters'][] = array('key' => 0, 'value' => $search_value);
*
* Filter entries by Entry meta (added using the gform_entry_meta hook)
* $search_criteria['field_filters'][] = array('key' => 'gquiz_score', 'value' => '1');
* $search_criteria['field_filters'][] = array('key' => 'gquiz_is_pass', 'value' => '1');
*
* Filter by ALL / ANY of the field filters
* $search_criteria['field_filters']['mode'] = 'all'; // default
* $search_criteria['field_filters']['mode'] = 'any';
*
* Sorting: column, field or entry meta
* $sorting = array('key' => $sort_field, 'direction' => 'ASC' );
*
* Paging
* $paging = array('offset' => 0, 'page_size' => 20 );
*
*
*
* @since 1.8
* @access public
* @static
*
* @param int|array $form_ids The ID of the form or an array IDs of the Forms. Zero for all forms.
* @param array $search_criteria Optional. An array containing the search criteria
* @param array $sorting Optional. An array containing the sorting criteria
* @param array $paging Optional. An array containing the paging criteria
* @param int $total_count Optional. An output parameter containing the total number of entries. Pass a non-null value to get the total count.
*
* @return mixed Either an array of the Entry objects or a WP_Error instance
*/
public static function get_entries( $form_ids, $search_criteria = array(), $sorting = null, $paging = null, &$total_count = null ) {
if ( empty( $sorting ) ) {
$sorting = array( 'key' => 'id', 'direction' => 'DESC', 'is_numeric' => true );
}
$entries = GFFormsModel::search_leads( $form_ids, $search_criteria, $sorting, $paging );
if ( ! is_null( $total_count ) ) {
$total_count = self::count_entries( $form_ids, $search_criteria );
}
return $entries;
}
/**
* Returns the total number of entries for the given search criteria. See get_entries() for examples of the search criteria.
*
* @since 1.8
* @access public
* @static
*
* @param int|array $form_ids The ID of the Form or an array of Form IDs
* @param array $search_criteria Optional. An array containing the search criteria
*
* @return int The total count
*/
public static function count_entries( $form_ids, $search_criteria = array() ) {
return GFFormsModel::count_search_leads( $form_ids, $search_criteria );
}
/**
* Returns the Entry object for a given Entry ID
*
* @since 1.8
* @access public
* @static
*
* @param int $entry_id The ID of the Entry
*
* @return mixed The Entry object or a WP_Error instance
*/
public static function get_entry( $entry_id ) {
$search_criteria['field_filters'][] = array( 'key' => 'id', 'value' => $entry_id );
$paging = array( 'offset' => 0, 'page_size' => 1 );
$entries = self::get_entries( 0, $search_criteria, null, $paging );
if ( empty( $entries ) ) {
return new WP_Error( 'not_found', sprintf( __( 'Entry with id %s not found', 'gravityforms' ), $entry_id ), $entry_id );
}
return $entries[0];
}
/**
* Adds multiple Entry objects.
*
* @since 1.8
* @access public
* @static
*
* @param array $entries The Entry objects
* @param int $form_id Optional. If specified, the form_id in the Entry objects will be ignored
*
* @return mixed Either an array of new Entry IDs or a WP_Error instance
*/
public static function add_entries( $entries, $form_id = null ) {
$entry_ids = array();
foreach ( $entries as $entry ) {
if ( $form_id ) {
$entry['form_id'] = $form_id;
}
$result = self::add_entry( $entry );
if ( is_wp_error( $result ) ) {
return $result;
}
$entry_ids[] = $result;
}
return $entry_ids;
}
/**
* Updates multiple Entry objects.
*
* @since 1.8
* @access public
* @static
*
* @param array $entries The Entry objects
*
* @return mixed Either True for success, or a WP_Error instance
*/
public static function update_entries( $entries ) {
foreach ( $entries as $entry ) {
$result = self::update_entry( $entry, $entry['id'] );
if ( is_wp_error( $result ) ) {
return $result;
}
}
return true;
}
/**
* Updates a single Entry object.
*
* @since 1.8
* @access public
* @static
*
* @param array $entry The Entry object
* @param int $entry_id Optional. If specified, the ID in the Entry object will be ignored
*
* @return mixed Either True or a WP_Error instance
*/
public static function update_entry( $entry, $entry_id = null ) {
global $wpdb;
if ( empty( $entry_id ) ) {
$entry_id = absint( $entry['id'] );
} else {
$entry['id'] = absint( $entry_id );
}
if ( empty( $entry_id ) ) {
return new WP_Error( 'missing_entry_id', __( 'Missing entry id', 'gravityforms' ) );
}
$current_entry = $original_entry = self::get_entry( $entry_id );
if ( ! $current_entry ) {
return new WP_Error( 'not_found', __( 'Entry not found', 'gravityforms' ), $entry_id );
}
if ( is_wp_error( $current_entry ) ) {
return $current_entry;
}
// make sure the form id exists
$form_id = rgar( $entry, 'form_id' );
if ( empty( $form_id ) ) {
$form_id = rgar( $current_entry, 'form_id' );
}
if ( false === self::form_id_exists( $form_id ) ) {
return new WP_Error( 'invalid_form_id', __( 'The form for this entry does not exist', 'gravityforms' ) );
}
$entry = apply_filters( 'gform_entry_pre_update', $entry, $original_entry );
// use values in the entry object if present
$post_id = isset( $entry['post_id'] ) ? intval( $entry['post_id'] ) : 'NULL';
$date_created = isset( $entry['date_created'] ) ? sprintf( "'%s'", esc_sql( $entry['date_created'] ) ) : 'utc_timestamp()';
$is_starred = isset( $entry['is_starred'] ) ? $entry['is_starred'] : 0;
$is_read = isset( $entry['is_read'] ) ? $entry['is_read'] : 0;
$ip = isset( $entry['ip'] ) ? $entry['ip'] : GFFormsModel::get_ip();
$source_url = isset( $entry['source_url'] ) ? $entry['source_url'] : GFFormsModel::get_current_page_url();
$user_agent = isset( $entry['user_agent'] ) ? $entry['user_agent'] : 'API';
$currency = isset( $entry['currency'] ) ? $entry['currency'] : GFCommon::get_currency();
$payment_status = isset( $entry['payment_status'] ) ? sprintf( "'%s'", esc_sql( $entry['payment_status'] ) ) : 'NULL';
$payment_date = strtotime( rgar( $entry, 'payment_date' ) ) ? "'" . gmdate( 'Y-m-d H:i:s', strtotime( "{$entry['payment_date']}" ) ) . "'" : 'NULL';
$payment_amount = isset( $entry['payment_amount'] ) ? (float) $entry['payment_amount'] : 'NULL';
$payment_method = isset( $entry['payment_method'] ) ? $entry['payment_method'] : '';
$transaction_id = isset( $entry['transaction_id'] ) ? sprintf( "'%s'", esc_sql( $entry['transaction_id'] ) ) : 'NULL';
$is_fulfilled = isset( $entry['is_fulfilled'] ) ? intval( $entry['is_fulfilled'] ) : 'NULL';
$status = isset( $entry['status'] ) ? $entry['status'] : 'active';
global $current_user;
$user_id = isset( $entry['created_by'] ) ? absint( $entry['created_by'] ) : '';
if ( empty( $user_id ) ) {
$user_id = $current_user && $current_user->ID ? absint( $current_user->ID ) : 'NULL';
}
$transaction_type = isset( $entry['transaction_type'] ) ? intval( $entry['transaction_type'] ) : 'NULL';
$lead_table = GFFormsModel::get_lead_table_name();
$result = $wpdb->query(
$wpdb->prepare(
"
UPDATE $lead_table
SET
form_id = %d,
post_id = {$post_id},
date_created = {$date_created},
is_starred = %d,
is_read = %d,
ip = %s,
source_url = %s,
user_agent = %s,
currency = %s,
payment_status = {$payment_status},
payment_date = {$payment_date},
payment_amount = {$payment_amount},
transaction_id = {$transaction_id},
is_fulfilled = {$is_fulfilled},
created_by = {$user_id},
transaction_type = {$transaction_type},
status = %s,
payment_method = %s
WHERE
id = %d
", $form_id, $is_starred, $is_read, $ip, $source_url, $user_agent, $currency, $status, $payment_method, $entry_id
)
);
if ( false === $result ) {
return new WP_Error( 'update_entry_properties_failed', __( 'There was a problem while updating the entry properties', 'gravityforms' ), $wpdb->last_error );
}
// only save field values for fields that currently exist in the form. The rest in $entry will be ignored. The rest in $current_entry will get deleted.
$lead_detail_table = GFFormsModel::get_lead_details_table_name();
$current_fields = $wpdb->get_results( $wpdb->prepare( "SELECT id, field_number FROM $lead_detail_table WHERE lead_id=%d", $entry_id ) );
$form = GFFormsModel::get_form_meta( $form_id );
$form = apply_filters( 'gform_form_pre_update_entry', $form, $entry, $entry_id );
$form = apply_filters( "gform_form_pre_update_entry_{$form_id}", $form, $entry, $entry_id );
foreach ( $form['fields'] as $field ) {
/* @var GF_Field $field */
$type = GFFormsModel::get_input_type( $field );
if ( in_array( $type, array( 'html', 'page', 'section' ) ) ) {
continue;
}
$inputs = $field->get_entry_inputs();
if ( is_array( $inputs ) ) {
foreach ( $field->inputs as $input ) {
$input_id = (string) $input['id'];
if ( isset( $entry[ $input_id ] ) ) {
if ( $entry[ $input_id ] != $current_entry[ $input_id ] ) {
$lead_detail_id = GFFormsModel::get_lead_detail_id( $current_fields, $input_id );
$result = GFFormsModel::update_lead_field_value( $form, $entry, $field, $lead_detail_id, $input_id, $entry[ $input_id ] );
if ( false === $result ) {
return new WP_Error( 'update_input_value_failed', __( 'There was a problem while updating one of the input values for the entry', 'gravityforms' ), $wpdb->last_error );
}
}
unset( $current_entry[ $input_id ] );
}
}
} else {
$field_id = $field->id;
$field_value = isset( $entry[ (string) $field_id ] ) ? $entry[ (string) $field_id ] : '';
if ( $field_value != $current_entry[ $field_id ] ) {
$lead_detail_id = GFFormsModel::get_lead_detail_id( $current_fields, $field_id );
$result = GFFormsModel::update_lead_field_value( $form, $entry, $field, $lead_detail_id, $field_id, $field_value );
if ( false === $result ) {
return new WP_Error( 'update_field_values_failed', __( 'There was a problem while updating the field values', 'gravityforms' ), $wpdb->last_error );
}
}
unset( $current_entry[ $field_id ] );
}
}
// save the entry meta values - only for the entry meta currently available for the form, ignore the rest
$entry_meta = GFFormsModel::get_entry_meta( $form_id );
if ( is_array( $entry_meta ) ) {
foreach ( array_keys( $entry_meta ) as $key ) {
if ( isset( $entry[ $key ] ) ) {
if ( $entry[ $key ] != $current_entry[ $key ] ) {
gform_update_meta( $entry_id, $key, $entry[ $key ] );
}
unset( $current_entry[ $key ] );
}
}
}
// now delete remaining values from the old entry
if ( is_array( $entry_meta ) ) {
foreach ( array_keys( $entry_meta ) as $meta_key ) {
if ( isset( $current_entry[ $meta_key ] ) ) {
gform_delete_meta( $entry_id, $meta_key );
unset( $current_entry[ $meta_key ] );
}
}
}
foreach ( $current_entry as $k => $v ) {
$lead_detail_id = GFFormsModel::get_lead_detail_id( $current_fields, $k );
$field = GFFormsModel::get_field( $form, $k );
$result = GFFormsModel::update_lead_field_value( $form, $entry, $field, $lead_detail_id, $k, '' );
if ( false === $result ) {
return new WP_Error( 'update_field_values_failed', __( 'There was a problem while updating the field values', 'gravityforms' ), $wpdb->last_error );
}
}
do_action( 'gform_post_update_entry', $entry, $original_entry );
return true;
}
/**
* Adds a single Entry object.
*
* Intended to be used for importing an entry object. The usual hooks that are triggered while saving entries are not fired here.
* Checks that the form id, field ids and entry meta exist and ignores legacy values (i.e. values for fields that no longer exist).
*
* @since 1.8
* @access public
* @static
*
* @param array $entry The Entry object
*
* @return mixed Either the new Entry ID or a WP_Error instance
*/
public static function add_entry( $entry ) {
global $wpdb;
if ( ! is_array( $entry ) ) {
return new WP_Error( 'invalid_entry_object', __( 'The entry object must be an array', 'gravityforms' ) );
}
// make sure the form id exists
$form_id = rgar( $entry, 'form_id' );
if ( empty( $form_id ) ) {
return new WP_Error( 'empty_form_id', __( 'The form id must be specified', 'gravityforms' ) );
}
if ( false === self::form_id_exists( $form_id ) ) {
return new WP_Error( 'invalid_form_id', __( 'The form for this entry does not exist', 'gravityforms' ) );
}
// use values in the entry object if present
$post_id = isset( $entry['post_id'] ) ? intval( $entry['post_id'] ) : 'NULL';
$date_created = isset( $entry['date_created'] ) && $entry['date_created'] != '' ? sprintf( "'%s'", esc_sql( $entry['date_created'] ) ) : 'utc_timestamp()';
$is_starred = isset( $entry['is_starred'] ) ? $entry['is_starred'] : 0;
$is_read = isset( $entry['is_read'] ) ? $entry['is_read'] : 0;
$ip = isset( $entry['ip'] ) ? $entry['ip'] : GFFormsModel::get_ip();
$source_url = isset( $entry['source_url'] ) ? $entry['source_url'] : GFFormsModel::get_current_page_url();
$user_agent = isset( $entry['user_agent'] ) ? $entry['user_agent'] : 'API';
$currency = isset( $entry['currency'] ) ? $entry['currency'] : GFCommon::get_currency();
$payment_status = isset( $entry['payment_status'] ) ? sprintf( "'%s'", esc_sql( $entry['payment_status'] ) ) : 'NULL';
$payment_date = strtotime( rgar( $entry, 'payment_date' ) ) ? sprintf( "'%s'", gmdate( 'Y-m-d H:i:s', strtotime( "{$entry['payment_date']}" ) ) ) : 'NULL';
$payment_amount = isset( $entry['payment_amount'] ) ? (float) $entry['payment_amount'] : 'NULL';
$payment_method = isset( $entry['payment_method'] ) ? $entry['payment_method'] : '';
$transaction_id = isset( $entry['transaction_id'] ) ? sprintf( "'%s'", esc_sql( $entry['transaction_id'] ) ) : 'NULL';
$is_fulfilled = isset( $entry['is_fulfilled'] ) ? intval( $entry['is_fulfilled'] ) : 'NULL';
$status = isset( $entry['status'] ) ? $entry['status'] : 'active';
global $current_user;
$user_id = isset( $entry['created_by'] ) ? absint( $entry['created_by'] ) : '';
if ( empty( $user_id ) ) {
$user_id = $current_user && $current_user->ID ? absint( $current_user->ID ) : 'NULL';
}
$transaction_type = isset( $entry['transaction_type'] ) ? intval( $entry['transaction_type'] ) : 'NULL';
$lead_table = GFFormsModel::get_lead_table_name();
$result = $wpdb->query(
$wpdb->prepare(
"
INSERT INTO $lead_table
(form_id, post_id, date_created, is_starred, is_read, ip, source_url, user_agent, currency, payment_status, payment_date, payment_amount, transaction_id, is_fulfilled, created_by, transaction_type, status, payment_method)
VALUES
(%d, {$post_id}, {$date_created}, %d, %d, %s, %s, %s, %s, {$payment_status}, {$payment_date}, {$payment_amount}, {$transaction_id}, {$is_fulfilled}, {$user_id}, {$transaction_type}, %s, %s)
", $form_id, $is_starred, $is_read, $ip, $source_url, $user_agent, $currency, $status, $payment_method
)
);
if ( false === $result ) {
return new WP_Error( 'insert_entry_properties_failed', __( 'There was a problem while inserting the entry properties', 'gravityforms' ), $wpdb->last_error );
}
// reading newly created lead id
$entry_id = $wpdb->insert_id;
$entry['id'] = $entry_id;
// only save field values for fields that currently exist in the form
$form = GFFormsModel::get_form_meta( $form_id );
foreach ( $form['fields'] as $field ) {
/* @var GF_Field $field */
if ( in_array( $field->type, array( 'html', 'page', 'section' ) ) ) {
continue;
}
$inputs = $field->get_entry_inputs();
if ( is_array( $inputs ) ) {
foreach ( $inputs as $input ) {
$input_id = (string) $input['id'];
if ( isset( $entry[ $input_id ] ) ) {
$result = GFFormsModel::update_lead_field_value( $form, $entry, $field, 0, $input_id, $entry[ $input_id ] );
if ( false === $result ) {
return new WP_Error( 'insert_input_value_failed', __( 'There was a problem while inserting one of the input values for the entry', 'gravityforms' ), $wpdb->last_error );
}
}
}
} else {
$field_id = $field->id;
$field_value = isset( $entry[ (string) $field_id ] ) ? $entry[ (string) $field_id ] : '';
$result = GFFormsModel::update_lead_field_value( $form, $entry, $field, 0, $field_id, $field_value );
if ( false === $result ) {
return new WP_Error( 'insert_field_values_failed', __( 'There was a problem while inserting the field values', 'gravityforms' ), $wpdb->last_error );
}
}
}
// add save the entry meta values - only for the entry meta currently available for the form, ignore the rest
$entry_meta = GFFormsModel::get_entry_meta( $form_id );
if ( is_array( $entry_meta ) ) {
foreach ( array_keys( $entry_meta ) as $key ) {
if ( isset( $entry[ $key ] ) ) {
gform_update_meta( $entry_id, $key, $entry[ $key ], $form['id'] );
}
}
}
return $entry_id;
}
/**
* Deletes a single Entry.
*
* @since 1.8
* @access public
* @static
*
* @param int $entry_id The ID of the Entry object
*
* @return mixed Either true for success or a WP_Error instance
*/
public static function delete_entry( $entry_id ) {
$entry = GFFormsModel::get_lead( $entry_id );
if ( empty( $entry ) ) {
return new WP_Error( 'invalid_entry_id', sprintf( __( 'Invalid entry id: %s', 'gravityforms' ), $entry_id ), $entry_id );
}
GFFormsModel::delete_lead( $entry_id );
return true;
}
/**
* Updates a single property of an entry.
*
* @since 1.8.3.1
* @access public
* @static
*
* @param int $entry_id The ID of the Entry object
* @param string $property The property of the Entry object to be updated
* @param mixed $value The value to which the property should be set
*
* @return bool Whether the entry property was updated successfully
*/
public static function update_entry_property( $entry_id, $property, $value ) {
return GFFormsModel::update_lead_property( $entry_id, $property, $value );
}
/**
* Updates a single field of an entry.
*
* @since 1.9
* @access public
* @static
*
* @param int $entry_id The ID of the Entry object
* @param string $input_id The id of the input to be updated. For single input fields such as text, paragraph, website, drop down etc... this will be the same as the field ID.
* For multi input fields such as name, address, checkboxes, etc... the input id will be in the format {FIELD_ID}.{INPUT NUMBER}. ( i.e. "1.3" )
* The $input_id can be obtained by inspecting the key for the specified field in the $entry object.
*
* @param mixed $value The value to which the field should be set
*
* @return bool Whether the entry property was updated successfully
*/
public static function update_entry_field( $entry_id, $input_id, $value ) {
global $wpdb;
$entry = self::get_entry( $entry_id );
if ( is_wp_error( $entry ) ) {
return $entry;
}
$form = self::get_form( $entry['form_id'] );
if ( ! $form ) {
return false;
}
$field = GFFormsModel::get_field( $form, $input_id );
$input_id_min = (float) $input_id - 0.0001;
$input_id_max = (float) $input_id + 0.0001;
$lead_details_table_name = GFFormsModel::get_lead_details_table_name();
$lead_detail_id = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$lead_details_table_name} WHERE lead_id=%d AND field_number BETWEEN %s AND %s", $entry_id, $input_id_min, $input_id_max ) );
$result = true;
if ( ! isset( $entry[ $input_id ] ) || $entry[ $input_id ] != $value ){
$result = GFFormsModel::update_lead_field_value( $form, $entry, $field, $lead_detail_id, $input_id, $value );
}
return $result;
}
// FORM SUBMISSIONS -------------------------------------------
/**
* Submits a form. Use this function to send input values through the complete form submission process.
* Supports field validation, notifications, confirmations, multiple-pages and save & continue.
*
* Example usage:
* $input_values['input_1'] = 'Single line text';
* $input_values['input_2_3'] = 'First name';
* $input_values['input_2_6'] = 'Last name';
* $input_values['input_5'] = 'A paragraph of text.';
* //$input_values['gform_save'] = true; // support for save and continue
*
* $result = GFAPI::submit_form( 52, $input_values );
*
* Example output for a successful submission:
* 'is_valid' => boolean true
* 'page_number' => int 0
* 'source_page_number' => int 1
* 'confirmation_message' => string 'confirmation message [snip]'
*
* Example output for failed validation:
* 'is_valid' => boolean false
* 'validation_messages' =>
* array (size=1)
* 2 => string 'This field is required. Please enter the first and last name.'
* 'page_number' => int 1
* 'source_page_number' => int 1
* 'confirmation_message' => string ''
*
*
* Example output for save and continue:
* 'is_valid' => boolean true
* 'page_number' => int 1
* 'source_page_number' => int 1
* 'confirmation_message' => string 'Please use the following link to return to your form from any computer. [snip]'
* 'resume_token' => string '045f941cc4c04d479556bab1db6d3495'
*
*
* @param int $form_id The Form ID
* @param array $input_values An array of values.
* @param array $field_values Optional.
* @param int $target_page Optional.
* @param int $source_page Optional.
*
* @return array An array containing the result of the submission.
*/
public static function submit_form( $form_id, $input_values, $field_values = array(), $target_page = 0, $source_page = 1 ) {
$form_id = absint( $form_id );
$form = GFAPI::get_form( $form_id );
if ( empty( $form ) || ! $form['is_active'] || $form['is_trash'] ) {
return new WP_Error( 'form_not_found', __( 'Your form could not be found', 'gravityforms' ) );
}
$input_values[ 'is_submit_' . $form_id ] = true;
$input_values['gform_submit'] = $form_id;
$input_values[ 'gform_target_page_number_' . $form_id ] = absint( $target_page );
$input_values[ 'gform_source_page_number_' . $form_id ] = absint( $source_page );
$input_values['gform_field_values'] = $field_values;
require_once(GFCommon::get_base_path() . '/form_display.php');
if ( ! isset( $_POST ) ) {
$_POST = array();
}
$_POST = array_merge_recursive( $_POST, $input_values );
try {
GFFormDisplay::process_form( $form_id );
} catch ( Exception $ex ) {
return new WP_Error( 'error_processing_form', __( 'There was an error while processing the form:', 'gravityforms' ) . ' ' . $ex->getCode() . ' ' . $ex->getMessage() );
}
if ( empty( GFFormDisplay::$submission ) ) {
return new WP_Error( 'error_processing_form', __( 'There was an error while processing the form:', 'gravityforms' ) );
}
$submissions_array = GFFormDisplay::$submission;
$submission_details = $submissions_array[ $form_id ];
$result = array();
$result['is_valid'] = $submission_details['is_valid'];
if ( $result['is_valid'] == false ) {
$validation_messages = array();
foreach ( $submission_details['form']['fields'] as $field ) {
if ( $field->failed_validation ) {
$validation_messages[ $field->id ] = $field->validation_message;
}
}
$result['validation_messages'] = $validation_messages;
}
$result['page_number'] = $submission_details['page_number'];
$result['source_page_number'] = $submission_details['source_page_number'];
$result['confirmation_message'] = $submission_details['confirmation_message'];
if ( isset( $submission_details['resume_token'] ) ) {
$result['resume_token'] = $submission_details['resume_token'];
$form = self::get_form( $form_id );
$result['confirmation_message'] = GFFormDisplay::replace_save_variables( $result['confirmation_message'], $form, $result['resume_token'] );
}
return $result;
}
// FEEDS ------------------------------------------------------
/**
* Returns all the feeds for the given criteria.
*
* @since 1.8
* @access public
* @static
*
* @param mixed $feed_ids The ID of the Feed or an array of Feed IDs
* @param int $form_id The ID of the Form to which the Feeds belong
* @param string $addon_slug The slug of the add-on to which the Feeds belong
* @param bool $is_active
*
* @return mixed Either an array of Feed objects or a WP_Error instance
*/
public static function get_feeds( $feed_ids = null, $form_id = null, $addon_slug = null, $is_active = true ) {
global $wpdb;
$table = $wpdb->prefix . 'gf_addon_feed';
$where_arr = array();
$where_arr[] = $wpdb->prepare( 'is_active=%d', $is_active );
if ( false === empty( $form_id ) ) {
$where_arr[] = $wpdb->prepare( 'form_id=%d', $form_id );
}
if ( false === empty( $addon_slug ) ) {
$where_arr[] = $wpdb->prepare( 'addon_slug=%s', $addon_slug );
}
if ( false === empty( $feed_ids ) ) {
if ( ! is_array( $feed_ids ) ) {
$feed_ids = array( $feed_ids );
}
$in_str_arr = array_fill( 0, count( $feed_ids ), '%d' );
$in_str = join( $in_str_arr, ',' );
$where_arr[] = $wpdb->prepare( "id IN ($in_str)", $feed_ids );
}
$where = join( ' AND ', $where_arr );
$sql = "SELECT id, form_id, addon_slug, meta FROM {$table} WHERE $where";
$results = $wpdb->get_results( $sql, ARRAY_A );
if ( empty( $results ) ) {
return new WP_Error( 'not_found', __( 'Feed not found', 'gravityforms' ) );
}
foreach ( $results as &$result ) {
$result['meta'] = json_decode( $result['meta'], true );
}
return $results;
}
/**
* Deletes a single Feed
*
* @since 1.8
* @access public
* @static
*
* @param int $feed_id The ID of the Feed to delete
*
* @return mixed Either an array of Feed objects or a WP_Error instance
*/
public static function delete_feed( $feed_id ) {
global $wpdb;
$table = $wpdb->prefix . 'gf_addon_feed';
$sql = $wpdb->prepare( "DELETE FROM {$table} WHERE id=%d", $feed_id );
$results = $wpdb->query( $sql );
if ( false === $results ) {
return new WP_Error( 'error_deleting', sprintf( __( 'There was an an error while deleting feed id %s', 'gravityforms' ), $feed_id ), $wpdb->last_error );
}
if ( 0 === $results ) {
return new WP_Error( 'not_found', sprintf( __( 'Feed id %s not found', 'gravityforms' ), $feed_id ) );
}
return true;
}
public static function update_feed( $feed_id, $feed_meta, $form_id = null ) {
global $wpdb;
$feed_meta_json = json_encode( $feed_meta );
$table = $wpdb->prefix . 'gf_addon_feed';
if ( empty( $form_id ) ) {
$sql = $wpdb->prepare( "UPDATE {$table} SET meta= %s WHERE id=%d", $feed_meta_json, $feed_id );
} else {
$sql = $wpdb->prepare( "UPDATE {$table} SET form_id = %d, meta= %s WHERE id=%d", $form_id, $feed_meta_json, $feed_id );
}
$results = $wpdb->query( $sql );
if ( false === $results ) {
return new WP_Error( 'error_updating', sprintf( __( 'There was an an error while updating feed id %s', 'gravityforms' ), $feed_id ), $wpdb->last_error );
}
if ( 0 === $results ) {
return new WP_Error( 'not_found', sprintf( __( 'Feed id %s not found', 'gravityforms' ), $feed_id ) );
}
return $results;
}
/**
* Adds a feed with the given Feed object.
*
* @since 1.8
* @access public
* @static
*
* @param int $form_id The ID of the Form to which the Feed belongs
* @param array $feed_meta The Feed object
* @param string $addon_slug The slug of the add-on to which the Feeds belong
*
* @return mixed Either the ID of the newly created Feed or a WP_Error instance
*/
public static function add_feed( $form_id, $feed_meta, $addon_slug ) {
global $wpdb;
$table = $wpdb->prefix . 'gf_addon_feed';
$feed_meta_json = json_encode( $feed_meta );
$sql = $wpdb->prepare( "INSERT INTO {$table} (form_id, meta, addon_slug) VALUES (%d, %s, %s)", $form_id, $feed_meta_json, $addon_slug );
$results = $wpdb->query( $sql );
if ( false === $results ) {
return new WP_Error( 'error_inserting', __( 'There was an an error while inserting a feed', 'gravityforms' ), $wpdb->last_error );
}
return $wpdb->insert_id;
}
// NOTIFICATIONS ----------------------------------------------
/**
* Sends all active notifications for a form given an entry object and an event.
*
* @param $form
* @param $entry
* @param string $event Default = 'form_submission'
*
* @return array
*/
public static function send_notifications( $form, $entry, $event = 'form_submission' ) {
if ( rgempty( 'notifications', $form ) || ! is_array( $form['notifications'] ) ) {
return array();
}
$entry_id = rgar( $entry, 'id' );
GFCommon::log_debug( "GFAPI::send_notifications(): Gathering notifications for {$event} event for entry #{$entry_id}." );
$notifications_to_send = array();
//running through filters that disable form submission notifications
foreach ( $form['notifications'] as $notification ) {
if ( rgar( $notification, 'event' ) != $event ) {
continue;
}
if ( $event == 'form_submission' ) {
if ( rgar( $notification, 'type' ) == 'user' && apply_filters( "gform_disable_user_notification_{$form['id']}", apply_filters( 'gform_disable_user_notification', false, $form, $entry ), $form, $entry ) ) {
GFCommon::log_debug( "GFAPI::send_notifications(): Notification is disabled by gform_disable_user_notification hook, not including notification (#{$notification['id']} - {$notification['name']})." );
//skip user notification if it has been disabled by a hook
continue;
} elseif ( rgar( $notification, 'type' ) == 'admin' && apply_filters( "gform_disable_admin_notification_{$form['id']}", apply_filters( 'gform_disable_admin_notification', false, $form, $entry ), $form, $entry ) ) {
GFCommon::log_debug( "GFAPI::send_notifications(): Notification is disabled by gform_disable_admin_notification hook, not including notification (#{$notification['id']} - {$notification['name']})." );
//skip admin notification if it has been disabled by a hook
continue;
}
}
if ( apply_filters( "gform_disable_notification_{$form['id']}", apply_filters( 'gform_disable_notification', false, $notification, $form, $entry ), $notification, $form, $entry ) ) {
GFCommon::log_debug( "GFAPI::send_notifications(): Notification is disabled by gform_disable_notification hook, not including notification (#{$notification['id']} - {$notification['name']})." );
//skip notifications if it has been disabled by a hook
continue;
}
$notifications_to_send[] = $notification['id'];
}
GFCommon::send_notifications( $notifications_to_send, $form, $entry, true, $event );
}
// PERMISSIONS ------------------------------------------------
/**
* Checks the permissions for the current user. Returns true if the current user has any of the specified capabilities.
* IMPORTANT: Call this before calling any of the other API Functions as permission checks are not performed at lower levels.
*
* @since 1.8.5.10
* @access public
* @static
*
* @param array|string $capabilities An array of capabilities, or a single capability
*
* @return bool Returns true if the current user has any of the specified capabilities
*/
public static function current_user_can_any( $capabilities ) {
return GFCommon::current_user_can_any( $capabilities );
}
// FIELDS -----------------------------------------------------
/**
* Returns an array containing the form fields of the specified type or types.
*
* @since 1.9.9.8
*
* @param array $form
* @param array|string $types
* @param bool $use_input_type
*
* @return GF_Field[]
*/
public static function get_fields_by_type( $form, $types, $use_input_type = false ) {
return GFFormsModel::get_fields_by_type( $form, $types, $use_input_type );
}
// HELPERS ----------------------------------------------------
/**
* Private.
*
* @since 1.8
* @access private
* @static
* @ignore
*/
public static function form_id_exists( $form_id ) {
global $wpdb;
$form_table_name = GFFormsModel::get_form_table_name();
$form_id = intval( $form_id );
$result = $wpdb->get_var(
$wpdb->prepare(
" SELECT count(id) FROM {$form_table_name}
WHERE id=%d", $form_id
)
);
$result = intval( $result );
return $result > 0;
}
}
| gpl-2.0 |
emakis/erpnext | erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.js | 5857 | // Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
frappe.provide("erpnext.stock");
frappe.ui.form.on("Stock Reconciliation", {
onload: function(frm) {
frm.add_fetch("item_code", "item_name", "item_name");
// end of life
frm.set_query("item_code", "items", function(doc, cdt, cdn) {
return {
query: "erpnext.controllers.queries.item_query",
filters:{
"is_stock_item": 1,
"has_serial_no": 0
}
}
});
if (frm.doc.company) {
erpnext.queries.setup_queries(frm, "Warehouse", function() {
return erpnext.queries.warehouse(frm.doc);
});
}
},
refresh: function(frm) {
if(frm.doc.docstatus < 1) {
frm.add_custom_button(__("Items"), function() {
frm.events.get_items(frm);
});
}
if(frm.doc.company) {
frm.trigger("toggle_display_account_head");
}
},
get_items: function(frm) {
frappe.prompt({label:"Warehouse", fieldtype:"Link", options:"Warehouse", reqd: 1},
function(data) {
frappe.call({
method:"erpnext.stock.doctype.stock_reconciliation.stock_reconciliation.get_items",
args: {
warehouse: data.warehouse,
posting_date: frm.doc.posting_date,
posting_time: frm.doc.posting_time
},
callback: function(r) {
var items = [];
frm.clear_table("items");
for(var i=0; i< r.message.length; i++) {
var d = frm.add_child("items");
$.extend(d, r.message[i]);
if(!d.qty) d.qty = null;
if(!d.valuation_rate) d.valuation_rate = null;
}
frm.refresh_field("items");
}
});
}
, __("Get Items"), __("Update"));
},
set_valuation_rate_and_qty: function(frm, cdt, cdn) {
var d = frappe.model.get_doc(cdt, cdn);
if(d.item_code && d.warehouse) {
frappe.call({
method: "erpnext.stock.doctype.stock_reconciliation.stock_reconciliation.get_stock_balance_for",
args: {
item_code: d.item_code,
warehouse: d.warehouse,
posting_date: frm.doc.posting_date,
posting_time: frm.doc.posting_time
},
callback: function(r) {
frappe.model.set_value(cdt, cdn, "qty", r.message.qty);
frappe.model.set_value(cdt, cdn, "valuation_rate", r.message.rate);
frappe.model.set_value(cdt, cdn, "current_qty", r.message.qty);
frappe.model.set_value(cdt, cdn, "current_valuation_rate", r.message.rate);
frappe.model.set_value(cdt, cdn, "current_amount", r.message.rate * r.message.qty);
frappe.model.set_value(cdt, cdn, "amount", r.message.rate * r.message.qty);
}
});
}
},
set_item_code: function(doc, cdt, cdn) {
var d = frappe.model.get_doc(cdt, cdn);
if (d.barcode) {
frappe.call({
method: "erpnext.stock.get_item_details.get_item_code",
args: {"barcode": d.barcode },
callback: function(r) {
if (!r.exe){
frappe.model.set_value(cdt, cdn, "item_code", r.message);
}
}
});
}
},
set_amount_quantity: function(doc, cdt, cdn) {
var d = frappe.model.get_doc(cdt, cdn);
if (d.qty & d.valuation_rate) {
frappe.model.set_value(cdt, cdn, "amount", flt(d.qty) * flt(d.valuation_rate));
frappe.model.set_value(cdt, cdn, "quantity_difference", flt(d.qty) - flt(d.current_qty));
frappe.model.set_value(cdt, cdn, "amount_difference", flt(d.amount) - flt(d.current_amount));
}
},
company: function(frm) {
frm.trigger("toggle_display_account_head");
},
toggle_display_account_head: function(frm) {
frm.toggle_display(['expense_account', 'cost_center'],
erpnext.is_perpetual_inventory_enabled(frm.doc.company));
}
});
frappe.ui.form.on("Stock Reconciliation Item", {
barcode: function(frm, cdt, cdn) {
frm.events.set_item_code(frm, cdt, cdn);
},
warehouse: function(frm, cdt, cdn) {
frm.events.set_valuation_rate_and_qty(frm, cdt, cdn);
},
item_code: function(frm, cdt, cdn) {
frm.events.set_valuation_rate_and_qty(frm, cdt, cdn);
},
qty: function(frm, cdt, cdn) {
frm.events.set_amount_quantity(frm, cdt, cdn);
},
valuation_rate: function(frm, cdt, cdn) {
frm.events.set_amount_quantity(frm, cdt, cdn);
}
});
erpnext.stock.StockReconciliation = erpnext.stock.StockController.extend({
onload: function() {
this.set_default_expense_account();
},
set_default_expense_account: function() {
var me = this;
if(this.frm.doc.company) {
if (erpnext.is_perpetual_inventory_enabled(this.frm.doc.company) && !this.frm.doc.expense_account) {
return this.frm.call({
method: "erpnext.accounts.utils.get_company_default",
args: {
"fieldname": "stock_adjustment_account",
"company": this.frm.doc.company
},
callback: function(r) {
if (!r.exc) {
me.frm.set_value("expense_account", r.message);
}
}
});
}
}
},
setup: function() {
var me = this;
this.setup_posting_date_time_check();
if (me.frm.doc.company && erpnext.is_perpetual_inventory_enabled(me.frm.doc.company)) {
this.frm.add_fetch("company", "stock_adjustment_account", "expense_account");
this.frm.add_fetch("company", "cost_center", "cost_center");
}
this.frm.fields_dict["expense_account"].get_query = function() {
if(erpnext.is_perpetual_inventory_enabled(me.frm.doc.company)) {
return {
"filters": {
'company': me.frm.doc.company,
"is_group": 0
}
}
}
}
this.frm.fields_dict["cost_center"].get_query = function() {
if(erpnext.is_perpetual_inventory_enabled(me.frm.doc.company)) {
return {
"filters": {
'company': me.frm.doc.company,
"is_group": 0
}
}
}
}
},
refresh: function() {
if(this.frm.doc.docstatus==1) {
this.show_stock_ledger();
if (erpnext.is_perpetual_inventory_enabled(this.frm.doc.company)) {
this.show_general_ledger();
}
}
},
});
cur_frm.cscript = new erpnext.stock.StockReconciliation({frm: cur_frm});
| gpl-3.0 |
kuali/kc-rice | rice-middleware/it/kew/src/test/java/org/kuali/rice/kew/routemodule/TestRouteModule.java | 5545 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.kew.routemodule;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.kuali.rice.kew.actionrequest.ActionRequestFactory;
import org.kuali.rice.kew.actionrequest.ActionRequestValue;
import org.kuali.rice.kew.actionrequest.KimGroupRecipient;
import org.kuali.rice.kew.actionrequest.KimPrincipalRecipient;
import org.kuali.rice.kew.actionrequest.Recipient;
import org.kuali.rice.kew.api.action.RecipientType;
import org.kuali.rice.kew.api.exception.ResourceUnavailableException;
import org.kuali.rice.kew.api.exception.WorkflowException;
import org.kuali.rice.kew.engine.RouteContext;
import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.kew.util.ResponsibleParty;
/**
* @author Kuali Rice Team ([email protected])
*/
public class TestRouteModule implements RouteModule {
private static Map responsibilityMap = new HashMap();
public List findActionRequests(RouteContext context) throws ResourceUnavailableException, WorkflowException {
return findActionRequests(context.getDocument());
}
public List findActionRequests(DocumentRouteHeaderValue routeHeader) throws ResourceUnavailableException, WorkflowException {
TestRouteLevel routeLevel = TestRouteModuleXMLHelper.parseCurrentRouteLevel(routeHeader);
List actionRequests = new ArrayList();
if (routeLevel == null) {
return actionRequests;
}
for (Iterator iterator = routeLevel.getResponsibilities().iterator(); iterator.hasNext();) {
TestResponsibility responsibility = (TestResponsibility) iterator.next();
TestRecipient recipient = responsibility.getRecipient();
Recipient realRecipient = getRealRecipient(recipient);
ActionRequestFactory arFactory = new ActionRequestFactory(routeHeader);
String responsibilityId = KEWServiceLocator.getResponsibilityIdService().getNewResponsibilityId();
ActionRequestValue request = arFactory.addRootActionRequest(responsibility.getActionRequested(), new Integer(responsibility.getPriority()), realRecipient, "", responsibilityId, Boolean.FALSE, null, null);
responsibilityMap.put(request.getResponsibilityId(), recipient);
for (Iterator delIt = responsibility.getDelegations().iterator(); delIt.hasNext();) {
TestDelegation delegation = (TestDelegation) delIt.next();
TestRecipient delegationRecipient = delegation.getResponsibility().getRecipient();
Recipient realDelegationRecipient = getRealRecipient(delegationRecipient);
responsibilityId = KEWServiceLocator.getResponsibilityIdService().getNewResponsibilityId();
ActionRequestValue delegationRequest = arFactory.addDelegationRequest(request, realDelegationRecipient, responsibilityId, Boolean.FALSE, delegation.getType(), "", null);
responsibilityMap.put(delegationRequest.getResponsibilityId(), delegationRecipient);
}
actionRequests.add(request);
}
return actionRequests;
}
public Recipient getRealRecipient(TestRecipient recipient) throws WorkflowException {
Recipient realRecipient = null;
if (recipient.getType().equals(RecipientType.PRINCIPAL.getCode())) {
realRecipient = new KimPrincipalRecipient(recipient.getId());
} else if (recipient.getType().equals(RecipientType.GROUP.getCode())) {
realRecipient = new KimGroupRecipient(recipient.getId());
} else {
throw new WorkflowException("Could not resolve recipient with type " + recipient.getType());
}
return realRecipient;
}
public ResponsibleParty resolveResponsibilityId(String responsibilityId) throws ResourceUnavailableException, WorkflowException {
TestRecipient recipient = (TestRecipient)responsibilityMap.get(responsibilityId);
if (recipient == null) {
return null;
}
ResponsibleParty responsibleParty = new ResponsibleParty();
if (recipient.getType().equals(RecipientType.PRINCIPAL.getCode())) {
responsibleParty.setPrincipalId(recipient.getId());
} else if (recipient.getType().equals(RecipientType.GROUP.getCode())) {
responsibleParty.setGroupId(recipient.getId());
} else if (recipient.getType().equals(RecipientType.ROLE.getCode())) {
responsibleParty.setRoleName(recipient.getId());
} else {
throw new WorkflowException("Invalid recipient type code of '"+recipient.getType()+"' for responsibility id "+responsibilityId);
}
return responsibleParty;
}
@Override
public boolean isMoreRequestsAvailable(RouteContext context) {
return false;
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.