answer
stringlengths
15
1.25M
//!if outputMode == ECMAScript51Global var ScalaJS = {}; //!endif // Get the environment info ScalaJS.env = (typeof __ScalaJSEnv === "object" && __ScalaJSEnv) ? __ScalaJSEnv : {}; // Global scope ScalaJS.g = (typeof ScalaJS.env["global"] === "object" && ScalaJS.env["global"]) ? ScalaJS.env["global"] : ((typeof global === "object" && global && global["Object"] === Object) ? global : this); ScalaJS.env["global"] = ScalaJS.g; // Where to send exports //!if moduleKind == CommonJSModule ScalaJS.e = exports; //!else ScalaJS.e = (typeof ScalaJS.env["exportsNamespace"] === "object" && ScalaJS.env["exportsNamespace"]) ? ScalaJS.env["exportsNamespace"] : ScalaJS.g; //!endif ScalaJS.env["exportsNamespace"] = ScalaJS.e; // Freeze the environment info ScalaJS.g["Object"]["freeze"](ScalaJS.env); // Linking info - must be in sync with scala.scalajs.runtime.LinkingInfo ScalaJS.linkingInfo = { "envInfo": ScalaJS.env, "semantics": { //!if asInstanceOfs == Compliant "asInstanceOfs": 0, //!else //!if asInstanceOfs == Fatal "asInstanceOfs": 1, //!else "asInstanceOfs": 2, //!endif //!endif //!if <API key> == Compliant "<API key>": 0, //!else //!if <API key> == Fatal "<API key>": 1, //!else "<API key>": 2, //!endif //!endif //!if moduleInit == Compliant "moduleInit": 0, //!else //!if moduleInit == Fatal "moduleInit": 1, //!else "moduleInit": 2, //!endif //!endif //!if floats == Strict "strictFloats": true, //!else "strictFloats": false, //!endif //!if productionMode == true "productionMode": true //!else "productionMode": false //!endif }, //!if outputMode == ECMAScript6 "assumingES6": true, //!else "assumingES6": false, //!endif "linkerVersion": "{{LINKER_VERSION}}" }; ScalaJS.g["Object"]["freeze"](ScalaJS.linkingInfo); ScalaJS.g["Object"]["freeze"](ScalaJS.linkingInfo["semantics"]); // Snapshots of builtins and polyfills //!if outputMode == ECMAScript6 ScalaJS.imul = ScalaJS.g["Math"]["imul"]; ScalaJS.fround = ScalaJS.g["Math"]["fround"]; ScalaJS.clz32 = ScalaJS.g["Math"]["clz32"]; //!else ScalaJS.imul = ScalaJS.g["Math"]["imul"] || (function(a, b) { const ah = (a >>> 16) & 0xffff; const al = a & 0xffff; const bh = (b >>> 16) & 0xffff; const bl = b & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0); }); ScalaJS.fround = ScalaJS.g["Math"]["fround"] || //!if floats == Strict (ScalaJS.g["Float32Array"] ? (function(v) { const array = new ScalaJS.g["Float32Array"](1); array[0] = v; return array[0]; }) : (function(v) { return ScalaJS.m.sjsr_package$().<API key>(+v); })); //!else (function(v) { return +v; }); //!endif ScalaJS.clz32 = ScalaJS.g["Math"]["clz32"] || (function(i) { // See Hacker's Delight, Section 5-3 if (i === 0) return 32; let r = 1; if ((i & 0xffff0000) === 0) { i <<= 16; r += 16; }; if ((i & 0xff000000) === 0) { i <<= 8; r += 8; }; if ((i & 0xf0000000) === 0) { i <<= 4; r += 4; }; if ((i & 0xc0000000) === 0) { i <<= 2; r += 2; }; return r + (i >> 31); }); //!endif // Other fields //!if outputMode == ECMAScript51Global ScalaJS.d = {}; // Data for types ScalaJS.a = {}; // Scala.js-defined JS class value accessors ScalaJS.b = {}; // Scala.js-defined JS class value fields ScalaJS.c = {}; // Scala.js constructors ScalaJS.h = {}; // Inheritable constructors (without initialization code) ScalaJS.s = {}; // Static methods ScalaJS.t = {}; // Static fields ScalaJS.f = {}; // Default methods ScalaJS.n = {}; // Module instances ScalaJS.m = {}; // Module accessors ScalaJS.is = {}; // isInstanceOf methods ScalaJS.isArrayOf = {}; // isInstanceOfArrayOf methods //!if asInstanceOfs != Unchecked ScalaJS.as = {}; // asInstanceOf methods ScalaJS.asArrayOf = {}; // asInstanceOfArrayOf methods //!endif ScalaJS.lastIDHash = 0; // last value attributed to an id hash code ScalaJS.idHashCodeMap = ScalaJS.g["WeakMap"] ? new ScalaJS.g["WeakMap"]() : null; //!else let $lastIDHash = 0; // last value attributed to an id hash code //!if outputMode == ECMAScript6 const $idHashCodeMap = new ScalaJS.g["WeakMap"](); //!else const $idHashCodeMap = ScalaJS.g["WeakMap"] ? new ScalaJS.g["WeakMap"]() : null; //!endif //!endif // Core mechanism ScalaJS.<API key> = function(primitiveData) { return function(obj, depth) { return !!(obj && obj.$classData && (obj.$classData.arrayDepth === depth) && (obj.$classData.arrayBase === primitiveData)); } }; //!if asInstanceOfs != Unchecked ScalaJS.<API key> = function(<API key>, arrayEncodedName) { return function(obj, depth) { if (<API key>(obj, depth) || (obj === null)) return obj; else ScalaJS.<API key>(obj, arrayEncodedName, depth); } }; //!endif /** Encode a property name for runtime manipulation * Usage: * env.propertyName({someProp:0}) * Returns: * "someProp" * Useful when the property is renamed by a global optimizer (like Closure) * but we must still get hold of a string of that name for runtime * reflection. */ ScalaJS.propertyName = function(obj) { for (const prop in obj) return prop; }; // Runtime functions ScalaJS.isScalaJSObject = function(obj) { return !!(obj && obj.$classData); }; //!if asInstanceOfs != Unchecked ScalaJS.<API key> = function(instance, classFullName) { //!if asInstanceOfs == Compliant throw new ScalaJS.c.<API key>().init___T( instance + " is not an instance of " + classFullName); //!else throw new ScalaJS.c.<API key>().init___jl_Throwable( new ScalaJS.c.<API key>().init___T( instance + " is not an instance of " + classFullName)); //!endif }; ScalaJS.<API key> = function(instance, <API key>, depth) { for (; depth; --depth) <API key> = "[" + <API key>; ScalaJS.<API key>(instance, <API key>); }; //!endif //!if <API key> != Unchecked ScalaJS.<API key> = function(i) { const msg = (i === null) ? null : ("" + i); //!if <API key> == Compliant throw new ScalaJS.c.<API key>().init___T(msg); //!else throw new ScalaJS.c.<API key>().init___jl_Throwable( new ScalaJS.c.<API key>().init___T(msg)); //!endif }; //!endif ScalaJS.noIsInstance = function(instance) { throw new ScalaJS.g["TypeError"]( "Cannot call isInstance() on a Class representing a raw JS trait/object"); }; ScalaJS.<API key> = function(arrayClassData, nativeArray) { return new arrayClassData.constr(nativeArray); }; ScalaJS.newArrayObject = function(arrayClassData, lengths) { return ScalaJS.<API key>(arrayClassData, lengths, 0); }; ScalaJS.<API key> = function(arrayClassData, lengths, lengthIndex) { const result = new arrayClassData.constr(lengths[lengthIndex]); if (lengthIndex < lengths.length-1) { const subArrayClassData = arrayClassData.componentData; const subLengthIndex = lengthIndex+1; const underlying = result.u; for (let i = 0; i < underlying.length; i++) { underlying[i] = ScalaJS.<API key>( subArrayClassData, lengths, subLengthIndex); } } return result; }; ScalaJS.objectToString = function(instance) { if (instance === void 0) return "undefined"; else return instance.toString(); }; ScalaJS.objectGetClass = function(instance) { switch (typeof instance) { case "string": return ScalaJS.d.T.getClassOf(); case "number": { const v = instance | 0; if (v === instance) { // is the value integral? if (ScalaJS.isByte(v)) return ScalaJS.d.jl_Byte.getClassOf(); else if (ScalaJS.isShort(v)) return ScalaJS.d.jl_Short.getClassOf(); else return ScalaJS.d.jl_Integer.getClassOf(); } else { if (ScalaJS.isFloat(instance)) return ScalaJS.d.jl_Float.getClassOf(); else return ScalaJS.d.jl_Double.getClassOf(); } } case "boolean": return ScalaJS.d.jl_Boolean.getClassOf(); case "undefined": return ScalaJS.d.sr_BoxedUnit.getClassOf(); default: if (instance === null) return instance.getClass__jl_Class(); else if (ScalaJS.is.sjsr_RuntimeLong(instance)) return ScalaJS.d.jl_Long.getClassOf(); else if (ScalaJS.isScalaJSObject(instance)) return instance.$classData.getClassOf(); else return null; // Exception? } }; ScalaJS.objectClone = function(instance) { if (ScalaJS.isScalaJSObject(instance) || (instance === null)) return instance.clone__O(); else throw new ScalaJS.c.<API key>().init___(); }; ScalaJS.objectNotify = function(instance) { // final and no-op in java.lang.Object if (instance === null) instance.notify__V(); }; ScalaJS.objectNotifyAll = function(instance) { // final and no-op in java.lang.Object if (instance === null) instance.notifyAll__V(); }; ScalaJS.objectFinalize = function(instance) { if (ScalaJS.isScalaJSObject(instance) || (instance === null)) instance.finalize__V(); // else no-op }; ScalaJS.objectEquals = function(instance, rhs) { if (ScalaJS.isScalaJSObject(instance) || (instance === null)) return instance.equals__O__Z(rhs); else if (typeof instance === "number") return typeof rhs === "number" && ScalaJS.numberEquals(instance, rhs); else return instance === rhs; }; ScalaJS.numberEquals = function(lhs, rhs) { return (lhs === rhs) ? ( // 0.0.equals(-0.0) must be false lhs !== 0 || 1/lhs === 1/rhs ) : ( // are they both NaN? (lhs !== lhs) && (rhs !== rhs) ); }; ScalaJS.objectHashCode = function(instance) { switch (typeof instance) { case "string": return ScalaJS.m.sjsr_RuntimeString$().hashCode__T__I(instance); case "number": return ScalaJS.m.sjsr_Bits$().<API key>(instance); case "boolean": return instance ? 1231 : 1237; case "undefined": return 0; default: if (ScalaJS.isScalaJSObject(instance) || instance === null) return instance.hashCode__I(); //!if outputMode != ECMAScript6 else if (ScalaJS.idHashCodeMap === null) return 42; //!endif else return ScalaJS.<API key>(instance); } }; ScalaJS.comparableCompareTo = function(instance, rhs) { switch (typeof instance) { case "string": //!if asInstanceOfs != Unchecked ScalaJS.as.T(rhs); //!endif return instance === rhs ? 0 : (instance < rhs ? -1 : 1); case "number": //!if asInstanceOfs != Unchecked ScalaJS.as.jl_Number(rhs); //!endif return ScalaJS.m.jl_Double$().compare__D__D__I(instance, rhs); case "boolean": //!if asInstanceOfs != Unchecked ScalaJS.asBoolean(rhs); //!endif return instance - rhs; // yes, this gives the right result default: return instance.compareTo__O__I(rhs); } }; ScalaJS.charSequenceLength = function(instance) { if (typeof(instance) === "string") //!if asInstanceOfs != Unchecked return ScalaJS.uI(instance["length"]); //!else return instance["length"] | 0; //!endif else return instance.length__I(); }; ScalaJS.charSequenceCharAt = function(instance, index) { if (typeof(instance) === "string") //!if asInstanceOfs != Unchecked return ScalaJS.uI(instance["charCodeAt"](index)) & 0xffff; //!else return instance["charCodeAt"](index) & 0xffff; //!endif else return instance.charAt__I__C(index); }; ScalaJS.<API key> = function(instance, start, end) { if (typeof(instance) === "string") //!if asInstanceOfs != Unchecked return ScalaJS.as.T(instance["substring"](start, end)); //!else return instance["substring"](start, end); //!endif else return instance.<API key>(start, end); }; ScalaJS.booleanBooleanValue = function(instance) { if (typeof instance === "boolean") return instance; else return instance.booleanValue__Z(); }; ScalaJS.numberByteValue = function(instance) { if (typeof instance === "number") return (instance << 24) >> 24; else return instance.byteValue__B(); }; ScalaJS.numberShortValue = function(instance) { if (typeof instance === "number") return (instance << 16) >> 16; else return instance.shortValue__S(); }; ScalaJS.numberIntValue = function(instance) { if (typeof instance === "number") return instance | 0; else return instance.intValue__I(); }; ScalaJS.numberLongValue = function(instance) { if (typeof instance === "number") return ScalaJS.m.sjsr_RuntimeLong$().<API key>(instance); else return instance.longValue__J(); }; ScalaJS.numberFloatValue = function(instance) { if (typeof instance === "number") return ScalaJS.fround(instance); else return instance.floatValue__F(); }; ScalaJS.numberDoubleValue = function(instance) { if (typeof instance === "number") return instance; else return instance.doubleValue__D(); }; ScalaJS.isNaN = function(instance) { return instance !== instance; }; ScalaJS.isInfinite = function(instance) { return !ScalaJS.g["isFinite"](instance) && !ScalaJS.isNaN(instance); }; ScalaJS.doubleToInt = function(x) { return (x > 2147483647) ? (2147483647) : ((x < -2147483648) ? -2147483648 : (x | 0)); }; /** Instantiates a JS object with variadic arguments to the constructor. */ ScalaJS.<API key> = function(ctor, args) { // This basically emulates the ECMAScript specification for 'new'. const instance = ScalaJS.g["Object"]["create"](ctor.prototype); const result = ctor["apply"](instance, args); switch (typeof result) { case "string": case "number": case "boolean": case "undefined": case "symbol": return instance; default: return result === null ? instance : result; } }; ScalaJS.resolveSuperRef = function(initialProto, propName) { const getPrototypeOf = ScalaJS.g["Object"]["getPrototypeOf"]; const <API key> = ScalaJS.g["Object"]["<API key>"]; let superProto = getPrototypeOf(initialProto); while (superProto !== null) { const desc = <API key>(superProto, propName); if (desc !== void 0) return desc; superProto = getPrototypeOf(superProto); } return void 0; }; ScalaJS.superGet = function(initialProto, self, propName) { const desc = ScalaJS.resolveSuperRef(initialProto, propName); if (desc !== void 0) { const getter = desc["get"]; if (getter !== void 0) return getter["call"](self); else return desc["value"]; } return void 0; }; ScalaJS.superSet = function(initialProto, self, propName, value) { const desc = ScalaJS.resolveSuperRef(initialProto, propName); if (desc !== void 0) { const setter = desc["set"]; if (setter !== void 0) { setter["call"](self, value); return void 0; } } throw new ScalaJS.g["TypeError"]("super has no setter '" + propName + "'."); }; //!if moduleKind == CommonJSModule ScalaJS.moduleDefault = function(m) { return (m && (typeof m === "object") && "default" in m) ? m["default"] : m; }; //!endif ScalaJS.propertiesOf = function(obj) { const result = []; for (const prop in obj) result["push"](prop); return result; }; ScalaJS.systemArraycopy = function(src, srcPos, dest, destPos, length) { const srcu = src.u; const destu = dest.u; //!if <API key> != Unchecked if (srcPos < 0 || destPos < 0 || length < 0 || (srcPos > ((srcu.length - length) | 0)) || (destPos > ((destu.length - length) | 0))) { ScalaJS.<API key>(null); } //!endif if (srcu !== destu || destPos < srcPos || (((srcPos + length) | 0) < destPos)) { for (let i = 0; i < length; i = (i + 1) | 0) destu[(destPos + i) | 0] = srcu[(srcPos + i) | 0]; } else { for (let i = (length - 1) | 0; i >= 0; i = (i - 1) | 0) destu[(destPos + i) | 0] = srcu[(srcPos + i) | 0]; } }; ScalaJS.<API key> = //!if outputMode != ECMAScript6 (ScalaJS.idHashCodeMap !== null) ? //!endif (function(obj) { switch (typeof obj) { case "string": case "number": case "boolean": case "undefined": return ScalaJS.objectHashCode(obj); default: if (obj === null) { return 0; } else { let hash = ScalaJS.idHashCodeMap["get"](obj); if (hash === void 0) { hash = (ScalaJS.lastIDHash + 1) | 0; ScalaJS.lastIDHash = hash; ScalaJS.idHashCodeMap["set"](obj, hash); } return hash; } } //!if outputMode != ECMAScript6 }) : (function(obj) { if (ScalaJS.isScalaJSObject(obj)) { let hash = obj["$idHashCode$0"]; if (hash !== void 0) { return hash; } else if (!ScalaJS.g["Object"]["isSealed"](obj)) { hash = (ScalaJS.lastIDHash + 1) | 0; ScalaJS.lastIDHash = hash; obj["$idHashCode$0"] = hash; return hash; } else { return 42; } } else if (obj === null) { return 0; } else { return ScalaJS.objectHashCode(obj); } //!endif }); // is/as for hijacked boxed classes (the non-trivial ones) ScalaJS.isByte = function(v) { return (v << 24 >> 24) === v && 1/v !== 1/-0; }; ScalaJS.isShort = function(v) { return (v << 16 >> 16) === v && 1/v !== 1/-0; }; ScalaJS.isInt = function(v) { return (v | 0) === v && 1/v !== 1/-0; }; ScalaJS.isFloat = function(v) { //!if floats == Strict return v !== v || ScalaJS.fround(v) === v; //!else return typeof v === "number"; //!endif }; //!if asInstanceOfs != Unchecked ScalaJS.asUnit = function(v) { if (v === void 0 || v === null) return v; else ScalaJS.<API key>(v, "scala.runtime.BoxedUnit"); }; ScalaJS.asBoolean = function(v) { if (typeof v === "boolean" || v === null) return v; else ScalaJS.<API key>(v, "java.lang.Boolean"); }; ScalaJS.asByte = function(v) { if (ScalaJS.isByte(v) || v === null) return v; else ScalaJS.<API key>(v, "java.lang.Byte"); }; ScalaJS.asShort = function(v) { if (ScalaJS.isShort(v) || v === null) return v; else ScalaJS.<API key>(v, "java.lang.Short"); }; ScalaJS.asInt = function(v) { if (ScalaJS.isInt(v) || v === null) return v; else ScalaJS.<API key>(v, "java.lang.Integer"); }; ScalaJS.asFloat = function(v) { if (ScalaJS.isFloat(v) || v === null) return v; else ScalaJS.<API key>(v, "java.lang.Float"); }; ScalaJS.asDouble = function(v) { if (typeof v === "number" || v === null) return v; else ScalaJS.<API key>(v, "java.lang.Double"); }; //!endif // Unboxes //!if asInstanceOfs != Unchecked ScalaJS.uZ = function(value) { return !!ScalaJS.asBoolean(value); }; ScalaJS.uB = function(value) { return ScalaJS.asByte(value) | 0; }; ScalaJS.uS = function(value) { return ScalaJS.asShort(value) | 0; }; ScalaJS.uI = function(value) { return ScalaJS.asInt(value) | 0; }; ScalaJS.uJ = function(value) { return null === value ? ScalaJS.m.sjsr_RuntimeLong$().Zero$1 : ScalaJS.as.sjsr_RuntimeLong(value); }; ScalaJS.uF = function(value) { /* Here, it is fine to use + instead of fround, because asFloat already * ensures that the result is either null or a float. */ return +ScalaJS.asFloat(value); }; ScalaJS.uD = function(value) { return +ScalaJS.asDouble(value); }; //!else ScalaJS.uJ = function(value) { return null === value ? ScalaJS.m.sjsr_RuntimeLong$().Zero$1 : value; }; //!endif // TypeArray conversions ScalaJS.<API key> = function(value) { return new ScalaJS.g["Int8Array"](value.u); }; ScalaJS.<API key> = function(value) { return new ScalaJS.g["Int16Array"](value.u); }; ScalaJS.<API key> = function(value) { return new ScalaJS.g["Uint16Array"](value.u); }; ScalaJS.intArray2TypedArray = function(value) { return new ScalaJS.g["Int32Array"](value.u); }; ScalaJS.<API key> = function(value) { return new ScalaJS.g["Float32Array"](value.u); }; ScalaJS.<API key> = function(value) { return new ScalaJS.g["Float64Array"](value.u); }; ScalaJS.<API key> = function(value) { const arrayClassData = ScalaJS.d.B.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Int8Array"](value)); }; ScalaJS.<API key> = function(value) { const arrayClassData = ScalaJS.d.S.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Int16Array"](value)); }; ScalaJS.<API key> = function(value) { const arrayClassData = ScalaJS.d.C.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Uint16Array"](value)); }; ScalaJS.typedArray2IntArray = function(value) { const arrayClassData = ScalaJS.d.I.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Int32Array"](value)); }; ScalaJS.<API key> = function(value) { const arrayClassData = ScalaJS.d.F.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Float32Array"](value)); }; ScalaJS.<API key> = function(value) { const arrayClassData = ScalaJS.d.D.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Float64Array"](value)); }; // TypeData class //!if outputMode != ECMAScript6 /** @constructor */ ScalaJS.TypeData = function() { //!else class $TypeData { constructor() { //!endif // Runtime support this.constr = void 0; this.parentData = void 0; this.ancestors = null; this.componentData = null; this.arrayBase = null; this.arrayDepth = 0; this.zero = null; this.arrayEncodedName = ""; this._classOf = void 0; this._arrayOf = void 0; this.isArrayOf = void 0; // java.lang.Class support this["name"] = ""; this["isPrimitive"] = false; this["isInterface"] = false; this["isArrayClass"] = false; this["isRawJSType"] = false; this["isInstance"] = void 0; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.initPrim = function( //!else initPrim( //!endif zero, arrayEncodedName, displayName) { // Runtime support this.ancestors = {}; this.componentData = null; this.zero = zero; this.arrayEncodedName = arrayEncodedName; this.isArrayOf = function(obj, depth) { return false; }; // java.lang.Class support this["name"] = displayName; this["isPrimitive"] = true; this["isInstance"] = function(obj) { return false; }; return this; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.initClass = function( //!else initClass( //!endif internalNameObj, isInterface, fullName, ancestors, isRawJSType, parentData, isInstance, isArrayOf) { const internalName = ScalaJS.propertyName(internalNameObj); isInstance = isInstance || function(obj) { return !!(obj && obj.$classData && obj.$classData.ancestors[internalName]); }; isArrayOf = isArrayOf || function(obj, depth) { return !!(obj && obj.$classData && (obj.$classData.arrayDepth === depth) && obj.$classData.arrayBase.ancestors[internalName]) }; // Runtime support this.parentData = parentData; this.ancestors = ancestors; this.arrayEncodedName = "L"+fullName+";"; this.isArrayOf = isArrayOf; // java.lang.Class support this["name"] = fullName; this["isInterface"] = isInterface; this["isRawJSType"] = !!isRawJSType; this["isInstance"] = isInstance; return this; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.initArray = function( //!else initArray( //!endif componentData) { // The constructor const componentZero0 = componentData.zero; // The zero for the Long runtime representation // is a special case here, since the class has not // been defined yet, when this file is read const componentZero = (componentZero0 == "longZero") ? ScalaJS.m.sjsr_RuntimeLong$().Zero$1 : componentZero0; //!if outputMode != ECMAScript6 /** @constructor */ const ArrayClass = function(arg) { if (typeof(arg) === "number") { // arg is the length of the array this.u = new Array(arg); for (let i = 0; i < arg; i++) this.u[i] = componentZero; } else { // arg is a native array that we wrap this.u = arg; } } ArrayClass.prototype = new ScalaJS.h.O; ArrayClass.prototype.constructor = ArrayClass; //!if <API key> != Unchecked ArrayClass.prototype.get = function(i) { if (i < 0 || i >= this.u.length) ScalaJS.<API key>(i); return this.u[i]; }; ArrayClass.prototype.set = function(i, v) { if (i < 0 || i >= this.u.length) ScalaJS.<API key>(i); this.u[i] = v; }; //!endif ArrayClass.prototype.clone__O = function() { if (this.u instanceof Array) return new ArrayClass(this.u["slice"](0)); else // The underlying Array is a TypedArray return new ArrayClass(new this.u.constructor(this.u)); }; //!else class ArrayClass extends ScalaJS.c.O { constructor(arg) { super(); if (typeof(arg) === "number") { // arg is the length of the array this.u = new Array(arg); for (let i = 0; i < arg; i++) this.u[i] = componentZero; } else { // arg is a native array that we wrap this.u = arg; } }; //!if <API key> != Unchecked get(i) { if (i < 0 || i >= this.u.length) ScalaJS.<API key>(i); return this.u[i]; }; set(i, v) { if (i < 0 || i >= this.u.length) ScalaJS.<API key>(i); this.u[i] = v; }; //!endif clone__O() { if (this.u instanceof Array) return new ArrayClass(this.u["slice"](0)); else // The underlying Array is a TypedArray return new ArrayClass(new this.u.constructor(this.u)); }; }; //!endif ArrayClass.prototype.$classData = this; // Don't generate reflective call proxies. The compiler special cases // reflective calls to methods on scala.Array // The data const encodedName = "[" + componentData.arrayEncodedName; const componentBase = componentData.arrayBase || componentData; const arrayDepth = componentData.arrayDepth + 1; const isInstance = function(obj) { return componentBase.isArrayOf(obj, arrayDepth); } // Runtime support this.constr = ArrayClass; this.parentData = ScalaJS.d.O; this.ancestors = {O: 1, jl_Cloneable: 1, <API key>: 1}; this.componentData = componentData; this.arrayBase = componentBase; this.arrayDepth = arrayDepth; this.zero = null; this.arrayEncodedName = encodedName; this._classOf = undefined; this._arrayOf = undefined; this.isArrayOf = undefined; // java.lang.Class support this["name"] = encodedName; this["isPrimitive"] = false; this["isInterface"] = false; this["isArrayClass"] = true; this["isInstance"] = isInstance; return this; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.getClassOf = function() { //!else getClassOf() { //!endif if (!this._classOf) this._classOf = new ScalaJS.c.jl_Class().<API key>(this); return this._classOf; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.getArrayOf = function() { //!else getArrayOf() { //!endif if (!this._arrayOf) this._arrayOf = new ScalaJS.TypeData().initArray(this); return this._arrayOf; }; // java.lang.Class support //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype["getFakeInstance"] = function() { //!else "getFakeInstance"() { //!endif if (this === ScalaJS.d.T) return "some string"; else if (this === ScalaJS.d.jl_Boolean) return false; else if (this === ScalaJS.d.jl_Byte || this === ScalaJS.d.jl_Short || this === ScalaJS.d.jl_Integer || this === ScalaJS.d.jl_Float || this === ScalaJS.d.jl_Double) return 0; else if (this === ScalaJS.d.jl_Long) return ScalaJS.m.sjsr_RuntimeLong$().Zero$1; else if (this === ScalaJS.d.sr_BoxedUnit) return void 0; else return {$classData: this}; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype["getSuperclass"] = function() { //!else "getSuperclass"() { //!endif return this.parentData ? this.parentData.getClassOf() : null; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype["getComponentType"] = function() { //!else "getComponentType"() { //!endif return this.componentData ? this.componentData.getClassOf() : null; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype["newArrayOfThisClass"] = function(lengths) { //!else "newArrayOfThisClass"(lengths) { //!endif let arrayClassData = this; for (let i = 0; i < lengths.length; i++) arrayClassData = arrayClassData.getArrayOf(); return ScalaJS.newArrayObject(arrayClassData, lengths); }; //!if outputMode == ECMAScript6 }; //!endif // Create primitive types ScalaJS.d.V = new ScalaJS.TypeData().initPrim(undefined, "V", "void"); ScalaJS.d.Z = new ScalaJS.TypeData().initPrim(false, "Z", "boolean"); ScalaJS.d.C = new ScalaJS.TypeData().initPrim(0, "C", "char"); ScalaJS.d.B = new ScalaJS.TypeData().initPrim(0, "B", "byte"); ScalaJS.d.S = new ScalaJS.TypeData().initPrim(0, "S", "short"); ScalaJS.d.I = new ScalaJS.TypeData().initPrim(0, "I", "int"); ScalaJS.d.J = new ScalaJS.TypeData().initPrim("longZero", "J", "long"); ScalaJS.d.F = new ScalaJS.TypeData().initPrim(0.0, "F", "float"); ScalaJS.d.D = new ScalaJS.TypeData().initPrim(0.0, "D", "double"); // Instance tests for array of primitives ScalaJS.isArrayOf.Z = ScalaJS.<API key>(ScalaJS.d.Z); ScalaJS.d.Z.isArrayOf = ScalaJS.isArrayOf.Z; ScalaJS.isArrayOf.C = ScalaJS.<API key>(ScalaJS.d.C); ScalaJS.d.C.isArrayOf = ScalaJS.isArrayOf.C; ScalaJS.isArrayOf.B = ScalaJS.<API key>(ScalaJS.d.B); ScalaJS.d.B.isArrayOf = ScalaJS.isArrayOf.B; ScalaJS.isArrayOf.S = ScalaJS.<API key>(ScalaJS.d.S); ScalaJS.d.S.isArrayOf = ScalaJS.isArrayOf.S; ScalaJS.isArrayOf.I = ScalaJS.<API key>(ScalaJS.d.I); ScalaJS.d.I.isArrayOf = ScalaJS.isArrayOf.I; ScalaJS.isArrayOf.J = ScalaJS.<API key>(ScalaJS.d.J); ScalaJS.d.J.isArrayOf = ScalaJS.isArrayOf.J; ScalaJS.isArrayOf.F = ScalaJS.<API key>(ScalaJS.d.F); ScalaJS.d.F.isArrayOf = ScalaJS.isArrayOf.F; ScalaJS.isArrayOf.D = ScalaJS.<API key>(ScalaJS.d.D); ScalaJS.d.D.isArrayOf = ScalaJS.isArrayOf.D; //!if asInstanceOfs != Unchecked // asInstanceOfs for array of primitives ScalaJS.asArrayOf.Z = ScalaJS.<API key>(ScalaJS.isArrayOf.Z, "Z"); ScalaJS.asArrayOf.C = ScalaJS.<API key>(ScalaJS.isArrayOf.C, "C"); ScalaJS.asArrayOf.B = ScalaJS.<API key>(ScalaJS.isArrayOf.B, "B"); ScalaJS.asArrayOf.S = ScalaJS.<API key>(ScalaJS.isArrayOf.S, "S"); ScalaJS.asArrayOf.I = ScalaJS.<API key>(ScalaJS.isArrayOf.I, "I"); ScalaJS.asArrayOf.J = ScalaJS.<API key>(ScalaJS.isArrayOf.J, "J"); ScalaJS.asArrayOf.F = ScalaJS.<API key>(ScalaJS.isArrayOf.F, "F"); ScalaJS.asArrayOf.D = ScalaJS.<API key>(ScalaJS.isArrayOf.D, "D"); //!endif
#include "chrome/browser/ui/panels/<API key>.h" #include "base/logging.h" #include "chrome/browser/ui/panels/panel.h" #include "chrome/browser/ui/panels/panel_manager.h" namespace { static bool ResizingLeft(panel::ResizingSides sides) { return sides == panel::RESIZE_TOP_LEFT || sides == panel::RESIZE_LEFT || sides == panel::RESIZE_BOTTOM_LEFT; } static bool ResizingRight(panel::ResizingSides sides) { return sides == panel::RESIZE_TOP_RIGHT || sides == panel::RESIZE_RIGHT || sides == panel::RESIZE_BOTTOM_RIGHT; } static bool ResizingTop(panel::ResizingSides sides) { return sides == panel::RESIZE_TOP_LEFT || sides == panel::RESIZE_TOP || sides == panel::RESIZE_TOP_RIGHT; } static bool ResizingBottom(panel::ResizingSides sides) { return sides == panel::RESIZE_BOTTOM_RIGHT || sides == panel::RESIZE_BOTTOM || sides == panel::RESIZE_BOTTOM_LEFT; } } <API key>::<API key>(PanelManager* panel_manager) : panel_manager_(panel_manager), resizing_panel_(NULL), sides_resized_(panel::RESIZE_NONE) { } void <API key>::StartResizing(Panel* panel, const gfx::Point& mouse_location, panel::ResizingSides sides) { DCHECK(!IsResizing()); DCHECK_NE(panel::RESIZE_NONE, sides); panel::Resizability resizability = panel->CanResizeByMouse(); DCHECK_NE(panel::NOT_RESIZABLE, resizability); panel::Resizability <API key>; switch (sides) { case panel::RESIZE_TOP_LEFT: <API key> = panel::RESIZABLE_TOP_LEFT; break; case panel::RESIZE_TOP: <API key> = panel::RESIZABLE_TOP; break; case panel::RESIZE_TOP_RIGHT: <API key> = panel::RESIZABLE_TOP_RIGHT; break; case panel::RESIZE_LEFT: <API key> = panel::RESIZABLE_LEFT; break; case panel::RESIZE_RIGHT: <API key> = panel::RESIZABLE_RIGHT; break; case panel::RESIZE_BOTTOM_LEFT: <API key> = panel::<API key>; break; case panel::RESIZE_BOTTOM: <API key> = panel::RESIZABLE_BOTTOM; break; case panel::RESIZE_BOTTOM_RIGHT: <API key> = panel::<API key>; break; default: <API key> = panel::NOT_RESIZABLE; break; } if ((resizability & <API key>) == 0) { DLOG(WARNING) << "Resizing not allowed. Is this a test?"; return; } <API key> = mouse_location; bounds_at_start_ = panel->GetBounds(); sides_resized_ = sides; resizing_panel_ = panel; resizing_panel_-><API key>(); } void <API key>::Resize(const gfx::Point& mouse_location) { DCHECK(IsResizing()); panel::Resizability resizability = resizing_panel_->CanResizeByMouse(); if (panel::NOT_RESIZABLE == resizability) { EndResizing(false); return; } gfx::Rect bounds = resizing_panel_->GetBounds(); if (ResizingRight(sides_resized_)) { bounds.set_width(std::max(bounds_at_start_.width() + mouse_location.x() - <API key>.x(), 0)); } if (ResizingBottom(sides_resized_)) { bounds.set_height(std::max(bounds_at_start_.height() + mouse_location.y() - <API key>.y(), 0)); } if (ResizingLeft(sides_resized_)) { bounds.set_width(std::max(bounds_at_start_.width() + <API key>.x() - mouse_location.x(), 0)); } if (ResizingTop(sides_resized_)) { int new_height = std::max(bounds_at_start_.height() + <API key>.y() - mouse_location.y(), 0); int new_y = bounds_at_start_.bottom() - new_height; // If the mouse is within the main screen area, make sure that the top // border of panel cannot go outside the work area. This is to prevent // panel's titlebar from being resized under the taskbar or OSX menu bar // that is aligned to top screen edge. int <API key> = panel_manager_->display_area().y(); if (panel_manager_-><API key>()-> <API key>().Contains(mouse_location) && new_y < <API key>) { new_height -= <API key> - new_y; } bounds.set_height(new_height); } resizing_panel_->IncreaseMaxSize(bounds.size()); // This effectively only clamps using the min size, since the max_size was // updated above. bounds.set_size(resizing_panel_->ClampSize(bounds.size())); if (ResizingLeft(sides_resized_)) bounds.set_x(bounds_at_start_.right() - bounds.width()); if (ResizingTop(sides_resized_)) bounds.set_y(bounds_at_start_.bottom() - bounds.height()); if (bounds != resizing_panel_->GetBounds()) resizing_panel_-><API key>(bounds); } Panel* <API key>::EndResizing(bool cancelled) { DCHECK(IsResizing()); if (cancelled) resizing_panel_-><API key>(bounds_at_start_); // Do a thorough cleanup. resizing_panel_-><API key>(); Panel* resized_panel = resizing_panel_; resizing_panel_ = NULL; sides_resized_ = panel::RESIZE_NONE; bounds_at_start_ = gfx::Rect(); <API key> = gfx::Point(); return resized_panel; } void <API key>::OnPanelClosed(Panel* panel) { if (!resizing_panel_) return; // If the resizing panel is closed, abort the resize operation. if (resizing_panel_ == panel) EndResizing(false); }
/* $OpenBSD: limits.h,v 1.5 1998/03/22 21:15:24 millert Exp $ */ /* $NetBSD: limits.h,v 1.7 1996/01/05 18:10:57 pk Exp $ */ #define CHAR_BIT 8 /* number of bits in a char */ #define MB_LEN_MAX 1 /* no multibyte characters */ #define SCHAR_MIN (-0x7f-1) /* max value for a signed char */ #define SCHAR_MAX 0x7f /* min value for a signed char */ #define UCHAR_MAX 0xffU /* max value for an unsigned char */ #define CHAR_MAX 0x7f /* max value for a char */ #define CHAR_MIN (-0x7f-1) /* min value for a char */ #define USHRT_MAX 0xffffU /* max value for an unsigned short */ #define SHRT_MAX 0x7fff /* max value for a short */ #define SHRT_MIN (-0x7fff-1) /* min value for a short */ #define UINT_MAX 0xffffffffU /* max value for an unsigned int */ #define INT_MAX 0x7fffffff /* max value for an int */ #define INT_MIN (-0x7fffffff-1) /* min value for an int */ #define ULONG_MAX 0xffffffffUL /* max value for an unsigned long */ #define LONG_MAX 0x7fffffffL /* max value for a long */ #define LONG_MIN (-0x7fffffffL-1) /* min value for a long */ #if !defined(_ANSI_SOURCE) #define SSIZE_MAX INT_MAX /* max value for a ssize_t */ #if !defined(_POSIX_SOURCE) && !defined(_XOPEN_SOURCE) #define SIZE_T_MAX UINT_MAX /* max value for a size_t */ #define UID_MAX UINT_MAX /* max value for a uid_t */ #define GID_MAX UINT_MAX /* max value for a gid_t */ /* GCC requires that quad constants be written as expressions. */ #define UQUAD_MAX ((u_quad_t)0-1) /* max value for a uquad_t */ /* max value for a quad_t */ #define QUAD_MAX ((quad_t)(UQUAD_MAX >> 1)) #define QUAD_MIN (-QUAD_MAX-1) /* min value for a quad_t */ #endif /* !_POSIX_SOURCE && !_XOPEN_SOURCE */ #endif /* !_ANSI_SOURCE */ #if (!defined(_ANSI_SOURCE)&&!defined(_POSIX_SOURCE)) || defined(_XOPEN_SOURCE) #define LONG_BIT 32 #define WORD_BIT 32 #define DBL_DIG 15 #define DBL_MAX 1.7976931348623157E+308 #define DBL_MIN 2.<API key> #define FLT_DIG 6 #define FLT_MAX 3.40282347E+38F #define FLT_MIN 1.17549435E-38F #endif
package com.percolate.sdk.dto; import com.fasterxml.jackson.annotation.*; import com.percolate.sdk.interfaces.HasExtraFields; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @SuppressWarnings("UnusedDeclaration") @<API key>(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class <API key> implements Serializable, HasExtraFields { private static final long serialVersionUID = -<API key>; @JsonIgnore public List<<API key>> extraMessages = new ArrayList<>(); // Set by client to group messages happening around the same time @JsonIgnore public String stickerUrl; //Set by client. If message is empty, <API key> is used to check for images/stickers. @JsonIgnore public List<<API key>> attachments; //Set by client after calling <API key>. @JsonIgnore public Flag flag; //Set by client after calling ApiGetFlags @JsonProperty("id") protected String id; @JsonProperty("conversation_id") protected String conversationId; @JsonProperty("from") protected FacebookUser from; // <API key> API returns "from" // ApiGetFlag API returns "from_user" // The setter method for this value sets <code>from</code> field. @JsonProperty("from_user") protected FacebookUser tempFromUser; @JsonProperty("created_at") protected String createdAt; @JsonProperty("has_attachments") protected Boolean hasAttachments; @JsonProperty("message") protected String message; @JsonIgnore protected Map<String, Object> extraFields = new HashMap<>(); @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getConversationId() { return conversationId; } public void setConversationId(String conversationId) { this.conversationId = conversationId; } public FacebookUser getFrom() { return from; } public void setFrom(FacebookUser from) { this.from = from; } public void setTempFromUser(FacebookUser from) { this.tempFromUser = from; this.from = from; } public FacebookUser getTempFromUser() { return tempFromUser; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public Boolean getHasAttachments() { return hasAttachments; } public void setHasAttachments(Boolean hasAttachments) { this.hasAttachments = hasAttachments; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public Map<String, Object> getExtraFields() { if(extraFields == null) { extraFields = new HashMap<>(); } return extraFields; } @Override @JsonAnySetter public void putExtraField(String key, Object value) { getExtraFields().put(key, value); } }
<?php use yii\helpers\Html; use kartik\grid\GridView; use yii\helpers\ArrayHelper; use backend\modules\qtn\models\Survey; /* @var $this yii\web\View */ /* @var $searchModel backend\modules\qtn\Models\SurveySearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Qtn Surveys'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="qtn-survey-index"> <h1><?= Html::encode($this->title) ?></h1> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <p> <?= Html::a('Create Qtn Survey', ['create'], ['class' => 'btn btn-success']) ?> </p> <?= GridView::widget([ 'dataProvider' => $dataProvider, // 'filterModel' => $searchModel, 'showPageSummary'=>true, 'pjax'=>true, 'striped'=>true, 'hover'=>true, 'panel'=>['type'=>'primary', 'heading'=>'Grid Grouping Example'], 'columns' => [ ['class'=>'kartik\grid\SerialColumn'], [ 'attribute'=>'id', 'format' => 'raw', 'width'=>'310px', 'value'=>function ($model, $key, $index, $widget) { $txt= $model->surveyTab->survey->name; if($model->surveyTab->survey->status==0){ $txt .= '&nbsp;'.Html::a('<span class=" glyphicon glyphicon-pencil"></span>',[ 'survey/update?id=' . $model->surveyTab->survey_id]); } $txt .= '___' .Html::a('<span class="glyphicon glyphicon-list-alt"></span>',[ 'survey/view?id=' .$model->surveyTab->survey_id]); return $txt; }, 'filterInputOptions'=>['placeholder'=>'Any supplier'], 'group'=>true, // enable grouping, 'groupedRow'=>true, // move grouped column to a single grouped row 'groupOddCssClass'=>'kv-grouped-row', // configure odd group cell css class 'groupEvenCssClass'=>'kv-grouped-row', // configure even group cell css class ], [ 'attribute'=>'survey_tab_id', 'width'=>'310px', 'value'=>function ($model, $key, $index, $widget) { return $model->surveyTab->name; }, 'group'=>true, ], [ 'attribute'=>'name', 'format' => 'raw', 'value'=>function ($data) { $txt= $data->name; if($data->surveyTab->survey->status==0){ $txt .= '&nbsp;'.Html::a('คำถาม',[ 'survey/question?id=' . $data->surveyTab->survey_id]); //$txt .=Html::a('table',[ 'survey/choice-title?id=' . $data->id]); } return $txt; }, ], ], ]); ?> </div>
@echo off rem rem Collective Knowledge rem rem See CK LICENSE.txt for licensing details. rem See CK Copyright.txt for copyright details. rem rem Developer: Grigori Fursin rem rem CK entry point rem Set default path by detecting the path to this script set ck_path=%~dp0\.. rem Check if CK_ROOT is defined and used it, otherwise use auto-detected path IF "%CK_ROOT%"=="" set CK_ROOT=%ck_path% rem Load kernel module IF EXIST %CK_ROOT%\ck\kernel.py ( python -W ignore::DeprecationWarning %CK_ROOT%\ck\kernel.py %* ) ELSE ( echo cK Error: kernel module not found! )
Bool_t <API key> = kFALSE; Bool_t <API key> = kFALSE; std::string centralityFilename = ""; std::string <API key> = "/alice/cern.ch/user/a/acapon/.root"; const Int_t triggerNames = AliVEvent::kINT7; const Int_t nMCSignal = 0; const Int_t nCutsetting = 0; const Double_t minGenPt = 0.05; const Double_t maxGenPt = 20; const Double_t minGenEta = -1.5; const Double_t maxGenEta = 1.5; const Double_t minPtCut = 0.2; const Double_t maxPtCut = 15.0; const Double_t minEtaCut = -0.8; const Double_t maxEtaCut = 0.8; // const Double_t minPtCut = 0.2; // const Double_t maxPtCut = 8.0; // const Double_t minEtaCut = -0.8; // const Double_t maxEtaCut = 0.8; // binning of single leg histograms Bool_t usePtVector = kTRUE; Double_t ptBins[] = {0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40, 0.45,0.50,0.55,0.60,0.65,0.70,0.75,0.80,0.85, 0.90,0.95,1.00,1.10,1.20,1.30,1.40,1.50,1.60, 1.70,1.80,1.90,2.00,2.10,2.30,2.50,3.00,3.50, 4.00,5.00,6.00,7.00,8.00,10.0,15.0}; const Int_t nBinsPt = ( sizeof(ptBins) / sizeof(ptBins[0]) )-1; const Double_t minPtBin = 0; const Double_t maxPtBin = 20; const Int_t stepsPtBin = 800; const Double_t minEtaBin = -1.0; const Double_t maxEtaBin = 1.0; const Int_t stepsEtaBin = 20; const Double_t minPhiBin = 0; const Double_t maxPhiBin = 6.3; const Int_t stepsPhiBin = 20; const Double_t minThetaBin = 0; const Double_t maxThetaBin = TMath::TwoPi(); const Int_t stepsThetaBin = 60; const Double_t minMassBin = 0; const Double_t maxMassBin = 5; const Int_t stepsMassBin = 500; const Double_t minPairPtBin = 0; const Double_t maxPairPtBin = 10; const Int_t stepsPairPtBin = 100; // Binning of resolution histograms const Int_t NbinsDeltaMom = 2000; const Double_t DeltaMomMin = -10.0; const Double_t DeltaMomMax = 10.0; const Int_t NbinsRelMom = 400; const Double_t RelMomMin = 0.0; const Double_t RelMomMax = 2.0; const Int_t NbinsDeltaEta = 200; const Double_t DeltaEtaMin = -0.4; const Double_t DeltaEtaMax = 0.4; const Int_t NbinsDeltaTheta = 200; const Double_t DeltaThetaMin = -0.4; const Double_t DeltaThetaMax = 0.4; const Int_t NbinsDeltaPhi = 200; const Double_t DeltaPhiMin = -0.4; const Double_t DeltaPhiMax = 0.4; void GetCentrality(const Int_t centrality, Double_t& CentMin, Double_t& CentMax){ std::cout << "GetCentrality with centrality " << centrality << std::endl; if (centrality == 0){CentMin = 0; CentMax = 100;} else if(centrality == 1){CentMin = 0; CentMax = 20;} else if(centrality == 2){CentMin = 20; CentMax = 40;} else if(centrality == 3){CentMin = 40; CentMax = 60;} else if(centrality == 4){CentMin = 60; CentMax = 100;} else if(centrality == 5){CentMin = 60; CentMax = 80;} else if(centrality == 6){CentMin = 80; CentMax = 100;} else if(centrality == 7){CentMin = 0; CentMax = 5;} else if(centrality == 8){CentMin = -1; CentMax = -1;} else {std::cout << "WARNING::Centrality range not found....." std::endl;} return; } void <API key>(<API key>* task, Int_t whichDet, Bool_t wSDD){ std::cout << task << std::endl; std::cout << "starting <API key>()\n"; if(whichDet == 0 && wSDD){// ITS std::cout << "Loading ITS correction" << std::endl; TString localPath = "/home/aaron/Data/<API key>/PIDcalibration/"; TString fileName = "outputITS_MC.root"; TFile* inFile = TFile::Open(localPath+fileName); if(!inFile){ gSystem->Exec("alien_cp alien:///alice/cern.ch/user/a/acapon/PIDcalibration/"+fileName+" ."); std::cout << "Copy ITS correction from Alien" << std::endl; inFile = TFile::Open(fileName); } else { std::cout << "Correction loaded" << std::endl; } TH3D* mean = dynamic_cast<TH3D*>(inFile->Get("sum_mean_correction")); TH3D* width= dynamic_cast<TH3D*>(inFile->Get("<API key>")); task-><API key>(<API key>::kITS, mean, <API key>::kP, <API key>::kEta, <API key>::kRefMultTPConly); task-><API key> (<API key>::kITS, width, <API key>::kP, <API key>::kEta, <API key>::kRefMultTPConly); } if(whichDet == 1){// TOF std::cout << "Loading TOF correction" << std::endl; TString localPath = "/home/aaron/Data/<API key>/PIDcalibration/"; TString fileName = "outputTOF"; if(wSDD == kTRUE){ fileName.Append("_MC.root"); }else{ fileName.Append("_woSDD_MC.root"); } TFile* inFile = TFile::Open(localPath+fileName); if(!inFile){ gSystem->Exec("alien_cp alien:///alice/cern.ch/user/a/acapon/PIDcalibration/"+fileName+" ."); std::cout << "Copy TOF correction from Alien" << std::endl; inFile = TFile::Open(fileName); } else { std::cout << "Correction loaded" << std::endl; } TH3D* mean = dynamic_cast<TH3D*>(inFile->Get("sum_mean_correction")); TH3D* width= dynamic_cast<TH3D*>(inFile->Get("<API key>")); task-><API key>(<API key>::kTOF, mean, <API key>::kP, <API key>::kEta, <API key>::kRefMultTPConly); task-><API key> (<API key>::kTOF, width, <API key>::kP, <API key>::kEta, <API key>::kRefMultTPConly); } } // // AliAnalysisFilter* <API key>(TString cutDefinition, Bool_t wSDD) { std::cout << "<API key>( cutInstance = " << cutDefinition << " )" <<std::endl; AliAnalysisFilter *anaFilter = new AliAnalysisFilter("anaFilter","anaFilter"); // named constructor seems mandatory! LMEECutLib* LMcutlib = new LMEECutLib(wSDD); if(cutDefinition == "kResolutionCuts"){ std::cout << "Resolution Track Cuts being set" << std::endl; anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::<API key>, LMEECutLib::<API key>)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutSet1"){ //TMVA std::cout << "Setting up cut set 1" << std::endl; anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kCutSet1)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kTheoPID"){ // PID cut set from a Run 1 pPb analysis. Standard track cuts std::cout << "Setting up Theo PID. Standard track cuts." << std::endl; anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kTheoPID)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kScheidCuts"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kScheidCuts, LMEECutLib::kScheidCuts)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } // // These variations use the kCutSet1 track cuts and only vary PID else if(cutDefinition == "kPIDcut1"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut1)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut2"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut2)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut3"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut3)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut4"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut4)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut5"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut5)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut6"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut6)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut7"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut7)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut8"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut8)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut9"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut9)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut10"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut10)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut11"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut11)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut12"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut12)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut13"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut13)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut14"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut14)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut15"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut15)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut16"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut16)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut17"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut17)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut18"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut18)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut19"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut19)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut20"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut20)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } // else if(cutDefinition == "kCutVar1"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar1, LMEECutLib::kCutVar1)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar2"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar2, LMEECutLib::kCutVar2)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar3"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar3, LMEECutLib::kCutVar3)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar4"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar4, LMEECutLib::kCutVar4)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar5"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar5, LMEECutLib::kCutVar5)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar6"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar6, LMEECutLib::kCutVar6)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar7"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar7, LMEECutLib::kCutVar7)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar8"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar8, LMEECutLib::kCutVar8)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar9"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar9, LMEECutLib::kCutVar9)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar10"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar10, LMEECutLib::kCutVar10)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar11"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar11, LMEECutLib::kCutVar11)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar12"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar12, LMEECutLib::kCutVar12)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar13"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar13, LMEECutLib::kCutVar13)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar14"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar14, LMEECutLib::kCutVar14)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar15"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar15, LMEECutLib::kCutVar15)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar16"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar16, LMEECutLib::kCutVar16)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar17"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar17, LMEECutLib::kCutVar17)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar18"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar18, LMEECutLib::kCutVar18)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar19"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar19, LMEECutLib::kCutVar19)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar20"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar20, LMEECutLib::kCutVar20)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else{ std::cout << "Undefined cut definition...." << std::endl; return 0x0; } return anaFilter; } // // std::vector<Bool_t> <API key>(<API key>* task){ // SetLegPDGs() requires two pdg codes. For single tracks a dummy value is // passed, "1". // All final state electrons (excluding conversion electrons) <API key> eleFinalState("eleFinalState","eleFinalState"); eleFinalState.SetLegPDGs(11,1); eleFinalState.<API key>(kTRUE,kTRUE); eleFinalState.SetLegSources(<API key>::kFinalState, <API key>::kFinalState); eleFinalState.SetMotherPDGs(22, 22, kTRUE, kTRUE); // Exclude conversion electrons // Electrons from open charm mesons and baryons <API key> eleFinalStateFromD("eleFinalStateFromD","eleFinalStateFromD"); eleFinalStateFromD.SetLegPDGs(11,1); eleFinalStateFromD.<API key>(kTRUE,kTRUE); eleFinalStateFromD.SetLegSources(<API key>::kFinalState, <API key>::kFinalState); eleFinalStateFromD.SetMotherPDGs(402, 402); eleFinalStateFromD.<API key>(kTRUE,kTRUE); // Electrons from open beauty mesons and baryons <API key> eleFinalStateFromB("eleFinalStateFromB","eleFinalStateFromB"); eleFinalStateFromB.SetLegPDGs(11,1); eleFinalStateFromB.<API key>(kTRUE,kTRUE); eleFinalStateFromB.SetLegSources(<API key>::kFinalState, <API key>::kFinalState); eleFinalStateFromB.SetMotherPDGs(502, 502); eleFinalStateFromB.<API key>(kTRUE,kTRUE); // Add signals task-><API key>(eleFinalState); task-><API key>(eleFinalStateFromD); task-><API key>(eleFinalStateFromB); // This is used to get electrons not from same mother for pair efficiency. // Needed to look at D and B meson electrons as functionality to pair those is // not implemented in the framework. Instead, use all final start electrons // from D or B decays for efficiency correction, for example. // The ordering must match the ordering of the added signals above*. std::vector<Bool_t> <API key>; <API key>.push_back(kFALSE); <API key>.push_back(kTRUE); <API key>.push_back(kTRUE); return <API key>; } // // void AddPairMCSignal(<API key>* task){ // Dielectron pairs from same mother (excluding conversions) <API key> pair_sameMother("sameMother","sameMother"); pair_sameMother.SetLegPDGs(11,-11); pair_sameMother.<API key>(kTRUE,kTRUE); pair_sameMother.SetLegSources(<API key>::kFinalState, <API key>::kFinalState); // Set mother properties pair_sameMother.SetMothersRelation(<API key>::kSame); pair_sameMother.SetMotherPDGs(22,22,kTRUE,kTRUE); // Exclude conversion // // Signals for specific dielectron decay channels <API key> <API key>("sameMother_pion","sameMother_pion"); <API key>.SetLegPDGs(11,-11); <API key>.<API key>(kTRUE,kTRUE); <API key>.SetLegSources(<API key>::kFinalState, <API key>::kFinalState); // Set mother properties <API key>.SetMothersRelation(<API key>::kSame); <API key>.SetMotherPDGs(111,111); <API key> pair_sameMother_eta("sameMother_eta","sameMother_eta"); pair_sameMother_eta.SetLegPDGs(11,-11); pair_sameMother_eta.<API key>(kTRUE,kTRUE); pair_sameMother_eta.SetLegSources(<API key>::kFinalState, <API key>::kFinalState); // Set mother properties pair_sameMother_eta.SetMothersRelation(<API key>::kSame); pair_sameMother_eta.SetMotherPDGs(221,221); <API key> <API key>("sameMother_etaP","sameMother_etaP"); <API key>.SetLegPDGs(11,-11); <API key>.<API key>(kTRUE,kTRUE); <API key>.SetLegSources(<API key>::kFinalState, <API key>::kFinalState); // Set mother properties <API key>.SetMothersRelation(<API key>::kSame); <API key>.SetMotherPDGs(331,331); <API key> pair_sameMother_rho("sameMother_rho","sameMother_rho"); pair_sameMother_rho.SetLegPDGs(11,-11); pair_sameMother_rho.<API key>(kTRUE,kTRUE); pair_sameMother_rho.SetLegSources(<API key>::kFinalState, <API key>::kFinalState); // Set mother properties pair_sameMother_rho.SetMothersRelation(<API key>::kSame); pair_sameMother_rho.SetMotherPDGs(113, 113); <API key> <API key>("sameMother_omega","sameMother_omega"); <API key>.SetLegPDGs(11,-11); <API key>.<API key>(kTRUE,kTRUE); <API key>.SetLegSources(<API key>::kFinalState, <API key>::kFinalState); // Set mother properties <API key>.SetMothersRelation(<API key>::kSame); <API key>.SetMotherPDGs(223, 223); <API key> pair_sameMother_phi("sameMother_phi","sameMother_phi"); pair_sameMother_phi.SetLegPDGs(11,-11); pair_sameMother_phi.<API key>(kTRUE,kTRUE); pair_sameMother_phi.SetLegSources(<API key>::kFinalState, <API key>::kFinalState); // Set mother properties pair_sameMother_phi.SetMothersRelation(<API key>::kSame); pair_sameMother_phi.SetMotherPDGs(333, 333); <API key> <API key>("sameMother_jpsi","sameMother_jpsi"); <API key>.SetLegPDGs(11,-11); <API key>.<API key>(kTRUE,kTRUE); <API key>.SetLegSources(<API key>::kFinalState, <API key>::kFinalState); // Set mother properties <API key>.SetMothersRelation(<API key>::kSame); <API key>.SetMotherPDGs(443, 443); task->AddPairMCSignal(pair_sameMother); // task->AddPairMCSignal(<API key>); // task->AddPairMCSignal(pair_sameMother_eta); // task->AddPairMCSignal(<API key>); // task->AddPairMCSignal(pair_sameMother_rho); // task->AddPairMCSignal(<API key>); // task->AddPairMCSignal(pair_sameMother_phi); // task->AddPairMCSignal(<API key>); }
<?php $list_def_file = "list/web_aliasdomain.list.php"; $tform_def_file = "form/web_aliasdomain.tform.php"; require_once('../../lib/config.inc.php'); require_once('../../lib/app.inc.php');
#include "chrome/browser/<API key>.h" #include <stdint.h> #include <string> #include <vector> #include "base/macros.h" #include "base/strings/<API key>.h" #include "base/strings/string_util.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/net/<API key>.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/ash/login/demo_mode/demo_session.h" #endif #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/pref_names.h" #include "components/language/core/browser/language_prefs.h" #include "components/language/core/browser/pref_names.h" #include "components/prefs/pref_service.h" #include "content/public/browser/<API key>.h" #include "content/public/browser/<API key>.h" #include "media/media_buildflags.h" #include "third_party/blink/public/common/peerconnection/<API key>.h" #include "third_party/blink/public/common/<API key>/<API key>.h" #include "third_party/blink/public/public_buildflags.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/ui_base_features.h" #if defined(TOOLKIT_VIEWS) #include "ui/views/controls/textfield/textfield.h" #endif #if defined(OS_MAC) #include "ui/base/cocoa/defaults_utils.h" #endif #if defined(USE_AURA) && (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/<API key>.h" #include "ui/views/linux_ui/linux_ui.h" #endif #include "content/nw/src/common/<API key>.h" namespace { // Parses a string |range| with a port range in the form "<min>-<max>". // If |range| is not in the correct format or contains an invalid range, zero // is written to |min_port| and |max_port|. // TODO(guidou): Consider replacing with remoting/protocol/port_range.cc void ParsePortRange(const std::string& range, uint16_t* min_port, uint16_t* max_port) { *min_port = 0; *max_port = 0; if (range.empty()) return; size_t separator_index = range.find('-'); if (separator_index == std::string::npos) return; std::string min_port_string, max_port_string; base::TrimWhitespaceASCII(range.substr(0, separator_index), base::TRIM_ALL, &min_port_string); base::TrimWhitespaceASCII(range.substr(separator_index + 1), base::TRIM_ALL, &max_port_string); unsigned min_port_uint, max_port_uint; if (!base::StringToUint(min_port_string, &min_port_uint) || !base::StringToUint(max_port_string, &max_port_uint)) { return; } if (min_port_uint == 0 || min_port_uint > max_port_uint || max_port_uint > UINT16_MAX) { return; } *min_port = static_cast<uint16_t>(min_port_uint); *max_port = static_cast<uint16_t>(max_port_uint); } // Extracts the string representation of URLs allowed for local IP exposure. std::vector<std::string> <API key>( const base::ListValue* allowed_urls) { std::vector<std::string> ret; if (allowed_urls) { const auto& urls = allowed_urls->GetList(); for (const auto& url : urls) ret.push_back(url.GetString()); } return ret; } std::string <API key>(Profile* profile, const std::string& language_list) { if (profile->IsOffTheRecord()) { // In incognito mode return only the first language. return language::GetFirstLanguage(language_list); } #if BUILDFLAG(IS_CHROMEOS_ASH) // On Chrome OS, if in demo mode, add the demo mode private language list. if (ash::DemoSession::IsDeviceInDemoMode()) { return language_list + "," + ash::DemoSession::<API key>(); } #endif return language_list; } } // namespace namespace <API key> { void <API key>(blink::RendererPreferences* prefs, Profile* profile) { const PrefService* pref_service = profile->GetPrefs(); prefs->accept_languages = <API key>( profile, pref_service->GetString(language::prefs::kAcceptLanguages)); prefs->enable_referrers = pref_service->GetBoolean(prefs::kEnableReferrers); prefs->enable_do_not_track = pref_service->GetBoolean(prefs::kEnableDoNotTrack); prefs-><API key> = pref_service->GetBoolean(prefs::<API key>); prefs-><API key> = std::string(); #if !defined(OS_ANDROID) prefs-><API key> = pref_service->GetBoolean(prefs::<API key>); content::<API key>::GetInstance()-><API key>( prefs-><API key>); #endif if (prefs-><API key>.empty()) { prefs-><API key> = pref_service->GetString(prefs::<API key>); } std::string <API key> = pref_service->GetString(prefs::kWebRTCUDPPortRange); ParsePortRange(<API key>, &prefs->webrtc_udp_min_port, &prefs->webrtc_udp_max_port); const base::ListValue* allowed_urls = pref_service->GetList(prefs::<API key>); prefs-><API key> = <API key>(allowed_urls); prefs-><API key> = pref_service->GetBoolean(prefs::<API key>); #if defined(USE_AURA) prefs->focus_ring_color = SkColorSetRGB(0x4D, 0x90, 0xFE); #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS) // This color is 0x544d90fe modulated with 0xffffff. prefs-><API key> = SkColorSetRGB(0xCB, 0xE4, 0xFA); prefs-><API key> = SK_ColorBLACK; prefs-><API key> = SkColorSetRGB(0xEA, 0xEA, 0xEA); prefs-><API key> = SK_ColorBLACK; #endif #endif #if defined(TOOLKIT_VIEWS) prefs-><API key> = views::Textfield::<API key>(); #endif #if defined(OS_MAC) base::TimeDelta interval; if (ui::<API key>(&interval)) prefs-><API key> = interval; #endif #if defined(USE_AURA) && (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) views::LinuxUI* linux_ui = views::LinuxUI::instance(); if (linux_ui) { if (ThemeServiceFactory::GetForProfile(profile)->UsingSystemTheme()) { prefs->focus_ring_color = linux_ui->GetFocusRingColor(); prefs-><API key> = linux_ui-><API key>(); prefs-><API key> = linux_ui-><API key>(); prefs-><API key> = linux_ui-><API key>(); prefs-><API key> = linux_ui-><API key>(); } // If we have a linux_ui object, set the caret blink interval regardless of // whether we're in native theme mode. prefs-><API key> = linux_ui-><API key>(); } #endif #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) || \ defined(OS_WIN) content::<API key>(prefs); #endif #if !defined(OS_MAC) prefs-><API key> = pref_service->GetBoolean(prefs::kFullscreenAllowed); #endif PrefService* local_state = g_browser_process->local_state(); if (local_state) { prefs-><API key> = local_state->GetBoolean(prefs::<API key>); prefs-><API key> = <API key>(local_state); } #if defined(OS_MAC) prefs->focus_ring_color = SkColorSetRGB(0x00, 0x5F, 0xCC); #else prefs->focus_ring_color = SkColorSetRGB(0x10, 0x10, 0x10); #endif std::string user_agent; if (nw::<API key>(&user_agent)) prefs->user_agent_override.ua_string_override = user_agent; } } // namespace <API key>
package net.minidev.ovh.api.price.dedicatedcloud._2014v1.sbg1a.infrastructure.filer; import com.fasterxml.jackson.annotation.JsonProperty; /** * Enum of Hourlys */ public enum OvhHourlyEnum { @JsonProperty("iscsi-1200-GB") iscsi_1200_GB("iscsi-1200-GB"), @JsonProperty("iscsi-13200g-GB") iscsi_13200g_GB("iscsi-13200g-GB"), @JsonProperty("iscsi-3300-GB") iscsi_3300_GB("iscsi-3300-GB"), @JsonProperty("iscsi-6600-GB") iscsi_6600_GB("iscsi-6600-GB"), @JsonProperty("iscsi-800-GB") iscsi_800_GB("iscsi-800-GB"), @JsonProperty("nfs-100-GB") nfs_100_GB("nfs-100-GB"), @JsonProperty("nfs-1200-GB") nfs_1200_GB("nfs-1200-GB"), @JsonProperty("nfs-13200-GB") nfs_13200_GB("nfs-13200-GB"), @JsonProperty("nfs-1600-GB") nfs_1600_GB("nfs-1600-GB"), @JsonProperty("nfs-2400-GB") nfs_2400_GB("nfs-2400-GB"), @JsonProperty("nfs-3300-GB") nfs_3300_GB("nfs-3300-GB"), @JsonProperty("nfs-6600-GB") nfs_6600_GB("nfs-6600-GB"), @JsonProperty("nfs-800-GB") nfs_800_GB("nfs-800-GB"); final String value; OvhHourlyEnum(String s) { this.value = s; } public String toString() { return this.value; } }
<?php class <API key> implements SmartyLint_Rule { /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return array('NEW_LINE'); } /** * Processes this rule, when one of its tokens is encountered. * * @param SmartyLint_File $smartylFile The file being scanned. * @param int $stackPtr The position of the current token in * the stack passed in $tokens. * * @return void */ public function process(SmartyLint_File $smartylFile, $stackPtr) { $tokens = $smartylFile->getTokens(); $beforeNewLine = false; if (isset($tokens[($stackPtr - 1)])) { $beforeNewLine = $tokens[($stackPtr - 1)]['type']; if ($beforeNewLine == 'TAB' || $beforeNewLine == 'SPACE') { $smartylFile->addError('Whitespace found at end of line', $stackPtr, 'EndFile'); } } $newLinesFound = 1; for ($i = ($stackPtr-1); $i >= 0; $i if (isset($tokens[$i]) && $tokens[$i]['type'] == 'NEW_LINE') { $newLinesFound++; } else { break; } } if ($newLinesFound > 3) { $error = 'Found %s empty lines in a row.'; $data = array($newLinesFound); $smartylFile->addError($error, ($stackPtr - $newLinesFound), 'EmptyLines', $data); } } }
<?php App::uses('CloggyAppModel', 'Cloggy.Model'); class <API key> extends CloggyAppModel { public $name = '<API key>'; public $useTable = 'search_fulltext'; public $actsAs = array('<API key>','<API key>'); public function getTotal() { return $this->find('count'); } public function search($query) { //default used mode $usedMode = __d('cloggy','Natural Search'); /* * first try to search with natural search * NATURAL SEARCH */ $data = $this->find('all',array( 'contain' => false, 'fields' => array('*','MATCH (<API key>.source_sentences,<API key>.source_text) AGAINST (\''.$query.'\') AS rating'), 'conditions' => array('MATCH (<API key>.source_sentences,<API key>.source_text) AGAINST (\''.$query.'\')'), 'order' => array('rating' => 'desc') )); /* * if failed or empty results then * reset search in BOOLEAN MODE * with operator '*' that means search * data which contain 'query' or 'queries', etc */ if (empty($data)) { //format query string $query = $this->buildTerm($query); /* * begin searching data */ $data = $this->find('all',array( 'contain' => false, 'fields' => array('*','MATCH (<API key>.source_sentences,<API key>.source_text) AGAINST (\''.$query.'\' IN BOOLEAN MODE) AS rating'), 'conditions' => array('MATCH (<API key>.source_sentences,<API key>.source_text) AGAINST (\''.$query.'\' IN BOOLEAN MODE)'), 'order' => array('rating' => 'desc') )); //switch search mode $usedMode = __d('cloggy','Boolean Mode'); } return array( 'mode' => $usedMode, 'results' => $data ); } }
<!DOCTYPE html> <html> <head> <title>{title} - Montage Docs</title> <link rel="stylesheet" href="/mdl/material.min.css"> <link rel="stylesheet" href="/mdl/styles.css"> <script src="/mdl/material.min.js"></script> <link rel="stylesheet" href="https://tools-static.wmflabs.org/fontcdn/css?family=Roboto:400,200,100"> </head> <body class="mdl-montage mdl-color--grey-100 <API key> mdl-base"> <header class="mdl-layout__header <API key>"> <div class="mdl-layout mdl-js-layout <API key>"> <div class="<API key> <API key>"> <button class="mdl-button mdl-js-button mdl-button--icon" disabled="disabled"> <img alt="Montage Logo" src="/dist/images/logo_white_fat.svg"> </button> <h1><a href="/docs/">Montage</a>: {title}</h1> </div> </div> </header> <main class="mdl-layout__content"> <section class="section--center mdl-grid <API key> mdl-shadow--2dp"> <div class="mdl-card mdl-cell mdl-cell--12-col"> <div class="<API key> mdl-grid"> <p> <p>{?body}{body|s}{:else}Nothing to see here!{/body}</p> </p> </div> </div> </section> </main> </body> </html>
package org.usfirst.frc369.Robot2017Code.subsystems; import org.usfirst.frc369.Robot2017Code.Robot; import edu.wpi.first.wpilibj.Relay; import edu.wpi.first.wpilibj.command.Subsystem; public class LED extends Subsystem { // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } public void LEDOn(){ Robot.LEDSys.equals(Relay.Value.kForward); } public void LEDelse(){ Robot.LEDSys.equals(Relay.Value.kReverse); } public void LEDOff(){ Robot.LEDSys.equals(Relay.Value.kOff); } }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="description" content="Javadoc API documentation for Fresco." /> <link rel="shortcut icon" type="image/x-icon" href="../../../../favicon.ico" /> <title> com.facebook.imagepipeline.nativecode Details - Fresco API | Fresco </title> <link href="../../../../../assets/<API key>.css" rel="stylesheet" type="text/css" /> <link href="../../../../../assets/customizations.css" rel="stylesheet" type="text/css" /> <script src="../../../../../assets/search_autocomplete.js" type="text/javascript"></script> <script src="../../../../../assets/jquery-resizable.min.js" type="text/javascript"></script> <script src="../../../../../assets/<API key>.js" type="text/javascript"></script> <script src="../../../../../assets/prettify.js" type="text/javascript"></script> <script type="text/javascript"> setToRoot("../../../../", "../../../../../assets/"); </script> <script src="../../../../../assets/<API key>.js" type="text/javascript"></script> <script src="../../../../../assets/navtree_data.js" type="text/javascript"></script> <script src="../../../../../assets/customizations.js" type="text/javascript"></script> <noscript> <style type="text/css"> html,body{overflow:auto;} #body-content{position:relative; top:0;} #doc-content{overflow:visible;border-left:3px solid #666;} #side-nav{padding:0;} #side-nav .toggle-list ul {display:block;} #resize-packages-nav{border-bottom:3px solid #666;} </style> </noscript> </head> <body class=""> <div id="header"> <div id="headerLeft"> <span id="masthead-title"><a href="../../../../packages.html">Fresco</a></span> </div> <div id="headerRight"> <div id="search" > <div id="searchForm"> <form accept-charset="utf-8" class="gsc-search-box" onsubmit="return submit_search()"> <table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody> <tr> <td class="gsc-input"> <input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off" title="search developer docs" name="q" value="search developer docs" onFocus="<API key>(this, true)" onBlur="<API key>(this, false)" onkeydown="return search_changed(event, true, '../../../../')" onkeyup="return search_changed(event, false, '../../../../')" /> <div id="search_filtered_div" class="no-display"> <table id="search_filtered" cellspacing=0> </table> </div> </td> <!-- <td class="gsc-search-button"> <input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" /> </td> <td class="gsc-clear-button"> <div title="clear results" class="gsc-clear-button">&nbsp;</div> </td> </tr></tbody> </table> </form> </div><!-- searchForm --> </div><!-- search --> </div> </div><!-- header --> <div class="g-section g-tpl-240" id="body-content"> <div class="g-unit g-first side-nav-resizable" id="side-nav"> <div id="swapper"> <div id="nav-panels"> <div id="resize-packages-nav"> <div id="packages-nav"> <div id="index-links"> <a href="../../../../packages.html" >Packages</a> | <a href="../../../../classes.html" >Classes</a> </div> <ul> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/gif/package-summary.html">com.facebook.animated.gif</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/webp/package-summary.html">com.facebook.animated.webp</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/binaryresource/package-summary.html">com.facebook.binaryresource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/cache/common/package-summary.html">com.facebook.cache.common</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/cache/disk/package-summary.html">com.facebook.cache.disk</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/activitylistener/package-summary.html">com.facebook.common.activitylistener</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/disk/package-summary.html">com.facebook.common.disk</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/executors/package-summary.html">com.facebook.common.executors</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/file/package-summary.html">com.facebook.common.file</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/internal/package-summary.html">com.facebook.common.internal</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/lifecycle/package-summary.html">com.facebook.common.lifecycle</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/logging/package-summary.html">com.facebook.common.logging</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/media/package-summary.html">com.facebook.common.media</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/memory/package-summary.html">com.facebook.common.memory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/references/package-summary.html">com.facebook.common.references</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/soloader/package-summary.html">com.facebook.common.soloader</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/statfs/package-summary.html">com.facebook.common.statfs</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/streams/package-summary.html">com.facebook.common.streams</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/time/package-summary.html">com.facebook.common.time</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/util/package-summary.html">com.facebook.common.util</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/webp/package-summary.html">com.facebook.common.webp</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/datasource/package-summary.html">com.facebook.datasource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawable/base/package-summary.html">com.facebook.drawable.base</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/backends/pipeline/package-summary.html">com.facebook.drawee.backends.pipeline</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/backends/volley/package-summary.html">com.facebook.drawee.backends.volley</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/components/package-summary.html">com.facebook.drawee.components</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/controller/package-summary.html">com.facebook.drawee.controller</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/debug/package-summary.html">com.facebook.drawee.debug</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/drawable/package-summary.html">com.facebook.drawee.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/generic/package-summary.html">com.facebook.drawee.generic</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/gestures/package-summary.html">com.facebook.drawee.gestures</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/interfaces/package-summary.html">com.facebook.drawee.interfaces</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/span/package-summary.html">com.facebook.drawee.span</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/view/package-summary.html">com.facebook.drawee.view</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/backend/package-summary.html">com.facebook.fresco.animation.backend</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/package-summary.html">com.facebook.fresco.animation.bitmap</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/cache/package-summary.html">com.facebook.fresco.animation.bitmap.cache</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/preparation/package-summary.html">com.facebook.fresco.animation.bitmap.preparation</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/wrapper/package-summary.html">com.facebook.fresco.animation.bitmap.wrapper</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/drawable/package-summary.html">com.facebook.fresco.animation.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/drawable/animator/package-summary.html">com.facebook.fresco.animation.drawable.animator</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/factory/package-summary.html">com.facebook.fresco.animation.factory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/frame/package-summary.html">com.facebook.fresco.animation.frame</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imageformat/package-summary.html">com.facebook.imageformat</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/base/package-summary.html">com.facebook.imagepipeline.animated.base</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/factory/package-summary.html">com.facebook.imagepipeline.animated.factory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/impl/package-summary.html">com.facebook.imagepipeline.animated.impl</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/util/package-summary.html">com.facebook.imagepipeline.animated.util</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/backends/okhttp3/package-summary.html">com.facebook.imagepipeline.backends.okhttp3</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/backends/volley/package-summary.html">com.facebook.imagepipeline.backends.volley</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/bitmaps/package-summary.html">com.facebook.imagepipeline.bitmaps</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/cache/package-summary.html">com.facebook.imagepipeline.cache</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/common/package-summary.html">com.facebook.imagepipeline.common</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/core/package-summary.html">com.facebook.imagepipeline.core</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/datasource/package-summary.html">com.facebook.imagepipeline.datasource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/decoder/package-summary.html">com.facebook.imagepipeline.decoder</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/drawable/package-summary.html">com.facebook.imagepipeline.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/image/package-summary.html">com.facebook.imagepipeline.image</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/listener/package-summary.html">com.facebook.imagepipeline.listener</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/memory/package-summary.html">com.facebook.imagepipeline.memory</a></li> <li class="selected api apilevel-"> <a href="../../../../com/facebook/imagepipeline/nativecode/package-summary.html">com.facebook.imagepipeline.nativecode</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/platform/package-summary.html">com.facebook.imagepipeline.platform</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/postprocessors/package-summary.html">com.facebook.imagepipeline.postprocessors</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/producers/package-summary.html">com.facebook.imagepipeline.producers</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/request/package-summary.html">com.facebook.imagepipeline.request</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imageutils/package-summary.html">com.facebook.imageutils</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/webpsupport/package-summary.html">com.facebook.webpsupport</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/widget/text/span/package-summary.html">com.facebook.widget.text.span</a></li> </ul><br/> </div> <!-- end packages --> </div> <!-- end resize-packages --> <div id="classes-nav"> <ul> <li><h2>Interfaces</h2> <ul> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/WebpTranscoder.html">WebpTranscoder</a></li> </ul> </li> <li><h2>Classes</h2> <ul> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/Bitmaps.html">Bitmaps</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/<API key>.html"><API key></a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/JpegTranscoder.html">JpegTranscoder</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/NativeBlurFilter.html">NativeBlurFilter</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/<API key>.html"><API key></a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/<API key>.html"><API key></a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/<API key>.html"><API key></a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/WebpTranscoderImpl.html">WebpTranscoderImpl</a></li> </ul> </li> </ul><br/> </div><!-- end classes --> </div><!-- end nav-panels --> <div id="nav-tree" style="display:none"> <div id="index-links"> <a href="../../../../packages.html" >Packages</a> | <a href="../../../../classes.html" >Classes</a> </div> </div><!-- end nav-tree --> </div><!-- end swapper --> </div> <!-- end side-nav --> <script> if (!isMobile) { //$("<a href='#' id='nav-swap' onclick='swapNav();return false;' style='font-size:10px;line-height:9px;margin-left:1em;text-decoration:none;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>").appendTo("#side-nav"); chooseDefaultNav(); if ($("#nav-tree").is(':visible')) { <API key>("../../../../"); } else { addLoadEvent(function() { scrollIntoView("packages-nav"); scrollIntoView("classes-nav"); }); } //$("#swapper").css({borderBottom:"2px solid #aaa"}); } else { swapNav(); // tree view should be used on mobile } </script> <div class="g-unit" id="doc-content"> <div id="api-info-block"> <div class="api-level"> </div> </div> <div id="jd-header"> package <h1>com.facebook.imagepipeline.nativecode</b></h1> <div class="jd-nav"> <a class="jd-navlink" href="package-summary.html">Classes</a> | Description </div> </div><!-- end header --> <div id="naMessage"></div> <div id="jd-content" class="api apilevel-"> <div class="jd-descr"> <p></p> </div> <div id="footer"> +Generated by <a href="http://code.google.com/p/doclava/">Doclava</a>. +</div> <!-- end footer - @generated --> </div><!-- end jd-content --> </div> <!-- end doc-content --> </div> <!-- end body-content --> <script type="text/javascript"> init(); /* initialize <API key>.js */ </script> </body> </html>
var NETKI_PUBAPI_HOST = 'https://pubapi.netki.com'; var NETKI_API_HOST = 'https://api.netki.com'; var SHORTCODES = { 'btc': 'Bitcoin', 'tbtc': 'Bitcoin Testnet', 'ltc': 'Litecoin', 'dgc': 'Dogecoin', 'nmc': 'Namecoin', 'tusd': 'tetherUSD', 'teur': 'tetherEUR', 'tjpy': 'tetherJPY', 'oap': 'Open Asset', 'fct': 'Factom Factoid', 'fec': 'Factom Entry Credit', 'eth': 'Ethereum Ether' }; function isWalletName(walletName) { var pattern = /^(?!:\/\/)([a-zA-Z0-9]+\.)?[a-zA-Z0-9][a-zA-Z0-9-]+\.[a-zA-Z]{2,24}?$/i; return pattern.test(walletName); }
#!/bin/bash set -x # configure tweaks mv /tmp/docker-* /etc/apt/apt.conf.d chown root:root /etc/apt/apt.conf.d/docker-* chmod 644 /etc/apt/apt.conf.d/docker-* # make sure we're fully up-to-date apt-get update && apt-get dist-upgrade -y reboot
package gov.nih.nci.system.webservice; import gov.nih.nci.system.applicationservice.ApplicationService; import gov.nih.nci.system.client.proxy.ListProxy; import gov.nih.nci.system.query.hibernate.HQLCriteria; import gov.nih.nci.system.query.nestedcriteria.NestedCriteriaPath; import gov.nih.nci.system.util.ClassCache; import gov.nih.nci.system.webservice.util.WSUtils; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import javax.xml.rpc.ServiceException; import org.apache.log4j.Logger; import org.springframework.remoting.jaxrpc.<API key>; public class WSQueryImpl extends <API key> implements WSQuery{ private static Logger log = Logger.getLogger(WSQueryImpl.class); private static ApplicationService applicationService; private static ClassCache classCache; private static int resultCountPerQuery = 1000; public void destroy() { applicationService = null; classCache = null; resultCountPerQuery = 0; } protected void onInit() throws ServiceException { classCache = (ClassCache)<API key>().getBean("ClassCache"); applicationService = (ApplicationService)<API key>().getBean("<API key>"); Properties systemProperties = (Properties) <API key>().getBean("SystemProperties"); try { String count = systemProperties.getProperty("resultCountPerQuery"); log.debug("resultCountPerQuery: " + count); if (count != null) { resultCountPerQuery = Integer.parseInt(count); } } catch (Exception ex) { log.error("Exception initializing resultCountPerQuery: ", ex); throw new ServiceException("Exception initializing resultCountPerQuery: ", ex); } } public int <API key>(String targetClassName, Object criteria) throws Exception{ return <API key>(targetClassName, criteria, 0).size(); } public List queryObject(String targetClassName, Object criteria) throws Exception { return query(targetClassName,criteria,0); } public List query(String targetClassName, Object criteria, int startIndex) throws Exception { List results = new ArrayList(); results = <API key>(targetClassName, criteria, startIndex); List alteredResults = alterResultSet(results); return alteredResults; } private List <API key>(String targetClassName, Object searchCriteria, int startIndex) throws Exception{ List results = new ArrayList(); String searchClassName = getSearchClassName(targetClassName); try { if(searchClassName != null && searchCriteria != null){ List<Object> paramList = new ArrayList<Object>(); paramList.add(searchCriteria); NestedCriteriaPath pathCriteria = new NestedCriteriaPath(targetClassName,paramList); results = applicationService.query(pathCriteria, startIndex, targetClassName); } else{ throw new Exception("Invalid arguments passed over to the server"); } } catch(Exception e) { log.error("WSQuery caught an exception: ", e); throw e; } return results; } public List getAssociation(Object source, String associationName, int startIndex) throws Exception { List results = new ArrayList(); String targetClassName = source.getClass().getName(); log.debug("targetClassName: " + targetClassName); String hql = "select obj."+associationName+" from "+targetClassName+" obj where obj = ?"; log.debug("hql: " + hql); List<Object> params = new ArrayList<Object>(); params.add(source); HQLCriteria criteria = new HQLCriteria(hql,params); results = getHQLResultSet(targetClassName, criteria, startIndex); List alteredResults = alterResultSet(results); return alteredResults; } private List getHQLResultSet(String targetClassName, Object searchCriteria, int startIndex) throws Exception{ List results = new ArrayList(); String searchClassName = getSearchClassName(targetClassName); try { if(searchClassName != null && searchCriteria != null){ results = applicationService.query(searchCriteria, startIndex, targetClassName); } else{ throw new Exception("Invalid arguments passed over to the server"); } } catch(Exception e) { log.error("WSQuery caught an exception: ", e); throw e; } return results; } private String getSearchClassName(String targetClassName)throws Exception { String searchClassName = ""; if(targetClassName.indexOf(",")>0){ StringTokenizer st = new StringTokenizer(targetClassName, ","); while(st.hasMoreTokens()){ String className = st.nextToken(); String validClassName = classCache.<API key>(className); log.debug("validClassName: " + validClassName); searchClassName += validClassName + ","; } searchClassName = searchClassName.substring(0,searchClassName.lastIndexOf(",")); } else{ searchClassName = classCache.<API key>(targetClassName); } if(searchClassName == null){ throw new Exception("Invalid class name: " + targetClassName); } return searchClassName; } private List alterResultSet(List results) { List objList; if (results instanceof ListProxy) { ListProxy listProxy = (ListProxy)results; objList = listProxy.getListChunk(); } else { objList = results; } WSUtils util = new WSUtils(); objList = (List)util.convertToProxy(null, objList); return objList; } }
ls | `cat` | wc -l | wc -c
package au.gov.ga.geodesy.sitelog.domain.model; import javax.validation.constraints.Size; public class Contact { private Integer id; @Size(max = 200) protected String name; @Size(max = 200) protected String telephonePrimary; @Size(max = 200) protected String telephoneSecondary; @Size(max = 200) protected String fax; @Size(max = 200) protected String email; @SuppressWarnings("unused") private Integer getId() { return id; } @SuppressWarnings("unused") private void setId(Integer id) { this.id = id; } /** * Return name. */ public String getName() { return name; } /** * Set name. */ public void setName(String value) { this.name = value; } /** * Return primary telephone number. */ public String getTelephonePrimary() { return telephonePrimary; } /** * Set primary telephone number. */ public void setTelephonePrimary(String value) { this.telephonePrimary = value; } /** * Return secondary telephone number. */ public String <API key>() { return telephoneSecondary; } /** * Set secondary telephone number. */ public void <API key>(String value) { this.telephoneSecondary = value; } /** * Return fax number. */ public String getFax() { return fax; } /** * Set fax number. */ public void setFax(String value) { this.fax = value; } /** * Return email address. */ public String getEmail() { return email; } /** * Set email address. */ public void setEmail(String value) { this.email = value; } }
#endregion namespace ProCenter.Mvc.Infrastructure.Service.Completeness { #region Using Statements using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Domain.AssessmentModule.Lookups; using ProCenter.Domain.AssessmentModule.Metadata; using ProCenter.Service.Message.Assessment; using ProCenter.Service.Message.Common.Lookups; using ProCenter.Service.Message.Metadata; #endregion <summary>The completeness model validtor provider class.</summary> public class <API key> : <API key> { #region Public Methods and Operators <summary> Gets a list of validators. </summary> <param name="metadata">The metadata.</param> <param name="context">The context.</param> <returns> A list of validators. </returns> public override IEnumerable<ModelValidator> GetValidators ( ModelMetadata metadata, ControllerContext context ) { if ( metadata.PropertyName != null && context is ViewContext && (context.Controller.ViewData.Model is <API key> || context.Controller.ViewData.Model is SectionDto )) { var viewContext = context as ViewContext; if ( viewContext.ViewData != null ) { if ( ( metadata.ContainerType == typeof(ItemDto) && metadata.PropertyName == "Value" ) || ( metadata.ContainerType == typeof(LookupDto) && metadata.PropertyName == "Code" ) ) { // only care about value var sectionDto = context.Controller.ViewData.Model is <API key> ? (context.Controller.ViewData.Model as <API key>).CurrentSectionDto : context.Controller.ViewData.Model as SectionDto; if ( sectionDto != null ) { var propertyParts = viewContext.ViewData.TemplateInfo.<API key> ( metadata.PropertyName ).Split ( '.' ); if ( propertyParts.Length == 2 ) { var index = propertyParts[0].IndexOf ( "_Value", StringComparison.Ordinal ); if ( index != -1 ) { var code = propertyParts[0].Substring ( 0, index ); var itemDto = GetItemDtoByCode ( sectionDto, code ); if ( itemDto != null ) { var metadataItemDto = itemDto.Metadata.FindMetadataItem<<API key>> (); if ( metadataItemDto != null ) { yield return new <API key> ( metadata, context, metadataItemDto.<API key> ); } } } } } } } } } #endregion #region Methods private static ItemDto GetItemDtoByCode ( IContainItems sectionDto, string code ) { foreach ( var itemDto in sectionDto.Items ) { if ( itemDto.ItemDefinitionCode == code && itemDto.ItemType == ItemType.Question.CodedConcept.Code ) { return itemDto; } if ( itemDto.Items != null ) { foreach ( var childItemDto in itemDto.Items.Where ( childItemDto => childItemDto.ItemDefinitionCode == code && childItemDto.ItemType == ItemType.Question.CodedConcept.Code ) ) { return childItemDto; } foreach (var containerDto in itemDto.Items.Where(i => i.ItemType != ItemType.Question.CodedConcept.Code).OfType<IContainItems> ()) { var childItem = GetItemDtoByCode ( containerDto, code ); if ( childItem != null ) { return childItem; } } } } return null; } #endregion } }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_14) on Fri Sep 18 14:09:15 BST 2009 --> <TITLE> uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs </TITLE> <META NAME="date" CONTENT="2009-09-18"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/service/globus/resource/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/bindings/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <H2> Package uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs </H2> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/<API key>.html" title="interface in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs"><API key></A></B></TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/InterProScanRequest.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs">InterProScanRequest</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/<API key>.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs"><API key></A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/<API key>.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs"><API key></A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/<API key>.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs"><API key></A></B></TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <DL> </DL> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/service/globus/resource/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/bindings/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> </BODY> </HTML>
package edu.cmu.minorthird.text.gui; import edu.cmu.minorthird.text.FancyLoader; import edu.cmu.minorthird.text.TextLabels; import edu.cmu.minorthird.util.gui.ControlledViewer; import edu.cmu.minorthird.util.gui.VanillaViewer; import edu.cmu.minorthird.util.gui.Viewer; import edu.cmu.minorthird.util.gui.ViewerFrame; import edu.cmu.minorthird.util.gui.ZoomedViewer; /** * View the contents of a bunch of spans, using the util.gui.Viewer framework. * * <p> Hopefully this will evolve into a cleaner version of the * TextBaseViewer, TextBaseEditor, etc suite. It replaces an earlier * attempt, the SpanLooperViewer. * * @author William Cohen */ public class <API key> extends ZoomedViewer{ static final long serialVersionUID=20080202L; public <API key>(TextLabels labels){ Viewer zoomedOut=new ControlledViewer(new TextLabelsViewer(labels),new MarkupControls(labels)); Viewer zoomedIn=new VanillaViewer("[Empty TextBase]"); if(labels.getTextBase().size()>0){ zoomedIn=new SpanViewer(labels,labels.getTextBase().<API key>().next()); } this.setSubViews(zoomedOut,zoomedIn); } // test case public static void main(String[] argv){ try{ final TextLabels labels=FancyLoader.loadTextLabels(argv[0]); new ViewerFrame(argv[0],new <API key>(labels)); }catch(Exception e){ e.printStackTrace(); System.out.println("Usage: labelKey"); } } }
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE <API key> #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TupleSections #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Test.PGConstant ( TestPGConstant(..) , spec ) where import Data.Proxy (Proxy(..)) import Database.PostgreSQL.Simple.Bind.Parser import Test.Hspec (Spec, describe) import Test.QuickCheck (Arbitrary(..), oneof) import Test.Common (PGSql(..)) import Test.Utils (propParsingWorks) import Test.PGString (TestPGString(..)) data TestPGConstant = TPGCString TestPGString | TPGCNumeric Double deriving (Show, Eq) instance Arbitrary TestPGConstant where arbitrary = oneof [ TPGCString <$> arbitrary , TPGCNumeric <$> arbitrary] instance PGSql TestPGConstant where render (TPGCString s) = render s render (TPGCNumeric c) = show c spec :: Spec spec = do describe "pgConstant" $ do propParsingWorks pgConstant (Proxy :: Proxy TestPGConstant)
<?php $modules["recurringinvoices"]["name"] = "Recurring Invoices"; $modules["recurringinvoices"]["version"] = "1.01"; $modules["recurringinvoices"]["description"] = "This module adds the ability to repeat invoices on a scheduled basis."; $modules["recurringinvoices"]["requirements"] = "phpBMS Core v0.9 or greater; BMS module v0.9 or greater; phpBMS Scheduler activated through cron or other scheduling program."; ?>
/* eslint-disable <API key> */ export default function ({ client, filterQuery, mustContain, busy, encodeQueryAsString, }) { return { listUsers(query) { const params = filterQuery( query, 'text', 'limit', 'offset', 'sort', 'sortdir' ); return busy( client._.get('/user', { params, }) ); }, createUser(user) { const expected = [ 'login', 'email', 'firstName', 'lastName', 'password', 'admin', ]; const params = filterQuery(user, ...expected); const { missingKeys, promise } = mustContain(user, ...expected); return missingKeys ? promise : busy(client._.post(`/user${encodeQueryAsString(params)}`)); }, changePassword(old, newPassword) { const params = { old, new: newPassword, }; return busy(client._.put(`/user/password${encodeQueryAsString(params)}`)); }, resetPassword(email) { const params = { email, }; return busy( client._.delete('/user/password', { params, }) ); }, deleteUser(id) { return busy(client._.delete(`/user/${id}`)); }, getUser(id) { return busy(client._.get(`/user/${id}`)); }, updateUser(user) { const expected = ['email', 'firstName', 'lastName', '_id']; const params = filterQuery(user, ...expected.slice(0, 3)); // Remove '_id' const { missingKeys, promise } = mustContain(user, ...expected); return missingKeys ? promise : busy(client._.put(`/user/${user._id}${encodeQueryAsString(params)}`)); }, }; }
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <div id="container"></div> <script src="KineticJS/kinetic.js"></script> <script src="kiigame.js"></script> <script src="latkazombit.js"></script> </body> </html>
module.exports = (function () { var TypeChecker = Cactus.Util.TypeChecker; var JSON = Cactus.Util.JSON; var stringify = JSON.stringify; var object = Cactus.Addon.Object; var collection = Cactus.Data.Collection; var gettype = TypeChecker.gettype.bind(TypeChecker); return { "null and undefined" : function () { var o = new TypeChecker({ type : "number" }); exception(/Expected "number", but got undefined \(type "undefined"\)/, o.parse.bind(o, undefined)); exception(/Expected "number", but got null \(type "null"\)/, o.parse.bind(o, null)); }, "required values" : function () { var o = new TypeChecker({ required : false, type : "boolean" }); equal(true, o.parse(true)); o.parse(null); }, "default value" : function () { var o = new TypeChecker({ type : "number", defaultValue : 3 }); assert.eql(3, o.parse(null)); assert.eql(4, o.parse(4)); o = new TypeChecker({ type : { a : { type : "number", defaultValue : 1 } } }); var h = o.parse({ a : 2 }); assert.eql(2, o.parse({ a : 2}).a); assert.eql(1, o.parse({ a : null }).a); assert.eql(1, o.parse({}).a); o = new TypeChecker({ type : { x : { type : "boolean", defaultValue : false } } }); eql({ x : true }, o.parse({ x : true })); eql({ x : false }, o.parse({ x : false })); eql({ x : false }, o.parse({})); // When not passing bool properties. o = new TypeChecker({ type : { b : { type : "boolean", defaultValue : false } } }); eql({ b : false }, o.parse({})); // Default values with incorrect types should have special error message (always throw error) exception(/Expected "boolean", but got 1/, function () { return new TypeChecker({ type : "boolean", defaultValue : 1 }); }); }, defaultValueFunc : function () { var o = new TypeChecker({ defaultValueFunc : function () { return 1; }, type : "number" }); assert.strictEqual(1, o.parse(null)); o = new TypeChecker({ type : { a : { defaultValueFunc : function () { return 2; }, type : "number" } } }); assert.strictEqual(2, o.parse({ a : null }).a); assert.strictEqual(2, o.parse({}).a); // defaultValueFunc return value must match type. exception(/expected "boolean", but got 1/i, function () { return new TypeChecker({ defaultValueFunc : function () { return 1; }, type : "boolean" }).parse(undefined); }); exception(/expected "boolean", but got 1/i, function () { return new TypeChecker({ type : { a : { defaultValueFunc : function () { return 1; }, type : "boolean" } } }).parse({}); }); }, validators : function () { var o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > 0; } }] }); o.parse(1); o.parse(0, false); eql({ "" : ["Validation failed: got 0."] }, o.getErrors()); // Validation error message. o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > 0; }, message : "Expected positive number." }] }); o.parse(1); exception(/TypeChecker: Error: Expected positive number./, o.parse.bind(o, 0)); eql({ "" : ["Expected positive number."] }, o.getErrors()); // Multiple ordered validators. o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > -1; }, message : "Expected number bigger than -1." }, { func : function (v) { return v < 1; }, message : "Expected number smaller than 1." }] }); o.parse(0); exception(/Expected number bigger than -1/i, o.parse.bind(o, -1)); exception(/Expected number smaller than 1/i, o.parse.bind(o, 1)); o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > 0; }, message : "Expected number bigger than 0." }, { func : function (v) { return v > 1; }, message : "Expected number bigger than 1." }] }); o.parse(2); exception(/bigger than 0.+ bigger than 1./i, o.parse.bind(o, 0)); }, "simple interface" : function () { var o = TypeChecker.simple("number"); o.parse(1); o = TypeChecker.simple(["number"]); o.parse([1]); o = TypeChecker.simple({ a : "number", b : "boolean" }); o.parse({ a : 1, b : true }); o = TypeChecker.simple({ a : ["number"] }); o.parse({ a : [1] }); o = TypeChecker.simple({ a : { b : "boolean" } }); o.parse({ a : { b : true } }); // Classes. Class("X"); o = TypeChecker.simple({ _type : X }); o.parse(new X()); o = TypeChecker.simple({ a : { _type : X } }); o.parse({ a : new X() }); }, errorHash : function () { var o = TypeChecker.simple("string"); exception(/Nothing parsed/i, o.hasErrors.bind(o)); exception(/Nothing parsed/i, o.getErrors.bind(o)); o.parse("x", false); exception(/No errors exist/, o.getErrors.bind(o)); o.parse(1, false); ok(o.hasErrors()); var errors = o.getErrors(); ok(o.hasErrorsFor("")); not(o.hasErrorsFor("foo")); eql({ "" : ['Expected "string", but got 1 (type "number")'] }, o.getErrors()); o = TypeChecker.simple({ a : "number", b : "number" }); o.parse({ a : "x", b : true }, false); ok(o.hasErrors()); eql({ a : ['Expected "number", but got "x" (type "string")'], b : ['Expected "number", but got true (type "boolean")'] }, o.getErrors()); ok(o.hasErrorsFor("a")); ok(o.hasErrorsFor("b")); eql(['Expected "number", but got "x" (type "string")'], o.getErrorsFor("a")); eql(['Expected "number", but got true (type "boolean")'], o.getErrorsFor("b")); o = new TypeChecker({ type : "number", validators : [{ func : Function.returning(false), message : "false" }] }); o.parse(1, false); eql({ "" : ["false"] }, o.getErrors()); // Errors for array validators. o = new TypeChecker({ type : { p : { type : "string", validators : [{ func : Function.returning(false), message : "Error }, { func : Function.returning(false), message : "Error }] } } }); o.parse({ p : "" }, false); eql({ p : ["Error #1.", "Error #2."] }, o.getErrors()); // When Error is thrown, there should be a hash property with the error // messages as well. o = new TypeChecker({ type : "string" }); o.parse(1, false); assert.throws(o.parse.bind(o, 1), function (e) { assert.ok(/expected "string".+got 1 \(type "number"\)/i.test(e.message)); assert.ok("hash" in e, "Missing hash property"); eql({ "" : ['Expected "string", but got 1 (type "number")'] }, e.hash); return true; }); }, validators2 : function () { // Validators should run only if all other validations pass. var ran = false; var o = new TypeChecker({ type : "number", defaultValue : 0, validators : [{ func : function (v) { ran = true; return v === 0; }, message : "Only way to validate is to send null or 0." }] }); o.parse(0); o.parse("x", false); eql({ "" : [ 'Expected "number", but got "x" (type "string")', 'Only way to validate is to send null or 0.' ] }, o.getErrors()); // Do not run validators if constraints fail. o.parse("x", false); assert.strictEqual(1, object.count(o.getErrors())); o.parse(-1, false); eql({ "" : ["Only way to validate is to send null or 0."] }, o.getErrors()); // Default value should be applied before validation as well. ran = false; assert.strictEqual(0, o.parse(null)); assert.ok(ran, "Validation did not run."); }, "predefined validations" : function () { var o = new TypeChecker({ type : "number", validators : ["natural"] }); o.parse(1); o.parse(0); o.parse(-1, false); eql({ "" : ["Expected natural number."] }, o.getErrors()); o = new TypeChecker({ type : "number", validators : ["positive"] }); o.parse(1); o.parse(0, false); eql({ "" : ["Expected positive number."] }, o.getErrors()); o = new TypeChecker({ type : "number", validators : ["negative"] }); o.parse(-1); o.parse(0, false); eql({ "" : ["Expected negative number."] }, o.getErrors()); o = new TypeChecker({ type : "number", validators : ["x"] }); exception(/Undefined built in validator "x"/i, o.parse.bind(o, 1)); o = new TypeChecker({ type : { a : { type : "number", validators : ["x"] } } }); exception(/Undefined built in validator "x"/i, o.parse.bind(o, { a : 1 })); o = new TypeChecker({ type : "string", validators : ["non empty string"] }); o.parse("x"); o.parse("", false); eql({ "" : ["Expected non-empty string."] }, o.getErrors()); }, T_Array : function () { eql([{ type : "string" }], gettype(new TypeChecker.types.T_Array({ type : "string" }))); var o = new TypeChecker({ type : [{ type : "number" }] }); eql([1, 2], o.parse([1, 2])); eql([], o.parse([])); exception(/Expected \[\{"type":"number"\}\], but got "a" \(type "string"\)/i, o.parse.bind(o, "a")); exception(/error in property "0": expected "number", but got "a" \(type "string"\)/i, o.parse.bind(o, ["a"])); exception(/error in property "1": expected "number", but got true \(type "boolean"\)/i, o.parse.bind(o, [1, true])); exception(/error in property "0": expected "number", but got "a"[\s\S]+error in property "1": expected "number", but got true/i, o.parse.bind(o, ["a", true])); // Nesting of arrays. var o = new TypeChecker({ type : [{ type : [{ type : "number" }] }] }); eql([[1, 2]], o.parse([[1, 2]])); exception(/^TypeChecker: Error in property "0": expected \[\{"type":"number"\}\], but got 1/i, o.parse.bind(o, [1, [2, 3]])); exception(/^TypeChecker: Error in property "1.1": expected "number", but got true/i, o.parse.bind(o, [[1], [2, true]])); eql([[]], o.parse([[]])); eql([], o.parse([])); // Optional arrays. o = new TypeChecker({ type : [{ type : "mixed" }], defaultValue : [] }); o.parse(null); // Optional array in hash. o = new TypeChecker({ type : { a : { type : [{ type : "number" }], defaultValue : [] } } }); o.parse({}); }, T_Primitive : function () { var o = new TypeChecker({ type : "string" }); assert.eql("aoeu", o.parse("aoeu")); exception(/expected "string", but got 1 \(type "number"\)/i, o.parse.bind(o, 1)); exception(/expected "string", but got true \(type "boolean"\)/i, o.parse.bind(o, true)); o = new TypeChecker({ type : "number" }); assert.eql(100, o.parse(100)); exception(/^TypeChecker: Error: Expected "number", but got "1" \(type "string"\)$/, o.parse.bind(o, "1")); // Default values o = new TypeChecker({ type : "boolean", defaultValue : false }); o.parse(true); o.parse(false); not(o.parse(null)); }, T_Enumerable : function () { var o = new TypeChecker({ enumerable : [1,2,3] }); eql(1, o.parse(1)); o.parse(2); o.parse(3); exception(/^TypeChecker: Error: Expected a value in \[1,2,3\], but got 0$/, o.parse.bind(o, 0)); exception(/^TypeChecker: Error: Expected a value in \[1,2,3\], but got 4$/, o.parse.bind(o, 4)); eql({ enumerable : [1,2,3] }, gettype(new TypeChecker.types.T_Enumerable([1, 2, 3]))); }, "T_Union" : function () { var o = new TypeChecker({ union : ["string", "number"] }); eql(1, o.parse(1)); eql("x", o.parse("x")); exception(/Expected a Union/, o.parse.bind(o, true)); eql({ union : [ { type : "string"}, { type : "number" } ]}, gettype(new TypeChecker.types.T_Union([ { type : "string" }, { type : "number" } ]))); }, "T_Instance" : function () { var Foo2 = Class("Foo2", {}); Class("Bar", { isa : Foo2 }); var o = new TypeChecker({ type : Foo2 }); var foo2 = new Foo2(); equal(foo2, o.parse(foo2)); o.parse(new Bar()); exception(/Expected an instance of "Foo2", but got value <1> \(type "number"\)/, o.parse.bind(o, 1)); Class("Baz"); exception(/Expected an instance of "Foo2", but got value <a Baz> \(type "Baz"\)$/, o.parse.bind(o, new Baz())); // Non-Joose classes. function Bax() { } function Qux() { } Qux.extend(Bax); o = new TypeChecker({ type : Bax }); o.parse(new Bax()); o.parse(new Qux()); function Qax() { } Qax.prototype.toString = function () { return "my Qax"; }; exception(/Expected an instance of "Bax", but got value <1> \(type "number"\)/, o.parse.bind(o, 1)); exception(/Expected an instance of "Bax", but got value <my Qax> \(type "Qax"\)$/, o.parse.bind(o, new Qax())); // Anonymous classes. var F = function () {}; var G = function () {}; o = new TypeChecker({ type : F }); G.extend(F); o.parse(new F()); o.parse(new G()); var H = function () {}; H.prototype.toString = Function.returning("my H"); exception(/Expected an instance of "anonymous type", but got value <1>/, o.parse.bind(o, 1)); exception(/Expected an instance of "anonymous type", but got value <my H> \(type "anonymous type"\)/i, o.parse.bind(o, new H())); function I() {} equal(I, gettype(new TypeChecker.types.T_Instance(I)).type); }, T_Hash : function () { var o = new TypeChecker({ x : { type : "boolean" } }); eql({ x : { type : "boolean" } }, gettype(new TypeChecker.types.T_Hash({ x : { type : "boolean" } }))); o = new TypeChecker({ type : { a : { type : "number" }, b : { type : "boolean" } } }); eql({ a : 1, b : true }, o.parse({ a : 1, b : true })); o = new TypeChecker({ type : { a : { type : "number" }, b : { type : "boolean" } } }); exception(/Expected \{"a":\{"type":"number"\},"b":\{"type":"boolean"\}\}, but got 1/i, o.parse.bind(o, 1)); exception(/Error in property "a": expected "number", but got "2"/i, o.parse.bind(o, { a : "2", b : true })); exception(/Error in property "a": expected "number", but got "2"[\s\S]+Error in property "b": expected "boolean", but got "2"/i, o.parse.bind(o, { a : "2", b : "2" })); exception(/Error in property "b": Missing property/, o.parse.bind(o, { a : 1 })); exception(/Error in property "c": Property lacks definition/i, o.parse.bind(o, { a : 1, b : true, c : "1" })); // With required specified. o = new TypeChecker({ type : { name : { type : "string", required : true } } }); assert.throws(o.parse.bind(o, {}), function (e) { assert.ok(/"name": Missing property/.test(e.message)); return true; }); // Non-required properties. o = new TypeChecker({ type : { a : { type : "number", required : false }, b : { type : "boolean", required : false } } }); eql({ a : 1, b : false }, o.parse({ a : 1, b : false })); var h = o.parse({ a : 1, b : undefined }); ok(!("b" in h)); h = o.parse({ a : 1, b : null }); equal(null, h.b); h = o.parse({ a : undefined, b : undefined }); ok(object.isEmpty(h)); h = o.parse({}); ok(object.isEmpty(h)); // Skip properties not in definition. o = new TypeChecker({ allowUndefined : true, type : { a : { type : "number" } } }); o.parse({}, false); eql({ a : ["Missing property"] }, o.getErrors()); o.parse({ a : 1 }); o.parse({ a : 1, b : 2 }); o.parse({ b : 2 }, false); eql({ a : ["Missing property"] }, o.getErrors()); // Remove skipped props that are undefined. eql({ a : 1 }, o.parse({ a : 1 })); }, T_Map : function () { var o = new TypeChecker({ map : true, type : "number" }); eql({ a : 1, b : 1 }, o.parse({ a : 1, b : 1 })); o.parse({ a : 1, b : false }, false); eql({ b : ['Expected "number", but got false (type "boolean")'] }, o.getErrors()); }, "T_Mixed" : function () { var o = new TypeChecker({ type : "mixed" }); equal(true, o.parse(true)); o.parse(""); o.parse({}); eql([], o.parse([])); ok(null === o.parse(null)); ok(undefined === o.parse(undefined)); equal("mixed", gettype(new TypeChecker.types.T_Mixed())); }, "typeof" : function () { var t = TypeChecker.typeof.bind(TypeChecker); equal("number", t(1)); equal("boolean", t(true)); equal("undefined", t(undefined)); equal("null", t(null)); equal("Function", t(function () {})); equal("Object", t({})); equal("Array", t([])); Class("JooseClass"); equal("JooseClass", t(new JooseClass())); function MyClass() {} equal("MyClass", t(new MyClass())); var AnonymousClass = function () {}; equal("anonymous type", t(new AnonymousClass)); }, "BUILD errors" : function () { exception(/Must be a hash/i, function () { return new TypeChecker(); }); exception(/May only specify one of required, defaultValue and defaultValueFunc/i, function () { return new TypeChecker({ required : true, defaultValue : 1 }); }); // required or defaultValue or defaultValueFunc }, helpers : function () { //var tc = new TypeChecker({ // type : "number", // validators : [{ // func : function (o, helpers) { // return !!helpers; // message : "helpers == false" //tc.parse(1, true, true); //tc.parse(1, false, true); //eql({ // "" : ["helpers == false"] //}, tc.getErrors()); }, "recursive definition" : function () { var o = new TypeChecker({ type : { // type type : { required : false, type : "mixed", validators : [{ func : function (v) { if (typeof v === "string") { return collection.hasValue(["string", "number", "object", "function", "boolean", "mixed"], v); } else if (v instanceof Array) { // Flat check only. return v.length === 1; } else if (v instanceof Object) { // Flat check only. return true; } return false; } }] }, required : { type : "boolean", defaultValue : true }, defaultValue : { required : false, type : "mixed" }, defaultValueFunc : { required : false, type : Function }, validators : { type : [{ type : { func : { type : Function }, message : { type : "string" } } }], defaultValue : [] }, enumerable : { required : false, type : Array }, allowUndefined : { defaultValue : false, type : "boolean" } } }); o.parse({ type : "string" }); o.parse({ type : "number" }); o.parse({ required : false, type : "number" }); o.parse({ defaultValue : 3, type : "number" }); o.parse({ defaultValue : true, type : "boolean" }); o.parse({ defaultValue : 4, type : "mixed" }); o.parse({ defaultValue : {}, type : "mixed" }); o.parse({ defaultValueFunc : function () { return 1; }, type : "number" }); o.parse({ type : [{ type : "string" }] }); o.parse({ type : "mixed", validators : [{ func : Function.empty, message : "msg" }] }); o.parse({ type : "number", enumerable : [1,2,3] }); o.parse({ type : {} }); o.parse({ allowUndefined : true, type : {} }); } }; })();
<?php namespace common\models; use Yii; /** * This is the model class for table "mcp_accesslogs". * * @property integer $user_id * @property string $browser * @property string $ip * @property string $session * @property string $intime * @property string $outtime */ class McpAccesslogs extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'mcp_accesslogs'; } /** * @return \yii\db\Connection the database connection used by this AR class. */ public static function getDb() { return Yii::$app->get('oldcmsdb'); } /** * @inheritdoc */ public function rules() { return [ [['user_id'], 'integer'], [['intime', 'outtime'], 'safe'], [['browser'], 'string', 'max' => 255], [['ip'], 'string', 'max' => 30], [['session'], 'string', 'max' => 40] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'user_id' => 'user,s reference', 'browser' => 'Browser', 'ip' => 'Ip', 'session' => 'Session', 'intime' => 'Intime', 'outtime' => 'Outtime', ]; } }
/** * Swedish translation for bootstrap-wysihtml5 */ (function($){ $.fn.wysihtml5.locale["sv-SE"] = { font_styles: { normal: "Normal Text", h1: "Rubrik 1", h2: "Rubrik 2", h3: "Rubrik 3" }, emphasis: { bold: "Fet", italic: "Kursiv", underline: "Understruken" }, lists: { unordered: "Osorterad lista", ordered: "Sorterad lista", outdent: "Minska indrag", indent: "Öka indrag" }, link: { insert: "Lägg till länk", cancel: "Avbryt" }, image: { insert: "Lägg till Bild", cancel: "Avbryt" }, html: { edit: "Redigera HTML" }, colours: { black: "Svart", silver: "Silver", gray: "Grå", maroon: "Kastaniebrun", red: "Röd", purple: "Lila", green: "Grön", olive: "Olivgrön", navy: "Marinblå", blue: "Blå", orange: "Orange" } }; }(jQuery));
<?php namespace Tests\Unit; use Tests\TestCase; use Illuminate\Foundation\Testing\RefreshDatabase; class TextPostTest extends TestCase { use RefreshDatabase; protected $textPost; public function setup() { parent::setUp(); $this->authenticate(); $this->textPost = create('Knot\Models\TextPost', ['user_id' => auth()->id()]); } /** @test */ public function <API key>() { $this->assertInstanceOf('Knot\Models\User', $this->textPost->user); } /** @test */ public function <API key>() { $this->assertInstanceOf('Knot\Models\Post', $this->textPost->post); } }
// This example code is from the book: // Object-Oriented Programming with C++ and OSF/Motif // Douglas Young // Prentice Hall, 1992 // ISBN 0-13-630252-1 // any purpose except publication and without fee is hereby granted, provided // DialogManager.h: A base class for cached dialogs #ifndef DIALOGMANAGER_H #define DIALOGMANAGER_H #include "UIComponent.h" #include "DialogCallbackData.h" class DialogManager : public UIComponent { private: Widget getDialog(); static void <API key> ( Widget, XtPointer, XtPointer ); static void okCallback ( Widget, XtPointer, XtPointer ); static void cancelCallback ( Widget, XtPointer, XtPointer ); static void helpCallback ( Widget, XtPointer, XtPointer ); void cleanup ( Widget, DialogCallbackData* ); protected: // Called to get a new dialog virtual Widget createDialog ( Widget ) = 0; public: DialogManager ( const char * ); virtual Widget post ( const char *, void *clientData = NULL, DialogCallback ok = NULL, DialogCallback cancel = NULL, DialogCallback help = NULL ); }; #endif
<?php namespace Users; use Zend\EventManager\EventInterface as Event; use Users\Model\AuthorisationClass as AuthorisationClass; class Module { public function onBootstrap(Event $e) { // This method is called once the MVC bootstrapping is complete $application = $e->getApplication(); $services = $application->getServiceManager(); $e -> getApplication() -> getEventManager() -> getSharedManager() -> attach('Zend\Mvc\Controller\<API key>', 'dispatch', function($e) { $controller = $e -> getTarget(); $<API key> = $controller -> params('controller'); $id=0; if ($user = $controller -> identity()) { $role = $user -> getRoleName()->getName(); $id = $user->getId(); } else { $role = 'guest'; } $routeMatch = $e->getRouteMatch(); $checkId = $routeMatch->getParam('param0',0); $controllerClass = $routeMatch->getParam('controller',0); $<API key> = explode('\\', $controllerClass); $controllerName = $<API key>['2']; $moduleName = $<API key>['0']; $role = strtolower($role); $routeCheck = $moduleName.'\\'.$controllerName; $acl = new AuthorisationClass($id,$checkId); if (!$acl->isAuthorised($role,$routeCheck,$routeMatch->getParam('action'))) { $response = $e -> getResponse(); $response -> getHeaders() -> addHeaderLine('Location', '/users/auth/failure/Please log in as an authorised user to view that page'); $response -> setStatusCode(302); $response -> sendHeaders(); exit ; } }, 100); } public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getServiceConfig() { return array( 'factories' => array( 'Zend\Authentication\<API key> => function($serviceManager) { // If you are using DoctrineORMModule: return $serviceManager->get('doctrine.<API key>.orm_default'); // If you are using DoctrineODMModule: return $serviceManager->get('doctrine.<API key>.odm_default'); } ) ); } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } }
// RUN: %clang_builtins %s %librt -o %t && %run %t // The LLVM Compiler Infrastructure // This file tests __ctzti2 for the compiler_rt library. #include "int_lib.h" #include <stdio.h> #ifdef CRT_HAS_128BIT // Returns: the number of trailing 0-bits // Precondition: a != 0 COMPILER_RT_ABI si_int __ctzti2(ti_int a); int test__ctzti2(ti_int a, si_int expected) { si_int x = __ctzti2(a); if (x != expected) { twords at; at.all = a; printf("error in __ctzti2(0x%llX%.16llX) = %d, expected %d\n", at.s.high, at.s.low, x, expected); } return x != expected; } char assumption_1[sizeof(ti_int) == 2*sizeof(di_int)] = {0}; #endif int main() { #ifdef CRT_HAS_128BIT if (test__ctzti2(0x00000001, 0)) return 1; if (test__ctzti2(0x00000002, 1)) return 1; if (test__ctzti2(0x00000003, 0)) return 1; if (test__ctzti2(0x00000004, 2)) return 1; if (test__ctzti2(0x00000005, 0)) return 1; if (test__ctzti2(0x0000000A, 1)) return 1; if (test__ctzti2(0x10000000, 28)) return 1; if (test__ctzti2(0x20000000, 29)) return 1; if (test__ctzti2(0x60000000, 29)) return 1; if (test__ctzti2(0x80000000uLL, 31)) return 1; if (test__ctzti2(<API key>, 40)) return 1; if (test__ctzti2(<API key>, 43)) return 1; if (test__ctzti2(<API key>, 57)) return 1; if (test__ctzti2(<API key>, 63)) return 1; if (test__ctzti2(make_ti(<API key>, <API key>), 93)) return 1; if (test__ctzti2(make_ti(<API key>, <API key>), 124)) return 1; if (test__ctzti2(make_ti(<API key>, <API key>), 127)) return 1; #else printf("skipped\n"); #endif return 0; }
CREATE TABLE test_table(column_integer INTEGER, column_smallint SMALLINT, column_numeric_9_2 NUMERIC(9,2), column_char_9 CHAR(9), column_varchar_92 VARCHAR(92), column_date DATE, column_bit BIT(4), column_time TIME, column_timestamp TIMESTAMP, column_datetime datetime, monet monetary, big bigint, float_num float, double_num double, PRIMARY KEY (column_integer) ); INSERT INTO test_table VALUES(1, 11, 1.1, '1', '2/28/2001', '12/31/2002', NULL, '07:00:34 PM', '05:55:31 PM 05/04/2002', '05:55:31 PM 05/04/2000', 123.3, 4444444444444, 44.44, 44.44); select str_to_date(column_varchar_92, '%m/%d/%Y') from test_table where column_integer = 1; select str_to_date(123, '%m/%d/%Y'); select str_to_date('07:00:34 PM', '%r'); select str_to_date('07:00:34 PM', '% r'); select str_to_date('05:55:31 PM 05/04/2002', '%r %m/%d/%Y'); select str_to_date('07:00:34 PM', '0%%%q %r'); select str_to_date('Sat Jan 12 3rd', '%a %b %c %D'), str_to_date('Foo', '%a'), str_to_date('Bar', '%b'), str_to_date('-1', '%c'), str_to_date('-2nd', '%D'); select str_to_date('31 999999 21', '%e %f %H'), str_to_date('-4', '%d'), str_to_date('-3', '%e'), str_to_date('-1', '%f'), str_to_date('-2', '%H'); select str_to_date('11 11 311 11', '%I %i %j %k'), str_to_date('-1', '%i'), str_to_date('-1', '%I'), str_to_date('-1', '%j'), str_to_date('-2', '%k'); select str_to_date('11 am pm', '%l %p %p'), str_to_date('-1', '%l'), str_to_date('genaro', '%M'), str_to_date('-1', '%m'), str_to_date('gm', '%p'); select str_to_date('07 : 00 : 34 PM 07:00:34 AM 88', '%r %r %S'), str_to_date('-07:00:34 PM', '%r'), str_to_date('07:-01:34 PM', '%r'), str_to_date('07:00:-34 PM', '%r'); select str_to_date('07x00:34 PM', '%r'), str_to_date('07:01x34 PM', '%r'), str_to_date('07:00:34 gm', '%r'), str_to_date('-99', '%S'), str_to_date('-14', '%s'); select str_to_date('07 : 00 : 34 88 33', '%T %u %U'), str_to_date('-07:00:34', '%T'), str_to_date('07:-01:34', '%T'), str_to_date('07:00:-34', '%T'); select str_to_date('07x00:34', '%T'), str_to_date('07:01x34', '%T'), str_to_date('-99', '%u'), str_to_date('-14', '%U'); select str_to_date('12 12 Monday 0', '%v %V %W %w'), str_to_date('-1', '%v'), str_to_date('-1', '%V'), str_to_date('mandei', '%W'), str_to_date('-2', '%w'); select str_to_date('12 12 78 30 2000', '%x %X %y %y %Y'), str_to_date('-1', '%x'), str_to_date('-1', '%X'), str_to_date('-99', '%y'), str_to_date('-2', '%Y'); select str_to_date('23 am', '%H %p'); select str_to_date('0000', '%Y'); select str_to_date('13 2002', '%m %Y'); select str_to_date('32 2002', '%d %Y'); select str_to_date('04/2002', '%d/%Y'); select str_to_date('29 02 2001', '%d %m %Y'); select str_to_date('2001 54', '%Y %u'); select str_to_date('2001 54', '%x %v'); select str_to_date('2001 0', '%x %v'); select str_to_date('2001 0', '%X %V'); select str_to_date('2001 999', '%Y %j'); select str_to_date('2001 9', '%Y %w'); select str_to_date('23 am', '%h %p'); select str_to_date('70', '%i'); select str_to_date('70', '%s'); select str_to_date('1999 40 0', '%Y %u %w'); select str_to_date('1999 40 0', '%Y %U %w'); select str_to_date('1999 0 0', '%Y %U %w'); select str_to_date('1999 0 0', '%Y %u %w'); select str_to_date('1999 30 0', '%Y %u %w'); select str_to_date('1998 0 4', '%Y %u %w'); select str_to_date('1998 300', '%Y %j'); select str_to_date('1998 300 23:14:34', '%Y %j %T'); select str_to_date('2000 53 6', '%Y %U %w'); select str_to_date('2001 53 6', '%Y %U %w'); select str_to_date('2007 53 6', '%Y %U %w'); DROP TABLE test_table;
<?php /* @var $this yii\web\View */ $this->title = 'My Yii Application'; ?> <div class="bodyParser"> <?=$this->render('table', [ 'dataHistory' => $dataHistory ])?> </div>
/* * from: FreeBSD: src/sys/tools/fw_stub.awk,v 1.6 2007/03/02 11:42:53 flz */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: releng/9.3/sys/dev/cxgb/cxgb_t3fw.c 189643 2009-03-10 19:22:45Z gnn $"); #include <sys/param.h> #include <sys/errno.h> #include <sys/kernel.h> #include <sys/module.h> #include <sys/linker.h> #include <sys/firmware.h> #include <sys/systm.h> #include <cxgb_t3fw.h> #include <t3b_protocol_sram.h> #include <t3b_tp_eeprom.h> #include <t3c_protocol_sram.h> #include <t3c_tp_eeprom.h> static int cxgb_t3fw_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3fw", t3fw, (size_t)t3fw_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3fw"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3fw_mod = { "cxgb_t3fw", cxgb_t3fw_modevent, 0 }; DECLARE_MODULE(cxgb_t3fw, cxgb_t3fw_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3fw, 1); MODULE_DEPEND(cxgb_t3fw, firmware, 1, 1, 1); static int <API key>(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("<API key>", t3b_protocol_sram, (size_t)<API key>, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("<API key>"); return (error); } return (EINVAL); } static moduledata_t <API key> = { "<API key>", <API key>, 0 }; DECLARE_MODULE(<API key>, <API key>, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(<API key>, 1); MODULE_DEPEND(<API key>, firmware, 1, 1, 1); static int <API key>(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3b_tp_eeprom", t3b_tp_eeprom, (size_t)<API key>, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3b_tp_eeprom"); return (error); } return (EINVAL); } static moduledata_t <API key> = { "cxgb_t3b_tp_eeprom", <API key>, 0 }; DECLARE_MODULE(cxgb_t3b_tp_eeprom, <API key>, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3b_tp_eeprom, 1); MODULE_DEPEND(cxgb_t3b_tp_eeprom, firmware, 1, 1, 1); static int <API key>(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("<API key>", t3c_protocol_sram, (size_t)<API key>, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("<API key>"); return (error); } return (EINVAL); } static moduledata_t <API key> = { "<API key>", <API key>, 0 }; DECLARE_MODULE(<API key>, <API key>, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(<API key>, 1); MODULE_DEPEND(<API key>, firmware, 1, 1, 1); static int <API key>(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3c_tp_eeprom", t3c_tp_eeprom, (size_t)<API key>, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3c_tp_eeprom"); return (error); } return (EINVAL); } static moduledata_t <API key> = { "cxgb_t3c_tp_eeprom", <API key>, 0 }; DECLARE_MODULE(cxgb_t3c_tp_eeprom, <API key>, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3c_tp_eeprom, 1); MODULE_DEPEND(cxgb_t3c_tp_eeprom, firmware, 1, 1, 1);
#!/usr/bin/python import json import os import subprocess import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import pynacl.platform python = sys.executable bash = '/bin/bash' echo = 'echo' BOT_ASSIGNMENT = { # Buildbots. 'xp-newlib-opt': python + ' buildbot\\buildbot_standard.py opt 32 newlib --no-gyp', 'xp-glibc-opt': python + ' buildbot\\buildbot_standard.py opt 32 glibc --no-gyp', 'xp-bare-newlib-opt': python + ' buildbot\\buildbot_standard.py opt 32 newlib --no-gyp', 'xp-bare-glibc-opt': python + ' buildbot\\buildbot_standard.py opt 32 glibc --no-gyp', '<API key>': python + ' buildbot/buildbot_standard.py opt 64 glibc --validator', # Clang. '<API key>': python + ' buildbot/buildbot_standard.py dbg 64 newlib --clang', 'mac10.7-newlib-dbg-clang': python + ' buildbot/buildbot_standard.py dbg 32 newlib --clang', # ASan. '<API key>': python + ' buildbot/buildbot_standard.py opt 64 newlib --asan', 'mac10.7-newlib-dbg-asan': python + ' buildbot/buildbot_standard.py opt 32 newlib --asan', # PNaCl. '<API key>': bash + ' buildbot/buildbot_pnacl.sh <API key>', '<API key>': bash + ' buildbot/buildbot_pnacl.sh <API key>', '<API key>': bash + ' buildbot/buildbot_pnacl.sh <API key>', '<API key>': bash + ' buildbot/buildbot_pnacl.sh <API key>', '<API key>': python + ' buildbot/buildbot_pnacl.py opt 32 pnacl', '<API key>': python + ' buildbot/buildbot_pnacl.py opt 64 pnacl', 'mac10.8-newlib-opt-pnacl': python + ' buildbot/buildbot_pnacl.py opt 32 pnacl', '<API key>': python + ' buildbot/buildbot_pnacl.py opt 64 pnacl', '<API key>': echo + ' "TODO(mseaborn): add mips"', # PNaCl Spec '<API key>': bash + ' buildbot/buildbot_spec2k.sh pnacl-arm-buildonly', '<API key>': bash + ' buildbot/buildbot_spec2k.sh pnacl-arm-hw', '<API key>': bash + ' buildbot/buildbot_spec2k.sh pnacl-x8632', '<API key>': bash + ' buildbot/buildbot_spec2k.sh pnacl-x8664', # NaCl Spec '<API key>': bash + ' buildbot/buildbot_spec2k.sh nacl-x8632', '<API key>': bash + ' buildbot/buildbot_spec2k.sh nacl-x8664', # Valgrind bots. '<API key>': echo + ' "Valgrind bots are disabled: see ' 'https://code.google.com/p/nativeclient/issues/detail?id=3158"', '<API key>': echo + ' "Valgrind bots are disabled: see ' 'https://code.google.com/p/nativeclient/issues/detail?id=3158"', # Coverage. 'mac10.6-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 64 newlib --coverage'), '<API key>': python + (' buildbot/buildbot_standard.py ' 'coverage 32 newlib --coverage'), '<API key>': python + (' buildbot/buildbot_standard.py ' 'coverage 64 newlib --coverage'), 'xp-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 32 newlib --coverage'), # Trybots. '<API key>': python + ' buildbot/buildbot_standard.py opt 64 glibc --validator', '<API key>': bash + ' buildbot/buildbot_valgrind.sh newlib', '<API key>': bash + ' buildbot/buildbot_valgrind.sh glibc', # Coverage trybots. 'nacl-mac10.6-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 64 newlib --coverage'), '<API key>': python + (' buildbot/buildbot_standard.py ' 'coverage 32 newlib --coverage'), '<API key>': python + (' buildbot/buildbot_standard.py ' 'coverage 64 newlib --coverage'), '<API key>': python + (' buildbot/buildbot_standard.py ' 'coverage 32 newlib --coverage'), # Clang trybots. '<API key>': python + ' buildbot/buildbot_standard.py dbg 64 newlib --clang', 'nacl-mac10.6-newlib-dbg-clang': python + ' buildbot/buildbot_standard.py dbg 32 newlib --clang', # Pnacl main trybots '<API key>': bash + ' buildbot/buildbot_pnacl.sh mode-trybot-qemu', '<API key>': python + ' buildbot/buildbot_pnacl.py opt 32 pnacl', '<API key>': python + ' buildbot/buildbot_pnacl.py opt 64 pnacl', '<API key>': echo + ' "TODO(mseaborn): add mips"', 'nacl-arm_opt_panda': bash + ' buildbot/buildbot_pnacl.sh <API key>', '<API key>': bash + ' buildbot/buildbot_pnacl.sh <API key>', 'nacl-mac10.8_newlib_opt_pnacl': python + ' buildbot/buildbot_pnacl.py opt 32 pnacl', '<API key>': python + ' buildbot/buildbot_pnacl.py opt 64 pnacl', # Pnacl spec2k trybots '<API key>': bash + ' buildbot/buildbot_spec2k.sh pnacl-trybot-x8632', '<API key>': bash + ' buildbot/buildbot_spec2k.sh pnacl-trybot-x8664', 'nacl-arm_perf_panda': bash + ' buildbot/buildbot_spec2k.sh <API key>', '<API key>': bash + ' buildbot/buildbot_spec2k.sh pnacl-trybot-arm-hw', # Toolchain glibc. 'precise64-glibc': bash + ' buildbot/<API key>.sh', 'mac-glibc': bash + ' buildbot/<API key>.sh', 'win7-glibc': 'buildbot\\<API key>.bat', # Toolchain newlib x86. 'win7-toolchain_x86': 'buildbot\\<API key>.bat', 'mac-toolchain_x86': bash + ' buildbot/buildbot_toolchain.sh mac', '<API key>': bash + ' buildbot/buildbot_toolchain.sh linux', # Toolchain newlib arm. 'win7-toolchain_arm': python + ' buildbot/<API key>.py' ' toolchain_build' ' --buildbot', 'mac-toolchain_arm': python + ' buildbot/<API key>.py' ' toolchain_build' ' --buildbot', '<API key>': python + ' buildbot/<API key>.py' ' toolchain_build' ' --buildbot', # BIONIC toolchain builders. '<API key>': python + ' buildbot/<API key>.py' ' <API key>' ' --buildbot', # Pnacl toolchain builders. '<API key>': bash + ' buildbot/<API key>.sh', 'linux-pnacl-x86_32': python + ' buildbot/<API key>.py --buildbot', 'linux-pnacl-x86_64': python + ' buildbot/<API key>.py --buildbot', '<API key>': python + ' buildbot/<API key>.py --buildbot', '<API key>': python + ' buildbot/<API key>.py --buildbot', 'mac-pnacl-x86_32': python + ' buildbot/<API key>.py --buildbot', # TODO(robertm): Delete this once we are using win-pnacl-x86_64 'win-pnacl-x86_32': python + ' buildbot/<API key>.py --buildbot', # TODO(robertm): use this in favor or the misnamed win-pnacl-x86_32 'win-pnacl-x86_64': python + ' buildbot/<API key>.py --buildbot', # Pnacl toolchain testers '<API key>': bash + ' buildbot/<API key>.sh tc-test-bot x86-64', '<API key>': bash + ' buildbot/<API key>.sh tc-test-bot x86-32', '<API key>': bash + ' buildbot/<API key>.sh tc-test-bot arm', # MIPS toolchain buildbot. '<API key>': bash + ' buildbot/<API key>.sh', # Toolchain trybots. '<API key>': bash + ' buildbot/buildbot_toolchain.sh linux', '<API key>': bash + ' buildbot/buildbot_toolchain.sh mac', '<API key>': 'buildbot\\<API key>.bat', '<API key>': python + ' buildbot/<API key>.py' ' toolchain_build' ' --trybot', '<API key>': python + ' buildbot/<API key>.py' ' toolchain_build' ' --trybot', '<API key>': python + ' buildbot/<API key>.py' ' toolchain_build' ' --trybot', '<API key>': bash + ' buildbot/<API key>.sh', '<API key>': bash + ' buildbot/<API key>.sh', '<API key>': 'buildbot\\<API key>.bat', # Pnacl toolchain trybots. '<API key>': python + ' buildbot/<API key>.py --trybot', '<API key>': python + ' buildbot/<API key>.py --trybot', '<API key>': echo + ' "TODO(mseaborn)"', '<API key>': python + ' buildbot/<API key>.py --trybot', '<API key>': python + ' buildbot/<API key>.py --trybot', '<API key>': echo + ' "TODO(mseaborn)"', '<API key>': python + ' buildbot/<API key>.py --trybot', '<API key>': python + ' buildbot/<API key>.py --trybot', } special_for_arm = [ 'win7_64', 'win7-64', 'lucid-64', 'lucid64', 'precise-64', 'precise64' ] for platform in [ 'vista', 'win7', 'win8', 'win', 'mac10.6', 'mac10.7', 'mac10.8', 'lucid', 'precise'] + special_for_arm: if platform in special_for_arm: arch_variants = ['arm'] else: arch_variants = ['', '32', '64', 'arm'] for arch in arch_variants: arch_flags = '' real_arch = arch arch_part = '-' + arch # Disable GYP build for win32 bots and arm cross-builders. In this case # "win" means Windows XP, not Vista, Windows 7, etc. # Building via GYP always builds all toolchains by default, but the win32 # XP pnacl builds are pathologically slow (e.g. ~38 seconds per compile on # the <API key> trybot). There are other builders that test # Windows builds via gyp, so the reduced test coverage should be slight. if arch == 'arm' or (platform == 'win' and arch == '32'): arch_flags += ' --no-gyp' if arch == '': arch_part = '' real_arch = '32' # Test with Breakpad tools only on basic Linux builds. if sys.platform.startswith('linux'): arch_flags += ' --use-breakpad-tools' for mode in ['dbg', 'opt']: for libc in ['newlib', 'glibc']: # Buildbots. for bare in ['', '-bare']: name = platform + arch_part + bare + '-' + libc + '-' + mode assert name not in BOT_ASSIGNMENT, name BOT_ASSIGNMENT[name] = ( python + ' buildbot/buildbot_standard.py ' + mode + ' ' + real_arch + ' ' + libc + arch_flags) # Trybots for arch_sep in ['', '-', '_']: name = 'nacl-' + platform + arch_sep + arch + '_' + libc + '_' + mode assert name not in BOT_ASSIGNMENT, name BOT_ASSIGNMENT[name] = ( python + ' buildbot/buildbot_standard.py ' + mode + ' ' + real_arch + ' ' + libc + arch_flags) def EscapeJson(data): return '"' + json.dumps(data).replace('"', r'\"') + '"' def Main(): builder = os.environ.get('<API key>') build_number = os.environ.get('<API key>') slave_type = os.environ.get('BUILDBOT_SLAVE_TYPE') cmd = BOT_ASSIGNMENT.get(builder) if not cmd: sys.stderr.write('ERROR - unset/invalid builder name\n') sys.exit(1) env = os.environ.copy() # Don't write out .pyc files because in cases in which files move around or # the PYTHONPATH / sys.path change, old .pyc files can be mistakenly used. # This avoids the need for admin changes on the bots in this case. env['<API key>'] = '1' # Use .boto file from home-dir instead of buildbot supplied one. if 'AWS_CREDENTIAL_FILE' in env: del env['AWS_CREDENTIAL_FILE'] env['BOTO_CONFIG'] = os.path.expanduser('~/.boto') env['GSUTIL'] = '/b/build/third_party/gsutil/gsutil' # When running from cygwin, we sometimes want to use a native python. # The native python will use the depot_tools version by invoking python.bat. if pynacl.platform.IsWindows(): env['NATIVE_PYTHON'] = 'python.bat' else: env['NATIVE_PYTHON'] = 'python' if sys.platform == 'win32': # If the temp directory is not on the same drive as the working directory, # there can be random failures when cleaning up temp directories, so use # a directory on the current drive. Use __file__ here instead of os.getcwd() # because toolchain_main picks its working directories relative to __file__ filedrive, _ = os.path.splitdrive(__file__) tempdrive, _ = os.path.splitdrive(env['TEMP']) if tempdrive != filedrive: env['TEMP'] = filedrive + '\\temp' env['TMP'] = env['TEMP'] if not os.path.exists(env['TEMP']): os.mkdir(env['TEMP']) # Run through runtest.py to get upload of perf data. build_properties = { 'buildername': builder, 'mastername': 'client.nacl', 'buildnumber': str(build_number), } factory_properties = { 'perf_id': builder, 'show_perf_results': True, 'step_name': 'naclperf', # Seems unused, but is required. 'test_name': 'naclperf', # Really "Test Suite" } # Locate the buildbot build directory by relative path, as it's absolute # location varies by platform and configuration. buildbot_build_dir = os.path.join(* [os.pardir] * 4) runtest = os.path.join(buildbot_build_dir, 'scripts', 'slave', 'runtest.py') # For builds with an actual build number, require that the script is present # (i.e. that we're run from an actual buildbot). if build_number is not None and not os.path.exists(runtest): raise Exception('runtest.py script not found at: %s\n' % runtest) cmd_exe = cmd.split(' ')[0] cmd_exe_ext = os.path.splitext(cmd_exe)[1] # Do not wrap these types of builds with runtest.py: # - tryjobs # - commands beginning with 'echo ' # - batch files # - debug builders if not (slave_type == 'Trybot' or cmd_exe == echo or cmd_exe_ext == '.bat' or '-dbg' in builder): # Perf dashboards are now generated by output scraping that occurs in the # script runtest.py, which lives in the buildbot repository. # Non-trybot builds should be run through runtest, allowing it to upload # perf data if relevant. cmd = ' '.join([ python, runtest, '--build-dir=src/out', '--results-url=https://chromeperf.appspot.com', '--annotate=graphing', '--no-xvfb', # We provide our own xvfb invocation. '--factory-properties', EscapeJson(factory_properties), '--build-properties', EscapeJson(build_properties), cmd, ]) print "%s runs: %s\n" % (builder, cmd) retcode = subprocess.call(cmd, env=env, shell=True) sys.exit(retcode) if __name__ == '__main__': Main()
from contextlib import contextmanager from _pytest.python import FixtureRequest import mock from mock import Mock import pyramid.testing from webob.multidict import MultiDict import pyramid_swagger import pyramid_swagger.tween import pytest import simplejson from pyramid.config import Configurator from pyramid.interfaces import IRoutesMapper from pyramid.registry import Registry from pyramid.response import Response from pyramid.urldispatch import RoutesMapper from webtest import AppError from .request_test import test_app from pyramid_swagger.exceptions import <API key> from pyramid_swagger.ingest import <API key> from pyramid_swagger.ingest import <API key> from pyramid_swagger.tween import <API key> class <API key>(Exception): pass class <API key>(pyramid.testing.DummyRequest): """ pyramid.testing.DummyRequest doesn't support MultiDicts like the real pyramid.request.Request so this is the next best thing. """ def __init__(self, **kw): super(<API key>, self).__init__(**kw) self.GET = MultiDict(self.GET) # Make sure content_type attr exists is not passed in via **kw self.content_type = getattr(self, 'content_type', None) @contextmanager def validation_context(request, response=None): try: yield except Exception: raise <API key> validation_ctx_path = 'tests.acceptance.response_test.validation_context' def get_registry(settings): registry = Registry('testing') config = Configurator(registry=registry) if getattr(registry, 'settings', None) is None: config._set_settings(settings) registry.registerUtility(RoutesMapper(), IRoutesMapper) config.commit() return registry def get_swagger_schema(schema_dir='tests/sample_schemas/good_app/'): return <API key>( schema_dir, <API key>(schema_dir, False) ) def <API key>(request, response=None, **overrides): """ Acceptance testing helper for testing the validation tween with Swagger 1.2 responses. :param request: pytest fixture :param response: standard fixture by default """ def handler(request): return response or Response() settings = dict({ 'pyramid_swagger.swagger_versions': ['1.2'], 'pyramid_swagger.<API key>': False, 'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/'}, **overrides ) settings['pyramid_swagger.schema12'] = get_swagger_schema() settings['pyramid_swagger.schema20'] = None registry = get_registry(settings) # Let's make request validation a no-op so we can focus our tests. with mock.patch.object(pyramid_swagger.tween, 'validate_request'): <API key>(handler, registry)(request) def <API key>(): request = <API key>( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) # Omit the logging_info key from the response. If response validation # occurs, we'll fail it. response = Response( body=simplejson.dumps({'raw_response': 'foo'}), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(<API key>) as excinfo: <API key>(request, response=response) assert "'logging_info' is a required property" in str(excinfo.value) def <API key>(): request = <API key>( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) # Omit the logging_info key from the response. response = Response( body=simplejson.dumps({'raw_response': 'foo'}), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(<API key>) as excinfo: <API key>(request, response=response) assert "'logging_info' is a required property" in str(excinfo.value) def <API key>(): request = <API key>( method='GET', path='/sample/nonstring/{int_arg}/{float_arg}/{boolean_arg}', params={'required_arg': 'test'}, matchdict={'int_arg': '1', 'float_arg': '2.0', 'boolean_arg': 'true'}, ) response = Response( body=simplejson.dumps(None), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) <API key>(request, response=response) def <API key>(): request = <API key>( method='GET', path='/sample/nonstring/{int_arg}/{float_arg}/{boolean_arg}', params={'required_arg': 'test'}, matchdict={'int_arg': '1', 'float_arg': '2.0', 'boolean_arg': 'true'}, ) response = Response(body='{}') <API key>(request, response=response) def <API key>(): request = <API key>( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) response = Response( body=simplejson.dumps({ 'raw_response': 1.0, 'logging_info': {'foo': 'bar'} }), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(<API key>) as excinfo: <API key>(request, response=response) assert "1.0 is not of type 'string'" in str(excinfo.value) def <API key>(): request = <API key>( method='GET', path='/<API key>', ) response = Response( body=simplejson.dumps([{"enum_value": "bad_enum_value"}]), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(<API key>) as excinfo: <API key>(request, response=response) assert "is not one of ['good_enum_value']" in str(excinfo.value) def <API key>(): request = <API key>( method='GET', path='/<API key>', ) response = Response( body=simplejson.dumps([{"enum_value": "good_enum_value"}]), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) <API key>(request, response=response) def <API key>(): app = test_app( request=Mock(spec=FixtureRequest, param=['1.2']), **{'pyramid_swagger.<API key>': True} ) response = app.post_json('/sample', {'foo': 'test', 'bar': 'test'}) assert response.status_code == 200 def <API key>(): # FIXME(#64): This test is broken and doesn't check anything. app = test_app( request=Mock(spec=FixtureRequest, param=['1.2']), **{'pyramid_swagger.exclude_paths': [r'^/sample/?']} ) response = app.get( '/sample/path_arg1/resource', params={'required_arg': 'test'} ) assert response.status_code == 200 def <API key>(): """If path missing and validation is disabled we want to let something else handle the error. TestApp throws an AppError, but Pyramid would throw a HTTPNotFound exception. """ with pytest.raises(AppError): app = test_app( request=Mock(spec=FixtureRequest, param=['1.2']), **{'pyramid_swagger.<API key>': False} ) assert app.get('/this/path/doesnt/exist') def <API key>(): request = <API key>( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) # Omit the logging_info key from the response. response = Response( body=simplejson.dumps({'raw_response': 'foo'}), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(<API key>): <API key>( request, response=response, **{'pyramid_swagger.<API key>': validation_ctx_path} )
// Benchpress: A collection of micro-benchmarks. var allResults = [ ]; // F r a m e w o r k function Benchmark(string, run) { this.string = string; this.run = run; } // Run each benchmark for two seconds and count number of iterations. function time(benchmark) { var elapsed = 0; var start = new Date(); for (var n = 0; elapsed < 2000; n++) { benchmark.run(); elapsed = new Date() - start; } var usec = (elapsed * 1000) / n; allResults.push(usec); print('Time (' + benchmark.string + '): ' + Math.floor(usec) + ' us.'); } function error(string) { print(string); } // L o o p function loop() { var sum = 0; for (var i = 0; i < 200; i++) { for (var j = 0; j < 100; j++) { sum++; } } if (sum != 20000) error("Wrong result: " + sum + " should be: 20000"); } var Loop = new Benchmark("Loop", loop); // M a i n time(Loop); var logMean = 0; for (var i = 0; i < allResults.length; i++) logMean += Math.log(allResults[i]); logMean /= allResults.length; print("Geometric mean: " + Math.round(Math.pow(Math.E, logMean)) + " us.");
#!/usr/bin/perl # start in the directory with all the files $argc = @ARGV; # get the number of arguments if ($argc == 0 ) { print "<API key>.pl dir multi vic2odl_xsl odl2pds_xsl max \n"; print "prints a set of transcoder (jConvertIIO) commands to test .DAT and .VIC files \n"; print "Output goes to STDOUT. Redirect to a file to keep the output as a script or arg file.\n"; print "There are no command switches, just put the values on the command line. Order is important. \n"; print " dir - the input directory \n"; print " multi - {multi/single] create standalone java commands or a set to be executed from a file \n"; print "vic2odl_xsl - full path to the xsl script to convert vicar files to ODL (<API key>.xsl)\n"; print "odl2pds_xsl - full path to the xsl script to convert ODL files to PDS (<API key>.xsl)\n"; print "max - the maximum number fo files to process. \n"; print " (Optional argument) Useful to limit the number of comands generated for a large input directory\n"; print " If the multi option is used, redirect the output to a file. Use this file as the input file for the \n"; print " command: java -Xmx256m jpl.mipl.io.jConvertIIO arg=multi.txt \n"; } $outdir = $ARGV[0]; $multi = $ARGV[1]; $vic2odl_xsl = $ARGV[2]; $odl2pds_xsl = $ARGV[3]; if ($argc > 4) { $max = $ARGV[4]; # maximum number of files used } else { $max = 1000; } # cd /Volumes/bigraid/MSL_data/Sample_EDRS/5-9-2011/clean_data # cp *.VIC ../out_multi # cp *.VIC ../out_single # cd /Volumes/bigraid/MSL_data/Sample_EDRS/ # ~/bin/msl_Vic2ODL-PDS-jpg.pl /Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11 multi 11 > multi11.txt # ~/bin/msl_Vic2ODL-PDS-jpg.pl /Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11 single 11 > single11.txt # ~/bin/msl_Vic2ODL-PDS-jpg.pl /Volumes/bigraid/MSL_data/Sample_EDRS/5-9-2011/out_single single 1 > single1.txt # capture output to a file. execute each # sh single1.txt # sh single.txt # java -Xmx256m jpl.mipl.io.jConvertIIO arg=multi.txt # time sh single.txt # time java -Xmx256m jpl.mipl.io.jConvertIIO ARGFILE=multi.txt # 152.015u 30.504s 3:06.07 98.0% 0+0k 236+326io 918pf+0w # time sh single100.txt # 617.869u 87.299s 15:35.90 75.3% 0+0k 1+1171io 3267pf+0w chdir $outdir; print "#!/bin/sh \n"; $cwd = `pwd`; print "# $cwd \n"; # $debug = " debug=true xml=true "; $debug = " "; if ($multi =~ /^m/) { $java = ""; } else { $java = "java -Xmx256m jpl.mipl.io.jConvertIIO "; } $ct = 0; while (<*.DAT>) { $file = $_; ($base,$ext) = split(/[.]/,$file); $pds = sprintf ( "%s.%s", $base, "LBL"); # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11/<API key>.DAT out=/Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11/<API key>.lbl PDS_DETACHED_ONLY=true format=PDS PDS_LABEL_TYPE=PDS3 xsl=/eclipse_3.6_workspace/MSL_xsl/<API key>.xsl $xsl = "/eclipse_3.6_workspace/MSL_xsl/<API key>.xsl"; $xsl = $odl2pds_xsl; # other options: RI <API key>=true $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=PDS PDS_DETACHED_ONLY=true PDS_LABEL_TYPE=PDS3 xsl=%s ", $java, $outdir, $file, $outdir, $pds, $debug, $xsl); print "$cmd \n"; } $ct=0; while (<*.VIC>) { $file = $_; $vic = $file; ($base,$ext) = split(/[.]/,$file); $odl = sprintf ( "%s.%s", $base, "IMG"); $pds = sprintf ( "%s.%s", $base, "LBL"); $vic_jpg = sprintf ( "%s_vic.%s", $base, "jpg"); $odl_tif = sprintf ( "%s_odl.%s", $base, "tif"); # VIC to ODL # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/<API key>.VIC out=/Users/slevoe/MSL/Sample_EDRS/out_ODL/<API key>.ODL format=PDS ADD_BLOB=true RI EMBED PDS_LABEL_TYPE=ODL3 xsl=/eclipse_3.6_workspace/MSL_xsl/<API key>.xsl $xsl = "/eclipse_3.6_workspace/MSL_xsl/<API key>.xsl"; $xsl = $vic2odl_xsl; $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=PDS ADD_BLOB=true RI EMBED PDS_LABEL_TYPE=ODL3 xsl=%s ", $java, $outdir, $vic, $outdir, $odl, $debug, $xsl); print "$cmd \n"; # system($cmd); # $cmd = sprintf("~/bin/getPdsLabel.pl %s/%s ", $outdir, $odl); # print "$cmd \n"; # ODL - PDS detached # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/out-ODL-PDS_Libs/<API key>.DAT out=/Users/slevoe/MSL/Sample_EDRS/out-ODL-PDS_Libs/<API key>.PDS <API key>=true xml=true debug=true PDS_DETACHED_ONLY=true format=pds PDS_LABEL_TYPE=PDS3 xsl=/eclipse_3.6_workspace/MSL_xsl/<API key>.xsl $xsl = "/eclipse_3.6_workspace/MSL_xsl/<API key>.xsl"; $xsl = $odl2pds_xsl; # other options: RI <API key>=true $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=PDS PDS_DETACHED_ONLY=true PDS_LABEL_TYPE=PDS3 xsl=%s ", $java, $outdir, $odl, $outdir, $pds, $debug, $xsl); print "$cmd \n"; # ODL to tif # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/<API key>.ODL out=/Users/slevoe/MSL/Sample_EDRS/<API key>.jpg 2RGB format=jpg RI OFORM=byte $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=tif RI OFORM=byte ", $java, $outdir, $odl, $outdir, $odl_tif, $debug); print "$cmd \n"; # Vicar to jpg # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/<API key>.VIC out=/Users/slevoe/MSL/Sample_EDRS/<API key>.jpg format=tif RI OFORM=byte $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=jpg RI 2RGB OFORM=byte ", $java, $outdir, $vic, $outdir, $vic_jpg, $debug); print "$cmd \n\n"; $ct++; if($ct >= $max) { exit; } }
#include <stdio.h> #include <stdlib.h> int GO_fputc(int c, GO_FILE *stream) { if (stream->p >= stream->p1) abort(); *stream->p++ = c; /* GOL_debuglog(1, &c); */ return (unsigned char) c; }
import ghcnpy # Provide introduction ghcnpy.intro() # Print Latest Version ghcnpy.get_ghcnd_version() # Testing Search Capabilities print("\nTESTING SEARCH CAPABILITIES") ghcnpy.find_station("Asheville") # Testing Search Capabilities print("\nTESTING PULL CAPABILITIES") outfile=ghcnpy.get_data_station("USW00003812") print(outfile," has been downloaded")
{% extends 'magicflatpages/base_content.html' %} {% load floppyforms %} {% block js_top %} {{ block.super }} {{ form.media }} {% endblock %} {% block navbar %} {% endblock navbar %} {% block footer_area %} {% endblock footer_area %} {% block content %} <div class="popup-content"> <div class="row"> <div class="col-sm-2"> <div class="side-fix-menus"> <ul class="nav nav-pills nav-stacked" id="nav-elements"> <li role="presentation" class="active"> <a href="#" id="goto-title">Page<br/><i class="fa fa-minus"></i></a> </li> </ul> </div> </div> <div class="col-lg-9"> <h1><small>Page {{ object.title }} details</h1> <form method='post' enctype="multipart/form-data">{% csrf_token %} {{ form }} <div class="bottom-fix-menu" align="center"> <h1> <input type="submit" class="btn btn-lg btn-success" value="Save" /> <a href="{% url 'magiccontent.windows_close' %}?dont_reload=1" class="btn btn-lg btn-danger" role="button" >Cancel</a> </h1> </div> </form> <br/><br/><br/><br/> </div> </div> </div> {% endblock content %} {% block post_content %}{% endblock post_content %} {% block extrajs %} <script type="text/javascript"> // hide the picture filters when there is no picture $(document).ready(function(){ $("#id_url").prop('readonly', true); }); </script> {% endblock extrajs %}
#ifndef XML_DO_READ_H #define XML_DO_READ_H class TranslationUnit; class StringTable; TranslationUnit *xmlDoRead(StringTable &strTable, char const *inputFname); #endif // XML_DO_READ_H
'use strict'; myApp.controller('<API key>', ['$scope', '$state', 'loadingMaskService', 'CONSTANTS', '$uibModal', '$log', '$rootScope', '$http', function ($scope, $state, loadingMaskService, CONSTANTS, $uibModal, $log, $rootScope, $http) { var userInfo = JSON.parse(localStorage.getItem(CONSTANTS.LOCAL_STORAGE_KEY)); $scope.email = userInfo.email; $scope.date = userInfo.birthDate; $scope.firstName = userInfo.firstName; $scope.lastName = userInfo.lastName; $scope.relations = userInfo.relations; $scope.relationOptions = ['Мама', 'Отец', 'Брат']; $scope.submit = function () { if ($scope.editProfileForm.$valid && $scope.editProfileForm.$dirty) { // if form is valid var userInfo = { email: $scope.email, birthDate: $scope.date, firstName: $scope.firstName, lastName: $scope.lastName, relations: $scope.relations }; $http({ method: 'POST', url: '/editRelation', data: { email: userInfo.email, relations: $scope.relations } }).then(function successCallback(response) { localStorage.setItem(CONSTANTS.LOCAL_STORAGE_KEY, JSON.stringify(userInfo)); loadingMaskService.sendRequest(); $state.go('mainPageState.userProfile'); }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. }); } }; $rootScope.$on('relationsUpdated', function(event, relations){ $scope.relations = relations; }); $rootScope.$on('relationRemoved', function(event, relations){ $scope.relations = relations; }); $scope.removeRelation = function(index) { var modalInstance = $uibModal.open({ templateUrl: 'app/pages/src/editProfilePage/src/tpl/<API key>.tpl.html', controller: '<API key>', resolve: { index: function () { return index } } }); } $scope.open = function (size) { var modalInstance = $uibModal.open({ templateUrl: 'app/pages/src/editProfilePage/src/tpl/addARelation.tpl.html', controller: '<API key>' }); }; }]);
<?php $deleteStyle = isset($this->existing) ? 'inline' : 'none' ?> <?php $addStyle = $deleteStyle == 'inline' ? 'none' : 'inline' ?> <div id="watch-controls"> </div> <h2><?php $this->o($this->notes[0]->title);?></h2> <?php $note = null; ?> <?php foreach ($this->notes as $note): ?> <div class="note"> <div class="note-header"> <form class="inline right" method="post" action="<?php echo build_url('note', 'delete')?>" onsubmit="return confirm('Are you sure?')"> <input type="hidden" value="<?php echo $note->id?>" name="id" /> <input title="Delete" type="image" src="<?php echo resource('images/delete.png')?>" /> </form> <h4><?php $this->o($note->title)?></h4> <span class="note-by">By <?php $this->o($note->userid.' on '.$note->created)?></span> </div> <div class="note-body"><?php $this->bbCode($note->note);?></div> </div> <?php endforeach; ?> <div class="note"> <form method="post" action="<?php echo build_url('note', 'add');?>"> <input type="hidden" value="<?php echo $note->attachedtotype?>" name="attachedtotype"/> <input type="hidden" value="<?php echo $note->attachedtoid?>" name="attachedtoid"/> <input type="hidden" value="<?php echo za()->getUser()->getUsername()?>" name="userid"/> <p> <label for="note-title">Title:</label> <input class="input" type="text" name="title" id="note-title" value="Re: <?php $this->o(str_replace('Re: ', '', $note->title))?>" /> </p> <p> <label for="note-note">Note:</label> <textarea name="note" rows="5" cols="45" id="note-note"></textarea> </p> <p> <input type="submit" class="abutton" value="Add Note" /> <a class="abutton" style="display: <?php echo $deleteStyle?>;" id="delete-watch" href="#" onclick="$.get('<?php echo build_url('note', 'deletewatch')?>', {id:'<?php echo $this->itemid?>', type:'<?php echo $this->itemtype?>'}, function() {$('#delete-watch').hide();$('#add-watch').show(); }); return false;">Remove Watch</a> <a class="abutton" style="display: <?php echo $addStyle?>;" id="add-watch" href="#" onclick="$.get('<?php echo build_url('note', 'addwatch')?>', {id:'<?php echo $this->itemid?>', type:'<?php echo $this->itemtype?>'}, function() {$('#add-watch').hide();$('#delete-watch').show(); }); return false;">Add Watch</a> </p> </form> </div>
YUI.add('master', function(Y, NAME) { /** * The master module. * * @module master */ var DIMENSIONS = { device: 'smartphone', region: 'CA', skin : 'grey' }; /** * Constructor for the Controller class. * * @class Controller * @constructor */ Y.mojito.controllers[NAME] = { init: function(config) { this.config = config; }, /** * Method corresponding to the 'index' action. * * @param ac {Object} The ActionContext that provides access * to the Mojito API. */ index: function(ac) { var dims = ac.params.getFromUrl(), self = this, config = { view: 'index', children: { primary: { type: 'primary', action: 'index' }, secondary: { type: 'secondary', action: 'index' } } }; ac.composite.execute(config, function (data, meta) { data.buttons = self.createButtons(ac, dims); ac.done(data, meta); }); }, createButtons: function (ac, dims) { var buttons = [], className, label, url; Y.each(Y.Object.keys(DIMENSIONS), function (dim) { var params = Y.merge({}, dims); className = 'nav nav-' + dim + (dims[dim] ? ' active' : ''); params[dim] ? delete params[dim] : params[dim] = DIMENSIONS[dim]; url = ac.url.make('htmlframe', 'index', null, 'GET', params); label = dim.substring(0,1).toUpperCase() + dim.substring(1); buttons.push('<a href="'+url+'" class="'+className+'">'+label+'</a>'); }); return buttons.join('\n'); } }; }, '0.0.1', {requires: ['mojito', 'mojito-assets-addon']});
/** * \file PancakeNode.hpp * * * * \author eaburns * \date 18-01-2010 */ #include "search/Node.hpp" #include "pancake/PancakeTypes.hpp" #include "pancake/PancakeState.hpp" #if !defined(_PANCAKE_NODE_H_) #define _PANCAKE_NODE_H_ typedef Node<PancakeState14, PancakeCost> PancakeNode14; #endif // !_PANCAKE_NODE_H_
//Cortex //modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of Cortex nor the // names of its contributors may be used to endorse or promote products //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 Joshua Scoggins 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. using System; using System.Collections.Generic; using System.Runtime; using System.Text; using System.Text.RegularExpressions; using System.Reflection; using System.IO; using System.Linq; namespace Cortex.Operation { public class GraphVizLink : IGraphLink { private int from, to; private string label; public int From { get { return from; } } public int To { get { return to; } } public string Label { get { return label; } } public GraphVizLink(int from, int to, string label) { this.from = from; this.to = to; this.label = label; } public override string ToString() { if(label.Equals(string.Empty)) return string.Format("node{0} -> node{1};", From, To); else return string.Format("node{0} -> node{1} {2};", From, To, Label); } } public class <API key> : GraphBuilder<GraphVizLink> { public <API key>() : base() { } public override void Link(int i0, int i1, string label) { Add(new GraphVizLink(i0,i1,label)); } public override string ToString(string graphName) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("digraph {0}\n",graphName); sb.AppendLine("{"); foreach(var v in this) sb.AppendLine(v.ToString()); sb.AppendLine("}"); return sb.ToString(); } } }
#include "mitkPluginActivator.h" #include "DicomEventHandler.h" #include <service/event/ctkEventConstants.h> #include <ctkDictionary.h> #include <mitkLogMacros.h> #include <mitkDataNode.h> #include <<API key>.h> #include <service/event/ctkEventAdmin.h> #include <ctkServiceReference.h> #include <<API key>.h> #include <QVector> #include "mitkImage.h" #include <mitkContourModelSet.h> #include <<API key>.h> #include <<API key>.h> #include <mitkDICOMEnums.h> #include <<API key>.h> #include <mitkDICOMProperty.h> #include <<API key>.h> #include "<API key>.h" #include <<API key>.h> #include <<API key>.h> #include <<API key>.h> #include <mitkRTConstants.h> #include <<API key>.h> #include <<API key>.h> #include <<API key>.h> #include <<API key>.h> #include <mitkRTUIConstants.h> #include <<API key>.h> #include <mitkDoseNodeHelper.h> #include <vtkSmartPointer.h> #include <vtkMath.h> #include <<API key>.h> #include <<API key>.h> #include <<API key>.h> #include <mitkLocaleSwitch.h> #include <mitkIOUtil.h> #include <<API key>.h> #include <berryIPreferences.h> #include <berryPlatform.h> #include <ImporterUtil.h> DicomEventHandler::DicomEventHandler() { } DicomEventHandler::~DicomEventHandler() { } void DicomEventHandler::<API key>(const ctkEvent& ctkEvent) { QStringList <API key>; <API key> = ctkEvent.getProperty("FilesForSeries").toStringList(); if (!<API key>.isEmpty()) { //for rt data, if the modality tag isn't defined or is "CT" the image is handled like before if(ctkEvent.containsProperty("Modality") && (ctkEvent.getProperty("Modality").toString().compare("RTDOSE",Qt::CaseInsensitive) == 0 || ctkEvent.getProperty("Modality").toString().compare("RTSTRUCT",Qt::CaseInsensitive) == 0 || ctkEvent.getProperty("Modality").toString().compare("RTPLAN", Qt::CaseInsensitive) == 0)) { QString modality = ctkEvent.getProperty("Modality").toString(); if(modality.compare("RTDOSE",Qt::CaseInsensitive) == 0) { auto doseReader = mitk::RTDoseReaderService(); doseReader.SetInput(ImporterUtil::getUTF8String(<API key>.front())); std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = doseReader.Read(); if (!readerOutput.empty()){ mitk::Image::Pointer doseImage = dynamic_cast<mitk::Image*>(readerOutput.at(0).GetPointer()); mitk::DataNode::Pointer doseImageNode = mitk::DataNode::New(); doseImageNode->SetData(doseImage); doseImageNode->SetName("RTDose"); if (doseImage != nullptr) { std::string sopUID; if (mitk::<API key>(0x0008, 0x0016, "dicomseriesreader.SOPClassUID", doseImage->GetPropertyList(), sopUID)) { doseImageNode->SetName(sopUID); }; berry::IPreferencesService* prefService = berry::Platform::<API key>(); berry::IPreferences::Pointer prefNode = prefService-><API key>()->Node(mitk::RTUIConstants::<API key>.c_str()); if (prefNode.IsNull()) { mitkThrow() << "Error in preference interface. Cannot find preset node under given name. Name: " << prefNode->ToString().toStdString(); } //set some specific colorwash and isoline properties bool showColorWashGlobal = prefNode->GetBool(mitk::RTUIConstants::<API key>.c_str(), true); //Set reference dose property double referenceDose = prefNode->GetDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID.c_str(), mitk::RTUIConstants::<API key>); mitk::<API key>(doseImageNode, mitk::<API key>(), referenceDose, showColorWashGlobal); ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService-><API key>().GetPointer()->GetDataStorage(); dataStorage->Add(doseImageNode); mitk::RenderingManager::GetInstance()-><API key>(dataStorage); } }//END DOSE } else if(modality.compare("RTSTRUCT",Qt::CaseInsensitive) == 0) { auto structReader = mitk::<API key>(); structReader.SetInput(ImporterUtil::getUTF8String(<API key>.front())); std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = structReader.Read(); if (readerOutput.empty()){ MITK_ERROR << "No structure sets were created" << endl; } else { std::vector<mitk::DataNode::Pointer> modelVector; ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService-><API key>().GetPointer()->GetDataStorage(); for (const auto& aStruct : readerOutput){ mitk::ContourModelSet::Pointer countourModelSet = dynamic_cast<mitk::ContourModelSet*>(aStruct.GetPointer()); mitk::DataNode::Pointer structNode = mitk::DataNode::New(); structNode->SetData(countourModelSet); structNode->SetProperty("name", aStruct->GetProperty("name")); structNode->SetProperty("color", aStruct->GetProperty("contour.color")); structNode->SetProperty("contour.color", aStruct->GetProperty("contour.color")); structNode->SetProperty("<API key>", mitk::BoolProperty::New(false)); structNode->SetVisibility(true, mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::<API key>("stdmulti.widget0"))); structNode->SetVisibility(false, mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::<API key>("stdmulti.widget1"))); structNode->SetVisibility(false, mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::<API key>("stdmulti.widget2"))); structNode->SetVisibility(true, mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::<API key>("stdmulti.widget3"))); dataStorage->Add(structNode); } mitk::RenderingManager::GetInstance()-><API key>(dataStorage); } } else if (modality.compare("RTPLAN", Qt::CaseInsensitive) == 0) { auto planReader = mitk::RTPlanReaderService(); planReader.SetInput(ImporterUtil::getUTF8String(<API key>.front())); std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = planReader.Read(); if (!readerOutput.empty()){ //there is no image, only the properties are interesting mitk::Image::Pointer planDummyImage = dynamic_cast<mitk::Image*>(readerOutput.at(0).GetPointer()); mitk::DataNode::Pointer planImageNode = mitk::DataNode::New(); planImageNode->SetData(planDummyImage); planImageNode->SetName("RTPlan"); ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService-><API key>().GetPointer()->GetDataStorage(); dataStorage->Add(planImageNode); } } } else { mitk::StringList seriesToLoad; QStringListIterator it(<API key>); while (it.hasNext()) { seriesToLoad.push_back(ImporterUtil::getUTF8String(it.next())); } //Get Reference for default data storage. ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService-><API key>().GetPointer()->GetDataStorage(); std::vector<mitk::BaseData::Pointer> baseDatas = mitk::IOUtil::Load(seriesToLoad.front()); for (const auto &data : baseDatas) { mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(data); std::string nodeName = mitk::DataNode::NO_NAME_VALUE(); auto nameDataProp = data->GetProperty("name"); if (nameDataProp.IsNotNull()) { //if data has a name property set by reader, use this name nodeName = nameDataProp->GetValueAsString(); } else { //reader didn't specify a name, generate one. nodeName = mitk::<API key>(node); } node->SetName(nodeName); dataStorage->Add(node); } } } else { MITK_INFO << "There are no files for the current series"; } } void DicomEventHandler::<API key>(const ctkEvent& /*ctkEvent*/) { } void DicomEventHandler::SubscribeSlots() { ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference<ctkEventAdmin>(); if (ref) { ctkEventAdmin* eventAdmin = mitk::PluginActivator::getContext()->getService<ctkEventAdmin>(ref); ctkDictionary properties; properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/ADD"; eventAdmin->subscribeSlot(this, SLOT(<API key>(ctkEvent)), properties); properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/DELETED"; eventAdmin->subscribeSlot(this, SLOT(<API key>(ctkEvent)), properties); } }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="ApiGen 2.8.0" /> <meta name="robots" content="noindex" /> <title>File widgets/fineuploader/WhFineUploader.php | YiiWheels</title> <script type="text/javascript" src="resources/combined.js?1965618976"></script> <script type="text/javascript" src="elementlist.js?53054354"></script> <link rel="stylesheet" type="text/css" media="all" href="resources/bootstrap.min.css?260161822" /> <link rel="stylesheet" type="text/css" media="all" href="resources/style.css?2015443609" /> </head> <body> <div id="navigation" class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a href="index.html" class="brand">YiiWheels</a> <div class="nav-collapse"> <ul class="nav"> <li> <a href="package-YiiWheels.widgets.fileuploader.html" title="Summary of YiiWheels\widgets\fileuploader"><span>Package</span></a> </li> <li> <a href="<API key>.html" title="Summary of WhFineUploader"><span>Class</span></a> </li> <li class="divider-vertical"></li> <li> <a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a> </li> </ul> </div> </div> </div> </div> <div id="left"> <div id="menu"> <form id="search" class="form-search"> <input type="hidden" name="cx" value="" /> <input type="hidden" name="ie" value="UTF-8" /> <input type="text" name="q" class="search-query" placeholder="Search" /> </form> <div id="groups"> <h3>Packages</h3> <ul> <li><a href="package-None.html">None</a> </li> <li><a href="package-yiiwheels.html">yiiwheels<span></span></a> <ul> <li><a href="package-yiiwheels.behaviors.html">behaviors</a> </li> <li><a href="package-yiiwheels.widgets.html">widgets</a> </li> <li class="active"><a href="package-YiiWheels.widgets.html">widgets<span></span></a> <ul> <li><a href="package-YiiWheels.widgets.ace.html">ace</a> </li> <li><a href="package-YiiWheels.widgets.box.html">box</a> </li> <li><a href="package-YiiWheels.widgets.datepicker.html">datepicker</a> </li> <li><a href="package-YiiWheels.widgets.daterangepicker.html">daterangepicker</a> </li> <li><a href="package-YiiWheels.widgets.datetimepicker.html">datetimepicker</a> </li> <li><a href="package-YiiWheels.widgets.detail.html">detail</a> </li> <li><a href="package-YiiWheels.widgets.fileupload.html">fileupload</a> </li> <li class="active"><a href="package-YiiWheels.widgets.fileuploader.html">fileuploader</a> </li> <li><a href="package-YiiWheels.widgets.gallery.html">gallery</a> </li> <li><a href="package-YiiWheels.widgets.google.html">google</a> </li> <li><a href="package-YiiWheels.widgets.grid.html">grid<span></span></a> <ul> <li><a href="package-yiiwheels.widgets.grid.behaviors.html">behaviors</a> </li> <li><a href="package-YiiWheels.widgets.grid.operations.html">operations</a> </li> </ul></li> <li><a href="package-YiiWheels.widgets.highcharts.html">highcharts</a> </li> <li><a href="package-YiiWheels.widgets.maskInput.html">maskInput</a> </li> <li><a href="package-YiiWheels.widgets.maskmoney.html">maskmoney</a> </li> <li><a href="package-YiiWheels.widgets.modal.html">modal</a> </li> <li><a href="package-YiiWheels.widgets.multiselect.html">multiselect</a> </li> <li><a href="package-YiiWheels.widgets.rangeslider.html">rangeslider</a> </li> <li><a href="package-YiiWheels.widgets.redactor.html">redactor</a> </li> <li><a href="package-YiiWheels.widgets.select2.html">select2</a> </li> <li><a href="package-YiiWheels.widgets.sparklines.html">sparklines</a> </li> <li><a href="package-YiiWheels.widgets.switch.html">switch</a> </li> <li><a href="package-YiiWheels.widgets.timeago.html">timeago</a> </li> <li><a href="package-YiiWheels.widgets.timepicker.html">timepicker</a> </li> <li><a href="package-YiiWheels.widgets.toggle.html">toggle</a> </li> <li><a href="package-YiiWheels.widgets.typeahead.html">typeahead</a> </li> </ul></li></ul></li> </ul> </div> <div id="elements"> <h3>Classes</h3> <ul> <li class="active"><a href="<API key>.html">WhFineUploader</a></li> </ul> </div> </div> </div> <div id="splitter"></div> <div id="right"> <div id="rightInner"> <pre id="source"><code><span id="1" class="l"><a class="l" href="#1"> 1 </a><span class="xlang">&lt;?php</span> </span><span id="11" class="l"><a class="l" href="#11"> 11 </a>Yii::import(<span class="php-quote">'bootstrap.helpers.TbArray'</span>); </span><span id="12" class="l"><a class="l" href="#12"> 12 </a> </span><span id="13" class="l"><a class="l" href="#13"> 13 </a><span class="php-keyword1">class</span> <a id="WhFineUploader" href="#WhFineUploader">WhFineUploader</a> <span class="php-keyword1">extends</span> CInputWidget </span><span id="14" class="l"><a class="l" href="#14"> 14 </a>{ </span><span id="15" class="l"><a class="l" href="#15"> 15 </a> <span class="php-comment">/** </span></span><span id="16" class="l"><a class="l" href="#16"> 16 </a><span class="php-comment"> * @var string upload action url </span></span><span id="17" class="l"><a class="l" href="#17"> 17 </a><span class="php-comment"> */</span> </span><span id="18" class="l"><a class="l" href="#18"> 18 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$uploadAction" href="#$uploadAction">$uploadAction</a></span>; </span><span id="19" class="l"><a class="l" href="#19"> 19 </a> </span><span id="20" class="l"><a class="l" href="#20"> 20 </a> <span class="php-comment">/** </span></span><span id="21" class="l"><a class="l" href="#21"> 21 </a><span class="php-comment"> * @var string the HTML tag to render the uploader to </span></span><span id="22" class="l"><a class="l" href="#22"> 22 </a><span class="php-comment"> */</span> </span><span id="23" class="l"><a class="l" href="#23"> 23 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$tagName" href="#$tagName">$tagName</a></span> = <span class="php-quote">'div'</span>; </span><span id="24" class="l"><a class="l" href="#24"> 24 </a> </span><span id="25" class="l"><a class="l" href="#25"> 25 </a> <span class="php-comment">/** </span></span><span id="26" class="l"><a class="l" href="#26"> 26 </a><span class="php-comment"> * @var string text to display if javascript is disabled </span></span><span id="27" class="l"><a class="l" href="#27"> 27 </a><span class="php-comment"> */</span> </span><span id="28" class="l"><a class="l" href="#28"> 28 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$noScriptText" href="#$noScriptText">$noScriptText</a></span>; </span><span id="29" class="l"><a class="l" href="#29"> 29 </a> </span><span id="30" class="l"><a class="l" href="#30"> 30 </a> <span class="php-comment">/** </span></span><span id="31" class="l"><a class="l" href="#31"> 31 </a><span class="php-comment"> * @var array the plugin options </span></span><span id="32" class="l"><a class="l" href="#32"> 32 </a><span class="php-comment"> */</span> </span><span id="33" class="l"><a class="l" href="#33"> 33 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$pluginOptions" href="#$pluginOptions">$pluginOptions</a></span> = <span class="php-keyword1">array</span>(); </span><span id="34" class="l"><a class="l" href="#34"> 34 </a> </span><span id="35" class="l"><a class="l" href="#35"> 35 </a> <span class="php-comment">/** </span></span><span id="36" class="l"><a class="l" href="#36"> 36 </a><span class="php-comment"> * @var array the events </span></span><span id="37" class="l"><a class="l" href="#37"> 37 </a><span class="php-comment"> */</span> </span><span id="38" class="l"><a class="l" href="#38"> 38 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$events" href="#$events">$events</a></span> = <span class="php-keyword1">array</span>(); </span><span id="39" class="l"><a class="l" href="#39"> 39 </a> </span><span id="40" class="l"><a class="l" href="#40"> 40 </a> <span class="php-comment">/** </span></span><span id="41" class="l"><a class="l" href="#41"> 41 </a><span class="php-comment"> * @var string which scenario we get the validation from </span></span><span id="42" class="l"><a class="l" href="#42"> 42 </a><span class="php-comment"> */</span> </span><span id="43" class="l"><a class="l" href="#43"> 43 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$scenario" href="#$scenario">$scenario</a></span>; </span><span id="44" class="l"><a class="l" href="#44"> 44 </a> </span><span id="45" class="l"><a class="l" href="#45"> 45 </a> <span class="php-comment">/** </span></span><span id="46" class="l"><a class="l" href="#46"> 46 </a><span class="php-comment"> * @var array d </span></span><span id="47" class="l"><a class="l" href="#47"> 47 </a><span class="php-comment"> */</span> </span><span id="48" class="l"><a class="l" href="#48"> 48 </a> <span class="php-keyword1">protected</span> <span class="php-var"><a id="$defaultOptions" href="#$defaultOptions">$defaultOptions</a></span> = <span class="php-keyword1">array</span>(); </span><span id="49" class="l"><a class="l" href="#49"> 49 </a> </span><span id="50" class="l"><a class="l" href="#50"> 50 </a> <span class="php-comment">/** </span></span><span id="51" class="l"><a class="l" href="#51"> 51 </a><span class="php-comment"> * @throws CException </span></span><span id="52" class="l"><a class="l" href="#52"> 52 </a><span class="php-comment"> */</span> </span><span id="53" class="l"><a class="l" href="#53"> 53 </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> <a id="_init" href="#_init">init</a>() </span><span id="54" class="l"><a class="l" href="#54"> 54 </a> { </span><span id="55" class="l"><a class="l" href=" </span><span id="56" class="l"><a class="l" href="#56"> 56 </a> <span class="php-keyword1">throw</span> <span class="php-keyword1">new</span> CException(Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'&quot;uploadAction&quot; attribute cannot be blank'</span>)); </span><span id="57" class="l"><a class="l" href="#57"> 57 </a> } </span><span id="58" class="l"><a class="l" href=" </span><span id="59" class="l"><a class="l" href="#59"> 59 </a> <span class="php-var">$this</span>-&gt;noScriptText = Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">&quot;Please enable JavaScript to use file uploader.&quot;</span>); </span><span id="60" class="l"><a class="l" href="#60"> 60 </a> } </span><span id="61" class="l"><a class="l" href="#61"> 61 </a> </span><span id="62" class="l"><a class="l" href="#62"> 62 </a> <span class="php-var">$this</span>-&gt;attachBehavior(<span class="php-quote">'ywplugin'</span>, <span class="php-keyword1">array</span>(<span class="php-quote">'class'</span> =&gt; <span class="php-quote">'yiiwheels.behaviors.WhPlugin'</span>)); </span><span id="63" class="l"><a class="l" href="#63"> 63 </a> </span><span id="64" class="l"><a class="l" href="#64"> 64 </a> <span class="php-var">$this</span>-&gt;initDefaultOptions(); </span><span id="65" class="l"><a class="l" href="#65"> 65 </a> } </span><span id="66" class="l"><a class="l" href="#66"> 66 </a> </span><span id="67" class="l"><a class="l" href="#67"> 67 </a> <span class="php-comment">/** </span></span><span id="68" class="l"><a class="l" href="#68"> 68 </a><span class="php-comment"> * Widget's run method </span></span><span id="69" class="l"><a class="l" href="#69"> 69 </a><span class="php-comment"> */</span> </span><span id="70" class="l"><a class="l" href="#70"> 70 </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> <a id="_run" href="#_run">run</a>() </span><span id="71" class="l"><a class="l" href="#71"> 71 </a> { </span><span id="72" class="l"><a class="l" href="#72"> 72 </a> <span class="php-var">$this</span>-&gt;renderTag(); </span><span id="73" class="l"><a class="l" href="#73"> 73 </a> <span class="php-var">$this</span>-&gt;<API key>(); </span><span id="74" class="l"><a class="l" href="#74"> 74 </a> } </span><span id="75" class="l"><a class="l" href="#75"> 75 </a> </span><span id="76" class="l"><a class="l" href="#76"> 76 </a> <span class="php-comment">/** </span></span><span id="77" class="l"><a class="l" href="#77"> 77 </a><span class="php-comment"> * Renders the tag where the button is going to be rendered </span></span><span id="78" class="l"><a class="l" href="#78"> 78 </a><span class="php-comment"> */</span> </span><span id="79" class="l"><a class="l" href="#79"> 79 </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> <a id="_renderTag" href="#_renderTag">renderTag</a>() </span><span id="80" class="l"><a class="l" href="#80"> 80 </a> { </span><span id="81" class="l"><a class="l" href="#81"> 81 </a> <span class="php-keyword1">echo</span> CHtml::tag(<span class="php-var">$this</span>-&gt;tagName, <span class="php-var">$this</span>-&gt;htmlOptions, <span class="php-quote">'&lt;noscript&gt;'</span> . <span class="php-var">$this</span>-&gt;noScriptText . <span class="php-quote">'&lt;/noscript&gt;'</span>, <span class="php-keyword1">true</span>); </span><span id="82" class="l"><a class="l" href="#82"> 82 </a> } </span><span id="83" class="l"><a class="l" href="#83"> 83 </a> </span><span id="84" class="l"><a class="l" href="#84"> 84 </a> <span class="php-comment">/** </span></span><span id="85" class="l"><a class="l" href="#85"> 85 </a><span class="php-comment"> * Registers required client script for finuploader </span></span><span id="86" class="l"><a class="l" href="#86"> 86 </a><span class="php-comment"> */</span> </span><span id="87" class="l"><a class="l" href="#87"> 87 </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> <a id="<API key>" href="#<API key>"><API key></a>() </span><span id="88" class="l"><a class="l" href="#88"> 88 </a> { </span><span id="89" class="l"><a class="l" href="#89"> 89 </a> <span class="php-comment">/* publish assets dir */</span> </span><span id="90" class="l"><a class="l" href="#90"> 90 </a> <span class="php-var">$path</span> = <span class="php-keyword2">dirname</span>(__FILE__) . DIRECTORY_SEPARATOR . <span class="php-quote">'assets'</span>; </span><span id="91" class="l"><a class="l" href="#91"> 91 </a> <span class="php-var">$assetsUrl</span> = <span class="php-var">$this</span>-&gt;getAssetsUrl(<span class="php-var">$path</span>); </span><span id="92" class="l"><a class="l" href="#92"> 92 </a> </span><span id="93" class="l"><a class="l" href="#93"> 93 </a> <span class="php-comment">/* @var $cs CClientScript */</span> </span><span id="94" class="l"><a class="l" href="#94"> 94 </a> <span class="php-var">$cs</span> = Yii::app()-&gt;getClientScript(); </span><span id="95" class="l"><a class="l" href="#95"> 95 </a> </span><span id="96" class="l"><a class="l" href="#96"> 96 </a> <span class="php-var">$script</span> = YII_DEBUG ? <span class="php-quote">'jquery.fineuploader-3.2.js'</span> : <span class="php-quote">'jquery.fineuploader-3.2.min.js'</span>; </span><span id="97" class="l"><a class="l" href="#97"> 97 </a> </span><span id="98" class="l"><a class="l" href="#98"> 98 </a> <span class="php-var">$cs</span>-&gt;registerCssFile(<span class="php-var">$assetsUrl</span> . <span class="php-quote">'/css/fineuploader.css'</span>); </span><span id="99" class="l"><a class="l" href="#99"> 99 </a> <span class="php-var">$cs</span>-&gt;registerScriptFile(<span class="php-var">$assetsUrl</span> . <span class="php-quote">'/js/'</span> . <span class="php-var">$script</span>); </span><span id="100" class="l"><a class="l" href="#100">100 </a> </span><span id="101" class="l"><a class="l" href="#101">101 </a> <span class="php-comment">/* initialize plugin */</span> </span><span id="102" class="l"><a class="l" href="#102">102 </a> <span class="php-var">$selector</span> = <span class="php-quote">'#'</span> . TbArray::getValue(<span class="php-quote">'id'</span>, <span class="php-var">$this</span>-&gt;htmlOptions, <span class="php-var">$this</span>-&gt;getId()); </span><span id="103" class="l"><a class="l" href="#103">103 </a> </span><span id="104" class="l"><a class="l" href="#104">104 </a> <span class="php-var">$this</span>-&gt;getApi()-&gt;registerPlugin( </span><span id="105" class="l"><a class="l" href="#105">105 </a> <span class="php-quote">'fineUploader'</span>, </span><span id="106" class="l"><a class="l" href="#106">106 </a> <span class="php-var">$selector</span>, </span><span id="107" class="l"><a class="l" href="#107">107 </a> CMap::mergeArray(<span class="php-var">$this</span>-&gt;defaultOptions, <span class="php-var">$this</span>-&gt;pluginOptions) </span><span id="108" class="l"><a class="l" href="#108">108 </a> ); </span><span id="109" class="l"><a class="l" href="#109">109 </a> <span class="php-var">$this</span>-&gt;getApi()-&gt;registerEvents(<span class="php-var">$selector</span>, <span class="php-var">$this</span>-&gt;events); </span><span id="110" class="l"><a class="l" href="#110">110 </a> } </span><span id="111" class="l"><a class="l" href="#111">111 </a> </span><span id="116" class="l"><a class="l" href="#116">116 </a> <span class="php-keyword1">protected</span> <span class="php-keyword1">function</span> <a id="_initDefaultOptions" href="#_initDefaultOptions">initDefaultOptions</a>() </span><span id="117" class="l"><a class="l" href="#117">117 </a> { </span><span id="118" class="l"><a class="l" href="#118">118 </a> <span class="php-keyword1">list</span>(<span class="php-var">$name</span>, <span class="php-var">$id</span>) = <span class="php-var">$this</span>-&gt;resolveNameID(); </span><span id="119" class="l"><a class="l" href="#119">119 </a> </span><span id="120" class="l"><a class="l" href="#120">120 </a> TbArray::defaultValue(<span class="php-quote">'id'</span>, <span class="php-var">$id</span>, <span class="php-var">$this</span>-&gt;htmlOptions); </span><span id="121" class="l"><a class="l" href="#121">121 </a> TbArray::defaultValue(<span class="php-quote">'name'</span>, <span class="php-var">$name</span>, <span class="php-var">$this</span>-&gt;htmlOptions); </span><span id="122" class="l"><a class="l" href="#122">122 </a> </span><span id="123" class="l"><a class="l" href="#123">123 </a> </span><span id="124" class="l"><a class="l" href="#124">124 </a> <span class="php-var">$this</span>-&gt;defaultOptions = <span class="php-keyword1">array</span>( </span><span id="125" class="l"><a class="l" href="#125">125 </a> <span class="php-quote">'request'</span> =&gt; <span class="php-keyword1">array</span>( </span><span id="126" class="l"><a class="l" href="#126">126 </a> <span class="php-quote">'endpoint'</span> =&gt; <span class="php-var">$this</span>-&gt;uploadAction, </span><span id="127" class="l"><a class="l" href="#127">127 </a> <span class="php-quote">'inputName'</span> =&gt; <span class="php-var">$name</span>, </span><span id="128" class="l"><a class="l" href="#128">128 </a> ), </span><span id="129" class="l"><a class="l" href="#129">129 </a> <span class="php-quote">'validation'</span> =&gt; <span class="php-var">$this</span>-&gt;getValidator(), </span><span id="130" class="l"><a class="l" href="#130">130 </a> <span class="php-quote">'messages'</span> =&gt; <span class="php-keyword1">array</span>( </span><span id="131" class="l"><a class="l" href="#131">131 </a> <span class="php-quote">'typeError'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'{file} has an invalid extension. Valid extension(s): {extensions}.'</span>), </span><span id="132" class="l"><a class="l" href="#132">132 </a> <span class="php-quote">'sizeError'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'{file} is too large, maximum file size is {sizeLimit}.'</span>), </span><span id="133" class="l"><a class="l" href="#133">133 </a> <span class="php-quote">'minSizeError'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'{file} is too small, minimum file size is {minSizeLimit}.'</span>), </span><span id="134" class="l"><a class="l" href="#134">134 </a> <span class="php-quote">'emptyError:'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'{file} is empty, please select files again without it.'</span>), </span><span id="135" class="l"><a class="l" href="#135">135 </a> <span class="php-quote">'noFilesError'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'No files to upload.'</span>), </span><span id="136" class="l"><a class="l" href="#136">136 </a> <span class="php-quote">'onLeave'</span> =&gt; Yii::t( </span><span id="137" class="l"><a class="l" href="#137">137 </a> <span class="php-quote">'zii'</span>, </span><span id="138" class="l"><a class="l" href="#138">138 </a> <span class="php-quote">'The files are being uploaded, if you leave now the upload will be cancelled.'</span> </span><span id="139" class="l"><a class="l" href="#139">139 </a> ) </span><span id="140" class="l"><a class="l" href="#140">140 </a> ), </span><span id="141" class="l"><a class="l" href="#141">141 </a> ); </span><span id="142" class="l"><a class="l" href="#142">142 </a> } </span><span id="143" class="l"><a class="l" href="#143">143 </a> </span><span id="144" class="l"><a class="l" href="#144">144 </a> <span class="php-comment">/** </span></span><span id="145" class="l"><a class="l" href="#145">145 </a><span class="php-comment"> * @return array </span></span><span id="146" class="l"><a class="l" href="#146">146 </a><span class="php-comment"> */</span> </span><span id="147" class="l"><a class="l" href="#147">147 </a> <span class="php-keyword1">protected</span> <span class="php-keyword1">function</span> <a id="_getValidator" href="#_getValidator">getValidator</a>() </span><span id="148" class="l"><a class="l" href="#148">148 </a> { </span><span id="149" class="l"><a class="l" href="#149">149 </a> <span class="php-var">$ret</span> = <span class="php-keyword1">array</span>(); </span><span id="150" class="l"><a class="l" href="#150">150 </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;hasModel()) { </span><span id="151" class="l"><a class="l" href="#151">151 </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;scenario !== <span class="php-keyword1">null</span>) { </span><span id="152" class="l"><a class="l" href="#152">152 </a> <span class="php-var">$originalScenario</span> = <span class="php-var">$this</span>-&gt;model-&gt;getScenario(); </span><span id="153" class="l"><a class="l" href="#153">153 </a> <span class="php-var">$this</span>-&gt;model-&gt;setScenario(<span class="php-var">$this</span>-&gt;scenario); </span><span id="154" class="l"><a class="l" href="#154">154 </a> <span class="php-var">$validators</span> = <span class="php-var">$this</span>-&gt;model-&gt;getValidators(<span class="php-var">$this</span>-&gt;attribute); </span><span id="155" class="l"><a class="l" href="#155">155 </a> <span class="php-var">$this</span>-&gt;model-&gt;setScenario(<span class="php-var">$originalScenario</span>); </span><span id="156" class="l"><a class="l" href="#156">156 </a> </span><span id="157" class="l"><a class="l" href="#157">157 </a> } <span class="php-keyword1">else</span> { </span><span id="158" class="l"><a class="l" href="#158">158 </a> <span class="php-var">$validators</span> = <span class="php-var">$this</span>-&gt;model-&gt;getValidators(<span class="php-var">$this</span>-&gt;attribute); </span><span id="159" class="l"><a class="l" href="#159">159 </a> } </span><span id="160" class="l"><a class="l" href="#160">160 </a> </span><span id="161" class="l"><a class="l" href="#161">161 </a> <span class="php-comment">// we are just looking for the first founded CFileValidator</span> </span><span id="162" class="l"><a class="l" href="#162">162 </a> <span class="php-keyword1">foreach</span> (<span class="php-var">$validators</span> <span class="php-keyword1">as</span> <span class="php-var">$validator</span>) { </span><span id="163" class="l"><a class="l" href="#163">163 </a> <span class="php-keyword1">if</span> (<span class="php-keyword2">is_a</span>(<span class="php-var">$validator</span>, <span class="php-quote">'CFileValidator'</span>)) { </span><span id="164" class="l"><a class="l" href="#164">164 </a> <span class="php-var">$ret</span> = <span class="php-keyword1">array</span>( </span><span id="165" class="l"><a class="l" href="#165">165 </a> <span class="php-quote">'allowedExtensions'</span> =&gt; <span class="php-keyword2">explode</span>(<span class="php-quote">','</span>, <span class="php-keyword2">str_replace</span>(<span class="php-quote">' '</span>, <span class="php-quote">''</span>, <span class="php-var">$validator</span>-&gt;types)), </span><span id="166" class="l"><a class="l" href="#166">166 </a> <span class="php-quote">'sizeLimit'</span> =&gt; <span class="php-var">$validator</span>-&gt;maxSize, </span><span id="167" class="l"><a class="l" href="#167">167 </a> <span class="php-quote">'minSizeLimit'</span> =&gt; <span class="php-var">$validator</span>-&gt;minSize, </span><span id="168" class="l"><a class="l" href="#168">168 </a> ); </span><span id="169" class="l"><a class="l" href="#169">169 </a> <span class="php-keyword1">break</span>; </span><span id="170" class="l"><a class="l" href="#170">170 </a> } </span><span id="171" class="l"><a class="l" href="#171">171 </a> } </span><span id="172" class="l"><a class="l" href="#172">172 </a> } </span><span id="173" class="l"><a class="l" href="#173">173 </a> <span class="php-keyword1">return</span> <span class="php-var">$ret</span>; </span><span id="174" class="l"><a class="l" href="#174">174 </a> } </span><span id="175" class="l"><a class="l" href="#175">175 </a></span>}</code></pre> </div> <div id="footer"> YiiWheels API documentation generated by <a href="http://apigen.org">ApiGen 2.8.0</a> </div> </div> </body> </html>
// Use of this source code is governed by a BSD-style // godoc: Go Documentation Server // Web server tree: // (idea is if you say import "compress/zlib", you go to // Command-line interface: // godoc packagepath [name ...] // godoc compress/zlib // - prints doc for package compress/zlib // godoc crypto/block Cipher NewCMAC // - prints doc for Cipher and NewCMAC in package crypto/block // +build !appengine package main import ( "archive/zip" _ "expvar" // to serve /debug/vars "flag" "fmt" "go/build" "log" "net/http" "net/http/httptest"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http: <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>QGeoCodingManager &mdash; PyQt 5.5.1 Reference Guide</title> <link rel="stylesheet" href="../_static/classic.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var <API key> = { URL_ROOT: '../', VERSION: '5.5.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="shortcut icon" href="../_static/logo_tn.ico"/> <link rel="top" title="PyQt 5.5.1 Reference Guide" href="../index.html" /> <link rel="up" title="PyQt5 Class Reference" href="../class_reference.html" /> <link rel="next" title="<API key>" href="<API key>.html" /> <link rel="prev" title="QGeoCodeReply" href="qgeocodereply.html" /> </head> <body role="document"> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="<API key>.html" title="<API key>" accesskey="N">next</a> |</li> <li class="right" > <a href="qgeocodereply.html" title="QGeoCodeReply" accesskey="P">previous</a> |</li> <li class="nav-item nav-item-0"><a href="../index.html">PyQt 5.5.1 Reference Guide</a> &raquo;</li> <li class="nav-item nav-item-1"><a href="../class_reference.html" accesskey="U">PyQt5 Class Reference</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="qgeocodingmanager"> <h1>QGeoCodingManager<a class="headerlink" href=" <dl class="class"> <dt id="PyQt5.QtLocation.QGeoCodingManager"> <em class="property">class </em><code class="descclassname">PyQt5.QtLocation.</code><code class="descname">QGeoCodingManager</code><a class="headerlink" href=" <dd><p><a class="reference external" href="http://doc.qt.io/qt-5/qgeocodingmanager.html">C++ documentation</a></p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="<API key>"> <p class="logo"><a href="../index.html"> <img class="logo" src="../_static/logo.png" alt="Logo"/> </a></p> <h4>Previous topic</h4> <p class="topless"><a href="qgeocodereply.html" title="previous chapter">QGeoCodeReply</a></p> <h4>Next topic</h4> <p class="topless"><a href="<API key>.html" title="next chapter"><API key></a></p> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="<API key>.html" title="<API key>" >next</a> |</li> <li class="right" > <a href="qgeocodereply.html" title="QGeoCodeReply" >previous</a> |</li> <li class="nav-item nav-item-0"><a href="../index.html">PyQt 5.5.1 Reference Guide</a> &raquo;</li> <li class="nav-item nav-item-1"><a href="../class_reference.html" >PyQt5 Class Reference</a> &raquo;</li> </ul> </div> <div class="footer" role="contentinfo"> &copy; Copyright 2015 Riverbank Computing Limited. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.3.1. </div> </body> </html>
{-# LANGUAGE OverloadedStrings #-} module WildBind.SeqSpec (main,spec) where import Control.Applicative ((<*>)) import Control.Monad (forM_) import Control.Monad.IO.Class (liftIO) import qualified Control.Monad.Trans.State as State import Data.Monoid ((<>)) import Data.IORef (modifyIORef, newIORef, readIORef) import Test.Hspec import WildBind.Binding ( binds, on, run, as, boundActions, actDescription, boundInputs, Binding, justBefore ) import WildBind.Description (ActionDescription) import WildBind.Seq ( prefix, toSeq, fromSeq, withPrefix, withCancel, reviseSeq ) import WildBind.ForTest ( SampleInput(..), SampleState(..), evalStateEmpty, execAll, boundDescs, curBoundInputs, curBoundDescs, curBoundDesc, checkBoundInputs, checkBoundDescs, checkBoundDesc, withRefChecker ) main :: IO () main = hspec spec spec :: Spec spec = do spec_prefix spec_SeqBinding spec_reviseSeq spec_prefix :: Spec spec_prefix = describe "prefix" $ do let base_b = binds $ do on SIa `as` "a" `run` return () on SIb `as` "b" `run` return () specify "no prefix" $ do let b = prefix [] [] base_b boundDescs b (SS "") `shouldMatchList` [ (SIa, "a"), (SIb, "b") ] specify "one prefix" $ evalStateEmpty $ do State.put $ prefix [] [SIc] base_b checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIc] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] specify "two prefixes" $ evalStateEmpty $ do State.put $ prefix [] [SIc, SIb] base_b checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] checkBoundInputs (SS "") [SIb] execAll (SS "") [SIb] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] specify "cancel binding" $ evalStateEmpty $ do State.put $ prefix [SIa] [SIc, SIb] base_b checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] -- there is no cancel binding at the top level. checkBoundInputs (SS "") [SIa, SIb] checkBoundDesc (SS "") SIa "cancel" execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc, SIb] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] -- cancel binding should be weak and overridden. execAll (SS "") [SIb] checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc, SIb] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] spec_SeqBinding :: Spec spec_SeqBinding = describe "SeqBinding" $ do let b_a = binds $ on SIa `as` "a" `run` return () b_b = binds $ on SIb `as` "b" `run` return () describe "withPrefix" $ do it "should allow nesting" $ evalStateEmpty $ do State.put $ fromSeq $ withPrefix [SIb] $ withPrefix [SIc] $ withPrefix [SIa] $ toSeq (b_a <> b_b) checkBoundInputs (SS "") [SIb] execAll (SS "") [SIb] checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] checkBoundInputs (SS "") [SIa] execAll (SS "") [SIa] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIb] describe "mappend" $ do it "should be able to combine SeqBindings with different prefixes." $ evalStateEmpty $ do State.put $ fromSeq $ withPrefix [SIc] $ ( (withPrefix [SIa, SIc] $ toSeq $ b_a) <> (withPrefix [SIa] $ toSeq $ b_b) ) checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] checkBoundInputs (SS "") [SIa] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc, SIb] checkBoundDesc (SS "") SIb "b" execAll (SS "") [SIb] checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc, SIa] checkBoundInputs (SS "") [SIc, SIb] execAll (SS "") [SIc] checkBoundDescs (SS "") [(SIa, "a")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] describe "withCancel" $ do it "should weakly add 'cancel' binding when at least one prefix is kept in the state." $ evalStateEmpty $ do State.put $ fromSeq $ withPrefix [SIa, SIc] $ withCancel [SIa, SIb, SIc] $ ( toSeq b_a <> (withPrefix [SIc] $ toSeq b_b) ) let checkPrefixOne = do checkBoundInputs (SS "") [SIa] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIa, SIb, SIc] forM_ [SIa, SIb] $ \c -> checkBoundDesc (SS "") c "cancel" checkPrefixOne execAll (SS "") [SIa] checkPrefixOne execAll (SS "") [SIc] checkBoundInputs (SS "") [SIa, SIb, SIc] checkBoundDesc (SS "") SIa "a" checkBoundDesc (SS "") SIb "cancel" execAll (SS "") [SIa] checkPrefixOne execAll (SS "") [SIc, SIb] checkPrefixOne execAll (SS "") [SIc, SIc] checkBoundDescs (SS "") [(SIa, "cancel"), (SIb, "b"), (SIc, "cancel")] execAll (SS "") [SIb] checkPrefixOne spec_reviseSeq :: Spec spec_reviseSeq = describe "reviseSeq" $ do it "should allow access to prefix keys input so far" $ evalStateEmpty $ withRefChecker [] $ \out checkOut -> do act_out <- liftIO $ newIORef ("" :: String) let sb = withCancel [SIa] $ withPrefix [SIa, SIb, SIc] $ toSeq $ base_b base_b = binds $ on SIb `as` "B" `run` modifyIORef act_out (++ "B executed") rev ps _ _ = justBefore $ modifyIORef out (++ [ps]) State.put $ fromSeq $ reviseSeq rev sb execAll (SS "") [SIa, SIa] checkOut [[], [SIa]] execAll (SS "") [SIa, SIb, SIc] checkOut [[], [SIa], [], [SIa], [SIa, SIb]] liftIO $ readIORef act_out `shouldReturn` "" execAll (SS "") [SIb] checkOut [[], [SIa], [], [SIa], [SIa, SIb], [SIa, SIb, SIc]] liftIO $ readIORef act_out `shouldReturn` "B executed" it "should allow unbinding" $ evalStateEmpty $ do let sb = withPrefix [SIa] ( toSeq ba <> (withPrefix [SIb] $ toSeq bab) <> (withPrefix [SIa] $ toSeq baa) ) ba = binds $ on SIc `as` "c on a" `run` return () bab = binds $ on SIc `as` "c on ab" `run` return () baa = binds $ do on SIc `as` "c on aa" `run` return () on SIb `as` "b on aa" `run` return () rev ps _ i act = if (ps == [SIa] && i == SIb) || (ps == [SIa,SIa] && i == SIc) then Nothing else Just act State.put $ fromSeq $ reviseSeq rev sb checkBoundInputs (SS "") [SIa] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIa, SIc] -- SIb should be canceled execAll (SS "") [SIa] checkBoundDescs (SS "") [(SIb, "b on aa")] -- SIc should be canceled execAll (SS "") [SIb] checkBoundInputs (SS "") [SIa]
.filebrowser table td { font-size: 10px; } .filebrowser table a { font-size: 11px; } .filebrowser thead th.sorted a { padding-right: 13px; } .filebrowser td { padding: 9px 10px 7px 10px !important; } .filebrowser td.fb_icon { padding: 6px 5px 5px 5px !important; } table a.fb_deletelink, table a.fb_renamelink, table a.fb_selectlink, table a.fb_makethumblink, table a.<API key> { cursor: pointer; display: block; padding: 0; margin: 0; width: 23px; height: 17px; background-color: transparent; background-position: 0 center; background-repeat: no-repeat; } table .fb_deletelink:link, table .fb_deletelink:visited { width: 15px; background-image: url('../img/<API key>.gif'); } table .fb_deletelink:hover, table .fb_deletelink:active { background-image: url('../img/<API key>.gif'); } table .fb_renamelink:link, table .fb_renamelink:visited { width: 14px; background-image: url('../img/<API key>.gif'); } table .fb_renamelink:hover, table .fb_renamelink:active { background-image: url('../img/<API key>.gif'); } table .fb_selectlink:link, table .fb_selectlink:visited { background-image: url('../img/<API key>.gif'); } table .fb_selectlink:hover, table .fb_selectlink:active { background-image: url('../img/<API key>.gif'); } table .fb_makethumblink:link, table .fb_makethumblink:visited { width: 50px; height: 29px; background-image: url('../img/<API key>.gif'); } table .fb_makethumblink:hover, table .fb_makethumblink:active { background-image: url('../img/<API key>.gif'); } table .<API key>:link, table .<API key>:visited { background-image: url('../img/<API key>.gif'); } table .<API key>:hover, table .<API key>:active { background-image: url('../img/<API key>.gif'); } .object-tools { position:relative; float:right; font-weight:bold; font-family:Arial,Helvetica,sans-serif; text-transform: none; margin-top: -23px; margin-bottom:-10px; padding:0; } .form-row .object-tools { margin-top:5px; margin-bottom:5px; float:none; } .object-tools li { display:block; float:left; color: #ccc; font-size: 12px !important; line-height: 12px !important; padding: 0; background: none !important; } .object-tools li:hover { background:none !important; } .object-tools a { display: block; float: left; margin: -3px 0 0 15px; padding: 3px 0 2px 22px !important; font-size: 12px !important; line-height: 12px !important; background-color: #fff !important; background-position: 0 0 !important; background-repeat: no-repeat; } .object-tools a:link, .object-tools a:visited { color: #659DC2 !important; } .object-tools a:hover, .object-tools a:active { color: #555 !important; } .object-tools .<API key>:link, .object-tools .<API key>:visited { padding-left: 28px !important; background-image: url('../img/<API key>.gif') !important; } .object-tools .<API key>:hover, .object-tools .<API key>:active { background-image: url('../img/<API key>.gif') !important; } .object-tools .<API key>:link, .object-tools .<API key>:visited { padding-left: 24px !important; background-image: url('../img/<API key>.gif') !important; } .object-tools .<API key>:hover, .object-tools .<API key>:active { background-image: url('../img/<API key>.gif') !important; } .object-tools .<API key>:link, .object-tools .<API key>:visited { padding-left: 26px !important; background-image: url('../img/<API key>.gif') !important; } .object-tools .<API key>:hover, .object-tools .<API key>:active { background-image: url('../img/<API key>.gif') !important; } .object-tools .fb_makethumbslink:link, .object-tools .fb_makethumbslink:visited { padding-left: 28px !important; background-image: url('../img/<API key>.gif') !important; } .object-tools .fb_makethumbslink:hover, .object-tools .fb_makethumbslink:active { background-image: url('../img/<API key>.gif') !important; }
<?php return array( 'Status\\V1\\Rpc\\Ping\\Controller' => array( 'GET' => array( 'description' => 'Ping the API for availability and receive a timestamp for acknowledgement.', 'request' => null, 'response' => '{ "ack": "Acknowledge the request with a timestamp" }', ), 'description' => 'Ping the API for availability.', ), 'Status\\V1\\Rest\\Status\\Controller' => array( 'collection' => array( 'GET' => array( 'description' => 'Retrieve a paginated list of status messages.', 'request' => null, 'response' => null, ), 'POST' => array( 'description' => 'Create a new status messages.', 'request' => null, 'response' => null, ), 'description' => 'Manipulate lists of status messages.', ), 'entity' => array( 'GET' => array( 'description' => 'Retrieve a status message.', 'request' => null, 'response' => '{ "_links": { "self": { "href": "/status[/:status_id]" } } "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', ), 'PATCH' => array( 'description' => 'Update a status message.', 'request' => '{ "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', 'response' => '{ "_links": { "self": { "href": "/status[/:status_id]" } } "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', ), 'PUT' => array( 'description' => 'Replace a status message.', 'request' => '{ "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', 'response' => '{ "_links": { "self": { "href": "/status[/:status_id]" } } "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', ), 'DELETE' => array( 'description' => 'Delete a status message.', 'request' => null, 'response' => null, ), 'description' => 'Manipulate and retrieve individual status messages.', ), 'description' => 'Create, manipulate, and retrieve status messages.', ), );
#include <pulsar/testing/CppTester.hpp> #include <pulsar/system/Atom.hpp> using namespace pulsar; TEST_SIMPLE(TestAtom){ CppTester tester("Testing the Atom class"); Atom H=create_atom({0.0,0.0,0.0},1); Atom H2=create_atom({0.0,0.0,0.0},1,1); tester.test_equal("create_atom works",H,H2); tester.test_equal("correct Z",1,H.Z); tester.test_equal("correct isotope",1,H.isotope); tester.test_equal("correct mass",1.007975,H.mass); tester.test_equal("correct isotope mass",1.0078250322,H.isotope_mass); tester.test_equal("correct charge",0,H.charge); tester.test_equal("correct multiplicity",2,H.multiplicity); tester.test_equal("correct nelectrons",1,H.nelectrons); tester.test_equal("correct covalent radius",0.5858150988919267,H.cov_radius); tester.test_equal("correct vDW radius",2.267671350549394,H.vdw_radius); Atom H3(H2); tester.test_equal("copy constructor works",H,H3); Atom H4(std::move(H3)); tester.test_equal("move constructor works",H,H4); Atom D=create_atom({0.0,0.0,0.0},1,2); tester.test_equal("Isotopes work",2,D.isotope); tester.test_equal("Isotopes are different",true,D!=H); D=H4; tester.test_equal("assignment works",D,H); Atom U=create_atom({0.0,0.0,0.0},92); U=std::move(H4); tester.test_equal("move assignment works",U,H); tester.test_equal("hash works",H.my_hash(),U.my_hash()); tester.test_equal("hash works 1",H.my_hash(),H2.my_hash()); tester.test_equal("hash works 2",H.my_hash(),D.my_hash()); Atom GH=make_ghost_atom(H2); tester.test_equal("ghost works",true,is_ghost_atom(GH)); Atom q=make_point_charge(H2,3.3),q2=make_point_charge(H2.get_coords(),3.3); tester.test_equal("point charges work",true,is_point_charge(q)); tester.test_equal("point charges work 2",true,is_point_charge(q2)); tester.test_equal("is same point charge",q,q2); Atom Dm=make_dummy_atom(H),Dm2=make_dummy_atom(H.get_coords()); tester.test_equal("is dummy atom",true,is_dummy_atom(Dm)); tester.test_equal("is dummy atom 2",true,is_dummy_atom(Dm2)); tester.test_equal("is same dummy atom",Dm,Dm2); tester.print_results(); return tester.nfailed(); }
<?php namespace app\tests\codeception\unit\modules\mobile\models; use app\modules\mobile\models\Trip; use app\tests\codeception\unit\fixtures\TripFixture; use Codeception\Specify; use yii\codeception\TestCase; use MongoDate; class TripTest extends TestCase{ use Specify; /** * @var \UnitTester */ protected $tester; public function fixtures() { return [ 'reports' => [ 'class' => TripFixture::className(), ], ]; } public function testGetStatus() { $this->specify("Status must be correct", function($duration, $possession, $complete, $expected) { $model = new Trip(); $model['duration'] = $duration; $model['numberPossession'] = $possession; $model['complete'] = $complete; expect($model->getStatus())->equals($expected); },[ 'examples' => [ [ 'duration' => ['to' => new MongoDate(strtotime('08.03.2015'))], 'possession' => ['to' => new MongoDate(strtotime('07.03.2015'))], 'complete' => true, 'expected' => Trip::STATUS_COMPLETE ], [ 'duration' => ['to' => new MongoDate(strtotime('08.03.2015'))], 'possession' => ['to' => new MongoDate(strtotime('11.03.2015'))], 'complete' => true, 'expected' => Trip::STATUS_COMPLETE ], [ 'duration' => ['to' => new MongoDate(strtotime('08.03.2015'))], 'possession' => ['to' => new MongoDate(strtotime('12.03.2015'))], 'complete' => true, 'expected' => Trip::STATUS_EXPIRED ], [ 'duration' => ['to' => new MongoDate()], 'possession' => ['to' => null], 'complete' => false, 'expected' => Trip::STATUS_INCOMPLETE ], [ 'duration' => ['to' => new MongoDate(time()-Trip::<API key> - 1)], 'possession' => ['to' => null], 'complete' => false, 'expected' => Trip::STATUS_EXPIRED ], ] ]); } }
<?php class ReCopyWidget extends CWidget { public $targetClass='clone'; //Target CSS class target for duplicate public $limit=0; //The number of allowed copies. Default: 0 is unlimited public $addButtonId; // Add button id. Set id differently if this widget is called multiple times per page. public $addButtonLabel='Add more'; //Add button text. public $addButtonCssClass=''; //Add button CSS class. public $removeButtonLabel='Remove'; //Remove button text public $<API key>='recopy-remove'; //Remove button CSS class. public $excludeSelector; //A jQuery selector used to exclude an element and its children public $copyClass; //A class to attach to each copy public $clearInputs; //Boolean Option to clear each copies text input fields or textarea private $_assetsUrl; /** * Initializes the widgets */ public function init() { parent::init(); if ($this->_assetsUrl === null) { $assetsDir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets'; $this->_assetsUrl = Yii::app()->assetManager->publish($assetsDir); } $this->addButtonId=trim($this->addButtonId); if(empty($this->addButtonId)) $this->addButtonId='recopy-add'; if($this->limit) $this->limit= (is_numeric($this->limit) && $this->limit > 0)? (int)ceil($this->limit):0; } /** * Execute the widgets */ public function run() { if($this->limit==1) return ; Yii::app()->clientScript ->registerScriptFile($this->_assetsUrl . '/reCopy.js', CClientScript::POS_HEAD) ->registerScript(__CLASS__.$this->addButtonId, ' $(function(){ var removeLink = \' <a class="'.$this-><API key>.'" href="#" onclick="$(this).parent().slideUp(function(){ $(this).remove() }); return false">'.$this->removeButtonLabel.'</a>\'; $("a#'.$this->addButtonId.'").relCopy({'.implode(', ', array_filter(array( empty($this->excludeSelector)?'':'excludeSelector: "'.$this->excludeSelector.'"', empty($this->limit)? '': 'limit: '.$this->limit, empty($this->copyClass)? '': 'copyClass: "'.$this->copyClass.'"', $this->clearInputs===true? 'clearInputs: true':'', $this->clearInputs===false? 'clearInputs: false':'', 'append: removeLink', ))).'}); }); ', CClientScript::POS_END); echo CHtml::link($this->addButtonLabel, '#', array( 'id'=>$this->addButtonId, 'rel'=>'.'.$this->targetClass, 'class'=>$this->addButtonCssClass) ); } }//end class
<?php namespace PayrollCalculator; use Zend\ModuleManager\Feature\<API key>; use Zend\Console\Adapter\AdapterInterface as Console; class Module { public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } public function getConsoleUsage(Console $console) { return array( // Describe available commands 'outputpaydays FileName.csv' => 'Show pay days for the remainder of the year', // Describe expected parameters array( 'FileName.csv', 'A file where you would like your output saved' ), ); } }
from django.utils.translation import ugettext as _ from django.db import models from jmbo.models import ModelBase class Superhero(ModelBase): name = models.CharField(max_length=256, editable=False) class Meta: verbose_name_plural = _("Superheroes")
export default {"viewBox":"0 0 100 100","xmlns":"http:
<?php namespace common\widgets; use yii\helpers\VarDumper; class PredictionAsset extends \yii\web\AssetBundle { public $depends = [ 'yii\web\JqueryAsset', ]; public $css = [ ]; public $js = [ ]; public function init() { $this->setSourcePath(__DIR__ . '/assets/prediction'); parent::init(); } /** * Sets the source path if empty * * @param string $path the path to be set */ protected function setSourcePath($path) { if (empty($this->sourcePath)) { $this->sourcePath = $path; } } }
/*@author gihan tharanga*/ #include <iostream> #include <string> //video capturing methods int videoCapturing(); int videoCapOriginal(); /*detect the faces display the frames and number of face*/ int FaceDetector(std::string&);
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.c Label Definition File: <API key>.label.xml Template File: sources-sinks-07.tmpl.c */ /* * @description * CWE: 191 Integer Underflow * BadSource: rand Set data to result of rand() * GoodSource: Set data to a small, non-zero number (negative two) * Sinks: decrement * GoodSink: Ensure there will not be an underflow before decrementing data * BadSink : Decrement data, which can cause an Underflow * Flow Variant: 07 Control flow: if(staticFive==5) and if(staticFive!=5) * * */ #include "std_testcase.h" /* The variable below is not declared "const", but is never assigned any other value so a tool should be able to identify that reads of this will always give its initialized value. */ static int staticFive = 5; #ifndef OMITBAD void <API key>() { short data; data = 0; if(staticFive==5) { /* POTENTIAL FLAW: Use a random value */ data = (short)RAND32(); } if(staticFive==5) { { /* POTENTIAL FLAW: Decrementing data could cause an underflow */ data short result = data; printIntLine(result); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G1() - use badsource and goodsink by changing the second staticFive==5 to staticFive!=5 */ static void goodB2G1() { short data; data = 0; if(staticFive==5) { /* POTENTIAL FLAW: Use a random value */ data = (short)RAND32(); } if(staticFive!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Add a check to prevent an underflow from occurring */ if (data > SHRT_MIN) { data short result = data; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ static void goodB2G2() { short data; data = 0; if(staticFive==5) { /* POTENTIAL FLAW: Use a random value */ data = (short)RAND32(); } if(staticFive==5) { /* FIX: Add a check to prevent an underflow from occurring */ if (data > SHRT_MIN) { data short result = data; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodG2B1() - use goodsource and badsink by changing the first staticFive==5 to staticFive!=5 */ static void goodG2B1() { short data; data = 0; if(staticFive!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */ data = -2; } if(staticFive==5) { { /* POTENTIAL FLAW: Decrementing data could cause an underflow */ data short result = data; printIntLine(result); } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ static void goodG2B2() { short data; data = 0; if(staticFive==5) { /* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */ data = -2; } if(staticFive==5) { { /* POTENTIAL FLAW: Decrementing data could cause an underflow */ data short result = data; printIntLine(result); } } } void <API key>() { goodB2G1(); goodB2G2(); goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); <API key>(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); <API key>(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
<?php namespace VKBansal\Test\Spectrum\Plugin; class PlugTest extends \<API key>{ protected $plugin; protected $plug; public function setUp() { $this->plugin = $this-><API key>('VKBansal\Spectrum\Plugin\AbstractPlugin'); $this->plugin ->method('getName')->will($this->returnValue('test-plugin')); $this->plugin ->method('add')->will($this->returnValue(true)); $this->plugin ->method('remove')->will($this->returnValue(true)); $this->plug = $this->getMockForTrait('VKBansal\Spectrum\Plugin\PluggableTrait', [], 'Spectrum'); } /** * @expectedException \VKBansal\Spectrum\Plugin\<API key> */ public function testRemoveException() { $this->markTestSkipped(); $this->plug->addPlugin($this->plugin); $this->plug->removePlugin('test-plugin'); $this->plug->removePlugin('test-plugin'); } }
<div> <div class="os-page-commands"> <div class="left" os-imaging> <button show-if-allowed="specimenResource.updateOpts" class="default" ui-sref="specimen-addedit" ng-if="!!visit.id && !specimen.reserved && (!specimen.activityStatus || specimen.activityStatus == 'Active')" ng-switch on="!!specimen.id"> <span ng-switch-when="true"> <span class="fa fa-pencil"></span> <span translate="common.buttons.edit">Edit</span> </span> <span ng-switch-default> <span class="fa fa-plus"></span> <span translate="specimens.buttons.collect">Collect</span> </span> </button> <span ng-if="!!specimen.id"> <div ng-if="!specimen.reserved && specimen.activityStatus == 'Active' && specimen.status == 'Collected'" show-if-allowed="specimenResource.allUpdateOpts" dropdown class="os-inline-btn"> <button class="btn btn-default dropdown-toggle default"> <span class="fa fa-plus"></span> <span translate="common.buttons.create">Create</span> <span class="fa fa-caret-down"></span> </button> <ul class="dropdown-menu"> <li> <a ui-sref="<API key>( {eventId: visit.eventId, visitId: visit.id, specimenId: specimen.id, srId: specimen.reqId})"> <span class="fa fa-flask"></span> <span translate="specimens.ctx_menu.create_derivative">Create Derivative</span> </a> </li> <li> <a ui-sref="<API key>( {eventId: visit.eventId, visitId: visit.id, specimenId: specimen.id, srId: specimen.reqId})"> <span class="fa fa-share-alt"></span> <span translate="specimens.ctx_menu.create_aliquots">Create Aliquots</span> </a> </li> </ul> </div> <<API key> menu-align="left" on-add-to-list="<API key>(list)"> </<API key>> <button show-if-allowed="specimenResource.updateOpts" class="default" ng-if="!cpViewCtx.isCoordinator && specimen.activityStatus == 'Active' && specimen.status == 'Collected'" ng-click="printSpecimenLabels()"> <span class="fa fa-print"></span> <span translate="specimens.buttons.print">Print</span> </button> <button show-if-allowed="specimenResource.deleteOpts" class="default" ng-click="deleteSpecimen()"> <span class="fa fa-trash"></span> <span translate="common.buttons.delete">Delete</span> </button> <div dropdown <API key> class="os-inline-btn"> <button class="btn btn-default dropdown-toggle default"> <span translate="common.buttons.more">More</span> <span class="fa fa-caret-down"></span> </button> <ul class="dropdown-menu dropdown-menu-right"> <li ng-if="!!specimen.imageId"> <os-view-image image-id="specimen.imageId" show-text="true"></os-view-image> </li> <li show-if-allowed="specimenResource.updateOpts" ng-if="!cpViewCtx.isCoordinator && !specimen.reserved && specimen.activityStatus == 'Active' && specimen.status == 'Collected'"> <a ui-sref="specimen-detail.events( {eventId: visit.eventId, visitId: visit.id, specimenId: specimen.id, srId: specimen.reqId})"> <span class="fa fa-calendar-o"></span> <span translate="specimens.ctx_menu.add_event">Add Event</span> </a> </li> <li show-if-allowed="specimenResource.updateOpts" ng-if="!cpViewCtx.isCoordinator && !specimen.reserved && specimen.activityStatus == 'Active' && specimen.status == 'Collected'"> <a ng-click="closeSpecimen()"> <span class="fa fa-remove"></span> <span translate="common.buttons.close">Close</span> </a> </li> <li show-if-allowed="specimenResource.updateOpts" ng-if="!cpViewCtx.isCoordinator && specimen.activityStatus == 'Closed'"> <a ng-click="reopen()"> <span class="fa fa-check"></span> <span translate="specimens.buttons.reopen">Reopen</span> </a> </li> </ul> </div> </span> </div> <div class="right"> <button class="default" <API key> ng-switch on="spmnCtx.showActivity" ng-click="toggleShowActivity()"> <span ng-switch-when="true" translate="common.buttons.hide_activity">Hide Events</span> <span ng-switch-when="false" translate="common.buttons.show_activity">Show Events</span> </button> </div> </div> <div class="clearfix <API key>"> <div class="container os-col" style="width: 100%;"> <div ng-switch on="fieldsCtx.hasDict"> <div ng-switch-when="true"> <sde-fields-overview base-fields="fieldsCtx.sysDict" fields="fieldsCtx.cpDict" obj="spmnCtx.obj" in-objs="spmnCtx.inObjs" ex-objs="spmnCtx.exObjs" watcher="spmnCtx.watcher"> </sde-fields-overview> </div> <div ng-switch-default> <div ng-include="'modules/biospecimen/participant/specimen/static-fields.html'"></div> </div> </div> <span show-if-allowed="specimenResource.allReadOpts" style="display: inline-block; width: 100%;"> <os-specimen-tree cp="cp" cpr="cpr" visit="visit" specimens="treeSpecimens" allowed-ops="specimenAllowedOps" reload="reload()" <API key>="<API key>"> </os-specimen-tree> </span> </div> <div class="os-col os-no-border" os-right-drawer open-width="34" style="position: static;"> <div ng-if="!!specimen.id"> <os-audit-overview class="os-no-top-margin" object-name="'specimen'" object-id="specimen.id"></os-audit-overview> </div> <div ng-include="'modules/biospecimen/participant/specimen/activities.html'"></div> </div> </div> </div> <script type="text/ng-template" id="modules/biospecimen/participant/specimen/static-fields.html"> <div> <ul class="os-key-values os-two-cols"> <li class="item"> <strong class="key key-sm" translate="specimens.lineage">Lineage</strong> <span class="value value-md">{{specimen.lineage | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.collection_status">Status</strong> <ng-switch on="!specimen.distributionStatus"> <ng-switch ng-switch-when="true" on="specimen.status"> <span ng-switch-when="Collected" class="value value-md os-status-collected">Collected</span> <span ng-switch-when="Missed Collection" class="value value-md os-status-missed">Missed Collection</span> <span ng-switch-when="Not Collected" class="value value-md os-status-missed">Not Collected</span> <span ng-switch-default class="value value-md os-status-pending">Pending</span> </ng-switch> <ng-switch ng-switch-when="false" on="specimen.distributionStatus"> <span ng-switch-when="Distributed"> <span class="value value-md" ng-class="specimen.availableQty > 0 ? '<API key>' : '<API key>'"> Distributed </span> </span> <span ng-switch-when="Returned" class="value value-md os-status-returned">Returned</span> </ng-switch> </ng-switch> </li> <li class="item" ng-if="barcodingEnabled"> <strong class="key key-sm" translate="specimens.barcode">Barcode</strong> <span class="value value-md">{{specimen.barcode | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.type">Specimen Type</strong> <span class="value value-md"> <span>{{specimen.type | osNoValue}}</span> <span ng-if="specimen.specimenClass">({{specimen.specimenClass}})</span> </span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.anatomic_site">Anatomic Site</strong> <span class="value value-md">{{specimen.anatomicSite | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.laterality">Laterality</strong> <span class="value value-md">{{specimen.laterality | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.initial_qty">Initial Quantity</strong> <os-spmn-measure-val value="specimen.initialQty" specimen="specimen"></os-spmn-measure-val> </li> <li class="item"> <strong class="key key-sm" translate="specimens.available_qty">Available Quantity</strong> <os-spmn-measure-val value="specimen.availableQty" specimen="specimen"></os-spmn-measure-val> </li> <li class="item"> <strong class="key key-sm" translate="specimens.concentration">Concentration</strong> <os-spmn-measure-val value="specimen.concentration" measure="'concentration'" specimen="specimen"> </os-spmn-measure-val> </li> <li class="item" ng-if="!!specimen.parentId"> <strong class="key key-sm" translate="specimens.parent_specimen">Parent Specimen</strong> <span class="value value-md"> <a ui-sref="specimen-detail.overview( {eventId: visit.eventId, visitId: visit.id, specimenId: specimen.parentId, srId: specimen.reqId})"> <span ng-if="!!specimen.parentLabel">{{specimen.parentLabel}}</span> <span ng-if="!specimen.parentLabel" translate="specimens.parent_specimen">Parent Specimen</span> </a> </span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.pathology">Pathology Status</strong> <span class="value value-md">{{specimen.pathology | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.storage_location">Storage Location</strong> <ng-switch on="!!specimen.storageLocation.id && specimen.storageLocation.id != -1"> <span class="value value-md" ng-switch-when="true"> <a ui-sref="container-detail.locations({containerId: specimen.storageLocation.id})"> <<API key> position="specimen.storageLocation"></<API key>> </a> </span> <span class="value value-md" ng-switch-default translate="specimens.virtually_located"> Virtual </span> </ng-switch> </li> <li class="item"> <strong class="key key-sm" translate="specimens.biohazards">Biohazards</strong> <span class="value value-md">{{specimen.biohazards | osArrayJoin | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.created_on">Created On</strong> <span class="value value-md">{{specimen.createdOn | date: global.dateTimeFmt | osNoValue}}</span> </li> <li class="item" ng-if="specimen.lineage != 'New'"> <strong class="key key-sm" translate="specimens.created_by">Created By</strong> <span class="value value-md">{{specimen.createdBy | osUserDisplayName | osNoValue}}</span> </li> <li class="item"> <strong class="key key-sm" translate="specimens.freeze_thaw_cycles">Freeze/Thaw Cycles</strong> <span class="value value-md">{{specimen.freezeThawCycles | osNoValue}}</span> </li> </ul> <div ng-if="!!specimen.extensionDetail"> <div <API key> ext-object="specimen.extensionDetail" show-column="2"></div> </div> <div class="os-section os-line-section" ng-if="!!specimen.comments"> <strong class="key key-sm"> <span translate="specimens.comments">Comments</span> <span>&nbsp;</span> </strong> <span class="value value-md">{{specimen.comments}}</span> </div> <div ng-include="'modules/biospecimen/participant/specimen/external-ids.html'"></div> <div class="os-section" ng-init="opCollapsed=false" ng-if="specimen.specimensPool.length >= 1"> <button class="<API key> os-btn-transparent" ng-click="opCollapsed=!opCollapsed"> <span ng-if="!opCollapsed" class="fa <API key>"></span> <span ng-if="opCollapsed" class="fa <API key>"></span> </button> <h3 class="<API key>"> <span translate="specimens.pooled_from">Pooled From</span> </h3> <div collapse="opCollapsed"> <span ng-repeat="p in specimen.specimensPool"> <a ui-sref="specimen-detail.overview({cpId: p.cpId, cprId: p.cprId, visitId: p.visitId, specimenId: p.id})"> <span>{{p.label}}{{$last ? '' : ','}}</span> </a> </span> </div> </div> <div class="os-section" ng-init="opCollapsed=false" ng-if="specimen.pooledSpecimens.length >= 1"> <button class="<API key> os-btn-transparent" ng-click="opCollapsed=!opCollapsed"> <span ng-if="!opCollapsed" class="fa <API key>"></span> <span ng-if="opCollapsed" class="fa <API key>"></span> </button> <h3 class="<API key>"> <span translate="specimens.pooled_in">Pooled In</span> </h3> <div collapse="opCollapsed"> <span ng-repeat="p in specimen.pooledSpecimens"> <a ui-sref="specimen-detail.overview({cpId: p.cpId, cprId: p.cprId, visitId: p.visitId, specimenId: p.id})"> <span>{{p.label}}{{$last ? '' : ','}}</span> </a> </span> </div> </div> </div> </script> <script type="text/ng-template" id="modules/biospecimen/participant/specimen/activities.html"> <div> <h3 class="<API key>" translate="specimens.recent_events"> Recent Activity </h3> <span ng-if="activities.length == 0" translate="common.none">None</span> <ul class="os-activity-list" ng-if="activities.length > 0"> <li class="os-activity" ng-repeat="activity in activities"> <div class="title" ng-switch on="activity.isEditable"> <a ui-sref="specimen-detail.event-overview({recordId: activity.id, formId: activity.formId})"> <ng-include src="'modules/biospecimen/participant/specimen/activity-info.html'"></ng-include> </a> </div> <div class="info"> <span> {{activity.updatedBy | osUserDisplayName}} - {{activity.updateTime | date: global.dateTimeFmt}} </span> </div> </li> </ul> </div> </script> <script type="text/ng-template" id="modules/biospecimen/participant/specimen/activity-info.html"> <span> <span ng-if="!!activity.user && !!activity.time"> {{'specimens.activity_full_info' | translate: activity}} </span> <span ng-if="!!activity.user && !activity.time"> {{'specimens.activity_user_info' | translate: activity}} </span> <span ng-if="!activity.user && !!activity.time"> {{'specimens.activity_time_info' | translate: activity}} </span> <span ng-if="!activity.user && !activity.time"> {{'specimens.activity_info' | translate: activity}} </span> </span> </script> <script type="text/ng-template" id="modules/biospecimen/participant/specimen/confirm-print.html"> <div class="os-modal"> <div class="os-modal-header"> <span translate="specimens.confirm_print">Confirm Print</span> </div> <div class="os-modal-body"> <span translate="specimens.confirm_print_q">Do you want to print child specimen labels as well?</span> </div> <div class="os-modal-footer"> <button class="btn os-btn-text" ng-click="cancel()"> <span translate="common.buttons.discard">Cancel</span> </button> <button class="btn os-btn-secondary" ng-click="printSpecimenLabels(false)"> <span translate="specimens.buttons.print_current">No, only current specimen</span> </button> <button class="btn btn-primary" ng-click="printSpecimenLabels(true)"> <span translate="common.yes">Yes</span> </button> </div> </div> </script> <script type="text/ng-template" id="modules/biospecimen/participant/specimen/external-ids.html"> <div class="os-section" ng-init="extIdsCollapsed=false" ng-if="specimen.externalIds.length > 0"> <button class="<API key> os-btn-transparent" ng-click="extIdsCollapsed=!extIdsCollapsed"> <span class="fa" ng-class="{true: '<API key>', false: '<API key>'}[extIdsCollapsed]"></span> </button> <h3 class="<API key>" translate="specimens.external_ids">External IDs</h3> <div collapse="extIdsCollapsed"> <table class="os-table os-table-muted-hdr os-border"> <thead class="os-table-head"> <tr class="row"> <th class="col col-xs-6"> <span translate="common.name">Name</span> </th> <th class="col col-xs-6"> <span translate="common.value">Value</span> </th> </tr> </thead> <tbody class="os-table-body"> <tr class="row" ng-repeat="extId in specimen.externalIds"> <td class="col col-xs-6"> <span>{{extId.name | osNoValue}}</span> </td> <td class="col col-xs-6"> <span>{{extId.value | osNoValue}}</span> </td> </tr> </tbody> </table> </div> </div> </script>
#include "config.h" #include "ewk_history.h" #include "BackForwardList.h" #include "CairoUtilitiesEfl.h" #include "HistoryItem.h" #include "IconDatabaseBase.h" #include "Image.h" #include "IntSize.h" #include "Page.h" #include "PageGroup.h" #include "ewk_history_private.h" #include "ewk_private.h" #include <Eina.h> #include <eina_safety_checks.h> #include <wtf/text/CString.h> struct _Ewk_History { WebCore::BackForwardList* core; }; #define <API key>(history, core_, ...) \ if (!(history)) { \ CRITICAL("history is NULL."); \ return __VA_ARGS__; \ } \ if (!(history)->core) { \ CRITICAL("history->core is NULL."); \ return __VA_ARGS__; \ } \ if (!(history)->core->enabled()) { \ ERR("history->core is disabled!."); \ return __VA_ARGS__; \ } \ WebCore::BackForwardList* core_ = (history)->core struct _Ewk_History_Item { WebCore::HistoryItem* core; const char* title; const char* alternateTitle; const char* uri; const char* originalUri; }; #define <API key>(item, core_, ...) \ if (!(item)) { \ CRITICAL("item is NULL."); \ return __VA_ARGS__; \ } \ if (!(item)->core) { \ CRITICAL("item->core is NULL."); \ return __VA_ARGS__; \ } \ WebCore::HistoryItem* core_ = (item)->core static inline Eina_List* <API key>(const WebCore::HistoryItemVector& coreItems) { Eina_List* result = 0; unsigned int size; size = coreItems.size(); for (unsigned int i = 0; i < size; i++) { Ewk_History_Item* item = <API key>(coreItems[i].get()); if (item) result = eina_list_append(result, item); } return result; } Eina_Bool ewk_history_clear(Ewk_History* history) { <API key>(history, core, false); WebCore::Page* page = core->page(); if (page && page->groupPtr()) page->groupPtr()->removeVisitedLinks(); const int limit = <API key>(history); <API key>(history, 0); <API key>(history, limit); return true; } Eina_Bool ewk_history_forward(Ewk_History* history) { <API key>(history, core, false); if (core->forwardListCount() < 1) return false; core->goForward(); return true; } Eina_Bool ewk_history_back(Ewk_History* history) { <API key>(history, core, false); if (core->backListCount() < 1) return false; core->goBack(); return true; } Eina_Bool <API key>(Ewk_History* history, const Ewk_History_Item* item) { <API key>(history, history_core, false); <API key>(item, item_core, false); history_core->addItem(item_core); return true; } Eina_Bool <API key>(Ewk_History* history, const Ewk_History_Item* item) { <API key>(history, history_core, false); <API key>(item, item_core, false); history_core->goToItem(item_core); return true; } Ewk_History_Item* <API key>(const Ewk_History* history) { <API key>(history, core, 0); return <API key>(core->backItem()); } Ewk_History_Item* <API key>(const Ewk_History* history) { <API key>(history, core, 0); WebCore::HistoryItem* currentItem = core->currentItem(); if (currentItem) return <API key>(currentItem); return 0; } Ewk_History_Item* <API key>(const Ewk_History* history) { <API key>(history, core, 0); return <API key>(core->forwardItem()); } Ewk_History_Item* <API key>(const Ewk_History* history, int index) { <API key>(history, core, 0); return <API key>(core->itemAtIndex(index)); } Eina_Bool <API key>(const Ewk_History* history, const Ewk_History_Item* item) { <API key>(history, history_core, false); <API key>(item, item_core, false); return history_core->containsItem(item_core); } Eina_List* <API key>(const Ewk_History* history) { <API key>(history, core, 0); WebCore::HistoryItemVector items; int limit = core->forwardListCount(); core-><API key>(limit, items); return <API key>(items); } Eina_List* <API key>(const Ewk_History* history, int limit) { <API key>(history, core, 0); WebCore::HistoryItemVector items; core-><API key>(limit, items); return <API key>(items); } int <API key>(const Ewk_History* history) { <API key>(history, core, 0); return core->forwardListCount(); } Eina_List* <API key>(const Ewk_History* history) { <API key>(history, core, 0); WebCore::HistoryItemVector items; int limit = core->backListCount(); core->backListWithLimit(limit, items); return <API key>(items); } Eina_List* <API key>(const Ewk_History* history, int limit) { <API key>(history, core, 0); WebCore::HistoryItemVector items; core->backListWithLimit(limit, items); return <API key>(items); } int <API key>(const Ewk_History* history) { <API key>(history, core, 0); return core->backListCount(); } int <API key>(Ewk_History* history) { <API key>(history, core, 0); return core->capacity(); } Eina_Bool <API key>(const Ewk_History* history, int limit) { <API key>(history, core, false); core->setCapacity(limit); return true; } Ewk_History_Item* <API key>(WebCore::HistoryItem* core) { Ewk_History_Item* item; if (!core) { ERR("WebCore::HistoryItem is NULL."); return 0; } core->ref(); item = new Ewk_History_Item; memset(item, 0, sizeof(*item)); item->core = core; return item; } Ewk_History_Item* <API key>(const char* uri, const char* title) { WTF::String historyUri = WTF::String::fromUTF8(uri); WTF::String historyTitle = WTF::String::fromUTF8(title); WTF::RefPtr<WebCore::HistoryItem> core = WebCore::HistoryItem::create(historyUri, historyTitle, 0); Ewk_History_Item* item = <API key>(core.release().leakRef()); return item; } static inline void <API key>(Ewk_History_Item* item, WebCore::HistoryItem* core) { core->deref(); delete item; } void <API key>(Ewk_History_Item* item) { <API key>(item, core); <API key>(item, core); } void <API key>(Eina_List* history_items) { void* deleteItem; EINA_LIST_FREE(history_items, deleteItem) { Ewk_History_Item* item = (Ewk_History_Item*)deleteItem; <API key>(item, item->core); } } const char* <API key>(const Ewk_History_Item* item) { <API key>(item, core, 0); // hide the following optimzation from outside Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>(item); <API key>(&historyItem->title, core->title().utf8().data()); return historyItem->title; } const char* <API key>(const Ewk_History_Item* item) { <API key>(item, core, 0); // hide the following optimzation from outside Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>(item); <API key>(&historyItem->alternateTitle, core->alternateTitle().utf8().data()); return historyItem->alternateTitle; } void <API key>(Ewk_History_Item* item, const char* title) { <API key>(item, core); if (!<API key>(&item->alternateTitle, title)) return; core->setAlternateTitle(WTF::String::fromUTF8(title)); } const char* <API key>(const Ewk_History_Item* item) { <API key>(item, core, 0); // hide the following optimzation from outside Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>((item)); <API key>(&historyItem->uri, core->urlString().utf8().data()); return historyItem->uri; } const char* <API key>(const Ewk_History_Item* item) { <API key>(item, core, 0); // hide the following optimzation from outside Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>(item); <API key>(&historyItem->originalUri, core->originalURLString().utf8().data()); return historyItem->originalUri; } double <API key>(const Ewk_History_Item* item) { <API key>(item, core, 0.0); return core->lastVisitedTime(); } cairo_surface_t* <API key>(const Ewk_History_Item* item) { <API key>(item, core, 0); RefPtr<cairo_surface_t> icon = WebCore::iconDatabase().<API key>(core->url(), WebCore::IntSize(16, 16)); if (!icon) ERR("icon is NULL."); return icon.get(); } Evas_Object* <API key>(const Ewk_History_Item* item, Evas* canvas) { <API key>(item, core, 0); <API key>(canvas, 0); RefPtr<cairo_surface_t> surface = WebCore::iconDatabase().<API key>(core->url(), WebCore::IntSize(16, 16)); if (!surface) { ERR("icon is NULL."); return 0; } return surface ? WebCore::<API key>(canvas, surface.get()).leakRef() : 0; } Eina_Bool <API key>(const Ewk_History_Item* item) { <API key>(item, core, false); return core->isInPageCache(); } int <API key>(const Ewk_History_Item* item) { <API key>(item, core, 0); return core->visitCount(); } Eina_Bool <API key>(const Ewk_History_Item* item) { <API key>(item, core, true); return core->lastVisitWasFailure(); } /** * @internal * * Creates history for given view. Called internally by ewk_view and * should never be called from outside. * * @param core WebCore::BackForwardList instance to use internally. * * @return newly allocated history instance or @c NULL on errors. */ Ewk_History* ewk_history_new(WebCore::BackForwardList* core) { Ewk_History* history; <API key>(core, 0); DBG("core=%p", core); history = new Ewk_History; history->core = core; core->ref(); return history; } /** * @internal * * Destroys previously allocated history instance. This is called * automatically by ewk_view and should never be called from outside. * * @param history instance to free */ void ewk_history_free(Ewk_History* history) { DBG("history=%p", history); history->core->deref(); delete history; } namespace EWKPrivate { WebCore::HistoryItem* coreHistoryItem(const Ewk_History_Item* ewkHistoryItem) { <API key>(ewkHistoryItem, core, 0); return core; } } // namespace EWKPrivate
<?php class Yasc_App_Config { /** * * @var array */ protected $_options = array(); /** * * @var bool */ protected $_useViewStream = false; /** * Layout. * * @var string */ protected $_layoutScript = null; public function __construct() { $this->_addDefaultPaths(); } /** * * @param array $options * @return Yasc_App_Config */ public function setOptions(Array $options) { $this->_options = $options; return $this; } /** * * @return array */ public function getOptions() { return $this->_options; } /** * * @param mixed $key * @param mixed $default * @return mixed|null */ public function getOption($key, $default = null) { if (true === isset($this->_options[$key])) { return $this->_options[$key]; } return $default; } /** * * @param array $options * @return Yasc_App_Config */ public function addOptions(Array $options) { $this->_options = array_merge($this->_options, $options); return $this; } /** * * @param mixed $key * @param mixed $value * @return Yasc_App_Config */ public function addOption($key, $value = null) { $this->_options[$key] = $value; return $this; } /** * * @param bool $flag * @return Yasc_App_Config */ public function setViewStream($flag = false) { $this->_useViewStream = $flag; return $this; } /** * * @return bool */ public function useViewStream() { return $this->_useViewStream; } /** * * @return array */ public function getViewsPaths() { return <API key>::getInstance()->getPaths( <API key>::PATH_TYPE_VIEW); } /** * * @param string $path * @return Yasc_App_Config */ public function setViewsPath($path) { <API key>::getInstance()->addPath( <API key>::<API key>, $path); return $this; } /** * * @param string $path * @return Yasc_App_Config */ public function addViewsPath($path) { <API key>::getInstance()->addPath( <API key>::PATH_TYPE_VIEW, $path); return $this; } /** * * @return string */ public function getLayoutScript() { return $this->_layoutScript; } /** * * @param string $layout * @return Yasc_App_Config */ public function setLayoutScript($layout) { if (false === is_string($layout)) { return false; } $layout = realpath($layout); if (false === is_file($layout)) { throw new Yasc_App_Exception("Layout file '{$layout}' not found"); } $this->_layoutScript = $layout; // Cause a layout is a view too, we going to add layout script folder // to the views folders. $this->addViewsPath(dirname($this->_layoutScript)); return $this; } /** * * @return array */ public function getViewHelperPaths() { return <API key>::getInstance()->getPaths( <API key>::<API key>); } /** * * @param string $classPrefix * @return string */ public function getViewHelpersPath($classPrefix = null) { return <API key>::getInstance()->getPath( <API key>::<API key>, $classPrefix); } /** * * @param string $path * @param string $classPrefix * @return Yasc_App_Config */ public function setViewHelpersPath($path, $classPrefix = null) { <API key>::getInstance()->setPath( <API key>::<API key>, $path, $classPrefix); return $this; } /** * * @param string $path * @param string $classPrefix * @return Yasc_App_Config */ public function addViewHelpersPath($path, $classPrefix = null) { <API key>::getInstance()->addPath( <API key>::<API key>, $path, $classPrefix); return $this; } /** * * @return array */ public function <API key>() { return <API key>::getInstance()->getPaths( <API key>::<API key>); } /** * * @param string $classPrefix * @return string */ public function <API key>($classPrefix = null) { return <API key>::getInstance()->getPath( <API key>::<API key>, $classPrefix); } /** * * @param string $path * @param string $classPrefix * @return Yasc_App_Config */ public function <API key>($path, $classPrefix = null) { <API key>::getInstance()->setPath( <API key>::<API key>, $path, $classPrefix); return $this; } /** * * @param string $path * @param string $classPrefix * @return Yasc_App_Config */ public function <API key>($path, $classPrefix = null) { <API key>::getInstance()->addPath( <API key>::<API key>, $path, $classPrefix); return $this; } /** * * @return array */ public function getModelPaths() { return <API key>::getInstance()->getPaths( <API key>::PATH_TYPE_MODEL); } /** * * @param string $path * @param string $classPrefix * @return Yasc_App_Config */ public function setModelsPath($path, $classPrefix = null) { <API key>::getInstance()->setPath( <API key>::PATH_TYPE_MODEL, $path, $classPrefix); return $this; } /** * * @param string $path * @param string $classPrefix * @return Yasc_App_Config */ public function addModelsPath($path, $classPrefix = null) { <API key>::getInstance()->addPath( <API key>::PATH_TYPE_MODEL, $path, $classPrefix); return $this; } /** * * @return void */ protected function _addDefaultPaths() { $views = realpath(APPLICATION_PATH . "/views"); $helpers = realpath(APPLICATION_PATH . "/views/helpers"); $models = realpath(APPLICATION_PATH . "/models"); // default paths, if they exist. if (true === is_dir($views)) { <API key>::getInstance()->addPath( <API key>::PATH_TYPE_VIEW, $views); } if (true === is_dir($helpers)) { <API key>::getInstance()->addPath( <API key>::<API key>, $helpers, "Helper"); } if (true === is_dir($models)) { <API key>::getInstance()->addPath( <API key>::PATH_TYPE_MODEL, $models, "Model"); } } }
// <API key>: Apache-2.0 WITH LLVM-exception #include "fold-implementation.h" namespace Fortran::evaluate { template <int KIND> Expr<Type<TypeCategory::Real, KIND>> <API key>( FoldingContext &context, FunctionRef<Type<TypeCategory::Real, KIND>> &&funcRef) { using T = Type<TypeCategory::Real, KIND>; using ComplexT = Type<TypeCategory::Complex, KIND>; ActualArguments &args{funcRef.arguments()}; auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)}; CHECK(intrinsic); std::string name{intrinsic->name}; if (name == "acos" || name == "acosh" || name == "asin" || name == "asinh" || (name == "atan" && args.size() == 1) || name == "atanh" || name == "bessel_j0" || name == "bessel_j1" || name == "bessel_y0" || name == "bessel_y1" || name == "cos" || name == "cosh" || name == "erf" || name == "erfc" || name == "erfc_scaled" || name == "exp" || name == "gamma" || name == "log" || name == "log10" || name == "log_gamma" || name == "sin" || name == "sinh" || name == "sqrt" || name == "tan" || name == "tanh") { CHECK(args.size() == 1); if (auto callable{context.<API key>() .<API key><Scalar, T, T>(name)}) { return <API key><T, T>( context, std::move(funcRef), *callable); } else { context.messages().Say( "%s(real(kind=%d)) cannot be folded on host"_en_US, name, KIND); } } else if (name == "atan" || name == "atan2" || name == "hypot" || name == "mod") { std::string localName{name == "atan2" ? "atan" : name}; CHECK(args.size() == 2); if (auto callable{ context.<API key>() .<API key><Scalar, T, T, T>(localName)}) { return <API key><T, T, T>( context, std::move(funcRef), *callable); } else { context.messages().Say( "%s(real(kind=%d), real(kind%d)) cannot be folded on host"_en_US, name, KIND, KIND); } } else if (name == "bessel_jn" || name == "bessel_yn") { if (args.size() == 2) { // elemental // runtime functions use int arg using Int4 = Type<TypeCategory::Integer, 4>; if (auto callable{ context.<API key>() .<API key><Scalar, T, Int4, T>(name)}) { return <API key><T, Int4, T>( context, std::move(funcRef), *callable); } else { context.messages().Say( "%s(integer(kind=4), real(kind=%d)) cannot be folded on host"_en_US, name, KIND); } } } else if (name == "abs") { // Argument can be complex or real if (auto *x{UnwrapExpr<Expr<SomeReal>>(args[0])}) { return <API key><T, T>( context, std::move(funcRef), &Scalar<T>::ABS); } else if (auto *z{UnwrapExpr<Expr<SomeComplex>>(args[0])}) { if (auto callable{ context.<API key>() .<API key><Scalar, T, ComplexT>("abs")}) { return <API key><T, ComplexT>( context, std::move(funcRef), *callable); } else { context.messages().Say( "abs(complex(kind=%d)) cannot be folded on host"_en_US, KIND); } } else { common::die(" unexpected argument type inside abs"); } } else if (name == "aimag") { return <API key><T, ComplexT>( context, std::move(funcRef), &Scalar<ComplexT>::AIMAG); } else if (name == "aint" || name == "anint") { // ANINT rounds ties away from zero, not to even common::RoundingMode mode{name == "aint" ? common::RoundingMode::ToZero : common::RoundingMode::TiesAwayFromZero}; return <API key><T, T>(context, std::move(funcRef), ScalarFunc<T, T>([&name, &context, mode]( const Scalar<T> &x) -> Scalar<T> { ValueWithRealFlags<Scalar<T>> y{x.ToWholeNumber(mode)}; if (y.flags.test(RealFlag::Overflow)) { context.messages().Say("%s intrinsic folding overflow"_en_US, name); } return y.value; })); } else if (name == "dprod") { if (auto scalars{<API key><T, T>(context, args)}) { return Fold(context, Expr<T>{Multiply<T>{ Expr<T>{std::get<0>(*scalars)}, Expr<T>{std::get<1>(*scalars)}}}); } } else if (name == "epsilon") { return Expr<T>{Scalar<T>::EPSILON()}; } else if (name == "huge") { return Expr<T>{Scalar<T>::HUGE()}; } else if (name == "max") { return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater); } else if (name == "merge") { return FoldMerge<T>(context, std::move(funcRef)); } else if (name == "min") { return FoldMINorMAX(context, std::move(funcRef), Ordering::Less); } else if (name == "real") { if (auto *expr{args[0].value().UnwrapExpr()}) { return ToReal<KIND>(context, std::move(*expr)); } } else if (name == "sign") { return <API key><T, T, T>( context, std::move(funcRef), &Scalar<T>::SIGN); } else if (name == "tiny") { return Expr<T>{Scalar<T>::TINY()}; } // TODO: cshift, dim, dot_product, eoshift, fraction, matmul, // maxval, minval, modulo, nearest, norm2, pack, product, // reduce, rrspacing, scale, set_exponent, spacing, spread, // sum, transfer, transpose, unpack, bessel_jn (transformational) and // bessel_yn (transformational) return Expr<T>{std::move(funcRef)}; } template <int KIND> Expr<Type<TypeCategory::Real, KIND>> FoldOperation( FoldingContext &context, ComplexComponent<KIND> &&x) { using Operand = Type<TypeCategory::Complex, KIND>; using Result = Type<TypeCategory::Real, KIND>; if (auto array{ApplyElementwise(context, x, std::function<Expr<Result>(Expr<Operand> &&)>{ [=](Expr<Operand> &&operand) { return Expr<Result>{ComplexComponent<KIND>{ x.isImaginaryPart, std::move(operand)}}; }})}) { return *array; } using Part = Type<TypeCategory::Real, KIND>; auto &operand{x.left()}; if (auto value{<API key><Operand>(operand)}) { if (x.isImaginaryPart) { return Expr<Part>{Constant<Part>{value->AIMAG()}}; } else { return Expr<Part>{Constant<Part>{value->REAL()}}; } } return Expr<Part>{std::move(x)}; } FOR_EACH_REAL_KIND(template class ExpressionBase, ) template class ExpressionBase<SomeReal>; } // namespace Fortran::evaluate
<?php namespace app\models; use Yii; use yii\base\Model; /** * LoginForm is the model behind the login form. */ class LoginForm extends Model { public $login; public $password; public $rememberMe = true; private $_user = false; /** * @return array the validation rules. */ public function rules() { return [ [['login', 'password'], 'required'], ['login', 'exist', 'targetClass' => '\app\models\UserModel', 'message' => Yii::t('app', 'A specified login does not exist')], ['rememberMe', 'boolean'], ['password', 'validatePassword'], ]; } /** * Validates the password. * This method serves as the inline validation for password. * * @param string $attribute the attribute currently being validated * @param array $params the additional name-value pairs given in the rule */ public function validatePassword($attribute, $params) { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute, Yii::t('app', 'Incorrect password')); } } } /** * Logs in a user using the provided username and password. * @return boolean whether the user is logged in successfully */ public function login() { if ($this->validate()) { return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0); } return false; } /** * Finds user by [[username]] * * @return User|null */ public function getUser() { if ($this->_user === false) { $this->_user = UserModel::findByLogin($this->login); } return $this->_user; } }
#include "Test.h" #if SK_SUPPORT_GPU #include "GrReducedClip.h" #endif #include "SkClipStack.h" #include "SkPath.h" #include "SkRandom.h" #include "SkRect.h" #include "SkRegion.h" static void <API key>(skiatest::Reporter* reporter) { SkClipStack s; bool doAA = false; REPORTER_ASSERT(reporter, 0 == s.getSaveCount()); // Build up a clip stack with a path, an empty clip, and a rect. s.save(); REPORTER_ASSERT(reporter, 1 == s.getSaveCount()); SkPath p; p.moveTo(5, 6); p.lineTo(7, 8); p.lineTo(5, 9); p.close(); s.clipDevPath(p, SkRegion::kIntersect_Op, doAA); s.save(); REPORTER_ASSERT(reporter, 2 == s.getSaveCount()); SkRect r = SkRect::MakeLTRB(1, 2, 3, 4); s.clipDevRect(r, SkRegion::kIntersect_Op, doAA); r = SkRect::MakeLTRB(10, 11, 12, 13); s.clipDevRect(r, SkRegion::kIntersect_Op, doAA); s.save(); REPORTER_ASSERT(reporter, 3 == s.getSaveCount()); r = SkRect::MakeLTRB(14, 15, 16, 17); s.clipDevRect(r, SkRegion::kUnion_Op, doAA); // Test that assignment works. SkClipStack copy = s; REPORTER_ASSERT(reporter, s == copy); // Test that different save levels triggers not equal. s.restore(); REPORTER_ASSERT(reporter, 2 == s.getSaveCount()); REPORTER_ASSERT(reporter, s != copy); // Test that an equal, but not copied version is equal. s.save(); REPORTER_ASSERT(reporter, 3 == s.getSaveCount()); r = SkRect::MakeLTRB(14, 15, 16, 17); s.clipDevRect(r, SkRegion::kUnion_Op, doAA); REPORTER_ASSERT(reporter, s == copy); // Test that a different op on one level triggers not equal. s.restore(); REPORTER_ASSERT(reporter, 2 == s.getSaveCount()); s.save(); REPORTER_ASSERT(reporter, 3 == s.getSaveCount()); r = SkRect::MakeLTRB(14, 15, 16, 17); s.clipDevRect(r, SkRegion::kIntersect_Op, doAA); REPORTER_ASSERT(reporter, s != copy); // Test that different state (clip type) triggers not equal. // NO LONGER VALID: if a path contains only a rect, we turn // it into a bare rect for performance reasons (working // around Chromium/JavaScript bad pattern). /* s.restore(); s.save(); SkPath rp; rp.addRect(r); s.clipDevPath(rp, SkRegion::kUnion_Op, doAA); REPORTER_ASSERT(reporter, s != copy); */ // Test that different rects triggers not equal. s.restore(); REPORTER_ASSERT(reporter, 2 == s.getSaveCount()); s.save(); REPORTER_ASSERT(reporter, 3 == s.getSaveCount()); r = SkRect::MakeLTRB(24, 25, 26, 27); s.clipDevRect(r, SkRegion::kUnion_Op, doAA); REPORTER_ASSERT(reporter, s != copy); // Sanity check s.restore(); REPORTER_ASSERT(reporter, 2 == s.getSaveCount()); copy.restore(); REPORTER_ASSERT(reporter, 2 == copy.getSaveCount()); REPORTER_ASSERT(reporter, s == copy); s.restore(); REPORTER_ASSERT(reporter, 1 == s.getSaveCount()); copy.restore(); REPORTER_ASSERT(reporter, 1 == copy.getSaveCount()); REPORTER_ASSERT(reporter, s == copy); // Test that different paths triggers not equal. s.restore(); REPORTER_ASSERT(reporter, 0 == s.getSaveCount()); s.save(); REPORTER_ASSERT(reporter, 1 == s.getSaveCount()); p.addRect(r); s.clipDevPath(p, SkRegion::kIntersect_Op, doAA); REPORTER_ASSERT(reporter, s != copy); } static void assert_count(skiatest::Reporter* reporter, const SkClipStack& stack, int count) { SkClipStack::B2TIter iter(stack); int counter = 0; while (iter.next()) { counter += 1; } REPORTER_ASSERT(reporter, count == counter); } // Exercise the SkClipStack's bottom to top and bidirectional iterators // (including the skipToTopmost functionality) static void test_iterators(skiatest::Reporter* reporter) { SkClipStack stack; static const SkRect gRects[] = { { 0, 0, 40, 40 }, { 60, 0, 100, 40 }, { 0, 60, 40, 100 }, { 60, 60, 100, 100 } }; for (size_t i = 0; i < SK_ARRAY_COUNT(gRects); i++) { // the union op will prevent these from being fused together stack.clipDevRect(gRects[i], SkRegion::kUnion_Op, false); } assert_count(reporter, stack, 4); // bottom to top iteration { const SkClipStack::Element* element = NULL; SkClipStack::B2TIter iter(stack); int i; for (i = 0, element = iter.next(); element; ++i, element = iter.next()) { REPORTER_ASSERT(reporter, SkClipStack::Element::kRect_Type == element->getType()); REPORTER_ASSERT(reporter, element->getRect() == gRects[i]); } SkASSERT(i == 4); } // top to bottom iteration { const SkClipStack::Element* element = NULL; SkClipStack::Iter iter(stack, SkClipStack::Iter::kTop_IterStart); int i; for (i = 3, element = iter.prev(); element; --i, element = iter.prev()) { REPORTER_ASSERT(reporter, SkClipStack::Element::kRect_Type == element->getType()); REPORTER_ASSERT(reporter, element->getRect() == gRects[i]); } SkASSERT(i == -1); } // skipToTopmost { const SkClipStack::Element* element = NULL; SkClipStack::Iter iter(stack, SkClipStack::Iter::kBottom_IterStart); element = iter.skipToTopmost(SkRegion::kUnion_Op); REPORTER_ASSERT(reporter, SkClipStack::Element::kRect_Type == element->getType()); REPORTER_ASSERT(reporter, element->getRect() == gRects[3]); } } // Exercise the SkClipStack's <API key> computation static void test_bounds(skiatest::Reporter* reporter, bool useRects) { static const int gNumCases = 20; static const SkRect gAnswerRectsBW[gNumCases] = { // A op B { 40, 40, 50, 50 }, { 10, 10, 50, 50 }, { 10, 10, 80, 80 }, { 10, 10, 80, 80 }, { 40, 40, 80, 80 }, // invA op B { 40, 40, 80, 80 }, { 0, 0, 100, 100 }, { 0, 0, 100, 100 }, { 0, 0, 100, 100 }, { 40, 40, 50, 50 }, // A op invB { 10, 10, 50, 50 }, { 40, 40, 50, 50 }, { 0, 0, 100, 100 }, { 0, 0, 100, 100 }, { 0, 0, 100, 100 }, // invA op invB { 0, 0, 100, 100 }, { 40, 40, 80, 80 }, { 0, 0, 100, 100 }, { 10, 10, 80, 80 }, { 10, 10, 50, 50 }, }; static const SkRegion::Op gOps[] = { SkRegion::kIntersect_Op, SkRegion::kDifference_Op, SkRegion::kUnion_Op, SkRegion::kXOR_Op, SkRegion::<API key> }; SkRect rectA, rectB; rectA.iset(10, 10, 50, 50); rectB.iset(40, 40, 80, 80); SkPath clipA, clipB; clipA.addRoundRect(rectA, SkIntToScalar(5), SkIntToScalar(5)); clipB.addRoundRect(rectB, SkIntToScalar(5), SkIntToScalar(5)); SkClipStack stack; SkRect devClipBound; bool <API key> = false; int testCase = 0; int numBitTests = useRects ? 1 : 4; for (int invBits = 0; invBits < numBitTests; ++invBits) { for (size_t op = 0; op < SK_ARRAY_COUNT(gOps); ++op) { stack.save(); bool doInvA = SkToBool(invBits & 1); bool doInvB = SkToBool(invBits & 2); clipA.setFillType(doInvA ? SkPath::<API key> : SkPath::kEvenOdd_FillType); clipB.setFillType(doInvB ? SkPath::<API key> : SkPath::kEvenOdd_FillType); if (useRects) { stack.clipDevRect(rectA, SkRegion::kIntersect_Op, false); stack.clipDevRect(rectB, gOps[op], false); } else { stack.clipDevPath(clipA, SkRegion::kIntersect_Op, false); stack.clipDevPath(clipB, gOps[op], false); } REPORTER_ASSERT(reporter, !stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID != stack.getTopmostGenID()); stack.<API key>(0, 0, 100, 100, &devClipBound, &<API key>); if (useRects) { REPORTER_ASSERT(reporter, <API key> == (gOps[op] == SkRegion::kIntersect_Op)); } else { REPORTER_ASSERT(reporter, !<API key>); } SkASSERT(testCase < gNumCases); REPORTER_ASSERT(reporter, devClipBound == gAnswerRectsBW[testCase]); ++testCase; stack.restore(); } } } // Test out 'isWideOpen' entry point static void test_isWideOpen(skiatest::Reporter* reporter) { { // Empty stack is wide open. Wide open stack means that gen id is wide open. SkClipStack stack; REPORTER_ASSERT(reporter, stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID()); } SkRect rectA, rectB; rectA.iset(10, 10, 40, 40); rectB.iset(50, 50, 80, 80); // Stack should initially be wide open { SkClipStack stack; REPORTER_ASSERT(reporter, stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID()); } // Test out case where the user specifies a union that includes everything { SkClipStack stack; SkPath clipA, clipB; clipA.addRoundRect(rectA, SkIntToScalar(5), SkIntToScalar(5)); clipA.setFillType(SkPath::<API key>); clipB.addRoundRect(rectB, SkIntToScalar(5), SkIntToScalar(5)); clipB.setFillType(SkPath::<API key>); stack.clipDevPath(clipA, SkRegion::kReplace_Op, false); stack.clipDevPath(clipB, SkRegion::kUnion_Op, false); REPORTER_ASSERT(reporter, stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID()); } // Test out union w/ a wide open clip { SkClipStack stack; stack.clipDevRect(rectA, SkRegion::kUnion_Op, false); REPORTER_ASSERT(reporter, stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID()); } // Test out empty difference from a wide open clip { SkClipStack stack; SkRect emptyRect; emptyRect.setEmpty(); stack.clipDevRect(emptyRect, SkRegion::kDifference_Op, false); REPORTER_ASSERT(reporter, stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID()); } // Test out return to wide open { SkClipStack stack; stack.save(); stack.clipDevRect(rectA, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, !stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID != stack.getTopmostGenID()); stack.restore(); REPORTER_ASSERT(reporter, stack.isWideOpen()); REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID()); } } static int count(const SkClipStack& stack) { SkClipStack::Iter iter(stack, SkClipStack::Iter::kTop_IterStart); const SkClipStack::Element* element = NULL; int count = 0; for (element = iter.prev(); element; element = iter.prev(), ++count) { ; } return count; } static void <API key>(skiatest::Reporter* reporter) { // non-intersecting rectangles SkRect rect = SkRect::MakeLTRB(0, 0, 10, 10); SkPath path; path.addRect(rect); path.<API key>(); SkClipStack stack; stack.clipDevPath(path, SkRegion::kIntersect_Op, false); SkRect bounds; SkClipStack::BoundsType boundsType; stack.getBounds(&bounds, &boundsType); REPORTER_ASSERT(reporter, SkClipStack::<API key> == boundsType); REPORTER_ASSERT(reporter, bounds == rect); } static void test_rect_replace(skiatest::Reporter* reporter) { SkRect rect = SkRect::MakeWH(100, 100); SkRect rect2 = SkRect::MakeXYWH(50, 50, 100, 100); SkRect bound; SkClipStack::BoundsType type; bool <API key>; // Adding a new rect with the replace operator should not increase // the stack depth. BW replacing BW. { SkClipStack stack; REPORTER_ASSERT(reporter, 0 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); } // Adding a new rect with the replace operator should not increase // the stack depth. AA replacing AA. { SkClipStack stack; REPORTER_ASSERT(reporter, 0 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); } // Adding a new rect with the replace operator should not increase // the stack depth. BW replacing AA replacing BW. { SkClipStack stack; REPORTER_ASSERT(reporter, 0 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); } // Make sure replace clip rects don't collapse too much. { SkClipStack stack; stack.clipDevRect(rect, SkRegion::kReplace_Op, false); stack.clipDevRect(rect2, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.save(); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 2 == count(stack)); stack.getBounds(&bound, &type, &<API key>); REPORTER_ASSERT(reporter, bound == rect); stack.restore(); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.save(); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 2 == count(stack)); stack.restore(); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.save(); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); stack.clipDevRect(rect2, SkRegion::kIntersect_Op, false); stack.clipDevRect(rect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 2 == count(stack)); stack.restore(); REPORTER_ASSERT(reporter, 1 == count(stack)); } } // Simplified path-based version of test_rect_replace. static void test_path_replace(skiatest::Reporter* reporter) { SkRect rect = SkRect::MakeWH(100, 100); SkPath path; path.addCircle(50, 50, 50); // Replace operation doesn't grow the stack. { SkClipStack stack; REPORTER_ASSERT(reporter, 0 == count(stack)); stack.clipDevPath(path, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.clipDevPath(path, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); } // Replacing rect with path. { SkClipStack stack; stack.clipDevRect(rect, SkRegion::kReplace_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.clipDevPath(path, SkRegion::kReplace_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); } } // Test out SkClipStack's merging of rect clips. In particular exercise // merging of aa vs. bw rects. static void test_rect_merging(skiatest::Reporter* reporter) { SkRect overlapLeft = SkRect::MakeLTRB(10, 10, 50, 50); SkRect overlapRight = SkRect::MakeLTRB(40, 40, 80, 80); SkRect nestedParent = SkRect::MakeLTRB(10, 10, 90, 90); SkRect nestedChild = SkRect::MakeLTRB(40, 40, 60, 60); SkRect bound; SkClipStack::BoundsType type; bool <API key>; // all bw overlapping - should merge { SkClipStack stack; stack.clipDevRect(overlapLeft, SkRegion::kReplace_Op, false); stack.clipDevRect(overlapRight, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.getBounds(&bound, &type, &<API key>); REPORTER_ASSERT(reporter, <API key>); } // all aa overlapping - should merge { SkClipStack stack; stack.clipDevRect(overlapLeft, SkRegion::kReplace_Op, true); stack.clipDevRect(overlapRight, SkRegion::kIntersect_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.getBounds(&bound, &type, &<API key>); REPORTER_ASSERT(reporter, <API key>); } // mixed overlapping - should _not_ merge { SkClipStack stack; stack.clipDevRect(overlapLeft, SkRegion::kReplace_Op, true); stack.clipDevRect(overlapRight, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, 2 == count(stack)); stack.getBounds(&bound, &type, &<API key>); REPORTER_ASSERT(reporter, !<API key>); } // mixed nested (bw inside aa) - should merge { SkClipStack stack; stack.clipDevRect(nestedParent, SkRegion::kReplace_Op, true); stack.clipDevRect(nestedChild, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.getBounds(&bound, &type, &<API key>); REPORTER_ASSERT(reporter, <API key>); } // mixed nested (aa inside bw) - should merge { SkClipStack stack; stack.clipDevRect(nestedParent, SkRegion::kReplace_Op, false); stack.clipDevRect(nestedChild, SkRegion::kIntersect_Op, true); REPORTER_ASSERT(reporter, 1 == count(stack)); stack.getBounds(&bound, &type, &<API key>); REPORTER_ASSERT(reporter, <API key>); } // reverse nested (aa inside bw) - should _not_ merge { SkClipStack stack; stack.clipDevRect(nestedChild, SkRegion::kReplace_Op, false); stack.clipDevRect(nestedParent, SkRegion::kIntersect_Op, true); REPORTER_ASSERT(reporter, 2 == count(stack)); stack.getBounds(&bound, &type, &<API key>); REPORTER_ASSERT(reporter, !<API key>); } } static void test_quickContains(skiatest::Reporter* reporter) { SkRect testRect = SkRect::MakeLTRB(10, 10, 40, 40); SkRect insideRect = SkRect::MakeLTRB(20, 20, 30, 30); SkRect intersectingRect = SkRect::MakeLTRB(25, 25, 50, 50); SkRect outsideRect = SkRect::MakeLTRB(0, 0, 50, 50); SkRect nonIntersectingRect = SkRect::MakeLTRB(100, 100, 110, 110); SkPath insideCircle; insideCircle.addCircle(25, 25, 5); SkPath intersectingCircle; intersectingCircle.addCircle(25, 40, 10); SkPath outsideCircle; outsideCircle.addCircle(25, 25, 50); SkPath <API key>; <API key>.addCircle(100, 100, 5); { SkClipStack stack; stack.clipDevRect(outsideRect, SkRegion::kDifference_Op, false); // return false because quickContains currently does not care for kDifference_Op REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } // Replace Op tests { SkClipStack stack; stack.clipDevRect(outsideRect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, true == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevRect(insideRect, SkRegion::kIntersect_Op, false); stack.save(); // To prevent in-place substitution by replace OP stack.clipDevRect(outsideRect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, true == stack.quickContains(testRect)); stack.restore(); } { SkClipStack stack; stack.clipDevRect(outsideRect, SkRegion::kIntersect_Op, false); stack.save(); // To prevent in-place substitution by replace OP stack.clipDevRect(insideRect, SkRegion::kReplace_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); stack.restore(); } // Verify proper traversal of multi-element clip { SkClipStack stack; stack.clipDevRect(insideRect, SkRegion::kIntersect_Op, false); // Use a path for second clip to prevent in-place intersection stack.clipDevPath(outsideCircle, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } // Intersect Op tests with rectangles { SkClipStack stack; stack.clipDevRect(outsideRect, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, true == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevRect(insideRect, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevRect(intersectingRect, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevRect(nonIntersectingRect, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } // Intersect Op tests with circle paths { SkClipStack stack; stack.clipDevPath(outsideCircle, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, true == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevPath(insideCircle, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevPath(intersectingCircle, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; stack.clipDevPath(<API key>, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } // Intersect Op tests with inverse filled rectangles { SkClipStack stack; SkPath path; path.addRect(outsideRect); path.<API key>(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; SkPath path; path.addRect(insideRect); path.<API key>(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; SkPath path; path.addRect(intersectingRect); path.<API key>(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; SkPath path; path.addRect(nonIntersectingRect); path.<API key>(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, true == stack.quickContains(testRect)); } // Intersect Op tests with inverse filled circles { SkClipStack stack; SkPath path = outsideCircle; path.<API key>(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; SkPath path = insideCircle; path.<API key>(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; SkPath path = intersectingCircle; path.<API key>(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, false == stack.quickContains(testRect)); } { SkClipStack stack; SkPath path = <API key>; path.<API key>(); stack.clipDevPath(path, SkRegion::kIntersect_Op, false); REPORTER_ASSERT(reporter, true == stack.quickContains(testRect)); } } #if SK_SUPPORT_GPU // Functions that add a shape to the clip stack. The shape is computed from a rectangle. // AA is always disabled since the clip stack reducer can cause changes in aa rasterization of the // stack. A fractional edge repeated in different elements may be rasterized fewer times using the // reduced stack. typedef void (*AddElementFunc) (const SkRect& rect, bool invert, SkRegion::Op op, SkClipStack* stack); static void add_round_rect(const SkRect& rect, bool invert, SkRegion::Op op, SkClipStack* stack) { SkPath path; SkScalar rx = rect.width() / 10; SkScalar ry = rect.height() / 20; path.addRoundRect(rect, rx, ry); if (invert) { path.setFillType(SkPath::<API key>); } stack->clipDevPath(path, op, false); }; static void add_rect(const SkRect& rect, bool invert, SkRegion::Op op, SkClipStack* stack) { if (invert) { SkPath path; path.addRect(rect); path.setFillType(SkPath::<API key>); stack->clipDevPath(path, op, false); } else { stack->clipDevRect(rect, op, false); } }; static void add_oval(const SkRect& rect, bool invert, SkRegion::Op op, SkClipStack* stack) { SkPath path; path.addOval(rect); if (invert) { path.setFillType(SkPath::<API key>); } stack->clipDevPath(path, op, false); }; static void add_elem_to_stack(const SkClipStack::Element& element, SkClipStack* stack) { switch (element.getType()) { case SkClipStack::Element::kRect_Type: stack->clipDevRect(element.getRect(), element.getOp(), element.isAA()); break; case SkClipStack::Element::kPath_Type: stack->clipDevPath(element.getPath(), element.getOp(), element.isAA()); break; case SkClipStack::Element::kEmpty_Type: SkDEBUGFAIL("Why did the reducer produce an explicit empty."); stack->clipEmpty(); break; } } static void add_elem_to_region(const SkClipStack::Element& element, const SkIRect& bounds, SkRegion* region) { SkRegion elemRegion; SkRegion boundsRgn(bounds); switch (element.getType()) { case SkClipStack::Element::kRect_Type: { SkPath path; path.addRect(element.getRect()); elemRegion.setPath(path, boundsRgn); break; } case SkClipStack::Element::kPath_Type: elemRegion.setPath(element.getPath(), boundsRgn); break; case SkClipStack::Element::kEmpty_Type: region->setEmpty(); return; } region->op(elemRegion, element.getOp()); } static void <API key>(skiatest::Reporter* reporter) { // We construct random clip stacks, reduce them, and then rasterize both versions to verify that // they are equal. // All the clip elements will be contained within these bounds. static const SkRect kBounds = SkRect::MakeWH(100, 100); enum { kNumTests = 200, kMinElemsPerTest = 1, kMaxElemsPerTest = 50, }; // min/max size of a clip element as a fraction of kBounds. static const SkScalar kMinElemSizeFrac = SK_Scalar1 / 5; static const SkScalar kMaxElemSizeFrac = SK_Scalar1; static const SkRegion::Op kOps[] = { SkRegion::kDifference_Op, SkRegion::kIntersect_Op, SkRegion::kUnion_Op, SkRegion::kXOR_Op, SkRegion::<API key>, SkRegion::kReplace_Op, }; // Replace operations short-circuit the optimizer. We want to make sure that we test this code // path a little bit but we don't want it to prevent us from testing many longer traversals in // the optimizer. static const int kReplaceDiv = 4 * kMaxElemsPerTest; // We want to test inverse fills. However, they are quite rare in practice so don't over do it. static const SkScalar kFractionInverted = SK_Scalar1 / kMaxElemsPerTest; static const AddElementFunc kElementFuncs[] = { add_rect, add_round_rect, add_oval, }; SkRandom r; for (int i = 0; i < kNumTests; ++i) { // Randomly generate a clip stack. SkClipStack stack; int numElems = r.nextRangeU(kMinElemsPerTest, kMaxElemsPerTest); for (int e = 0; e < numElems; ++e) { SkRegion::Op op = kOps[r.nextULessThan(SK_ARRAY_COUNT(kOps))]; if (op == SkRegion::kReplace_Op) { if (r.nextU() % kReplaceDiv) { --e; continue; } } // saves can change the clip stack behavior when an element is added. bool doSave = r.nextBool(); SkSize size = SkSize::Make( <API key>(SkScalarMul(kBounds.width(), r.nextRangeScalar(kMinElemSizeFrac, kMaxElemSizeFrac))), <API key>(SkScalarMul(kBounds.height(), r.nextRangeScalar(kMinElemSizeFrac, kMaxElemSizeFrac)))); SkPoint xy = {<API key>(r.nextRangeScalar(kBounds.fLeft, kBounds.fRight - size.fWidth)), <API key>(r.nextRangeScalar(kBounds.fTop, kBounds.fBottom - size.fHeight))}; SkRect rect = SkRect::MakeXYWH(xy.fX, xy.fY, size.fWidth, size.fHeight); bool invert = r.nextBiasedBool(kFractionInverted); kElementFuncs[r.nextULessThan(SK_ARRAY_COUNT(kElementFuncs))](rect, invert, op, &stack); if (doSave) { stack.save(); } } SkRect inflatedBounds = kBounds; inflatedBounds.outset(kBounds.width() / 2, kBounds.height() / 2); SkIRect inflatedIBounds; inflatedBounds.roundOut(&inflatedIBounds); typedef GrReducedClip::ElementList ElementList; // Get the reduced version of the stack. ElementList reducedClips; int32_t reducedGenID; GrReducedClip::InitialState initial; SkIRect tBounds(inflatedIBounds); SkIRect* tightBounds = r.nextBool() ? &tBounds : NULL; GrReducedClip::ReduceClipStack(stack, inflatedIBounds, &reducedClips, &reducedGenID, &initial, tightBounds); REPORTER_ASSERT(reporter, SkClipStack::kInvalidGenID != reducedGenID); // Build a new clip stack based on the reduced clip elements SkClipStack reducedStack; if (GrReducedClip::<API key> == initial) { // whether the result is bounded or not, the whole plane should start outside the clip. reducedStack.clipEmpty(); } for (ElementList::Iter iter = reducedClips.headIter(); NULL != iter.get(); iter.next()) { add_elem_to_stack(*iter.get(), &reducedStack); } // GrReducedClipStack assumes that the final result is clipped to the returned bounds if (NULL != tightBounds) { reducedStack.clipDevRect(*tightBounds, SkRegion::kIntersect_Op); } // convert both the original stack and reduced stack to SkRegions and see if they're equal SkRegion region; SkRegion reducedRegion; region.setRect(inflatedIBounds); const SkClipStack::Element* element; SkClipStack::Iter iter(stack, SkClipStack::Iter::kBottom_IterStart); while ((element = iter.next())) { add_elem_to_region(*element, inflatedIBounds, &region); } reducedRegion.setRect(inflatedIBounds); iter.reset(reducedStack, SkClipStack::Iter::kBottom_IterStart); while ((element = iter.next())) { add_elem_to_region(*element, inflatedIBounds, &reducedRegion); } REPORTER_ASSERT(reporter, region == reducedRegion); } } #if defined(WIN32) #define <API key> #else #define <API key> __attribute__((visibility("hidden"))) #endif static void <API key>(skiatest::Reporter* reporter) { { SkClipStack stack; stack.clipDevRect(SkRect::MakeXYWH(0, 0, 100, 100), SkRegion::kReplace_Op, true); stack.clipDevRect(SkRect::MakeXYWH(0, 0, SkScalar(50.3), SkScalar(50.3)), SkRegion::kReplace_Op, true); SkIRect inflatedIBounds = SkIRect::MakeXYWH(0, 0, 100, 100); GrReducedClip::ElementList reducedClips; int32_t reducedGenID; GrReducedClip::InitialState initial; SkIRect tightBounds; GrReducedClip::ReduceClipStack(stack, inflatedIBounds, &reducedClips, &reducedGenID, &initial, &tightBounds); REPORTER_ASSERT(reporter, reducedClips.count() == 1); // Clips will be cached based on the generation id. Make sure the gen id is valid. REPORTER_ASSERT(reporter, SkClipStack::kInvalidGenID != reducedGenID); } { SkClipStack stack; // Create a clip with following 25.3, 25.3 boxes which are 25 apart: // A B // C D stack.clipDevRect(SkRect::MakeXYWH(0, 0, SkScalar(25.3), SkScalar(25.3)), SkRegion::kReplace_Op, true); int32_t genIDA = stack.getTopmostGenID(); stack.clipDevRect(SkRect::MakeXYWH(50, 0, SkScalar(25.3), SkScalar(25.3)), SkRegion::kUnion_Op, true); int32_t genIDB = stack.getTopmostGenID(); stack.clipDevRect(SkRect::MakeXYWH(0, 50, SkScalar(25.3), SkScalar(25.3)), SkRegion::kUnion_Op, true); int32_t genIDC = stack.getTopmostGenID(); stack.clipDevRect(SkRect::MakeXYWH(50, 50, SkScalar(25.3), SkScalar(25.3)), SkRegion::kUnion_Op, true); int32_t genIDD = stack.getTopmostGenID(); #define XYWH SkIRect::MakeXYWH SkIRect unused; unused.setEmpty(); SkIRect stackBounds = XYWH(0, 0, 76, 76); // The base test is to test each rect in two ways: // 1) The box dimensions. (Should reduce to "all in", no elements). // 2) A bit over the box dimensions. // In the case 2, test that the generation id is what is expected. // The rects are of fractional size so that case 2 never gets optimized to an empty element // list. // Not passing in tighter bounds is tested for consistency. static const struct <API key> { SkIRect testBounds; int reducedClipCount; int32_t reducedGenID; GrReducedClip::InitialState initialState; SkIRect tighterBounds; // If this is empty, the query will not pass tighter bounds // parameter. } testCases[] = { // Rect A. { XYWH(0, 0, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, XYWH(0, 0, 25, 25) }, { XYWH(0, 0, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, unused }, { XYWH(0, 0, 27, 27), 1, genIDA, GrReducedClip::<API key>, XYWH(0, 0, 27, 27)}, { XYWH(0, 0, 27, 27), 1, genIDA, GrReducedClip::<API key>, unused }, // Rect B. { XYWH(50, 0, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, XYWH(50, 0, 25, 25) }, { XYWH(50, 0, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, unused }, { XYWH(50, 0, 27, 27), 1, genIDB, GrReducedClip::<API key>, XYWH(50, 0, 26, 27) }, { XYWH(50, 0, 27, 27), 1, genIDB, GrReducedClip::<API key>, unused }, // Rect C. { XYWH(0, 50, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, XYWH(0, 50, 25, 25) }, { XYWH(0, 50, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, unused }, { XYWH(0, 50, 27, 27), 1, genIDC, GrReducedClip::<API key>, XYWH(0, 50, 27, 26) }, { XYWH(0, 50, 27, 27), 1, genIDC, GrReducedClip::<API key>, unused }, // Rect D. { XYWH(50, 50, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, unused }, { XYWH(50, 50, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, XYWH(50, 50, 25, 25)}, { XYWH(50, 50, 27, 27), 1, genIDD, GrReducedClip::<API key>, unused }, { XYWH(50, 50, 27, 27), 1, genIDD, GrReducedClip::<API key>, XYWH(50, 50, 26, 26)}, // Other tests: { XYWH(0, 0, 100, 100), 4, genIDD, GrReducedClip::<API key>, unused }, { XYWH(0, 0, 100, 100), 4, genIDD, GrReducedClip::<API key>, stackBounds }, // Rect in the middle, touches none. { XYWH(26, 26, 24, 24), 0, SkClipStack::kEmptyGenID, GrReducedClip::<API key>, unused }, { XYWH(26, 26, 24, 24), 0, SkClipStack::kEmptyGenID, GrReducedClip::<API key>, XYWH(26, 26, 24, 24) }, // Rect in the middle, touches all the rects. GenID is the last rect. { XYWH(24, 24, 27, 27), 4, genIDD, GrReducedClip::<API key>, unused }, { XYWH(24, 24, 27, 27), 4, genIDD, GrReducedClip::<API key>, XYWH(24, 24, 27, 27) }, }; #undef XYWH for (size_t i = 0; i < SK_ARRAY_COUNT(testCases); ++i) { GrReducedClip::ElementList reducedClips; int32_t reducedGenID; GrReducedClip::InitialState initial; SkIRect tightBounds; GrReducedClip::ReduceClipStack(stack, testCases[i].testBounds, &reducedClips, &reducedGenID, &initial, testCases[i].tighterBounds.isEmpty() ? NULL : &tightBounds); REPORTER_ASSERT(reporter, reducedClips.count() == testCases[i].reducedClipCount); SkASSERT(reducedClips.count() == testCases[i].reducedClipCount); REPORTER_ASSERT(reporter, reducedGenID == testCases[i].reducedGenID); SkASSERT(reducedGenID == testCases[i].reducedGenID); REPORTER_ASSERT(reporter, initial == testCases[i].initialState); SkASSERT(initial == testCases[i].initialState); if (!testCases[i].tighterBounds.isEmpty()) { REPORTER_ASSERT(reporter, tightBounds == testCases[i].tighterBounds); SkASSERT(tightBounds == testCases[i].tighterBounds); } } } } static void <API key>(skiatest::Reporter* reporter) { SkClipStack stack; stack.clipDevRect(SkIRect::MakeXYWH(0, 0, 100, 100), SkRegion::kReplace_Op); stack.clipDevRect(SkIRect::MakeXYWH(0, 0, 50, 50), SkRegion::kReplace_Op); SkIRect inflatedIBounds = SkIRect::MakeXYWH(0, 0, 100, 100); GrReducedClip::ElementList reducedClips; int32_t reducedGenID; GrReducedClip::InitialState initial; SkIRect tightBounds; // At the time, this would crash. GrReducedClip::ReduceClipStack(stack, inflatedIBounds, &reducedClips, &reducedGenID, &initial, &tightBounds); REPORTER_ASSERT(reporter, 0 == reducedClips.count()); } #endif DEF_TEST(ClipStack, reporter) { SkClipStack stack; REPORTER_ASSERT(reporter, 0 == stack.getSaveCount()); assert_count(reporter, stack, 0); static const SkIRect gRects[] = { { 0, 0, 100, 100 }, { 25, 25, 125, 125 }, { 0, 0, 1000, 1000 }, { 0, 0, 75, 75 } }; for (size_t i = 0; i < SK_ARRAY_COUNT(gRects); i++) { stack.clipDevRect(gRects[i], SkRegion::kIntersect_Op); } // all of the above rects should have been intersected, leaving only 1 rect SkClipStack::B2TIter iter(stack); const SkClipStack::Element* element = iter.next(); SkRect answer; answer.iset(25, 25, 75, 75); REPORTER_ASSERT(reporter, NULL != element); REPORTER_ASSERT(reporter, SkClipStack::Element::kRect_Type == element->getType()); REPORTER_ASSERT(reporter, SkRegion::kIntersect_Op == element->getOp()); REPORTER_ASSERT(reporter, element->getRect() == answer); // now check that we only had one in our iterator REPORTER_ASSERT(reporter, !iter.next()); stack.reset(); REPORTER_ASSERT(reporter, 0 == stack.getSaveCount()); assert_count(reporter, stack, 0); <API key>(reporter); test_iterators(reporter); test_bounds(reporter, true); // once with rects test_bounds(reporter, false); // once with paths test_isWideOpen(reporter); test_rect_merging(reporter); test_rect_replace(reporter); <API key>(reporter); test_path_replace(reporter); test_quickContains(reporter); #if SK_SUPPORT_GPU <API key>(reporter); <API key>(reporter); <API key>(reporter); #endif }
<?php namespace app\models; use Yii; use app\models\general\GeneralLabel; use app\models\general\GeneralMessage; /** * This is the model class for table "tbl_six_step". * * @property integer $six_step_id * @property integer $atlet_id * @property string $stage * @property string $status */ class SixStepBiomekanik extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '<API key>'; } public function behaviors() { return [ 'bedezign\yii2\audit\AuditTrailBehavior', [ 'class' => \yii\behaviors\BlameableBehavior::className(), 'createdByAttribute' => 'created_by', 'updatedByAttribute' => 'updated_by', ], [ 'class' => \yii\behaviors\TimestampBehavior::className(), 'createdAtAttribute' => 'created', 'updatedAtAttribute' => 'updated', 'value' => new \yii\db\Expression('NOW()'), ], ]; } /** * @inheritdoc */ public function rules() { return [ [['atlet_id', 'stage', 'status', 'tarikh'], 'required', 'skipOnEmpty' => true, 'message' => GeneralMessage::<API key>], [['atlet_id', 'kategori_atlet', 'sukan', 'acara'], 'integer', 'message' => GeneralMessage::<API key>], [['stage', 'status'], 'string', 'max' => 30, 'tooLong' => GeneralMessage::<API key>], [['stage', 'status'], function ($attribute, $params) { if (!\common\models\general\GeneralFunction::validateXSS($this->$attribute)) { $this->addError($attribute, GeneralMessage::yii_validation_xss); } }], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'six_step_id' => GeneralLabel::six_step_id, 'atlet_id' => GeneralLabel::atlet_id, 'kategori_atlet' => GeneralLabel::kategori_atlet, 'sukan' => GeneralLabel::sukan, 'acara' => GeneralLabel::acara, 'stage' => GeneralLabel::stage, 'status' => GeneralLabel::status, 'tarikh' => GeneralLabel::tarikh, ]; } /** * @return \yii\db\ActiveQuery */ public function getAtlet(){ return $this->hasOne(Atlet::className(), ['atlet_id' => 'atlet_id']); } /** * @return \yii\db\ActiveQuery */ public function <API key>(){ return $this->hasOne(<API key>::className(), ['id' => 'stage']); } /** * @return \yii\db\ActiveQuery */ public function <API key>(){ return $this->hasOne(<API key>::className(), ['id' => 'status']); } }
from qiime2.plugin import SemanticType from ..plugin_setup import plugin from . import <API key> SampleData = SemanticType('SampleData', field_names='type') AlphaDiversity = SemanticType('AlphaDiversity', variant_of=SampleData.field['type']) plugin.<API key>(SampleData, AlphaDiversity) plugin.<API key>( SampleData[AlphaDiversity], artifact_format=<API key> )
using System; using System.Data; using System.Data.SqlClient; using System.IO; using System.Xml.Serialization; using JetBat.Client.Entities; using JetBat.Client.Metadata.Abstract; using JetBat.Client.Metadata.Definitions; using JetBat.Client.Metadata.Misc; using JetBat.Client.Metadata.Simple; namespace JetBat.Client.SqlServer.Concrete { public class <API key> : <API key> { private const int <API key> = 2; private readonly string _connectionString; private readonly bool _enableCaching; public <API key>(string connectionString, bool enableCaching) { _connectionString = connectionString; _enableCaching = enableCaching; } #region <API key> Members public Type TargetObjectType { get { return typeof(<API key>); } } public int TargetObjectID { get { return <API key>; } } public ObjectDefinition LoadImmutable(string objectNamespace, string objectName) { return new <API key>((PlainObjectListView)Load(objectNamespace, objectName)); } #endregion public BusinessObject Load(string objectNamespace, string objectName) { #region Load from cache string cacheDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, StaticHelper.<API key> + @"\PlainObjectListView"); string cacheFileName = string.Format(@"{0}\{1}.{2}.xml", cacheDirectory, objectNamespace, objectName); if (_enableCaching) { if (File.Exists(cacheFileName)) { XmlSerializer serializer = new XmlSerializer(typeof(PlainObjectListView)); using (FileStream stream = new FileStream(cacheFileName, FileMode.Open, FileAccess.Read)) return (PlainObjectListView)serializer.Deserialize(stream); } } #endregion string uiListCaption; string <API key>; string basicObjectName; string <API key>; string <API key>; string namespaceName; string name; int objectType; string friendlyName; string description; <API key><ObjectAttribute> attributes; <API key><<API key>> complexAttributes; <API key><ObjectAction> actions; <API key><ObjectMethod> methods; using (SqlConnection sqlConnection = new SqlConnection(_connectionString)) { sqlConnection.Open(); SqlCommand command = new SqlCommand("<API key>", sqlConnection) { CommandType = CommandType.StoredProcedure }; command.Parameters.AddWithValue("@Namespace", objectNamespace); command.Parameters.AddWithValue("@Name", objectName); SqlDataReader reader = command.ExecuteReader(); if (reader == null) throw new <API key>("DataReader is null while must not be."); using (reader) { reader.Read(); uiListCaption = reader["UIListCaption"].ToString(); <API key> = Convert.ToString(reader["EntityNamespaceName"]); basicObjectName = Convert.ToString(reader["EntityName"]); <API key> = reader["<API key>"].Equals(DBNull.Value) ? "" : Convert.ToString(reader["<API key>"]); <API key> = reader["<API key>"].Equals(DBNull.Value) ? "" : Convert.ToString(reader["<API key>"]); objectType = Convert.ToInt32(reader["ObjectTypeID"]); namespaceName = Convert.ToString(reader["NamespaceName"]); name = Convert.ToString(reader["Name"]); friendlyName = Convert.ToString(reader["FriendlyName"]); description = Convert.ToString(reader["Description"]); reader.NextResult(); attributes = StaticHelper.<API key>(reader); reader.NextResult(); complexAttributes = StaticHelper.<API key>(reader); reader.NextResult(); StaticHelper.<API key>(reader, complexAttributes); reader.NextResult(); actions = StaticHelper.<API key>(reader); reader.NextResult(); methods = StaticHelper.<API key>(reader); reader.NextResult(); StaticHelper.<API key>(reader, methods); } } BusinessObject definition = new PlainObjectListView { UIListCaption = uiListCaption, <API key> = <API key>, BasicObjectName = basicObjectName, <API key> = <API key>, <API key> = <API key>, ObjectNamespace = namespaceName, ObjectName = name, ObjectType = objectType, FriendlyName = friendlyName, Description = description, Attributes = attributes, ComplexAttributes = complexAttributes, Actions = actions, Methods = methods }; #region Save to cache if (_enableCaching) { if (!Directory.Exists(cacheDirectory)) Directory.CreateDirectory(cacheDirectory); XmlSerializer serializer = new XmlSerializer(typeof(PlainObjectListView)); using (FileStream stream = new FileStream(cacheFileName, FileMode.OpenOrCreate, FileAccess.Write)) serializer.Serialize(stream, definition); } #endregion return definition; } } }
from ..base import BaseTopazTest class TestMarshal(BaseTopazTest): def <API key>(self, space): w_res = space.execute("return Marshal::MAJOR_VERSION") assert space.int_w(w_res) == 4 w_res = space.execute("return Marshal::MINOR_VERSION") assert space.int_w(w_res) == 8 w_res = space.execute("return Marshal.dump('test')[0].ord") assert space.int_w(w_res) == 4 w_res = space.execute("return Marshal.dump('test')[1].ord") assert space.int_w(w_res) == 8 def test_dump_constants(self, space): w_res = space.execute("return Marshal.dump(nil)") assert space.str_w(w_res) == "\x04\b0" w_res = space.execute("return Marshal.dump(true)") assert space.str_w(w_res) == "\x04\bT" w_res = space.execute("return Marshal.dump(false)") assert space.str_w(w_res) == "\x04\bF" def test_load_constants(self, space): w_res = space.execute("return Marshal.load('\x04\b0')") assert w_res == space.w_nil w_res = space.execute("return Marshal.load('\x04\bT')") assert w_res == space.w_true w_res = space.execute("return Marshal.load('\x04\bF')") assert w_res == space.w_false def test_constants(self, space): w_res = space.execute("return Marshal.load(Marshal.dump(nil))") assert w_res == space.w_nil w_res = space.execute("return Marshal.load(Marshal.dump(true))") assert w_res == space.w_true w_res = space.execute("return Marshal.load(Marshal.dump(false))") assert w_res == space.w_false def <API key>(self, space): w_res = space.execute("return Marshal.dump(5)") assert space.str_w(w_res) == "\x04\bi\n" w_res = space.execute("return Marshal.dump(100)") assert space.str_w(w_res) == "\x04\bii" w_res = space.execute("return Marshal.dump(0)") assert space.str_w(w_res) == "\x04\bi\x00" w_res = space.execute("return Marshal.dump(-1)") assert space.str_w(w_res) == "\x04\bi\xFA" w_res = space.execute("return Marshal.dump(-123)") assert space.str_w(w_res) == "\x04\bi\x80" w_res = space.execute("return Marshal.dump(122)") assert space.str_w(w_res) == "\x04\bi\x7F" def <API key>(self, space): w_res = space.execute("return Marshal.load('\x04\bi\n')") assert space.int_w(w_res) == 5 w_res = space.execute("return Marshal.load('\x04\bii')") assert space.int_w(w_res) == 100 #w_res = space.execute('return Marshal.load("\x04\bi\x00")') w_res = space.execute('return Marshal.load(Marshal.dump(0))') assert space.int_w(w_res) == 0 w_res = space.execute("return Marshal.load('\x04\bi\xFA')") assert space.int_w(w_res) == -1 w_res = space.execute("return Marshal.load('\x04\bi\x80')") assert space.int_w(w_res) == -123 w_res = space.execute("return Marshal.load('\x04\bi\x7F')") assert space.int_w(w_res) == 122 def test_dump_array(self, space): w_res = space.execute("return Marshal.dump([])") assert space.str_w(w_res) == "\x04\b[\x00" w_res = space.execute("return Marshal.dump([nil])") assert space.str_w(w_res) == "\x04\b[\x060" w_res = space.execute("return Marshal.dump([nil, true, false])") assert space.str_w(w_res) == "\x04\b[\b0TF" w_res = space.execute("return Marshal.dump([1, 2, 3])") assert space.str_w(w_res) == "\x04\b[\x08i\x06i\x07i\x08" w_res = space.execute("return Marshal.dump([1, [2, 3], 4])") assert space.str_w(w_res) == "\x04\b[\bi\x06[\ai\ai\bi\t" w_res = space.execute("return Marshal.dump([:foo, :bar])") assert space.str_w(w_res) == "\x04\b[\a:\bfoo:\bbar" def test_load_array(self, space): #w_res = space.execute("return Marshal.load('\x04\b[\x00')") w_res = space.execute("return Marshal.load(Marshal.dump([]))") assert self.unwrap(space, w_res) == [] w_res = space.execute("return Marshal.load('\x04\b[\x060')") assert self.unwrap(space, w_res) == [None] w_res = space.execute("return Marshal.load('\x04\b[\b0TF')") assert self.unwrap(space, w_res) == [None, True, False] w_res = space.execute("return Marshal.load('\x04\b[\x08i\x06i\x07i\x08')") assert self.unwrap(space, w_res) == [1, 2, 3] w_res = space.execute("return Marshal.load('\x04\b[\bi\x06[\ai\ai\bi\t')") assert self.unwrap(space, w_res) == [1, [2, 3], 4] w_res = space.execute("return Marshal.load('\x04\b[\a:\bfoo:\bbar')") assert self.unwrap(space, w_res) == ["foo", "bar"] def test_dump_symbol(self, space): w_res = space.execute("return Marshal.dump(:abc)") assert space.str_w(w_res) == "\x04\b:\babc" w_res = space.execute("return Marshal.dump(('hello' * 25).to_sym)") assert space.str_w(w_res) == "\x04\b:\x01}" + "hello" * 25 w_res = space.execute("return Marshal.dump(('hello' * 100).to_sym)") assert space.str_w(w_res) == "\x04\b:\x02\xF4\x01" + "hello" * 100 def test_load_symbol(self, space): w_res = space.execute("return Marshal.load('\x04\b:\babc')") assert space.symbol_w(w_res) == "abc" w_res = space.execute("return Marshal.load('\x04\b:\x01}' + 'hello' * 25)") assert space.symbol_w(w_res) == "hello" * 25 def test_dump_hash(self, space): w_res = space.execute("return Marshal.dump({})") assert space.str_w(w_res) == "\x04\b{\x00" w_res = space.execute("return Marshal.dump({1 => 2, 3 => 4})") assert self.unwrap(space, w_res) == "\x04\b{\ai\x06i\ai\bi\t" w_res = space.execute("return Marshal.dump({1 => {2 => 3}, 4 => 5})") assert self.unwrap(space, w_res) == "\x04\b{\ai\x06{\x06i\ai\bi\ti\n" w_res = space.execute("return Marshal.dump({1234 => {23456 => 3456789}, 4 => 5})") assert self.unwrap(space, w_res) == "\x04\b{\ai\x02\xD2\x04{\x06i\x02\xA0[i\x03\x15\xBF4i\ti\n" def test_load_hash(self, space): #w_res = space.execute("return Marshal.load('\x04\b{\x00')") w_res = space.execute("return Marshal.load(Marshal.dump({}))") assert self.unwrap(space, w_res) == {} w_res = space.execute("return Marshal.load('\x04\b{\ai\x06i\ai\bi\t')") assert self.unwrap(space, w_res) == {1: 2, 3: 4} w_res = space.execute("return Marshal.load('\x04\b{\ai\x06{\x06i\ai\bi\ti\n')") assert self.unwrap(space, w_res) == {1: {2: 3}, 4: 5} w_res = space.execute("return Marshal.load('\x04\b{\ai\x02\xD2\x04{\x06i\x02\xA0[i\x03\x15\xBF4i\ti\n')") assert self.unwrap(space, w_res) == {1234: {23456: 3456789}, 4: 5} def test_dump_integer(self, space): w_res = space.execute("return Marshal.dump(123)") assert space.str_w(w_res) == "\x04\bi\x01{" w_res = space.execute("return Marshal.dump(255)") assert space.str_w(w_res) == "\x04\bi\x01\xFF" w_res = space.execute("return Marshal.dump(256)") assert space.str_w(w_res) == "\x04\bi\x02\x00\x01" w_res = space.execute("return Marshal.dump(2 ** 16 - 2)") assert space.str_w(w_res) == "\x04\bi\x02\xFE\xFF" w_res = space.execute("return Marshal.dump(2 ** 16 - 1)") assert space.str_w(w_res) == "\x04\bi\x02\xFF\xFF" w_res = space.execute("return Marshal.dump(2 ** 16)") assert space.str_w(w_res) == "\x04\bi\x03\x00\x00\x01" w_res = space.execute("return Marshal.dump(2 ** 16 + 1)") assert space.str_w(w_res) == "\x04\bi\x03\x01\x00\x01" w_res = space.execute("return Marshal.dump(2 ** 30 - 1)") assert space.str_w(w_res) == "\x04\bi\x04\xFF\xFF\xFF?" # TODO: test tooo big numbers (they give a warning and inf) def test_load_integer(self, space): w_res = space.execute("return Marshal.load('\x04\bi\x01{')") assert space.int_w(w_res) == 123 w_res = space.execute("return Marshal.load('\x04\bi\x01\xFF')") assert space.int_w(w_res) == 255 #w_res = space.execute("return Marshal.load('\x04\bi\x02\x00\x01')") w_res = space.execute("return Marshal.load(Marshal.dump(256))") assert space.int_w(w_res) == 256 w_res = space.execute("return Marshal.load('\x04\bi\x02\xFE\xFF')") assert space.int_w(w_res) == 2 ** 16 - 2 w_res = space.execute("return Marshal.load('\x04\bi\x02\xFF\xFF')") assert space.int_w(w_res) == 2 ** 16 - 1 #w_res = space.execute("return Marshal.load('\x04\bi\x03\x00\x00\x01')") w_res = space.execute("return Marshal.load(Marshal.dump(2 ** 16))") assert space.int_w(w_res) == 2 ** 16 #w_res = space.execute("return Marshal.load('\x04\bi\x03\x01\x00\x01')") w_res = space.execute("return Marshal.load(Marshal.dump(2 ** 16 + 1))") assert space.int_w(w_res) == 2 ** 16 + 1 w_res = space.execute("return Marshal.load('\x04\bi\x04\xFF\xFF\xFF?')") assert space.int_w(w_res) == 2 ** 30 - 1 def <API key>(self, space): w_res = space.execute("return Marshal.dump(-1)") assert space.str_w(w_res) == "\x04\bi\xFA" w_res = space.execute("return Marshal.dump(-123)") assert space.str_w(w_res) == "\x04\bi\x80" w_res = space.execute("return Marshal.dump(-124)") assert space.str_w(w_res) == "\x04\bi\xFF\x84" w_res = space.execute("return Marshal.dump(-256)") assert space.str_w(w_res) == "\x04\bi\xFF\x00" w_res = space.execute("return Marshal.dump(-257)") assert space.str_w(w_res) == "\x04\bi\xFE\xFF\xFE" w_res = space.execute("return Marshal.dump(-(2 ** 30))") assert space.str_w(w_res) == "\x04\bi\xFC\x00\x00\x00\xC0" def <API key>(self, space): w_res = space.execute("return Marshal.load('\x04\bi\xFA')") assert space.int_w(w_res) == -1 w_res = space.execute("return Marshal.load('\x04\bi\x80')") assert space.int_w(w_res) == -123 w_res = space.execute("return Marshal.load('\x04\bi\xFF\x84')") assert space.int_w(w_res) == -124 #w_res = space.execute("return Marshal.load('\x04\bi\xFF\x00')") w_res = space.execute("return Marshal.load(Marshal.dump(-256))") assert space.int_w(w_res) == -256 w_res = space.execute("return Marshal.load('\x04\bi\xFE\xFF\xFE')") assert space.int_w(w_res) == -257 #w_res = space.execute("return Marshal.load('\x04\bi\xFE\x00\x00')") w_res = space.execute("return Marshal.load(Marshal.dump(-(2 ** 16)))") assert space.int_w(w_res) == -(2 ** 16) w_res = space.execute("return Marshal.load('\x04\bi\xFD\xFF\xFF\xFE')") assert space.int_w(w_res) == -(2 ** 16 + 1) #w_res = space.execute("return Marshal.load('\x04\bi\xFC\x00\x00\x00')") w_res = space.execute("return Marshal.load(Marshal.dump(-(2 ** 24)))") assert space.int_w(w_res) == -(2 ** 24) w_res = space.execute("return Marshal.load('\x04\bi\xFC\xFF\xFF\xFF\xFE')") assert space.int_w(w_res) == -(2 ** 24 + 1) #w_res = space.execute("return Marshal.load('\x04\bi\xFC\x00\x00\x00\xC0')") w_res = space.execute("return Marshal.load(Marshal.dump(-(2 ** 30)))") assert space.int_w(w_res) == -(2 ** 30) def test_dump_float(self, space): w_res = space.execute("return Marshal.dump(0.0)") assert space.str_w(w_res) == "\x04\bf\x060" w_res = space.execute("return Marshal.dump(0.1)") assert space.str_w(w_res) == "\x04\bf\b0.1" w_res = space.execute("return Marshal.dump(1.0)") assert space.str_w(w_res) == "\x04\bf\x061" w_res = space.execute("return Marshal.dump(1.1)") assert space.str_w(w_res) == "\x04\bf\b1.1" w_res = space.execute("return Marshal.dump(1.001)") assert space.str_w(w_res) == "\x04\bf\n1.001" #w_res = space.execute("return Marshal.dump(123456789.123456789)") #assert space.str_w(w_res) == "\x04\bf\x17123456789.12345679" #w_res = space.execute("return Marshal.dump(-123456789.123456789)") #assert space.str_w(w_res) == "\x04\bf\x18-123456789.12345679" #w_res = space.execute("return Marshal.dump(-0.0)") #assert space.str_w(w_res) == "\x04\bf\a-0" def test_load_float(self, space): w_res = space.execute("return Marshal.load('\x04\bf\x060')") assert space.float_w(w_res) == 0.0 w_res = space.execute("return Marshal.load('\x04\bf\b0.1')") assert space.float_w(w_res) == 0.1 w_res = space.execute("return Marshal.load('\x04\bf\x061')") assert space.float_w(w_res) == 1.0 w_res = space.execute("return Marshal.load('\x04\bf\b1.1')") assert space.float_w(w_res) == 1.1 w_res = space.execute("return Marshal.load('\x04\bf\n1.001')") assert space.float_w(w_res) == 1.001 #w_res = space.execute("return Marshal.load('\x04\bf\x17123456789.12345679')") #assert space.float_w(w_res) == 123456789.123456789 #w_res = space.execute("return Marshal.load('\x04\bf\x18-123456789.12345679')") #assert space.float_w(w_res) == -123456789.123456789 #w_res = space.execute("return Marshal.load('\x04\bf\a-0')") #assert repr(space.float_w(w_res)) == repr(-0.0) def test_dump_string(self, space): w_res = space.execute("return Marshal.dump('')") assert space.str_w(w_res) == "\x04\bI\"\x00\x06:\x06ET" w_res = space.execute("return Marshal.dump('abc')") assert space.str_w(w_res) == "\x04\bI\"\babc\x06:\x06ET" w_res = space.execute("return Marshal.dump('i am a longer string')") assert space.str_w(w_res) == "\x04\bI\"\x19i am a longer string\x06:\x06ET" def test_load_string(self, space): #w_res = space.execute("return Marshal.load('\x04\bI\"\x00\x06:\x06ET')") w_res = space.execute("return Marshal.load(Marshal.dump(''))") assert space.str_w(w_res) == "" w_res = space.execute("return Marshal.load('\x04\bI\"\babc\x06:\x06ET')") assert space.str_w(w_res) == "abc" w_res = space.execute("return Marshal.load('\x04\bI\"\x19i am a longer string\x06:\x06ET')") assert space.str_w(w_res) == "i am a longer string" def test_array(self, space): w_res = space.execute("return Marshal.load(Marshal.dump([1, 2, 3]))") assert self.unwrap(space, w_res) == [1, 2, 3] w_res = space.execute("return Marshal.load(Marshal.dump([1, [2, 3], 4]))") assert self.unwrap(space, w_res) == [1, [2, 3], 4] w_res = space.execute("return Marshal.load(Marshal.dump([130, [2, 3], 4]))") assert self.unwrap(space, w_res) == [130, [2, 3], 4] w_res = space.execute("return Marshal.load(Marshal.dump([-10000, [2, 123456], -9000]))") assert self.unwrap(space, w_res) == [-10000, [2, 123456], -9000] w_res = space.execute("return Marshal.load(Marshal.dump([:foo, :bar]))") assert self.unwrap(space, w_res) == ["foo", "bar"] w_res = space.execute("return Marshal.load(Marshal.dump(['foo', 'bar']))") assert self.unwrap(space, w_res) == ["foo", "bar"] def <API key>(self, space): with self.raises( space, "TypeError", "incompatible marshal file format (can't be read)\n" "format version 4.8 required; 97.115 given" ): space.execute("Marshal.load('asd')") def test_short_data(self, space): with self.raises(space, "ArgumentError", "marshal data too short"): space.execute("Marshal.load('')") def test_parameters(self, space): with self.raises(space, "TypeError", "instance of IO needed"): space.execute("Marshal.load(4)") def test_io(self, space, tmpdir): f = tmpdir.join("testfile") w_res = space.execute(""" Marshal.dump('hallo', File.new('%s', 'wb')) file = File.open('%s', 'rb') return Marshal.load(file.read) """ % (f, f)) assert space.str_w(w_res) == "hallo" w_res = space.execute(""" Marshal.dump('hallo', File.new('%s', 'wb')) file = File.open('%s', 'rb') return Marshal.load(file) """ % (f, f)) assert space.str_w(w_res) == "hallo"
package org.openquark.gems.client; import java.awt.Container; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import javax.swing.JList; import javax.swing.JViewport; import javax.swing.ListSelectionModel; import org.openquark.gems.client.IntellicutListModel.FilterLevel; import org.openquark.gems.client.<API key>.IntellicutListEntry; import org.openquark.gems.client.IntellicutManager.IntellicutMode; /** * A list that encapsulates all the details associated with populating * a list with the unqualified names of gems. * @author Ken Wong * @author Frank Worsley */ public class IntellicutList extends JList { private static final long serialVersionUID = -<API key>; /** The last list index that was visible when the state was saved. */ private int savedVisibleIndex = -1; /** The last list entry that was visible when the state was saved. */ private IntellicutListEntry savedVisibleEntry = null; /** The list entry that was selected when the state was saved. */ private IntellicutListEntry savedSelectedEntry = null; /** Whether or not this list should be drawn transparently. */ private boolean transparent = false; /** * Constructor for IntellicutList. */ public IntellicutList(IntellicutMode mode) { setName("MatchingGemsList"); setCellRenderer(new <API key>(mode)); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } /** * Enables the list to be transparent. If the list is transparent non selected list items * will let the components below them show through. Selected list items will draw a blue * semi-transparent tint as their background. * @param value whether or not the list should be transparent */ void setTransparent(boolean value) { this.transparent = value; updateUI(); } /** * @return whether or not the intellicut list is transparent */ public boolean isTransparent() { return transparent; } /** * Saves the currently selected list item and the scroll position of the * list so that the list state can be restored later. */ private void saveListState() { IntellicutListModel listModel = (IntellicutListModel) getModel(); savedVisibleEntry = null; savedSelectedEntry = null; savedVisibleIndex = getLastVisibleIndex(); int selectedIndex = getSelectedIndex(); try { savedVisibleEntry = listModel.get(savedVisibleIndex); savedSelectedEntry = listModel.get(selectedIndex); // We only want to make the selected entry visible again after refreshing // the list if it was visible before. if (selectedIndex > getLastVisibleIndex() || selectedIndex < <API key>()) { savedSelectedEntry = null; } } catch (Exception ex) { // This might throw a <API key> or <API key> // if the model is not initialized. In that case there is no index we can restore. } } /** * Restores the previously saved list state as closely as possible. */ private void restoreListState() { IntellicutListModel listModel = (IntellicutListModel) getModel(); int newSelectedIndex = listModel.indexOf(savedSelectedEntry); int newVisibleIndex = listModel.indexOf(savedVisibleEntry); if (newVisibleIndex == -1) { newVisibleIndex = savedVisibleIndex; } // We have to add one cell height, otherwise the cell will be just // outside of the visible range of the list. <API key> doesn't // work here since we want the index to appear at the very bottom. Point newLocation = indexToLocation(newVisibleIndex); if (newLocation != null) { newLocation.y += getCellBounds(0, 0).height; scrollRectToVisible(new Rectangle(newLocation)); } if (newSelectedIndex != -1) { setSelectedIndex(newSelectedIndex); <API key>(newSelectedIndex); } else { setSelectedIndex(0); } } /** * Refreshes the list while remembering the selected item and scroll position * as closely as possible. Simply refreshing the list model will not remember * the list state. * @param prefix the new prefix for values in the list */ public void refreshList(String prefix) { IntellicutListModel listModel = (IntellicutListModel) getModel(); saveListState(); listModel.refreshList(prefix); restoreListState(); } /** * Finds the JViewport this list is embedded in. * @return the viewport or null if there is no viewport */ private JViewport getViewport() { Container parent = getParent(); while (parent != null && !(parent instanceof JViewport)) { parent = parent.getParent (); } return (JViewport) parent; } /** * Scrolls the given index as close as possible to the top of the list's viewport. * @param index index of the item to scroll to the top */ void scrollToTop(int index) { Point location = indexToLocation(index); if (location == null) { return; } JViewport viewport = getViewport(); // Scroll this element as close to the top as possible. if (viewport.getViewSize().height - location.y < viewport.getSize().height) { location.y -= viewport.getSize().height - viewport.getViewSize().height + location.y; } viewport.setViewPosition(location); } /** * Sets the current gem filtering level. * * The list is automatically refreshed after doing this. This method also saves * the list's displayed state as opposed to just setting the filter level which * will not remember the list state. * @param filterLevel the new level to filter at */ void setFilterLevel(FilterLevel filterLevel) { if (filterLevel == null) { throw new <API key>("filterLevel must not be null in IntellicutList.setFilterLevel"); } IntellicutListModel listModel = (IntellicutListModel) getModel(); saveListState(); listModel.setFilterLevel(filterLevel); restoreListState(); } /** * Returns the user selected IntellicutListEntry * @return IntellicutListEntry */ IntellicutListEntry getSelected(){ return getModel().getSize() > 0 ? (IntellicutListEntry) getSelectedValue() : null; } /** * We want tooltips to be displayed to the right of an item. * If there is no item at the coordinates it returns null. * @param e the mouse event for which to determine the location * @return the tooltip location for the list item at the coordinates of the mouse event */ @Override public Point getToolTipLocation(MouseEvent e) { int index = locationToIndex(e.getPoint()); if (index == -1) { return null; } Rectangle cellBounds = getCellBounds(index, index); // take off 50 and add 5 for good looks return new Point (cellBounds.x + cellBounds.width - 50, cellBounds.y + 5); } /** * @param e the MouseEvent for which to get the tooltip text * @return the tooltip text for the list item at the coordinates or null if there is no * item at the coordinates */ @Override public String getToolTipText(MouseEvent e) { int index = locationToIndex(e.getPoint()); if (index == -1) { return null; } IntellicutListEntry listEntry = (IntellicutListEntry) getModel().getElementAt(index); if (listEntry == null) { return null; } IntellicutListModel listModel = (IntellicutListModel) getModel(); return listModel.getAdapter().<API key>(listEntry, this); } }
# modification, are permitted provided that the following conditions are # met: # the distribution. # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import unittest import IECore import Gaffer import GafferImage import GafferImageTest class ObjectToImageTest( GafferImageTest.ImageTestCase ) : fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" ) negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/<API key>.200x150.exr" ) def test( self ) : i = IECore.Reader.create( self.fileName ).read() n = GafferImage.ObjectToImage() n["object"].setValue( i ) self.assertEqual( n["out"].image(), i ) def <API key>( self ) : i = IECore.Reader.create( self.negFileName ).read() n = GafferImage.ObjectToImage() n["object"].setValue( i ) self.assertEqual( n["out"].image(), i ) def <API key>( self ) : n = GafferImage.ObjectToImage() n["object"].setValue( IECore.Reader.create( self.fileName ).read() ) self.assertNotEqual( n["out"].channelDataHash( "R", IECore.V2i( 0 ) ), n["out"].channelDataHash( "G", IECore.V2i( 0 ) ) ) self.assertNotEqual( n["out"].channelDataHash( "R", IECore.V2i( 0 ) ), n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) ) ) if __name__ == "__main__": unittest.main()
import React from 'react'; import 'isomorphic-fetch'; import {RouteHandler} from 'react-router'; import Transmit from 'react-transmit'; import {createStore, combineReducers} from 'redux'; import {Provider} from 'react-redux'; import * as reducers from '../reducers/index'; class AppContainer extends React.Component { static propTypes = { initialState: React.PropTypes.object.isRequired } render() { const reducer = combineReducers(reducers); const store = createStore(reducer, this.props.initialState); return ( <Provider store={store}> {() => <RouteHandler /> } </Provider> ); } } export default Transmit.createContainer(AppContainer, { queries: {} });
require("../pc.v0"); require("util").puts(JSON.stringify({ "name": "pc", "version": pc.version, "description": "property creation for reusable d3.js code.", "keywords": ["d3", "visualization"], "homepage": "http://milroc.github.com/pc/", "author": {"name": "Miles McCrocklin", "url": "http: "repository": {"type": "git", "url": "http://github.com/milroc/pc.git"}, "devDependencies": { "uglify-js": "1.2.6", "vows": "0.6.0" } }, null, 2));
.title { margin-top: 30px; vertical-align: top; } .title button { margin-top: 20px; } .contents { margin-top: 100px; } .contetns span { margin-top: 20px; }
package immortal import ( "os/exec" "syscall" "testing" "time" ) func TestWatchPidGetpid(t *testing.T) { ch := make(chan error, 1) d := &Daemon{} cmd := exec.Command("go", "version") cmd.Start() pid := cmd.Process.Pid go func() { d.WatchPid(pid, ch) ch <- cmd.Wait() }() select { case <-time.After(time.Millisecond): syscall.Kill(pid, syscall.SIGTERM) case err := <-ch: if err != nil { if err.Error() != "EXIT" { t.Error(err) } } } } func <API key>(t *testing.T) { d := &Daemon{} ch := make(chan error, 1) cmd := exec.Command("sleep", "100") cmd.Start() pid := cmd.Process.Pid go func() { d.WatchPid(pid, ch) ch <- cmd.Wait() }() select { case err := <-ch: if err != nil { if err.Error() != "EXIT" { t.Error(err) } } case <-time.After(1 * time.Millisecond): if err := cmd.Process.Kill(); err != nil { t.Errorf("failed to kill: %s", err) } } }
#include "Utilities.h" #include <string.h> char Utilities::toHEX (char code) { return m_hex[code & 15]; } long Utilities::Escaping (char * src, char * dest) { char *pstr = src; char *pbuf = dest; long count = 0; while (*pstr) { if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') { *pbuf++ = *pstr; count++; } else if (*pstr == ' ') { *pbuf++ = '+'; count++; } else if (*pstr == '=') { *pbuf++ = *pstr; count++; } else { *pbuf++ = '%', *pbuf++ = toHEX(*pstr >> 4), *pbuf++ = toHEX(*pstr & 15); count += 3; } pstr++; } *pbuf = '\0'; return count; } std::string Utilities::EncodeBase64 (unsigned char const* bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) { ret += m_base64_chars[char_array_4[i]]; } i = 0; } } if (i) { for(j = i; j < 3; j++) { char_array_3[j] = '\0'; } char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) { ret += m_base64_chars[char_array_4[j]]; } while((i++ < 3)) ret += '='; } return ret; }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_51) on Tue May 19 11:04:42 CEST 2015 --> <title>Uses of Interface com.mxgraph.util.svg.ShapeProducer (JGraph X 3.3.0.1 API Specification)</title> <meta name="date" content="2015-05-19"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface com.mxgraph.util.svg.ShapeProducer (JGraph X 3.3.0.1 API Specification)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><p><b>JGraph X 3.3.0.1</b></p></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/mxgraph/util/svg/class-use/ShapeProducer.html" target="_top">Frames</a></li> <li><a href="ShapeProducer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Interface com.mxgraph.util.svg.ShapeProducer" class="title">Uses of Interface<br>com.mxgraph.util.svg.ShapeProducer</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">ShapeProducer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.mxgraph.util.svg">com.mxgraph.util.svg</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.mxgraph.util.svg"> </a> <h3>Uses of <a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">ShapeProducer</a> in <a href="../../../../../com/mxgraph/util/svg/package-summary.html">com.mxgraph.util.svg</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../com/mxgraph/util/svg/package-summary.html">com.mxgraph.util.svg</a> that implement <a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">ShapeProducer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/mxgraph/util/svg/AWTPathProducer.html" title="class in com.mxgraph.util.svg">AWTPathProducer</a></strong></code> <div class="block">This class provides an implementation of the PathHandler that initializes a Shape from the value of a path's 'd' attribute.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/mxgraph/util/svg/AWTPolygonProducer.html" title="class in com.mxgraph.util.svg">AWTPolygonProducer</a></strong></code> <div class="block">This class produces a polygon shape from a reader.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/mxgraph/util/svg/AWTPolylineProducer.html" title="class in com.mxgraph.util.svg">AWTPolylineProducer</a></strong></code> <div class="block">This class produces a polyline shape from a reader.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><p><b>JGraph X 3.3.0.1</b></p></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/mxgraph/util/svg/class-use/ShapeProducer.html" target="_top">Frames</a></li> <li><a href="ShapeProducer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small><font size=1>Copyright (c) 2010 <a href="http: target="_blank">Gaudenz Alder</a>. All rights reserved.</font></small></p> </body> </html>
SEEK::Application.configure do #This holds a secret phrase, used for encrypting private information in the database #GLOBAL_PASSPHRASE="" Seek::Config.default :solr_enabled, true end
#pragma once #include "boxFilter.hpp" class <API key> : public cp::BoxFilterBase { protected: int ksize; void filter_naive_impl() override; void filter_omp_impl() override; void operator()(const cv::Range& range) const override; public: <API key>(cv::Mat& _src, cv::Mat& _dest, int _r, int _parallelType); virtual void init(); }; class <API key> : public <API key> { private: __m128 mDiv; void filter_naive_impl() override; void filter_omp_impl() override; void operator()(const cv::Range& range) const override; public: <API key>(cv::Mat& _src, cv::Mat& _dest, int _r, int _parallelType); void init() override; }; class <API key> : public <API key> { private: __m256 mDiv; void filter_naive_impl() override; void filter_omp_impl() override; void operator()(const cv::Range& range) const override; public: <API key>(cv::Mat& _src, cv::Mat& _dest, int _r, int _parallelType); void init() override; };
package com.tubros.constraints.core.spi.solver package runtime import org.junit.runner.RunWith import org.scalamock.scalatest.MockFactory import org.scalatest._ import org.scalatest.junit.JUnitRunner import com.tubros.constraints.api._ * The '''SymbolTableSpec''' type defines the unit tests responsible for /** * certifying the [[com.tubros.constraints.core.spi.solver.runtime.SymbolTable]] * abstraction for use in CSP implementations. * * @author svickers * */ @RunWith (classOf[JUnitRunner]) class SymbolTableSpec extends ProjectSpec { "A SymbolTable" should "be able to be constructed with nothing in it" in { val table = SymbolTable.empty; table shouldNot be (null); table ('unknown) should be ('empty); table.contains ('anyName) shouldBe (false); } it should "support symbol name addition" in { val entry = VariableName ('aName); val oneEntry = SymbolTable.empty addSymbol (entry); oneEntry.contains (entry) shouldBe (true); oneEntry (entry) shouldBe (Set (entry)); } it should "support dependant definitions" in { val dependant = ( SymbolTable.empty addSymbol ('a) addSymbol ('b) addDerivedSymbol ('c, Set ('a, 'b)) ); dependant ('c) should not be ('empty); dependant.contains ('c) shouldBe (true); dependant ('c) shouldBe ( Set (VariableName ('a), VariableName ('b)) ); } it should "support nested dependant definitions" in { val nested = ( SymbolTable.empty addDerivedSymbol ('d, Set ('c)) addDerivedSymbol ('c, Set ('a, 'b)) addSymbol ('b) addSymbol ('a) ); nested.contains ('d) shouldBe (true); nested ('d) should not be ('empty); nested ('d) shouldBe ( Set (VariableName ('a), VariableName ('b)) ); } it should "be able to determine what symbols are dependants" in { val dependant = ( SymbolTable.empty addSymbol ('a) addSymbol ('b) addDerivedSymbol ('c, Set ('a, 'b)) ); dependant.isDerived ('a) shouldBe (false); dependant.isDerived ('c) shouldBe (true); } it should "be able to resolve dependants available when expected" in { val dependant = ( SymbolTable.empty addSymbol ('a) addSymbol ('b) addDerivedSymbol ('c, Set ('a, 'b)) ); dependant.derivedFrom (Set[VariableName] ('a, 'b)) shouldBe ( Set (VariableName ('c)) ); } it should "not resolve a dependant unless all roots are available" in { val dependant = ( SymbolTable.empty addSymbol ('a) addSymbol ('b) addDerivedSymbol ('c, Set ('a, 'b)) ); dependant.derivedFrom (Set[VariableName] ('a)) should be ('empty); } it should "not resolve a dependant unless all participants are available" in { val dependant = ( SymbolTable.empty addSymbol ('a) addSymbol ('b) addSymbol ('d) addDerivedSymbol ('c, Set ('a, 'e)) addDerivedSymbol ('e, Set ('d)) ); dependant.derivedFrom (Set[VariableName] ('a, 'b)) should be ('empty); } }
#include "synchronization/Communicator.hpp" namespace Synchronization { Communicator::Communicator() : _numManagedCons(0), _numManagedFmus(0) { } size_type Synchronization::Communicator::addFmu(FMI::AbstractFmu* in, vector<FMI::InputMapping> & valuePacking) { vector<ConnectionSPtr>& connList = in->getConnections(); size_type numNewCons = 0; for (auto & con : connList) { con->initialize(in->getFmuName()); size_type conId; auto it = _knownConIds.find(con->getStartTag()); if (it == _knownConIds.end()) { valuePacking.push_back(con->getPacking()); conId = _numManagedCons++; _knownConIds[con->getStartTag()] = conId; ++numNewCons; } else { conId = it->second; if (con->isShared()) { ++numNewCons; valuePacking.push_back(con->getPacking()); } } con->setLocalId(conId); } in->setSharedId(_numManagedFmus++); for (auto & con : connList) { if (con->getLocalId() + 1 > _connections.size()) { _connections.resize(con->getLocalId() + 1); _connections[con->getLocalId()] = con; } } if (_outConnectionIds.size() < in->getSharedId() + 1) { _outConnectionIds.resize(in->getSharedId() + 1); } if (_inConnectionIds.size() < in->getSharedId() + 1) { _inConnectionIds.resize(in->getSharedId() + 1); } for (auto & i : connList) { if (i->isOutgoing(in->getFmuName())) { _outConnectionIds[in->getSharedId()].push_back(i->getLocalId()); } else { _inConnectionIds[in->getSharedId()].push_back(i->getLocalId()); } } return numNewCons; } bool_type Communicator::send(HistoryEntry const & in, size_type communicationId) { return static_cast<bool_type>(_connections[communicationId]->send(in)); } HistoryEntry Communicator::recv(size_type communicationId) { return _connections[communicationId]->recv(); } int_type Communicator::connectionIsFree(size_type communicationId) { return _connections[communicationId]->hasFreeBuffer(); } const vector<size_type> & Communicator::getInConnectionIds(const FMI::AbstractFmu * in) const { return _inConnectionIds[in->getSharedId()]; } const vector<size_type> & Communicator::getOutConnectionIds(const FMI::AbstractFmu * in) const { return _outConnectionIds[in->getSharedId()]; } size_type Communicator::getNumInConnections() const { size_type sum = 0; for (const auto & _inConnectionId : _inConnectionIds) { sum += _inConnectionId.size(); } return sum; } size_type Communicator::<API key>() const { size_type sum = 0; for (const auto & _outConnectionId : _outConnectionIds) { sum += _outConnectionId.size(); } return sum; } } /* namespace Synchronization */
{% load url from future %} <div class="well"> <h3 class="title">Violence</h3> <table class="table tabulated-data"> <thead> <tr> <th>Group</th> <th>Monthly Numbers</th> </tr> </thead> <tbody> <tr> <td>Girls Cases</td> <td>{{ <API key>|floatformat:0 }}</td> </tr> <tr> <td>Boys Cases</td> <td>{{ <API key>|floatformat:0 }}</td> </tr> <tr> <td>Cases Referred to Police</td> <td>{{ <API key>|floatformat:0 }}</td> </tr> </tbody> </table> <div class="actions"> <a href="{% url '<API key>' %}" class="btn btn-secondary"><i class="icon-th-list"></i> View Details</a> </div> </div>
#!/usr/bin/env python2 from __future__ import print_function import sys import os import urllib import argparse import xml.etree.ElementTree as ET def warn(*msgs): for x in msgs: print('[WARNING]:', x, file=sys.stderr) class PDBTM: def __init__(self, filename): #self.tree = ET.parse(filename) #self.root = self.tree.getroot() def strsum(l): s = '' for x in l: s += x.rstrip() + '\n' return s f = open(filename) s = [] for l in f: s.append(l) #s = strsum(s[1:-1]).strip() s = strsum(s).strip() self.root = ET.fromstring(s) print(root) def get_database(prefix='.'): if not prefix.endswith('/'): prefix += '/' print('Fetching database...', file=sys.stderr) db = urllib.urlopen('http://pdbtm.enzim.hu/data/pdbtmall') print('Saving database...', file=sys.stderr) f = open('%s/pdbtmall' % prefix, 'w') for l in db: f.write(l) #f.write(db.read()) db.close() f.close() def build_database(fn, prefix): print('Unpacking database...', file=sys.stderr) f = open(fn) db = f.read() f.close() firstline = 1 header = '' entries = [] pdbids = [] for l in db.split('\n'): if firstline: header += l firstline -= 1 continue if 'PDBTM>' in l: continue if l.startswith('<?'): continue if l.startswith('<pdbtm'): a = l.find('ID=') + 4 b = a + 4 pdbids.append(l[a:b]) entries.append(header) entries[-1] += '\n' + l if not prefix.endswith('/'): prefix += '/' if not os.path.isdir(prefix): os.mkdir(prefix) for entry in zip(pdbids, entries): f = open(prefix + entry[0] + '.xml', 'w') f.write(entry[1]) f.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Manages PDBTM databases. Automatically fetches the PDBTM database if no options are specified. Run without any arguments, dbtool will retrieve the PDBTM database, store it in pdbtm, and unpack it.') parser.add_argument('-d', '--db', default='pdbtmall', help='name of concatenated database file {default:pdbtmall}') parser.add_argument('-b', '--build-db', action='store_true', help='(re)build database from an existing pdbtmsall file (available at http://pdbtm.enzim.hu/data/pdbtmall)') parser.add_argument('directory', nargs='?', default='pdbtm', help='directory to store database in') parser.add_argument('-f', '--force-refresh', action='store_true', help='force overwrite of existing database. Functionally equivalent to removing the old database and rerunning.') #parser.add_argument('-n', metavar='bundle_size', type=int, help='size to cut bundles into') args = parser.parse_args() if args.build_db: build_database(args.db, args.directory) else: #db = PDBTM(args.db) if not os.path.isdir(args.directory): os.mkdir(args.directory) if args.force_refresh or not os.path.isfile('%s/%s' % (args.directory, args.db)): get_database(args.directory) build_database('%s/%s' % (args.directory, args.db), args.directory)
{-# LANGUAGE TemplateHaskell #-} module Data.Comp.Trans.DeriveUntrans ( deriveUntrans ) where import Control.Lens ( view ,(^.)) import Control.Monad ( liftM ) import Control.Monad.Trans ( lift ) import Data.Comp.Multi ( Alg, cata, (:&:)(..) ) import Language.Haskell.TH import Data.Comp.Trans.Util -- Creates an @untranslate@ function inverting the @translate@ function -- import qualified Foo as F -- type ArithTerm = Term (Arith :+: Atom :+: Lit) -- deriveUntrans [''F.Arith, ''F.Atom, ''F.Lit] (TH.ConT ''ArithTerm) -- will create -- type family Targ l -- newtype T l = T {t :: Targ l} -- class Untrans f where -- untrans :: Alg f t -- untranslate :: ArithTerm l -> Targ l -- untranslate = t . cata untrans -- type instance Targ ArithL = F.Arith -- instance Untrans Arith where -- untrans (Add x y) = T $ F.Add (t x) (t y) -- type instance Targ AtomL = F.Atom -- instance Untrans Atom where -- untrans (Var s) = T $ F.Var s -- untrans (Const x) = T $ F.Const (t x) -- type instance Targ LitL = F.Lit -- instance Untrans Lit where -- untrans (Lit n) = T $ F.Lit n -- Note that you will need to manually provide an instance @(Untrans f, Untrans g) => Untrans (f :+: g)@ -- due to phase issues. (Or @(Untrans (f :&: p), Untrans (g :&: p)) => Untrans ((f :+: g) :&: p)@, if you -- are propagating annotations.) -- With annotation propagation on, it will instead produce -- `untranslate :: Term (Arith :&: Ann) l -> Targ l Ann` deriveUntrans :: [Name] -> Type -> CompTrans [Dec] deriveUntrans names term = do targDec <- mkTarg targNm wrapperDec <- mkWrapper wrapNm unwrapNm targNm fnDec <- mkFn untranslateNm term targNm unwrapNm fnNm classDec <- mkClass classNm fnNm wrapNm instances <- liftM concat $ mapM (mkInstance classNm fnNm wrapNm unwrapNm targNm) names return $ concat [ targDec , wrapperDec , fnDec , classDec , instances ] where targNm = mkName "Targ" wrapNm = mkName "T" unwrapNm = mkName "t" untranslateNm = mkName "untranslate" classNm = mkName "Untrans" fnNm = mkName "untrans" {- type family Targ l -} mkTarg :: Name -> CompTrans [Dec] mkTarg targNm = do i <- lift $ newName "i" return [FamilyD TypeFam targNm [PlainTV i] Nothing] {- newtype T l = T { t :: Targ l } -} mkWrapper :: Name -> Name -> Name -> CompTrans [Dec] mkWrapper tpNm fNm targNm = do i <- lift $ newName "i" let con = RecC tpNm [(fNm, NotStrict, AppT (ConT targNm) (VarT i))] return [NewtypeD [] tpNm [PlainTV i] con []] {- untranslate :: JavaTerm l -> Targ l untranslate = t . cata untrans -} mkFn :: Name -> Type -> Name -> Name -> Name -> CompTrans [Dec] mkFn fnNm term targNm fldNm untransNm = sequence [sig, def] where sig = do i <- lift $ newName "i" lift $ sigD fnNm (forallT [PlainTV i] (return []) (typ $ varT i)) typ :: Q Type -> Q Type typ i = [t| $term' $i -> $targ $i |] term' = return term targ = conT targNm def = lift $ valD (varP fnNm) (normalB body) [] body = [| $fld . cata $untrans |] fld = varE fldNm untrans = varE untransNm {- class Untrans f where untrans :: Alg f T -} mkClass :: Name -> Name -> Name -> CompTrans [Dec] mkClass classNm funNm newtpNm = do f <- lift $ newName "f" let funDec = SigD funNm (AppT (AppT (ConT ''Alg) (VarT f)) (ConT newtpNm)) return [ClassD [] classNm [PlainTV f] [] [funDec]] {- type instance Targ CompilationUnitL = J.CompilationUnit instance Untrans CompilationUnit where untrans (CompilationUnit x y z) = T $ J.CompilationUnit (t x) (t y) (t z) -} mkInstance :: Name -> Name -> Name -> Name -> Name -> Name -> CompTrans [Dec] mkInstance classNm funNm wrap unwrap targNm typNm = do inf <- lift $ reify typNm targTyp <- getFullyAppliedType typNm let nmTyps = simplifyDataInf inf clauses <- mapM (uncurry $ mkClause wrap unwrap) nmTyps let conTyp = ConT (transName typNm) annPropInf <- view annotationProp let instTyp = case annPropInf of Nothing -> conTyp Just api -> foldl AppT (ConT ''(:&:)) [conTyp, api ^. annTyp] return [ famInst targTyp , inst clauses instTyp ] where famInst targTyp = TySynInstD targNm (TySynEqn [ConT $ nameLab typNm] targTyp) inst clauses instTyp = InstanceD [] (AppT (ConT classNm) instTyp) [FunD funNm clauses] <API key> :: [a] -> (a -> b) -> (a -> Bool) -> [b] -> [b] <API key> src f p reps = go src reps where go [] _ = [] go (x:xs) (y:ys) | p x = y : go xs ys go (x:xs) l | not (p x) = f x : go xs l go (_:_ ) [] = error "<API key>: Insufficiently many replacements" mkClause :: Name -> Name -> Name -> [Type] -> CompTrans Clause mkClause wrap unwrap con tps = do isAnn <- getIsAnn nms <- mapM (const $ lift $ newName "x") tps nmAnn <- lift $ newName "a" tps' <- <API key> tps let nmTps = zip nms tps' Clause <$> (sequence [pat isAnn nmTps nmAnn]) <*> (body nmTps nmAnn) <*> pure [] where pat :: (Type -> Bool) -> [(Name, Type)] -> Name -> CompTrans Pat pat isAnn nmTps nmAnn = do isProp <- isPropagatingAnns if isProp then return $ ConP '(:&:) [nodeP, VarP nmAnn] else return nodeP where nonAnnNms = map fst $ filter (not.isAnn.snd) nmTps nodeP = ConP (transName con) (map VarP nonAnnNms) body :: [(Name, Type)] -> Name -> CompTrans Body body nmTps nmAnn = do annPropInf <- view annotationProp args <- case annPropInf of Nothing -> return $ map atom nmTps Just api -> do isAnn <- getIsAnn let unProp = api ^. unpropAnn let annVars = filter (isAnn.snd) nmTps let annExps = unProp (VarE nmAnn) (length annVars) return $ <API key> nmTps atom (isAnn.snd) annExps return $ makeRhs args where makeRhs :: [Exp] -> Body makeRhs args = NormalB $ AppE (ConE wrap) $ foldl AppE (ConE con) args atom :: (Name, Type) -> Exp atom (x, t) | elem t baseTypes = VarE x atom (x, _) = AppE (VarE unwrap) (VarE x)
from django.template import Library, Node, resolve_variable, TemplateSyntaxError from django.core.urlresolvers import reverse register = Library() @register.simple_tag def active(request, pattern): import re if re.search(pattern, request.get_full_path()): return 'active' return ''
#include <memory> #include <utility> #include <vector> #include "base/feature_list.h" #include "base/macros.h" #include "base/optional.h" #include "base/strings/string_util.h" #include "base/strings/<API key>.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/metrics/user_action_tester.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "base/test/<API key>.h" #include "build/build_config.h" #include "components/autofill/core/common/form_field_data.h" #include "components/password_manager/core/browser/form_fetcher_impl.h" #include "components/password_manager/core/browser/<API key>.h" #include "components/password_manager/core/browser/mock_password_store.h" #include "components/password_manager/core/browser/<API key>.h" #include "components/password_manager/core/browser/<API key>.h" #include "components/password_manager/core/browser/<API key>.h" #include "components/password_manager/core/browser/password_store.h" #include "components/password_manager/core/browser/<API key>.h" #include "components/password_manager/core/browser/<API key>.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using autofill::PasswordForm; using base::ASCIIToUTF16; using base::<API key>; using testing::_; using testing::AnyNumber; using testing::Invoke; using testing::Mock; using testing::Return; using testing::ReturnRef; using testing::SaveArg; using testing::WithArg; namespace password_manager { namespace { class <API key> : public <API key> { public: <API key>() {} MOCK_CONST_METHOD1(<API key>, bool(const GURL&)); MOCK_CONST_METHOD1(IsFillingEnabled, bool(const GURL&)); MOCK_METHOD2(AutofillHttpAuth, void(const autofill::PasswordForm&, const <API key>*)); MOCK_CONST_METHOD0(<API key>, PasswordStore*()); MOCK_METHOD0(<API key>, void()); // Workaround for std::unique_ptr<> lacking a copy constructor. bool <API key>( std::unique_ptr<<API key>> manager, bool update_password) override { <API key>(); return true; } }; class <API key> : public HttpAuthObserver { public: <API key>() = default; ~<API key>() override = default; MOCK_METHOD0(<API key>, void()); MOCK_METHOD2(<API key>, void(const base::string16&, const base::string16&)); <API key>(<API key>); }; // Invokes the password store consumer with a single copy of |form|. ACTION_P(InvokeConsumer, form) { std::vector<std::unique_ptr<PasswordForm>> result; result.push_back(std::make_unique<PasswordForm>(form)); arg0-><API key>(std::move(result)); } ACTION(<API key>) { arg0-><API key>(std::vector<std::unique_ptr<PasswordForm>>()); } } // namespace class HttpAuthManagerTest : public testing::Test { public: HttpAuthManagerTest() = default; ~HttpAuthManagerTest() override = default; protected: void SetUp() override { store_ = new testing::StrictMock<MockPasswordStore>; ASSERT_TRUE(store_->Init(nullptr)); ON_CALL(client_, <API key>()) .WillByDefault(Return(store_.get())); EXPECT_CALL(*store_, GetSiteStatsImpl(_)).Times(AnyNumber()); httpauth_manager_.reset(new HttpAuthManagerImpl(&client_)); EXPECT_CALL(*store_, <API key>()).WillRepeatedly(Return(true)); ON_CALL(client_, AutofillHttpAuth(_, _)) .WillByDefault( Invoke(httpauth_manager_.get(), &HttpAuthManagerImpl::Autofill)); } void TearDown() override { store_->ShutdownOnUIThread(); store_ = nullptr; } HttpAuthManagerImpl* httpauth_manager() { return httpauth_manager_.get(); } base::test::TaskEnvironment task_environment_; scoped_refptr<MockPasswordStore> store_; testing::NiceMock<<API key>> client_; std::unique_ptr<HttpAuthManagerImpl> httpauth_manager_; }; TEST_F(HttpAuthManagerTest, HttpAuthFilling) { for (bool filling_enabled : {false, true}) { SCOPED_TRACE(testing::Message("filling_enabled=") << filling_enabled); EXPECT_CALL(client_, IsFillingEnabled(_)) .WillRepeatedly(Return(filling_enabled)); PasswordForm observed_form; observed_form.scheme = PasswordForm::Scheme::kBasic; observed_form.origin = GURL("http://proxy.com/"); observed_form.signon_realm = "proxy.com/realm"; PasswordForm stored_form = observed_form; stored_form.username_value = ASCIIToUTF16("user"); stored_form.password_value = ASCIIToUTF16("1234"); <API key> observer; <API key>* consumer = nullptr; EXPECT_CALL(*store_, GetLogins(_, _)).WillOnce(SaveArg<1>(&consumer)); httpauth_manager()-><API key>(&observer, observed_form); EXPECT_CALL(observer, <API key>(ASCIIToUTF16("user"), ASCIIToUTF16("1234"))) .Times(filling_enabled); ASSERT_TRUE(consumer); std::vector<std::unique_ptr<PasswordForm>> result; result.push_back(std::make_unique<PasswordForm>(stored_form)); consumer-><API key>(std::move(result)); testing::Mock::<API key>(&store_); httpauth_manager()->DetachObserver(&observer); } } TEST_F(HttpAuthManagerTest, HttpAuthSaving) { for (bool <API key> : {true, false}) { SCOPED_TRACE(testing::Message("<API key>=") << <API key>); EXPECT_CALL(client_, <API key>(_)) .WillRepeatedly(Return(<API key>)); PasswordForm observed_form; observed_form.scheme = PasswordForm::Scheme::kBasic; observed_form.origin = GURL("http://proxy.com/"); observed_form.signon_realm = "proxy.com/realm"; <API key> observer; EXPECT_CALL(*store_, GetLogins(_, _)) .WillRepeatedly(WithArg<1>(<API key>())); // Initiate creating a form manager. httpauth_manager()-><API key>(&observer, observed_form); // Emulate that http auth credentials submitted. PasswordForm submitted_form = observed_form; submitted_form.username_value = ASCIIToUTF16("user"); submitted_form.password_value = ASCIIToUTF16("1234"); httpauth_manager()-><API key>(submitted_form); httpauth_manager()-><API key>(); // Expect save prompt on successful submission. std::unique_ptr<<API key>> <API key>; EXPECT_CALL(client_, <API key>()) .Times(<API key> ? 1 : 0); httpauth_manager()-><API key>(); testing::Mock::<API key>(&client_); httpauth_manager()->DetachObserver(&observer); } } TEST_F(HttpAuthManagerTest, <API key>) { EXPECT_CALL(client_, <API key>(_)) .WillRepeatedly(Return(true)); PasswordForm observed_form; observed_form.scheme = PasswordForm::Scheme::kBasic; observed_form.origin = GURL("http://proxy.com/"); observed_form.signon_realm = "proxy.com/realm"; <API key> observer; EXPECT_CALL(*store_, GetLogins(_, _)) .WillRepeatedly(WithArg<1>(<API key>())); // Initiate creating a form manager. httpauth_manager()-><API key>(&observer, observed_form); // Expect no prompt, since no submission was happened. EXPECT_CALL(client_, <API key>()).Times(0); httpauth_manager()-><API key>(); httpauth_manager()->DetachObserver(&observer); } TEST_F(HttpAuthManagerTest, <API key>) { EXPECT_CALL(client_, <API key>).WillRepeatedly(Return(true)); PasswordForm observed_form; observed_form.scheme = PasswordForm::Scheme::kBasic; observed_form.origin = GURL("http://proxy.com/"); observed_form.signon_realm = "proxy.com/realm"; <API key> observer; // The password store is queried but it's slow and won't respond. EXPECT_CALL(*store_, GetLogins); // Initiate creating a form manager. httpauth_manager()-><API key>(&observer, observed_form); PasswordForm submitted_form = observed_form; submitted_form.username_value = ASCIIToUTF16("user"); submitted_form.password_value = ASCIIToUTF16("1234"); httpauth_manager()-><API key>(submitted_form); httpauth_manager()-><API key>(); // Expect no prompt as the password store didn't reply. EXPECT_CALL(client_, <API key>()).Times(0); httpauth_manager()-><API key>(); httpauth_manager()->DetachObserver(&observer); } } // namespace password_manager
# VIVO: Connect, Share, Discover [![Build](https: VIVO is an open source semantic web tool for research discovery -- finding people and the research they do. VIVO supports editing, searching, browsing and visualizing research activity in order to discover people, programs, facilities, funding, scholarly works and events. VIVO's search returns results faceted by type for rapid retrieval of desired information across disciplines. ## Resources VIVO Project web site http://vivoweb.org/ VIVO Project Wiki https://wiki.lyrasis.org/display/VIVO/ Installation Instructions Installation instructions for the latest release can be found at this location on the wiki: https://wiki.lyrasis.org/display/VIVODOC112x/Installing+VIVO Docker VIVO docker container is available at [vivoweb/vivo](https: Docker Compose Docker Compose environment variables: .env defaults LOCAL_VIVO_HOME=./vivo-home RESET_HOME=false RESET_CORE=false - `LOCAL_VIVO_HOME`: VIVO home directory on your host machine which will mount to volume in docker container. Set this environment variable to persist your VIVO data on your host machine. - `RESET_HOME`: Convenience to reset VIVO home when starting container. **Caution**, will delete local configuration, content, and configuration model. - `RESET_CORE`: Convenience to reset VIVO Solr core when starting container. **Caution**, will require complete reindex. Before building VIVO, you will also need to clone (and switch to the same branch, if other than main) of [Vitro](https: Build and start VIVO. 1. In Vitro-languages, run: mvn install 2. In VIVO-languages, run: mvn install 3. In VIVO (with Vitro cloned alongside it), run: mvn clean package -s installer/example-settings.xml docker-compose up Docker Image To build and run local Docker image. docker build -t vivoweb/vivo:development . docker run -p 8080:8080 vivoweb/vivo:development ## Contact us There are several ways to contact the VIVO community. Whatever your interest, we would be pleased to hear from you. Contact form http://vivoweb.org/support/user-feedback Mailing lists This updates list provides news to the VIVO community of interest to all. Join the VIVO community! Here you'll find non-technical discussion regarding participation, the VIVO conference, policy, project management, outreach, and engagement. The best place to get your hands dirty in the VIVO Project. Developers and implementers frequent this list to get the latest on feature design, development, implementation, and testing. ## Contributing Code If you would like to contribute code to the VIVO project, please open a ticket in our [JIRA](https://jira.lyrasis.org/projects/VIVO), and prepare a pull request that references your ticket. Contributors welcome! ## Citing VIVO If you are using VIVO in your publications or projects, please cite the software paper in the Journal of Open Source Software: * Conlon et al., (2019). VIVO: a system for research discovery. Journal of Open Source Software, 4(39), 1182, https://doi.org/10.21105/joss.01182 BibTeX tex @article{Conlon2019, doi = {10.21105/joss.01182}, url = {https://doi.org/10.21105/joss.01182}, year = {2019}, publisher = {The Open Journal}, volume = {4}, number = {39}, pages = {1182}, author = {Michael Conlon and Andrew Woods and Graham Triggs and Ralph O'Flinn and Muhammad Javed and Jim Blake and Benjamin Gross and Qazi Asim Ijaz Ahmad and Sabih Ali and Martin Barber and Don Elsborg and Kitio Fofack and Christian Hauschke and Violeta Ilik and Huda Khan and Ted Lawless and Jacob Levernier and Brian Lowe and Jose Martin and Steve McKay and Simon Porter and Tatiana Walther and Marijane White and Stefan Wolff and Rebecca Younes}, title = {{VIVO}: a system for research discovery}, journal = {Journal of Open Source Software} }
#!/bin/bash # define helpers source_dir=~/.osx-bootstrap if [[ ! -f ~/.ssh/id_rsa ]]; then echo '' echo ' read github_user echo ' read github_email # setup github if [[ $github_user && $github_email ]]; then # setup config git config --global user.name $github_user git config --global user.email $github_email git config --global github.user $github_user git config --global github.token your_token_here git config --global color.ui true git config --global push.default current # sublime support # git config --global core.editor "subl -w" # set rsa key curl -s -O http://<API key>.s3.amazonaws.com/osx/<API key> chmod u+x <API key> sudo mv <API key> "$(dirname $(which git))/<API key>" git config --global credential.helper osxkeychain # generate ssh key cd ~/.ssh ssh-keygen -t rsa -C $github_email pbcopy < ~/.ssh/id_rsa.pub echo '' echo ' cat ~/.ssh/id_rsa.pub echo ' ssh -T git@github.com fi fi
#if !(NET35 || NET20 || WINDOWS_PHONE) using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Newtonsoft.Json.Utilities { internal sealed class <API key><T> : DynamicMetaObject { private readonly DynamicProxy<T> _proxy; private readonly bool _dontFallbackFirst; internal <API key>(Expression expression, T value, DynamicProxy<T> proxy, bool dontFallbackFirst) : base(expression, BindingRestrictions.Empty, value) { _proxy = proxy; _dontFallbackFirst = dontFallbackFirst; } private new T Value { get { return (T)base.Value; } } private bool IsOverridden(string method) { return _proxy.GetType().GetMember(method, MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance).Cast<MethodInfo>() .Any(info => // check that the method overrides the original on DynamicObjectProxy info.DeclaringType != typeof(DynamicProxy<T>) && info.GetBaseDefinition().DeclaringType == typeof(DynamicProxy<T>)); } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { return IsOverridden("TryGetMember") ? <API key>("TryGetMember", binder, NoArgs, e => binder.FallbackGetMember(this, e)) : base.BindGetMember(binder); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { return IsOverridden("TrySetMember") ? <API key>("TrySetMember", binder, GetArgs(value), e => binder.FallbackSetMember(this, value, e)) : base.BindSetMember(binder, value); } public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) { return IsOverridden("TryDeleteMember") ? CallMethodNoResult("TryDeleteMember", binder, NoArgs, e => binder.<API key>(this, e)) : base.BindDeleteMember(binder); } public override DynamicMetaObject BindConvert(ConvertBinder binder) { return IsOverridden("TryConvert") ? <API key>("TryConvert", binder, NoArgs, e => binder.FallbackConvert(this, e)) : base.BindConvert(binder); } public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { if (!IsOverridden("TryInvokeMember")) return base.BindInvokeMember(binder, args); // Generate a tree like: // object result; // TryInvokeMember(payload, out result) // ? result // : TryGetMember(payload, out result) // ? FallbackInvoke(result) // : fallbackResult // Then it calls <API key> with this tree as the // "error", giving the language the option of using this // tree or doing .NET binding. Fallback fallback = e => binder.<API key>(this, args, e); DynamicMetaObject call = <API key>( "TryInvokeMember", binder, GetArgArray(args), <API key>( "TryGetMember", new GetBinderAdapter(binder), NoArgs, fallback(null), e => binder.FallbackInvoke(e, args, null) ), null ); return _dontFallbackFirst ? call : fallback(call); } public override DynamicMetaObject BindCreateInstance(<API key> binder, DynamicMetaObject[] args) { return IsOverridden("TryCreateInstance") ? <API key>("TryCreateInstance", binder, GetArgArray(args), e => binder.<API key>(this, args, e)) : base.BindCreateInstance(binder, args); } public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { return IsOverridden("TryInvoke") ? <API key>("TryInvoke", binder, GetArgArray(args), e => binder.FallbackInvoke(this, args, e)) : base.BindInvoke(binder, args); } public override DynamicMetaObject BindBinaryOperation(<API key> binder, DynamicMetaObject arg) { return IsOverridden("TryBinaryOperation") ? <API key>("TryBinaryOperation", binder, GetArgs(arg), e => binder.<API key>(this, arg, e)) : base.BindBinaryOperation(binder, arg); } public override DynamicMetaObject BindUnaryOperation(<API key> binder) { return IsOverridden("TryUnaryOperation") ? <API key>("TryUnaryOperation", binder, NoArgs, e => binder.<API key>(this, e)) : base.BindUnaryOperation(binder); } public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { return IsOverridden("TryGetIndex") ? <API key>("TryGetIndex", binder, GetArgArray(indexes), e => binder.FallbackGetIndex(this, indexes, e)) : base.BindGetIndex(binder, indexes); } public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { return IsOverridden("TrySetIndex") ? <API key>("TrySetIndex", binder, GetArgArray(indexes, value), e => binder.FallbackSetIndex(this, indexes, value, e)) : base.BindSetIndex(binder, indexes, value); } public override DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes) { return IsOverridden("TryDeleteIndex") ? CallMethodNoResult("TryDeleteIndex", binder, GetArgArray(indexes), e => binder.FallbackDeleteIndex(this, indexes, e)) : base.BindDeleteIndex(binder, indexes); } private delegate DynamicMetaObject Fallback(DynamicMetaObject errorSuggestion); private readonly static Expression[] NoArgs = new Expression[0]; private static Expression[] GetArgs(params DynamicMetaObject[] args) { return args.Select(arg => Expression.Convert(arg.Expression, typeof(object))).ToArray(); } private static Expression[] GetArgArray(DynamicMetaObject[] args) { return new[] { Expression.NewArrayInit(typeof(object), GetArgs(args)) }; } private static Expression[] GetArgArray(DynamicMetaObject[] args, DynamicMetaObject value) { return new Expression[] { Expression.NewArrayInit(typeof(object), GetArgs(args)), Expression.Convert(value.Expression, typeof(object)) }; } private static ConstantExpression Constant(<API key> binder) { Type t = binder.GetType(); while (!t.IsVisible) t = t.BaseType; return Expression.Constant(binder, t); } <summary> Helper method for generating a MetaObject which calls a specific method on Dynamic that returns a result </summary> private DynamicMetaObject <API key>(string methodName, <API key> binder, Expression[] args, Fallback fallback, Fallback fallbackInvoke = null) { // First, call fallback to do default binding // This produces either an error or a call to a .NET member DynamicMetaObject fallbackResult = fallback(null); DynamicMetaObject callDynamic = <API key>(methodName, binder, args, fallbackResult, fallbackInvoke); // Now, call fallback again using our new MO as the error // When we do this, one of two things can happen: // 1. Binding will succeed, and it will ignore our call to // the dynamic method, OR // 2. Binding will fail, and it will use the MO we created // above. return _dontFallbackFirst ? callDynamic : fallback(callDynamic); } private DynamicMetaObject <API key>(string methodName, <API key> binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke) { // Build a new expression like: // object result; // TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult ParameterExpression result = Expression.Parameter(typeof(object), null); IList<Expression> callArgs = new List<Expression>(); callArgs.Add(Expression.Convert(Expression, typeof(T))); callArgs.Add(Constant(binder)); callArgs.AddRange(args); callArgs.Add(result); DynamicMetaObject resultMetaObject = new DynamicMetaObject(result, BindingRestrictions.Empty); // Need to add a conversion if calling TryConvert if (binder.ReturnType != typeof (object)) { UnaryExpression convert = Expression.Convert(resultMetaObject.Expression, binder.ReturnType); // will always be a cast or unbox resultMetaObject = new DynamicMetaObject(convert, resultMetaObject.Restrictions); } if (fallbackInvoke != null) resultMetaObject = fallbackInvoke(resultMetaObject); DynamicMetaObject callDynamic = new DynamicMetaObject( Expression.Block( new[] {result}, Expression.Condition( Expression.Call( Expression.Constant(_proxy), typeof(DynamicProxy<T>).GetMethod(methodName), callArgs ), resultMetaObject.Expression, fallbackResult.Expression, binder.ReturnType ) ), GetRestrictions().Merge(resultMetaObject.Restrictions).Merge(fallbackResult.Restrictions) ); return callDynamic; } <summary> Helper method for generating a MetaObject which calls a specific method on Dynamic, but uses one of the arguments for the result. </summary> private DynamicMetaObject <API key>(string methodName, <API key> binder, Expression[] args, Fallback fallback) { // First, call fallback to do default binding // This produces either an error or a call to a .NET member DynamicMetaObject fallbackResult = fallback(null); // Build a new expression like: // object result; // TrySetMember(payload, result = value) ? result : fallbackResult ParameterExpression result = Expression.Parameter(typeof(object), null); IList<Expression> callArgs = new List<Expression>(); callArgs.Add(Expression.Convert(Expression, typeof (T))); callArgs.Add(Constant(binder)); callArgs.AddRange(args); callArgs[args.Length + 1] = Expression.Assign(result, callArgs[args.Length + 1]); DynamicMetaObject callDynamic = new DynamicMetaObject( Expression.Block( new[] { result }, Expression.Condition( Expression.Call( Expression.Constant(_proxy), typeof(DynamicProxy<T>).GetMethod(methodName), callArgs ), result, fallbackResult.Expression, typeof(object) ) ), GetRestrictions().Merge(fallbackResult.Restrictions) ); // Now, call fallback again using our new MO as the error // When we do this, one of two things can happen: // 1. Binding will succeed, and it will ignore our call to // the dynamic method, OR // 2. Binding will fail, and it will use the MO we created // above. return _dontFallbackFirst ? callDynamic : fallback(callDynamic); } <summary> Helper method for generating a MetaObject which calls a specific method on Dynamic, but uses one of the arguments for the result. </summary> private DynamicMetaObject CallMethodNoResult(string methodName, <API key> binder, Expression[] args, Fallback fallback) { // First, call fallback to do default binding // This produces either an error or a call to a .NET member DynamicMetaObject fallbackResult = fallback(null); IList<Expression> callArgs = new List<Expression>(); callArgs.Add(Expression.Convert(Expression, typeof(T))); callArgs.Add(Constant(binder)); callArgs.AddRange(args); // Build a new expression like: // if (TryDeleteMember(payload)) { } else { fallbackResult } DynamicMetaObject callDynamic = new DynamicMetaObject( Expression.Condition( Expression.Call( Expression.Constant(_proxy), typeof(DynamicProxy<T>).GetMethod(methodName), callArgs ), Expression.Empty(), fallbackResult.Expression, typeof (void) ), GetRestrictions().Merge(fallbackResult.Restrictions) ); // Now, call fallback again using our new MO as the error // When we do this, one of two things can happen: // 1. Binding will succeed, and it will ignore our call to // the dynamic method, OR // 2. Binding will fail, and it will use the MO we created // above. return _dontFallbackFirst ? callDynamic : fallback(callDynamic); } <summary> Returns a Restrictions object which includes our current restrictions merged with a restriction limiting our type </summary> private BindingRestrictions GetRestrictions() { return (Value == null && HasValue) ? BindingRestrictions.<API key>(Expression, null) : BindingRestrictions.GetTypeRestriction(Expression, LimitType); } public override IEnumerable<string> <API key>() { return _proxy.<API key>(Value); } // It is okay to throw NotSupported from this binder. This object // is only used by DynamicObject.GetMember--it is not expected to // (and cannot) implement binding semantics. It is just so the DO // can use the Name and IgnoreCase properties. private sealed class GetBinderAdapter : GetMemberBinder { internal GetBinderAdapter(InvokeMemberBinder binder) : base(binder.Name, binder.IgnoreCase) { } public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { throw new <API key>(); } } } } #endif
/* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.in by autoheader. */ /* Whether to build xhprof as dynamic module */ #define COMPILE_DL_XHPROF 1 /* Define to 1 if you have the <dlfcn.h> header file. */ #define HAVE_DLFCN_H 1 /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* Define to 1 if your C compiler doesn't accept -c and -o together. */ /* #undef NO_MINUS_C_MINUS_O */ /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "" /* Define to the full name of this package. */ #define PACKAGE_NAME "" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "" /* Define to the version of this package. */ #define PACKAGE_VERSION "" /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1
''' Given a number, find the next higher number using only the digits in the given number. For example if the given number is 1234, next higher number with same digits is 1243 ''' def FindNext(num): number = str(num) length = len(number) for i in range(length-2,-1,-1): current = number[i] right = number[i+1] if current < right: temp = sorted(number[i:]) Next = temp[temp.index(current)+1] temp.remove(Next) temp = ''.join(temp) return int(number[:i]+Next+temp) return num
package manifest import ( "encoding/json" "fmt" "log" "reflect" "regexp" "strconv" "strings" "github.com/fatih/color" "github.com/servehub/serve/manifest/processor" "github.com/servehub/utils" "github.com/servehub/utils/gabs" ) type Manifest struct { tree *gabs.Container } func (m Manifest) String() string { return m.tree.StringIndent("", " ") } func (m Manifest) Unwrap() interface{} { return m.tree.Data() } func (m Manifest) Has(path string) bool { v := m.tree.Path(path).Data() return v != nil && v != "" } func (m Manifest) GetString(path string) string { return fmt.Sprintf("%v", m.tree.Path(path).Data()) } func (m Manifest) GetStringOr(path string, defaultVal string) string { if m.tree.ExistsP(path) { return m.GetString(path) } return defaultVal } func (m Manifest) GetFloat(path string) float64 { f, err := strconv.ParseFloat(m.GetString(path), 64) if err != nil { log.Fatalf("Error on parse float64 '%v' from: %v", path, m.GetString(path)) } return f } func (m Manifest) GetInt(path string) int { i, err := strconv.Atoi(m.GetString(path)) if err != nil { log.Fatalf("Error on parse integer '%v' from: %v", path, m.GetString(path)) } return i } func (m Manifest) GetIntOr(path string, defaultVal int) int { if m.tree.ExistsP(path) { return m.GetInt(path) } return defaultVal } func (m Manifest) GetBool(path string) bool { return strings.ToLower(m.GetString(path)) == "true" } func (m Manifest) GetMap(path string) map[string]Manifest { out := make(map[string]Manifest) tree := m.tree if len(path) > 0 && path != "." && path != "/" { tree = m.tree.Path(path) } mmap, err := tree.ChildrenMap() if err != nil { log.Fatalf("Error get map '%v' from: %v. Error: %s", path, m.tree.Path(path).Data(), err) } for k, v := range mmap { out[k] = Manifest{v} } return out } func (m Manifest) GetArray(path string) []Manifest { out := make([]Manifest, 0) arr, err := m.tree.Path(path).Children() if err != nil { log.Fatalf("Error get array `%v` from: %v", path, m.tree.Path(path).Data()) } for _, v := range arr { out = append(out, Manifest{v}) } return out } func (m Manifest) GetArrayForce(path string) []interface{} { out := make([]interface{}, 0) arr, err := m.tree.Path(path).Children() if err != nil && m.tree.ExistsP(path) { arr = append(arr, m.tree.Path(path)) } for _, v := range arr { out = append(out, v.Data()) } return out } func (m Manifest) GetTree(path string) Manifest { return Manifest{m.tree.Path(path)} } func (m Manifest) Set(path string, value interface{}) { m.tree.SetP(value, path) } func (m Manifest) ArrayAppend(path string, value interface{}) { m.tree.ArrayAppendP(value, path) } func (m Manifest) FindPlugins(plugin string) ([]PluginData, error) { tree := m.tree.Path(plugin) result := make([]PluginData, 0) if tree.Data() == nil { return nil, fmt.Errorf("Plugin `%s` not found in manifest!", plugin) } if _, ok := tree.Data().([]interface{}); ok { arr, _ := tree.Children() for _, item := range arr { if _, ok := item.Data().(string); ok { result = append(result, makePluginPair(plugin, item)) } else if res, err := item.ChildrenMap(); err == nil { if len(res) == 1 { for subplugin, data := range res { result = append(result, makePluginPair(plugin+"."+subplugin, data)) break } } else if len(res) == 0 && !PluginRegestry.Has(plugin) { // skip subplugin with empty data } else { result = append(result, makePluginPair(plugin, item)) } } } } else if PluginRegestry.Has(plugin) { result = append(result, makePluginPair(plugin, tree)) } else { log.Println(color.YellowString("Plugins for `%s` section not specified, skip...", plugin)) } return result, nil } func (m Manifest) DelTree(path string) error { return m.tree.DeleteP(path) } func (m Manifest) GetPluginWithData(plugin string) PluginData { return makePluginPair(plugin, m.tree) } var envNameRegex = regexp.MustCompile("\\W") func (m Manifest) ToEnvMap(prefix string) map[string]string { result := make(map[string]string) if children, err := m.tree.ChildrenMap(); err == nil { for k, child := range children { result = utils.MergeMaps(result, Manifest{child}.ToEnvMap(prefix+strings.ToUpper(envNameRegex.ReplaceAllString(k, "_"))+"_")) } } else if children, err := m.tree.Children(); err == nil { for i, child := range children { result = utils.MergeMaps(result, Manifest{child}.ToEnvMap(prefix+strconv.Itoa(i)+"_")) } } else if m.tree.Data() != nil { result[prefix[:len(prefix)-1]] = fmt.Sprintf("%v", m.tree.Data()) } return result } func Load(path string, vars map[string]string) *Manifest { tree, err := gabs.LoadYamlFile(path) if err != nil { log.Fatalln("Error on load file:", err) } for k, v := range vars { tree.Set(v, "vars", k) } for _, proc := range processor.GetAll() { if err := proc.Process(tree); err != nil { log.Fatalf("Error in processor '%v': %v. \n\nManifest: %s", reflect.ValueOf(proc).Type().Name(), err, tree.StringIndent("", " ")) } } return &Manifest{tree} } func LoadJSON(path string) *Manifest { tree, err := gabs.ParseJSONFile(path) if err != nil { log.Fatalf("Error on load json file '%s': %v\n", path, err) } return &Manifest{tree} } func ParseJSON(json string) *Manifest { tree, err := gabs.ParseJSON([]byte(json)) if err != nil { log.Fatalf("Error on parse json '%s': %v\n", json, err) } return &Manifest{tree} } func makePluginPair(plugin string, data *gabs.Container) PluginData { if s, ok := data.Data().(string); ok { obj := gabs.New() ns := strings.Split(plugin, ".") obj.Set(s, ns[len(ns)-1]) data = obj } else { var cpy interface{} bs, _ := json.Marshal(data.Data()) json.Unmarshal(bs, &cpy) data.Set(cpy) } return PluginData{plugin, PluginRegestry.Get(plugin), Manifest{data}} }