code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/*- * Copyright (c) 2005 David Xu <[email protected]> * Copyright (c) 1994 by Chris Provenzano, [email protected] * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Chris Provenzano. * 4. The name of Chris Provenzano may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY CHRIS PROVENZANO ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL CHRIS PROVENZANO 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. * * $FreeBSD: soc2013/dpl/head/sys/sys/timers.h 156180 2006-03-01 06:48:31Z davidxu $ * * Description : Basic timers header. */ #ifndef _SYS_TIMERS_H_ #define _SYS_TIMERS_H_ #include <sys/time.h> #ifdef _KERNEL /* * Structures used to manage POSIX timers in a process. */ struct itimer { struct mtx it_mtx; struct sigevent it_sigev; struct itimerspec it_time; struct proc *it_proc; int it_flags; int it_usecount; int it_overrun; /* Overruns currently accumulating */ int it_overrun_last; /* Overruns associated w/ a delivery */ int it_clockid; int it_timerid; ksiginfo_t it_ksi; union { /* realtime */ struct { struct callout it_callout; } _rt; /* cpu timer */ struct { LIST_ENTRY(itimer) it_link; TAILQ_ENTRY(itimer) it_worklink; int it_active; int it_cflags; } _cpu; } _data; }; #define it_callout _data._rt.it_callout #define it_link _data._cpu.it_link #define it_active _data._cpu.it_active #define it_worklink _data._cpu.it_worklink #define it_cflags _data._cpu.it_cflags #define ITF_DELETING 0x01 #define ITF_WANTED 0x02 #define ITCF_ONWORKLIST 0x01 #define TIMER_MAX 32 #define ITIMER_LOCK(it) mtx_lock(&(it)->it_mtx) #define ITIMER_UNLOCK(it) mtx_unlock(&(it)->it_mtx) LIST_HEAD(itimerlist, itimer); struct itimers { struct itimerlist its_virtual; struct itimerlist its_prof; TAILQ_HEAD(, itimer) its_worklist; struct itimer *its_timers[TIMER_MAX]; }; struct kclock { int (*timer_create)(struct itimer *timer); int (*timer_settime)(struct itimer * timer, int flags, struct itimerspec * new_value, struct itimerspec * old_value); int (*timer_delete)(struct itimer * timer); int (*timer_gettime)(struct itimer * timer, struct itimerspec * cur_value); void (*event_hook)(struct proc *p, clockid_t clock_id, int event); }; /* Event values for event_hook() */ #define ITIMER_EV_EXEC 0 #define ITIMER_EV_EXIT 1 int itimer_accept(struct proc *p, int tid, ksiginfo_t *ksi); #endif #endif /* !_SYS_TIMERS_H_ */
dplbsd/soc2013
head/sys/sys/timers.h
C
bsd-2-clause
3,761
/** * @license * Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import { GLMAT_ARRAY_TYPE } from './common'; /** * @class 3x3 Matrix * @name mat3 */ var mat3 = {}; /** * Creates a new identity mat3 * * @returns {mat3} a new 3x3 matrix */ mat3.create = function() { var out = new GLMAT_ARRAY_TYPE(9); out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 1; out[5] = 0; out[6] = 0; out[7] = 0; out[8] = 1; return out; }; /** * Copies the upper-left 3x3 values into the given mat3. * * @param {mat3} out the receiving 3x3 matrix * @param {mat4} a the source 4x4 matrix * @returns {mat3} out */ mat3.fromMat4 = function(out, a) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[4]; out[4] = a[5]; out[5] = a[6]; out[6] = a[8]; out[7] = a[9]; out[8] = a[10]; return out; }; /** * Creates a new mat3 initialized with values from an existing matrix * * @param {mat3} a matrix to clone * @returns {mat3} a new 3x3 matrix */ mat3.clone = function(a) { var out = new GLMAT_ARRAY_TYPE(9); out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4]; out[5] = a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; return out; }; /** * Copy the values from one mat3 to another * * @param {mat3} out the receiving matrix * @param {mat3} a the source matrix * @returns {mat3} out */ mat3.copy = function(out, a) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4]; out[5] = a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; return out; }; /** * Set a mat3 to the identity matrix * * @param {mat3} out the receiving matrix * @returns {mat3} out */ mat3.identity = function(out) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 1; out[5] = 0; out[6] = 0; out[7] = 0; out[8] = 1; return out; }; /** * Transpose the values of a mat3 * * @param {mat3} out the receiving matrix * @param {mat3} a the source matrix * @returns {mat3} out */ mat3.transpose = function(out, a) { // If we are transposing ourselves we can skip a few steps but have to cache some values if (out === a) { var a01 = a[1], a02 = a[2], a12 = a[5]; out[1] = a[3]; out[2] = a[6]; out[3] = a01; out[5] = a[7]; out[6] = a02; out[7] = a12; } else { out[0] = a[0]; out[1] = a[3]; out[2] = a[6]; out[3] = a[1]; out[4] = a[4]; out[5] = a[7]; out[6] = a[2]; out[7] = a[5]; out[8] = a[8]; } return out; }; /** * Inverts a mat3 * * @param {mat3} out the receiving matrix * @param {mat3} a the source matrix * @returns {mat3} out */ mat3.invert = function(out, a) { var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8], b01 = a22 * a11 - a12 * a21, b11 = -a22 * a10 + a12 * a20, b21 = a21 * a10 - a11 * a20, // Calculate the determinant det = a00 * b01 + a01 * b11 + a02 * b21; if (!det) { return null; } det = 1.0 / det; out[0] = b01 * det; out[1] = (-a22 * a01 + a02 * a21) * det; out[2] = (a12 * a01 - a02 * a11) * det; out[3] = b11 * det; out[4] = (a22 * a00 - a02 * a20) * det; out[5] = (-a12 * a00 + a02 * a10) * det; out[6] = b21 * det; out[7] = (-a21 * a00 + a01 * a20) * det; out[8] = (a11 * a00 - a01 * a10) * det; return out; }; /** * Calculates the adjugate of a mat3 * * @param {mat3} out the receiving matrix * @param {mat3} a the source matrix * @returns {mat3} out */ mat3.adjoint = function(out, a) { var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8]; out[0] = (a11 * a22 - a12 * a21); out[1] = (a02 * a21 - a01 * a22); out[2] = (a01 * a12 - a02 * a11); out[3] = (a12 * a20 - a10 * a22); out[4] = (a00 * a22 - a02 * a20); out[5] = (a02 * a10 - a00 * a12); out[6] = (a10 * a21 - a11 * a20); out[7] = (a01 * a20 - a00 * a21); out[8] = (a00 * a11 - a01 * a10); return out; }; /** * Calculates the determinant of a mat3 * * @param {mat3} a the source matrix * @returns {Number} determinant of a */ mat3.determinant = function (a) { var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8]; return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); }; /** * Multiplies two mat3's * * @param {mat3} out the receiving matrix * @param {mat3} a the first operand * @param {mat3} b the second operand * @returns {mat3} out */ mat3.multiply = function (out, a, b) { var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8], b00 = b[0], b01 = b[1], b02 = b[2], b10 = b[3], b11 = b[4], b12 = b[5], b20 = b[6], b21 = b[7], b22 = b[8]; out[0] = b00 * a00 + b01 * a10 + b02 * a20; out[1] = b00 * a01 + b01 * a11 + b02 * a21; out[2] = b00 * a02 + b01 * a12 + b02 * a22; out[3] = b10 * a00 + b11 * a10 + b12 * a20; out[4] = b10 * a01 + b11 * a11 + b12 * a21; out[5] = b10 * a02 + b11 * a12 + b12 * a22; out[6] = b20 * a00 + b21 * a10 + b22 * a20; out[7] = b20 * a01 + b21 * a11 + b22 * a21; out[8] = b20 * a02 + b21 * a12 + b22 * a22; return out; }; /** * Alias for {@link mat3.multiply} * @function */ mat3.mul = mat3.multiply; /** * Translate a mat3 by the given vector * * @param {mat3} out the receiving matrix * @param {mat3} a the matrix to translate * @param {vec2} v vector to translate by * @returns {mat3} out */ mat3.translate = function(out, a, v) { var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8], x = v[0], y = v[1]; out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a10; out[4] = a11; out[5] = a12; out[6] = x * a00 + y * a10 + a20; out[7] = x * a01 + y * a11 + a21; out[8] = x * a02 + y * a12 + a22; return out; }; /** * Rotates a mat3 by the given angle * * @param {mat3} out the receiving matrix * @param {mat3} a the matrix to rotate * @param {Number} rad the angle to rotate the matrix by * @returns {mat3} out */ mat3.rotate = function (out, a, rad) { var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8], s = Math.sin(rad), c = Math.cos(rad); out[0] = c * a00 + s * a10; out[1] = c * a01 + s * a11; out[2] = c * a02 + s * a12; out[3] = c * a10 - s * a00; out[4] = c * a11 - s * a01; out[5] = c * a12 - s * a02; out[6] = a20; out[7] = a21; out[8] = a22; return out; }; /** * Scales the mat3 by the dimensions in the given vec2 * * @param {mat3} out the receiving matrix * @param {mat3} a the matrix to rotate * @param {vec2} v the vec2 to scale the matrix by * @returns {mat3} out **/ mat3.scale = function(out, a, v) { var x = v[0], y = v[1]; out[0] = x * a[0]; out[1] = x * a[1]; out[2] = x * a[2]; out[3] = y * a[3]; out[4] = y * a[4]; out[5] = y * a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; return out; }; /** * Copies the values from a mat2d into a mat3 * * @param {mat3} out the receiving matrix * @param {mat2d} a the matrix to copy * @returns {mat3} out **/ mat3.fromMat2d = function(out, a) { out[0] = a[0]; out[1] = a[1]; out[2] = 0; out[3] = a[2]; out[4] = a[3]; out[5] = 0; out[6] = a[4]; out[7] = a[5]; out[8] = 1; return out; }; /** * Calculates a 3x3 matrix from the given quaternion * * @param {mat3} out mat3 receiving operation result * @param {quat} q Quaternion to create matrix from * * @returns {mat3} out */ mat3.fromQuat = function (out, q) { var x = q[0], y = q[1], z = q[2], w = q[3], x2 = x + x, y2 = y + y, z2 = z + z, xx = x * x2, yx = y * x2, yy = y * y2, zx = z * x2, zy = z * y2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2; out[0] = 1 - yy - zz; out[3] = yx - wz; out[6] = zx + wy; out[1] = yx + wz; out[4] = 1 - xx - zz; out[7] = zy - wx; out[2] = zx - wy; out[5] = zy + wx; out[8] = 1 - xx - yy; return out; }; /** * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix * * @param {mat3} out mat3 receiving operation result * @param {mat4} a Mat4 to derive the normal matrix from * * @returns {mat3} out */ mat3.normalFromMat4 = function (out, a) { var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32, // Calculate the determinant det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (!det) { return null; } det = 1.0 / det; out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; return out; }; /** * Returns Frobenius norm of a mat3 * * @param {mat3} a the matrix to calculate Frobenius norm of * @returns {Number} Frobenius norm */ mat3.frob = function (a) { return(Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2) + Math.pow(a[4], 2) + Math.pow(a[5], 2) + Math.pow(a[6], 2) + Math.pow(a[7], 2) + Math.pow(a[8], 2))) }; export default mat3;
pissang/qtek
src/glmatrix/mat3.js
JavaScript
bsd-2-clause
12,102
/* * Copyright (c) 2015, Linaro Limited * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <arm.h> #include <assert.h> #include <compiler.h> #include <inttypes.h> #include <kernel/generic_boot.h> #include <kernel/thread.h> #include <kernel/panic.h> #include <kernel/misc.h> #include <malloc.h> #include <mm/core_mmu.h> #include <mm/tee_mm.h> #include <mm/tee_mmu.h> #include <mm/tee_pager.h> #include <sm/tee_mon.h> #include <trace.h> #include <tee/tee_cryp_provider.h> #include <utee_defines.h> #include <util.h> #include <platform_config.h> #if !defined(CFG_WITH_ARM_TRUSTED_FW) #include <sm/sm.h> #endif #if defined(CFG_WITH_VFP) #include <kernel/vfp.h> #endif #define PADDR_INVALID 0xffffffff #ifdef CFG_BOOT_SYNC_CPU /* * Array used when booting, to synchronize cpu. * When 0, the cpu has not started. * When 1, it has started */ uint32_t sem_cpu_sync[CFG_TEE_CORE_NB_CORE] __data; #endif /* May be overridden in plat-$(PLATFORM)/main.c */ __weak void main_init_gic(void) { } #if defined(CFG_WITH_ARM_TRUSTED_FW) static void init_sec_mon(uint32_t nsec_entry __unused) { assert(nsec_entry == PADDR_INVALID); /* Do nothing as we don't have a secure monitor */ } #else static void init_sec_mon(uint32_t nsec_entry) { struct sm_nsec_ctx *nsec_ctx; assert(nsec_entry != PADDR_INVALID); /* Initialize secure monitor */ nsec_ctx = sm_get_nsec_ctx(); nsec_ctx->mon_lr = nsec_entry; nsec_ctx->mon_spsr = CPSR_MODE_SVC | CPSR_I; } #endif #if defined(CFG_WITH_ARM_TRUSTED_FW) static void init_vfp_nsec(void) { } #else static void init_vfp_nsec(void) { /* Normal world can use CP10 and CP11 (SIMD/VFP) */ write_nsacr(read_nsacr() | NSACR_CP10 | NSACR_CP11); } #endif #if defined(CFG_WITH_VFP) #ifdef ARM32 static void init_vfp_sec(void) { uint32_t cpacr = read_cpacr(); /* Enable usage of CP10 and CP11 (SIMD/VFP) */ cpacr &= ~CPACR_CP(10, CPACR_CP_ACCESS_FULL); cpacr |= CPACR_CP(10, CPACR_CP_ACCESS_PL1_ONLY); cpacr &= ~CPACR_CP(11, CPACR_CP_ACCESS_FULL); cpacr |= CPACR_CP(11, CPACR_CP_ACCESS_PL1_ONLY); write_cpacr(cpacr); } #endif /* ARM32 */ #ifdef ARM64 static void init_vfp_sec(void) { /* Not using VFP until thread_kernel_enable_vfp() */ vfp_disable(); } #endif /* ARM64 */ #else /* CFG_WITH_VFP */ static void init_vfp_sec(void) { /* Not using VFP */ } #endif #ifdef CFG_WITH_PAGER static size_t get_block_size(void) { struct core_mmu_table_info tbl_info; unsigned l; if (!core_mmu_find_table(CFG_TEE_RAM_START, UINT_MAX, &tbl_info)) panic(); l = tbl_info.level - 1; if (!core_mmu_find_table(CFG_TEE_RAM_START, l, &tbl_info)) panic(); return 1 << tbl_info.shift; } static void init_runtime(uint32_t pageable_part) { size_t n; size_t init_size = (size_t)__init_size; size_t pageable_size = __pageable_end - __pageable_start; size_t hash_size = (pageable_size / SMALL_PAGE_SIZE) * TEE_SHA256_HASH_SIZE; tee_mm_entry_t *mm; uint8_t *paged_store; uint8_t *hashes; uint8_t *tmp_hashes = __init_start + init_size; size_t block_size; TEE_ASSERT(pageable_size % SMALL_PAGE_SIZE == 0); /* Copy it right after the init area. */ memcpy(tmp_hashes, __data_end + init_size, hash_size); /* * Zero BSS area. Note that globals that would normally would go * into BSS which are used before this has to be put into .nozi.* * to avoid getting overwritten. */ memset(__bss_start, 0, __bss_end - __bss_start); malloc_init(__heap1_start, __heap1_end - __heap1_start); malloc_add_pool(__heap2_start, __heap2_end - __heap2_start); hashes = malloc(hash_size); EMSG("hash_size %zu", hash_size); TEE_ASSERT(hashes); memcpy(hashes, tmp_hashes, hash_size); /* * Need tee_mm_sec_ddr initialized to be able to allocate secure * DDR below. */ teecore_init_ta_ram(); mm = tee_mm_alloc(&tee_mm_sec_ddr, pageable_size); TEE_ASSERT(mm); paged_store = (uint8_t *)tee_mm_get_smem(mm); /* Copy init part into pageable area */ memcpy(paged_store, __init_start, init_size); /* Copy pageable part after init part into pageable area */ memcpy(paged_store + init_size, (void *)pageable_part, __pageable_part_end - __pageable_part_start); /* Check that hashes of what's in pageable area is OK */ DMSG("Checking hashes of pageable area"); for (n = 0; (n * SMALL_PAGE_SIZE) < pageable_size; n++) { const uint8_t *hash = hashes + n * TEE_SHA256_HASH_SIZE; const uint8_t *page = paged_store + n * SMALL_PAGE_SIZE; TEE_Result res; DMSG("hash pg_idx %zu hash %p page %p", n, hash, page); res = hash_sha256_check(hash, page, SMALL_PAGE_SIZE); if (res != TEE_SUCCESS) { EMSG("Hash failed for page %zu at %p: res 0x%x", n, page, res); panic(); } } /* * Copy what's not initialized in the last init page. Needed * because we're not going fault in the init pages again. We can't * fault in pages until we've switched to the new vector by calling * thread_init_handlers() below. */ if (init_size % SMALL_PAGE_SIZE) { uint8_t *p; memcpy(__init_start + init_size, paged_store + init_size, SMALL_PAGE_SIZE - (init_size % SMALL_PAGE_SIZE)); p = (uint8_t *)(((vaddr_t)__init_start + init_size) & ~SMALL_PAGE_MASK); cache_maintenance_l1(DCACHE_AREA_CLEAN, p, SMALL_PAGE_SIZE); cache_maintenance_l1(ICACHE_AREA_INVALIDATE, p, SMALL_PAGE_SIZE); } /* * Initialize the virtual memory pool used for main_mmu_l2_ttb which * is supplied to tee_pager_init() below. */ block_size = get_block_size(); if (!tee_mm_init(&tee_mm_vcore, ROUNDDOWN(CFG_TEE_RAM_START, block_size), ROUNDUP(CFG_TEE_RAM_START + CFG_TEE_RAM_VA_SIZE, block_size), SMALL_PAGE_SHIFT, 0)) panic(); /* * Claim virtual memory which isn't paged, note that there migth be * a gap between tee_mm_vcore.lo and TEE_RAM_START which is also * claimed to avoid later allocations to get that memory. */ mm = tee_mm_alloc2(&tee_mm_vcore, tee_mm_vcore.lo, (vaddr_t)(__text_init_start - tee_mm_vcore.lo)); TEE_ASSERT(mm); /* * Allocate virtual memory for the pageable area and let the pager * take charge of all the pages already assigned to that memory. */ mm = tee_mm_alloc2(&tee_mm_vcore, (vaddr_t)__pageable_start, pageable_size); TEE_ASSERT(mm); tee_pager_add_area(mm, TEE_PAGER_AREA_RO | TEE_PAGER_AREA_X, paged_store, hashes); tee_pager_add_pages((vaddr_t)__pageable_start, ROUNDUP(init_size, SMALL_PAGE_SIZE) / SMALL_PAGE_SIZE, false); tee_pager_add_pages((vaddr_t)__pageable_start + ROUNDUP(init_size, SMALL_PAGE_SIZE), (pageable_size - ROUNDUP(init_size, SMALL_PAGE_SIZE)) / SMALL_PAGE_SIZE, true); } #else static void init_runtime(uint32_t pageable_part __unused) { /* * Zero BSS area. Note that globals that would normally would go * into BSS which are used before this has to be put into .nozi.* * to avoid getting overwritten. */ memset(__bss_start, 0, __bss_end - __bss_start); malloc_init(__heap1_start, __heap1_end - __heap1_start); /* * Initialized at this stage in the pager version of this function * above */ teecore_init_ta_ram(); } #endif static void init_primary_helper(uint32_t pageable_part, uint32_t nsec_entry) { /* * Mask asynchronous exceptions before switch to the thread vector * as the thread handler requires those to be masked while * executing with the temporary stack. The thread subsystem also * asserts that IRQ is blocked when using most if its functions. */ thread_set_exceptions(THREAD_EXCP_ALL); init_vfp_sec(); init_runtime(pageable_part); IMSG("Initializing (%s)\n", core_v_str); thread_init_primary(generic_boot_get_handlers()); thread_init_per_cpu(); init_sec_mon(nsec_entry); main_init_gic(); init_vfp_nsec(); if (init_teecore() != TEE_SUCCESS) panic(); DMSG("Primary CPU switching to normal world boot\n"); } static void init_secondary_helper(uint32_t nsec_entry) { /* * Mask asynchronous exceptions before switch to the thread vector * as the thread handler requires those to be masked while * executing with the temporary stack. The thread subsystem also * asserts that IRQ is blocked when using most if its functions. */ thread_set_exceptions(THREAD_EXCP_ALL); thread_init_per_cpu(); init_sec_mon(nsec_entry); init_vfp_sec(); init_vfp_nsec(); DMSG("Secondary CPU Switching to normal world boot\n"); } #if defined(CFG_WITH_ARM_TRUSTED_FW) uint32_t *generic_boot_init_primary(uint32_t pageable_part) { init_primary_helper(pageable_part, PADDR_INVALID); return thread_vector_table; } uint32_t generic_boot_cpu_on_handler(uint32_t a0 __unused, uint32_t a1 __unused) { DMSG("cpu %zu: a0 0x%x", get_core_pos(), a0); init_secondary_helper(PADDR_INVALID); return 0; } #else void generic_boot_init_primary(uint32_t pageable_part, uint32_t nsec_entry) { init_primary_helper(pageable_part, nsec_entry); } void generic_boot_init_secondary(uint32_t nsec_entry) { init_secondary_helper(nsec_entry); } #endif
BreezeWu/optee_os
core/arch/arm/kernel/generic_boot.c
C
bsd-2-clause
10,169
cask :v1 => 'kicad-nightly' do version 'r6188.20150913-035418' sha256 'd43da295d54c1a80b7d0b6ad541bdea0a8f6168002413a3859574bc0c3a06087' url "http://downloads.kicad-pcb.org/osx/kicad-#{version}.dmg" name 'KiCad' homepage 'http://www.kicad-pcb.org' license :gpl artifact 'kicad', :target => Pathname.new(File.expand_path('~')).join('Library/Application Support/kicad') suite 'Kicad' end
1zaman/homebrew-versions
Casks/kicad-nightly.rb
Ruby
bsd-2-clause
404
class LeanCli < Formula desc "Command-line tool to develop and manage LeanCloud apps." homepage "https://github.com/leancloud/lean-cli" url "https://github.com/leancloud/lean-cli/archive/v0.16.2.tar.gz" sha256 "70c31c81966bc12cf9de22a3192e55f03c64055a907e42995e5df98db2c89a32" head "https://github.com/leancloud/lean-cli.git" bottle do cellar :any_skip_relocation sha256 "3e80626dbf7efd1e5c509e5af4c7cd92c8003487c5a3ca1ed989471aad785c80" => :high_sierra sha256 "e9c7fd636b43d700d52e45d07d7ecf6d625e0b3df61b18c5af979ca202593519" => :sierra sha256 "3a33f49c57410134a2d8ae4f995b3bf67228cf375bcf5460f2bc096d34903430" => :el_capitan end depends_on "go" => :build def install build_from = build.head? ? "homebrew-head" : "homebrew" ENV["GOPATH"] = buildpath mkdir_p buildpath/"src/github.com/leancloud/" ln_s buildpath, buildpath/"src/github.com/leancloud/lean-cli" system "go", "build", "-o", bin/"lean", "-ldflags", "-X main.pkgType=#{build_from}", "github.com/leancloud/lean-cli/lean" bash_completion.install "misc/lean-bash-completion" => "lean" zsh_completion.install "misc/lean-zsh-completion" => "_lean" end test do assert_match "lean version #{version}", shell_output("#{bin}/lean --version") end end
bfontaine/homebrew-core
Formula/lean-cli.rb
Ruby
bsd-2-clause
1,313
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder\Iterator; use Symfony\Component\Finder\Expression\Expression; /** * MultiplePcreFilterIterator filters files using patterns (regexps, globs or strings). * * @author Fabien Potencier <[email protected]> */ abstract class MultiplePcreFilterIterator extends FilterIterator { protected $matchRegexps = array(); protected $noMatchRegexps = array(); /** * Constructor. * * @param \Iterator $iterator The Iterator to filter * @param array $matchPatterns An array of patterns that need to match * @param array $noMatchPatterns An array of patterns that need to not match */ public function __construct( \Iterator $iterator, array $matchPatterns, array $noMatchPatterns ) { foreach ($matchPatterns as $pattern) { $this->matchRegexps[] = $this->toRegex( $pattern ); } foreach ($noMatchPatterns as $pattern) { $this->noMatchRegexps[] = $this->toRegex( $pattern ); } parent::__construct( $iterator ); } /** * Converts string into regexp. * * @param string $str Pattern * * @return string regexp corresponding to a given string */ abstract protected function toRegex( $str ); /** * Checks whether the string is a regex. * * @param string $str * * @return bool Whether the given string is a regex */ protected function isRegex( $str ) { return Expression::create( $str )->isRegex(); } }
TheTypoMaster/SPHERE-Framework
Library/MOC-V/Core/SecureKernel/Vendor/PhpSecLib/0.3.9/vendor/symfony/finder/Symfony/Component/Finder/Iterator/MultiplePcreFilterIterator.php
PHP
bsd-2-clause
1,788
<!DOCTYPE html> <html> <head> <link rel="shortcut icon" type="image/png" href="/logo.png" /> <link rel="stylesheet" href="qtopology_dashboard.css" /> <script src="qtopology_dashboard.js"></script> <script src="d3.min.js"></script> <script src="jquery-2.2.0.min.js"></script> <script src="knockout-3.4.0.js"></script> </head> <body> <div class="header"> <div style="float: left; padding-right: 40px; padding-top: 10px;" data-bind="visible: show_back_link"> <a data-bind="attr: { href: back_url, title: back_title }"> &laquo; <span data-bind="text: back_title"> Back </span> </a> </div> <img src="logo.png" alt="logo" class="logo" /> <h1 data-bind="text: title"></h1> </div> <div class="error-panel" data-bind="visible: showError" style="display: none"> <div class="error-content"> <!-- <div class="pull-right"> <span class="error-panel-button" data-bind="click: closeError">&times;</span> </div> --> <div class="error-close close-btn" data-bind="click: closeError">&times;</div> <h3>Error</h3> <p data-bind="text: errorMessage"></p> </div> </div> <div id="bladeMsgQueue" class="blade" style="display: none"> <div class="blade-content"> <div class="blade-close close-btn" data-bind="click: closeBlade">&times;</div> <h1>Message queue</h1> <div> <div class="cell-12"> <div class="panel"> <div class="panel-header"> <div class="title">Current queue</div> </div> <div class="panel-body"> <table> <thead> <tr> <th class="td-datetime">When</th> <th class="td-datetime">Valid until</th> <th>Worker</th> <th>Cmd</th> <th>Content</th> </tr> </thead> <tbody data-bind="foreach: msg_queue_current"> <tr> <td class="td-datetime" data-bind="text: ts_s"></td> <td class="td-datetime" data-bind="text: valid_until_s"></td> <td data-bind="text: worker"></td> <td data-bind="text: cmd"></td> <td data-bind="text: content_s"></td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> <div id="bladeWorker" class="blade" style="display: none"> <div class="blade-content" data-bind="with: selected_worker"> <div class="blade-close close-btn" data-bind="click: $parent.closeBlade">&times;</div> <h1>Worker info</h1> <div> <div class="cell-2"> <div class="panel"> <div class="panel-header"> <div class="title">Properties</div> </div> <div class="panel-body props"> <dt>Name</dt> <dd data-bind="text: name()"></dd> <dt>Status</dt> <dd> <span class="badge badge-green" data-bind="visible: status()=='alive'">Alive</span> <span class="badge badge-red" data-bind="visible: status()=='dead'">Dead</span> <span class="badge badge-orange" data-bind="visible: status()=='closing'">Closing</span> <span class="badge" data-bind="visible: status()=='disabled'">Disabled</span> <span class="badge" data-bind="visible: status()=='unloaded'">Unloaded</span> </dd> <dt>Status updated</dt> <dd data-bind="text: last_ping_s()"></dd> <dt>Leadership status</dt> <dd> <span class="badge badge-gold" data-bind="visible: lstatus() == 'leader'">Leader</span> <span class="badge" data-bind="visible: lstatus() != 'leader'">Normal</span> </dd> </div> </div> <div class="panel"> <div class="panel-header"> <div class="title">Actions</div> </div> <div class="panel-body props"> <div class="action-panel" data-bind="visible: status() == 'alive' && lstatus() == 'leader'"> <div class="action-title"> Rebalance </div> <div class="action-desc"> Sends a message to this worker (it must be marked as leader) to performa rebalance of topologies. </div> <div class="action-btn"> <button data-bind="click: rebalance">Rebalance</button> </div> </div> <div class="action-panel" data-bind="visible: status() == 'alive'"> <div class="action-title"> Shut down </div> <div class="action-desc"> Shuts down this worker. You have to have a mechanism to bring it up again, as it cannot be done via this dashboard. </div> <div class="action-btn"> <button data-bind="click: shut_down">Shutdown</button> </div> </div> <div class="action-panel" data-bind="visible: status() == 'alive'"> <div class="action-title"> Disable </div> <div class="action-desc"> Disables this worker. All topologies on this worker are stopped and no new one is assigned. </div> <div class="action-btn"> <button data-bind="click: disable">Disable</button> </div> </div> <div class="action-panel" data-bind="visible: status() == 'disabled'"> <div class="action-title"> Enable </div> <div class="action-desc"> Enables this worker. It becomes ready to accept new topology assignments. </div> <div class="action-btn"> <button data-bind="click: enable">Enable</button> </div> </div> <div class="action-panel" data-bind="visible: status() == 'unloaded'"> <div class="action-title"> Delete worker </div> <div class="action-desc"> If this worker record is obsolete, you can delete it from the list of workers. </div> <div class="action-btn"> <button data-bind="click: remove">Delete</button> </div> </div> </div> </div> </div> <div class="cell-6"> <div class="panel"> <div class="panel-header"> <div class="title">Topologies</div> </div> <div class="panel-body"> <div data-bind="foreach: topologies"> <div class="ticket"> <div class="ticket-inner"> <div class="pull-right"> <!-- Enabled/diabled badge --> <span class="badge badge-green" data-bind="visible: enabled()==true">Enabled</span> <span class="badge " data-bind="visible: enabled()==false">Disabled</span> <!--Status badge--> <span class="badge badge-green" data-bind="visible: status()=='running'">Running</span> <span class="badge badge-red" data-bind="visible: status()=='error'">Error</span> <span class="badge" data-bind="visible: status()=='unloaded'">Unloaded</span> <span class="badge badge-orange" data-bind="visible: status()=='waiting'">Waiting</span> </div> <label data-bind="text: uuid()"></label> <div> worker: <span data-bind="text: worker()"></span> &bull; pid: <span data-bind="text: pid()"></span> </div> <div class="right"> <a data-bind="click: open">More &raquo;</a> </div> </div> </div> </div> </div> </div> </div> <div class="cell-4"> <div class="panel"> <div class="panel-header"> <div class="title">History</div> </div> <div class="panel-body"> <table> <thead> <tr> <th class="td-datetime">When</th> <th>Status</th> <th>Leadership</th> </tr> </thead> <tbody data-bind="foreach: history"> <tr> <td class="td-datetime" data-bind="text: ts_s"></td> <td> <span class="badge badge-green" data-bind="visible: status=='alive'">Alive</span> <span class="badge badge-red" data-bind="visible: status=='dead'">Dead</span> <span class="badge badge-orange" data-bind="visible: status=='closing'">Closing</span> <span class="badge" data-bind="visible: status=='unloaded'">Unloaded</span> <span class="badge" data-bind="visible: status=='disabled'">Disabled</span> </td> <td> <span class="badge badge-gold" data-bind="visible: lstatus=='leader'">Leader</span> <span class="badge" data-bind="visible: lstatus!='leader'">Normal</span> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> <div id="bladeTopology" class="blade" style="display: none"> <div class="blade-content" data-bind="with: selected_topology"> <div class="blade-close close-btn" data-bind="click: $parent.closeBlade">&times;</div> <h1>Topology info</h1> <div class="cell-2"> <div class="panel"> <div class="panel-header"> <div class="title">Properties</div> </div> <div class="panel-body"> <div class="props"> <dt>UUID</dt> <dd data-bind="text: uuid()"></dd> <dt>Enabled</dt> <dd> <span class="badge badge-green" data-bind="visible: enabled()==true">Enabled</span> <span class="badge " data-bind="visible: enabled()==false">Disabled</span> </dd> <dt>Status</dt> <dd> <span class="badge badge-green" data-bind="visible: status()=='running'">Running</span> <span class="badge badge-red" data-bind="visible: status()=='error'">Error</span> <span class="badge" data-bind="visible: status()=='unassigned'">Unassigned</span> <span class="badge badge-orange" data-bind="visible: status()=='waiting'">Waiting</span> </dd> <dt>Worker</dt> <dd data-bind="text: worker()"></dd> <dt>PID</dt> <dd data-bind="text: pid()"></dd> <dt>Error</dt> <dd data-bind="text: error()"></dd> </div> </div> <div class="panel"> <div class="panel-header"> <div class="title">Actions</div> </div> <div class="panel-body props"> <div class="action-panel" data-bind="visible: enabled() == true"> <div class="action-title"> Disable </div> <div class="action-desc"> <p> Click the button to mark the topology as disabled. This will prevent it from running again. </p> <p> It will not stop it, if it is currently running. </p> </div> <div class="action-btn"> <button data-bind="click: set_disabled">Disable</button> </div> </div> <div class="action-panel" data-bind="visible: enabled() == false"> <div class="action-title"> Enable </div> <div class="action-desc"> Click the button to mark the topology as enabled. This will make it available to workers and one of them pick should it up very soon, if there is at least one worker running. </div> <div class="action-btn"> <button data-bind="click: set_enabled">Enable</button> </div> </div> <div class="action-panel" data-bind="visible: enabled() == true && status() == 'error'"> <div class="action-title"> Clear the error </div> <div class="action-desc"> This topology was marked with error. Clear the error tag to make it start running again. </div> <div class="action-btn"> <button data-bind="click: clear_error">Clear error</button> </div> </div> <div class="action-panel" data-bind="visible: status() == 'running'"> <div class="action-title"> Stop this topology </div> <div class="action-desc"> <p> Send STOP signal to the worker that is running this topology. </p> <p> Also, the topology will be marked as disabled, so other workers wont pick it up and run it. </p> </div> <div class="action-btn"> <button data-bind="click: stop">Stop topology</button> </div> </div> <div class="action-panel" data-bind="visible: status() == 'running'"> <div class="action-title"> Kill this topology </div> <div class="action-desc"> <h2>USE WITH CAUTION</h2> <p> Instruct worker to send KILL signal to the topology. This will abruptly stop the topology and might <b>cause corrupt state</b>. </p> <p> Also, the topology will be marked as disabled, so other workers wont pick it up and run it. </p> </div> <div class="action-btn"> <button data-bind="click: kill">Kill topology</button> </div> </div> </div> </div> </div> </div> <div class="cell-10"> <div class="panel"> <div class="panel-header"> <div class="title">Visualization</div> </div> <div class="panel-body"> <img data-bind="attr: {src: viz_html}" style="max-width: 100%"> </div> </div> <div> <div class="cell-6"> <div class="panel"> <div class="panel-header"> <div class="title">Run-time info</div> </div> <div class="panel-body"> </div> </div> <div class="panel"> <div class="panel-header"> <div class="title">Configuration</div> </div> <div class="panel-body"> <pre data-bind="text: JSON.stringify(config(), null, 4)"> </pre> </div> </div> </div> <div class="cell-6"> <div class="panel"> <div class="panel-header"> <div class="title">History</div> </div> <div class="panel-body"> <table> <thead> <tr> <th class="td-datetime">When</th> <th>Enabled</th> <th>Status</th> <th>Worker</th> <th>Pid</th> <th>Error</th> </tr> </thead> <tbody data-bind="foreach: history"> <tr> <td class="td-datetime" data-bind="text: ts_s"></td> <td> <span class="badge badge-green" data-bind="visible: enabled==true">Enabled</span> <span class="badge " data-bind="visible: enabled==false">Disabled</span> </td> <td> <span class="badge badge-green" data-bind="visible: status=='running'">Running</span> <span class="badge badge-red" data-bind="visible: status=='error'">Error</span> <span class="badge" data-bind="visible: status=='unassigned'">Unassigned</span> <span class="badge badge-orange" data-bind="visible: status=='waiting'">Waiting</span> </td> <td data-bind="text: worker"></td> <td data-bind="text: pid"></td> <td> <div data-bind="visible: error != null && error.length > 0"> <a href="#" data-bind="click: click">Show &raquo;</a> </div> </td> </tr> <tr> <td></td> <td colspan="4" data-bind="visible: expanded" class="td-error"> <h3>Error message</h3> <span data-bind="text: error"></span> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> </div> <div class="content" style="display: none" data-bind="visible: show_content"> <div class="cell-4"> <div class="panel"> <div class="panel-header"> <div class="title">Alive Workers (<span data-bind="text: workers_alive().length"></span>)</div> </div> <div class="panel-body"> <div data-bind="foreach: workers_alive"> <div class="ticket"> <div class="ticket-inner"> <div class="pull-right"> <span class="badge badge-gold" data-bind="visible: lstatus()=='leader'">Leader</span> <span class="badge badge-green" data-bind="visible: status()=='alive'">Alive</span> <span class="badge badge-red" data-bind="visible: status()=='dead'">Dead</span> <span class="badge badge-orange" data-bind="visible: status()=='closing'">Closing</span> <span class="badge" data-bind="visible: status()=='unloaded'">Unloaded</span> <span class="badge" data-bind="visible: status()=='disabled'">Disabled</span> </div> <label data-bind="text: name()"></label> <div> topologies: <span data-bind="text: topologies_count()"></span> </div> <div class="right"> <a data-bind="click: open">More &raquo;</a> </div> </div> </div> </div> </div> </div> <div class="panel"> <div class="panel-header"> <a class="float-right" href="#" data-bind="click: toggle_workers_not_alive, visible: workers_not_alive_expanded">&#9650;</a> <a class="float-right" href="#" data-bind="click: toggle_workers_not_alive, visible: !workers_not_alive_expanded()">&#9660;</a> <div class="title">Dead Workers (<span data-bind="text: workers_not_alive().length"></span>) </div> </div> <div class="panel-body" data-bind="visible: workers_not_alive_expanded"> <div data-bind="foreach: workers_not_alive"> <div class="ticket"> <div class="ticket-inner"> <div class="pull-right"> <span class="badge badge-gold" data-bind="visible: lstatus()=='leader'">Leader</span> <span class="badge badge-green" data-bind="visible: status()=='alive'">Alive</span> <span class="badge badge-red" data-bind="visible: status()=='dead'">Dead</span> <span class="badge badge-orange" data-bind="visible: status()=='closing'">Closing</span> <span class="badge" data-bind="visible: status()=='unloaded'">Unloaded</span> <span class="badge" data-bind="visible: status()=='disabled'">Disabled</span> </div> <label data-bind="text: name()"></label> <div> topologies: <span data-bind="text: topologies_count()"></span> </div> <div class="right"> <a data-bind="click: open">More &raquo;</a> </div> </div> </div> </div> </div> </div> </div> <div class="cell-5"> <div class="panel"> <div class="panel-header"> <div class="title">Enabled Topologies (<span data-bind="text: topologies_enabled().length"></span>)</div> </div> <div class="panel-body"> <div data-bind="foreach: topologies_enabled"> <div class="ticket"> <div class="ticket-inner"> <div class="pull-right"> <span class="badge badge-green" data-bind="visible: enabled()==true">Enabled</span> <span class="badge " data-bind="visible: enabled()==false">Disabled</span> <span class="badge badge-green" data-bind="visible: status()=='running'">Running</span> <span class="badge badge-red" data-bind="visible: status()=='error'">Error</span> <span class="badge" data-bind="visible: status()=='unassigned'">Unassigned</span> <span class="badge badge-orange" data-bind="visible: status()=='waiting'">Waiting</span> </div> <label data-bind="text: uuid()"></label> <div> worker: <span data-bind="text: worker()"></span> &bull; pid: <span data-bind="text: pid()"></span> </div> <div class="right"> <a data-bind="click: open">More &raquo;</a> </div> </div> </div> </div> </div> </div> <div class="panel"> <div class="panel-header"> <a class="float-right" href="#" data-bind="click: toggle_topologies_not_enabled, visible: topologies_not_enabled_expanded">&#9650;</a> <a class="float-right" href="#" data-bind="click: toggle_topologies_not_enabled, visible: !topologies_not_enabled_expanded()">&#9660;</a> <div class="title">Disabled Topologies (<span data-bind="text: topologies_not_enabled().length"></span>)</div> </div> <div class="panel-body" data-bind="visible: topologies_not_enabled_expanded"> <div data-bind="foreach: topologies_not_enabled"> <div class="ticket"> <div class="ticket-inner"> <div class="pull-right"> <span class="badge badge-green" data-bind="visible: enabled()==true">Enabled</span> <span class="badge " data-bind="visible: enabled()==false">Disabled</span> <span class="badge badge-green" data-bind="visible: status()=='running'">Running</span> <span class="badge badge-red" data-bind="visible: status()=='error'">Error</span> <span class="badge" data-bind="visible: status()=='unassigned'">Unassigned</span> <span class="badge badge-orange" data-bind="visible: status()=='waiting'">Waiting</span> </div> <label data-bind="text: uuid()"></label> <div> &nbsp; </div> <div class="right"> <a data-bind="click: open">More &raquo;</a> </div> </div> </div> </div> </div> </div> </div> <div class="cell-3"> <div class="panel" data-bind="visible: show_custom_props" style="display: none"> <div class="panel-header"> <div class="title">Custom properties</div> </div> <div class="panel-body props"> <div data-bind="foreach: custom_props"> <dt data-bind="text: key"></dt> <dd data-bind="text: value"></dd> </div> </div> </div> <div class="panel"> <div class="panel-header"> <div class="title">Coordination storage</div> </div> <div class="panel-body props"> <div data-bind="foreach: storage_props"> <dt data-bind="text: key"></dt> <dd data-bind="text: value"></dd> </div> </div> </div> <div class="panel"> <div class="panel-header"> <div class="title">Message queue</div> </div> <div class="panel-body"> <div> <div class="action-panel"> <div class="action-title"> Inspect </div> <div class="action-desc"> <p> Show messages of the message queue. </p> </div> <div class="action-btn"> <button data-bind="click: showMsgQueue">Show message queue</button> </div> </div> </div> </div> </div> </div> </div> </body> <script src="viz.js"></script> <script language="javascript" type="text/javascript"> $(function () { var model = new QTopologyDashboardViewModel(); ko.applyBindings(model); model.init(function () { // result = Viz("digraph { a -> b; }", { format: "svg", engine: "dot" }); // alert($('.blade .panel-body').length) // $('.blade .panel-body').text(result); //image = Viz("digraph g { a -> b; }", { format: "png-image-element" }); //document.body.appendChild(image); //document.getElementById("para").innerHTML = result; //document.getElementById("divVizJs").appendChild(image); //console.log(result); }); }); </script> </html>
qminer/qtopology
resources/gui/qtopology_dashboard.html
HTML
bsd-2-clause
35,555
/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DOUGLAS_PEUCKER_HPP_ #define DOUGLAS_PEUCKER_HPP_ #include <stack> #include <vector> #include <array> /* This class object computes the bitvector of indicating generalized input * points according to the (Ramer-)Douglas-Peucker algorithm. * * Input is vector of pairs. Each pair consists of the point information and a * bit indicating if the points is present in the generalization. * Note: points may also be pre-selected*/ struct SegmentInformation; static const std::array<int, 19> DOUGLAS_PEUCKER_THRESHOLDS {{ 512440, // z0 256720, // z1 122560, // z2 56780, // z3 28800, // z4 14400, // z5 7200, // z6 3200, // z7 2400, // z8 1000, // z9 600, // z10 120, // z11 60, // z12 45, // z13 36, // z14 20, // z15 8, // z16 6, // z17 4 // z18 }}; class DouglasPeucker { public: using RandomAccessIt = std::vector<SegmentInformation>::iterator; using GeometryRange = std::pair<RandomAccessIt, RandomAccessIt>; // Stack to simulate the recursion std::stack<GeometryRange> recursion_stack; public: void Run(RandomAccessIt begin, RandomAccessIt end, const unsigned zoom_level); void Run(std::vector<SegmentInformation> &input_geometry, const unsigned zoom_level); }; #endif /* DOUGLAS_PEUCKER_HPP_ */
VRPTools/pkg-osrm-backend
algorithms/douglas_peucker.hpp
C++
bsd-2-clause
2,685
\documentclass[review,supplement]{siamart} \input{ex_shared} \externaldocument{ex_article} % Optional PDF information \ifpdf \hypersetup{ pdftitle={Supplementary Materials: \TheTitle}, pdfauthor={\TheAuthors} } \fi \begin{document} \maketitle \section{A detailed example} Here we include some equations and theorem-like environments to show how these are labeled in a supplement and can be referenced from the main text. Consider the following equation: \begin{equation} \label{eq:suppa} a^2 + b^2 = c^2. \end{equation} You can also reference equations such as \cref{eq:matrices,eq:bb} from the main article in this supplement. \lipsum[100-101] \begin{theorem} An example theorem. \end{theorem} \lipsum[102] \begin{lemma} An example lemma. \end{lemma} \lipsum[103-105] Here is an example citation: \cite{KoMa14}. \section[Proof of Thm]{Proof of \cref{thm:bigthm}} \label{sec:proof} \lipsum[106-114] \section{Additional experimental results} \Cref{tab:foo} shows additional supporting evidence. \begin{table}[htbp] \caption{Example table} \label{tab:foo} \centering \begin{tabular}{|c|c|c|} \hline Species & \bf Mean & \bf Std.~Dev. \\ \hline 1 & 3.4 & 1.2 \\ 2 & 5.4 & 0.6 \\ \hline \end{tabular} \end{table} \bibliographystyle{siamplain} \bibliography{references} \end{document}
tgkolda/siam-latex
siamlatex/ex_supplement.tex
TeX
bsd-2-clause
1,333
/** * @module ol/format/filter/Intersects */ import Spatial from './Spatial.js'; /** * @classdesc * Represents a `<Intersects>` operator to test whether a geometry-valued property * intersects a given geometry. * @api */ class Intersects extends Spatial { /** * @param {!string} geometryName Geometry name to use. * @param {!import("../../geom/Geometry.js").default} geometry Geometry. * @param {string=} opt_srsName SRS name. No srsName attribute will be * set on geometries when this is not provided. */ constructor(geometryName, geometry, opt_srsName) { super('Intersects', geometryName, geometry, opt_srsName); } } export default Intersects;
geekdenz/ol3
src/ol/format/filter/Intersects.js
JavaScript
bsd-2-clause
683
/* * Copyright (c) 2017, Adam <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.http.service.item; import java.time.Instant; import lombok.Data; import net.runelite.http.api.item.ItemType; @Data public class ItemEntry { private int id; private String name; private String description; private ItemType type; private Instant timestamp; }
Sethtroll/runelite
http-service/src/main/java/net/runelite/http/service/item/ItemEntry.java
Java
bsd-2-clause
1,665
var assert = require('assert'); describe('Core -> slot', function() { var slot; before(function() { var testEnv = require('./testEnv')(); slot = testEnv.slot; testEnv.app.loadModule = function(conf) { return { id: function() { return conf.moduleId; }, type: conf.type, slot: slot, init: function(data, cb) { cb(); } }; }; }); it('#init с параметрами (type, callback)', function(cb) { assert(slot.init, 'slot имеет метод init'); slot.init('foo', function(err, module) { assert(!err); assert(module); assert.equal(module.type, 'foo'); cb(); }); }); it('#init с параметрами (type, data, callback)', function(cb) { slot.init('foo', {}, function(err, module) { assert(!err); assert(module); assert.equal(module.type, 'foo'); cb(); }); }); it('#init с параметрами (moduleConf, callback)', function(cb) { slot.init({type: 'foo', data: {}}, function(err, module) { assert(!err); assert(module); assert.equal(module.type, 'foo'); cb(); }); }); /* it('blank', function() { assert(slot); }); it('setTimeout на клиенте возвращает id таймаута для возможности его отмены', function() { var saveIsClient = testEnv.app.isClient; var saveIsServer = testEnv.app.isServer; testEnv.app.isServer = false; testEnv.app.isClient = true; var timer = slot.setTimeout(function() {}, 1); assert(timer); testEnv.app.isServer = saveIsServer; testEnv.app.isClient = saveIsClient; }); it('setTimeout устанавливает таймаут и выполняет callback', function() { var saveIsClient = testEnv.app.isClient; var saveIsServer = testEnv.app.isServer; testEnv.app.isServer = false; testEnv.app.isClient = true; var clock = sinon.useFakeTimers(), test = sinon.spy(), timer = slot.setTimeout(test, 100); assert(!test.called); clock.tick(100); assert(test.calledOnce); clock.restore(); testEnv.app.isServer = saveIsServer; testEnv.app.isClient = saveIsClient; }); it('clearTimeouts отменяет все установленные через слот таймауты', function() { var saveIsClient = testEnv.app.isClient; var saveIsServer = testEnv.app.isServer; testEnv.app.isServer = false; testEnv.app.isClient = true; var clock = sinon.useFakeTimers(), test = sinon.spy(), timer = slot.setTimeout(test, 100); slot.clearTimeouts(); clock.tick(100); assert(!test.called); clock.restore(); testEnv.app.isServer = saveIsServer; testEnv.app.isClient = saveIsClient; }); describe('ifAlive', function() { it('ifAlive регистрирует функцию и в живом модуле вызывает именно её', function() { var result = false, fn = function() { result = true; }; var toCall = slot.ifAlive(fn); toCall(); assert(result, 'Функция так и не была вызвана'); }); it('ifAlive регистрирует функцию и в мёртвом модуле её не вызывает', function() { var result = true, fn = function() { result = false; }; var toCall = slot.ifAlive(fn); slot.dispose(); toCall(); assert(result, 'Функция была вызвана после slot.dispose'); }); it('ifAlive регистрирует функцию после смерти модуля и её не вызывает', function() { var result = true, fn = function() { result = false; }; slot.dispose(); var toCall = slot.ifAlive(fn); toCall(); assert(result, 'Функция была вызвана после slot.dispose'); }); }); */ });
2gis/slot
tests/slot.spec.js
JavaScript
bsd-2-clause
4,647
(function() { // ANSI color code outputs for strings var ANSI_CODES = { "off": 0, "bold": 1, "italic": 3, "underline": 4, "blink": 5, "inverse": 7, "hidden": 8, "black": 30, "red": 31, "green": 32, "yellow": 33, "blue": 34, "magenta": 35, "cyan": 36, "white": 37, "black_bg": 40, "red_bg": 41, "green_bg": 42, "yellow_bg": 43, "blue_bg": 44, "magenta_bg": 45, "cyan_bg": 46, "white_bg": 47 }; function setColor(str,color) { if(!color) return str; var color_attrs = color.split("+"); var ansi_str = ""; for(var i=0, attr; attr = color_attrs[i]; i++) { ansi_str += "\033[" + ANSI_CODES[attr] + "m"; } ansi_str += str + "\033[" + ANSI_CODES["off"] + "m"; return ansi_str; } function logMessage(message,color) { console.log(setColor(message,color)); } function replace(full_text, search_regex, color) { try { var regex = new RegExp('(' + search_regex + ')', 'ig'); var new_text = full_text.replace(regex, setColor('$1', color)); return new_text; } catch (e) { return full_text; } } if (typeof exports !== "undefined") { exports.log = logMessage; exports.set = setColor; exports.replace = replace; } else if (typeof define !== "undefined") { define([], function() { return { set: setColor, log: logMessage }; }); } }());
vikasums/ansi-color
lib/ansi-color.js
JavaScript
bsd-2-clause
1,312
### Summary The goal of this proposed work is to change how we use Jupyter Notebook cells for rendering KBase methods and data. Currently we use modified Markdown cells for that purpose, with method and app cells making direct kernel calls to invoke their functions. Although this is functional, it carries many security issues, and does not conform to the Jupyter standard for extensions. This work would change those to behave as code cells, conforming to the Jupyter notebook methodology and Jupyter extension specifications. ### Background When we started the Narrative project back in 2013, the IPython notebook was at an early dev version. At that time, there were mocked up designs for point-and-click-based cells (that have now grown into KBase method and app cells). Though the eventual goal was to serve both computationalists and experimentalists, our first focus was on support for experimentalists with the simpler interface. This was stymied, at the time, by limited support in the IPython notebook for visual, interactive (i.e. JavaScript-based) extensions. However, Markdown cells had the ability to render arbitrary JavaScript. We leveraged that to build the suite of App and Method cells, as well as a framework for rendering a library of interactive widgets on the front end. These were limited, however, to only working in the user's browser, which can require doing some heavy computation. As we developed things for KBase needs, the IPython (later, Jupyter) team developed similar things to support their broader userbase. This includes a set of code-cell based "widgets" that interact directly with the kernel, and can trigger computation that takes place on the back-end, allowing the front-end to only render the visual output. This brings us to today. The KBase cells are still modified markdown cells that render semi-raw JavaScript. Jupyter notebook code cells, however, support more tightly designed extensions that allow close interaction between the kernel's computational power and the browser for rendering. It would be very beneficial to the KBase project to migrate our cell representation to code cells. ### Description The focus of this project is on the standardization of KBase cells to extend code cells in all cases. Currently, our changes to markdown cells for rendering methods and apps are problematic in the following ways: 1. KBase changes to markdown cells are not sustainable with current and upcoming changes to Jupyter. 2. By their nature, our changes to markdown cells are not secure. We had to modify Jupyter to allow running arbitrary JavaScript in markdown cells. 3. Interactions are all currently from the client (i.e. browser) to various services. This has several implications: a. Puts undue stress on the client's browser to download, process, and render data components that can be done more efficiently by the kernel. b. This changes the central metaphor of the Jupyter notebook, where code should be written in cells and executed in the kernel, not in the browser. c. Introduces more challenges with regard to serving our computational users who would want to programmatically run methods and view outputs. The work described here will change those cells to run as semi-automatic code cells, following a similar pattern already performed by the GenePattern project. Any user interaction that would generate a visual cell (whether app, output, or viewer) would generate a piece of code injected into a code cell. This cell would be automatically run to produce the interactive viewer. This viewer would then have a toggle button to optionally show the code that (a) generated it and (b) is run by it, in the case of method cells. These cell modifications will standardize around the code that gets run, and will be a first good step toward enabling a KBase API that advanced computational users could use. Additionally, this will help enable a greater breadth of UI elements. Since output visualizations would then follow the Jupyter notebook standard, this would allow for more custom code to be created in SDK modules. Finally, this will be a step on the path toward creating static HTML narratives through the Jupyter nbconvert package, although this will require modification of our JavaScript visualization widgets. ### User Stories A developer should be able to invoke their method programmatically using a KBase API command that gets generated by method cells. A user should be able to click a button in a method, app, or viewer to see the code that generated that cell. A user should be able to modify the code that generated a cell, run it again, and see a new cell output. A less-computationally-savvy user should not see a difference in their user experience once the cell updates have been made. ### Narrative Mockup (to be completed) ### Timeline Three sprints 1. **Goal**: render visualization widgets in the Narrative via some Narrative API call. This is mostly already doable, but this sprint will expand on the capability. 1. Allow for widget packages built as a kbase-ui plugin to render in the Narrative. - Implies a way to list available widgets, import particular widgets, ensure they're loaded, etc. - Will require a way to build and test locally. 2. Start migrating existing widgets in the narrative repo into a kbase-ui plugin for loading in both the NI and landing pages. 3. Widgets generated this way should look identical to current widgets, but should be able to toggle their Code Cell input area. A successful sprint here would result in a simple API (at least a prototype) that allows for running widgets that save and restore state in such a way that they're indistinguishable from other Jupyter cell commands (e.g. runs done with Plot.ly or matplotlib) 2. **Goal**: prototype an API that executes jobs programmatically. 1. Job running should behave as it does now - creates and manages a job in the Jobs Panel, also creates a Job Object that can be queried for status, logs, and result widgets. 2. Newly clicked method cells should be invoked by similar code cells. Clicking the Run button should execute code via the API. 3. Test the API with internal users. A successful sprint here would produce a prototype, possibly incomplete API that would likely consist of accessory functions for fetching KBase App information and Job management. 3. **Goal**: finalize the standardization 1. Clean up the prototype API based on testing and interaction with internal users. 2. Finalize cell rendering functionality to be entirely based on code cells. 3. Build a Narrative updater that will migrate existing Narratives using Markdown cells to the new format. A successful final sprint will have an initial release of the programmatic API, as well as using it internally for all new point-and-click based method calls. ### Test Plan Testing is critical to this project. As it is mainly a refactor project, testing should focus on automated regression tests - making sure that app cells continue to render and run in a similar way.
kbase/roadmap
Scheduled product descriptions/2016Q2/Narrative Cell Standardization.md
Markdown
bsd-2-clause
7,118
2016-04-26T17:00:49-05:00 Mon, 25 Apr 2016 19:33:49 -0500 <div class="clear"></div> <div class="nota-texto" itemprop="articleBody"> <p>El estreno de la sexta temporada de "<a href="http://elcomercio.pe/noticias/game-of-thrones-369285?ref=nota_lima&amp;ft=contenido"><strong>Game of Thrones</strong></a>" no dejó ajeno a nadie y al parecer esto último también incluye al administrador de la página de <a href="http://elcomercio.pe/noticias/facebook-514822?ref=nota_lima&amp;ft=contenido"><strong>Facebook</strong></a> de la Policía Nacional del Perú (<strong>PNP</strong>).</p> <p>En una divertida imagen que alude claramente a la serie de HBO,&nbsp;<span>"</span><strong>Game of Thrones</strong><span>"</span>, la policía envía en <strong>Facebook</strong> un contundente mensaje que habla sobre la igualdad ante la ley de los ciudadanos&nbsp; peruanos.</p> <p>“No importa quién seas, no importa tu apellido, no importa a quién conozcas, la ley es la misma para todos”, reza el mensaje que aparece en la imagen publicada en <strong>Facebook</strong> por la PNP. Al fondo se puede ver el trono de hierro, uno de los símbolos más conocidos de <span>"</span><strong>Game of Thrones</strong><span>"</span>.</p> <div class="img-nota"><iframe allowtransparency="true" frameborder="0" height="658" scrolling="no" src="https://www.facebook.com/plugins/post.php?href=https%3A%2F%2Fwww.facebook.com%2FPoliciaDelPeru%2Fposts%2F1357782140903750&amp;width=500" width="500"></iframe></div> <p>La publicación ha demostrado ser bastante popular en <strong>Facebook</strong> pues acumula más de cinco mil reacciones y ha sido compartida por 882 personas.</p> <p>El buen criterio de la página de la PNP al elegir los temas de actualidad en sus campañas ha generado una gran empatía con los usuarios de <strong>Facebook</strong> y más de uno dice que el administrador “no se pierde una”.</p> <p><em>MÁS EN <strong>FACEBOOK</strong>...</em></p> <div> <blockquote class="twitter-tweet" data-lang="es"> <p dir="ltr" lang="es">Mejora tu experiencia en <a href="https://twitter.com/hashtag/Facebook?src=hash">#Facebook</a> con estas aplicaciones ► <a href="https://t.co/wv6AUdDAn3">https://t.co/wv6AUdDAn3</a> <a href="https://t.co/qqgMykPOsx">pic.twitter.com/qqgMykPOsx</a></p> — El Comercio (@elcomercio) <a href="https://twitter.com/elcomercio/status/724606149937487872">25 de abril de 2016</a></blockquote> <script async="" charset="utf-8" src="//platform.twitter.com/widgets.js"></script></div> <p>&nbsp;</p> </div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/es_LA/sdk.js#xfbml=1&version=v2.4&appId=154150073751"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <div class="box-follow-fb"> <div class="fb-page" data-href="https://www.facebook.com/elcomercio.pe" data-width="433" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true" data-show-posts="false"><div class="fb-xfbml-parse-ignore"><blockquote cite="https://www.facebook.com/elcomercio.pe"><a href="https://www.facebook.com/elcomercio.pe">Diario El Comercio (Perú)</a></blockquote></div></div> </div> <br> <div class="nota-tags"> <h4>Tags relacionados</h4> <h2><a href="http://elcomercio.pe/noticias/facebook-514822" itemprop="keywords">Facebook</a></h2> <h2><a href="http://elcomercio.pe/noticias/game-of-thrones-369285" itemprop="keywords">Game of Thrones</a></h2> </div>
gcvalderrama/Palantir
news/raw/attack--facebook-policia-nacional-tampoco-ignoro-regreso-game-of-thrones-noticia-1896874.html
HTML
bsd-2-clause
3,843
"""Miscellaneous AMICI Python interface tests""" import amici import sympy as sp def test_csc_matrix(): """Test sparse CSC matrix creation""" matrix = sp.Matrix([[1, 0], [2, 3]]) symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, sparse_matrix \ = amici.ode_export.csc_matrix(matrix, rownames=['a1', 'a2'], colnames=['b1', 'b2']) assert symbol_col_ptrs == [0, 2, 3] assert symbol_row_vals == [0, 1, 1] assert sparse_list == sp.Matrix([[1], [2], [3]]) assert symbol_list == ['da1_db1', 'da2_db1', 'da2_db2'] assert str(sparse_matrix) == 'Matrix([[da1_db1, 0], [da2_db1, da2_db2]])' def test_csc_matrix_empty(): """Test sparse CSC matrix creation for empty matrix""" matrix = sp.Matrix() symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, sparse_matrix \ = amici.ode_export.csc_matrix(matrix, rownames=[], colnames=[]) assert symbol_col_ptrs == [] assert symbol_row_vals == [] assert sparse_list == sp.Matrix(0, 0, []) assert symbol_list == [] assert str(sparse_matrix) == 'Matrix(0, 0, [])' def test_csc_matrix_vector(): """Test sparse CSC matrix creation from matrix slice""" matrix = sp.Matrix([[1, 0], [2, 3]]) symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, sparse_matrix \ = amici.ode_export.csc_matrix( matrix[:, 0], colnames=[sp.Symbol('b')], rownames=[sp.Symbol('a1'), sp.Symbol('a2')] ) assert symbol_col_ptrs == [0, 2] assert symbol_row_vals == [0, 1] assert sparse_list == sp.Matrix([[1], [2]]) assert symbol_list == ['da1_db', 'da2_db'] assert str(sparse_matrix) == 'Matrix([[da1_db], [da2_db]])' # Test continuation of numbering of symbols symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, sparse_matrix \ = amici.ode_export.csc_matrix( matrix[:, 1], colnames=[sp.Symbol('b')], rownames=[sp.Symbol('a1'), sp.Symbol('a2')], identifier=1 ) assert symbol_col_ptrs == [0, 1] assert symbol_row_vals == [1] assert sparse_list == sp.Matrix([[3]]) assert symbol_list == ['da2_db_1'] assert str(sparse_matrix) == 'Matrix([[0], [da2_db_1]])'
AMICI-developer/AMICI
python/tests/test_ode_export.py
Python
bsd-2-clause
2,256
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>qLibc: Globals</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">qLibc </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li class="current"><a href="globals.html"><span>Globals</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li class="current"><a href="globals.html"><span>All</span></a></li> <li><a href="globals_func.html"><span>Functions</span></a></li> <li><a href="globals_defs.html"><span>Macros</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="globals.html#index__"><span>_</span></a></li> <li class="current"><a href="globals_a.html#index_a"><span>a</span></a></li> <li><a href="globals_b.html#index_b"><span>b</span></a></li> <li><a href="globals_c.html#index_c"><span>c</span></a></li> <li><a href="globals_d.html#index_d"><span>d</span></a></li> <li><a href="globals_e.html#index_e"><span>e</span></a></li> <li><a href="globals_f.html#index_f"><span>f</span></a></li> <li><a href="globals_g.html#index_g"><span>g</span></a></li> <li><a href="globals_h.html#index_h"><span>h</span></a></li> <li><a href="globals_o.html#index_o"><span>o</span></a></li> <li><a href="globals_p.html#index_p"><span>p</span></a></li> <li><a href="globals_q.html#index_q"><span>q</span></a></li> <li><a href="globals_r.html#index_r"><span>r</span></a></li> <li><a href="globals_s.html#index_s"><span>s</span></a></li> <li><a href="globals_w.html#index_w"><span>w</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('globals_a.html','');}); </script> <div id="doc-content"> <div class="contents"> <div class="textblock">Here is a list of all documented functions, variables, defines, enums, and typedefs with links to the documentation:</div> <h3><a class="anchor" id="index_a"></a>- a -</h3><ul> <li>addoptions() : <a class="el" href="qaconf_8c.html#a4b7d9693f31e326b134f03f8ee4bca09">qaconf.c</a> </li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.6 </li> </ul> </div> </body> </html>
kirbyfan64/qlibc
doc/html/globals_a.html
HTML
bsd-2-clause
4,223
<?php /* vim: set expandtab tabstop=4 shiftwidth=4: */ /** * PHP version 5.3 * * Copyright (c) 2011-2012 KUBO Atsuhiro <[email protected]>, * 2011 Shigenobu Nishikawa <[email protected]>, * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package Stagehand_TestRunner * @copyright 2011-2012 KUBO Atsuhiro <[email protected]> * @copyright 2011 Shigenobu Nishikawa <[email protected]> * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version Release: @package_version@ * @since File available since Release 2.18.0 */ namespace Stagehand\TestRunner\Notification; use Stagehand\TestRunner\Util\LegacyProxy; use Stagehand\TestRunner\Util\OS; Notifier::$ICON_PASSED = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'icons' . DIRECTORY_SEPARATOR . 'passed.png'; Notifier::$ICON_FAILED = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'icons' . DIRECTORY_SEPARATOR . 'failed.png'; Notifier::$ICON_STOPPED = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'icons' . DIRECTORY_SEPARATOR . 'stopped.png'; /** * @package Stagehand_TestRunner * @copyright 2011-2012 KUBO Atsuhiro <[email protected]> * @copyright 2011 Shigenobu Nishikawa <[email protected]> * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version Release: @package_version@ * @since Class available since Release 2.18.0 */ class Notifier { const TITLE_PASSED = 'Test Passed'; const TITLE_FAILED = 'Test Failed'; const TITLE_STOPPED = 'Test Stopped'; public static $ICON_PASSED; public static $ICON_FAILED; public static $ICON_STOPPED; /** * @var \Stagehand\TestRunner\Util\LegacyProxy * @since Property available since Release 3.0.0 */ protected $legacyProxy; /** * @var \Stagehand\TestRunner\Util\OS * @since Property available since Release 3.0.1 */ protected $os; /** * @param \Stagehand\TestRunner\Util\OS $os * @since Method available since Release 3.0.1 */ public function setOS(OS $os) { $this->os = $os; } /** * @param \Stagehand\TestRunner\Notification\Notification $notification */ public function notifyResult(Notification $notification) { $this->executeNotifyCommand($this->buildNotifyCommand($notification)); } /** * @param \Stagehand\TestRunner\Util\LegacyProxy $legacyProxy * @since Method available since Release 3.0.0 */ public function setLegacyProxy(LegacyProxy $legacyProxy) { $this->legacyProxy = $legacyProxy; } /** * @param \Stagehand\TestRunner\Notification\Notification $notification * @return string */ protected function buildNotifyCommand(Notification $notification) { if ($notification->isPassed()) { $title = self::TITLE_PASSED; $icon = self::$ICON_PASSED; } elseif ($notification->isFailed()) { $title = self::TITLE_FAILED; $icon = self::$ICON_FAILED; } elseif ($notification->isStopped()) { $title = self::TITLE_STOPPED; $icon = self::$ICON_STOPPED; } if ($this->os->isWin()) { return sprintf( 'growlnotify /t:%s /p:-2 /i:%s /a:Stagehand_TestRunner /r:%s,%s,%s /n:%s /silent:true %s', escapeshellarg($title), escapeshellarg($icon), escapeshellarg(self::TITLE_PASSED), escapeshellarg(self::TITLE_FAILED), escapeshellarg(self::TITLE_STOPPED), escapeshellarg($title), escapeshellarg($notification->getMessage()) ); } elseif ($this->os->isDarwin()) { return sprintf( 'growlnotify --name %s --priority -2 --image %s --title %s --message %s', escapeshellarg($title), escapeshellarg($icon), escapeshellarg($title), escapeshellarg($notification->getMessage()) ); } elseif ($this->os->isLinux()) { return sprintf( 'notify-send --urgency=low --icon=%s %s %s', escapeshellarg($icon), escapeshellarg($title), escapeshellarg(str_replace('\\', '\\\\', $notification->getMessage())) ); } } /** * @param string $command */ protected function executeNotifyCommand($command) { if (strlen($command) > 0) { $exitStatus = null; $this->legacyProxy->system($command, $exitStatus); } } } /* * Local Variables: * mode: php * coding: iso-8859-1 * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * indent-tabs-mode: nil * End: */
iteman/stagehand-testrunner
src/Stagehand/TestRunner/Notification/Notifier.php
PHP
bsd-2-clause
6,268
/* * types.h * * Written by: Ullrich Hafner * * This file is part of FIASCO («F»ractal «I»mage «A»nd «S»equence «CO»dec) * Copyright (C) 1994-2000 Ullrich Hafner <[email protected]> */ /* * $Date: 2000/06/14 20:49:37 $ * $Author: hafner $ * $Revision: 5.1 $ * $State: Exp $ */ #ifndef _FIASCO_TYPES_H #define _FIASCO_TYPES_H #undef FALSE #undef NO #undef TRUE #undef YES enum fiasco_boolean { NO = 0, FALSE = 0, YES = 1, TRUE = 1}; typedef float real_t; typedef enum fiasco_boolean bool_t; typedef unsigned char byte_t; typedef short word_t; typedef unsigned short u_word_t; typedef struct pair { word_t key; word_t value; } pair_t; #endif
ownclo/jpeg-on-steroids
vendor/C/netpbm/converter/other/fiasco/lib/types.h
C
bsd-3-clause
726
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from json import loads from mock import MagicMock from oauthlib.common import urlencode from oauthlib.oauth2 import RequestValidator, RevocationEndpoint from ....unittest import TestCase class RevocationEndpointTest(TestCase): def setUp(self): self.validator = MagicMock(wraps=RequestValidator()) self.validator.authenticate_client.return_value = True self.validator.revoke_token.return_value = True self.endpoint = RevocationEndpoint(self.validator) self.uri = 'https://example.com/revoke_token' self.headers = { 'Content-Type': 'application/x-www-form-urlencoded', } def test_revoke_token(self): for token_type in ('access_token', 'refresh_token', 'invalid'): body = urlencode([('token', 'foo'), ('token_type_hint', token_type)]) h, b, s = self.endpoint.create_revocation_response(self.uri, headers=self.headers, body=body) self.assertEqual(h, {}) self.assertEqual(b, None) self.assertEqual(s, 200) def test_revoke_with_callback(self): callback = 'package.hello_world' for token_type in ('access_token', 'refresh_token', 'invalid'): body = urlencode([('token', 'foo'), ('token_type_hint', token_type), ('callback', callback)]) h, b, s = self.endpoint.create_revocation_response(self.uri, headers=self.headers, body=body) self.assertEqual(h, {}) self.assertEqual(b, callback + '()') self.assertEqual(s, 200) def test_revoke_unsupported_token(self): endpoint = RevocationEndpoint(self.validator, supported_token_types=['access_token']) body = urlencode([('token', 'foo'), ('token_type_hint', 'refresh_token')]) h, b, s = endpoint.create_revocation_response(self.uri, headers=self.headers, body=body) self.assertEqual(h, {}) self.assertEqual(loads(b)['error'], 'unsupported_token_type') self.assertEqual(s, 400) h, b, s = endpoint.create_revocation_response(self.uri, headers=self.headers, body='') self.assertEqual(h, {}) self.assertEqual(loads(b)['error'], 'invalid_request') self.assertEqual(s, 400)
masci/oauthlib
tests/oauth2/rfc6749/endpoints/test_revocation_endpoint.py
Python
bsd-3-clause
2,530
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model backend\models\Profile */ $this->title = 'Update Profile: ' . ' ' . $model->id; $this->params['breadcrumbs'][] = ['label' => 'Profiles', 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]]; $this->params['breadcrumbs'][] = 'Update'; ?> <div class="profile-update"> <h3><?= Html::encode($this->title) ?></h3> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
tolgayilmaz86/yii2-template
backend/views/profile/update.php
PHP
bsd-3-clause
533
/* Copyright (c) 2014, pGina Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the pGina Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pGina.Plugin.DriveMapper { public partial class ConfigurationUi : Form { private string[] m_driveOptions; private string[] m_credsOptions; private BindingList<DriveMap> m_maps; public ConfigurationUi() { InitializeComponent(); InitUi(); LoadSettings(); } private void InitUi() { m_driveOptions = new string[] { "E:", "F:", "G:", "H:", "I:", "J:", "K:", "L:", "M:", "N:", "O:", "P:", "Q:", "R:", "S:", "T:", "U:", "V:", "W:", "X:", "Y:", "Z:" }; m_driveLetterCb.Items.AddRange(m_driveOptions); m_driveLetterCb.SelectedIndex = 0; m_credsOptions = new string[] { DriveMap.CredentialOption.Original.ToString(), DriveMap.CredentialOption.Final.ToString(), DriveMap.CredentialOption.Custom.ToString() }; m_credsCb.Items.AddRange(m_credsOptions); m_credsCb.SelectedIndex = 1; DisableAndClearAllEditFields(); m_mapListDgv.Columns.Add(new DataGridViewTextBoxColumn() { Name = "Drive", DataPropertyName = "Drive", HeaderText = "Drive", AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells, ReadOnly = true }); m_mapListDgv.Columns.Add(new DataGridViewTextBoxColumn() { Name = "UNC", DataPropertyName = "UncPath", HeaderText = "UNC Path", AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, ReadOnly = true }); m_mapListDgv.Columns.Add(new DataGridViewTextBoxColumn() { Name = "Creds", DataPropertyName = "Credentials", HeaderText = "Credentials", AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells, ReadOnly = true }); m_mapListDgv.Columns.Add(new DataGridViewTextBoxColumn() { Name = "Group", DataPropertyName = "Group", HeaderText = "Group", AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells, ReadOnly = true }); m_mapListDgv.Columns.Add(new DataGridViewTextBoxColumn() { DataPropertyName = "Username", Visible = false }); m_mapListDgv.Columns.Add(new DataGridViewTextBoxColumn() { DataPropertyName = "Password", Visible = false }); m_mapListDgv.SelectionChanged += m_mapListDgv_SelectionChanged; m_uncPathTb.LostFocus += m_uncPathTb_LostFocus; m_passwordTb.LostFocus += m_passwordTb_LostFocus; m_usernameTb.LostFocus += m_usernameTb_LostFocus; m_groupTb.LostFocus += m_groupTb_LostFocus; } void m_groupTb_LostFocus(object sender, EventArgs e) { if (m_mapListDgv.SelectedRows.Count > 0) { DataGridViewRow row = m_mapListDgv.SelectedRows[0]; int idx = row.Index; DriveMap map = (DriveMap)row.DataBoundItem; map.Group = m_groupTb.Text; m_maps.ResetItem(idx); } } void m_usernameTb_LostFocus(object sender, EventArgs e) { if (m_mapListDgv.SelectedRows.Count > 0) { DataGridViewRow row = m_mapListDgv.SelectedRows[0]; int idx = row.Index; DriveMap map = (DriveMap)row.DataBoundItem; map.Username = m_usernameTb.Text; m_maps.ResetItem(idx); } } void m_passwordTb_LostFocus(object sender, EventArgs e) { if (m_mapListDgv.SelectedRows.Count > 0) { DataGridViewRow row = m_mapListDgv.SelectedRows[0]; int idx = row.Index; DriveMap map = (DriveMap)row.DataBoundItem; map.Password = m_passwordTb.Text; m_maps.ResetItem(idx); } } void m_uncPathTb_LostFocus(object sender, EventArgs e) { if (m_mapListDgv.SelectedRows.Count > 0) { DataGridViewRow row = m_mapListDgv.SelectedRows[0]; int idx = row.Index; DriveMap map = (DriveMap)row.DataBoundItem; map.UncPath = m_uncPathTb.Text; m_maps.ResetItem(idx); } } void m_mapListDgv_SelectionChanged(object sender, EventArgs e) { int numRowsSelected = m_mapListDgv.SelectedRows.Count; if( numRowsSelected == 0 ) DisableAndClearAllEditFields(); else { DataGridViewRow row = m_mapListDgv.SelectedRows[0]; DriveMap map = (DriveMap)row.DataBoundItem; SetEditFields(map); EnableEditFields(); if( map.Credentials == DriveMap.CredentialOption.Custom) { EnableCredentialsFields(); } } } private void EnableEditFields() { m_credsCb.Enabled = true; m_driveLetterCb.Enabled = true; m_groupTb.Enabled = true; m_uncPathTb.Enabled = true; } private void EnableCredentialsFields() { m_usernameTb.Enabled = true; m_passwordTb.Enabled = true; m_showPasswordCb.Enabled = true; } private void SetEditFields(DriveMap map) { m_driveLetterCb.SelectedItem = map.Drive; m_uncPathTb.Text = map.UncPath; m_credsCb.SelectedItem = map.Credentials.ToString(); m_usernameTb.Text = map.Username; m_passwordTb.Text = map.Password; m_groupTb.Text = map.Group; } private void DisableAndClearAllEditFields() { m_credsCb.Enabled = false; m_driveLetterCb.Enabled = false; m_groupTb.Enabled = false; m_uncPathTb.Enabled = false; m_uncPathTb.Text = ""; DisableAndClearCredentialsFields(); } private void DisableAndClearCredentialsFields() { m_usernameTb.Enabled = false; m_usernameTb.Text = ""; m_passwordTb.Enabled = false; m_passwordTb.Text = ""; m_showPasswordCb.Enabled = false; } private void LoadSettings() { List<DriveMap> maps = Settings.GetMaps(); m_maps = new BindingList<DriveMap>(maps); m_mapListDgv.DataSource = m_maps; } private void textBox4_TextChanged(object sender, EventArgs e) { } private void m_showPasswordCb_CheckedChanged(object sender, EventArgs e) { m_passwordTb.UseSystemPasswordChar = !m_showPasswordCb.Checked; } private void newMapButton_Click(object sender, EventArgs e) { DriveMap map = new DriveMap(); map.Drive = m_driveOptions[0]; map.Credentials = DriveMap.CredentialOption.Final; // Choose a drive letter that's available HashSet<string> usedLetters = new HashSet<string>(); foreach (DriveMap m in m_maps) { usedLetters.Add(m.Drive); } for (int i = 0; i < m_driveOptions.Length; i++) { if(!usedLetters.Contains(m_driveOptions[i])) { map.Drive = m_driveOptions[i]; break; } } m_maps.Add(map); m_mapListDgv.Rows[m_mapListDgv.Rows.Count - 1].Selected = true; } private void m_deleteMapButton_Click(object sender, EventArgs e) { int numRowsSelected = m_mapListDgv.SelectedRows.Count; if (numRowsSelected > 0) { m_maps.RemoveAt(m_mapListDgv.SelectedRows[0].Index); } } private void m_driveLetterCb_SelectedIndexChanged(object sender, EventArgs e) { if(m_mapListDgv.SelectedRows.Count > 0) { DataGridViewRow row = m_mapListDgv.SelectedRows[0]; int idx = row.Index; DriveMap map = (DriveMap)row.DataBoundItem; map.Drive = m_driveLetterCb.SelectedItem.ToString(); m_maps.ResetItem(idx); } } private void m_credsCb_SelectedIndexChanged(object sender, EventArgs e) { if (m_mapListDgv.SelectedRows.Count > 0) { DataGridViewRow row = m_mapListDgv.SelectedRows[0]; int idx = row.Index; DriveMap map = (DriveMap)row.DataBoundItem; map.Credentials = (DriveMap.CredentialOption)Enum.Parse(typeof(DriveMap.CredentialOption), m_credsCb.SelectedItem.ToString()); m_maps.ResetItem(idx); if (map.Credentials == DriveMap.CredentialOption.Custom) EnableCredentialsFields(); else DisableAndClearCredentialsFields(); } } private void m_saveCloseButton_Click(object sender, EventArgs e) { List<DriveMap> maps = m_maps.ToList<DriveMap>(); Settings.SaveMaps(maps); this.Close(); } private void m_cancelButton_Click(object sender, EventArgs e) { this.Close(); } } }
stefanwerfling/pgina
Plugins/Core/DriveMapper/ConfigurationUi.cs
C#
bsd-3-clause
11,624
/** * Declarative subset of JavaScript with a few extras beyond JSON, including * dates, non-finite numbers, etc. * Derived from and uses: http://www.JSON.org/json2.js 2008-11-19 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. */ if(typeof JSON === "undefined"){ require("json"); } var nativeJson = !!JSON.parse.toString().match(/native code/); exports.parse = function (text) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(value) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k; if (value && typeof value === 'object') { for (k in value) { var v = value[k]; if (typeof v === 'string') { var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(v); if (a) { value[k] = new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } else if (typeof v === 'object') { walk(v); } } } } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. var backSlashRemoved = text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'); if (/^[\],:{}\s]*$/. test(backSlashRemoved. replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // it is pure JSON if(nativeJson){ // use the native parser if available j = JSON.parse(text); } else{ // revert to eval j = eval('(' + text + ')'); } walk(j); return j; } else if (/^[\],:{}\s]*$/. test(backSlashRemoved. replace(/"[^"\\\n\r]*"|'[^'\\\n\r]*'|\(?new +Date\([0-9]*\)+|[\w$]+\s*:(?:\s*\[)*|true|false|null|undefined|-?Infinity|NaN|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,|&&)(?:\s*\[)+/g, ''))) { // not pure JSON, but safe declarative JavaScript j = eval('(' + text + ')'); walk(j); return j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; var nativeConstructors = {"String":String, "Object":Object, "Number":Number, "Boolean":Boolean, "Array":Array, "Date":Date}; exports.stringify = ({}).toSource ? // we will use toSource if it is available (function(){ Object.keys(nativeConstructors).forEach(function(name){ global[name].toSource = function(){ return name; }; }); return function(value){ if(value && typeof value == "object" || typeof value == "function"){ var source = value.toSource(); if(source.charAt(0) == "("){ // remove the surrounding paranthesis that are produced source = source.substring(1, source.length - 1); } return source; } if(typeof value === "number" && !isFinite(value)){ return value.toString(); } if(typeof value === "undefined"){ return "undefined"; } return JSON.stringify(value); }; })() : (function(){ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'function': if(nativeConstructors[value.name] === value){ return value.name; } value = value.toString(); case 'string': return quote(value); case 'number': case 'boolean': case 'undefined': case 'null': return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (value instanceof Date){ return "new Date(" + value.getTime() + ")"; } for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); partial.push(quote(k) + (gap ? ': ' : ':') + v); } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. return function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; })();
nko/the-node-kushes
lib/commonjs-utils/lib/json-ext.js
JavaScript
bsd-3-clause
10,016
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This command-line program converts an effective-TLD data file in UTF-8 from // the format provided by Mozilla to the format expected by Chrome. Any errors // or warnings are recorded in tld_cleanup.log. // // In particular, it // * Strips blank lines and comments, as well as notes for individual rules. // * Changes all line endings to LF. // * Strips a single leading and/or trailing dot from each rule, if present. // * Logs a warning if a rule contains '!' or '*.' other than at the beginning // of the rule. (This also catches multiple ! or *. at the start of a rule.) // * Logs a warning if GURL reports a rule as invalid, but keeps the rule. // * Canonicalizes each rule's domain by converting it to a GURL and back. // * Adds explicit rules for true TLDs found in any rule. #include <set> #include <string> #include "base/at_exit.h" #include "base/file_util.h" #include "base/icu_util.h" #include "base/logging.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/string_util.h" #include "googleurl/src/gurl.h" #include "googleurl/src/url_parse.h" typedef std::set<std::string> StringSet; // Writes the list of domain rules contained in the 'rules' set to the // 'outfile', with each rule terminated by a LF. The file must already have // been created with write access. bool WriteRules(const StringSet& rules, FilePath outfile) { std::string data; data.append( "// Copyright (c) 2009 The Chromium Authors. All rights reserved.\n" "// Use of this source code is governed by a BSD-style license that\n" "// can be found in the LICENSE file.\n\n" "// This file is generated by net/tools/tld_cleanup/.\n" "// DO NOT MANUALLY EDIT!\n" "#include \"net/base/registry_controlled_domain.h\"\n\n" "const char net::RegistryControlledDomainService::kDomainData[] =\n" ); for (StringSet::const_iterator iter = rules.begin(); iter != rules.end(); ++iter) { data.append(" \""); data.append(*iter); data.append("\\n\"\n"); } data.append(";\n"); int written = file_util::WriteFile(outfile.ToWStringHack(), data.data(), data.size()); return written == static_cast<int>(data.size()); } // These result codes should be in increasing order of severity. typedef enum { kSuccess, kWarning, kError, } NormalizeResult; // Adjusts the rule to a standard form: removes single extraneous dots and // canonicalizes it using GURL. Returns kSuccess if the rule is interpreted as // valid; logs a warning and returns kWarning if it is probably invalid; and // logs an error and returns kError if the rule is (almost) certainly invalid. NormalizeResult NormalizeRule(std::string* rule) { NormalizeResult result = kSuccess; // Strip single leading and trailing dots. if (rule->at(0) == '.') rule->erase(0, 1); if (rule->size() == 0) { LOG(WARNING) << "Ignoring empty rule"; return kWarning; } if (rule->at(rule->size() - 1) == '.') rule->erase(rule->size() - 1, 1); if (rule->size() == 0) { LOG(WARNING) << "Ignoring empty rule"; return kWarning; } // Allow single leading '*.' or '!', saved here so it's not canonicalized. bool wildcard = false; bool exception = false; size_t start_offset = 0; if (rule->at(0) == '!') { rule->erase(0, 1); exception = true; } else if (rule->find("*.") == 0) { rule->erase(0, 2); wildcard = true; } if (rule->size() == 0) { LOG(WARNING) << "Ignoring empty rule"; return kWarning; } // Warn about additional '*.' or '!'. if (rule->find("*.", start_offset) != std::string::npos || rule->find('!', start_offset) != std::string::npos) { LOG(WARNING) << "Keeping probably invalid rule: " << *rule; result = kWarning; } // Make a GURL and normalize it, then get the host back out. std::string url = "http://"; url.append(*rule); GURL gurl(url); const std::string& spec = gurl.possibly_invalid_spec(); url_parse::Component host = gurl.parsed_for_possibly_invalid_spec().host; if (host.len < 0) { LOG(ERROR) << "Ignoring rule that couldn't be normalized: " << *rule; return kError; } if (!gurl.is_valid()) { LOG(WARNING) << "Keeping rule that GURL says is invalid: " << *rule; result = kWarning; } rule->assign(spec.substr(host.begin, host.len)); // Restore wildcard or exception marker. if (exception) rule->insert(0, 1, '!'); else if (wildcard) rule->insert(0, "*."); return result; } // Loads the file described by 'in_filename', converts it to the desired format // (see the file comments above), and saves it into 'out_filename'. Returns // the most severe of the result codes encountered when normalizing the rules. NormalizeResult NormalizeFile(const FilePath& in_filename, const FilePath& out_filename) { std::string data; if (!file_util::ReadFileToString(in_filename, &data)) { LOG(ERROR) << "Unable to read file"; // We return success since we've already reported the error. return kSuccess; } // We do a lot of string assignment during parsing, but simplicity is more // important than performance here. std::string rule; NormalizeResult result = kSuccess; size_t line_start = 0; size_t line_end = 0; StringSet rules; while (line_start < data.size()) { // Skip comments. if (line_start + 1 < data.size() && data[line_start] == '/' && data[line_start + 1] == '/') { line_end = data.find_first_of("\r\n", line_start); if (line_end == std::string::npos) line_end = data.size(); } else { // Truncate at first whitespace. line_end = data.find_first_of("\r\n \t", line_start); if (line_end == std::string::npos) line_end = data.size(); rule.assign(data.data(), line_start, line_end - line_start); NormalizeResult new_result = NormalizeRule(&rule); if (new_result != kError) { rules.insert(rule); // Add true TLD for multi-level rules. size_t tld_start = rule.find_last_of('.'); if (tld_start != std::string::npos && tld_start + 1 < rule.size()) rules.insert(rule.substr(tld_start + 1)); } result = std::max(result, new_result); } // Find beginning of next non-empty line. line_start = data.find_first_of("\r\n", line_end); if (line_start == std::string::npos) line_start = data.size(); line_start = data.find_first_not_of("\r\n", line_start); if (line_start == std::string::npos) line_start = data.size(); } if (!WriteRules(rules, out_filename)) { LOG(ERROR) << "Error(s) writing output file"; result = kError; } return result; } int main(int argc, const char* argv[]) { base::EnableTerminationOnHeapCorruption(); if (argc != 1) { fprintf(stderr, "Normalizes and verifies UTF-8 TLD data files\n"); fprintf(stderr, "Usage: %s\n", argv[0]); return 1; } // Manages the destruction of singletons. base::AtExitManager exit_manager; // Only use OutputDebugString in debug mode. #ifdef NDEBUG logging::LoggingDestination destination = logging::LOG_ONLY_TO_FILE; #else logging::LoggingDestination destination = logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG; #endif CommandLine::Init(argc, argv); FilePath log_filename; PathService::Get(base::DIR_EXE, &log_filename); log_filename = log_filename.AppendASCII("tld_cleanup.log"); logging::InitLogging(log_filename.value().c_str(), destination, logging::LOCK_LOG_FILE, logging::DELETE_OLD_LOG_FILE); icu_util::Initialize(); FilePath input_file; PathService::Get(base::DIR_SOURCE_ROOT, &input_file); input_file = input_file.Append(FILE_PATH_LITERAL("net")) .Append(FILE_PATH_LITERAL("base")) .Append(FILE_PATH_LITERAL("effective_tld_names.dat")); FilePath output_file; PathService::Get(base::DIR_SOURCE_ROOT, &output_file); output_file = output_file.Append(FILE_PATH_LITERAL("net")) .Append(FILE_PATH_LITERAL("base")) .Append(FILE_PATH_LITERAL("effective_tld_names.cc")); NormalizeResult result = NormalizeFile(input_file, output_file); if (result != kSuccess) { fprintf(stderr, "Errors or warnings processing file. See log in tld_cleanup.log."); } if (result == kError) return 1; return 0; }
amyvmiwei/chromium
net/tools/tld_cleanup/tld_cleanup.cc
C++
bsd-3-clause
8,750
<?php /*========================================================================= Program: CDash - Cross-Platform Dashboard System Module: $Id$ Language: PHP Date: $Date$ Version: $Revision$ Copyright (c) 2002 Kitware, Inc. All rights reserved. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ require_once 'xml_handlers/abstract_handler.php'; require_once('models/build.php'); require_once('models/site.php'); require_once('models/buildupdate.php'); require_once('models/feed.php'); /** Write the updates in one block * In case of a lot of updates this might take up some memory */ class UpdateHandler extends AbstractHandler { private $StartTimeStamp; private $EndTimeStamp; private $Update; private $UpdateFile; /** Constructor */ public function __construct($projectID, $scheduleID) { parent::__construct($projectID, $scheduleID); $this->Build = new Build(); $this->Site = new Site(); $this->Feed = new Feed(); } /** Start element */ public function startElement($parser, $name, $attributes) { parent::startElement($parser, $name, $attributes); if($name=='UPDATE') { if(isset($attributes['GENERATOR'])) { $this->Build->Generator = $attributes['GENERATOR']; } $this->Update = new BuildUpdate(); } else if($name=='UPDATED' || $name=='CONFLICTING' || $name=='MODIFIED') { $this->UpdateFile = new BuildUpdateFile(); $this->UpdateFile->Status = $name; } else if($name=='UPDATERETURNSTATUS') { $this->Update->Status = ''; } } /** End element */ public function endElement($parser, $name) { parent::endElement($parser, $name); if($name=='SITE') { $this->Site->Insert(); } else if($name == 'UPDATE') { $this->Build->SiteId = $this->Site->Id; $start_time = gmdate(FMT_DATETIME, $this->StartTimeStamp); $end_time = gmdate(FMT_DATETIME, $this->EndTimeStamp); $submit_time = gmdate(FMT_DATETIME); $this->Build->ProjectId = $this->projectid; $buildid = $this->Build->GetIdFromName($this->SubProjectName); // If the build doesn't exist we add it if($buildid==0) { $this->Build->ProjectId = $this->projectid; $this->Build->StartTime = $start_time; $this->Build->EndTime = $end_time; $this->Build->SubmitTime = $submit_time; $this->Build->InsertErrors = false; add_build($this->Build, $this->scheduleid); $buildid = $this->Build->Id; } else { $this->Build->Id = $buildid; $this->Build->ProjectId = $this->projectid; $this->Build->StartTime = $start_time; $this->Build->EndTime = $end_time; $this->Build->SubmitTime = $submit_time; } $GLOBALS['PHP_ERROR_BUILD_ID'] = $buildid; $this->Update->BuildId = $buildid; $this->Update->StartTime = $start_time; $this->Update->EndTime = $end_time; // Insert the update $this->Update->Insert(); global $CDASH_ENABLE_FEED; if ($CDASH_ENABLE_FEED) { // We need to work the magic here to have a good description $this->Feed->InsertUpdate($this->projectid,$buildid); } // Compute the update statistics $this->Build->ComputeUpdateStatistics(); } else if($name=='UPDATED' || $name=='CONFLICTING' || $name=='MODIFIED') { $this->Update->AddFile($this->UpdateFile); unset($this->UpdateFile); } } // end function endElement /** Text */ public function text($parser, $data) { $parent = $this->getParent(); $element = $this->getElement(); if($parent == 'UPDATE') { switch ($element) { case 'BUILDNAME': $this->Build->Name = $data; if(empty($this->Build->Name)) { $this->Build->Name = "(empty)"; } break; case 'BUILDSTAMP': $this->Build->SetStamp($data); break; case 'SITE': $this->Site->Name = $data; if(empty($this->Site->Name)) { $this->Site->Name = "(empty)"; } break; case 'STARTTIME': $this->StartTimeStamp = $data; break; case 'STARTDATETIME': $this->StartTimeStamp = str_to_time($data, $this->getBuildStamp()); break; case 'ENDTIME': $this->EndTimeStamp = $data; break; case 'ENDDATETIME': $this->EndTimeStamp = str_to_time($data, $this->getBuildStamp()); break; case 'UPDATECOMMAND': $this->Update->Command .= $data; break; case 'UPDATETYPE': $this->Update->Type = $data; break; case 'REVISION': $this->Update->Revision = $data; break; case 'PRIORREVISION': $this->Update->PriorRevision = $data; break; case 'PATH': $this->Update->Path = $data; break; case 'UPDATERETURNSTATUS': $this->Update->Status .= $data; break; } } else if($parent != 'REVISIONS' && $element=='FULLNAME') { $this->UpdateFile->Filename = $data; } else if($parent != 'REVISIONS' && $element=='CHECKINDATE') { $this->UpdateFile->CheckinDate = $data; } else if($parent != 'REVISIONS' && $element=='AUTHOR') { $this->UpdateFile->Author .= $data; } else if($parent != 'REVISIONS' && $element=='EMAIL') { $this->UpdateFile->Email .= $data; } else if($parent != 'REVISIONS' && $element=='COMMITTER') { $this->UpdateFile->Committer .= $data; } else if($parent != 'REVISIONS' && $element=='COMMITTEREMAIL') { $this->UpdateFile->CommitterEmail .= $data; } else if($parent != 'REVISIONS' && $element=='LOG') { $this->UpdateFile->Log .= $data; } else if($parent != 'REVISIONS' && $element=='REVISION') { if($data=='Unknown') { $data = -1; } $this->UpdateFile->Revision = $data; } else if($parent != 'REVISIONS' && $element=='PRIORREVISION') { if($data=='Unknown') { $data = -1; } $this->UpdateFile->PriorRevision = $data; } } } ?>
cpatrick/CDash
xml_handlers/update_handler.php
PHP
bsd-3-clause
6,740
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE401_Memory_Leak__new_array_TwoIntsClass_73b.cpp Label Definition File: CWE401_Memory_Leak__new_array.label.xml Template File: sources-sinks-73b.tmpl.cpp */ /* * @description * CWE: 401 Memory Leak * BadSource: Allocate data using new[] * GoodSource: Point data to a stack buffer * Sinks: * GoodSink: call delete[] on data * BadSink : no deallocation of data * Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files * * */ #include "std_testcase.h" #include <list> #ifndef _WIN32 #include <wchar.h> #endif using namespace std; namespace CWE401_Memory_Leak__new_array_TwoIntsClass_73 { #ifndef OMITBAD void badSink(list<TwoIntsClass *> dataList) { /* copy data out of dataList */ TwoIntsClass * data = dataList.back(); /* POTENTIAL FLAW: No deallocation */ ; /* empty statement needed for some flow variants */ } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(list<TwoIntsClass *> dataList) { TwoIntsClass * data = dataList.back(); /* POTENTIAL FLAW: No deallocation */ ; /* empty statement needed for some flow variants */ } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(list<TwoIntsClass *> dataList) { TwoIntsClass * data = dataList.back(); /* FIX: Deallocate memory */ delete[] data; } #endif /* OMITGOOD */ } /* close namespace */
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE401_Memory_Leak/s02/CWE401_Memory_Leak__new_array_TwoIntsClass_73b.cpp
C++
bsd-3-clause
1,545
/*========================================================================= Program: Visualization Toolkit Module: vtkRAdapter.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2009 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ // .NAME vtkRAdapter - This is a utility class to convert VTK array data and // VTK tables to and from Gnu R S expression (SEXP) data structures. It is used // with the R .Call interface and the embedded R interpreter. // // .SECTION Description // // This class creates deep copies of input data. Created R SEXP variables created // by these functions can be freed by the R garbage collector by calling UNPROTECT(1). // The conversions are performed for double and integer data types. // // VTK data structures created by this class from R types are stored in array collections // and freed when the class destructor is called. Use the Register() method on a returned // object to increase its reference count by one, in order keep the object around after this // classes destructor has been called. The code calling Register() must eventually call Delete() // on the object to free memory. // // .SECTION See Also // vtkRinterface vtkRcalculatorFilter // // .SECTION Thanks // Developed by Thomas Otahal at Sandia National Laboratories. // #ifndef vtkRAdapter_h #define vtkRAdapter_h #include "vtkFiltersStatisticsGnuRModule.h" // For export macro #include "vtkObject.h" #ifndef VTK_BUILDING_FILTERS_STATISTICSGNUR #define R_NO_REMAP /* Don't pollute the namespace (some of which conflict). DO NOT REMOVE. */ #endif #include "Rinternals.h" // Needed for Rinternals.h SEXP data structure class vtkInformation; class vtkInformationVector; class vtkDataArray; class vtkArray; class vtkTable; class vtkTree; class vtkDataArrayCollection; class vtkArrayData; class vtkDataObjectCollection; class VTKFILTERSSTATISTICSGNUR_EXPORT vtkRAdapter : public vtkObject { public: vtkTypeMacro(vtkRAdapter, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); static vtkRAdapter *New(); // Description: // Create a vtkDataArray copy of GNU R input matrix vaiable (deep copy, allocates memory) // Input is a R matrix or vector of doubles or integers vtkDataArray* RToVTKDataArray(SEXP variable); // Description: // Create a vtkArray copy of the GNU R input variable multi-dimensional array (deep copy, allocates memory) // Input is a R multi-dimensional array of doubles or integers vtkArray* RToVTKArray(SEXP variable); // Description: // Create a GNU R matrix copy of the input vtkDataArray da (deep copy, allocates memory) SEXP VTKDataArrayToR(vtkDataArray* da); // Description: // Create a GNU R multi-dimensional array copy of the input vtkArray da (deep copy, allocates memory) SEXP VTKArrayToR(vtkArray* da); // Description: // Create a GNU R matrix copy of the input vtkTable table (deep copy, allocates memory) SEXP VTKTableToR(vtkTable* table); // Description: // Create a vtkTable copy of the GNU R input matrix variable (deep copy, allocates memory) // Input is R list of equal length vectors or a matrix. vtkTable* RToVTKTable(SEXP variable); // Description: // Create a GNU R phylo tree copy of the input vtkTree tree (deep copy, allocates memory) SEXP VTKTreeToR(vtkTree* tree); // Description: // Create a vtkTree copy of the GNU R input phylo tree variable (deep copy, allocates memory) vtkTree* RToVTKTree(SEXP variable); protected: vtkRAdapter(); ~vtkRAdapter(); private: vtkRAdapter(const vtkRAdapter&) VTK_DELETE_FUNCTION; void operator=(const vtkRAdapter&) VTK_DELETE_FUNCTION; vtkDataArrayCollection* vdac; // Collection of vtkDataArrays that have been converted from R. vtkArrayData* vad; // Collection of vtkArrays that have been converted from R. vtkDataObjectCollection* vdoc; // Collection of vtkTables that have been converted from R. }; #endif
keithroe/vtkoptix
Filters/StatisticsGnuR/vtkRAdapter.h
C
bsd-3-clause
4,591
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_SDK_META_AS_HPP_INCLUDED #define NT2_SDK_META_AS_HPP_INCLUDED #include <nt2/sdk/meta/factory_of.hpp> #include <nt2/sdk/meta/primitive_of.hpp> #include <boost/dispatch/meta/as.hpp> namespace nt2 { namespace ext { using boost::dispatch::meta::target_; } } namespace nt2 { namespace meta { using boost::dispatch::meta::as_; using boost::dispatch::meta::target_value; } } #endif
hainm/pythran
third_party/nt2/sdk/meta/as.hpp
C++
bsd-3-clause
906
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_BASE_IME_INPUT_METHOD_WIN_H_ #define UI_BASE_IME_INPUT_METHOD_WIN_H_ #include <windows.h> #include <string> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "ui/base/ime/input_method_base.h" #include "ui/base/win/ime_input.h" namespace ui { // An InputMethod implementation based on Windows IMM32 API. class UI_EXPORT InputMethodWin : public InputMethodBase { public: explicit InputMethodWin(internal::InputMethodDelegate* delegate, HWND hwnd); virtual ~InputMethodWin(); // Overridden from InputMethod: virtual void Init(bool focused) OVERRIDE; virtual void OnFocus() OVERRIDE; virtual void OnBlur() OVERRIDE; virtual bool DispatchKeyEvent( const base::NativeEvent& native_key_event) OVERRIDE; virtual bool DispatchFabricatedKeyEvent(const ui::KeyEvent& event) OVERRIDE; virtual void OnTextInputTypeChanged(const TextInputClient* client) OVERRIDE; virtual void OnCaretBoundsChanged(const TextInputClient* client) OVERRIDE; virtual void CancelComposition(const TextInputClient* client) OVERRIDE; virtual std::string GetInputLocale() OVERRIDE; virtual base::i18n::TextDirection GetInputTextDirection() OVERRIDE; virtual bool IsActive() OVERRIDE; virtual void SetFocusedTextInputClient(TextInputClient* client) OVERRIDE; virtual TextInputClient* GetTextInputClient() const OVERRIDE; // Handles IME messages. LRESULT OnImeMessages(UINT message, WPARAM wparam, LPARAM lparam, BOOL* handled); // Message handlers. The native widget is responsible for forwarding following // messages to the input method. void OnInputLangChange(DWORD character_set, HKL input_language_id); protected: // Overridden from InputMethodBase: virtual void OnWillChangeFocusedClient(TextInputClient* focused_before, TextInputClient* focused) OVERRIDE; virtual void OnDidChangeFocusedClient(TextInputClient* focused_before, TextInputClient* focused) OVERRIDE; private: LRESULT OnImeSetContext(UINT message, WPARAM wparam, LPARAM lparam, BOOL* handled); LRESULT OnImeStartComposition(UINT message, WPARAM wparam, LPARAM lparam, BOOL* handled); LRESULT OnImeComposition(UINT message, WPARAM wparam, LPARAM lparam, BOOL* handled); LRESULT OnImeEndComposition(UINT message, WPARAM wparam, LPARAM lparam, BOOL* handled); LRESULT OnImeRequest(UINT message, WPARAM wparam, LPARAM lparam, BOOL* handled); // For both WM_CHAR and WM_SYSCHAR LRESULT OnChar(UINT message, WPARAM wparam, LPARAM lparam, BOOL* handled); // For both WM_DEADCHAR and WM_SYSDEADCHAR LRESULT OnDeadChar(UINT message, WPARAM wparam, LPARAM lparam, BOOL* handled); LRESULT OnDocumentFeed(RECONVERTSTRING *reconv); LRESULT OnReconvertString(RECONVERTSTRING *reconv); // Asks the client to confirm current composition text. void ConfirmCompositionText(); // Enables or disables the IME according to the current text input type. void UpdateIMEState(); // The HWND this InputMethod is bound to. HWND hwnd_; // Indicates if the current input locale has an IME. bool active_; // Name of the current input locale. std::string locale_; // The current input text direction. base::i18n::TextDirection direction_; // The new text direction and layout alignment requested by the user by // pressing ctrl-shift. It'll be sent to the text input client when the key // is released. base::i18n::TextDirection pending_requested_direction_; // Windows IMM32 wrapper. // (See "ui/base/win/ime_input.h" for its details.) ui::ImeInput ime_input_; bool enabled_; DISALLOW_COPY_AND_ASSIGN(InputMethodWin); }; } // namespace ui #endif // UI_BASE_IME_INPUT_METHOD_WIN_H_
JoKaWare/GViews
ui/base/ime/input_method_win.h
C
bsd-3-clause
4,399
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>PyQt4.QtGui.QAbstractItemView.CursorAction</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="QGIS-AIMS-Plugin-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> PyQt4 :: QtGui :: QAbstractItemView :: CursorAction :: Class&nbsp;CursorAction </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="PyQt4.QtGui.QAbstractItemView.CursorAction-class.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== CLASS DESCRIPTION ==================== --> <h1 class="epydoc">Class CursorAction</h1><p class="nomargin-top"></p> <pre class="base-tree"> object --+ | int --+ | <strong class="uidshort">QAbstractItemView.CursorAction</strong> </pre> <hr /> <!-- ==================== INSTANCE METHODS ==================== --> <a name="section-InstanceMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="PyQt4.QtGui.QAbstractItemView.CursorAction-class.html#__reduce__" class="summary-sig-name">__reduce__</a>(<span class="summary-sig-arg">...</span>)</span><br /> helper for pickle</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code>int</code></b>: <code>__abs__</code>, <code>__add__</code>, <code>__and__</code>, <code>__cmp__</code>, <code>__coerce__</code>, <code>__div__</code>, <code>__divmod__</code>, <code>__float__</code>, <code>__floordiv__</code>, <code>__format__</code>, <code>__getattribute__</code>, <code>__getnewargs__</code>, <code>__hash__</code>, <code>__hex__</code>, <code>__index__</code>, <code>__int__</code>, <code>__invert__</code>, <code>__long__</code>, <code>__lshift__</code>, <code>__mod__</code>, <code>__mul__</code>, <code>__neg__</code>, <code>__new__</code>, <code>__nonzero__</code>, <code>__oct__</code>, <code>__or__</code>, <code>__pos__</code>, <code>__pow__</code>, <code>__radd__</code>, <code>__rand__</code>, <code>__rdiv__</code>, <code>__rdivmod__</code>, <code>__repr__</code>, <code>__rfloordiv__</code>, <code>__rlshift__</code>, <code>__rmod__</code>, <code>__rmul__</code>, <code>__ror__</code>, <code>__rpow__</code>, <code>__rrshift__</code>, <code>__rshift__</code>, <code>__rsub__</code>, <code>__rtruediv__</code>, <code>__rxor__</code>, <code>__str__</code>, <code>__sub__</code>, <code>__truediv__</code>, <code>__trunc__</code>, <code>__xor__</code>, <code>bit_length</code>, <code>conjugate</code> </p> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__delattr__</code>, <code>__init__</code>, <code>__reduce_ex__</code>, <code>__setattr__</code>, <code>__sizeof__</code>, <code>__subclasshook__</code> </p> </td> </tr> </table> <!-- ==================== PROPERTIES ==================== --> <a name="section-Properties"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Properties</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Properties" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code>int</code></b>: <code>denominator</code>, <code>imag</code>, <code>numerator</code>, <code>real</code> </p> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__class__</code> </p> </td> </tr> </table> <!-- ==================== METHOD DETAILS ==================== --> <a name="section-MethodDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Method Details</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-MethodDetails" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> </table> <a name="__reduce__"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">__reduce__</span>(<span class="sig-arg">...</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>helper for pickle</p> <dl class="fields"> <dt>Overrides: object.__reduce__ <dd><em class="note">(inherited documentation)</em></dd> </dt> </dl> </td></tr></table> </div> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="QGIS-AIMS-Plugin-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Tue Jun 14 13:29:14 2016 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
SPlanzer/QGIS-AIMS-Plugin
doc/Aims-Plugin_Doc/PyQt4.QtGui.QAbstractItemView.CursorAction-class.html
HTML
bsd-3-clause
9,516
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE506_Embedded_Malicious_Code__w32_screen_capture_06.c Label Definition File: CWE506_Embedded_Malicious_Code__w32.badonly.label.xml Template File: point-flaw-badonly-06.tmpl.c */ /* * @description * CWE: 506 Embedded Malicious Code * Sinks: screen_capture * BadSink : Capture the screen and save it to a file * BadOnly (No GoodSink) * Flow Variant: 06 Control flow: if(STATIC_CONST_FIVE==5) * * */ #include "std_testcase.h" #include "windows.h" #pragma comment(lib, "user32.lib") #pragma comment(lib, "Gdi32.lib") /* The variable below is declared "const", so a tool should be able to identify that reads of this will always give its initialized value. */ static const int STATIC_CONST_FIVE = 5; #ifndef OMITBAD void CWE506_Embedded_Malicious_Code__w32_screen_capture_06_bad() { if(STATIC_CONST_FIVE==5) { { /* adapted from http://msdn.microsoft.com/en-us/library/dd183402 */ HDC hdcWindow = NULL; HDC hdcMemDC = NULL; HBITMAP hbmScreen = NULL; HGDIOBJ selectResult = NULL; BITMAP bmpScreen; RECT rcClient; BITMAPFILEHEADER bmfHeader; BITMAPINFOHEADER bmiHeader; DWORD dwBmpSize; HANDLE hDIB = NULL; char *lpbitmap = NULL; HANDLE hFile = INVALID_HANDLE_VALUE; DWORD dwSizeofDIB; DWORD dwBytesWritten; HWND hWnd = GetDesktopWindow(); do { /* Retrieve the handle to a display device context for the client * area of the window. */ hdcWindow = GetDC(hWnd); if (hdcWindow == NULL) { break; } /* Create a compatible DC which is used in a BitBlt from the window DC */ hdcMemDC = CreateCompatibleDC(hdcWindow); if (hdcMemDC == NULL) { break; } /* Get the client area for size calculation */ if (GetClientRect(hWnd, &rcClient) == 0) { break; } /* Create a compatible bitmap from the Window DC */ hbmScreen = CreateCompatibleBitmap(hdcWindow, rcClient.right-rcClient.left, rcClient.bottom-rcClient.top); if (hbmScreen == NULL) { break; } /* Select the compatible bitmap into the compatible memory DC. */ selectResult = SelectObject(hdcMemDC,hbmScreen); if (selectResult == NULL || selectResult == HGDI_ERROR) { break; } /* Bit block transfer into our compatible memory DC. */ if (BitBlt(hdcMemDC, 0,0, rcClient.right-rcClient.left, rcClient.bottom-rcClient.top, hdcWindow, 0,0, SRCCOPY) == 0) { break; } /* Get the BITMAP from the HBITMAP */ if (GetObject(hbmScreen,sizeof(BITMAP),&bmpScreen) == 0) { break; } bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmiHeader.biWidth = bmpScreen.bmWidth; bmiHeader.biHeight = bmpScreen.bmHeight; bmiHeader.biPlanes = 1; bmiHeader.biBitCount = 32; bmiHeader.biCompression = BI_RGB; bmiHeader.biSizeImage = 0; bmiHeader.biXPelsPerMeter = 0; bmiHeader.biYPelsPerMeter = 0; bmiHeader.biClrUsed = 0; bmiHeader.biClrImportant = 0; dwBmpSize = ((bmpScreen.bmWidth * bmiHeader.biBitCount + 31) / 32) * 4 * bmpScreen.bmHeight; /* Starting with 32-bit Windows, GlobalAlloc and LocalAlloc are implemented as wrapper functions that * call HeapAlloc using a handle to the process's default heap. Therefore, GlobalAlloc and LocalAlloc * have greater overhead than HeapAlloc. */ hDIB = GlobalAlloc(GHND,dwBmpSize); if (hDIB == NULL) { break; } lpbitmap = (char *)GlobalLock(hDIB); if (lpbitmap == NULL) { break; } /* Gets the "bits" from the bitmap and copies them into a buffer * which is pointed to by lpbitmap. */ if (GetDIBits(hdcWindow, hbmScreen, 0, (UINT)bmpScreen.bmHeight, lpbitmap, (BITMAPINFO *)&bmiHeader, DIB_RGB_COLORS) == 0) { break; } /* A file is created, this is where we will save the screen capture. */ hFile = CreateFile(TEXT("capture.bmp"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { break; } /* Add the size of the headers to the size of the bitmap to get the total file size */ dwSizeofDIB = dwBmpSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); /* Offset to where the actual bitmap bits start. */ bmfHeader.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER); /* Size of the file */ bmfHeader.bfSize = dwSizeofDIB; /* bfType must always be BM for Bitmaps */ bmfHeader.bfType = 0x4D42; /* BM */ dwBytesWritten = 0; /* FLAW: Perform a screen capture and save the image to a file */ if (WriteFile(hFile, (LPSTR)&bmfHeader, sizeof(BITMAPFILEHEADER), &dwBytesWritten, NULL) == 0) { break; } if (WriteFile(hFile, (LPSTR)&bmiHeader, sizeof(BITMAPINFOHEADER), &dwBytesWritten, NULL) == 0) { break; } if (WriteFile(hFile, (LPSTR)lpbitmap, dwBmpSize, &dwBytesWritten, NULL) == 0) { break; } } while (0); /* Unlock and Free the DIB from the heap */ if (hDIB != NULL) { GlobalUnlock(hDIB); GlobalFree(hDIB); } /* Close the handle for the file that was created */ if (hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); } /* Clean up */ if (hbmScreen != NULL) { DeleteObject(hbmScreen); } if (hdcMemDC != NULL) { DeleteObject(hdcMemDC); } if (hdcWindow != NULL) { ReleaseDC(hWnd,hdcWindow); } } } } #endif /* OMITBAD */ /* 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 OMITBAD printLine("Calling bad()..."); CWE506_Embedded_Malicious_Code__w32_screen_capture_06_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE506_Embedded_Malicious_Code/CWE506_Embedded_Malicious_Code__w32_screen_capture_06.c
C
bsd-3-clause
8,386
#!/usr/bin/env python # Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Given the output of -t commands from a ninja build for a gyp and GN generated build, report on differences between the command lines. This script is best used interactively. Here's a recommended setup: $ PYTHONPATH=tools/gn/bin python >>> import sys >>> import pprint >>> sys.displayhook = pprint.pprint >>> import gyp_flag_compare as fc >>> fc.ConfigureBuild(['gyp_define=1', 'define=2'], ['gn_arg=1', 'arg=2']) >>> chrome = fc.Comparison('chrome') The above starts interactive Python, sets up the output to be pretty-printed (useful for making lists, dicts, and sets readable), configures the build with GN arguments and GYP defines, and then generates a comparison for that build configuration for the "chrome" target. After that, the |chrome| object can be used to investigate differences in the build. To configure an official build, use this configuration. Disabling NaCl produces a more meaningful comparison, as certain files need to get compiled twice for the IRT build, which uses different flags: >>> fc.ConfigureBuild( ['disable_nacl=1', 'buildtype=Official', 'branding=Chrome'], ['enable_nacl=false', 'is_official_build=true', 'is_chrome_branded=true']) """ import os import shlex import subprocess import sys # Must be in src/. os.chdir(os.path.join(os.path.dirname(__file__), '..', '..', '..')) _GN_OUT_DIR = 'out/gn_flags' _GYP_OUT_DIR = 'out_gyp_flags/Release' def ConfigureBuild(gyp_args=[], gn_args=[]): print >> sys.stderr, 'Regenerating in %s...' % _GN_OUT_DIR # Currently only Release, non-component. Run('gn gen %s --args="is_debug=false is_component_build=false %s"' % \ (_GN_OUT_DIR, ' '.join(gn_args))) os.environ.pop('GYP_DEFINES', None) # Remove environment variables required by gn but conflicting with GYP. # Relevant if Windows toolchain isn't provided by depot_tools. os.environ.pop('GYP_MSVS_OVERRIDE_PATH', None) os.environ.pop('WINDOWSSDKDIR', None) gyp_defines = '' if len(gyp_args) > 0: gyp_defines = '-D' + ' -D'.join(gyp_args) print >> sys.stderr, 'Regenerating in %s...' % _GYP_OUT_DIR Run('python build/gyp_chromium -Goutput_dir=out_gyp_flags ' + \ '-Gconfig=Release %s' % gyp_defines) def Counts(dict_of_list): """Given a dictionary whose value are lists, returns a dictionary whose values are the length of the list. This can be used to summarize a dictionary. """ return {k: len(v) for k, v in dict_of_list.iteritems()} def CountsByDirname(dict_of_list): """Given a list of files, returns a dict of dirname to counts in that dir.""" r = {} for path in dict_of_list: dirname = os.path.dirname(path) r.setdefault(dirname, 0) r[dirname] += 1 return r class Comparison(object): """A comparison of the currently-configured build for a target.""" def __init__(self, gyp_target, gn_target=None): """Creates a comparison of a GN and GYP target. If the target names differ between the two build systems, then two names may be passed. """ if gn_target is None: gn_target = gyp_target self._gyp_target = gyp_target self._gn_target = gn_target self._skipped = [] self._total_diffs = 0 self._missing_gyp_flags = {} self._missing_gn_flags = {} self._missing_gyp_files = {} self._missing_gn_files = {} self._CompareFiles() @property def gyp_files(self): """Returns the set of files that are in the GYP target.""" return set(self._gyp_flags.keys()) @property def gn_files(self): """Returns the set of files that are in the GN target.""" return set(self._gn_flags.keys()) @property def skipped(self): """Returns the list of compiler commands that were not processed during the comparison. """ return self._skipped @property def total_differences(self): """Returns the total number of differences detected.""" return self._total_diffs @property def missing_in_gyp(self): """Differences that are only in GYP build but not in GN, indexed by the difference.""" return self._missing_gyp_flags @property def missing_in_gn(self): """Differences that are only in the GN build but not in GYP, indexed by the difference.""" return self._missing_gn_flags @property def missing_in_gyp_by_file(self): """Differences that are only in the GYP build but not in GN, indexed by file. """ return self._missing_gyp_files @property def missing_in_gn_by_file(self): """Differences that are only in the GYP build but not in GN, indexed by file. """ return self._missing_gn_files def _CompareFiles(self): """Performs the actual target comparison.""" if sys.platform == 'win32': # On Windows flags are stored in .rsp files which are created by building. print >> sys.stderr, 'Building in %s...' % _GN_OUT_DIR Run('ninja -C %s -d keeprsp %s' % (_GN_OUT_DIR, self._gn_target)) print >> sys.stderr, 'Building in %s...' % _GYP_OUT_DIR Run('ninja -C %s -d keeprsp %s' % (_GYP_OUT_DIR, self._gn_target)) gn = Run('ninja -C %s -t commands %s' % (_GN_OUT_DIR, self._gn_target)) gyp = Run('ninja -C %s -t commands %s' % (_GYP_OUT_DIR, self._gyp_target)) self._gn_flags = self._GetFlags(gn.splitlines(), os.path.join(os.getcwd(), _GN_OUT_DIR)) self._gyp_flags = self._GetFlags(gyp.splitlines(), os.path.join(os.getcwd(), _GYP_OUT_DIR)) all_files = sorted(self.gn_files & self.gyp_files) for filename in all_files: gyp_flags = self._gyp_flags[filename] gn_flags = self._gn_flags[filename] self._CompareLists(filename, gyp_flags, gn_flags, 'dash_f') self._CompareLists(filename, gyp_flags, gn_flags, 'defines') self._CompareLists(filename, gyp_flags, gn_flags, 'include_dirs') self._CompareLists(filename, gyp_flags, gn_flags, 'warnings', # More conservative warnings in GN we consider to be OK. dont_care_gyp=[ '/wd4091', # 'keyword' : ignored on left of 'type' when no variable # is declared. '/wd4456', # Declaration hides previous local declaration. '/wd4457', # Declaration hides function parameter. '/wd4458', # Declaration hides class member. '/wd4459', # Declaration hides global declaration. '/wd4702', # Unreachable code. '/wd4800', # Forcing value to bool 'true' or 'false'. '/wd4838', # Conversion from 'type' to 'type' requires a narrowing # conversion. ] if sys.platform == 'win32' else None, dont_care_gn=[ '-Wendif-labels', '-Wextra', '-Wsign-compare', ] if not sys.platform == 'win32' else None) self._CompareLists(filename, gyp_flags, gn_flags, 'other') def _CompareLists(self, filename, gyp, gn, name, dont_care_gyp=None, dont_care_gn=None): """Return a report of any differences between gyp and gn lists, ignoring anything in |dont_care_{gyp|gn}| respectively.""" if gyp[name] == gn[name]: return if not dont_care_gyp: dont_care_gyp = [] if not dont_care_gn: dont_care_gn = [] gyp_set = set(gyp[name]) gn_set = set(gn[name]) missing_in_gyp = gyp_set - gn_set missing_in_gn = gn_set - gyp_set missing_in_gyp -= set(dont_care_gyp) missing_in_gn -= set(dont_care_gn) for m in missing_in_gyp: self._missing_gyp_flags.setdefault(name, {}) \ .setdefault(m, []).append(filename) self._total_diffs += 1 self._missing_gyp_files.setdefault(filename, {}) \ .setdefault(name, set()).update(missing_in_gyp) for m in missing_in_gn: self._missing_gn_flags.setdefault(name, {}) \ .setdefault(m, []).append(filename) self._total_diffs += 1 self._missing_gn_files.setdefault(filename, {}) \ .setdefault(name, set()).update(missing_in_gn) def _GetFlags(self, lines, build_dir): """Turn a list of command lines into a semi-structured dict.""" is_win = sys.platform == 'win32' flags_by_output = {} for line in lines: command_line = shlex.split(line.strip(), posix=not is_win)[1:] output_name = _FindAndRemoveArgWithValue(command_line, '-o') dep_name = _FindAndRemoveArgWithValue(command_line, '-MF') command_line = _MergeSpacedArgs(command_line, '-Xclang') cc_file = [x for x in command_line if x.endswith('.cc') or x.endswith('.c') or x.endswith('.cpp') or x.endswith('.mm') or x.endswith('.m')] if len(cc_file) != 1: self._skipped.append(command_line) continue assert len(cc_file) == 1 if is_win: rsp_file = [x for x in command_line if x.endswith('.rsp')] assert len(rsp_file) <= 1 if rsp_file: rsp_file = os.path.join(build_dir, rsp_file[0][1:]) with open(rsp_file, "r") as open_rsp_file: command_line = shlex.split(open_rsp_file, posix=False) defines = [x for x in command_line if x.startswith('-D')] include_dirs = [x for x in command_line if x.startswith('-I')] dash_f = [x for x in command_line if x.startswith('-f')] warnings = \ [x for x in command_line if x.startswith('/wd' if is_win else '-W')] others = [x for x in command_line if x not in defines and \ x not in include_dirs and \ x not in dash_f and \ x not in warnings and \ x not in cc_file] for index, value in enumerate(include_dirs): if value == '-Igen': continue path = value[2:] if not os.path.isabs(path): path = os.path.join(build_dir, path) include_dirs[index] = '-I' + os.path.normpath(path) # GYP supports paths above the source root like <(DEPTH)/../foo while such # paths are unsupported by gn. But gn allows to use system-absolute paths # instead (paths that start with single '/'). Normalize all paths. cc_file = [os.path.normpath(os.path.join(build_dir, cc_file[0]))] # Filter for libFindBadConstructs.so having a relative path in one and # absolute path in the other. others_filtered = [] for x in others: if x.startswith('-Xclang ') and \ (x.endswith('libFindBadConstructs.so') or \ x.endswith('libFindBadConstructs.dylib')): others_filtered.append( '-Xclang ' + os.path.join(os.getcwd(), os.path.normpath( os.path.join('out/gn_flags', x.split(' ', 1)[1])))) elif x.startswith('-B'): others_filtered.append( '-B' + os.path.join(os.getcwd(), os.path.normpath( os.path.join('out/gn_flags', x[2:])))) else: others_filtered.append(x) others = others_filtered flags_by_output[cc_file[0]] = { 'output': output_name, 'depname': dep_name, 'defines': sorted(defines), 'include_dirs': sorted(include_dirs), # TODO(scottmg): This is wrong. 'dash_f': sorted(dash_f), 'warnings': sorted(warnings), 'other': sorted(others), } return flags_by_output def _FindAndRemoveArgWithValue(command_line, argname): """Given a command line as a list, remove and return the value of an option that takes a value as a separate entry. Modifies |command_line| in place. """ if argname not in command_line: return '' location = command_line.index(argname) value = command_line[location + 1] command_line[location:location + 2] = [] return value def _MergeSpacedArgs(command_line, argname): """Combine all arguments |argname| with their values, separated by a space.""" i = 0 result = [] while i < len(command_line): arg = command_line[i] if arg == argname: result.append(arg + ' ' + command_line[i + 1]) i += 1 else: result.append(arg) i += 1 return result def Run(command_line): """Run |command_line| as a subprocess and return stdout. Raises on error.""" print >> sys.stderr, command_line return subprocess.check_output(command_line, shell=True) def main(): if len(sys.argv) != 2 and len(sys.argv) != 3: print 'usage: %s gyp_target gn_target' % __file__ print ' or: %s target' % __file__ return 1 ConfigureBuild() gyp_target = sys.argv[1] if len(sys.argv) == 2: gn_target = gyp_target else: gn_target = sys.argv[2] comparison = Comparison(gyp_target, gn_target) gyp_files = comparison.gyp_files gn_files = comparison.gn_files different_source_list = comparison.gyp_files != comparison.gn_files if different_source_list: print 'Different set of sources files:' print ' In gyp, not in GN:\n %s' % '\n '.join( sorted(gyp_files - gn_files)) print ' In GN, not in gyp:\n %s' % '\n '.join( sorted(gn_files - gyp_files)) print '\nNote that flags will only be compared for files in both sets.\n' differing_files = set(comparison.missing_in_gn_by_file.keys()) & \ set(comparison.missing_in_gyp_by_file.keys()) files_with_given_differences = {} for filename in differing_files: output = '' missing_in_gyp = comparison.missing_in_gyp_by_file.get(filename, {}) missing_in_gn = comparison.missing_in_gn_by_file.get(filename, {}) difference_types = sorted(set(missing_in_gyp.keys() + missing_in_gn.keys())) for difference_type in difference_types: output += ' %s differ:\n' % difference_type if difference_type in missing_in_gyp: output += ' In gyp, but not in GN:\n %s' % '\n '.join( sorted(missing_in_gyp[difference_type])) + '\n' if difference_type in missing_in_gn: output += ' In GN, but not in gyp:\n %s' % '\n '.join( sorted(missing_in_gn[difference_type])) + '\n' if output: files_with_given_differences.setdefault(output, []).append(filename) for diff, files in files_with_given_differences.iteritems(): print '\n'.join(sorted(files)) print diff print 'Total differences:', comparison.total_differences # TODO(scottmg): Return failure on difference once we're closer to identical. return 0 if __name__ == '__main__': sys.exit(main())
danakj/chromium
tools/gn/bin/gyp_flag_compare.py
Python
bsd-3-clause
14,986
$(".top-section").addClass("show-section"); setTimeout(function() { $(".vacancy-content").addClass("show-content"); }, 400); $(".item-vacancy").click(function() { $(".popup-container").addClass("popup-show"); $(".popup-container").focus(); $("body, html").css("overflow", "hidden"); var vacancyInfo = $(this).children(".hidden-vacancy-content").html(); $(".popup-past-description")[0].innerHTML = vacancyInfo; }); $(".close-popup").click(function() { $(".popup-container").removeClass("popup-show"); $("body, html").css("overflow", "normal"); }); $(".loader-img").addClass("loader-none");
zserg84/webteam
prototype/page/vacancy/scripts/configuration.js
JavaScript
bsd-3-clause
637
--- layout: plugin title: lightbox is_lightbox: true options: - name: prefix default: "'myLightbox'" - name: group default: "false" example: true - name: cycle default: "false" example: true - name: modal default: "false" example: true - name: modalClickable default: "false" example: true - name: modalClosable default: "false" example: true - name: forceLoad default: "false" example: true - name: easing default: "'swing'" example: true - name: duration default: "1000" example: true - name: speed default: "0" example: true - name: fixed default: "false" example: true - name: responsive default: "false" example: true - name: ajax default: "true" example: true - name: controls default: "false" - name: cls default: "my-lightbox" - name: opacity default: "0.5" - name: styles default: "{ 'background': 'red' }" - name: dimensions default: "{}" - name: keys default: "false" example: true - name: keyCodes default: "{}" - name: lang default: "{}" methods: - name: open - name: close - name: resize - name: destroy - name: next - name: previous - name: getElement - name: getCollection callbacks: - name: open - name: close - name: resize - name: destroy - name: next - name: previous - name: load - name: complete - name: unload --- <!-- start: example --> <p class="clear"> <a href="../static/dummy/img-large-001.jpg" class="lightbox box" id="group" title="&copy; Blizzard Entertainment."><img src="../static/dummy/img-001.jpg" alt="" /> <span>image</span></a> <a href="../static/dummy/img-large-002.jpg" class="lightbox-groups box" title="&copy; Blizzard Entertainment."><img src="../static/dummy/img-002.jpg" alt="" /> <span>image <strong>group</strong></span></a> <a href="../static/dummy/img-large-003.jpg" class="lightbox-groups box" title="&copy; Blizzard Entertainment."><img src="../static/dummy/img-003.jpg" alt="" /> <span>image <strong>group</strong></span></a> <a href="../static/dummy/img-large-004.jpg" class="lightbox-groups box" title="&copy; Blizzard Entertainment."><img src="../static/dummy/img-004.jpg" alt="" /> <span>image <strong>group</strong></span></a> <a href="http://www.youtube.com/embed/vCsGTP3-Jlw?rel=0" class="lightbox box"><img src="../static/dummy/youtube.jpg" alt="" /> <span>youtube</span></a> <a href="http://player.vimeo.com/video/43839129" class="lightbox box"><img src="../static/dummy/vimeo.jpg" alt="" /> <span>vimeoh</span></a> <a href="http://www.adobe.com/swf/software/flash/about/mini_FMA_about_01.swf" class="lightbox box"><img src="../static/dummy/swf.jpg" alt="" /> <span>flash</span></a> <a href="#inline" class="lightbox box"><img src="../static/dummy/inline.jpg" alt="" /> <span>inline</span></a> </p> <div hidden="hidden"> <div id="inline" style="padding:25px 25px 15px;"> <h2>Inline</h2> <p>Lorem ipsum dolor sit amet de shizzle the dizzle crocodizzle.</p> <form action="." method="post"> <fieldset> <legend>This is an inline form example!</legend> <label> <select> <option value="">Please choose</option> <option value="1">Option 1</option> <option value="2">Option 2</option> </select> </label> </fieldset> </form> </div> </div> <!-- start: example -->
divio/classjs-plugins
examples/cl.lightbox/index.html
HTML
bsd-3-clause
3,523
#include <framebuffer.h> #define labs(x) ((x) < 0 ? -(x) : (x)) int mediancmp( const void *left, const void *right ) { uint8 l = *((uint8*)left); uint8 r = *((uint8*)right); return (l == r ? 0 : l < r ? -1 : 1); } int mediancmp2( const void *left, const void *right ) { color_t *l = (color_t*)left; color_t *r = (color_t*)right; return color_cmp( *l, *r ); } int32 framebuffer_median( framebuffer_t *dst, framebuffer_t *src, int32 win ) { static int32 size = 0; static int32 bounds = 0; static uint8 *windowr = NULL; static uint8 *windowg = NULL; static uint8 *windowb = NULL; int32 x; int32 y; int32 i; int32 j; int32 xn; int32 yn; int32 indx; color_t t; // Make sure the filter is called with valid images if( dst->width != src->width ) return EINVAL; if( dst->height != src->height ) return EINVAL; // Determine if we need to allocate memory for the window if( bounds != win/2 ) { bounds = win / 2; size = 2*bounds+1; size *= size; if( windowr != NULL ) free( windowr ); if( windowg != NULL ) free( windowg ); if( windowb != NULL ) free( windowb ); windowr = (uint8*)malloc( size*sizeof(uint8) ); windowg = (uint8*)malloc( size*sizeof(uint8) ); windowb = (uint8*)malloc( size*sizeof(uint8) ); } for( y = 0; y < src->height; y++ ) { for( x = 0; x < src->width; x++ ) { indx = 0; for( j = -bounds; j <= bounds; j++ ) { for( i = -bounds; i <= bounds; i++ ) { xn = fbrng( x+i, 0, src->width-1 ); yn = fbrng( y+j, 0, src->height-1 ); t = framebuffer_get( src, xn, yn ); windowr[indx] = color_red(t); windowg[indx] = color_green(t); windowb[indx] = color_blue(t); indx++; } } qsort( windowr, size, sizeof(uint8), mediancmp ); qsort( windowg, size, sizeof(uint8), mediancmp ); qsort( windowb, size, sizeof(uint8), mediancmp ); framebuffer_set( dst, x, y, color_make(windowr[size/2],windowg[size/2],windowb[size/2],255)); } } return 0; } int32 framebuffer_median2( framebuffer_t *dst, framebuffer_t *src, int32 win ) { static int32 size = 0; static int32 bounds = 0; static color_t *window = NULL; int32 x; int32 y; int32 i; int32 j; int32 xn; int32 yn; int32 indx; color_t t; // Make sure the filter is called with valid images if( dst->width != src->width ) return EINVAL; if( dst->height != src->height ) return EINVAL; // Determine if we need to allocate memory for the window if( bounds != win/2 || window == NULL ) { bounds = win / 2; size = 2*bounds+1; size *= size; if( window != NULL ) free( window ); window = (color_t*)malloc( size*sizeof(color_t) ); } for( y = 0; y < src->height; y++ ) { for( x = 0; x < src->width; x++ ) { indx = 0; for( j = -bounds; j <= bounds; j++ ) { for( i = -bounds; i <= bounds; i++ ) { xn = fbrng( x+i, 0, src->width-1 ); yn = fbrng( y+j, 0, src->height-1 ); t = framebuffer_get( src, xn, yn ); window[indx++] = t; } } qsort( window, size, sizeof(color_t), mediancmp ); framebuffer_set( dst, x, y, window[size/2] ); } } return 0; }
masson2013/heterogeneous_hthreads
src/test/filter/src/filter/median.c
C
bsd-3-clause
3,795
import random from django import template from django.conf import settings from django.contrib.sites.models import Site from friends.models import Friendship, FriendshipInvitation from socialregistration.models import FacebookProfile register = template.Library() @register.inclusion_tag('social/inclusion_tags/twitter_connect_form.html', takes_context=True) def twitter_connect_form(context, form_id): context.update({ 'form_id': form_id, }) return context @register.inclusion_tag('social/inclusion_tags/facebook_connect_form.html', takes_context=True) def facebook_connect_form(context, form_id): context.update({ 'form_id': form_id, }) return context @register.inclusion_tag('social/inclusion_tags/twitter_connect_button.html') def twitter_connect_button(form_id, media_path): return { 'form_id': form_id, 'media_path': media_path, } @register.inclusion_tag('social/inclusion_tags/facebook_connect_button.html') def facebook_connect_button(form_id, media_path): return { 'form_id': form_id, 'media_path': media_path, } @register.inclusion_tag('social/inclusion_tags/friendship_setup_button.html', takes_context=True) def friendship_setup_button(context, user, include_template_name='social/inclusion_tags/friendship_setup_button_include.html'): """ Renders either an 'add friend', 'remove friend', 'awaiting confirmation' or 'friendship declined' button based on current friendship state. Also includes javascript to request friend or remove friend. """ if not user: return {} # Render add friend template by default. active_class = "add_friend" requesting_user = context['request'].user if requesting_user.is_authenticated(): # If users are friends already render remove friend template. are_friends = Friendship.objects.are_friends(requesting_user, user) if are_friends: active_class = "remove_friend" else: # If users are not friends but an invitation exists, render awaiting confirmation or declined template. status = FriendshipInvitation.objects.invitation_status(user1=requesting_user, user2=user) if status == 2: active_class = "awaiting_friend_confirmation" if status == 6: active_class = "request_declined" return { 'include_template_name': include_template_name, 'object': user, 'active_class': active_class, 'random': random.randint(0, 100000000) } @register.inclusion_tag('social/inclusion_tags/facebook_invite_friends.html', takes_context=True) def facebook_invite_friends(context, user): """ Renders Facebook friends invite form. """ current_site = Site.objects.get(id=settings.SITE_ID) # exclude id's of facebook users that are already using the app fb_profiles = FacebookProfile.objects.all() exclude_ids = ",".join([fb_profile.uid for fb_profile in fb_profiles]) return { 'exclude_ids': exclude_ids, 'site_name': current_site.name, 'site_domain': current_site.domain, 'next': context['next'], }
praekelt/jmbo-social
social/templatetags/social_inclusion_tags.py
Python
bsd-3-clause
3,195
--test ceil function with operators +,-,*,/ select ceil(-28)+2 from db_root; select ceil(-28)-2 from db_root; select ceil(-28)*2 from db_root; select ceil(-28)/2 from db_root order by 1;
CUBRID/cubrid-testcases
sql/_04_operator_function/_05_arighmetic_op/_005_ceil/cases/1014.sql
SQL
bsd-3-clause
186
// Copyright 2012, Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package tabletserver import ( "net/http" "sync" "time" log "github.com/golang/glog" "golang.org/x/net/context" "github.com/youtube/vitess/go/stats" "github.com/youtube/vitess/go/sync2" "github.com/youtube/vitess/go/vt/dbconfigs" "github.com/youtube/vitess/go/vt/dbconnpool" "github.com/youtube/vitess/go/vt/logutil" vtrpcpb "github.com/youtube/vitess/go/vt/proto/vtrpc" "github.com/youtube/vitess/go/vt/tableacl" "github.com/youtube/vitess/go/vt/tableacl/acl" ) // spotCheckMultiplier determines the precision of the // spot check ratio: 1e6 == 6 digits const spotCheckMultiplier = 1e6 // QueryEngine implements the core functionality of tabletserver. // It assumes that no requests will be sent to it before Open is // called and succeeds. // Shutdown is done in the following order: // // WaitForTxEmpty: There should be no more new calls to Begin // once this function is called. This will return when there // are no more pending transactions. // // Close: There should be no more pending queries when this // function is called. // // Functions of QueryEngine do not return errors. They instead // panic with NewTabletError as the error type. // TODO(sougou): Switch to error return scheme. type QueryEngine struct { schemaInfo *SchemaInfo config Config dbconfigs dbconfigs.DBConfigs // Pools cachePool *CachePool connPool *ConnPool streamConnPool *ConnPool // Services txPool *TxPool consolidator *sync2.Consolidator streamQList *QueryList tasks sync.WaitGroup // Vars spotCheckFreq sync2.AtomicInt64 strictMode sync2.AtomicInt64 autoCommit sync2.AtomicInt64 maxResultSize sync2.AtomicInt64 maxDMLRows sync2.AtomicInt64 streamBufferSize sync2.AtomicInt64 // tableaclExemptCount count the number of accesses allowed // based on membership in the superuser ACL tableaclExemptCount sync2.AtomicInt64 tableaclAllowed *stats.MultiCounters tableaclDenied *stats.MultiCounters tableaclPseudoDenied *stats.MultiCounters strictTableAcl bool enableTableAclDryRun bool exemptACL acl.ACL // Loggers accessCheckerLogger *logutil.ThrottledLogger // Stats queryServiceStats *QueryServiceStats } type compiledPlan struct { Query string *ExecPlan BindVars map[string]interface{} TransactionID int64 } // CacheInvalidator provides the abstraction needed for an instant invalidation // vs. delayed invalidation in the case of in-transaction dmls type CacheInvalidator interface { Delete(key string) } // Helper method for conn pools to convert errors func getOrPanic(ctx context.Context, pool *ConnPool) *DBConn { conn, err := pool.Get(ctx) if err == nil { return conn } if err == ErrConnPoolClosed { panic(ErrConnPoolClosed) } // If there's a problem with getting a connection out of the pool, that is // probably not due to the query itself. The query might succeed on a different // tablet. panic(NewTabletErrorSQL(ErrFatal, vtrpcpb.ErrorCode_INTERNAL_ERROR, err)) } // NewQueryEngine creates a new QueryEngine. // This is a singleton class. // You must call this only once. func NewQueryEngine(checker MySQLChecker, config Config) *QueryEngine { qe := &QueryEngine{config: config} qe.queryServiceStats = NewQueryServiceStats(config.StatsPrefix, config.EnablePublishStats) qe.cachePool = NewCachePool( config.PoolNamePrefix+"Rowcache", config.RowCache, time.Duration(config.IdleTimeout*1e9), config.DebugURLPrefix+"/memcache/", config.EnablePublishStats, qe.queryServiceStats, ) qe.schemaInfo = NewSchemaInfo( config.StatsPrefix, checker, config.QueryCacheSize, time.Duration(config.SchemaReloadTime*1e9), time.Duration(config.IdleTimeout*1e9), qe.cachePool, map[string]string{ debugQueryPlansKey: config.DebugURLPrefix + "/query_plans", debugQueryStatsKey: config.DebugURLPrefix + "/query_stats", debugTableStatsKey: config.DebugURLPrefix + "/table_stats", debugSchemaKey: config.DebugURLPrefix + "/schema", debugQueryRulesKey: config.DebugURLPrefix + "/query_rules", }, config.EnablePublishStats, qe.queryServiceStats, ) qe.connPool = NewConnPool( config.PoolNamePrefix+"ConnPool", config.PoolSize, time.Duration(config.IdleTimeout*1e9), config.EnablePublishStats, qe.queryServiceStats, checker, ) qe.streamConnPool = NewConnPool( config.PoolNamePrefix+"StreamConnPool", config.StreamPoolSize, time.Duration(config.IdleTimeout*1e9), config.EnablePublishStats, qe.queryServiceStats, checker, ) qe.txPool = NewTxPool( config.PoolNamePrefix+"TransactionPool", config.StatsPrefix, config.TransactionCap, time.Duration(config.TransactionTimeout*1e9), time.Duration(config.IdleTimeout*1e9), config.EnablePublishStats, qe.queryServiceStats, checker, ) qe.consolidator = sync2.NewConsolidator() http.Handle(config.DebugURLPrefix+"/consolidations", qe.consolidator) qe.streamQList = NewQueryList() qe.spotCheckFreq = sync2.NewAtomicInt64(int64(config.SpotCheckRatio * spotCheckMultiplier)) if config.StrictMode { qe.strictMode.Set(1) } if config.EnableAutoCommit { qe.autoCommit.Set(1) } qe.strictTableAcl = config.StrictTableAcl qe.enableTableAclDryRun = config.EnableTableAclDryRun if config.TableAclExemptACL != "" { if f, err := tableacl.GetCurrentAclFactory(); err == nil { if exemptACL, err := f.New([]string{config.TableAclExemptACL}); err == nil { log.Infof("Setting Table ACL exempt rule for %v", config.TableAclExemptACL) qe.exemptACL = exemptACL } else { log.Infof("Cannot build exempt ACL for table ACL: %v", err) } } else { log.Infof("Cannot get current ACL Factory: %v", err) } } qe.maxResultSize = sync2.NewAtomicInt64(int64(config.MaxResultSize)) qe.maxDMLRows = sync2.NewAtomicInt64(int64(config.MaxDMLRows)) qe.streamBufferSize = sync2.NewAtomicInt64(int64(config.StreamBufferSize)) qe.accessCheckerLogger = logutil.NewThrottledLogger("accessChecker", 1*time.Second) var tableACLAllowedName string var tableACLDeniedName string var tableACLPseudoDeniedName string if config.EnablePublishStats { stats.Publish(config.StatsPrefix+"MaxResultSize", stats.IntFunc(qe.maxResultSize.Get)) stats.Publish(config.StatsPrefix+"MaxDMLRows", stats.IntFunc(qe.maxDMLRows.Get)) stats.Publish(config.StatsPrefix+"StreamBufferSize", stats.IntFunc(qe.streamBufferSize.Get)) stats.Publish(config.StatsPrefix+"RowcacheSpotCheckRatio", stats.FloatFunc(func() float64 { return float64(qe.spotCheckFreq.Get()) / spotCheckMultiplier })) stats.Publish(config.StatsPrefix+"TableACLExemptCount", stats.IntFunc(qe.tableaclExemptCount.Get)) tableACLAllowedName = "TableACLAllowed" tableACLDeniedName = "TableACLDenied" tableACLPseudoDeniedName = "TableACLPseudoDenied" } qe.tableaclAllowed = stats.NewMultiCounters(tableACLAllowedName, []string{"TableName", "TableGroup", "PlanID", "Username"}) qe.tableaclDenied = stats.NewMultiCounters(tableACLDeniedName, []string{"TableName", "TableGroup", "PlanID", "Username"}) qe.tableaclPseudoDenied = stats.NewMultiCounters(tableACLPseudoDeniedName, []string{"TableName", "TableGroup", "PlanID", "Username"}) return qe } // Open must be called before sending requests to QueryEngine. func (qe *QueryEngine) Open(dbconfigs dbconfigs.DBConfigs, schemaOverrides []SchemaOverride) { qe.dbconfigs = dbconfigs appParams := dbconfigs.App.ConnParams // Create dba params based on App connection params // and Dba credentials. dbaParams := dbconfigs.App.ConnParams if dbconfigs.Dba.Uname != "" { dbaParams.Uname = dbconfigs.Dba.Uname dbaParams.Pass = dbconfigs.Dba.Pass } strictMode := false if qe.strictMode.Get() != 0 { strictMode = true } if !strictMode && qe.config.RowCache.Enabled { panic(NewTabletError(ErrFatal, vtrpcpb.ErrorCode_INTERNAL_ERROR, "Rowcache cannot be enabled when queryserver-config-strict-mode is false")) } if qe.config.RowCache.Enabled { qe.cachePool.Open() log.Infof("rowcache is enabled") } else { log.Infof("rowcache is not enabled") } start := time.Now() // schemaInfo depends on cachePool. Every table that has a rowcache // points to the cachePool. qe.schemaInfo.Open(&appParams, &dbaParams, schemaOverrides, strictMode) log.Infof("Time taken to load the schema: %v", time.Now().Sub(start)) qe.connPool.Open(&appParams, &dbaParams) qe.streamConnPool.Open(&appParams, &dbaParams) qe.txPool.Open(&appParams, &dbaParams) } // Launch launches the specified function inside a goroutine. // If Close or WaitForTxEmpty is called while a goroutine is running, // QueryEngine will not return until the existing functions have completed. // This functionality allows us to launch tasks with the assurance that // the QueryEngine will not be closed underneath us. func (qe *QueryEngine) Launch(f func()) { qe.tasks.Add(1) go func() { defer func() { qe.tasks.Done() if x := recover(); x != nil { qe.queryServiceStats.InternalErrors.Add("Task", 1) log.Errorf("task error: %v", x) } }() f() }() } // IsMySQLReachable returns true if we can connect to MySQL. func (qe *QueryEngine) IsMySQLReachable() bool { conn, err := dbconnpool.NewDBConnection(&qe.dbconfigs.App.ConnParams, qe.queryServiceStats.MySQLStats) if err != nil { if IsConnErr(err) { return false } log.Warningf("checking MySQL, unexpected error: %v", err) return true } conn.Close() return true } // WaitForTxEmpty must be called before calling Close. // Before calling WaitForTxEmpty, you must ensure that there // will be no more calls to Begin. func (qe *QueryEngine) WaitForTxEmpty() { qe.txPool.WaitForEmpty() } // Close must be called to shut down QueryEngine. // You must ensure that no more queries will be sent // before calling Close. func (qe *QueryEngine) Close() { qe.tasks.Wait() // Close in reverse order of Open. qe.txPool.Close() qe.streamConnPool.Close() qe.connPool.Close() qe.schemaInfo.Close() qe.cachePool.Close() } // Commit commits the specified transaction. func (qe *QueryEngine) Commit(ctx context.Context, logStats *LogStats, transactionID int64) { dirtyTables, err := qe.txPool.SafeCommit(ctx, transactionID) for tableName, invalidList := range dirtyTables { tableInfo := qe.schemaInfo.GetTable(tableName) if tableInfo == nil { continue } invalidations := int64(0) for key := range invalidList { // Use context.Background, becaause we don't want to fail // these deletes. tableInfo.Cache.Delete(context.Background(), key) invalidations++ } logStats.CacheInvalidations += invalidations tableInfo.invalidations.Add(invalidations) } if err != nil { panic(err) } } // ClearRowcache invalidates all items in the rowcache. func (qe *QueryEngine) ClearRowcache(ctx context.Context) error { if qe.cachePool.IsClosed() { return NewTabletError(ErrFatal, vtrpcpb.ErrorCode_INTERNAL_ERROR, "rowcache is not up") } conn := qe.cachePool.Get(ctx) defer func() { qe.cachePool.Put(conn) }() if err := conn.FlushAll(); err != nil { conn.Close() conn = nil return NewTabletError(ErrFatal, vtrpcpb.ErrorCode_INTERNAL_ERROR, "%s", err) } return nil }
aaijazi/vitess
go/vt/tabletserver/query_engine.go
GO
bsd-3-clause
11,311
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-example12-jquery</title> <script src="../../components/jquery-2.1.1/jquery.js"></script> <script src="../../../angular.js"></script> <script src="script.js"></script> </head> <body ng-app="docsSimpleDirective"> <div ng-controller="Controller"> <div my-customer></div> </div> </body> </html>
mudunuriRaju/tlr-live
tollbackend/web/js/angular-1.5.5/docs/examples/example-example12/index-jquery.html
HTML
bsd-3-clause
406
--[er]test cast function by casting integer data type to list of string data type set timezone '+9:00'; create class func_03( varchartest varchar(20), sinttest smallint, inttest int, numerictest numeric(38,10), floattest float, realtest real, doublepretest double precision, moneytest monetary, chartest char(8), datetest date, timetest time, timestamptest timestampltz, bittest bit(16), nchartest nchar(20), ncharvartest nchar varying(20), bitvartest bit varying(20), stringtest string); create class dummy( a int ); insert into func_03 values ( '1234567890', 123, 12345, 9876543210987654321012345678.0123456789, 987654.321, 987654321.987654321,987654.321, 9876.1,'char1234', DATE '08/14/1977', time '02:10:00', timestampltz '08/14/1977 5:35:00 pm',B'0', N'test111', N'test111', B'1','qa test'); insert into func_03 values ( '', 0, 0, 0, 0, 0,0, 0, '', null, null, null,B'', N'', N'', B'',''); insert into func_03(stringtest) values ( null); insert into dummy values (1); select cast(inttest as list of string) from func_03 order by 1; drop class func_03; drop class dummy; set timezone 'default';
CUBRID/cubrid-testcases
sql/_27_banana_qa/issue_5765_timezone_support/_00_dev_cases/_02_operator/_05_cast_op_local_tz/cases/1093.sql
SQL
bsd-3-clause
1,237
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.animated; import javax.annotation.Nullable; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.OnBatchCompleteListener; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.modules.core.DeviceEventManagerModule; import com.facebook.react.uimanager.GuardedChoreographerFrameCallback; import com.facebook.react.modules.core.ReactChoreographer; import com.facebook.react.uimanager.UIManagerModule; import java.util.ArrayList; /** * Module that exposes interface for creating and managing animated nodes on the "native" side. * * Animated.js library is based on a concept of a graph where nodes are values or transform * operations (such as interpolation, addition, etc) and connection are used to describe how change * of the value in one node can affect other nodes. * * Few examples of the nodes that can be created on the JS side: * - Animated.Value is a simplest type of node with a numeric value which can be driven by an * animation engine (spring, decay, etc) or by calling setValue on it directly from JS * - Animated.add is a type of node that may have two or more input nodes. It outputs the sum of * all the input node values * - interpolate - is actually a method you can call on any node and it creates a new node that * takes the parent node as an input and outputs its interpolated value (e.g. if you have value * that can animate from 0 to 1 you can create interpolated node and set output range to be 0 to * 100 and when the input node changes the output of interpolated node will multiply the values * by 100) * * You can mix and chain nodes however you like and this way create nodes graph with connections * between them. * * To map animated node values to view properties there is a special type of a node: AnimatedProps. * It is created by AnimatedImplementation whenever you render Animated.View and stores a mapping * from the view properties to the corresponding animated values (so it's actually also a node with * connections to the value nodes). * * Last "special" elements of the the graph are "animation drivers". Those are objects (represented * as a graph nodes too) that based on some criteria updates attached values every frame (we have * few types of those, e.g., spring, timing, decay). Animation objects can be "started" and * "stopped". Those are like "pulse generators" for the rest of the nodes graph. Those pulses then * propagate along the graph to the children nodes up to the special node type: AnimatedProps which * then can be used to calculate property update map for a view. * * This class acts as a proxy between the "native" API that can be called from JS and the main class * that coordinates all the action: {@link NativeAnimatedNodesManager}. Since all the methods from * {@link NativeAnimatedNodesManager} need to be called from the UI thread, we we create a queue of * animated graph operations that is then enqueued to be executed in the UI Thread at the end of the * batch of JS->native calls (similarily to how it's handled in {@link UIManagerModule}). This * isolates us from the problems that may be caused by concurrent updates of animated graph while UI * thread is "executing" the animation loop. */ @ReactModule(name = "NativeAnimatedModule") public class NativeAnimatedModule extends ReactContextBaseJavaModule implements OnBatchCompleteListener, LifecycleEventListener { private interface UIThreadOperation { void execute(NativeAnimatedNodesManager animatedNodesManager); } private final Object mOperationsCopyLock = new Object(); private @Nullable GuardedChoreographerFrameCallback mAnimatedFrameCallback; private @Nullable ReactChoreographer mReactChoreographer; private ArrayList<UIThreadOperation> mOperations = new ArrayList<>(); private volatile @Nullable ArrayList<UIThreadOperation> mReadyOperations = null; public NativeAnimatedModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public void initialize() { // Safe to acquire choreographer here, as initialize() is invoked from UI thread. mReactChoreographer = ReactChoreographer.getInstance(); ReactApplicationContext reactCtx = getReactApplicationContext(); UIManagerModule uiManager = reactCtx.getNativeModule(UIManagerModule.class); final NativeAnimatedNodesManager nodesManager = new NativeAnimatedNodesManager(uiManager); mAnimatedFrameCallback = new GuardedChoreographerFrameCallback(reactCtx) { @Override protected void doFrameGuarded(final long frameTimeNanos) { ArrayList<UIThreadOperation> operations; synchronized (mOperationsCopyLock) { operations = mReadyOperations; mReadyOperations = null; } if (operations != null) { for (int i = 0, size = operations.size(); i < size; i++) { operations.get(i).execute(nodesManager); } } if (nodesManager.hasActiveAnimations()) { nodesManager.runUpdates(frameTimeNanos); } // TODO: Would be great to avoid adding this callback in case there are no active animations // and no outstanding tasks on the operations queue. Apparently frame callbacks can only // be posted from the UI thread and therefore we cannot schedule them directly from // @ReactMethod methods Assertions.assertNotNull(mReactChoreographer).postFrameCallback( ReactChoreographer.CallbackType.NATIVE_ANIMATED_MODULE, mAnimatedFrameCallback); } }; reactCtx.addLifecycleEventListener(this); } @Override public void onBatchComplete() { // Note: The order of executing onBatchComplete handler (especially in terms of onBatchComplete // from the UIManagerModule) doesn't matter as we only enqueue operations for the UI thread to // be executed from here. Thanks to ReactChoreographer all the operations from here are going // to be executed *after* all the operations enqueued by UIManager as the callback type that we // use for ReactChoreographer (CallbackType.NATIVE_ANIMATED_MODULE) is run after callbacks that // UIManager uses. ArrayList<UIThreadOperation> operations = mOperations.isEmpty() ? null : mOperations; if (operations != null) { mOperations = new ArrayList<>(); synchronized (mOperationsCopyLock) { if (mReadyOperations == null) { mReadyOperations = operations; } else { mReadyOperations.addAll(operations); } } } } @Override public void onHostResume() { enqueueFrameCallback(); } @Override public void onHostPause() { clearFrameCallback(); } @Override public void onHostDestroy() { // do nothing } @Override public String getName() { return "NativeAnimatedModule"; } private void clearFrameCallback() { Assertions.assertNotNull(mReactChoreographer).removeFrameCallback( ReactChoreographer.CallbackType.NATIVE_ANIMATED_MODULE, mAnimatedFrameCallback); } private void enqueueFrameCallback() { Assertions.assertNotNull(mReactChoreographer).postFrameCallback( ReactChoreographer.CallbackType.NATIVE_ANIMATED_MODULE, mAnimatedFrameCallback); } @ReactMethod public void createAnimatedNode(final int tag, final ReadableMap config) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.createAnimatedNode(tag, config); } }); } @ReactMethod public void startListeningToAnimatedNodeValue(final int tag) { final AnimatedNodeValueListener listener = new AnimatedNodeValueListener() { public void onValueUpdate(double value) { WritableMap onAnimatedValueData = Arguments.createMap(); onAnimatedValueData.putInt("tag", tag); onAnimatedValueData.putDouble("value", value); getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("onAnimatedValueUpdate", onAnimatedValueData); } }; mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.startListeningToAnimatedNodeValue(tag, listener); } }); } @ReactMethod public void stopListeningToAnimatedNodeValue(final int tag) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.stopListeningToAnimatedNodeValue(tag); } }); } @ReactMethod public void dropAnimatedNode(final int tag) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.dropAnimatedNode(tag); } }); } @ReactMethod public void setAnimatedNodeValue(final int tag, final double value) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.setAnimatedNodeValue(tag, value); } }); } @ReactMethod public void setAnimatedNodeOffset(final int tag, final double value) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.setAnimatedNodeOffset(tag, value); } }); } @ReactMethod public void flattenAnimatedNodeOffset(final int tag) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.flattenAnimatedNodeOffset(tag); } }); } @ReactMethod public void extractAnimatedNodeOffset(final int tag) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.extractAnimatedNodeOffset(tag); } }); } @ReactMethod public void startAnimatingNode( final int animationId, final int animatedNodeTag, final ReadableMap animationConfig, final Callback endCallback) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.startAnimatingNode( animationId, animatedNodeTag, animationConfig, endCallback); } }); } @ReactMethod public void stopAnimation(final int animationId) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.stopAnimation(animationId); } }); } @ReactMethod public void connectAnimatedNodes(final int parentNodeTag, final int childNodeTag) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.connectAnimatedNodes(parentNodeTag, childNodeTag); } }); } @ReactMethod public void disconnectAnimatedNodes(final int parentNodeTag, final int childNodeTag) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.disconnectAnimatedNodes(parentNodeTag, childNodeTag); } }); } @ReactMethod public void connectAnimatedNodeToView(final int animatedNodeTag, final int viewTag) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.connectAnimatedNodeToView(animatedNodeTag, viewTag); } }); } @ReactMethod public void disconnectAnimatedNodeFromView(final int animatedNodeTag, final int viewTag) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.disconnectAnimatedNodeFromView(animatedNodeTag, viewTag); } }); } @ReactMethod public void addAnimatedEventToView(final int viewTag, final String eventName, final ReadableMap eventMapping) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.addAnimatedEventToView(viewTag, eventName, eventMapping); } }); } @ReactMethod public void removeAnimatedEventFromView(final int viewTag, final String eventName) { mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.removeAnimatedEventFromView(viewTag, eventName); } }); } }
htc2u/react-native
ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedModule.java
Java
bsd-3-clause
13,842
package org.hamcrest.text.pattern; public class PatternMatchException extends Exception { private static final long serialVersionUID = 1L; public PatternMatchException(String message) { super(message); } public PatternMatchException(String message, Throwable cause) { super(message, cause); } }
npryce/hamcrest-text-patterns
src/org/hamcrest/text/pattern/PatternMatchException.java
Java
bsd-3-clause
334
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS 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. */ #ifndef OESTextureHalfFloatLinear_h #define OESTextureHalfFloatLinear_h #include "bindings/core/v8/ScriptWrappable.h" #include "core/html/canvas/WebGLExtension.h" #include "wtf/PassRefPtr.h" namespace blink { class OESTextureHalfFloatLinear final : public WebGLExtension, public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: static PassRefPtrWillBeRawPtr<OESTextureHalfFloatLinear> create(WebGLRenderingContextBase*); static bool supported(WebGLRenderingContextBase*); static const char* extensionName(); virtual ~OESTextureHalfFloatLinear(); virtual WebGLExtensionName name() const override; private: explicit OESTextureHalfFloatLinear(WebGLRenderingContextBase*); }; } // namespace blink #endif // OESTextureHalfFloatLinear_h
smilusingjavascript/blink
Source/core/html/canvas/OESTextureHalfFloatLinear.h
C
bsd-3-clause
2,119
require 'rake/extensioncompiler' HOST = Rake::ExtensionCompiler.mingw_host TARGET = 'i386-pc-mingw32' ZLIB = 'zlib-1.2.5' ICONV = 'libiconv-1.13.1' LIBXML = 'libxml2-2.7.7' LIBXSLT = 'libxslt-1.1.26' RAKE_COMPILER_PKGCONFIG = File.expand_path(File.join(Dir.pwd, "tmp/cross/lib/pkgconfig/")) ### Build zlib ### file "tmp/cross/download/#{ZLIB}" do |t| FileUtils.mkdir_p('tmp/cross/download') file = ZLIB url = "http://zlib.net/#{file}.tar.gz" Dir.chdir('tmp/cross/download') do sh "wget #{url} || curl -O #{url}" sh "tar zxvf #{file}.tar.gz" end Dir.chdir t.name do mk = File.read('win32/Makefile.gcc') File.open('win32/Makefile.gcc', 'wb') do |f| f.puts "BINARY_PATH = #{CROSS_DIR}/bin" f.puts "LIBRARY_PATH = #{CROSS_DIR}/lib" f.puts "INCLUDE_PATH = #{CROSS_DIR}/include" # FIXME: need to make the cross compiler dynamic f.puts mk.sub(/^PREFIX\s*=\s*$/, "PREFIX = #{HOST}-") #. #sub(/^SHARED_MODE=0$/, 'SHARED_MODE=1'). #sub(/^IMPLIB\s*=.*$/, 'IMPLIB=libz.dll.a') end end end file 'tmp/cross/lib/libz.a' => "tmp/cross/download/#{ZLIB}" do |t| Dir.chdir t.prerequisites.first do sh 'make -f win32/Makefile.gcc' sh 'make -f win32/Makefile.gcc install' end end ### End build zlib ### ### Build iconv ### file "tmp/cross/download/#{ICONV}" do |t| FileUtils.mkdir_p('tmp/cross/download') file = ICONV url = "http://ftp.gnu.org/pub/gnu/libiconv/#{file}.tar.gz" Dir.chdir('tmp/cross/download') do sh "wget #{url} || curl -O #{url}" sh "tar zxvf #{file}.tar.gz" end Dir.chdir t.name do # FIXME: need to make the host dynamic sh "./configure --disable-shared --enable-static --host=#{HOST} --target=#{TARGET} --prefix=#{CROSS_DIR} CPPFLAGS='-mno-cygwin -Wall' CFLAGS='-mno-cygwin -O2 -g' CXXFLAGS='-mno-cygwin -O2 -g' LDFLAGS=-mno-cygwin" end end file 'tmp/cross/bin/iconv.exe' => "tmp/cross/download/#{ICONV}" do |t| Dir.chdir t.prerequisites.first do sh 'make' sh 'make install' end end ### End build iconv ### ### Build libxml2 ### file "tmp/cross/download/#{LIBXML}" do |t| FileUtils.mkdir_p('tmp/cross/download') file = LIBXML url = "ftp://ftp.xmlsoft.org/libxml2/#{file}.tar.gz" Dir.chdir('tmp/cross/download') do sh "wget #{url} || curl -O #{url}" sh "tar zxvf #{file}.tar.gz" end Dir.chdir t.name do # FIXME: need to make the host dynamic sh "CFLAGS='-DIN_LIBXML' ./configure --host=#{HOST} --target=#{TARGET} --enable-static --disable-shared --prefix=#{CROSS_DIR} --with-zlib=#{CROSS_DIR} --with-iconv=#{CROSS_DIR} --without-python --without-readline" end end file 'tmp/cross/bin/xml2-config' => "tmp/cross/download/#{LIBXML}" do |t| Dir.chdir t.prerequisites.first do sh 'make LDFLAGS="-avoid-version"' sh 'make install' end end ### End build libxml2 ### ### Build libxslt ### file "tmp/cross/download/#{LIBXSLT}" do |t| FileUtils.mkdir_p('tmp/cross/download') file = LIBXSLT url = "ftp://ftp.xmlsoft.org/libxml2/#{file}.tar.gz" Dir.chdir('tmp/cross/download') do sh "wget #{url} || curl -O #{url}" sh "tar zxvf #{file}.tar.gz" end Dir.chdir t.name do # FIXME: need to make the host dynamic sh "CFLAGS='-DIN_LIBXML' ./configure --host=#{HOST} --target=#{TARGET} --enable-static --disable-shared --prefix=#{CROSS_DIR} --with-libxml-prefix=#{CROSS_DIR} --without-python --without-crypto" end end file 'tmp/cross/bin/xslt-config' => "tmp/cross/download/#{LIBXSLT}" do |t| Dir.chdir t.prerequisites.first do sh 'make LDFLAGS="-avoid-version"' sh 'make install' end end ### End build libxslt ### file 'lib/nokogiri/nokogiri.rb' => 'cross:check' do File.open("lib/#{HOE.name}/#{HOE.name}.rb", 'wb') do |f| f.write <<-eoruby require "#{HOE.name}/\#{RUBY_VERSION.sub(/\\.\\d+$/, '')}/#{HOE.name}" eoruby end end namespace :cross do task :iconv => 'tmp/cross/bin/iconv.exe' task :zlib => 'tmp/cross/lib/libz.a' task :libxml2 => ['cross:zlib', 'cross:iconv', 'tmp/cross/bin/xml2-config'] task :libxslt => ['cross:libxml2', 'tmp/cross/bin/xslt-config'] task :check => ["cross:libxslt"] do unless File.directory?(RAKE_COMPILER_PKGCONFIG) raise RuntimeError.new("looks like rake-compiler changed where pkgconfig info is kept. (#{RAKE_COMPILER_PKGCONFIG})") end end task :copy_dlls do Dir['tmp/cross/bin/*.dll'].each do |file| cp file, "ext/nokogiri" end end task :file_list => 'cross:copy_dlls' do HOE.spec.extensions = [] HOE.spec.files += Dir["lib/#{HOE.name}/#{HOE.name}.rb"] HOE.spec.files += Dir["lib/#{HOE.name}/1.{8,9}/#{HOE.name}.so"] HOE.spec.files += Dir["ext/nokogiri/*.dll"] end end CLOBBER.include("lib/nokogiri/nokogiri.{so,dylib,rb,bundle}") CLOBBER.include("lib/nokogiri/1.{8,9}") CLOBBER.include("ext/nokogiri/*.dll") if Rake::Task.task_defined?(:cross) Rake::Task[:cross].prerequisites << "lib/nokogiri/nokogiri.rb" Rake::Task[:cross].prerequisites << "cross:file_list" end desc "build a windows gem without all the ceremony." task "gem:windows" do rake_compiler_config = YAML.load_file("#{ENV['HOME']}/.rake-compiler/config.yml") # check that rake-compiler config contains the right patchlevels of 1.8.6 and 1.9.1. see #279. ["1.8.6-p383", "1.9.1-p243"].each do |version| majmin, patchlevel = version.split("-") rbconfig = "rbconfig-#{majmin}" unless rake_compiler_config.key?(rbconfig) && rake_compiler_config[rbconfig] =~ /-#{patchlevel}/ raise "rake-compiler '#{rbconfig}' not #{patchlevel}. try running 'rake-compiler cross-ruby VERSION=#{version}'" end end # verify that --export-all is in the 1.9.1 rbconfig. see #279,#374,#375. rbconfig_191 = rake_compiler_config["rbconfig-1.9.1"] raise "rbconfig #{rbconfig_191} needs --export-all in its DLDFLAGS value" if File.read(rbconfig_191).grep(/CONFIG\["DLDFLAGS"\].*--export-all/).empty? system("env PKG_CONFIG_PATH=#{RAKE_COMPILER_PKGCONFIG} RUBY_CC_VERSION=1.8.6:1.9.1 rake cross native gem") || raise("build failed!") end
MitjaBezensek/shouldly
lib/gems/gems/nokogiri-1.4.4.1-x86-mingw32/tasks/cross_compile.rb
Ruby
bsd-3-clause
6,069
module.exports = { parser: 'sugarss', plugins: { 'postcss-import': {}, 'cssnext': {}, 'autoprefixer': {}, 'cssnano': {}, }, }
mattvoss/classes
webpack/postcss.config.js
JavaScript
bsd-3-clause
147
/* * Copyright (C) 2019-2020 Red Hat, Inc. * * Written By: Gal Hammer <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met : * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and / or other materials provided with the distribution. * 3. Neither the names of the copyright holders nor the names of their contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #pragma once #include "fuse.h" typedef struct { struct fuse_in_header hdr; struct fuse_init_in init; } FUSE_INIT_IN; typedef struct { struct fuse_out_header hdr; struct fuse_init_out init; } FUSE_INIT_OUT; typedef struct { struct fuse_in_header hdr; char name[MAX_PATH]; } FUSE_LOOKUP_IN; typedef struct { struct fuse_out_header hdr; struct fuse_entry_out entry; } FUSE_LOOKUP_OUT; typedef struct { struct fuse_in_header hdr; struct fuse_getattr_in getattr; } FUSE_GETATTR_IN, *PFUSE_GETATTR_IN; typedef struct { struct fuse_out_header hdr; struct fuse_attr_out attr; } FUSE_GETATTR_OUT, *PFUSE_GETATTR_OUT; typedef struct { struct fuse_in_header hdr; struct fuse_setattr_in setattr; } FUSE_SETATTR_IN, *PFUSE_SETATTR_IN; typedef struct { struct fuse_out_header hdr; struct fuse_attr_out attr; } FUSE_SETATTR_OUT, *PFUSE_SETATTR_OUT; typedef struct { struct fuse_in_header hdr; } FUSE_STATFS_IN, *PFUSE_STATFS_IN; typedef struct { struct fuse_out_header hdr; struct fuse_statfs_out statfs; } FUSE_STATFS_OUT, *PFUSE_STATFS_OUT; typedef struct { struct fuse_in_header hdr; struct fuse_create_in create; char name[MAX_PATH]; } FUSE_CREATE_IN, *PFUSE_CREATE_IN; typedef struct { struct fuse_out_header hdr; struct fuse_entry_out entry; struct fuse_open_out open; } FUSE_CREATE_OUT, *PFUSE_CREATE_OUT; typedef struct { struct fuse_in_header hdr; struct fuse_open_in open; } FUSE_OPEN_IN, *PFUSE_OPEN_IN; typedef struct { struct fuse_out_header hdr; struct fuse_open_out open; } FUSE_OPEN_OUT, *PFUSE_OPEN_OUT; typedef struct { struct fuse_in_header hdr; struct fuse_read_in read; } FUSE_READ_IN, *PFUSE_READ_IN; typedef struct { struct fuse_out_header hdr; char buf[]; } FUSE_READ_OUT, *PFUSE_READ_OUT; typedef struct { struct fuse_in_header hdr; struct fuse_release_in release; } FUSE_RELEASE_IN, *PFUSE_RELEASE_IN; typedef struct { struct fuse_out_header hdr; } FUSE_RELEASE_OUT, *PFUSE_RELEASE_OUT; typedef struct { struct fuse_in_header hdr; struct fuse_write_in write; char buf[]; } FUSE_WRITE_IN, *PFUSE_WRITE_IN; typedef struct { struct fuse_out_header hdr; struct fuse_write_out write; } FUSE_WRITE_OUT, *PFUSE_WRITE_OUT; typedef struct { struct fuse_in_header hdr; struct fuse_flush_in flush; } FUSE_FLUSH_IN; typedef struct { struct fuse_out_header hdr; } FUSE_FLUSH_OUT; typedef struct { struct fuse_in_header hdr; char name[MAX_PATH]; } FUSE_UNLINK_IN; typedef struct { struct fuse_out_header hdr; } FUSE_UNLINK_OUT; typedef struct { struct fuse_in_header hdr; struct fuse_rename_in rename; char names[]; } FUSE_RENAME_IN; typedef struct { struct fuse_in_header hdr; struct fuse_rename2_in rename; char names[]; } FUSE_RENAME2_IN; typedef struct { struct fuse_out_header hdr; } FUSE_RENAME_OUT; typedef struct { struct fuse_in_header hdr; struct fuse_mkdir_in mkdir; char name[MAX_PATH]; } FUSE_MKDIR_IN; typedef struct { struct fuse_out_header hdr; struct fuse_entry_out entry; } FUSE_MKDIR_OUT; typedef struct { struct fuse_in_header hdr; struct fuse_fallocate_in falloc; } FUSE_FALLOCATE_IN; typedef struct { struct fuse_out_header hdr; } FUSE_FALLOCATE_OUT; typedef struct { struct fuse_in_header hdr; } FUSE_READLINK_IN, *PFUSE_READLINK_IN; typedef struct { struct fuse_out_header hdr; char name[MAX_PATH]; } FUSE_READLINK_OUT, *PFUSE_READLINK_OUT; typedef struct { struct fuse_in_header hdr; char names[]; } FUSE_SYMLINK_IN; typedef struct { struct fuse_out_header hdr; struct fuse_entry_out entry; } FUSE_SYMLINK_OUT; typedef struct { struct fuse_in_header hdr; struct fuse_forget_in forget; } FUSE_FORGET_IN, * PFUSE_FORGET_IN; typedef struct { struct fuse_out_header hdr; } FUSE_FORGET_OUT, * PFUSE_FORGET_OUT;
virtio-win/kvm-guest-drivers-windows
viofs/svc/fusereq.h
C
bsd-3-clause
5,924
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from std_msgs/Int32.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class Int32(genpy.Message): _md5sum = "da5909fbe378aeaf85e547e830cc1bb7" _type = "std_msgs/Int32" _has_header = False #flag to mark the presence of a Header object _full_text = """int32 data """ __slots__ = ['data'] _slot_types = ['int32'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: data :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(Int32, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.data is None: self.data = 0 else: self.data = 0 def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: buff.write(_struct_i.pack(self.data)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ try: end = 0 start = end end += 4 (self.data,) = _struct_i.unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: buff.write(_struct_i.pack(self.data)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ try: end = 0 start = end end += 4 (self.data,) = _struct_i.unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I _struct_i = struct.Struct("<i")
MangoMangoDevelopment/neptune
lib/std_msgs-0.5.10/std_msgs/msg/_Int32.py
Python
bsd-3-clause
3,255
// +build startxref package main var pdfOld string = `%PDF-1.1 %¥±ë 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 144] >> endobj 3 0 obj << /Type /Page /Parent 2 0 R /Resources << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >> >> >> /Contents 4 0 R >> endobj 4 0 obj << /Length 55 >> stream BT /F1 18 Tf 0 0 Td (Hello World) Tj ET endstream endobj xref 0 5 0000000000 65535 f 0000000018 00000 n 0000000077 00000 n 0000000178 00000 n 0000000457 00000 n trailer << /Root 1 0 R /Size 5 >> startxref RABBITS! %%EOF ` var pdfNew string = `%PDF-1.1 %¥±ë 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 144] >> endobj 3 0 obj << /Type /Page /Parent 2 0 R /Resources << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >> >> >> /Contents 4 0 R >> endobj 4 0 obj << /Length 55 >> stream BT /F1 18 Tf 0 0 Td (Hello World) Tj ET endstream endobj xref 0 5 0000000000 65535 f 0000000018 00000 n 0000000077 00000 n 0000000178 00000 n 0000000457 00000 n trailer << /Root 1 0 R /Size 5 >> startxref 565 %%EOF ` var fragNoXref string = `endstream endobj 0 5 0000000000 65535 f 0000000018 00000 n 0000000077 00000 n 0000000178 00000 n 0000000457 00000 n trailer << /Root 1 0 R /Size 5 >> startxref RABBITS! %%EOF ` var fragNoStartxref string = `endstream endobj xref 0 5 0000000000 65535 f 0000000018 00000 n 0000000077 00000 n 0000000178 00000 n 0000000457 00000 n trailer << /Root 1 0 R /Size 5 >> RABBITS! %%EOF ` var fragEmpty string = "" var fragNeither = "I am the very model of a modern Major-General!" var doubleXrefs string = `%PDF-1.1 %¥±ë 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 144] >> endobj 3 0 obj << /Type /Page /Parent 2 0 R /Resources << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >> >> >> /Contents 4 0 R >> endobj xref 0 5 0000000000 65535 f 0000000018 00000 n 0000000077 00000 n 0000000178 00000 n 0000000457 00000 n trailer << /Root 1 0 R /Size 5 >> startxref RABBITS! 4 0 obj << /Length 55 >> stream BT /F1 18 Tf 0 0 Td (Hello World) Tj ET endstream endobj xref 0 5 0000000000 65535 f 0000000018 00000 n 0000000077 00000 n 0000000178 00000 n 0000000457 00000 n trailer << /Root 1 0 R /Size 5 >> startxref RABBITS! %%EOF ` var doubleXrefsFix string = `%PDF-1.1 %¥±ë 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 144] >> endobj 3 0 obj << /Type /Page /Parent 2 0 R /Resources << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >> >> >> /Contents 4 0 R >> endobj xref 0 5 0000000000 65535 f 0000000018 00000 n 0000000077 00000 n 0000000178 00000 n 0000000457 00000 n trailer << /Root 1 0 R /Size 5 >> startxref RABBITS! 4 0 obj << /Length 55 >> stream BT /F1 18 Tf 0 0 Td (Hello World) Tj ET endstream endobj xref 0 5 0000000000 65535 f 0000000018 00000 n 0000000077 00000 n 0000000178 00000 n 0000000457 00000 n trailer << /Root 1 0 R /Size 5 >> startxref 739 %%EOF `
zhuyue1314/aflfix
test_startxref.go
GO
bsd-3-clause
3,992
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE427_Uncontrolled_Search_Path_Element__char_listen_socket_54a.c Label Definition File: CWE427_Uncontrolled_Search_Path_Element.label.xml Template File: sources-sink-54a.tmpl.c */ /* * @description * CWE: 427 Uncontrolled Search Path Element * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Use a hardcoded path * Sink: * BadSink : Set the environment variable * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define NEW_PATH "%SystemRoot%\\system32" #define PUTENV _putenv #else #define NEW_PATH "/bin" #define PUTENV putenv #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define LISTEN_BACKLOG 5 #ifndef OMITBAD /* bad function declaration */ void CWE427_Uncontrolled_Search_Path_Element__char_listen_socket_54b_badSink(char * data); void CWE427_Uncontrolled_Search_Path_Element__char_listen_socket_54_bad() { char * data; char dataBuffer[250] = "PATH="; data = dataBuffer; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; char *replace; SOCKET listenSocket = INVALID_SOCKET; SOCKET acceptSocket = INVALID_SOCKET; size_t dataLen = strlen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a listen socket */ listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = INADDR_ANY; service.sin_port = htons(TCP_PORT); if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) { break; } acceptSocket = accept(listenSocket, NULL, NULL); if (acceptSocket == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed */ recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (250 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(char)] = '\0'; /* Eliminate CRLF */ replace = strchr(data, '\r'); if (replace) { *replace = '\0'; } replace = strchr(data, '\n'); if (replace) { *replace = '\0'; } } while (0); if (listenSocket != INVALID_SOCKET) { CLOSE_SOCKET(listenSocket); } if (acceptSocket != INVALID_SOCKET) { CLOSE_SOCKET(acceptSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } CWE427_Uncontrolled_Search_Path_Element__char_listen_socket_54b_badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declaration */ void CWE427_Uncontrolled_Search_Path_Element__char_listen_socket_54b_goodG2BSink(char * data); /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { char * data; char dataBuffer[250] = "PATH="; data = dataBuffer; /* FIX: Set the path as the "system" path */ strcat(data, NEW_PATH); CWE427_Uncontrolled_Search_Path_Element__char_listen_socket_54b_goodG2BSink(data); } void CWE427_Uncontrolled_Search_Path_Element__char_listen_socket_54_good() { goodG2B(); } #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()..."); CWE427_Uncontrolled_Search_Path_Element__char_listen_socket_54_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE427_Uncontrolled_Search_Path_Element__char_listen_socket_54_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE427_Uncontrolled_Search_Path_Element/CWE427_Uncontrolled_Search_Path_Element__char_listen_socket_54a.c
C
bsd-3-clause
5,575
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_22) on Wed Mar 02 16:45:58 EST 2011 --> <TITLE> Uses of Class gov.nih.nci.cabig.caaers.domain.repository.DeviceRepository </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Class gov.nih.nci.cabig.caaers.domain.repository.DeviceRepository"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&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;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?gov/nih/nci/cabig/caaers/domain/repository/class-use/DeviceRepository.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DeviceRepository.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> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>gov.nih.nci.cabig.caaers.domain.repository.DeviceRepository</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#gov.nih.nci.cabig.caaers.service.migrator"><B>gov.nih.nci.cabig.caaers.service.migrator</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#gov.nih.nci.cabig.caaers.web.admin"><B>gov.nih.nci.cabig.caaers.web.admin</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#gov.nih.nci.cabig.caaers.web.search"><B>gov.nih.nci.cabig.caaers.web.search</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#gov.nih.nci.cabig.caaers.web.study"><B>gov.nih.nci.cabig.caaers.web.study</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="gov.nih.nci.cabig.caaers.service.migrator"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A> in <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/service/migrator/package-summary.html">gov.nih.nci.cabig.caaers.service.migrator</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/service/migrator/package-summary.html">gov.nih.nci.cabig.caaers.service.migrator</A> that return <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></CODE></FONT></TD> <TD><CODE><B>StudyDeviceMigrator.</B><B><A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/service/migrator/StudyDeviceMigrator.html#getDeviceRepository()">getDeviceRepository</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/service/migrator/package-summary.html">gov.nih.nci.cabig.caaers.service.migrator</A> with parameters of type <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B>StudyDeviceMigrator.</B><B><A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/service/migrator/StudyDeviceMigrator.html#setDeviceRepository(gov.nih.nci.cabig.caaers.domain.repository.DeviceRepository)">setDeviceRepository</A></B>(<A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A>&nbsp;deviceRepository)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="gov.nih.nci.cabig.caaers.web.admin"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A> in <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/admin/package-summary.html">gov.nih.nci.cabig.caaers.web.admin</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/admin/package-summary.html">gov.nih.nci.cabig.caaers.web.admin</A> declared as <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;<A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></CODE></FONT></TD> <TD><CODE><B>DeviceController.</B><B><A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/admin/DeviceController.html#deviceRepository">deviceRepository</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/admin/package-summary.html">gov.nih.nci.cabig.caaers.web.admin</A> that return <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></CODE></FONT></TD> <TD><CODE><B>DeviceController.</B><B><A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/admin/DeviceController.html#getDeviceRepository()">getDeviceRepository</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/admin/package-summary.html">gov.nih.nci.cabig.caaers.web.admin</A> with parameters of type <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B>DeviceController.</B><B><A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/admin/DeviceController.html#setDeviceRepository(gov.nih.nci.cabig.caaers.domain.repository.DeviceRepository)">setDeviceRepository</A></B>(<A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A>&nbsp;deviceRepository)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="gov.nih.nci.cabig.caaers.web.search"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A> in <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/search/package-summary.html">gov.nih.nci.cabig.caaers.web.search</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/search/package-summary.html">gov.nih.nci.cabig.caaers.web.search</A> that return <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></CODE></FONT></TD> <TD><CODE><B>SearchStudyAjaxFacade.</B><B><A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/search/SearchStudyAjaxFacade.html#getDeviceRepository()">getDeviceRepository</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/search/package-summary.html">gov.nih.nci.cabig.caaers.web.search</A> with parameters of type <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B>SearchStudyAjaxFacade.</B><B><A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/search/SearchStudyAjaxFacade.html#setDeviceRepository(gov.nih.nci.cabig.caaers.domain.repository.DeviceRepository)">setDeviceRepository</A></B>(<A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A>&nbsp;deviceRepository)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="gov.nih.nci.cabig.caaers.web.study"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A> in <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/study/package-summary.html">gov.nih.nci.cabig.caaers.web.study</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/study/package-summary.html">gov.nih.nci.cabig.caaers.web.study</A> that return <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></CODE></FONT></TD> <TD><CODE><B>CreateStudyAjaxFacade.</B><B><A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/study/CreateStudyAjaxFacade.html#getDeviceRepository()">getDeviceRepository</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/study/package-summary.html">gov.nih.nci.cabig.caaers.web.study</A> with parameters of type <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B>CreateStudyAjaxFacade.</B><B><A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/web/study/CreateStudyAjaxFacade.html#setDeviceRepository(gov.nih.nci.cabig.caaers.domain.repository.DeviceRepository)">setDeviceRepository</A></B>(<A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository">DeviceRepository</A>&nbsp;deviceRepository)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <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="navbar_bottom_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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/domain/repository/DeviceRepository.html" title="class in gov.nih.nci.cabig.caaers.domain.repository"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&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;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?gov/nih/nci/cabig/caaers/domain/repository/class-use/DeviceRepository.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DeviceRepository.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> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
NCIP/caaers
caAERS/software/docs/gov/nih/nci/cabig/caaers/domain/repository/class-use/DeviceRepository.html
HTML
bsd-3-clause
20,405
package org.mafagafogigante.dungeon.entity.items; import org.mafagafogigante.dungeon.entity.Weight; interface LimitedInventory { int getItemLimit(); Weight getWeightLimit(); }
ffurkanhas/dungeon
src/main/java/org/mafagafogigante/dungeon/entity/items/LimitedInventory.java
Java
bsd-3-clause
185
/* Copyright 2021 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /** * @file * * @brief Backend API for TCS3400 emulator */ #ifndef __EMUL_TCS3400_H #define __EMUL_TCS3400_H #include <drivers/emul.h> #include <drivers/i2c.h> #include <drivers/i2c_emul.h> /** * @brief TCS3400 emulator backend API * @defgroup tcs_emul TCS3400 emulator * @{ * * TCS3400 emulator supports responses to all write and read I2C messages. * Light sensor data registers are obtained from internal emulator state, gain * and acquisition time. Application may alter emulator state: * * - define a devicetree overlay file to set which inadvisable driver behaviour * should be treated as error and emulated device ID and revision * - call @ref tcs_emul_set_reg and @ref tcs_emul_get_reg to set and get value * of TCS3400 registers * - call @ref tcs_emul_set_val and @ref tcs_emul_set_val to set and get * light sensor value * - call tcs_emul_set_err_* to change emulator behaviour on inadvisable driver * behaviour * - call functions from emul_common_i2c.h to setup custom handlers for I2C * messages */ /** * Maximum number of integration cycles (when ATIME is zero). Value read from * sensor is proportional to number of integration cycles, e.g. with constant * light, value obtainded with 128 cycles will be two times smaller than value * obtained with 256 cycles. */ #define TCS_EMUL_MAX_CYCLES 256 /** * Maximum gain supported by TCS3400. Value read from sensor is multiplied by * gain selected in CONTROL register. */ #define TCS_EMUL_MAX_GAIN 64 /** * Emulator units are value returned with gain x64 and 256 integration cycles. * Max value is 1024 returned when gain is x1 and 1 integration cycle. Max value * represented in emulator units is 1024 * 64 * 256 */ #define TCS_EMUL_MAX_VALUE (1024 * TCS_EMUL_MAX_GAIN * TCS_EMUL_MAX_CYCLES) /** Axis argument used in @ref tcs_emul_set_val @ref tcs_emul_get_val */ enum tcs_emul_axis { TCS_EMUL_R, TCS_EMUL_G, TCS_EMUL_B, TCS_EMUL_C, TCS_EMUL_IR, }; /** * Emulator saves only those registers in memory. IR select is stored sparately * and other registers are write only. */ #define TCS_EMUL_FIRST_REG TCS_I2C_ENABLE #define TCS_EMUL_LAST_REG TCS_I2C_BDATAH #define TCS_EMUL_REG_COUNT (TCS_EMUL_LAST_REG - TCS_EMUL_FIRST_REG + 1) /** * @brief Get pointer to TCS3400 emulator using device tree order number. * * @param ord Device tree order number obtained from DT_DEP_ORD macro * * @return Pointer to TCS3400 emulator */ struct i2c_emul *tcs_emul_get(int ord); /** * @brief Set value of given register of TCS3400 * * @param emul Pointer to TCS3400 emulator * @param reg Register address which value will be changed * @param val New value of the register */ void tcs_emul_set_reg(struct i2c_emul *emul, int reg, uint8_t val); /** * @brief Get value of given register of TCS3400 * * @param emul Pointer to TCS3400 emulator * @param reg Register address * * @return Value of the register */ uint8_t tcs_emul_get_reg(struct i2c_emul *emul, int reg); /** * @brief Get internal value of light sensor for given axis * * @param emul Pointer to TCS3400 emulator * @param axis Axis to access * * @return Value of given axis with gain x64 and 256 integration cycles */ int tcs_emul_get_val(struct i2c_emul *emul, enum tcs_emul_axis axis); /** * @brief Set internal value of light sensor for given axis * * @param emul Pointer to TCS3400 emulator * @param axis Axis to access * @param val New value of light sensor for given axis with gain x64 and * 256 integration cycles */ void tcs_emul_set_val(struct i2c_emul *emul, enum tcs_emul_axis axis, int val); /** * @brief Set if error should be generated when read only register is being * written * * @param emul Pointer to TCS3400 emulator * @param set Check for this error */ void tcs_emul_set_err_on_ro_write(struct i2c_emul *emul, bool set); /** * @brief Set if error should be generated when reserved bits of register are * not set to 0 on write I2C message * * @param emul Pointer to TCS3400 emulator * @param set Check for this error */ void tcs_emul_set_err_on_rsvd_write(struct i2c_emul *emul, bool set); /** * @brief Set if error should be generated when MSB register is accessed before * LSB register * * @param emul Pointer to TCS3400 emulator * @param set Check for this error */ void tcs_emul_set_err_on_msb_first(struct i2c_emul *emul, bool set); /** * @} */ #endif /* __EMUL_TCS3400_H */
coreboot/chrome-ec
zephyr/include/emul/emul_tcs3400.h
C
bsd-3-clause
4,627
--[er]test nullif with three operands select nullif(10, 10, 30) from db_root order by 1;
CUBRID/cubrid-testcases
sql/_04_operator_function/_07_case_func/_001_nullif_colaesce/cases/1014.sql
SQL
bsd-3-clause
88
/** * uri.c: set of generic URI related routines * * Reference: RFCs 2396, 2732 and 2373 * * See Copyright for the status of this software. * * [email protected] */ #define IN_LIBXML #include "libxml.h" #include <string.h> #include <libxml/xmlmemory.h> #include <libxml/uri.h> #include <libxml/globals.h> #include <libxml/xmlerror.h> /************************************************************************ * * * Macros to differentiate various character type * * directly extracted from RFC 2396 * * * ************************************************************************/ /* * alpha = lowalpha | upalpha */ #define IS_ALPHA(x) (IS_LOWALPHA(x) || IS_UPALPHA(x)) /* * lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | * "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | * "u" | "v" | "w" | "x" | "y" | "z" */ #define IS_LOWALPHA(x) (((x) >= 'a') && ((x) <= 'z')) /* * upalpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | * "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | * "U" | "V" | "W" | "X" | "Y" | "Z" */ #define IS_UPALPHA(x) (((x) >= 'A') && ((x) <= 'Z')) #ifdef IS_DIGIT #undef IS_DIGIT #endif /* * digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" */ #define IS_DIGIT(x) (((x) >= '0') && ((x) <= '9')) /* * alphanum = alpha | digit */ #define IS_ALPHANUM(x) (IS_ALPHA(x) || IS_DIGIT(x)) /* * hex = digit | "A" | "B" | "C" | "D" | "E" | "F" | * "a" | "b" | "c" | "d" | "e" | "f" */ #define IS_HEX(x) ((IS_DIGIT(x)) || (((x) >= 'a') && ((x) <= 'f')) || \ (((x) >= 'A') && ((x) <= 'F'))) /* * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" */ #define IS_MARK(x) (((x) == '-') || ((x) == '_') || ((x) == '.') || \ ((x) == '!') || ((x) == '~') || ((x) == '*') || ((x) == '\'') || \ ((x) == '(') || ((x) == ')')) /* * reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," | * "[" | "]" */ #define IS_RESERVED(x) (((x) == ';') || ((x) == '/') || ((x) == '?') || \ ((x) == ':') || ((x) == '@') || ((x) == '&') || ((x) == '=') || \ ((x) == '+') || ((x) == '$') || ((x) == ',') || ((x) == '[') || \ ((x) == ']')) /* * unreserved = alphanum | mark */ #define IS_UNRESERVED(x) (IS_ALPHANUM(x) || IS_MARK(x)) /* * escaped = "%" hex hex */ #define IS_ESCAPED(p) ((*(p) == '%') && (IS_HEX((p)[1])) && \ (IS_HEX((p)[2]))) /* * uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" | * "&" | "=" | "+" | "$" | "," */ #define IS_URIC_NO_SLASH(p) ((IS_UNRESERVED(*(p))) || (IS_ESCAPED(p)) ||\ ((*(p) == ';')) || ((*(p) == '?')) || ((*(p) == ':')) ||\ ((*(p) == '@')) || ((*(p) == '&')) || ((*(p) == '=')) ||\ ((*(p) == '+')) || ((*(p) == '$')) || ((*(p) == ','))) /* * pchar = unreserved | escaped | ":" | "@" | "&" | "=" | "+" | "$" | "," */ #define IS_PCHAR(p) ((IS_UNRESERVED(*(p))) || (IS_ESCAPED(p)) || \ ((*(p) == ':')) || ((*(p) == '@')) || ((*(p) == '&')) ||\ ((*(p) == '=')) || ((*(p) == '+')) || ((*(p) == '$')) ||\ ((*(p) == ','))) /* * rel_segment = 1*( unreserved | escaped | * ";" | "@" | "&" | "=" | "+" | "$" | "," ) */ #define IS_SEGMENT(p) ((IS_UNRESERVED(*(p))) || (IS_ESCAPED(p)) || \ ((*(p) == ';')) || ((*(p) == '@')) || ((*(p) == '&')) || \ ((*(p) == '=')) || ((*(p) == '+')) || ((*(p) == '$')) || \ ((*(p) == ','))) /* * scheme = alpha *( alpha | digit | "+" | "-" | "." ) */ #define IS_SCHEME(x) ((IS_ALPHA(x)) || (IS_DIGIT(x)) || \ ((x) == '+') || ((x) == '-') || ((x) == '.')) /* * reg_name = 1*( unreserved | escaped | "$" | "," | * ";" | ":" | "@" | "&" | "=" | "+" ) */ #define IS_REG_NAME(p) ((IS_UNRESERVED(*(p))) || (IS_ESCAPED(p)) || \ ((*(p) == '$')) || ((*(p) == ',')) || ((*(p) == ';')) || \ ((*(p) == ':')) || ((*(p) == '@')) || ((*(p) == '&')) || \ ((*(p) == '=')) || ((*(p) == '+'))) /* * userinfo = *( unreserved | escaped | ";" | ":" | "&" | "=" | * "+" | "$" | "," ) */ #define IS_USERINFO(p) ((IS_UNRESERVED(*(p))) || (IS_ESCAPED(p)) || \ ((*(p) == ';')) || ((*(p) == ':')) || ((*(p) == '&')) || \ ((*(p) == '=')) || ((*(p) == '+')) || ((*(p) == '$')) || \ ((*(p) == ','))) /* * uric = reserved | unreserved | escaped */ #define IS_URIC(p) ((IS_UNRESERVED(*(p))) || (IS_ESCAPED(p)) || \ (IS_RESERVED(*(p)))) /* * unwise = "{" | "}" | "|" | "\" | "^" | "`" */ #define IS_UNWISE(p) \ (((*(p) == '{')) || ((*(p) == '}')) || ((*(p) == '|')) || \ ((*(p) == '\\')) || ((*(p) == '^')) || ((*(p) == '[')) || \ ((*(p) == ']')) || ((*(p) == '`'))) /* * Skip to next pointer char, handle escaped sequences */ #define NEXT(p) ((*p == '%')? p += 3 : p++) /* * Productions from the spec. * * authority = server | reg_name * reg_name = 1*( unreserved | escaped | "$" | "," | * ";" | ":" | "@" | "&" | "=" | "+" ) * * path = [ abs_path | opaque_part ] */ #define STRNDUP(s, n) (char *) xmlStrndup((const xmlChar *)(s), (n)) /************************************************************************ * * * Generic URI structure functions * * * ************************************************************************/ /** * xmlCreateURI: * * Simply creates an empty xmlURI * * Returns the new structure or NULL in case of error */ xmlURIPtr xmlCreateURI(void) { xmlURIPtr ret; ret = (xmlURIPtr) xmlMalloc(sizeof(xmlURI)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlCreateURI: out of memory\n"); return(NULL); } memset(ret, 0, sizeof(xmlURI)); return(ret); } /** * xmlSaveUri: * @uri: pointer to an xmlURI * * Save the URI as an escaped string * * Returns a new string (to be deallocated by caller) */ xmlChar * xmlSaveUri(xmlURIPtr uri) { xmlChar *ret = NULL; const char *p; int len; int max; if (uri == NULL) return(NULL); max = 80; ret = (xmlChar *) xmlMallocAtomic((max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } len = 0; if (uri->scheme != NULL) { p = uri->scheme; while (*p != 0) { if (len >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } ret[len++] = *p++; } if (len >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } ret[len++] = ':'; } if (uri->opaque != NULL) { p = uri->opaque; while (*p != 0) { if (len + 3 >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } if (IS_RESERVED(*(p)) || IS_UNRESERVED(*(p))) ret[len++] = *p++; else { int val = *(unsigned char *)p++; int hi = val / 0x10, lo = val % 0x10; ret[len++] = '%'; ret[len++] = hi + (hi > 9? 'A'-10 : '0'); ret[len++] = lo + (lo > 9? 'A'-10 : '0'); } } } else { if (uri->server != NULL) { if (len + 3 >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } ret[len++] = '/'; ret[len++] = '/'; if (uri->user != NULL) { p = uri->user; while (*p != 0) { if (len + 3 >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } if ((IS_UNRESERVED(*(p))) || ((*(p) == ';')) || ((*(p) == ':')) || ((*(p) == '&')) || ((*(p) == '=')) || ((*(p) == '+')) || ((*(p) == '$')) || ((*(p) == ','))) ret[len++] = *p++; else { int val = *(unsigned char *)p++; int hi = val / 0x10, lo = val % 0x10; ret[len++] = '%'; ret[len++] = hi + (hi > 9? 'A'-10 : '0'); ret[len++] = lo + (lo > 9? 'A'-10 : '0'); } } if (len + 3 >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } ret[len++] = '@'; } p = uri->server; while (*p != 0) { if (len >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } ret[len++] = *p++; } if (uri->port > 0) { if (len + 10 >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } len += snprintf((char *) &ret[len], max - len, ":%d", uri->port); } } else if (uri->authority != NULL) { if (len + 3 >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } ret[len++] = '/'; ret[len++] = '/'; p = uri->authority; while (*p != 0) { if (len + 3 >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } if ((IS_UNRESERVED(*(p))) || ((*(p) == '$')) || ((*(p) == ',')) || ((*(p) == ';')) || ((*(p) == ':')) || ((*(p) == '@')) || ((*(p) == '&')) || ((*(p) == '=')) || ((*(p) == '+'))) ret[len++] = *p++; else { int val = *(unsigned char *)p++; int hi = val / 0x10, lo = val % 0x10; ret[len++] = '%'; ret[len++] = hi + (hi > 9? 'A'-10 : '0'); ret[len++] = lo + (lo > 9? 'A'-10 : '0'); } } } else if (uri->scheme != NULL) { if (len + 3 >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } ret[len++] = '/'; ret[len++] = '/'; } if (uri->path != NULL) { p = uri->path; while (*p != 0) { if (len + 3 >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } if ((IS_UNRESERVED(*(p))) || ((*(p) == '/')) || ((*(p) == ';')) || ((*(p) == '@')) || ((*(p) == '&')) || ((*(p) == '=')) || ((*(p) == '+')) || ((*(p) == '$')) || ((*(p) == ','))) ret[len++] = *p++; else { int val = *(unsigned char *)p++; int hi = val / 0x10, lo = val % 0x10; ret[len++] = '%'; ret[len++] = hi + (hi > 9? 'A'-10 : '0'); ret[len++] = lo + (lo > 9? 'A'-10 : '0'); } } } if (uri->query != NULL) { if (len + 3 >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } ret[len++] = '?'; p = uri->query; while (*p != 0) { if (len + 3 >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } if ((IS_UNRESERVED(*(p))) || (IS_RESERVED(*(p)))) ret[len++] = *p++; else { int val = *(unsigned char *)p++; int hi = val / 0x10, lo = val % 0x10; ret[len++] = '%'; ret[len++] = hi + (hi > 9? 'A'-10 : '0'); ret[len++] = lo + (lo > 9? 'A'-10 : '0'); } } } } if (uri->fragment != NULL) { if (len + 3 >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } ret[len++] = '#'; p = uri->fragment; while (*p != 0) { if (len + 3 >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } if ((IS_UNRESERVED(*(p))) || (IS_RESERVED(*(p)))) ret[len++] = *p++; else { int val = *(unsigned char *)p++; int hi = val / 0x10, lo = val % 0x10; ret[len++] = '%'; ret[len++] = hi + (hi > 9? 'A'-10 : '0'); ret[len++] = lo + (lo > 9? 'A'-10 : '0'); } } } if (len >= max) { max *= 2; ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlSaveUri: out of memory\n"); return(NULL); } } ret[len++] = 0; return(ret); } /** * xmlPrintURI: * @stream: a FILE* for the output * @uri: pointer to an xmlURI * * Prints the URI in the stream @stream. */ void xmlPrintURI(FILE *stream, xmlURIPtr uri) { xmlChar *out; out = xmlSaveUri(uri); if (out != NULL) { fprintf(stream, "%s", (char *) out); xmlFree(out); } } /** * xmlCleanURI: * @uri: pointer to an xmlURI * * Make sure the xmlURI struct is free of content */ static void xmlCleanURI(xmlURIPtr uri) { if (uri == NULL) return; if (uri->scheme != NULL) xmlFree(uri->scheme); uri->scheme = NULL; if (uri->server != NULL) xmlFree(uri->server); uri->server = NULL; if (uri->user != NULL) xmlFree(uri->user); uri->user = NULL; if (uri->path != NULL) xmlFree(uri->path); uri->path = NULL; if (uri->fragment != NULL) xmlFree(uri->fragment); uri->fragment = NULL; if (uri->opaque != NULL) xmlFree(uri->opaque); uri->opaque = NULL; if (uri->authority != NULL) xmlFree(uri->authority); uri->authority = NULL; if (uri->query != NULL) xmlFree(uri->query); uri->query = NULL; } /** * xmlFreeURI: * @uri: pointer to an xmlURI * * Free up the xmlURI struct */ void xmlFreeURI(xmlURIPtr uri) { if (uri == NULL) return; if (uri->scheme != NULL) xmlFree(uri->scheme); if (uri->server != NULL) xmlFree(uri->server); if (uri->user != NULL) xmlFree(uri->user); if (uri->path != NULL) xmlFree(uri->path); if (uri->fragment != NULL) xmlFree(uri->fragment); if (uri->opaque != NULL) xmlFree(uri->opaque); if (uri->authority != NULL) xmlFree(uri->authority); if (uri->query != NULL) xmlFree(uri->query); xmlFree(uri); } /************************************************************************ * * * Helper functions * * * ************************************************************************/ /** * xmlNormalizeURIPath: * @path: pointer to the path string * * Applies the 5 normalization steps to a path string--that is, RFC 2396 * Section 5.2, steps 6.c through 6.g. * * Normalization occurs directly on the string, no new allocation is done * * Returns 0 or an error code */ int xmlNormalizeURIPath(char *path) { char *cur, *out; if (path == NULL) return(-1); /* Skip all initial "/" chars. We want to get to the beginning of the * first non-empty segment. */ cur = path; while (cur[0] == '/') ++cur; if (cur[0] == '\0') return(0); /* Keep everything we've seen so far. */ out = cur; /* * Analyze each segment in sequence for cases (c) and (d). */ while (cur[0] != '\0') { /* * c) All occurrences of "./", where "." is a complete path segment, * are removed from the buffer string. */ if ((cur[0] == '.') && (cur[1] == '/')) { cur += 2; /* '//' normalization should be done at this point too */ while (cur[0] == '/') cur++; continue; } /* * d) If the buffer string ends with "." as a complete path segment, * that "." is removed. */ if ((cur[0] == '.') && (cur[1] == '\0')) break; /* Otherwise keep the segment. */ while (cur[0] != '/') { if (cur[0] == '\0') goto done_cd; (out++)[0] = (cur++)[0]; } /* nomalize // */ while ((cur[0] == '/') && (cur[1] == '/')) cur++; (out++)[0] = (cur++)[0]; } done_cd: out[0] = '\0'; /* Reset to the beginning of the first segment for the next sequence. */ cur = path; while (cur[0] == '/') ++cur; if (cur[0] == '\0') return(0); /* * Analyze each segment in sequence for cases (e) and (f). * * e) All occurrences of "<segment>/../", where <segment> is a * complete path segment not equal to "..", are removed from the * buffer string. Removal of these path segments is performed * iteratively, removing the leftmost matching pattern on each * iteration, until no matching pattern remains. * * f) If the buffer string ends with "<segment>/..", where <segment> * is a complete path segment not equal to "..", that * "<segment>/.." is removed. * * To satisfy the "iterative" clause in (e), we need to collapse the * string every time we find something that needs to be removed. Thus, * we don't need to keep two pointers into the string: we only need a * "current position" pointer. */ while (1) { char *segp, *tmp; /* At the beginning of each iteration of this loop, "cur" points to * the first character of the segment we want to examine. */ /* Find the end of the current segment. */ segp = cur; while ((segp[0] != '/') && (segp[0] != '\0')) ++segp; /* If this is the last segment, we're done (we need at least two * segments to meet the criteria for the (e) and (f) cases). */ if (segp[0] == '\0') break; /* If the first segment is "..", or if the next segment _isn't_ "..", * keep this segment and try the next one. */ ++segp; if (((cur[0] == '.') && (cur[1] == '.') && (segp == cur+3)) || ((segp[0] != '.') || (segp[1] != '.') || ((segp[2] != '/') && (segp[2] != '\0')))) { cur = segp; continue; } /* If we get here, remove this segment and the next one and back up * to the previous segment (if there is one), to implement the * "iteratively" clause. It's pretty much impossible to back up * while maintaining two pointers into the buffer, so just compact * the whole buffer now. */ /* If this is the end of the buffer, we're done. */ if (segp[2] == '\0') { cur[0] = '\0'; break; } /* Valgrind complained, strcpy(cur, segp + 3); */ /* string will overlap, do not use strcpy */ tmp = cur; segp += 3; while ((*tmp++ = *segp++) != 0); /* If there are no previous segments, then keep going from here. */ segp = cur; while ((segp > path) && ((--segp)[0] == '/')) ; if (segp == path) continue; /* "segp" is pointing to the end of a previous segment; find it's * start. We need to back up to the previous segment and start * over with that to handle things like "foo/bar/../..". If we * don't do this, then on the first pass we'll remove the "bar/..", * but be pointing at the second ".." so we won't realize we can also * remove the "foo/..". */ cur = segp; while ((cur > path) && (cur[-1] != '/')) --cur; } out[0] = '\0'; /* * g) If the resulting buffer string still begins with one or more * complete path segments of "..", then the reference is * considered to be in error. Implementations may handle this * error by retaining these components in the resolved path (i.e., * treating them as part of the final URI), by removing them from * the resolved path (i.e., discarding relative levels above the * root), or by avoiding traversal of the reference. * * We discard them from the final path. */ if (path[0] == '/') { cur = path; while ((cur[0] == '/') && (cur[1] == '.') && (cur[2] == '.') && ((cur[3] == '/') || (cur[3] == '\0'))) cur += 3; if (cur != path) { out = path; while (cur[0] != '\0') (out++)[0] = (cur++)[0]; out[0] = 0; } } return(0); } static int is_hex(char c) { if (((c >= '0') && (c <= '9')) || ((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F'))) return(1); return(0); } /** * xmlURIUnescapeString: * @str: the string to unescape * @len: the length in bytes to unescape (or <= 0 to indicate full string) * @target: optional destination buffer * * Unescaping routine, does not do validity checks ! * Output is direct unsigned char translation of %XX values (no encoding) * * Returns an copy of the string, but unescaped */ char * xmlURIUnescapeString(const char *str, int len, char *target) { char *ret, *out; const char *in; if (str == NULL) return(NULL); if (len <= 0) len = strlen(str); if (len < 0) return(NULL); if (target == NULL) { ret = (char *) xmlMallocAtomic(len + 1); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlURIUnescapeString: out of memory\n"); return(NULL); } } else ret = target; in = str; out = ret; while(len > 0) { if ((len > 2) && (*in == '%') && (is_hex(in[1])) && (is_hex(in[2]))) { in++; if ((*in >= '0') && (*in <= '9')) *out = (*in - '0'); else if ((*in >= 'a') && (*in <= 'f')) *out = (*in - 'a') + 10; else if ((*in >= 'A') && (*in <= 'F')) *out = (*in - 'A') + 10; in++; if ((*in >= '0') && (*in <= '9')) *out = *out * 16 + (*in - '0'); else if ((*in >= 'a') && (*in <= 'f')) *out = *out * 16 + (*in - 'a') + 10; else if ((*in >= 'A') && (*in <= 'F')) *out = *out * 16 + (*in - 'A') + 10; in++; len -= 3; out++; } else { *out++ = *in++; len--; } } *out = 0; return(ret); } /** * xmlURIEscapeStr: * @str: string to escape * @list: exception list string of chars not to escape * * This routine escapes a string to hex, ignoring reserved characters (a-z) * and the characters in the exception list. * * Returns a new escaped string or NULL in case of error. */ xmlChar * xmlURIEscapeStr(const xmlChar *str, const xmlChar *list) { xmlChar *ret, ch; const xmlChar *in; unsigned int len, out; if (str == NULL) return(NULL); if (str[0] == 0) return(xmlStrdup(str)); len = xmlStrlen(str); if (!(len > 0)) return(NULL); len += 20; ret = (xmlChar *) xmlMallocAtomic(len); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlURIEscapeStr: out of memory\n"); return(NULL); } in = (const xmlChar *) str; out = 0; while(*in != 0) { if (len - out <= 3) { len += 20; ret = (xmlChar *) xmlRealloc(ret, len); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlURIEscapeStr: out of memory\n"); return(NULL); } } ch = *in; if ((ch != '@') && (!IS_UNRESERVED(ch)) && (!xmlStrchr(list, ch))) { unsigned char val; ret[out++] = '%'; val = ch >> 4; if (val <= 9) ret[out++] = '0' + val; else ret[out++] = 'A' + val - 0xA; val = ch & 0xF; if (val <= 9) ret[out++] = '0' + val; else ret[out++] = 'A' + val - 0xA; in++; } else { ret[out++] = *in++; } } ret[out] = 0; return(ret); } /** * xmlURIEscape: * @str: the string of the URI to escape * * Escaping routine, does not do validity checks ! * It will try to escape the chars needing this, but this is heuristic * based it's impossible to be sure. * * Returns an copy of the string, but escaped * * 25 May 2001 * Uses xmlParseURI and xmlURIEscapeStr to try to escape correctly * according to RFC2396. * - Carl Douglas */ xmlChar * xmlURIEscape(const xmlChar * str) { xmlChar *ret, *segment = NULL; xmlURIPtr uri; int ret2; #define NULLCHK(p) if(!p) { \ xmlGenericError(xmlGenericErrorContext, \ "xmlURIEscape: out of memory\n"); \ return NULL; } if (str == NULL) return (NULL); uri = xmlCreateURI(); if (uri != NULL) { /* * Allow escaping errors in the unescaped form */ uri->cleanup = 1; ret2 = xmlParseURIReference(uri, (const char *)str); if (ret2) { xmlFreeURI(uri); return (NULL); } } if (!uri) return NULL; ret = NULL; if (uri->scheme) { segment = xmlURIEscapeStr(BAD_CAST uri->scheme, BAD_CAST "+-."); NULLCHK(segment) ret = xmlStrcat(ret, segment); ret = xmlStrcat(ret, BAD_CAST ":"); xmlFree(segment); } if (uri->authority) { segment = xmlURIEscapeStr(BAD_CAST uri->authority, BAD_CAST "/?;:@"); NULLCHK(segment) ret = xmlStrcat(ret, BAD_CAST "//"); ret = xmlStrcat(ret, segment); xmlFree(segment); } if (uri->user) { segment = xmlURIEscapeStr(BAD_CAST uri->user, BAD_CAST ";:&=+$,"); NULLCHK(segment) ret = xmlStrcat(ret,BAD_CAST "//"); ret = xmlStrcat(ret, segment); ret = xmlStrcat(ret, BAD_CAST "@"); xmlFree(segment); } if (uri->server) { segment = xmlURIEscapeStr(BAD_CAST uri->server, BAD_CAST "/?;:@"); NULLCHK(segment) if (uri->user == NULL) ret = xmlStrcat(ret, BAD_CAST "//"); ret = xmlStrcat(ret, segment); xmlFree(segment); } if (uri->port) { xmlChar port[10]; snprintf((char *) port, 10, "%d", uri->port); ret = xmlStrcat(ret, BAD_CAST ":"); ret = xmlStrcat(ret, port); } if (uri->path) { segment = xmlURIEscapeStr(BAD_CAST uri->path, BAD_CAST ":@&=+$,/?;"); NULLCHK(segment) ret = xmlStrcat(ret, segment); xmlFree(segment); } if (uri->query) { segment = xmlURIEscapeStr(BAD_CAST uri->query, BAD_CAST ";/?:@&=+,$"); NULLCHK(segment) ret = xmlStrcat(ret, BAD_CAST "?"); ret = xmlStrcat(ret, segment); xmlFree(segment); } if (uri->opaque) { segment = xmlURIEscapeStr(BAD_CAST uri->opaque, BAD_CAST ""); NULLCHK(segment) ret = xmlStrcat(ret, segment); xmlFree(segment); } if (uri->fragment) { segment = xmlURIEscapeStr(BAD_CAST uri->fragment, BAD_CAST "#"); NULLCHK(segment) ret = xmlStrcat(ret, BAD_CAST "#"); ret = xmlStrcat(ret, segment); xmlFree(segment); } xmlFreeURI(uri); #undef NULLCHK return (ret); } /************************************************************************ * * * Escaped URI parsing * * * ************************************************************************/ /** * xmlParseURIFragment: * @uri: pointer to an URI structure * @str: pointer to the string to analyze * * Parse an URI fragment string and fills in the appropriate fields * of the @uri structure. * * fragment = *uric * * Returns 0 or the error code */ static int xmlParseURIFragment(xmlURIPtr uri, const char **str) { const char *cur; if (str == NULL) return (-1); cur = *str; while (IS_URIC(cur) || IS_UNWISE(cur)) NEXT(cur); if (uri != NULL) { if (uri->fragment != NULL) xmlFree(uri->fragment); if (uri->cleanup & 2) uri->fragment = STRNDUP(*str, cur - *str); else uri->fragment = xmlURIUnescapeString(*str, cur - *str, NULL); } *str = cur; return (0); } /** * xmlParseURIQuery: * @uri: pointer to an URI structure * @str: pointer to the string to analyze * * Parse the query part of an URI * * query = *uric * * Returns 0 or the error code */ static int xmlParseURIQuery(xmlURIPtr uri, const char **str) { const char *cur; if (str == NULL) return (-1); cur = *str; while ((IS_URIC(cur)) || ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur)))) NEXT(cur); if (uri != NULL) { if (uri->query != NULL) xmlFree(uri->query); if (uri->cleanup & 2) uri->query = STRNDUP(*str, cur - *str); else uri->query = xmlURIUnescapeString(*str, cur - *str, NULL); } *str = cur; return (0); } /** * xmlParseURIScheme: * @uri: pointer to an URI structure * @str: pointer to the string to analyze * * Parse an URI scheme * * scheme = alpha *( alpha | digit | "+" | "-" | "." ) * * Returns 0 or the error code */ static int xmlParseURIScheme(xmlURIPtr uri, const char **str) { const char *cur; if (str == NULL) return(-1); cur = *str; if (!IS_ALPHA(*cur)) return(2); cur++; while (IS_SCHEME(*cur)) cur++; if (uri != NULL) { if (uri->scheme != NULL) xmlFree(uri->scheme); uri->scheme = STRNDUP(*str, cur - *str); } *str = cur; return(0); } /** * xmlParseURIOpaquePart: * @uri: pointer to an URI structure * @str: pointer to the string to analyze * * Parse an URI opaque part * * opaque_part = uric_no_slash *uric * * Returns 0 or the error code */ static int xmlParseURIOpaquePart(xmlURIPtr uri, const char **str) { const char *cur; if (str == NULL) return (-1); cur = *str; if (!((IS_URIC_NO_SLASH(cur)) || ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))) { return (3); } NEXT(cur); while ((IS_URIC(cur)) || ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur)))) NEXT(cur); if (uri != NULL) { if (uri->opaque != NULL) xmlFree(uri->opaque); if (uri->cleanup & 2) uri->opaque = STRNDUP(*str, cur - *str); else uri->opaque = xmlURIUnescapeString(*str, cur - *str, NULL); } *str = cur; return (0); } /** * xmlParseURIServer: * @uri: pointer to an URI structure * @str: pointer to the string to analyze * * Parse a server subpart of an URI, it's a finer grain analysis * of the authority part. * * server = [ [ userinfo "@" ] hostport ] * userinfo = *( unreserved | escaped | * ";" | ":" | "&" | "=" | "+" | "$" | "," ) * hostport = host [ ":" port ] * host = hostname | IPv4address | IPv6reference * hostname = *( domainlabel "." ) toplabel [ "." ] * domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum * toplabel = alpha | alpha *( alphanum | "-" ) alphanum * IPv6reference = "[" IPv6address "]" * IPv6address = hexpart [ ":" IPv4address ] * IPv4address = 1*3digit "." 1*3digit "." 1*3digit "." 1*3digit * hexpart = hexseq | hexseq "::" [ hexseq ]| "::" [ hexseq ] * hexseq = hex4 *( ":" hex4) * hex4 = 1*4hexdig * port = *digit * * Returns 0 or the error code */ static int xmlParseURIServer(xmlURIPtr uri, const char **str) { const char *cur; const char *host, *tmp; const int IPV4max = 4; const int IPV6max = 8; int oct; if (str == NULL) return(-1); cur = *str; /* * is there a userinfo ? */ while (IS_USERINFO(cur)) NEXT(cur); if (*cur == '@') { if (uri != NULL) { if (uri->user != NULL) xmlFree(uri->user); if (uri->cleanup & 2) uri->path = STRNDUP(*str, cur - *str); else uri->user = xmlURIUnescapeString(*str, cur - *str, NULL); } cur++; } else { if (uri != NULL) { if (uri->user != NULL) xmlFree(uri->user); uri->user = NULL; } cur = *str; } /* * This can be empty in the case where there is no server */ host = cur; if (*cur == '/') { if (uri != NULL) { if (uri->authority != NULL) xmlFree(uri->authority); uri->authority = NULL; if (uri->server != NULL) xmlFree(uri->server); uri->server = NULL; uri->port = 0; } return(0); } /* * host part of hostport can denote an IPV4 address, an IPV6 address * or an unresolved name. Check the IP first, its easier to detect * errors if wrong one. * An IPV6 address must start with a '[' and end with a ']'. */ if (*cur == '[') { int compress=0; cur++; for (oct = 0; oct < IPV6max; ++oct) { if (*cur == ':') { if (compress) return(3); /* multiple compression attempted */ if (!oct) { /* initial char is compression */ if (*++cur != ':') return(3); } compress = 1; /* set compression-encountered flag */ cur++; /* skip over the second ':' */ continue; } while(IS_HEX(*cur)) cur++; if (oct == (IPV6max-1)) continue; if (*cur != ':') break; cur++; } if ((!compress) && (oct != IPV6max)) return(3); if (*cur != ']') return(3); if (uri != NULL) { if (uri->server != NULL) xmlFree(uri->server); uri->server = (char *)xmlStrndup((xmlChar *)host+1, (cur-host)-1); } cur++; } else { /* * Not IPV6, maybe IPV4 */ for (oct = 0; oct < IPV4max; ++oct) { if (*cur == '.') return(3); /* e.g. http://.xml/ or http://18.29..30/ */ while(IS_DIGIT(*cur)) cur++; if (oct == (IPV4max-1)) continue; if (*cur != '.') break; cur++; } } if ((host[0] != '[') && (oct < IPV4max || (*cur == '.' && cur++) || IS_ALPHA(*cur))) { /* maybe host_name */ if (!IS_ALPHANUM(*cur)) return(4); /* e.g. http://xml.$oft */ do { do ++cur; while (IS_ALPHANUM(*cur)); if (*cur == '-') { --cur; if (*cur == '.') return(5); /* e.g. http://xml.-soft */ ++cur; continue; } if (*cur == '.') { --cur; if (*cur == '-') return(6); /* e.g. http://xml-.soft */ if (*cur == '.') return(7); /* e.g. http://xml..soft */ ++cur; continue; } break; } while (1); tmp = cur; if (tmp[-1] == '.') --tmp; /* e.g. http://xml.$Oft/ */ do --tmp; while (tmp >= host && IS_ALPHANUM(*tmp)); if ((++tmp == host || tmp[-1] == '.') && !IS_ALPHA(*tmp)) return(8); /* e.g. http://xmlsOft.0rg/ */ } if (uri != NULL) { if (uri->authority != NULL) xmlFree(uri->authority); uri->authority = NULL; if (host[0] != '[') { /* it's not an IPV6 addr */ if (uri->server != NULL) xmlFree(uri->server); if (uri->cleanup & 2) uri->server = STRNDUP(host, cur - host); else uri->server = xmlURIUnescapeString(host, cur - host, NULL); } } /* * finish by checking for a port presence. */ if (*cur == ':') { cur++; if (IS_DIGIT(*cur)) { if (uri != NULL) uri->port = 0; while (IS_DIGIT(*cur)) { if (uri != NULL) uri->port = uri->port * 10 + (*cur - '0'); cur++; } } } *str = cur; return(0); } /** * xmlParseURIRelSegment: * @uri: pointer to an URI structure * @str: pointer to the string to analyze * * Parse an URI relative segment * * rel_segment = 1*( unreserved | escaped | ";" | "@" | "&" | "=" | * "+" | "$" | "," ) * * Returns 0 or the error code */ static int xmlParseURIRelSegment(xmlURIPtr uri, const char **str) { const char *cur; if (str == NULL) return (-1); cur = *str; if (!((IS_SEGMENT(cur)) || ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))) { return (3); } NEXT(cur); while ((IS_SEGMENT(cur)) || ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur)))) NEXT(cur); if (uri != NULL) { if (uri->path != NULL) xmlFree(uri->path); if (uri->cleanup & 2) uri->path = STRNDUP(*str, cur - *str); else uri->path = xmlURIUnescapeString(*str, cur - *str, NULL); } *str = cur; return (0); } /** * xmlParseURIPathSegments: * @uri: pointer to an URI structure * @str: pointer to the string to analyze * @slash: should we add a leading slash * * Parse an URI set of path segments * * path_segments = segment *( "/" segment ) * segment = *pchar *( ";" param ) * param = *pchar * * Returns 0 or the error code */ static int xmlParseURIPathSegments(xmlURIPtr uri, const char **str, int slash) { const char *cur; if (str == NULL) return (-1); cur = *str; do { while ((IS_PCHAR(cur)) || ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur)))) NEXT(cur); while (*cur == ';') { cur++; while ((IS_PCHAR(cur)) || ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur)))) NEXT(cur); } if (*cur != '/') break; cur++; } while (1); if (uri != NULL) { int len, len2 = 0; char *path; /* * Concat the set of path segments to the current path */ len = cur - *str; if (slash) len++; if (uri->path != NULL) { len2 = strlen(uri->path); len += len2; } path = (char *) xmlMallocAtomic(len + 1); if (path == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlParseURIPathSegments: out of memory\n"); *str = cur; return (-1); } if (uri->path != NULL) memcpy(path, uri->path, len2); if (slash) { path[len2] = '/'; len2++; } path[len2] = 0; if (cur - *str > 0) { if (uri->cleanup & 2) { memcpy(&path[len2], *str, cur - *str); path[len2 + (cur - *str)] = 0; } else xmlURIUnescapeString(*str, cur - *str, &path[len2]); } if (uri->path != NULL) xmlFree(uri->path); uri->path = path; } *str = cur; return (0); } /** * xmlParseURIAuthority: * @uri: pointer to an URI structure * @str: pointer to the string to analyze * * Parse the authority part of an URI. * * authority = server | reg_name * server = [ [ userinfo "@" ] hostport ] * reg_name = 1*( unreserved | escaped | "$" | "," | ";" | ":" | * "@" | "&" | "=" | "+" ) * * Note : this is completely ambiguous since reg_name is allowed to * use the full set of chars in use by server: * * 3.2.1. Registry-based Naming Authority * * The structure of a registry-based naming authority is specific * to the URI scheme, but constrained to the allowed characters * for an authority component. * * Returns 0 or the error code */ static int xmlParseURIAuthority(xmlURIPtr uri, const char **str) { const char *cur; int ret; if (str == NULL) return(-1); cur = *str; /* * try first to parse it as a server string. */ ret = xmlParseURIServer(uri, str); if ((ret == 0) && (*str != NULL) && ((**str == 0) || (**str == '/') || (**str == '?'))) return(0); *str = cur; /* * failed, fallback to reg_name */ if (!IS_REG_NAME(cur)) { return(5); } NEXT(cur); while (IS_REG_NAME(cur)) NEXT(cur); if (uri != NULL) { if (uri->server != NULL) xmlFree(uri->server); uri->server = NULL; if (uri->user != NULL) xmlFree(uri->user); uri->user = NULL; if (uri->authority != NULL) xmlFree(uri->authority); if (uri->cleanup & 2) uri->authority = STRNDUP(*str, cur - *str); else uri->authority = xmlURIUnescapeString(*str, cur - *str, NULL); } *str = cur; return(0); } /** * xmlParseURIHierPart: * @uri: pointer to an URI structure * @str: pointer to the string to analyze * * Parse an URI hierarchical part * * hier_part = ( net_path | abs_path ) [ "?" query ] * abs_path = "/" path_segments * net_path = "//" authority [ abs_path ] * * Returns 0 or the error code */ static int xmlParseURIHierPart(xmlURIPtr uri, const char **str) { int ret; const char *cur; if (str == NULL) return(-1); cur = *str; if ((cur[0] == '/') && (cur[1] == '/')) { cur += 2; ret = xmlParseURIAuthority(uri, &cur); if (ret != 0) return(ret); if (cur[0] == '/') { cur++; ret = xmlParseURIPathSegments(uri, &cur, 1); } } else if (cur[0] == '/') { cur++; ret = xmlParseURIPathSegments(uri, &cur, 1); } else { return(4); } if (ret != 0) return(ret); if (*cur == '?') { cur++; ret = xmlParseURIQuery(uri, &cur); if (ret != 0) return(ret); } *str = cur; return(0); } /** * xmlParseAbsoluteURI: * @uri: pointer to an URI structure * @str: pointer to the string to analyze * * Parse an URI reference string and fills in the appropriate fields * of the @uri structure * * absoluteURI = scheme ":" ( hier_part | opaque_part ) * * Returns 0 or the error code */ static int xmlParseAbsoluteURI(xmlURIPtr uri, const char **str) { int ret; const char *cur; if (str == NULL) return(-1); cur = *str; ret = xmlParseURIScheme(uri, str); if (ret != 0) return(ret); if (**str != ':') { *str = cur; return(1); } (*str)++; if (**str == '/') return(xmlParseURIHierPart(uri, str)); return(xmlParseURIOpaquePart(uri, str)); } /** * xmlParseRelativeURI: * @uri: pointer to an URI structure * @str: pointer to the string to analyze * * Parse an relative URI string and fills in the appropriate fields * of the @uri structure * * relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ] * abs_path = "/" path_segments * net_path = "//" authority [ abs_path ] * rel_path = rel_segment [ abs_path ] * * Returns 0 or the error code */ static int xmlParseRelativeURI(xmlURIPtr uri, const char **str) { int ret = 0; const char *cur; if (str == NULL) return(-1); cur = *str; if ((cur[0] == '/') && (cur[1] == '/')) { cur += 2; ret = xmlParseURIAuthority(uri, &cur); if (ret != 0) return(ret); if (cur[0] == '/') { cur++; ret = xmlParseURIPathSegments(uri, &cur, 1); } } else if (cur[0] == '/') { cur++; ret = xmlParseURIPathSegments(uri, &cur, 1); } else if (cur[0] != '#' && cur[0] != '?') { ret = xmlParseURIRelSegment(uri, &cur); if (ret != 0) return(ret); if (cur[0] == '/') { cur++; ret = xmlParseURIPathSegments(uri, &cur, 1); } } if (ret != 0) return(ret); if (*cur == '?') { cur++; ret = xmlParseURIQuery(uri, &cur); if (ret != 0) return(ret); } *str = cur; return(ret); } /** * xmlParseURIReference: * @uri: pointer to an URI structure * @str: the string to analyze * * Parse an URI reference string and fills in the appropriate fields * of the @uri structure * * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] * * Returns 0 or the error code */ int xmlParseURIReference(xmlURIPtr uri, const char *str) { int ret; const char *tmp = str; if (str == NULL) return(-1); xmlCleanURI(uri); /* * Try first to parse absolute refs, then fallback to relative if * it fails. */ ret = xmlParseAbsoluteURI(uri, &str); if (ret != 0) { xmlCleanURI(uri); str = tmp; ret = xmlParseRelativeURI(uri, &str); } if (ret != 0) { xmlCleanURI(uri); return(ret); } if (*str == '#') { str++; ret = xmlParseURIFragment(uri, &str); if (ret != 0) return(ret); } if (*str != 0) { xmlCleanURI(uri); return(1); } return(0); } /** * xmlParseURI: * @str: the URI string to analyze * * Parse an URI * * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] * * Returns a newly built xmlURIPtr or NULL in case of error */ xmlURIPtr xmlParseURI(const char *str) { xmlURIPtr uri; int ret; if (str == NULL) return(NULL); uri = xmlCreateURI(); if (uri != NULL) { ret = xmlParseURIReference(uri, str); if (ret) { xmlFreeURI(uri); return(NULL); } } return(uri); } /** * xmlParseURIRaw: * @str: the URI string to analyze * @raw: if 1 unescaping of URI pieces are disabled * * Parse an URI but allows to keep intact the original fragments. * * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] * * Returns a newly built xmlURIPtr or NULL in case of error */ xmlURIPtr xmlParseURIRaw(const char *str, int raw) { xmlURIPtr uri; int ret; if (str == NULL) return(NULL); uri = xmlCreateURI(); if (uri != NULL) { if (raw) { uri->cleanup |= 2; } ret = xmlParseURIReference(uri, str); if (ret) { xmlFreeURI(uri); return(NULL); } } return(uri); } /************************************************************************ * * * Public functions * * * ************************************************************************/ /** * xmlBuildURI: * @URI: the URI instance found in the document * @base: the base value * * Computes he final URI of the reference done by checking that * the given URI is valid, and building the final URI using the * base URI. This is processed according to section 5.2 of the * RFC 2396 * * 5.2. Resolving Relative References to Absolute Form * * Returns a new URI string (to be freed by the caller) or NULL in case * of error. */ xmlChar * xmlBuildURI(const xmlChar *URI, const xmlChar *base) { xmlChar *val = NULL; int ret, len, indx, cur, out; xmlURIPtr ref = NULL; xmlURIPtr bas = NULL; xmlURIPtr res = NULL; /* * 1) The URI reference is parsed into the potential four components and * fragment identifier, as described in Section 4.3. * * NOTE that a completely empty URI is treated by modern browsers * as a reference to "." rather than as a synonym for the current * URI. Should we do that here? */ if (URI == NULL) ret = -1; else { if (*URI) { ref = xmlCreateURI(); if (ref == NULL) goto done; ret = xmlParseURIReference(ref, (const char *) URI); } else ret = 0; } if (ret != 0) goto done; if ((ref != NULL) && (ref->scheme != NULL)) { /* * The URI is absolute don't modify. */ val = xmlStrdup(URI); goto done; } if (base == NULL) ret = -1; else { bas = xmlCreateURI(); if (bas == NULL) goto done; ret = xmlParseURIReference(bas, (const char *) base); } if (ret != 0) { if (ref) val = xmlSaveUri(ref); goto done; } if (ref == NULL) { /* * the base fragment must be ignored */ if (bas->fragment != NULL) { xmlFree(bas->fragment); bas->fragment = NULL; } val = xmlSaveUri(bas); goto done; } /* * 2) If the path component is empty and the scheme, authority, and * query components are undefined, then it is a reference to the * current document and we are done. Otherwise, the reference URI's * query and fragment components are defined as found (or not found) * within the URI reference and not inherited from the base URI. * * NOTE that in modern browsers, the parsing differs from the above * in the following aspect: the query component is allowed to be * defined while still treating this as a reference to the current * document. */ res = xmlCreateURI(); if (res == NULL) goto done; if ((ref->scheme == NULL) && (ref->path == NULL) && ((ref->authority == NULL) && (ref->server == NULL))) { if (bas->scheme != NULL) res->scheme = xmlMemStrdup(bas->scheme); if (bas->authority != NULL) res->authority = xmlMemStrdup(bas->authority); else if (bas->server != NULL) { res->server = xmlMemStrdup(bas->server); if (bas->user != NULL) res->user = xmlMemStrdup(bas->user); res->port = bas->port; } if (bas->path != NULL) res->path = xmlMemStrdup(bas->path); if (ref->query != NULL) res->query = xmlMemStrdup(ref->query); else if (bas->query != NULL) res->query = xmlMemStrdup(bas->query); if (ref->fragment != NULL) res->fragment = xmlMemStrdup(ref->fragment); goto step_7; } /* * 3) If the scheme component is defined, indicating that the reference * starts with a scheme name, then the reference is interpreted as an * absolute URI and we are done. Otherwise, the reference URI's * scheme is inherited from the base URI's scheme component. */ if (ref->scheme != NULL) { val = xmlSaveUri(ref); goto done; } if (bas->scheme != NULL) res->scheme = xmlMemStrdup(bas->scheme); if (ref->query != NULL) res->query = xmlMemStrdup(ref->query); if (ref->fragment != NULL) res->fragment = xmlMemStrdup(ref->fragment); /* * 4) If the authority component is defined, then the reference is a * network-path and we skip to step 7. Otherwise, the reference * URI's authority is inherited from the base URI's authority * component, which will also be undefined if the URI scheme does not * use an authority component. */ if ((ref->authority != NULL) || (ref->server != NULL)) { if (ref->authority != NULL) res->authority = xmlMemStrdup(ref->authority); else { res->server = xmlMemStrdup(ref->server); if (ref->user != NULL) res->user = xmlMemStrdup(ref->user); res->port = ref->port; } if (ref->path != NULL) res->path = xmlMemStrdup(ref->path); goto step_7; } if (bas->authority != NULL) res->authority = xmlMemStrdup(bas->authority); else if (bas->server != NULL) { res->server = xmlMemStrdup(bas->server); if (bas->user != NULL) res->user = xmlMemStrdup(bas->user); res->port = bas->port; } /* * 5) If the path component begins with a slash character ("/"), then * the reference is an absolute-path and we skip to step 7. */ if ((ref->path != NULL) && (ref->path[0] == '/')) { res->path = xmlMemStrdup(ref->path); goto step_7; } /* * 6) If this step is reached, then we are resolving a relative-path * reference. The relative path needs to be merged with the base * URI's path. Although there are many ways to do this, we will * describe a simple method using a separate string buffer. * * Allocate a buffer large enough for the result string. */ len = 2; /* extra / and 0 */ if (ref->path != NULL) len += strlen(ref->path); if (bas->path != NULL) len += strlen(bas->path); res->path = (char *) xmlMallocAtomic(len); if (res->path == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlBuildURI: out of memory\n"); goto done; } res->path[0] = 0; /* * a) All but the last segment of the base URI's path component is * copied to the buffer. In other words, any characters after the * last (right-most) slash character, if any, are excluded. */ cur = 0; out = 0; if (bas->path != NULL) { while (bas->path[cur] != 0) { while ((bas->path[cur] != 0) && (bas->path[cur] != '/')) cur++; if (bas->path[cur] == 0) break; cur++; while (out < cur) { res->path[out] = bas->path[out]; out++; } } } res->path[out] = 0; /* * b) The reference's path component is appended to the buffer * string. */ if (ref->path != NULL && ref->path[0] != 0) { indx = 0; /* * Ensure the path includes a '/' */ if ((out == 0) && (bas->server != NULL)) res->path[out++] = '/'; while (ref->path[indx] != 0) { res->path[out++] = ref->path[indx++]; } } res->path[out] = 0; /* * Steps c) to h) are really path normalization steps */ xmlNormalizeURIPath(res->path); step_7: /* * 7) The resulting URI components, including any inherited from the * base URI, are recombined to give the absolute form of the URI * reference. */ val = xmlSaveUri(res); done: if (ref != NULL) xmlFreeURI(ref); if (bas != NULL) xmlFreeURI(bas); if (res != NULL) xmlFreeURI(res); return(val); } /** * xmlBuildRelativeURI: * @URI: the URI reference under consideration * @base: the base value * * Expresses the URI of the reference in terms relative to the * base. Some examples of this operation include: * base = "http://site1.com/docs/book1.html" * URI input URI returned * docs/pic1.gif pic1.gif * docs/img/pic1.gif img/pic1.gif * img/pic1.gif ../img/pic1.gif * http://site1.com/docs/pic1.gif pic1.gif * http://site2.com/docs/pic1.gif http://site2.com/docs/pic1.gif * * base = "docs/book1.html" * URI input URI returned * docs/pic1.gif pic1.gif * docs/img/pic1.gif img/pic1.gif * img/pic1.gif ../img/pic1.gif * http://site1.com/docs/pic1.gif http://site1.com/docs/pic1.gif * * * Note: if the URI reference is really wierd or complicated, it may be * worthwhile to first convert it into a "nice" one by calling * xmlBuildURI (using 'base') before calling this routine, * since this routine (for reasonable efficiency) assumes URI has * already been through some validation. * * Returns a new URI string (to be freed by the caller) or NULL in case * error. */ xmlChar * xmlBuildRelativeURI (const xmlChar * URI, const xmlChar * base) { xmlChar *val = NULL; int ret; int ix; int pos = 0; int nbslash = 0; int len; xmlURIPtr ref = NULL; xmlURIPtr bas = NULL; xmlChar *bptr, *uptr, *vptr; int remove_path = 0; if ((URI == NULL) || (*URI == 0)) return NULL; /* * First parse URI into a standard form */ ref = xmlCreateURI (); if (ref == NULL) return NULL; /* If URI not already in "relative" form */ if (URI[0] != '.') { ret = xmlParseURIReference (ref, (const char *) URI); if (ret != 0) goto done; /* Error in URI, return NULL */ } else ref->path = (char *)xmlStrdup(URI); /* * Next parse base into the same standard form */ if ((base == NULL) || (*base == 0)) { val = xmlStrdup (URI); goto done; } bas = xmlCreateURI (); if (bas == NULL) goto done; if (base[0] != '.') { ret = xmlParseURIReference (bas, (const char *) base); if (ret != 0) goto done; /* Error in base, return NULL */ } else bas->path = (char *)xmlStrdup(base); /* * If the scheme / server on the URI differs from the base, * just return the URI */ if ((ref->scheme != NULL) && ((bas->scheme == NULL) || (xmlStrcmp ((xmlChar *)bas->scheme, (xmlChar *)ref->scheme)) || (xmlStrcmp ((xmlChar *)bas->server, (xmlChar *)ref->server)))) { val = xmlStrdup (URI); goto done; } if (xmlStrEqual((xmlChar *)bas->path, (xmlChar *)ref->path)) { val = xmlStrdup(BAD_CAST ""); goto done; } if (bas->path == NULL) { val = xmlStrdup((xmlChar *)ref->path); goto done; } if (ref->path == NULL) { ref->path = (char *) "/"; remove_path = 1; } /* * At this point (at last!) we can compare the two paths * * First we take care of the special case where either of the * two path components may be missing (bug 316224) */ if (bas->path == NULL) { if (ref->path != NULL) { uptr = (xmlChar *) ref->path; if (*uptr == '/') uptr++; val = xmlStrdup(uptr); } goto done; } bptr = (xmlChar *)bas->path; if (ref->path == NULL) { for (ix = 0; bptr[ix] != 0; ix++) { if (bptr[ix] == '/') nbslash++; } uptr = NULL; len = 1; /* this is for a string terminator only */ } else { /* * Next we compare the two strings and find where they first differ */ if ((ref->path[pos] == '.') && (ref->path[pos+1] == '/')) pos += 2; if ((*bptr == '.') && (bptr[1] == '/')) bptr += 2; else if ((*bptr == '/') && (ref->path[pos] != '/')) bptr++; while ((bptr[pos] == ref->path[pos]) && (bptr[pos] != 0)) pos++; if (bptr[pos] == ref->path[pos]) { val = xmlStrdup(BAD_CAST ""); goto done; /* (I can't imagine why anyone would do this) */ } /* * In URI, "back up" to the last '/' encountered. This will be the * beginning of the "unique" suffix of URI */ ix = pos; if ((ref->path[ix] == '/') && (ix > 0)) ix--; else if ((ref->path[ix] == 0) && (ix > 1) && (ref->path[ix - 1] == '/')) ix -= 2; for (; ix > 0; ix--) { if (ref->path[ix] == '/') break; } if (ix == 0) { uptr = (xmlChar *)ref->path; } else { ix++; uptr = (xmlChar *)&ref->path[ix]; } /* * In base, count the number of '/' from the differing point */ if (bptr[pos] != ref->path[pos]) {/* check for trivial URI == base */ for (; bptr[ix] != 0; ix++) { if (bptr[ix] == '/') nbslash++; } } len = xmlStrlen (uptr) + 1; } if (nbslash == 0) { if (uptr != NULL) val = xmlStrdup (uptr); goto done; } /* * Allocate just enough space for the returned string - * length of the remainder of the URI, plus enough space * for the "../" groups, plus one for the terminator */ val = (xmlChar *) xmlMalloc (len + 3 * nbslash); if (val == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlBuildRelativeURI: out of memory\n"); goto done; } vptr = val; /* * Put in as many "../" as needed */ for (; nbslash>0; nbslash--) { *vptr++ = '.'; *vptr++ = '.'; *vptr++ = '/'; } /* * Finish up with the end of the URI */ if (uptr != NULL) { if ((vptr > val) && (len > 0) && (uptr[0] == '/') && (vptr[-1] == '/')) { memcpy (vptr, uptr + 1, len - 1); vptr[len - 2] = 0; } else { memcpy (vptr, uptr, len); vptr[len - 1] = 0; } } else { vptr[len - 1] = 0; } done: /* * Free the working variables */ if (remove_path != 0) ref->path = NULL; if (ref != NULL) xmlFreeURI (ref); if (bas != NULL) xmlFreeURI (bas); return val; } /** * xmlCanonicPath: * @path: the resource locator in a filesystem notation * * Constructs a canonic path from the specified path. * * Returns a new canonic path, or a duplicate of the path parameter if the * construction fails. The caller is responsible for freeing the memory occupied * by the returned string. If there is insufficient memory available, or the * argument is NULL, the function returns NULL. */ #define IS_WINDOWS_PATH(p) \ ((p != NULL) && \ (((p[0] >= 'a') && (p[0] <= 'z')) || \ ((p[0] >= 'A') && (p[0] <= 'Z'))) && \ (p[1] == ':') && ((p[2] == '/') || (p[2] == '\\'))) xmlChar * xmlCanonicPath(const xmlChar *path) { #if defined(_WIN32) && !defined(__CYGWIN__) int len = 0; /*int i = 0;*/ xmlChar *p = NULL; #endif xmlURIPtr uri; xmlChar *ret; const xmlChar *absuri; if (path == NULL) return(NULL); if ((uri = xmlParseURI((const char *) path)) != NULL) { xmlFreeURI(uri); return xmlStrdup(path); } absuri = xmlStrstr(path, BAD_CAST "://"); if (absuri != NULL) { int l, j; unsigned char c; xmlChar *escURI; /* * this looks like an URI where some parts have not been * escaped leading to a parsing problem check that the first * part matches a protocol. */ l = absuri - path; if ((l <= 0) || (l > 20)) goto path_processing; for (j = 0;j < l;j++) { c = path[j]; if (!(((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')))) goto path_processing; } escURI = xmlURIEscapeStr(path, BAD_CAST ":/?_.#&;="); if (escURI != NULL) { uri = xmlParseURI((const char *) escURI); if (uri != NULL) { xmlFreeURI(uri); return escURI; } xmlFreeURI(uri); } } path_processing: #if defined(_WIN32) && !defined(__CYGWIN__) /* * This really need to be cleaned up by someone with a Windows box */ uri = xmlCreateURI(); if (uri == NULL) { return(NULL); } len = xmlStrlen(path); if ((len > 2) && IS_WINDOWS_PATH(path)) { uri->scheme = xmlStrdup(BAD_CAST "file"); uri->path = xmlMallocAtomic(len + 2); if (uri->path == NULL) { xmlFreeURI(uri); return(NULL); } uri->path[0] = '/'; p = uri->path + 1; strncpy(p, path, len + 1); } else { uri->path = xmlStrdup(path); if (uri->path == NULL) { xmlFreeURI(uri); return(NULL); } p = uri->path; } while (*p != '\0') { if (*p == '\\') *p = '/'; p++; } if (uri->path == NULL) { xmlFreeURI(uri); return(NULL); } if (uri->scheme == NULL) { ret = xmlStrdup((const xmlChar *) path); } else { ret = xmlSaveUri(uri); } xmlFreeURI(uri); #else ret = xmlStrdup((const xmlChar *) path); #endif return(ret); } /** * xmlPathToURI: * @path: the resource locator in a filesystem notation * * Constructs an URI expressing the existing path * * Returns a new URI, or a duplicate of the path parameter if the * construction fails. The caller is responsible for freeing the memory * occupied by the returned string. If there is insufficient memory available, * or the argument is NULL, the function returns NULL. */ xmlChar * xmlPathToURI(const xmlChar *path) { xmlURIPtr uri; xmlURI temp; xmlChar *ret, *cal; if (path == NULL) return(NULL); if ((uri = xmlParseURI((const char *) path)) != NULL) { xmlFreeURI(uri); return xmlStrdup(path); } cal = xmlCanonicPath(path); if (cal == NULL) return(NULL); memset(&temp, 0, sizeof(temp)); temp.path = (char *) cal; ret = xmlSaveUri(&temp); xmlFree(cal); return(ret); } #define bottom_uri #include "elfgcchack.h"
hlzz/dotfiles
graphics/VTK-7.0.0/ThirdParty/libxml2/vtklibxml2/uri.c
C
bsd-3-clause
75,146
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE606_Unchecked_Loop_Condition__char_connect_socket_21.c Label Definition File: CWE606_Unchecked_Loop_Condition.label.xml Template File: sources-sinks-21.tmpl.c */ /* * @description * CWE: 606 Unchecked Input For Loop Condition * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Input a number less than MAX_LOOP * Sinks: * GoodSink: Use data as the for loop variant after checking to see if it is less than MAX_LOOP * BadSink : Use data as the for loop variant without checking its size * Flow Variant: 21 Control flow: Flow controlled by value of a static global variable. All functions contained in one file. * * */ #include "std_testcase.h" #define MAX_LOOP 10000 #ifndef _WIN32 #include <wchar.h> #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" #ifndef OMITBAD /* The static variable below is used to drive control flow in the sink function */ static int badStatic = 0; static void badSink(char * data) { if(badStatic) { { int i, n, intVariable; if (sscanf(data, "%d", &n) == 1) { /* POTENTIAL FLAW: user-supplied value 'n' could lead to very large loop iteration */ intVariable = 0; for (i = 0; i < n; i++) { /* INCIDENTAL: CWE 561: Dead Code - non-avoidable if n <= 0 */ intVariable++; /* avoid a dead/empty code block issue */ } printIntLine(intVariable); } } } } void CWE606_Unchecked_Loop_Condition__char_connect_socket_21_bad() { char * data; char dataBuffer[100] = ""; data = dataBuffer; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; char *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = strlen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(char)] = '\0'; /* Eliminate CRLF */ replace = strchr(data, '\r'); if (replace) { *replace = '\0'; } replace = strchr(data, '\n'); if (replace) { *replace = '\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } badStatic = 1; /* true */ badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* The static variables below are used to drive control flow in the sink functions. */ static int goodB2G1Static = 0; static int goodB2G2Static = 0; static int goodG2BStatic = 0; /* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */ static void goodB2G1Sink(char * data) { if(goodB2G1Static) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { int i, n, intVariable; if (sscanf(data, "%d", &n) == 1) { /* FIX: limit loop iteration counts */ if (n < MAX_LOOP) { intVariable = 0; for (i = 0; i < n; i++) { /* INCIDENTAL: CWE 561: Dead Code - non-avoidable if n <= 0 */ intVariable++; /* avoid a dead/empty code block issue */ } printIntLine(intVariable); } } } } } static void goodB2G1() { char * data; char dataBuffer[100] = ""; data = dataBuffer; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; char *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = strlen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(char)] = '\0'; /* Eliminate CRLF */ replace = strchr(data, '\r'); if (replace) { *replace = '\0'; } replace = strchr(data, '\n'); if (replace) { *replace = '\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } goodB2G1Static = 0; /* false */ goodB2G1Sink(data); } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */ static void goodB2G2Sink(char * data) { if(goodB2G2Static) { { int i, n, intVariable; if (sscanf(data, "%d", &n) == 1) { /* FIX: limit loop iteration counts */ if (n < MAX_LOOP) { intVariable = 0; for (i = 0; i < n; i++) { /* INCIDENTAL: CWE 561: Dead Code - non-avoidable if n <= 0 */ intVariable++; /* avoid a dead/empty code block issue */ } printIntLine(intVariable); } } } } } static void goodB2G2() { char * data; char dataBuffer[100] = ""; data = dataBuffer; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; char *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = strlen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(char)] = '\0'; /* Eliminate CRLF */ replace = strchr(data, '\r'); if (replace) { *replace = '\0'; } replace = strchr(data, '\n'); if (replace) { *replace = '\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } goodB2G2Static = 1; /* true */ goodB2G2Sink(data); } /* goodG2B() - use goodsource and badsink */ static void goodG2BSink(char * data) { if(goodG2BStatic) { { int i, n, intVariable; if (sscanf(data, "%d", &n) == 1) { /* POTENTIAL FLAW: user-supplied value 'n' could lead to very large loop iteration */ intVariable = 0; for (i = 0; i < n; i++) { /* INCIDENTAL: CWE 561: Dead Code - non-avoidable if n <= 0 */ intVariable++; /* avoid a dead/empty code block issue */ } printIntLine(intVariable); } } } } static void goodG2B() { char * data; char dataBuffer[100] = ""; data = dataBuffer; /* FIX: Set data to a number less than MAX_LOOP */ strcpy(data, "15"); goodG2BStatic = 1; /* true */ goodG2BSink(data); } void CWE606_Unchecked_Loop_Condition__char_connect_socket_21_good() { goodB2G1(); goodB2G2(); goodG2B(); } #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()..."); CWE606_Unchecked_Loop_Condition__char_connect_socket_21_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE606_Unchecked_Loop_Condition__char_connect_socket_21_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE606_Unchecked_Loop_Condition/CWE606_Unchecked_Loop_Condition__char_connect_socket_21.c
C
bsd-3-clause
13,008
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* Copyright (c) 2015-2016, Schadin Alexey ([email protected]) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Windows.Forms; namespace NppKate.Forms { public partial class BranchList : Form { public string SelectedItem { get; private set; } public BranchList() { InitializeComponent(); } private string _repoDir; public string RepoDirectory { get { return _repoDir; } set { _repoDir = value; ReloadBranched(); } } private void ReloadBranched() { var showRemoteBranch = rbAll.Checked || rbRemote.Checked; var showLocal = rbAll.Checked || rbLocal.Checked; lbItems.BeginUpdate(); lbItems.Items.Clear(); using (var repo = new LibGit2Sharp.Repository(_repoDir)) { foreach(var b in repo.Branches) { if (b.IsRemote == showRemoteBranch || !b.IsRemote == showLocal) { lbItems.Items.Add(b.FriendlyName); } } } lbItems.EndUpdate(); } private void lbItems_DoubleClick(object sender, EventArgs e) { Ok(); } private void lbItems_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter && lbItems.SelectedItem != null) { Ok(); } } private void Ok() { SelectedItem = (string)lbItems.SelectedItem; DialogResult = DialogResult.OK; } private void bOk_Click(object sender, EventArgs e) { Ok(); } private void bCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; } private void CheckedChanged(object sender, EventArgs e) { ReloadBranched(); } } }
schadin/NppKate
NppKate/Forms/BranchList.cs
C#
bsd-3-clause
3,704
<form name='dbform' method='POST'> <table summary="PHP settings"> <tr> <th> Database settings </th> <th> </th> </tr> <tr> <td colspan='2'> Spotweb needs an available MySQL or PostgreSQL database. The database needs to be created and you need to have an user account and password for this database. </td> </tr> <tr> <td> type </td> <td> <select name='dbform[engine]'> <option value='pdo_mysql'>mysql</option> <option value='pdo_pgsql'>PostgreSQL</option> <option value='pdo_sqlite'>SQLite (untested)</option> </select> </td> </tr> <tr> <td> server </td> <td> <input type='text' length='40' name='dbform[host]' value='<?php echo htmlspecialchars($form['host']); ?>'></input> </td> </tr> <tr> <td> database </td> <td> <input type='text' length='40' name='dbform[dbname]' value='<?php echo htmlspecialchars($form['dbname']); ?>' ></input></td> </tr> <tr> <td> username </td> <td> <input type='text' length='40' name='dbform[user]' value='<?php echo htmlspecialchars($form['user']); ?>'></input> </td> </tr> <tr> <td> password </td> <td> <input type='password' length='40' name='dbform[pass]' value='<?php echo htmlspecialchars($form['pass']); ?>'></input> </td> </tr> <tr> <td colspan='2'> <input type='submit' name='dbform[submit]' value='Verify database'> </td> </tr> </table> </form> <br /> <?php
rodikal/Spotweb
templates/installer/step-002.inc.php
PHP
bsd-3-clause
1,341
#! /usr/bin/env python # Example scipt to show integration of a 1D spectrum import nmrglue as ng import numpy as np import matplotlib.pyplot as plt # read in the data from a NMRPipe file dic, data = ng.pipe.read("1d_data.ft") length = data.shape[0] # read in the integration limits peak_list = np.recfromtxt("limits.in") # determind the ppm scale uc = ng.pipe.make_uc(dic, data) ppm_scale = uc.ppm_scale() # plot the spectrum fig = plt.figure() ax = fig.add_subplot(111) ax.plot(ppm_scale, data, 'k-') # prepare the output file f = open("area.out", 'w') f.write("#Name\tStart\tStop\tArea\n") # loop over the integration limits for name, start, end in peak_list: min = uc(start, "ppm") max = uc(end, "ppm") if min > max: min, max = max, min # extract the peak peak = data[min:max + 1] peak_scale = ppm_scale[min:max + 1] # plot the integration lines, limits and name of peaks ax.plot(peak_scale, peak.cumsum() / 100. + peak.max(), 'g-') ax.plot(peak_scale, [0] * len(peak_scale), 'r-') ax.text(peak_scale[0], 0.5 * peak.sum() / 100. + peak.max(), name, fontsize=8) # write out the integration info tup = (name, peak_scale[0], peak_scale[-1], peak.sum()) f.write("%s\t%.3f\t%.3f\t%E\n" % tup) # close the output file and save the plot f.close() ax.set_xlim(ppm_scale[0], ppm_scale[-1]) fig.savefig("plot.png")
atomman/nmrglue
examples/integration/integrate_1d/integrate_1d.py
Python
bsd-3-clause
1,395
<html> <head> <meta http-equiv="Content-type" content="text/html;charset=iso-8859-1"> <title>PyDbLite</title> <link rel="stylesheet" href="../pydblite.css"> </head> <body> <table width="100%" cellspacing="0" cellpadding="10"> <tr> <td class="navigation" align="center"><img src="../img/banniere.jpg"></td> <td class="lnk" align="right"><a class="langue" href="../en/PyDbLite.html">English</a></td> </tr> </table> <table width="100%" cellspacing="0" cellpadding="0"> <tr> <td class="menu"> <div id="niveau1">Documentation</div> <div id="niveau2"> <a href="index.html">Accueil</a> <br><a href="PyDbLite.html">Moteur pur-Python</a> <br><a href="SQLite.html">Adapteur SQLite </a> <br><a href="MySQL.html">Adapteur MySQL</a> </div> <div id="niveau1">Contacts</div> <div id="niveau2"> <a href="http://groups.google.com/group/pydblite">Communauté</a> <br><a href="contact.html">Mail</a> </div> <div id="niveau1">Code</div> <div id="niveau2"> <a href="http://sourceforge.net/project/platformdownload.php?group_id=210258">Téléchargement</a> <br><a href="http://pydblite.svn.sourceforge.net/viewvc/pydblite">Parcourir SVN</a> </div> <div id="niveau1"> <a href="bench.html">Comparaisons</a> </div> <div id="niveau1"> <a href="licence.html">Licence</a> </div> <div id="fill">&nbsp;<br>&nbsp;<br>&nbsp;<br> &nbsp;<br>&nbsp;<br>&nbsp;<br> &nbsp;<br>&nbsp;<br>&nbsp;<br> &nbsp;<br>&nbsp;<br>&nbsp;<br> </div> </td> <td class="content"> <p><h2>Moteur pur Python</h2> Le moteur pur-Python consiste en un module unique, <code>PyDbLite.py</code>. Pour l'utiliser, importer la classe <code>Base</code> depuis ce module : <p> &nbsp;&nbsp;&nbsp;&nbsp;<span class="python">from PyDbLite import Base</span> <h3>Créer ou ouvrir une base de données</h3> <ul> <li>créer une instance de base de données, en donnant un nom de fichier comme argument : <span class="python">db = Base('test.pdl')</span> <li>pour une nouvelle base, définissez les noms des champs : <span class="python">db.create('nom','age','taille')</span> <br>Vous n'avez pas à définir le type des champs. PyDbLite accepte toute valeur qui peut être sérialisée par le module <CODE>cPickle</CODE> : des chaînes de caractères, des chaînes Unicode, des entiers, réels, dates et dates-heures (instances des classes <CODE>date</CODE> et <CODE>datetime</CODE> dans le module <CODE>datetime</CODE>), des instances de classes définies par l'utilisateur, etc <li><span class="python">db.exists()</span> indique si la base existe <li>si la base existe déjà, pour l'ouvrir : <span class="python">db.open()</span> <li>on peut passer un paramètre "mode" à la méthode <CODE>create()</CODE>, pour indiquer ce qu'il faut faire si la base existe déjà sur le disque <ul> <li>mode = "open" : <span class="python">db.create('nom','age','taille',mode="open")</span> ouvre la base en ignorant la définition des champs <li> mode = "override" : <span class="python">db.create('nom','age','taille',mode="override")</span> efface la base existante et en crée une nouvelle avec les définitions de champs <li>si le mode n'est pas précisé et que la base existe déjà, une exception <CODE>IOError</CODE> est déclenchée</ul> </ul> </ul> <h3>Insertion, mise à jour, suppression d'enregistrements</h3> <ul> <li>insertion d'un nouvel enregistrement <ul> <li>par mots-clés : <span class="python">db.insert(nom='homer',age=23,taille=1.84)</span> <br>Si certains champs manquent, ils sont initialisés à la valeur <CODE>None</CODE> <li>par arguments positionnels : <span class="python">db.insert('homer',23,1.84)</span> <br>Les arguments doivent être fournis dans le même ordre que dans la méthode <CODE>create()</CODE> </ul> <li>pour sauvegarder les changements sur le disque : <span class="python">db.commit()</span> <br>Si vous ne confirmez pas les changements, les opérations d'insertion, de suppression et de mise à jour ne seront pas sauvegardés sur le disque <li>En plus des champs passés à la méthode <CODE>create()</CODE>, un champ interne appelé <CODE>__id__</CODE> est ajouté. C'est un entier, unique et inchangé pour chaque enregistrement, il peut donc être utilisé comme identifiant pour l'enregistrement <li> un autre champ interne appelé <CODE>__version__</CODE> est également géré par le moteur de base de données. Il s'agit d'un entier qui est initialisé à 0 quand l'enregistrement est créé, et incrémenté de 1 à chaque fois que l'enregistrement est mis à jour. Ceci sert pour la détection des accès concurrents, par exemple dans une application web dans laquelle deux utilisateurs veulent mettre à jour le même enregistrement en même temps <li>pour mettre à jour un enregistrement : <span class="python">db.update(record,age=24)</span> <li>pour supprimer un enregistrement : <span class="python">db.delete(record)</span> ou, si vous connaissez l'identifiant : <span class="python">del db[rec_id]</span> <li>pour supprimer une liste d'enregistrements : <span class="python">db.delete(liste_d_enregistrements)</span> <br><CODE>liste_d_enregistrements</CODE> peut être n'importe quel itérable (liste, tuple, set, etc) qui produit des enregistrements </ul> <h3>Sélection</h3> L'instance de <CODE>Base</CODE> est un itérateur sur les enregistrements. Pour itérer sur tous les enregistrements : <BLOCKQUOTE> <span class="python">for r in db:<br> &nbsp;&nbsp;&nbsp;&nbsp;fais_qqch_avec(r)</span> </BLOCKQUOTE> <h4>Accès direct</h4> On peut accéder directement à un enregistrement par son identifiant : <div class="python">record = db[rec_id]</div> retourne l'enregistrement tel que <code>record['__id__'] == rec_id</code> <h4>Sélection simples</h4> <ul> <li> <span class="python">db(cle1=val1,cle2=val2)</span> renvoie la liste des enregistrements dont les clés ont les valeurs données <li><span class="python">db(cle) >= valeur</span> retourne un itérateur sur tous les enregistrements pour lesquels la valeur du champ <CODE>cle</CODE> est supérieure ou égale à <CODE>valeur</CODE>. Exemple : <blockquote><span class="python">for rec in (db("age")>30):<br> &nbsp;&nbsp;&nbsp;&nbsp; print rec["nom"] </span></blockquote> <li>ces "comparaisons riches" peuvent être combinées avec des & (et) et des | (ou) :<br> <blockquote><span class="python">for rec in (db("age")>30) & (db("pays") == "France"):<br> &nbsp;&nbsp;&nbsp;&nbsp;print rec["nom"]</span></blockquote> </ul> <h4>Listes en intension</h4> <ul> <li>la sélection d'enregistrements peut utiliser la syntaxe des listes en intension ("list comprehensions") de Python : <br><span class="python">recs = [ r for r in db if 30 > r['age'] >= 18 and r['taille'] < 2 ]</span> <br>retourne les enregistrements de la base pour lesquels l'âge est compris entre 18 et 30 ans, et la taille est inférieure à 2 mètres. L'enregistrement est un dictionnaire, où la clé est le nom de champ et la valeur est la valeur de ce champ <li>la syntaxe des générateurs d'expression Python peut aussi être utilisée : <br><span class="python">for r in (r for r in db if r['nom'] in ('homer','marge') ):<br> &nbsp;&nbsp;&nbsp;&nbsp;faire_qqch_avec(r)</span> <br>itère sur les enregistrements dont le nom est 'homer' ou 'marge' </ul> <h4>Index</h4> <ul>Pour accélérer les sélections, un index peut être créé sur un champ : <span class="python">db.create_index('age')</span> <p>Quand un index est créé, l'instance de la base de données a un attribut (ici <CODE>_age</CODE> : noter le signe de soulignement initial, pour éviter les conflits de noms avec des noms internes). Cet attribut est un objet de type dictionnaire, où les clés sont les valeurs prises par le champ, et les valeurs sont les enregistrements dont le champ a la même valeur que la clé : <p><span class="python">records = db._age[23]</span> retourne la liste des enregistrements avec age == 23 <p>Si aucun enregistrement n'a cette valeur, la recherche par cette valeur retourne une liste vide <p>L'index supporte l'itération sur les valeurs du champ, et la méthode <CODE>keys()</CODE> retourne toutes les valeurs existantes pour le champ </ul> <h3>Autres attributs et méthodes</h3> <ul> <li><span class="python">db.add_field('nouveau_champ'[,default=v])</span> : ajoute un nouveau champ à la base de données. <i>default</i> est une valeur par défaut ; elle vaut <code>None</code> si elle n'est pas précisée <li><span class="python">db.drop_field('nom')</span> : supprime un champ existant <li><span class="python">db.path</span> : the chemin de la base de données dans le système de fichiers <li><span class="python">db.name</span> : le nom de la base de données : le nom de base du chemin (sans le répertoire), auquel on a enlevé l'extension <li><span class="python">len(db)</span> : nombre d'enregistrements dans la base <li><span class="python">db.fields</span> : la liste des champs (n'inclut pas les champs internes <code>__id__</code> et <code>__version__</code>) </td> </tr> </table> </body> </html>
PierreQuentel/PyDbLite
doc/fr/PyDbLite.html
HTML
bsd-3-clause
9,108
<?php /** * AccountAccountControllerSignUp Test * * @var $scenario \Codeception\Scenario * * @author Brett O'Donnell <[email protected]> * @author Zain Ul abidin <[email protected]> * @copyright 2013 Mr PHP * @link https://github.com/cornernote/yii-account-module * @license BSD-3-Clause https://raw.github.com/cornernote/yii-account-module/master/LICENSE * * @package yii-account-module */ $I = new WebGuy($scenario); $I->wantTo('ensure AccountAccountController lost password works'); // check we are not logged in $I->amOnPage('/'); $I->see('Hello guest'); // lost password with invalid username $I->amOnPage('/account/account/lostPassword'); $I->fillField('AccountLostPassword_email_or_username', 'admin123'); $I->click('Recover Password'); $I->see('Please fix the following input errors:'); $I->see('Username does not exist.'); // lost password with invalid email $I->amOnPage('/account/account/lostPassword'); $I->fillField('AccountLostPassword_email_or_username', '[email protected]'); $I->click('Recover Password'); $I->see('Please fix the following input errors:'); $I->see('Email does not exist.'); // lost password with correct username $I->amOnPage('/account/account/lostPassword'); $I->fillField('AccountLostPassword_email_or_username', 'admin'); $I->click('Recover Password'); $I->see('Password reset instructions have been sent to [email protected]. Please check your email.'); $I->seeInDatabase('email_spool', array( 'template' => 'account_lost_password', 'status' => 'pending', 'model_name' => 'AccountUser', 'model_id' => 1, 'to_address' => '{"[email protected]":"admin admin"}', 'from_address' => '{"webmaster@localhost":"My Application"}', )); $I->seeInDatabase('token', array( 'model_name' => 'AccountLostPassword', 'model_id' => 1, 'uses_allowed' => 1, 'uses_remaining' => 1, )); // lost password with correct email $I->amOnPage('/account/account/lostPassword'); $I->fillField('AccountLostPassword_email_or_username', '[email protected]'); $I->click('Recover Password'); $I->see('Password reset instructions have been sent to [email protected]. Please check your email.'); // check guest $I->amOnPage('/'); $I->see('Hello guest');
zainengineer/yii-account-module
tests/acceptance/AccountAccountControllerLostPasswordCept.php
PHP
bsd-3-clause
2,237
<?php /** * This file contains the CDbFixtureManager class. * * @author Qiang Xue <[email protected]> * @link http://www.yiiframework.com/ * @copyright 2008-2013 Yii Software LLC * @license http://www.yiiframework.com/license/ */ /** * CDbFixtureManager manages database fixtures during tests. * * A fixture represents a list of rows for a specific table. For a test method, * using a fixture means that at the beginning of the method, the table has and only * has the rows that are given in the fixture. Therefore, the table's state is * predictable. * * A fixture is represented as a PHP script whose name (without suffix) is the * same as the table name (if schema name is needed, it should be prefixed to * the table name). The PHP script returns an array representing a list of table * rows. Each row is an associative array of column values indexed by column names. * * A fixture can be associated with an init script which sits under the same fixture * directory and is named as "TableName.init.php". The init script is used to * initialize the table before populating the fixture data into the table. * If the init script does not exist, the table will be emptied. * * Fixtures must be stored under the {@link basePath} directory. The directory * may contain a file named "init.php" which will be executed once to initialize * the database. If this file is not found, all available fixtures will be loaded * into the database. * * @property CDbConnection $dbConnection The database connection. * @property array $fixtures The information of the available fixtures (table name => fixture file). * * @author Qiang Xue <[email protected]> * @package system.test * @since 1.1 */ class CDbFixtureManager extends CApplicationComponent { /** * * @var string the name of the initialization script that would be executed before the whole test set runs. * Defaults to 'init.php'. If the script does not exist, every table with a fixture file will be reset. */ public $initScript = 'init.php'; /** * * @var string the suffix for fixture initialization scripts. * If a table is associated with such a script whose name is TableName suffixed this property value, * then the script will be executed each time before the table is reset. */ public $initScriptSuffix = '.init.php'; /** * * @var string the base path containing all fixtures. Defaults to null, meaning * the path 'protected/tests/fixtures'. */ public $basePath; /** * * @var string the ID of the database connection. Defaults to 'db'. * Note, data in this database may be deleted or modified during testing. * Make sure you have a backup database. */ public $connectionID = 'db'; /** * * @var array list of database schemas that the test tables may reside in. Defaults to * array(''), meaning using the default schema (an empty string refers to the * default schema). This property is mainly used when turning on and off integrity checks * so that fixture data can be populated into the database without causing problem. */ public $schemas = array ( '' ); private $_db; private $_fixtures; private $_rows; // fixture name, row alias => row private $_records; // fixture name, row alias => record (or class name) /** * Initializes this application component. */ public function init() { parent::init (); if ($this->basePath === null) $this->basePath = Yii::getPathOfAlias ( 'application.tests.fixtures' ); $this->prepare (); } /** * Returns the database connection used to load fixtures. * * @throws CException if {@link connectionID} application component is invalid * @return CDbConnection the database connection */ public function getDbConnection() { if ($this->_db === null) { $this->_db = Yii::app ()->getComponent ( $this->connectionID ); if (! $this->_db instanceof CDbConnection) throw new CException ( Yii::t ( 'yii', 'CDbTestFixture.connectionID "{id}" is invalid. Please make sure it refers to the ID of a CDbConnection application component.', array ( '{id}' => $this->connectionID ) ) ); } return $this->_db; } /** * Prepares the fixtures for the whole test. * This method is invoked in {@link init}. It executes the database init script * if it exists. Otherwise, it will load all available fixtures. */ public function prepare() { $initFile = $this->basePath . DIRECTORY_SEPARATOR . $this->initScript; $this->checkIntegrity ( false ); if (is_file ( $initFile )) require ($initFile); else { foreach ( $this->getFixtures () as $tableName => $fixturePath ) { $this->resetTable ( $tableName ); $this->loadFixture ( $tableName ); } } $this->checkIntegrity ( true ); } /** * Resets the table to the state that it contains no fixture data. * If there is an init script named "tests/fixtures/TableName.init.php", * the script will be executed. * Otherwise, {@link truncateTable} will be invoked to delete all rows in the table * and reset primary key sequence, if any. * * @param string $tableName * the table name */ public function resetTable($tableName) { $initFile = $this->basePath . DIRECTORY_SEPARATOR . $tableName . $this->initScriptSuffix; if (is_file ( $initFile )) require ($initFile); else $this->truncateTable ( $tableName ); } /** * Loads the fixture for the specified table. * This method will insert rows given in the fixture into the corresponding table. * The loaded rows will be returned by this method. * If the table has auto-incremental primary key, each row will contain updated primary key value. * If the fixture does not exist, this method will return false. * Note, you may want to call {@link resetTable} before calling this method * so that the table is emptied first. * * @param string $tableName * table name * @return array the loaded fixture rows indexed by row aliases (if any). * False is returned if the table does not have a fixture. */ public function loadFixture($tableName) { $fileName = $this->basePath . DIRECTORY_SEPARATOR . $tableName . '.php'; if (! is_file ( $fileName )) return false; $rows = array (); $schema = $this->getDbConnection ()->getSchema (); $builder = $schema->getCommandBuilder (); $table = $schema->getTable ( $tableName ); foreach ( require ($fileName) as $alias => $row ) { $builder->createInsertCommand ( $table, $row )->execute (); $primaryKey = $table->primaryKey; if ($table->sequenceName !== null) { if (is_string ( $primaryKey ) && ! isset ( $row [$primaryKey] )) $row [$primaryKey] = $builder->getLastInsertID ( $table ); elseif (is_array ( $primaryKey )) { foreach ( $primaryKey as $pk ) { if (! isset ( $row [$pk] )) { $row [$pk] = $builder->getLastInsertID ( $table ); break; } } } } $rows [$alias] = $row; } return $rows; } /** * Returns the information of the available fixtures. * This method will search for all PHP files under {@link basePath}. * If a file's name is the same as a table name, it is considered to be the fixture data for that table. * * @return array the information of the available fixtures (table name => fixture file) */ public function getFixtures() { if ($this->_fixtures === null) { $this->_fixtures = array (); $schema = $this->getDbConnection ()->getSchema (); $folder = opendir ( $this->basePath ); $suffixLen = strlen ( $this->initScriptSuffix ); while ( $file = readdir ( $folder ) ) { if ($file === '.' || $file === '..' || $file === $this->initScript) continue; $path = $this->basePath . DIRECTORY_SEPARATOR . $file; if (substr ( $file, - 4 ) === '.php' && is_file ( $path ) && substr ( $file, - $suffixLen ) !== $this->initScriptSuffix) { $tableName = substr ( $file, 0, - 4 ); if ($schema->getTable ( $tableName ) !== null) $this->_fixtures [$tableName] = $path; } } closedir ( $folder ); } return $this->_fixtures; } /** * Enables or disables database integrity check. * This method may be used to temporarily turn off foreign constraints check. * * @param boolean $check * whether to enable database integrity check */ public function checkIntegrity($check) { foreach ( $this->schemas as $schema ) $this->getDbConnection ()->getSchema ()->checkIntegrity ( $check, $schema ); } /** * Removes all rows from the specified table and resets its primary key sequence, if any. * You may need to call {@link checkIntegrity} to turn off integrity check temporarily * before you call this method. * * @param string $tableName * the table name * @throws CException if given table does not exist */ public function truncateTable($tableName) { $db = $this->getDbConnection (); $schema = $db->getSchema (); if (($table = $schema->getTable ( $tableName )) !== null) { $db->createCommand ( 'DELETE FROM ' . $table->rawName )->execute (); $schema->resetSequence ( $table, 1 ); } else throw new CException ( "Table '$tableName' does not exist." ); } /** * Truncates all tables in the specified schema. * You may need to call {@link checkIntegrity} to turn off integrity check temporarily * before you call this method. * * @param string $schema * the schema name. Defaults to empty string, meaning the default database schema. * @see truncateTable */ public function truncateTables($schema = '') { $tableNames = $this->getDbConnection ()->getSchema ()->getTableNames ( $schema ); foreach ( $tableNames as $tableName ) $this->truncateTable ( $tableName ); } /** * Loads the specified fixtures. * For each fixture, the corresponding table will be reset first by calling * {@link resetTable} and then be populated with the fixture data. * The loaded fixture data may be later retrieved using {@link getRows} * and {@link getRecord}. * Note, if a table does not have fixture data, {@link resetTable} will still * be called to reset the table. * * @param array $fixtures * fixtures to be loaded. The array keys are fixture names, * and the array values are either AR class names or table names. * If table names, they must begin with a colon character (e.g. 'Post' * means an AR class, while ':Post' means a table name). */ public function load($fixtures) { $schema = $this->getDbConnection ()->getSchema (); $schema->checkIntegrity ( false ); $this->_rows = array (); $this->_records = array (); foreach ( $fixtures as $fixtureName => $tableName ) { if ($tableName [0] === ':') { $tableName = substr ( $tableName, 1 ); unset ( $modelClass ); } else { $modelClass = Yii::import ( $tableName, true ); $tableName = CActiveRecord::model ( $modelClass )->tableName (); } if (($prefix = $this->getDbConnection ()->tablePrefix) !== null) $tableName = preg_replace ( '/{{(.*?)}}/', $prefix . '\1', $tableName ); $this->resetTable ( $tableName ); $rows = $this->loadFixture ( $tableName ); if (is_array ( $rows ) && is_string ( $fixtureName )) { $this->_rows [$fixtureName] = $rows; if (isset ( $modelClass )) { foreach ( array_keys ( $rows ) as $alias ) $this->_records [$fixtureName] [$alias] = $modelClass; } } } $schema->checkIntegrity ( true ); } /** * Returns the fixture data rows. * The rows will have updated primary key values if the primary key is auto-incremental. * * @param string $name * the fixture name * @return array the fixture data rows. False is returned if there is no such fixture data. */ public function getRows($name) { if (isset ( $this->_rows [$name] )) return $this->_rows [$name]; else return false; } /** * Returns the specified ActiveRecord instance in the fixture data. * * @param string $name * the fixture name * @param string $alias * the alias for the fixture data row * @return CActiveRecord the ActiveRecord instance. False is returned if there is no such fixture row. */ public function getRecord($name, $alias) { if (isset ( $this->_records [$name] [$alias] )) { if (is_string ( $this->_records [$name] [$alias] )) { $row = $this->_rows [$name] [$alias]; $model = CActiveRecord::model ( $this->_records [$name] [$alias] ); $key = $model->getTableSchema ()->primaryKey; if (is_string ( $key )) $pk = $row [$key]; else { foreach ( $key as $k ) $pk [$k] = $row [$k]; } $this->_records [$name] [$alias] = $model->findByPk ( $pk ); } return $this->_records [$name] [$alias]; } else return false; } }
wangrunxinyes/sby
framework/test/CDbFixtureManager.php
PHP
bsd-3-clause
12,826
from __future__ import print_function import unittest2 from lldbsuite.test.decorators import * from lldbsuite.test.concurrent_base import ConcurrentEventsBase from lldbsuite.test.lldbtest import TestBase @skipIfWindows class ConcurrentSignalDelayBreak(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) @skipIfFreeBSD # timing out on buildbot # Atomic sequences are not supported yet for MIPS in LLDB. @skipIf(triple='^mips') def test(self): """Test signal and a (1 second delay) breakpoint in multiple threads.""" self.build(dictionary=self.getBuildFlags()) self.do_thread_actions( num_delay_breakpoint_threads=1, num_signal_threads=1)
youtube/cobalt
third_party/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalDelayBreak.py
Python
bsd-3-clause
737
/* * Copyright (c) 2011-2015, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "AlsaSubsystem.hpp" #include <string> #include <map> #include <tinyalsa/asoundlib.h> class TinyAlsaSubsystem : public AlsaSubsystem { public: TinyAlsaSubsystem(const std::string &name, core::log::Logger& logger); ~TinyAlsaSubsystem(); /** * Return a handle to the card's mixer. */ struct mixer *getMixerHandle(int32_t cardNumber); private: typedef std::map<int32_t, struct mixer *> MixerMap; /** * Cache to each card's mixer handle. */ MixerMap mMixers; };
android-ia/vendor_intel_hardware_audiocomms_parameter-framework_plugins_alsa
tinyalsa/TinyAlsaSubsystem.hpp
C++
bsd-3-clause
2,108
import pytest import numpy as np from qutip.qip.device import DispersiveCavityQED, CircularSpinChain from qutip.qip.compiler import ( SpinChainCompiler, CavityQEDCompiler, Instruction, GateCompiler ) from qutip.qip.circuit import QubitCircuit from qutip import basis, fidelity def test_compiling_with_scheduler(): """ Here we test if the compiling with scheduler works properly. The non scheduled pulse should be twice as long as the scheduled one. The numerical results are tested in test_device.py """ circuit = QubitCircuit(2) circuit.add_gate("X", 0) circuit.add_gate("X", 1) processor = DispersiveCavityQED(2) processor.load_circuit(circuit, schedule_mode=None) tlist = processor.get_full_tlist() time_not_scheduled = tlist[-1]-tlist[0] coeffs, tlist = processor.load_circuit(circuit, schedule_mode="ASAP") tlist = processor.get_full_tlist() time_scheduled1 = tlist[-1]-tlist[0] coeffs, tlist = processor.load_circuit(circuit, schedule_mode="ALAP") tlist = processor.get_full_tlist() time_scheduled2 = tlist[-1]-tlist[0] assert(abs(time_scheduled1 * 2 - time_not_scheduled) < 1.0e-10) assert(abs(time_scheduled2 * 2 - time_not_scheduled) < 1.0e-10) def gauss_dist(t, sigma, amplitude, duration): return amplitude/np.sqrt(2*np.pi) /sigma*np.exp(-0.5*((t-duration/2)/sigma)**2) def gauss_rx_compiler(gate, args): """ Compiler for the RX gate """ targets = gate.targets # target qubit parameters = args["params"] h_x2pi = parameters["sx"][targets[0]] # find the coupling strength for the target qubit amplitude = gate.arg_value / 2. / 0.9973 # 0.9973 is just used to compensate the finite pulse duration so that the total area is fixed gate_sigma = h_x2pi / np.sqrt(2*np.pi) duration = 6 * gate_sigma tlist = np.linspace(0, duration, 100) coeff = gauss_dist(tlist, gate_sigma, amplitude, duration) pulse_info = [("sx" + str(targets[0]), coeff)] # save the information in a tuple (pulse_name, coeff) return [Instruction(gate, tlist, pulse_info)] class MyCompiler(GateCompiler): # compiler class def __init__(self, num_qubits, params, pulse_dict): super(MyCompiler, self).__init__( num_qubits, params=params, pulse_dict=pulse_dict) # pass our compiler function as a compiler for RX (rotation around X) gate. self.gate_compiler["RX"] = gauss_rx_compiler self.args.update({"params": params}) spline_kind = [ pytest.param("step_func", id="discrete"), pytest.param("cubic", id="continuous"), ] schedule_mode = [ pytest.param("ASAP", id="ASAP"), pytest.param("ALAP", id="ALAP"), pytest.param(False, id="No schedule"), ] @pytest.mark.parametrize("spline_kind", spline_kind) @pytest.mark.parametrize("schedule_mode", schedule_mode) def test_compiler_with_continous_pulse(spline_kind, schedule_mode): num_qubits = 2 circuit = QubitCircuit(num_qubits) circuit.add_gate("X", targets=0) circuit.add_gate("X", targets=1) circuit.add_gate("X", targets=0) processor = CircularSpinChain(num_qubits) gauss_compiler = MyCompiler( processor.N, processor.params, processor.pulse_dict) processor.load_circuit( circuit, schedule_mode = schedule_mode, compiler=gauss_compiler) result = processor.run_state(init_state = basis([2,2], [0,0])) assert(abs(fidelity(result.states[-1],basis([2,2],[0,1])) - 1) < 1.e-6) def rx_compiler_without_pulse_dict(gate, args): """ Define a gate compiler that does not use pulse_dict but directly give the index of control pulses in the Processor. """ targets = gate.targets g = args["params"]["sx"][targets[0]] coeff = np.sign(gate.arg_value) * g tlist = abs(gate.arg_value) / (2 * g) pulse_info = [(targets[0], coeff)] return [Instruction(gate, tlist, pulse_info)] def test_compiler_without_pulse_dict(): """ Test for a compiler function without pulse_dict and using args. """ num_qubits = 2 circuit = QubitCircuit(num_qubits) circuit.add_gate("X", targets=[0]) circuit.add_gate("X", targets=[1]) processor = CircularSpinChain(num_qubits) compiler = SpinChainCompiler( num_qubits, params=processor.params, pulse_dict=None, setup="circular") compiler.gate_compiler["RX"] = rx_compiler_without_pulse_dict compiler.args = {"params": processor.params} processor.load_circuit(circuit, compiler=compiler) result = processor.run_state(basis([2,2], [0,0])) assert(abs(fidelity(result.states[-1], basis([2,2], [1,1])) - 1.) < 1.e-6 )
cgranade/qutip
qutip/tests/test_compiler.py
Python
bsd-3-clause
4,632
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrAAHairLinePathRenderer.h" #include "GrBatchTarget.h" #include "GrBatchTest.h" #include "GrCaps.h" #include "GrContext.h" #include "GrDefaultGeoProcFactory.h" #include "GrIndexBuffer.h" #include "GrPathUtils.h" #include "GrPipelineBuilder.h" #include "GrProcessor.h" #include "GrResourceProvider.h" #include "GrVertexBuffer.h" #include "SkGeometry.h" #include "SkStroke.h" #include "SkTemplates.h" #include "batches/GrVertexBatch.h" #include "effects/GrBezierEffect.h" #define PREALLOC_PTARRAY(N) SkSTArray<(N),SkPoint, true> // quadratics are rendered as 5-sided polys in order to bound the // AA stroke around the center-curve. See comments in push_quad_index_buffer and // bloat_quad. Quadratics and conics share an index buffer // lines are rendered as: // *______________* // |\ -_______ /| // | \ \ / | // | *--------* | // | / ______/ \ | // */_-__________\* // For: 6 vertices and 18 indices (for 6 triangles) // Each quadratic is rendered as a five sided polygon. This poly bounds // the quadratic's bounding triangle but has been expanded so that the // 1-pixel wide area around the curve is inside the poly. // If a,b,c are the original control points then the poly a0,b0,c0,c1,a1 // that is rendered would look like this: // b0 // b // // a0 c0 // a c // a1 c1 // Each is drawn as three triangles ((a0,a1,b0), (b0,c1,c0), (a1,c1,b0)) // specified by these 9 indices: static const uint16_t kQuadIdxBufPattern[] = { 0, 1, 2, 2, 4, 3, 1, 4, 2 }; static const int kIdxsPerQuad = SK_ARRAY_COUNT(kQuadIdxBufPattern); static const int kQuadNumVertices = 5; static const int kQuadsNumInIdxBuffer = 256; GR_DECLARE_STATIC_UNIQUE_KEY(gQuadsIndexBufferKey); static const GrIndexBuffer* ref_quads_index_buffer(GrResourceProvider* resourceProvider) { GR_DEFINE_STATIC_UNIQUE_KEY(gQuadsIndexBufferKey); return resourceProvider->findOrCreateInstancedIndexBuffer( kQuadIdxBufPattern, kIdxsPerQuad, kQuadsNumInIdxBuffer, kQuadNumVertices, gQuadsIndexBufferKey); } // Each line segment is rendered as two quads and two triangles. // p0 and p1 have alpha = 1 while all other points have alpha = 0. // The four external points are offset 1 pixel perpendicular to the // line and half a pixel parallel to the line. // // p4 p5 // p0 p1 // p2 p3 // // Each is drawn as six triangles specified by these 18 indices: static const uint16_t kLineSegIdxBufPattern[] = { 0, 1, 3, 0, 3, 2, 0, 4, 5, 0, 5, 1, 0, 2, 4, 1, 5, 3 }; static const int kIdxsPerLineSeg = SK_ARRAY_COUNT(kLineSegIdxBufPattern); static const int kLineSegNumVertices = 6; static const int kLineSegsNumInIdxBuffer = 256; GR_DECLARE_STATIC_UNIQUE_KEY(gLinesIndexBufferKey); static const GrIndexBuffer* ref_lines_index_buffer(GrResourceProvider* resourceProvider) { GR_DEFINE_STATIC_UNIQUE_KEY(gLinesIndexBufferKey); return resourceProvider->findOrCreateInstancedIndexBuffer( kLineSegIdxBufPattern, kIdxsPerLineSeg, kLineSegsNumInIdxBuffer, kLineSegNumVertices, gLinesIndexBufferKey); } // Takes 178th time of logf on Z600 / VC2010 static int get_float_exp(float x) { GR_STATIC_ASSERT(sizeof(int) == sizeof(float)); #ifdef SK_DEBUG static bool tested; if (!tested) { tested = true; SkASSERT(get_float_exp(0.25f) == -2); SkASSERT(get_float_exp(0.3f) == -2); SkASSERT(get_float_exp(0.5f) == -1); SkASSERT(get_float_exp(1.f) == 0); SkASSERT(get_float_exp(2.f) == 1); SkASSERT(get_float_exp(2.5f) == 1); SkASSERT(get_float_exp(8.f) == 3); SkASSERT(get_float_exp(100.f) == 6); SkASSERT(get_float_exp(1000.f) == 9); SkASSERT(get_float_exp(1024.f) == 10); SkASSERT(get_float_exp(3000000.f) == 21); } #endif const int* iptr = (const int*)&x; return (((*iptr) & 0x7f800000) >> 23) - 127; } // Uses the max curvature function for quads to estimate // where to chop the conic. If the max curvature is not // found along the curve segment it will return 1 and // dst[0] is the original conic. If it returns 2 the dst[0] // and dst[1] are the two new conics. static int split_conic(const SkPoint src[3], SkConic dst[2], const SkScalar weight) { SkScalar t = SkFindQuadMaxCurvature(src); if (t == 0) { if (dst) { dst[0].set(src, weight); } return 1; } else { if (dst) { SkConic conic; conic.set(src, weight); conic.chopAt(t, dst); } return 2; } } // Calls split_conic on the entire conic and then once more on each subsection. // Most cases will result in either 1 conic (chop point is not within t range) // or 3 points (split once and then one subsection is split again). static int chop_conic(const SkPoint src[3], SkConic dst[4], const SkScalar weight) { SkConic dstTemp[2]; int conicCnt = split_conic(src, dstTemp, weight); if (2 == conicCnt) { int conicCnt2 = split_conic(dstTemp[0].fPts, dst, dstTemp[0].fW); conicCnt = conicCnt2 + split_conic(dstTemp[1].fPts, &dst[conicCnt2], dstTemp[1].fW); } else { dst[0] = dstTemp[0]; } return conicCnt; } // returns 0 if quad/conic is degen or close to it // in this case approx the path with lines // otherwise returns 1 static int is_degen_quad_or_conic(const SkPoint p[3], SkScalar* dsqd) { static const SkScalar gDegenerateToLineTol = GrPathUtils::kDefaultTolerance; static const SkScalar gDegenerateToLineTolSqd = SkScalarMul(gDegenerateToLineTol, gDegenerateToLineTol); if (p[0].distanceToSqd(p[1]) < gDegenerateToLineTolSqd || p[1].distanceToSqd(p[2]) < gDegenerateToLineTolSqd) { return 1; } *dsqd = p[1].distanceToLineBetweenSqd(p[0], p[2]); if (*dsqd < gDegenerateToLineTolSqd) { return 1; } if (p[2].distanceToLineBetweenSqd(p[1], p[0]) < gDegenerateToLineTolSqd) { return 1; } return 0; } static int is_degen_quad_or_conic(const SkPoint p[3]) { SkScalar dsqd; return is_degen_quad_or_conic(p, &dsqd); } // we subdivide the quads to avoid huge overfill // if it returns -1 then should be drawn as lines static int num_quad_subdivs(const SkPoint p[3]) { SkScalar dsqd; if (is_degen_quad_or_conic(p, &dsqd)) { return -1; } // tolerance of triangle height in pixels // tuned on windows Quadro FX 380 / Z600 // trade off of fill vs cpu time on verts // maybe different when do this using gpu (geo or tess shaders) static const SkScalar gSubdivTol = 175 * SK_Scalar1; if (dsqd <= SkScalarMul(gSubdivTol, gSubdivTol)) { return 0; } else { static const int kMaxSub = 4; // subdividing the quad reduces d by 4. so we want x = log4(d/tol) // = log4(d*d/tol*tol)/2 // = log2(d*d/tol*tol) // +1 since we're ignoring the mantissa contribution. int log = get_float_exp(dsqd/(gSubdivTol*gSubdivTol)) + 1; log = SkTMin(SkTMax(0, log), kMaxSub); return log; } } /** * Generates the lines and quads to be rendered. Lines are always recorded in * device space. We will do a device space bloat to account for the 1pixel * thickness. * Quads are recorded in device space unless m contains * perspective, then in they are in src space. We do this because we will * subdivide large quads to reduce over-fill. This subdivision has to be * performed before applying the perspective matrix. */ static int gather_lines_and_quads(const SkPath& path, const SkMatrix& m, const SkIRect& devClipBounds, GrAAHairLinePathRenderer::PtArray* lines, GrAAHairLinePathRenderer::PtArray* quads, GrAAHairLinePathRenderer::PtArray* conics, GrAAHairLinePathRenderer::IntArray* quadSubdivCnts, GrAAHairLinePathRenderer::FloatArray* conicWeights) { SkPath::Iter iter(path, false); int totalQuadCount = 0; SkRect bounds; SkIRect ibounds; bool persp = m.hasPerspective(); for (;;) { SkPoint pathPts[4]; SkPoint devPts[4]; SkPath::Verb verb = iter.next(pathPts); switch (verb) { case SkPath::kConic_Verb: { SkConic dst[4]; // We chop the conics to create tighter clipping to hide error // that appears near max curvature of very thin conics. Thin // hyperbolas with high weight still show error. int conicCnt = chop_conic(pathPts, dst, iter.conicWeight()); for (int i = 0; i < conicCnt; ++i) { SkPoint* chopPnts = dst[i].fPts; m.mapPoints(devPts, chopPnts, 3); bounds.setBounds(devPts, 3); bounds.outset(SK_Scalar1, SK_Scalar1); bounds.roundOut(&ibounds); if (SkIRect::Intersects(devClipBounds, ibounds)) { if (is_degen_quad_or_conic(devPts)) { SkPoint* pts = lines->push_back_n(4); pts[0] = devPts[0]; pts[1] = devPts[1]; pts[2] = devPts[1]; pts[3] = devPts[2]; } else { // when in perspective keep conics in src space SkPoint* cPts = persp ? chopPnts : devPts; SkPoint* pts = conics->push_back_n(3); pts[0] = cPts[0]; pts[1] = cPts[1]; pts[2] = cPts[2]; conicWeights->push_back() = dst[i].fW; } } } break; } case SkPath::kMove_Verb: break; case SkPath::kLine_Verb: m.mapPoints(devPts, pathPts, 2); bounds.setBounds(devPts, 2); bounds.outset(SK_Scalar1, SK_Scalar1); bounds.roundOut(&ibounds); if (SkIRect::Intersects(devClipBounds, ibounds)) { SkPoint* pts = lines->push_back_n(2); pts[0] = devPts[0]; pts[1] = devPts[1]; } break; case SkPath::kQuad_Verb: { SkPoint choppedPts[5]; // Chopping the quad helps when the quad is either degenerate or nearly degenerate. // When it is degenerate it allows the approximation with lines to work since the // chop point (if there is one) will be at the parabola's vertex. In the nearly // degenerate the QuadUVMatrix computed for the points is almost singular which // can cause rendering artifacts. int n = SkChopQuadAtMaxCurvature(pathPts, choppedPts); for (int i = 0; i < n; ++i) { SkPoint* quadPts = choppedPts + i * 2; m.mapPoints(devPts, quadPts, 3); bounds.setBounds(devPts, 3); bounds.outset(SK_Scalar1, SK_Scalar1); bounds.roundOut(&ibounds); if (SkIRect::Intersects(devClipBounds, ibounds)) { int subdiv = num_quad_subdivs(devPts); SkASSERT(subdiv >= -1); if (-1 == subdiv) { SkPoint* pts = lines->push_back_n(4); pts[0] = devPts[0]; pts[1] = devPts[1]; pts[2] = devPts[1]; pts[3] = devPts[2]; } else { // when in perspective keep quads in src space SkPoint* qPts = persp ? quadPts : devPts; SkPoint* pts = quads->push_back_n(3); pts[0] = qPts[0]; pts[1] = qPts[1]; pts[2] = qPts[2]; quadSubdivCnts->push_back() = subdiv; totalQuadCount += 1 << subdiv; } } } break; } case SkPath::kCubic_Verb: m.mapPoints(devPts, pathPts, 4); bounds.setBounds(devPts, 4); bounds.outset(SK_Scalar1, SK_Scalar1); bounds.roundOut(&ibounds); if (SkIRect::Intersects(devClipBounds, ibounds)) { PREALLOC_PTARRAY(32) q; // we don't need a direction if we aren't constraining the subdivision const SkPathPriv::FirstDirection kDummyDir = SkPathPriv::kCCW_FirstDirection; // We convert cubics to quadratics (for now). // In perspective have to do conversion in src space. if (persp) { SkScalar tolScale = GrPathUtils::scaleToleranceToSrc(SK_Scalar1, m, path.getBounds()); GrPathUtils::convertCubicToQuads(pathPts, tolScale, false, kDummyDir, &q); } else { GrPathUtils::convertCubicToQuads(devPts, SK_Scalar1, false, kDummyDir, &q); } for (int i = 0; i < q.count(); i += 3) { SkPoint* qInDevSpace; // bounds has to be calculated in device space, but q is // in src space when there is perspective. if (persp) { m.mapPoints(devPts, &q[i], 3); bounds.setBounds(devPts, 3); qInDevSpace = devPts; } else { bounds.setBounds(&q[i], 3); qInDevSpace = &q[i]; } bounds.outset(SK_Scalar1, SK_Scalar1); bounds.roundOut(&ibounds); if (SkIRect::Intersects(devClipBounds, ibounds)) { int subdiv = num_quad_subdivs(qInDevSpace); SkASSERT(subdiv >= -1); if (-1 == subdiv) { SkPoint* pts = lines->push_back_n(4); // lines should always be in device coords pts[0] = qInDevSpace[0]; pts[1] = qInDevSpace[1]; pts[2] = qInDevSpace[1]; pts[3] = qInDevSpace[2]; } else { SkPoint* pts = quads->push_back_n(3); // q is already in src space when there is no // perspective and dev coords otherwise. pts[0] = q[0 + i]; pts[1] = q[1 + i]; pts[2] = q[2 + i]; quadSubdivCnts->push_back() = subdiv; totalQuadCount += 1 << subdiv; } } } } break; case SkPath::kClose_Verb: break; case SkPath::kDone_Verb: return totalQuadCount; } } } struct LineVertex { SkPoint fPos; float fCoverage; }; struct BezierVertex { SkPoint fPos; union { struct { SkScalar fK; SkScalar fL; SkScalar fM; } fConic; SkVector fQuadCoord; struct { SkScalar fBogus[4]; }; }; }; GR_STATIC_ASSERT(sizeof(BezierVertex) == 3 * sizeof(SkPoint)); static void intersect_lines(const SkPoint& ptA, const SkVector& normA, const SkPoint& ptB, const SkVector& normB, SkPoint* result) { SkScalar lineAW = -normA.dot(ptA); SkScalar lineBW = -normB.dot(ptB); SkScalar wInv = SkScalarMul(normA.fX, normB.fY) - SkScalarMul(normA.fY, normB.fX); wInv = SkScalarInvert(wInv); result->fX = SkScalarMul(normA.fY, lineBW) - SkScalarMul(lineAW, normB.fY); result->fX = SkScalarMul(result->fX, wInv); result->fY = SkScalarMul(lineAW, normB.fX) - SkScalarMul(normA.fX, lineBW); result->fY = SkScalarMul(result->fY, wInv); } static void set_uv_quad(const SkPoint qpts[3], BezierVertex verts[kQuadNumVertices]) { // this should be in the src space, not dev coords, when we have perspective GrPathUtils::QuadUVMatrix DevToUV(qpts); DevToUV.apply<kQuadNumVertices, sizeof(BezierVertex), sizeof(SkPoint)>(verts); } static void bloat_quad(const SkPoint qpts[3], const SkMatrix* toDevice, const SkMatrix* toSrc, BezierVertex verts[kQuadNumVertices]) { SkASSERT(!toDevice == !toSrc); // original quad is specified by tri a,b,c SkPoint a = qpts[0]; SkPoint b = qpts[1]; SkPoint c = qpts[2]; if (toDevice) { toDevice->mapPoints(&a, 1); toDevice->mapPoints(&b, 1); toDevice->mapPoints(&c, 1); } // make a new poly where we replace a and c by a 1-pixel wide edges orthog // to edges ab and bc: // // before | after // | b0 // b | // | // | a0 c0 // a c | a1 c1 // // edges a0->b0 and b0->c0 are parallel to original edges a->b and b->c, // respectively. BezierVertex& a0 = verts[0]; BezierVertex& a1 = verts[1]; BezierVertex& b0 = verts[2]; BezierVertex& c0 = verts[3]; BezierVertex& c1 = verts[4]; SkVector ab = b; ab -= a; SkVector ac = c; ac -= a; SkVector cb = b; cb -= c; // We should have already handled degenerates SkASSERT(ab.length() > 0 && cb.length() > 0); ab.normalize(); SkVector abN; abN.setOrthog(ab, SkVector::kLeft_Side); if (abN.dot(ac) > 0) { abN.negate(); } cb.normalize(); SkVector cbN; cbN.setOrthog(cb, SkVector::kLeft_Side); if (cbN.dot(ac) < 0) { cbN.negate(); } a0.fPos = a; a0.fPos += abN; a1.fPos = a; a1.fPos -= abN; c0.fPos = c; c0.fPos += cbN; c1.fPos = c; c1.fPos -= cbN; intersect_lines(a0.fPos, abN, c0.fPos, cbN, &b0.fPos); if (toSrc) { toSrc->mapPointsWithStride(&verts[0].fPos, sizeof(BezierVertex), kQuadNumVertices); } } // Equations based off of Loop-Blinn Quadratic GPU Rendering // Input Parametric: // P(t) = (P0*(1-t)^2 + 2*w*P1*t*(1-t) + P2*t^2) / (1-t)^2 + 2*w*t*(1-t) + t^2) // Output Implicit: // f(x, y, w) = f(P) = K^2 - LM // K = dot(k, P), L = dot(l, P), M = dot(m, P) // k, l, m are calculated in function GrPathUtils::getConicKLM static void set_conic_coeffs(const SkPoint p[3], BezierVertex verts[kQuadNumVertices], const SkScalar weight) { SkScalar klm[9]; GrPathUtils::getConicKLM(p, weight, klm); for (int i = 0; i < kQuadNumVertices; ++i) { const SkPoint pnt = verts[i].fPos; verts[i].fConic.fK = pnt.fX * klm[0] + pnt.fY * klm[1] + klm[2]; verts[i].fConic.fL = pnt.fX * klm[3] + pnt.fY * klm[4] + klm[5]; verts[i].fConic.fM = pnt.fX * klm[6] + pnt.fY * klm[7] + klm[8]; } } static void add_conics(const SkPoint p[3], const SkScalar weight, const SkMatrix* toDevice, const SkMatrix* toSrc, BezierVertex** vert) { bloat_quad(p, toDevice, toSrc, *vert); set_conic_coeffs(p, *vert, weight); *vert += kQuadNumVertices; } static void add_quads(const SkPoint p[3], int subdiv, const SkMatrix* toDevice, const SkMatrix* toSrc, BezierVertex** vert) { SkASSERT(subdiv >= 0); if (subdiv) { SkPoint newP[5]; SkChopQuadAtHalf(p, newP); add_quads(newP + 0, subdiv-1, toDevice, toSrc, vert); add_quads(newP + 2, subdiv-1, toDevice, toSrc, vert); } else { bloat_quad(p, toDevice, toSrc, *vert); set_uv_quad(p, *vert); *vert += kQuadNumVertices; } } static void add_line(const SkPoint p[2], const SkMatrix* toSrc, uint8_t coverage, LineVertex** vert) { const SkPoint& a = p[0]; const SkPoint& b = p[1]; SkVector ortho, vec = b; vec -= a; if (vec.setLength(SK_ScalarHalf)) { // Create a vector orthogonal to 'vec' and of unit length ortho.fX = 2.0f * vec.fY; ortho.fY = -2.0f * vec.fX; float floatCoverage = GrNormalizeByteToFloat(coverage); (*vert)[0].fPos = a; (*vert)[0].fCoverage = floatCoverage; (*vert)[1].fPos = b; (*vert)[1].fCoverage = floatCoverage; (*vert)[2].fPos = a - vec + ortho; (*vert)[2].fCoverage = 0; (*vert)[3].fPos = b + vec + ortho; (*vert)[3].fCoverage = 0; (*vert)[4].fPos = a - vec - ortho; (*vert)[4].fCoverage = 0; (*vert)[5].fPos = b + vec - ortho; (*vert)[5].fCoverage = 0; if (toSrc) { toSrc->mapPointsWithStride(&(*vert)->fPos, sizeof(LineVertex), kLineSegNumVertices); } } else { // just make it degenerate and likely offscreen for (int i = 0; i < kLineSegNumVertices; ++i) { (*vert)[i].fPos.set(SK_ScalarMax, SK_ScalarMax); } } *vert += kLineSegNumVertices; } /////////////////////////////////////////////////////////////////////////////// bool GrAAHairLinePathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const { if (!args.fAntiAlias) { return false; } if (!IsStrokeHairlineOrEquivalent(*args.fStroke, *args.fViewMatrix, NULL)) { return false; } if (SkPath::kLine_SegmentMask == args.fPath->getSegmentMasks() || args.fShaderCaps->shaderDerivativeSupport()) { return true; } return false; } template <class VertexType> bool check_bounds(const SkMatrix& viewMatrix, const SkRect& devBounds, void* vertices, int vCount) { SkRect tolDevBounds = devBounds; // The bounds ought to be tight, but in perspective the below code runs the verts // through the view matrix to get back to dev coords, which can introduce imprecision. if (viewMatrix.hasPerspective()) { tolDevBounds.outset(SK_Scalar1 / 1000, SK_Scalar1 / 1000); } else { // Non-persp matrices cause this path renderer to draw in device space. SkASSERT(viewMatrix.isIdentity()); } SkRect actualBounds; VertexType* verts = reinterpret_cast<VertexType*>(vertices); bool first = true; for (int i = 0; i < vCount; ++i) { SkPoint pos = verts[i].fPos; // This is a hack to workaround the fact that we move some degenerate segments offscreen. if (SK_ScalarMax == pos.fX) { continue; } viewMatrix.mapPoints(&pos, 1); if (first) { actualBounds.set(pos.fX, pos.fY, pos.fX, pos.fY); first = false; } else { actualBounds.growToInclude(pos.fX, pos.fY); } } if (!first) { return tolDevBounds.contains(actualBounds); } return true; } class AAHairlineBatch : public GrVertexBatch { public: struct Geometry { GrColor fColor; uint8_t fCoverage; SkMatrix fViewMatrix; SkPath fPath; SkIRect fDevClipBounds; }; static GrDrawBatch* Create(const Geometry& geometry) { return SkNEW_ARGS(AAHairlineBatch, (geometry)); } const char* name() const override { return "AAHairlineBatch"; } void getInvariantOutputColor(GrInitInvariantOutput* out) const override { // When this is called on a batch, there is only one geometry bundle out->setKnownFourComponents(fGeoData[0].fColor); } void getInvariantOutputCoverage(GrInitInvariantOutput* out) const override { out->setUnknownSingleComponent(); } void initBatchTracker(const GrPipelineOptimizations& opt) override { // Handle any color overrides if (!opt.readsColor()) { fGeoData[0].fColor = GrColor_ILLEGAL; } opt.getOverrideColorIfSet(&fGeoData[0].fColor); // setup batch properties fBatch.fColorIgnored = !opt.readsColor(); fBatch.fColor = fGeoData[0].fColor; fBatch.fUsesLocalCoords = opt.readsLocalCoords(); fBatch.fCoverageIgnored = !opt.readsCoverage(); fBatch.fCoverage = fGeoData[0].fCoverage; } void generateGeometry(GrBatchTarget* batchTarget) override; SkSTArray<1, Geometry, true>* geoData() { return &fGeoData; } private: typedef SkTArray<SkPoint, true> PtArray; typedef SkTArray<int, true> IntArray; typedef SkTArray<float, true> FloatArray; AAHairlineBatch(const Geometry& geometry) { this->initClassID<AAHairlineBatch>(); fGeoData.push_back(geometry); // compute bounds fBounds = geometry.fPath.getBounds(); geometry.fViewMatrix.mapRect(&fBounds); // This is b.c. hairlines are notionally infinitely thin so without expansion // two overlapping lines could be reordered even though they hit the same pixels. fBounds.outset(0.5f, 0.5f); } bool onCombineIfPossible(GrBatch* t, const GrCaps& caps) override { AAHairlineBatch* that = t->cast<AAHairlineBatch>(); if (!GrPipeline::CanCombine(*this->pipeline(), this->bounds(), *that->pipeline(), that->bounds(), caps)) { return false; } if (this->viewMatrix().hasPerspective() != that->viewMatrix().hasPerspective()) { return false; } // We go to identity if we don't have perspective if (this->viewMatrix().hasPerspective() && !this->viewMatrix().cheapEqualTo(that->viewMatrix())) { return false; } // TODO we can actually batch hairlines if they are the same color in a kind of bulk method // but we haven't implemented this yet // TODO investigate going to vertex color and coverage? if (this->coverage() != that->coverage()) { return false; } if (this->color() != that->color()) { return false; } SkASSERT(this->usesLocalCoords() == that->usesLocalCoords()); if (this->usesLocalCoords() && !this->viewMatrix().cheapEqualTo(that->viewMatrix())) { return false; } fGeoData.push_back_n(that->geoData()->count(), that->geoData()->begin()); this->joinBounds(that->bounds()); return true; } GrColor color() const { return fBatch.fColor; } uint8_t coverage() const { return fBatch.fCoverage; } bool usesLocalCoords() const { return fBatch.fUsesLocalCoords; } const SkMatrix& viewMatrix() const { return fGeoData[0].fViewMatrix; } bool coverageIgnored() const { return fBatch.fCoverageIgnored; } struct BatchTracker { GrColor fColor; uint8_t fCoverage; SkRect fDevBounds; bool fUsesLocalCoords; bool fColorIgnored; bool fCoverageIgnored; }; BatchTracker fBatch; SkSTArray<1, Geometry, true> fGeoData; }; void AAHairlineBatch::generateGeometry(GrBatchTarget* batchTarget) { // Setup the viewmatrix and localmatrix for the GrGeometryProcessor. SkMatrix invert; if (!this->viewMatrix().invert(&invert)) { return; } // we will transform to identity space if the viewmatrix does not have perspective bool hasPerspective = this->viewMatrix().hasPerspective(); const SkMatrix* geometryProcessorViewM = &SkMatrix::I(); const SkMatrix* geometryProcessorLocalM = &invert; const SkMatrix* toDevice = NULL; const SkMatrix* toSrc = NULL; if (hasPerspective) { geometryProcessorViewM = &this->viewMatrix(); geometryProcessorLocalM = &SkMatrix::I(); toDevice = &this->viewMatrix(); toSrc = &invert; } SkAutoTUnref<const GrGeometryProcessor> lineGP; { using namespace GrDefaultGeoProcFactory; Color color(this->color()); Coverage coverage(Coverage::kAttribute_Type); LocalCoords localCoords(this->usesLocalCoords() ? LocalCoords::kUsePosition_Type : LocalCoords::kUnused_Type); localCoords.fMatrix = geometryProcessorLocalM; lineGP.reset(GrDefaultGeoProcFactory::Create(color, coverage, localCoords, *geometryProcessorViewM)); } SkAutoTUnref<const GrGeometryProcessor> quadGP( GrQuadEffect::Create(this->color(), *geometryProcessorViewM, kHairlineAA_GrProcessorEdgeType, batchTarget->caps(), *geometryProcessorLocalM, this->usesLocalCoords(), this->coverage())); SkAutoTUnref<const GrGeometryProcessor> conicGP( GrConicEffect::Create(this->color(), *geometryProcessorViewM, kHairlineAA_GrProcessorEdgeType, batchTarget->caps(), *geometryProcessorLocalM, this->usesLocalCoords(), this->coverage())); // This is hand inlined for maximum performance. PREALLOC_PTARRAY(128) lines; PREALLOC_PTARRAY(128) quads; PREALLOC_PTARRAY(128) conics; IntArray qSubdivs; FloatArray cWeights; int quadCount = 0; int instanceCount = fGeoData.count(); for (int i = 0; i < instanceCount; i++) { const Geometry& args = fGeoData[i]; quadCount += gather_lines_and_quads(args.fPath, args.fViewMatrix, args.fDevClipBounds, &lines, &quads, &conics, &qSubdivs, &cWeights); } int lineCount = lines.count() / 2; int conicCount = conics.count() / 3; // do lines first if (lineCount) { SkAutoTUnref<const GrIndexBuffer> linesIndexBuffer( ref_lines_index_buffer(batchTarget->resourceProvider())); batchTarget->initDraw(lineGP, this->pipeline()); const GrVertexBuffer* vertexBuffer; int firstVertex; size_t vertexStride = lineGP->getVertexStride(); int vertexCount = kLineSegNumVertices * lineCount; LineVertex* verts = reinterpret_cast<LineVertex*>( batchTarget->makeVertSpace(vertexStride, vertexCount, &vertexBuffer, &firstVertex)); if (!verts|| !linesIndexBuffer) { SkDebugf("Could not allocate vertices\n"); return; } SkASSERT(lineGP->getVertexStride() == sizeof(LineVertex)); for (int i = 0; i < lineCount; ++i) { add_line(&lines[2*i], toSrc, this->coverage(), &verts); } { GrVertices vertices; vertices.initInstanced(kTriangles_GrPrimitiveType, vertexBuffer, linesIndexBuffer, firstVertex, kLineSegNumVertices, kIdxsPerLineSeg, lineCount, kLineSegsNumInIdxBuffer); batchTarget->draw(vertices); } } if (quadCount || conicCount) { const GrVertexBuffer* vertexBuffer; int firstVertex; SkAutoTUnref<const GrIndexBuffer> quadsIndexBuffer( ref_quads_index_buffer(batchTarget->resourceProvider())); size_t vertexStride = sizeof(BezierVertex); int vertexCount = kQuadNumVertices * quadCount + kQuadNumVertices * conicCount; void *vertices = batchTarget->makeVertSpace(vertexStride, vertexCount, &vertexBuffer, &firstVertex); if (!vertices || !quadsIndexBuffer) { SkDebugf("Could not allocate vertices\n"); return; } // Setup vertices BezierVertex* verts = reinterpret_cast<BezierVertex*>(vertices); int unsubdivQuadCnt = quads.count() / 3; for (int i = 0; i < unsubdivQuadCnt; ++i) { SkASSERT(qSubdivs[i] >= 0); add_quads(&quads[3*i], qSubdivs[i], toDevice, toSrc, &verts); } // Start Conics for (int i = 0; i < conicCount; ++i) { add_conics(&conics[3*i], cWeights[i], toDevice, toSrc, &verts); } if (quadCount > 0) { batchTarget->initDraw(quadGP, this->pipeline()); { GrVertices verts; verts.initInstanced(kTriangles_GrPrimitiveType, vertexBuffer, quadsIndexBuffer, firstVertex, kQuadNumVertices, kIdxsPerQuad, quadCount, kQuadsNumInIdxBuffer); batchTarget->draw(verts); firstVertex += quadCount * kQuadNumVertices; } } if (conicCount > 0) { batchTarget->initDraw(conicGP, this->pipeline()); { GrVertices verts; verts.initInstanced(kTriangles_GrPrimitiveType, vertexBuffer, quadsIndexBuffer, firstVertex, kQuadNumVertices, kIdxsPerQuad, conicCount, kQuadsNumInIdxBuffer); batchTarget->draw(verts); } } } } static GrDrawBatch* create_hairline_batch(GrColor color, const SkMatrix& viewMatrix, const SkPath& path, const GrStrokeInfo& stroke, const SkIRect& devClipBounds) { SkScalar hairlineCoverage; uint8_t newCoverage = 0xff; if (GrPathRenderer::IsStrokeHairlineOrEquivalent(stroke, viewMatrix, &hairlineCoverage)) { newCoverage = SkScalarRoundToInt(hairlineCoverage * 0xff); } AAHairlineBatch::Geometry geometry; geometry.fColor = color; geometry.fCoverage = newCoverage; geometry.fViewMatrix = viewMatrix; geometry.fPath = path; geometry.fDevClipBounds = devClipBounds; return AAHairlineBatch::Create(geometry); } bool GrAAHairLinePathRenderer::onDrawPath(const DrawPathArgs& args) { SkIRect devClipBounds; args.fPipelineBuilder->clip().getConservativeBounds(args.fPipelineBuilder->getRenderTarget(), &devClipBounds); SkAutoTUnref<GrDrawBatch> batch(create_hairline_batch(args.fColor, *args.fViewMatrix, *args.fPath, *args.fStroke, devClipBounds)); args.fTarget->drawBatch(*args.fPipelineBuilder, batch); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef GR_TEST_UTILS DRAW_BATCH_TEST_DEFINE(AAHairlineBatch) { GrColor color = GrRandomColor(random); SkMatrix viewMatrix = GrTest::TestMatrix(random); GrStrokeInfo stroke(SkStrokeRec::kHairline_InitStyle); SkPath path = GrTest::TestPath(random); SkIRect devClipBounds; devClipBounds.setEmpty(); return create_hairline_batch(color, viewMatrix, path, stroke, devClipBounds); } #endif
nvoron23/skia
src/gpu/GrAAHairLinePathRenderer.cpp
C++
bsd-3-clause
36,575
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_22) on Wed Mar 02 16:46:01 EST 2011 --> <TITLE> Uses of Class gov.nih.nci.cabig.caaers.audit.AuditInfoPopulatorInterceptor </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Class gov.nih.nci.cabig.caaers.audit.AuditInfoPopulatorInterceptor"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../gov/nih/nci/cabig/caaers/audit/AuditInfoPopulatorInterceptor.html" title="class in gov.nih.nci.cabig.caaers.audit"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&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;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?gov/nih/nci/cabig/caaers/audit/class-use/AuditInfoPopulatorInterceptor.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="AuditInfoPopulatorInterceptor.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> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>gov.nih.nci.cabig.caaers.audit.AuditInfoPopulatorInterceptor</B></H2> </CENTER> No usage of gov.nih.nci.cabig.caaers.audit.AuditInfoPopulatorInterceptor <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <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="navbar_bottom_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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../gov/nih/nci/cabig/caaers/audit/AuditInfoPopulatorInterceptor.html" title="class in gov.nih.nci.cabig.caaers.audit"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&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;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?gov/nih/nci/cabig/caaers/audit/class-use/AuditInfoPopulatorInterceptor.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="AuditInfoPopulatorInterceptor.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> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
NCIP/caaers
caAERS/software/docs/gov/nih/nci/cabig/caaers/audit/class-use/AuditInfoPopulatorInterceptor.html
HTML
bsd-3-clause
6,272
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opencl; import javax.annotation.*; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.JNI.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.Pointer.*; /** * Native bindings to the <strong>khr_command_buffer</strong> extension. * * <p>Command-buffers enable a reduction in overhead when enqueuing the same workload multiple times. By separating the command-queue setup from dispatch, * the ability to replay a set of previously created commands is introduced.</p> * * <p>Device-side {@code cl_sync_point_khr} synchronization-points can be used within command-buffers to define command dependencies. This allows the * commands of a command-buffer to execute out-of-order on a single compatible command-queue. The command-buffer itself has no inherent * in-order/out-of-order property, this ordering is inferred from the command-queue used on command recording. Out-of-order enqueues without event * dependencies of both regular commands, such as {@link CL12#clEnqueueFillBuffer EnqueueFillBuffer}, and command-buffers are allowed to execute concurrently, and it is up to the user * to express any dependencies using events.</p> * * <p>The command-queues a command-buffer will be executed on can be set on replay via parameters to {@link #clEnqueueCommandBufferKHR EnqueueCommandBufferKHR}, provided they are compatible * with the command-queues used on command-buffer recording.</p> * * <p>Requires {@link CL12 CL12}.</p> */ public class KHRCommandBuffer { /** Accepted values for the {@code param_name} parameter to {@link CL10#clGetDeviceInfo GetDeviceInfo}. */ public static final int CL_DEVICE_COMMAND_BUFFER_CAPABILITIES_KHR = 0x12A9, CL_DEVICE_COMMAND_BUFFER_REQUIRED_QUEUE_PROPERTIES_KHR = 0x12AA; /** Bits for {@code cl_device_command_buffer_capabilities_khr} bitfield. */ public static final int CL_COMMAND_BUFFER_CAPABILITY_KERNEL_PRINTF_KHR = 0x1 << 0, CL_COMMAND_BUFFER_CAPABILITY_DEVICE_SIDE_ENQUEUE_KHR = 0x1 << 1, CL_COMMAND_BUFFER_CAPABILITY_SIMULTANEOUS_USE_KHR = 0x1 << 2, CL_COMMAND_BUFFER_CAPABILITY_OUT_OF_ORDER_KHR = 0x1 << 3; /** Values for {@code cl_command_buffer_state_khr}. */ public static final int CL_COMMAND_BUFFER_STATE_RECORDING_KHR = 0x0, CL_COMMAND_BUFFER_STATE_EXECUTABLE_KHR = 0x1, CL_COMMAND_BUFFER_STATE_PENDING_KHR = 0x2, CL_COMMAND_BUFFER_STATE_INVALID_KHR = 0x3; /** Error codes. */ public static final int CL_INVALID_COMMAND_BUFFER_KHR = -1138, CL_INVALID_SYNC_POINT_WAIT_LIST_KHR = -1139, CL_INCOMPATIBLE_COMMAND_QUEUE_KHR = -1140; /** Bitfield to {@link #clCreateCommandBufferKHR CreateCommandBufferKHR}. */ public static final int CL_COMMAND_BUFFER_FLAGS_KHR = 0x1293; /** Bits for {@code cl_command_buffer_flags_khr} bitfield. */ public static final int CL_COMMAND_BUFFER_SIMULTANEOUS_USE_KHR = 0x1 << 0; /** {@code cl_command_buffer_info_khr} queries to {@link #clGetCommandBufferInfoKHR GetCommandBufferInfoKHR}. */ public static final int CL_COMMAND_BUFFER_QUEUES_KHR = 0x1294, CL_COMMAND_BUFFER_NUM_QUEUES_KHR = 0x1295, CL_COMMAND_BUFFER_REFERENCE_COUNT_KHR = 0x1296, CL_COMMAND_BUFFER_STATE_KHR = 0x1297, CL_COMMAND_BUFFER_PROPERTIES_ARRAY_KHR = 0x1298; /** {@code cl_event} command-buffer enqueue command type. */ public static final int CL_COMMAND_COMMAND_BUFFER_KHR = 0x12A8; protected KHRCommandBuffer() { throw new UnsupportedOperationException(); } // --- [ clCreateCommandBufferKHR ] --- /** * Unsafe version of: {@link #clCreateCommandBufferKHR CreateCommandBufferKHR} * * @param num_queues the number of command-queues listed in {@code queues}. This extension only supports a single command-queue, so this <b>must</b> be one. */ public static long nclCreateCommandBufferKHR(int num_queues, long queues, long properties, long errcode_ret) { long __functionAddress = CL.getICD().clCreateCommandBufferKHR; if (CHECKS) { check(__functionAddress); } return callPPPP(num_queues, queues, properties, errcode_ret, __functionAddress); } /** * Creates a command-buffer that can record commands to the specified queues. * * @param queues a pointer to a command-queue that the command-buffer commands will be recorded to. {@code queues must} be a non-{@code NULL} value. * @param properties a list of properties for the command-buffer and their corresponding values. * * <p>Each property name is immediately followed by the corresponding desired value. The list is terminated with 0. If a supported property and its value * is not specified in properties, its default value will be used. {@code properties} can be {@code NULL} in which case the default values for supported * command-buffer properties will be used.</p> * @param errcode_ret will return an appropriate error code. If {@code errcode_ret} is {@code NULL}, no error code is returned. */ @NativeType("cl_command_buffer_khr") public static long clCreateCommandBufferKHR(@NativeType("cl_command_queue const *") PointerBuffer queues, @Nullable @NativeType("cl_command_buffer_properties_khr const *") LongBuffer properties, @Nullable @NativeType("cl_int *") IntBuffer errcode_ret) { if (CHECKS) { checkNTSafe(properties); checkSafe(errcode_ret, 1); } return nclCreateCommandBufferKHR(queues.remaining(), memAddress(queues), memAddressSafe(properties), memAddressSafe(errcode_ret)); } // --- [ clRetainCommandBufferKHR ] --- /** * Increments the {@code command_buffer} reference count. * * @param command_buffer the command-buffer to retain */ @NativeType("cl_int") public static int clRetainCommandBufferKHR(@NativeType("cl_command_buffer_khr") long command_buffer) { long __functionAddress = CL.getICD().clRetainCommandBufferKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); } return callPI(command_buffer, __functionAddress); } // --- [ clReleaseCommandBufferKHR ] --- /** * Decrements the {@code command_buffer} reference count. * * @param command_buffer the command-buffer to release */ @NativeType("cl_int") public static int clReleaseCommandBufferKHR(@NativeType("cl_command_buffer_khr") long command_buffer) { long __functionAddress = CL.getICD().clReleaseCommandBufferKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); } return callPI(command_buffer, __functionAddress); } // --- [ clFinalizeCommandBufferKHR ] --- /** * Finalizes command recording ready for enqueuing the command-buffer on a command-queue. * * @param command_buffer a valid command-buffer object */ @NativeType("cl_int") public static int clFinalizeCommandBufferKHR(@NativeType("cl_command_buffer_khr") long command_buffer) { long __functionAddress = CL.getICD().clFinalizeCommandBufferKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); } return callPI(command_buffer, __functionAddress); } // --- [ clEnqueueCommandBufferKHR ] --- /** * Unsafe version of: {@link #clEnqueueCommandBufferKHR EnqueueCommandBufferKHR} * * @param num_queues the number of command-queues listed in {@code queues} * @param num_events_in_wait_list the number of events in {@code event_wait_list} */ public static int nclEnqueueCommandBufferKHR(int num_queues, long queues, long command_buffer, int num_events_in_wait_list, long event_wait_list, long event) { long __functionAddress = CL.getICD().clEnqueueCommandBufferKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); } return callPPPPI(num_queues, queues, command_buffer, num_events_in_wait_list, event_wait_list, event, __functionAddress); } /** * Enqueues a command-buffer to execute on command-queues specified by {@code queues, or} on default command-queues used during recording if * {@code queues} is empty. * * @param queues a pointer to an ordered list of command-queues compatible with the command-queues used on recording. * * <p>{@code queues} can be {@code NULL} in which case the default command-queues used on command-buffer creation are used and {@code num_queues} must be 0.</p> * @param command_buffer a valid command-buffer object * @param event_wait_list a list of events that need to complete before this particular command can be executed. If {@code event_wait_list} is {@code NULL}, then this particular command * does not wait on any event to complete. The events specified in {@code event_wait_list} act as synchronization points. The context associated with events in * {@code event_wait_list} and {@code command_queue} must be the same. * @param event Returns an event object that identifies this particular command and can be used to query or queue a wait for this particular command to complete. * {@code event} can be {@code NULL} in which case it will not be possible for the application to query the status of this command or queue a wait for this command to * complete. If the {@code event_wait_list} and the {@code event} arguments are not {@code NULL}, the event argument should not refer to an element of the * {@code event_wait_list} array. */ @NativeType("cl_int") public static int clEnqueueCommandBufferKHR(@Nullable @NativeType("cl_command_queue *") PointerBuffer queues, @NativeType("cl_command_buffer_khr") long command_buffer, @Nullable @NativeType("cl_event const *") PointerBuffer event_wait_list, @Nullable @NativeType("cl_event *") PointerBuffer event) { if (CHECKS) { checkSafe(event, 1); } return nclEnqueueCommandBufferKHR(remainingSafe(queues), memAddressSafe(queues), command_buffer, remainingSafe(event_wait_list), memAddressSafe(event_wait_list), memAddressSafe(event)); } // --- [ clCommandBarrierWithWaitListKHR ] --- /** Unsafe version of: {@link #clCommandBarrierWithWaitListKHR CommandBarrierWithWaitListKHR} */ public static int nclCommandBarrierWithWaitListKHR(long command_buffer, long command_queue, int num_sync_points_in_wait_list, long sync_point_wait_list, long sync_point, long mutable_handle) { long __functionAddress = CL.getICD().clCommandBarrierWithWaitListKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); } return callPPPPPI(command_buffer, command_queue, num_sync_points_in_wait_list, sync_point_wait_list, sync_point, mutable_handle, __functionAddress); } /** * Records a barrier operation used as a synchronization point. * * @param command_buffer a valid command-buffer object * @param command_queue the command-queue the command will be recorded to. * * <p>Parameter is unused by this extension as only a single command-queue is supported and <b>must</b> be {@code NULL}.</p> * @param sync_point_wait_list the synchronization-points that need to complete before this particular command can be executed. * * <p>If {@code sync_point_wait_list} is {@code NULL}, {@code num_sync_points_in_wait_list} must be 0. If {@code sync_point_wait_list} is not {@code NULL}, the list of * synchronization-points pointed to by {@code sync_point_wait_list} must be valid and {@code num_sync_points_in_wait_list} must be greater than 0. * The synchronization-points specified in {@code sync_point_wait_list} are <b>device side</b> synchronization-points. The command-buffer associated * with synchronization-points in {@code sync_point_wait_list} must be the same as {@code command_buffer}. The memory associated with * {@code sync_point_wait_list} can be reused or freed after the function returns.</p> * * <p>If {@code sync_point_wait_list} is {@code NULL}, then this particular command waits until all previous recorded commands to {@code command_queue} have * completed.</p> * @param sync_point returns a synchronization-point ID that identifies this particular command. * * <p>Synchronization-point objects are unique and can be used to identify this barrier command later on. {@code sync_point} can be {@code NULL} in which case * it will not be possible for the application to record a wait for this command to complete. If the {@code sync_point_wait_list} and the * {@code sync_point} arguments are not {@code NULL}, the {@code sync_point} argument should not refer to an element of the {@code sync_point_wait_list} * array.</p> * @param mutable_handle returns a handle to the command. * * <p>Handle is unused by this extension and must be passed as {@code NULL}.</p> */ @NativeType("cl_int") public static int clCommandBarrierWithWaitListKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @Nullable @NativeType("cl_sync_point_khr const *") IntBuffer sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") IntBuffer sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { if (CHECKS) { checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return nclCommandBarrierWithWaitListKHR(command_buffer, command_queue, remainingSafe(sync_point_wait_list), memAddressSafe(sync_point_wait_list), memAddressSafe(sync_point), memAddressSafe(mutable_handle)); } // --- [ clCommandCopyBufferKHR ] --- /** Unsafe version of: {@link #clCommandCopyBufferKHR CommandCopyBufferKHR} */ public static int nclCommandCopyBufferKHR(long command_buffer, long command_queue, long src_buffer, long dst_buffer, long src_offset, long dst_offset, long size, int num_sync_points_in_wait_list, long sync_point_wait_list, long sync_point, long mutable_handle) { long __functionAddress = CL.getICD().clCommandCopyBufferKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(src_buffer); check(dst_buffer); } return callPPPPPPPPPPI(command_buffer, command_queue, src_buffer, dst_buffer, src_offset, dst_offset, size, num_sync_points_in_wait_list, sync_point_wait_list, sync_point, mutable_handle, __functionAddress); } /** * Records a command to copy from one buffer object to another. * * @param command_buffer a valid command-buffer object * @param command_queue the command-queue the command will be recorded to. * * <p>Parameter is unused by this extension as only a single command-queue is supported and <b>must</b> be {@code NULL}.</p> * @param sync_point_wait_list the synchronization-points that need to complete before this particular command can be executed. * * <p>If {@code sync_point_wait_list} is {@code NULL}, {@code num_sync_points_in_wait_list} must be 0. If {@code sync_point_wait_list} is not {@code NULL}, the list of * synchronization-points pointed to by {@code sync_point_wait_list} must be valid and {@code num_sync_points_in_wait_list} must be greater than 0. * The synchronization-points specified in {@code sync_point_wait_list} are <b>device side</b> synchronization-points. The command-buffer associated * with synchronization-points in {@code sync_point_wait_list} must be the same as {@code command_buffer}. The memory associated with * {@code sync_point_wait_list} can be reused or freed after the function returns.</p> * * <p>If {@code sync_point_wait_list} is {@code NULL}, then this particular command waits until all previous recorded commands to {@code command_queue} have * completed.</p> * @param sync_point returns a synchronization-point ID that identifies this particular command. * * <p>Synchronization-point objects are unique and can be used to identify this barrier command later on. {@code sync_point} can be {@code NULL} in which case * it will not be possible for the application to record a wait for this command to complete. If the {@code sync_point_wait_list} and the * {@code sync_point} arguments are not {@code NULL}, the {@code sync_point} argument should not refer to an element of the {@code sync_point_wait_list} * array.</p> * @param mutable_handle returns a handle to the command. * * <p>Handle is unused by this extension and must be passed as {@code NULL}.</p> */ @NativeType("cl_int") public static int clCommandCopyBufferKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long src_buffer, @NativeType("cl_mem") long dst_buffer, @NativeType("size_t") long src_offset, @NativeType("size_t") long dst_offset, @NativeType("size_t") long size, @Nullable @NativeType("cl_sync_point_khr const *") IntBuffer sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") IntBuffer sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { if (CHECKS) { checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return nclCommandCopyBufferKHR(command_buffer, command_queue, src_buffer, dst_buffer, src_offset, dst_offset, size, remainingSafe(sync_point_wait_list), memAddressSafe(sync_point_wait_list), memAddressSafe(sync_point), memAddressSafe(mutable_handle)); } // --- [ clCommandCopyBufferRectKHR ] --- /** Unsafe version of: {@link #clCommandCopyBufferRectKHR CommandCopyBufferRectKHR} */ public static int nclCommandCopyBufferRectKHR(long command_buffer, long command_queue, long src_buffer, long dst_buffer, long src_origin, long dst_origin, long region, long src_row_pitch, long src_slice_pitch, long dst_row_pitch, long dst_slice_pitch, int num_sync_points_in_wait_list, long sync_point_wait_list, long sync_point, long mutable_handle) { long __functionAddress = CL.getICD().clCommandCopyBufferRectKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(src_buffer); check(dst_buffer); } return callPPPPPPPPPPPPPPI(command_buffer, command_queue, src_buffer, dst_buffer, src_origin, dst_origin, region, src_row_pitch, src_slice_pitch, dst_row_pitch, dst_slice_pitch, num_sync_points_in_wait_list, sync_point_wait_list, sync_point, mutable_handle, __functionAddress); } /** * Records a command to copy a rectangular region from a buffer object to another buffer object. * * @param command_buffer a valid command-buffer object * @param command_queue the command-queue the command will be recorded to. * * <p>Parameter is unused by this extension as only a single command-queue is supported and <b>must</b> be {@code NULL}.</p> * @param sync_point_wait_list the synchronization-points that need to complete before this particular command can be executed. * * <p>If {@code sync_point_wait_list} is {@code NULL}, {@code num_sync_points_in_wait_list} must be 0. If {@code sync_point_wait_list} is not {@code NULL}, the list of * synchronization-points pointed to by {@code sync_point_wait_list} must be valid and {@code num_sync_points_in_wait_list} must be greater than 0. * The synchronization-points specified in {@code sync_point_wait_list} are <b>device side</b> synchronization-points. The command-buffer associated * with synchronization-points in {@code sync_point_wait_list} must be the same as {@code command_buffer}. The memory associated with * {@code sync_point_wait_list} can be reused or freed after the function returns.</p> * * <p>If {@code sync_point_wait_list} is {@code NULL}, then this particular command waits until all previous recorded commands to {@code command_queue} have * completed.</p> * @param sync_point returns a synchronization-point ID that identifies this particular command. * * <p>Synchronization-point objects are unique and can be used to identify this barrier command later on. {@code sync_point} can be {@code NULL} in which case * it will not be possible for the application to record a wait for this command to complete. If the {@code sync_point_wait_list} and the * {@code sync_point} arguments are not {@code NULL}, the {@code sync_point} argument should not refer to an element of the {@code sync_point_wait_list} * array.</p> * @param mutable_handle returns a handle to the command. * * <p>Handle is unused by this extension and must be passed as {@code NULL}.</p> */ @NativeType("cl_int") public static int clCommandCopyBufferRectKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long src_buffer, @NativeType("cl_mem") long dst_buffer, @NativeType("size_t const *") PointerBuffer src_origin, @NativeType("size_t const *") PointerBuffer dst_origin, @NativeType("size_t const *") PointerBuffer region, @NativeType("size_t") long src_row_pitch, @NativeType("size_t") long src_slice_pitch, @NativeType("size_t") long dst_row_pitch, @NativeType("size_t") long dst_slice_pitch, @Nullable @NativeType("cl_sync_point_khr const *") IntBuffer sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") IntBuffer sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { if (CHECKS) { check(src_origin, 3); check(dst_origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return nclCommandCopyBufferRectKHR(command_buffer, command_queue, src_buffer, dst_buffer, memAddress(src_origin), memAddress(dst_origin), memAddress(region), src_row_pitch, src_slice_pitch, dst_row_pitch, dst_slice_pitch, remainingSafe(sync_point_wait_list), memAddressSafe(sync_point_wait_list), memAddressSafe(sync_point), memAddressSafe(mutable_handle)); } // --- [ clCommandCopyBufferToImageKHR ] --- /** Unsafe version of: {@link #clCommandCopyBufferToImageKHR CommandCopyBufferToImageKHR} */ public static int nclCommandCopyBufferToImageKHR(long command_buffer, long command_queue, long src_buffer, long dst_image, long src_offset, long dst_origin, long region, int num_sync_points_in_wait_list, long sync_point_wait_list, long sync_point, long mutable_handle) { long __functionAddress = CL.getICD().clCommandCopyBufferToImageKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(src_buffer); check(dst_image); } return callPPPPPPPPPPI(command_buffer, command_queue, src_buffer, dst_image, src_offset, dst_origin, region, num_sync_points_in_wait_list, sync_point_wait_list, sync_point, mutable_handle, __functionAddress); } /** * Records a command to copy a buffer object to an image object. * * @param command_buffer a valid command-buffer object * @param command_queue the command-queue the command will be recorded to. * * <p>Parameter is unused by this extension as only a single command-queue is supported and <b>must</b> be {@code NULL}.</p> * @param sync_point_wait_list the synchronization-points that need to complete before this particular command can be executed. * * <p>If {@code sync_point_wait_list} is {@code NULL}, {@code num_sync_points_in_wait_list} must be 0. If {@code sync_point_wait_list} is not {@code NULL}, the list of * synchronization-points pointed to by {@code sync_point_wait_list} must be valid and {@code num_sync_points_in_wait_list} must be greater than 0. * The synchronization-points specified in {@code sync_point_wait_list} are <b>device side</b> synchronization-points. The command-buffer associated * with synchronization-points in {@code sync_point_wait_list} must be the same as {@code command_buffer}. The memory associated with * {@code sync_point_wait_list} can be reused or freed after the function returns.</p> * * <p>If {@code sync_point_wait_list} is {@code NULL}, then this particular command waits until all previous recorded commands to {@code command_queue} have * completed.</p> * @param sync_point returns a synchronization-point ID that identifies this particular command. * * <p>Synchronization-point objects are unique and can be used to identify this barrier command later on. {@code sync_point} can be {@code NULL} in which case * it will not be possible for the application to record a wait for this command to complete. If the {@code sync_point_wait_list} and the * {@code sync_point} arguments are not {@code NULL}, the {@code sync_point} argument should not refer to an element of the {@code sync_point_wait_list} * array.</p> * @param mutable_handle returns a handle to the command. * * <p>Handle is unused by this extension and must be passed as {@code NULL}.</p> */ @NativeType("cl_int") public static int clCommandCopyBufferToImageKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long src_buffer, @NativeType("cl_mem") long dst_image, @NativeType("size_t") long src_offset, @NativeType("size_t const *") PointerBuffer dst_origin, @NativeType("size_t const *") PointerBuffer region, @Nullable @NativeType("cl_sync_point_khr const *") IntBuffer sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") IntBuffer sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { if (CHECKS) { check(dst_origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return nclCommandCopyBufferToImageKHR(command_buffer, command_queue, src_buffer, dst_image, src_offset, memAddress(dst_origin), memAddress(region), remainingSafe(sync_point_wait_list), memAddressSafe(sync_point_wait_list), memAddressSafe(sync_point), memAddressSafe(mutable_handle)); } // --- [ clCommandCopyImageKHR ] --- /** Unsafe version of: {@link #clCommandCopyImageKHR CommandCopyImageKHR} */ public static int nclCommandCopyImageKHR(long command_buffer, long command_queue, long src_image, long dst_image, long src_origin, long dst_origin, long region, int num_sync_points_in_wait_list, long sync_point_wait_list, long sync_point, long mutable_handle) { long __functionAddress = CL.getICD().clCommandCopyImageKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(src_image); check(dst_image); } return callPPPPPPPPPPI(command_buffer, command_queue, src_image, dst_image, src_origin, dst_origin, region, num_sync_points_in_wait_list, sync_point_wait_list, sync_point, mutable_handle, __functionAddress); } /** * Records a command to copy image objects. * * @param command_buffer a valid command-buffer object * @param command_queue the command-queue the command will be recorded to. * * <p>Parameter is unused by this extension as only a single command-queue is supported and <b>must</b> be {@code NULL}.</p> * @param sync_point_wait_list the synchronization-points that need to complete before this particular command can be executed. * * <p>If {@code sync_point_wait_list} is {@code NULL}, {@code num_sync_points_in_wait_list} must be 0. If {@code sync_point_wait_list} is not {@code NULL}, the list of * synchronization-points pointed to by {@code sync_point_wait_list} must be valid and {@code num_sync_points_in_wait_list} must be greater than 0. * The synchronization-points specified in {@code sync_point_wait_list} are <b>device side</b> synchronization-points. The command-buffer associated * with synchronization-points in {@code sync_point_wait_list} must be the same as {@code command_buffer}. The memory associated with * {@code sync_point_wait_list} can be reused or freed after the function returns.</p> * * <p>If {@code sync_point_wait_list} is {@code NULL}, then this particular command waits until all previous recorded commands to {@code command_queue} have * completed.</p> * @param sync_point returns a synchronization-point ID that identifies this particular command. * * <p>Synchronization-point objects are unique and can be used to identify this barrier command later on. {@code sync_point} can be {@code NULL} in which case * it will not be possible for the application to record a wait for this command to complete. If the {@code sync_point_wait_list} and the * {@code sync_point} arguments are not {@code NULL}, the {@code sync_point} argument should not refer to an element of the {@code sync_point_wait_list} * array.</p> * @param mutable_handle returns a handle to the command. * * <p>Handle is unused by this extension and must be passed as {@code NULL}.</p> */ @NativeType("cl_int") public static int clCommandCopyImageKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long src_image, @NativeType("cl_mem") long dst_image, @NativeType("size_t const *") PointerBuffer src_origin, @NativeType("size_t const *") PointerBuffer dst_origin, @NativeType("size_t const *") PointerBuffer region, @Nullable @NativeType("cl_sync_point_khr const *") IntBuffer sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") IntBuffer sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { if (CHECKS) { check(src_origin, 3); check(dst_origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return nclCommandCopyImageKHR(command_buffer, command_queue, src_image, dst_image, memAddress(src_origin), memAddress(dst_origin), memAddress(region), remainingSafe(sync_point_wait_list), memAddressSafe(sync_point_wait_list), memAddressSafe(sync_point), memAddressSafe(mutable_handle)); } // --- [ clCommandCopyImageToBufferKHR ] --- /** Unsafe version of: {@link #clCommandCopyImageToBufferKHR CommandCopyImageToBufferKHR} */ public static int nclCommandCopyImageToBufferKHR(long command_buffer, long command_queue, long src_image, long dst_buffer, long src_origin, long region, long dst_offset, int num_sync_points_in_wait_list, long sync_point_wait_list, long sync_point, long mutable_handle) { long __functionAddress = CL.getICD().clCommandCopyImageToBufferKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(src_image); check(dst_buffer); } return callPPPPPPPPPPI(command_buffer, command_queue, src_image, dst_buffer, src_origin, region, dst_offset, num_sync_points_in_wait_list, sync_point_wait_list, sync_point, mutable_handle, __functionAddress); } /** * Records a command to copy an image object to a buffer object. * * @param command_buffer a valid command-buffer object * @param command_queue the command-queue the command will be recorded to. * * <p>Parameter is unused by this extension as only a single command-queue is supported and <b>must</b> be {@code NULL}.</p> * @param sync_point_wait_list the synchronization-points that need to complete before this particular command can be executed. * * <p>If {@code sync_point_wait_list} is {@code NULL}, {@code num_sync_points_in_wait_list} must be 0. If {@code sync_point_wait_list} is not {@code NULL}, the list of * synchronization-points pointed to by {@code sync_point_wait_list} must be valid and {@code num_sync_points_in_wait_list} must be greater than 0. * The synchronization-points specified in {@code sync_point_wait_list} are <b>device side</b> synchronization-points. The command-buffer associated * with synchronization-points in {@code sync_point_wait_list} must be the same as {@code command_buffer}. The memory associated with * {@code sync_point_wait_list} can be reused or freed after the function returns.</p> * * <p>If {@code sync_point_wait_list} is {@code NULL}, then this particular command waits until all previous recorded commands to {@code command_queue} have * completed.</p> * @param sync_point returns a synchronization-point ID that identifies this particular command. * * <p>Synchronization-point objects are unique and can be used to identify this barrier command later on. {@code sync_point} can be {@code NULL} in which case * it will not be possible for the application to record a wait for this command to complete. If the {@code sync_point_wait_list} and the * {@code sync_point} arguments are not {@code NULL}, the {@code sync_point} argument should not refer to an element of the {@code sync_point_wait_list} * array.</p> * @param mutable_handle returns a handle to the command. * * <p>Handle is unused by this extension and must be passed as {@code NULL}.</p> */ @NativeType("cl_int") public static int clCommandCopyImageToBufferKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long src_image, @NativeType("cl_mem") long dst_buffer, @NativeType("size_t const *") PointerBuffer src_origin, @NativeType("size_t const *") PointerBuffer region, @NativeType("size_t") long dst_offset, @Nullable @NativeType("cl_sync_point_khr const *") IntBuffer sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") IntBuffer sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { if (CHECKS) { check(src_origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return nclCommandCopyImageToBufferKHR(command_buffer, command_queue, src_image, dst_buffer, memAddress(src_origin), memAddress(region), dst_offset, remainingSafe(sync_point_wait_list), memAddressSafe(sync_point_wait_list), memAddressSafe(sync_point), memAddressSafe(mutable_handle)); } // --- [ clCommandFillBufferKHR ] --- /** Unsafe version of: {@link #clCommandFillBufferKHR CommandFillBufferKHR} */ public static int nclCommandFillBufferKHR(long command_buffer, long command_queue, long buffer, long pattern, long pattern_size, long offset, long size, int num_sync_points_in_wait_list, long sync_point_wait_list, long sync_point, long mutable_handle) { long __functionAddress = CL.getICD().clCommandFillBufferKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(buffer); } return callPPPPPPPPPPI(command_buffer, command_queue, buffer, pattern, pattern_size, offset, size, num_sync_points_in_wait_list, sync_point_wait_list, sync_point, mutable_handle, __functionAddress); } /** * Records a command to fill a buffer object with a pattern of a given pattern size. * * @param command_buffer a valid command-buffer object * @param command_queue the command-queue the command will be recorded to. * * <p>Parameter is unused by this extension as only a single command-queue is supported and <b>must</b> be {@code NULL}.</p> * @param sync_point_wait_list the synchronization-points that need to complete before this particular command can be executed. * * <p>If {@code sync_point_wait_list} is {@code NULL}, {@code num_sync_points_in_wait_list} must be 0. If {@code sync_point_wait_list} is not {@code NULL}, the list of * synchronization-points pointed to by {@code sync_point_wait_list} must be valid and {@code num_sync_points_in_wait_list} must be greater than 0. * The synchronization-points specified in {@code sync_point_wait_list} are <b>device side</b> synchronization-points. The command-buffer associated * with synchronization-points in {@code sync_point_wait_list} must be the same as {@code command_buffer}. The memory associated with * {@code sync_point_wait_list} can be reused or freed after the function returns.</p> * * <p>If {@code sync_point_wait_list} is {@code NULL}, then this particular command waits until all previous recorded commands to {@code command_queue} have * completed.</p> * @param sync_point returns a synchronization-point ID that identifies this particular command. * * <p>Synchronization-point objects are unique and can be used to identify this barrier command later on. {@code sync_point} can be {@code NULL} in which case * it will not be possible for the application to record a wait for this command to complete. If the {@code sync_point_wait_list} and the * {@code sync_point} arguments are not {@code NULL}, the {@code sync_point} argument should not refer to an element of the {@code sync_point_wait_list} * array.</p> * @param mutable_handle returns a handle to the command. * * <p>Handle is unused by this extension and must be passed as {@code NULL}.</p> */ @NativeType("cl_int") public static int clCommandFillBufferKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long buffer, @NativeType("void const *") ByteBuffer pattern, @NativeType("size_t") long offset, @NativeType("size_t") long size, @Nullable @NativeType("cl_sync_point_khr const *") IntBuffer sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") IntBuffer sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { if (CHECKS) { checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return nclCommandFillBufferKHR(command_buffer, command_queue, buffer, memAddress(pattern), pattern.remaining(), offset, size, remainingSafe(sync_point_wait_list), memAddressSafe(sync_point_wait_list), memAddressSafe(sync_point), memAddressSafe(mutable_handle)); } // --- [ clCommandFillImageKHR ] --- /** Unsafe version of: {@link #clCommandFillImageKHR CommandFillImageKHR} */ public static int nclCommandFillImageKHR(long command_buffer, long command_queue, long image, long fill_color, long origin, long region, int num_sync_points_in_wait_list, long sync_point_wait_list, long sync_point, long mutable_handle) { long __functionAddress = CL.getICD().clCommandFillImageKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(image); } return callPPPPPPPPPI(command_buffer, command_queue, image, fill_color, origin, region, num_sync_points_in_wait_list, sync_point_wait_list, sync_point, mutable_handle, __functionAddress); } /** * Records a command to fill an image object with a specified color. * * @param command_buffer a valid command-buffer object * @param command_queue the command-queue the command will be recorded to. * * <p>Parameter is unused by this extension as only a single command-queue is supported and <b>must</b> be {@code NULL}.</p> * @param sync_point_wait_list the synchronization-points that need to complete before this particular command can be executed. * * <p>If {@code sync_point_wait_list} is {@code NULL}, {@code num_sync_points_in_wait_list} must be 0. If {@code sync_point_wait_list} is not {@code NULL}, the list of * synchronization-points pointed to by {@code sync_point_wait_list} must be valid and {@code num_sync_points_in_wait_list} must be greater than 0. * The synchronization-points specified in {@code sync_point_wait_list} are <b>device side</b> synchronization-points. The command-buffer associated * with synchronization-points in {@code sync_point_wait_list} must be the same as {@code command_buffer}. The memory associated with * {@code sync_point_wait_list} can be reused or freed after the function returns.</p> * * <p>If {@code sync_point_wait_list} is {@code NULL}, then this particular command waits until all previous recorded commands to {@code command_queue} have * completed.</p> * @param sync_point returns a synchronization-point ID that identifies this particular command. * * <p>Synchronization-point objects are unique and can be used to identify this barrier command later on. {@code sync_point} can be {@code NULL} in which case * it will not be possible for the application to record a wait for this command to complete. If the {@code sync_point_wait_list} and the * {@code sync_point} arguments are not {@code NULL}, the {@code sync_point} argument should not refer to an element of the {@code sync_point_wait_list} * array.</p> * @param mutable_handle returns a handle to the command. * * <p>Handle is unused by this extension and must be passed as {@code NULL}.</p> */ @NativeType("cl_int") public static int clCommandFillImageKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long image, @NativeType("void const *") ByteBuffer fill_color, @NativeType("size_t const *") PointerBuffer origin, @NativeType("size_t const *") PointerBuffer region, @Nullable @NativeType("cl_sync_point_khr const *") IntBuffer sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") IntBuffer sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { if (CHECKS) { check(fill_color, 16); check(origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return nclCommandFillImageKHR(command_buffer, command_queue, image, memAddress(fill_color), memAddress(origin), memAddress(region), remainingSafe(sync_point_wait_list), memAddressSafe(sync_point_wait_list), memAddressSafe(sync_point), memAddressSafe(mutable_handle)); } /** * Records a command to fill an image object with a specified color. * * @param command_buffer a valid command-buffer object * @param command_queue the command-queue the command will be recorded to. * * <p>Parameter is unused by this extension as only a single command-queue is supported and <b>must</b> be {@code NULL}.</p> * @param sync_point_wait_list the synchronization-points that need to complete before this particular command can be executed. * * <p>If {@code sync_point_wait_list} is {@code NULL}, {@code num_sync_points_in_wait_list} must be 0. If {@code sync_point_wait_list} is not {@code NULL}, the list of * synchronization-points pointed to by {@code sync_point_wait_list} must be valid and {@code num_sync_points_in_wait_list} must be greater than 0. * The synchronization-points specified in {@code sync_point_wait_list} are <b>device side</b> synchronization-points. The command-buffer associated * with synchronization-points in {@code sync_point_wait_list} must be the same as {@code command_buffer}. The memory associated with * {@code sync_point_wait_list} can be reused or freed after the function returns.</p> * * <p>If {@code sync_point_wait_list} is {@code NULL}, then this particular command waits until all previous recorded commands to {@code command_queue} have * completed.</p> * @param sync_point returns a synchronization-point ID that identifies this particular command. * * <p>Synchronization-point objects are unique and can be used to identify this barrier command later on. {@code sync_point} can be {@code NULL} in which case * it will not be possible for the application to record a wait for this command to complete. If the {@code sync_point_wait_list} and the * {@code sync_point} arguments are not {@code NULL}, the {@code sync_point} argument should not refer to an element of the {@code sync_point_wait_list} * array.</p> * @param mutable_handle returns a handle to the command. * * <p>Handle is unused by this extension and must be passed as {@code NULL}.</p> */ @NativeType("cl_int") public static int clCommandFillImageKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long image, @NativeType("void const *") IntBuffer fill_color, @NativeType("size_t const *") PointerBuffer origin, @NativeType("size_t const *") PointerBuffer region, @Nullable @NativeType("cl_sync_point_khr const *") IntBuffer sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") IntBuffer sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { if (CHECKS) { check(fill_color, 16 >> 2); check(origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return nclCommandFillImageKHR(command_buffer, command_queue, image, memAddress(fill_color), memAddress(origin), memAddress(region), remainingSafe(sync_point_wait_list), memAddressSafe(sync_point_wait_list), memAddressSafe(sync_point), memAddressSafe(mutable_handle)); } /** * Records a command to fill an image object with a specified color. * * @param command_buffer a valid command-buffer object * @param command_queue the command-queue the command will be recorded to. * * <p>Parameter is unused by this extension as only a single command-queue is supported and <b>must</b> be {@code NULL}.</p> * @param sync_point_wait_list the synchronization-points that need to complete before this particular command can be executed. * * <p>If {@code sync_point_wait_list} is {@code NULL}, {@code num_sync_points_in_wait_list} must be 0. If {@code sync_point_wait_list} is not {@code NULL}, the list of * synchronization-points pointed to by {@code sync_point_wait_list} must be valid and {@code num_sync_points_in_wait_list} must be greater than 0. * The synchronization-points specified in {@code sync_point_wait_list} are <b>device side</b> synchronization-points. The command-buffer associated * with synchronization-points in {@code sync_point_wait_list} must be the same as {@code command_buffer}. The memory associated with * {@code sync_point_wait_list} can be reused or freed after the function returns.</p> * * <p>If {@code sync_point_wait_list} is {@code NULL}, then this particular command waits until all previous recorded commands to {@code command_queue} have * completed.</p> * @param sync_point returns a synchronization-point ID that identifies this particular command. * * <p>Synchronization-point objects are unique and can be used to identify this barrier command later on. {@code sync_point} can be {@code NULL} in which case * it will not be possible for the application to record a wait for this command to complete. If the {@code sync_point_wait_list} and the * {@code sync_point} arguments are not {@code NULL}, the {@code sync_point} argument should not refer to an element of the {@code sync_point_wait_list} * array.</p> * @param mutable_handle returns a handle to the command. * * <p>Handle is unused by this extension and must be passed as {@code NULL}.</p> */ @NativeType("cl_int") public static int clCommandFillImageKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long image, @NativeType("void const *") FloatBuffer fill_color, @NativeType("size_t const *") PointerBuffer origin, @NativeType("size_t const *") PointerBuffer region, @Nullable @NativeType("cl_sync_point_khr const *") IntBuffer sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") IntBuffer sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { if (CHECKS) { check(fill_color, 16 >> 2); check(origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return nclCommandFillImageKHR(command_buffer, command_queue, image, memAddress(fill_color), memAddress(origin), memAddress(region), remainingSafe(sync_point_wait_list), memAddressSafe(sync_point_wait_list), memAddressSafe(sync_point), memAddressSafe(mutable_handle)); } // --- [ clCommandNDRangeKernelKHR ] --- /** Unsafe version of: {@link #clCommandNDRangeKernelKHR CommandNDRangeKernelKHR} */ public static int nclCommandNDRangeKernelKHR(long command_buffer, long command_queue, long properties, long kernel, int work_dim, long global_work_offset, long global_work_size, long local_work_size, int num_sync_points_in_wait_list, long sync_point_wait_list, long sync_point, long mutable_handle) { long __functionAddress = CL.getICD().clCommandNDRangeKernelKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(kernel); } return callPPPPPPPPPPI(command_buffer, command_queue, properties, kernel, work_dim, global_work_offset, global_work_size, local_work_size, num_sync_points_in_wait_list, sync_point_wait_list, sync_point, mutable_handle, __functionAddress); } /** * Records a command to execute a kernel on a device. * * @param command_buffer a valid command-buffer object * @param command_queue the command-queue the command will be recorded to. * * <p>Parameter is unused by this extension as only a single command-queue is supported and <b>must</b> be {@code NULL}.</p> * @param kernel a valid kernel object * @param sync_point_wait_list the synchronization-points that need to complete before this particular command can be executed. * * <p>If {@code sync_point_wait_list} is {@code NULL}, {@code num_sync_points_in_wait_list} must be 0. If {@code sync_point_wait_list} is not {@code NULL}, the list of * synchronization-points pointed to by {@code sync_point_wait_list} must be valid and {@code num_sync_points_in_wait_list} must be greater than 0. * The synchronization-points specified in {@code sync_point_wait_list} are <b>device side</b> synchronization-points. The command-buffer associated * with synchronization-points in {@code sync_point_wait_list} must be the same as {@code command_buffer}. The memory associated with * {@code sync_point_wait_list} can be reused or freed after the function returns.</p> * * <p>If {@code sync_point_wait_list} is {@code NULL}, then this particular command waits until all previous recorded commands to {@code command_queue} have * completed.</p> * @param sync_point returns a synchronization-point ID that identifies this particular command. * * <p>Synchronization-point objects are unique and can be used to identify this barrier command later on. {@code sync_point} can be {@code NULL} in which case * it will not be possible for the application to record a wait for this command to complete. If the {@code sync_point_wait_list} and the * {@code sync_point} arguments are not {@code NULL}, the {@code sync_point} argument should not refer to an element of the {@code sync_point_wait_list} * array.</p> * @param mutable_handle returns a handle to the command. * * <p>Handle is unused by this extension and must be passed as {@code NULL}.</p> */ @NativeType("cl_int") public static int clCommandNDRangeKernelKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @Nullable @NativeType("cl_ndrange_kernel_command_properties_khr const *") LongBuffer properties, @NativeType("cl_kernel") long kernel, @NativeType("cl_uint") int work_dim, @Nullable @NativeType("size_t const *") PointerBuffer global_work_offset, @Nullable @NativeType("size_t const *") PointerBuffer global_work_size, @Nullable @NativeType("size_t const *") PointerBuffer local_work_size, @Nullable @NativeType("cl_sync_point_khr const *") IntBuffer sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") IntBuffer sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { if (CHECKS) { checkNTSafe(properties); checkSafe(global_work_offset, work_dim); checkSafe(global_work_size, work_dim); checkSafe(local_work_size, work_dim); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return nclCommandNDRangeKernelKHR(command_buffer, command_queue, memAddressSafe(properties), kernel, work_dim, memAddressSafe(global_work_offset), memAddressSafe(global_work_size), memAddressSafe(local_work_size), remainingSafe(sync_point_wait_list), memAddressSafe(sync_point_wait_list), memAddressSafe(sync_point), memAddressSafe(mutable_handle)); } // --- [ clGetCommandBufferInfoKHR ] --- /** * Unsafe version of: {@link #clGetCommandBufferInfoKHR GetCommandBufferInfoKHR} * * @param param_value_size the size in bytes of memory pointed to by {@code param_value}. This size must be &#x2265; size of return type. If {@code param_value} is {@code NULL}, it is ignored. */ public static int nclGetCommandBufferInfoKHR(long command_buffer, int param_name, long param_value_size, long param_value, long param_value_size_ret) { long __functionAddress = CL.getICD().clGetCommandBufferInfoKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); } return callPPPPI(command_buffer, param_name, param_value_size, param_value, param_value_size_ret, __functionAddress); } /** * Queries information about a command-buffer. * * @param command_buffer the command-buffer being queried * @param param_name the information to query * @param param_value a pointer to memory where the appropriate result being queried is returned. If {@code param_value} is {@code NULL}, it is ignored. * @param param_value_size_ret the actual size in bytes of data being queried by {@code param_value}. If {@code NULL}, it is ignored. */ @NativeType("cl_int") public static int clGetCommandBufferInfoKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_buffer_info_khr") int param_name, @Nullable @NativeType("void *") ByteBuffer param_value, @Nullable @NativeType("size_t *") PointerBuffer param_value_size_ret) { if (CHECKS) { checkSafe(param_value_size_ret, 1); } return nclGetCommandBufferInfoKHR(command_buffer, param_name, remainingSafe(param_value), memAddressSafe(param_value), memAddressSafe(param_value_size_ret)); } /** * Queries information about a command-buffer. * * @param command_buffer the command-buffer being queried * @param param_name the information to query * @param param_value a pointer to memory where the appropriate result being queried is returned. If {@code param_value} is {@code NULL}, it is ignored. * @param param_value_size_ret the actual size in bytes of data being queried by {@code param_value}. If {@code NULL}, it is ignored. */ @NativeType("cl_int") public static int clGetCommandBufferInfoKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_buffer_info_khr") int param_name, @Nullable @NativeType("void *") IntBuffer param_value, @Nullable @NativeType("size_t *") PointerBuffer param_value_size_ret) { if (CHECKS) { checkSafe(param_value_size_ret, 1); } return nclGetCommandBufferInfoKHR(command_buffer, param_name, Integer.toUnsignedLong(remainingSafe(param_value)) << 2, memAddressSafe(param_value), memAddressSafe(param_value_size_ret)); } /** * Queries information about a command-buffer. * * @param command_buffer the command-buffer being queried * @param param_name the information to query * @param param_value a pointer to memory where the appropriate result being queried is returned. If {@code param_value} is {@code NULL}, it is ignored. * @param param_value_size_ret the actual size in bytes of data being queried by {@code param_value}. If {@code NULL}, it is ignored. */ @NativeType("cl_int") public static int clGetCommandBufferInfoKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_buffer_info_khr") int param_name, @Nullable @NativeType("void *") PointerBuffer param_value, @Nullable @NativeType("size_t *") PointerBuffer param_value_size_ret) { if (CHECKS) { checkSafe(param_value_size_ret, 1); } return nclGetCommandBufferInfoKHR(command_buffer, param_name, Integer.toUnsignedLong(remainingSafe(param_value)) << POINTER_SHIFT, memAddressSafe(param_value), memAddressSafe(param_value_size_ret)); } /** Array version of: {@link #clCreateCommandBufferKHR CreateCommandBufferKHR} */ @NativeType("cl_command_buffer_khr") public static long clCreateCommandBufferKHR(@NativeType("cl_command_queue const *") PointerBuffer queues, @Nullable @NativeType("cl_command_buffer_properties_khr const *") long[] properties, @Nullable @NativeType("cl_int *") int[] errcode_ret) { long __functionAddress = CL.getICD().clCreateCommandBufferKHR; if (CHECKS) { check(__functionAddress); checkNTSafe(properties); checkSafe(errcode_ret, 1); } return callPPPP(queues.remaining(), memAddress(queues), properties, errcode_ret, __functionAddress); } /** Array version of: {@link #clCommandBarrierWithWaitListKHR CommandBarrierWithWaitListKHR} */ @NativeType("cl_int") public static int clCommandBarrierWithWaitListKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @Nullable @NativeType("cl_sync_point_khr const *") int[] sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") int[] sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { long __functionAddress = CL.getICD().clCommandBarrierWithWaitListKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return callPPPPPI(command_buffer, command_queue, lengthSafe(sync_point_wait_list), sync_point_wait_list, sync_point, memAddressSafe(mutable_handle), __functionAddress); } /** Array version of: {@link #clCommandCopyBufferKHR CommandCopyBufferKHR} */ @NativeType("cl_int") public static int clCommandCopyBufferKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long src_buffer, @NativeType("cl_mem") long dst_buffer, @NativeType("size_t") long src_offset, @NativeType("size_t") long dst_offset, @NativeType("size_t") long size, @Nullable @NativeType("cl_sync_point_khr const *") int[] sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") int[] sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { long __functionAddress = CL.getICD().clCommandCopyBufferKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(src_buffer); check(dst_buffer); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return callPPPPPPPPPPI(command_buffer, command_queue, src_buffer, dst_buffer, src_offset, dst_offset, size, lengthSafe(sync_point_wait_list), sync_point_wait_list, sync_point, memAddressSafe(mutable_handle), __functionAddress); } /** Array version of: {@link #clCommandCopyBufferRectKHR CommandCopyBufferRectKHR} */ @NativeType("cl_int") public static int clCommandCopyBufferRectKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long src_buffer, @NativeType("cl_mem") long dst_buffer, @NativeType("size_t const *") PointerBuffer src_origin, @NativeType("size_t const *") PointerBuffer dst_origin, @NativeType("size_t const *") PointerBuffer region, @NativeType("size_t") long src_row_pitch, @NativeType("size_t") long src_slice_pitch, @NativeType("size_t") long dst_row_pitch, @NativeType("size_t") long dst_slice_pitch, @Nullable @NativeType("cl_sync_point_khr const *") int[] sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") int[] sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { long __functionAddress = CL.getICD().clCommandCopyBufferRectKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(src_buffer); check(dst_buffer); check(src_origin, 3); check(dst_origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return callPPPPPPPPPPPPPPI(command_buffer, command_queue, src_buffer, dst_buffer, memAddress(src_origin), memAddress(dst_origin), memAddress(region), src_row_pitch, src_slice_pitch, dst_row_pitch, dst_slice_pitch, lengthSafe(sync_point_wait_list), sync_point_wait_list, sync_point, memAddressSafe(mutable_handle), __functionAddress); } /** Array version of: {@link #clCommandCopyBufferToImageKHR CommandCopyBufferToImageKHR} */ @NativeType("cl_int") public static int clCommandCopyBufferToImageKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long src_buffer, @NativeType("cl_mem") long dst_image, @NativeType("size_t") long src_offset, @NativeType("size_t const *") PointerBuffer dst_origin, @NativeType("size_t const *") PointerBuffer region, @Nullable @NativeType("cl_sync_point_khr const *") int[] sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") int[] sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { long __functionAddress = CL.getICD().clCommandCopyBufferToImageKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(src_buffer); check(dst_image); check(dst_origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return callPPPPPPPPPPI(command_buffer, command_queue, src_buffer, dst_image, src_offset, memAddress(dst_origin), memAddress(region), lengthSafe(sync_point_wait_list), sync_point_wait_list, sync_point, memAddressSafe(mutable_handle), __functionAddress); } /** Array version of: {@link #clCommandCopyImageKHR CommandCopyImageKHR} */ @NativeType("cl_int") public static int clCommandCopyImageKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long src_image, @NativeType("cl_mem") long dst_image, @NativeType("size_t const *") PointerBuffer src_origin, @NativeType("size_t const *") PointerBuffer dst_origin, @NativeType("size_t const *") PointerBuffer region, @Nullable @NativeType("cl_sync_point_khr const *") int[] sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") int[] sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { long __functionAddress = CL.getICD().clCommandCopyImageKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(src_image); check(dst_image); check(src_origin, 3); check(dst_origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return callPPPPPPPPPPI(command_buffer, command_queue, src_image, dst_image, memAddress(src_origin), memAddress(dst_origin), memAddress(region), lengthSafe(sync_point_wait_list), sync_point_wait_list, sync_point, memAddressSafe(mutable_handle), __functionAddress); } /** Array version of: {@link #clCommandCopyImageToBufferKHR CommandCopyImageToBufferKHR} */ @NativeType("cl_int") public static int clCommandCopyImageToBufferKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long src_image, @NativeType("cl_mem") long dst_buffer, @NativeType("size_t const *") PointerBuffer src_origin, @NativeType("size_t const *") PointerBuffer region, @NativeType("size_t") long dst_offset, @Nullable @NativeType("cl_sync_point_khr const *") int[] sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") int[] sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { long __functionAddress = CL.getICD().clCommandCopyImageToBufferKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(src_image); check(dst_buffer); check(src_origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return callPPPPPPPPPPI(command_buffer, command_queue, src_image, dst_buffer, memAddress(src_origin), memAddress(region), dst_offset, lengthSafe(sync_point_wait_list), sync_point_wait_list, sync_point, memAddressSafe(mutable_handle), __functionAddress); } /** Array version of: {@link #clCommandFillBufferKHR CommandFillBufferKHR} */ @NativeType("cl_int") public static int clCommandFillBufferKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long buffer, @NativeType("void const *") ByteBuffer pattern, @NativeType("size_t") long offset, @NativeType("size_t") long size, @Nullable @NativeType("cl_sync_point_khr const *") int[] sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") int[] sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { long __functionAddress = CL.getICD().clCommandFillBufferKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(buffer); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return callPPPPPPPPPPI(command_buffer, command_queue, buffer, memAddress(pattern), (long)pattern.remaining(), offset, size, lengthSafe(sync_point_wait_list), sync_point_wait_list, sync_point, memAddressSafe(mutable_handle), __functionAddress); } /** Array version of: {@link #clCommandFillImageKHR CommandFillImageKHR} */ @NativeType("cl_int") public static int clCommandFillImageKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long image, @NativeType("void const *") ByteBuffer fill_color, @NativeType("size_t const *") PointerBuffer origin, @NativeType("size_t const *") PointerBuffer region, @Nullable @NativeType("cl_sync_point_khr const *") int[] sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") int[] sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { long __functionAddress = CL.getICD().clCommandFillImageKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(image); check(fill_color, 16); check(origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return callPPPPPPPPPI(command_buffer, command_queue, image, memAddress(fill_color), memAddress(origin), memAddress(region), lengthSafe(sync_point_wait_list), sync_point_wait_list, sync_point, memAddressSafe(mutable_handle), __functionAddress); } /** Array version of: {@link #clCommandFillImageKHR CommandFillImageKHR} */ @NativeType("cl_int") public static int clCommandFillImageKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long image, @NativeType("void const *") int[] fill_color, @NativeType("size_t const *") PointerBuffer origin, @NativeType("size_t const *") PointerBuffer region, @Nullable @NativeType("cl_sync_point_khr const *") int[] sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") int[] sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { long __functionAddress = CL.getICD().clCommandFillImageKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(image); check(fill_color, 16 >> 2); check(origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return callPPPPPPPPPI(command_buffer, command_queue, image, fill_color, memAddress(origin), memAddress(region), lengthSafe(sync_point_wait_list), sync_point_wait_list, sync_point, memAddressSafe(mutable_handle), __functionAddress); } /** Array version of: {@link #clCommandFillImageKHR CommandFillImageKHR} */ @NativeType("cl_int") public static int clCommandFillImageKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @NativeType("cl_mem") long image, @NativeType("void const *") float[] fill_color, @NativeType("size_t const *") PointerBuffer origin, @NativeType("size_t const *") PointerBuffer region, @Nullable @NativeType("cl_sync_point_khr const *") int[] sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") int[] sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { long __functionAddress = CL.getICD().clCommandFillImageKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); check(image); check(fill_color, 16 >> 2); check(origin, 3); check(region, 3); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return callPPPPPPPPPI(command_buffer, command_queue, image, fill_color, memAddress(origin), memAddress(region), lengthSafe(sync_point_wait_list), sync_point_wait_list, sync_point, memAddressSafe(mutable_handle), __functionAddress); } /** Array version of: {@link #clCommandNDRangeKernelKHR CommandNDRangeKernelKHR} */ @NativeType("cl_int") public static int clCommandNDRangeKernelKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_queue") long command_queue, @Nullable @NativeType("cl_ndrange_kernel_command_properties_khr const *") long[] properties, @NativeType("cl_kernel") long kernel, @NativeType("cl_uint") int work_dim, @Nullable @NativeType("size_t const *") PointerBuffer global_work_offset, @Nullable @NativeType("size_t const *") PointerBuffer global_work_size, @Nullable @NativeType("size_t const *") PointerBuffer local_work_size, @Nullable @NativeType("cl_sync_point_khr const *") int[] sync_point_wait_list, @Nullable @NativeType("cl_sync_point_khr *") int[] sync_point, @Nullable @NativeType("cl_mutable_command_khr *") PointerBuffer mutable_handle) { long __functionAddress = CL.getICD().clCommandNDRangeKernelKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); checkNTSafe(properties); check(kernel); checkSafe(global_work_offset, work_dim); checkSafe(global_work_size, work_dim); checkSafe(local_work_size, work_dim); checkSafe(sync_point, 1); checkSafe(mutable_handle, 1); } return callPPPPPPPPPPI(command_buffer, command_queue, properties, kernel, work_dim, memAddressSafe(global_work_offset), memAddressSafe(global_work_size), memAddressSafe(local_work_size), lengthSafe(sync_point_wait_list), sync_point_wait_list, sync_point, memAddressSafe(mutable_handle), __functionAddress); } /** Array version of: {@link #clGetCommandBufferInfoKHR GetCommandBufferInfoKHR} */ @NativeType("cl_int") public static int clGetCommandBufferInfoKHR(@NativeType("cl_command_buffer_khr") long command_buffer, @NativeType("cl_command_buffer_info_khr") int param_name, @Nullable @NativeType("void *") int[] param_value, @Nullable @NativeType("size_t *") PointerBuffer param_value_size_ret) { long __functionAddress = CL.getICD().clGetCommandBufferInfoKHR; if (CHECKS) { check(__functionAddress); check(command_buffer); checkSafe(param_value_size_ret, 1); } return callPPPPI(command_buffer, param_name, Integer.toUnsignedLong(lengthSafe(param_value)) << 2, param_value, memAddressSafe(param_value_size_ret), __functionAddress); } }
LWJGL-CI/lwjgl3
modules/lwjgl/opencl/src/generated/java/org/lwjgl/opencl/KHRCommandBuffer.java
Java
bsd-3-clause
80,872
using System.Xml.Linq; namespace Orchard.Feeds.Models { public class FeedItem { private object _item; public object Item { get { return _item; } set { SetItem(value); } } public XElement Element { get; set; } protected virtual void SetItem(object item) { _item = item; } } public class FeedItem<TItem> : FeedItem { private TItem _item; public new TItem Item { get { return _item; } set { SetItem(value); } } protected override void SetItem(object item) { _item = (TItem)item; base.SetItem(item); } } }
stevetayloruk/Orchard2
src/OrchardCore/Orchard.Feeds.Abstractions/Models/FeedItem.cs
C#
bsd-3-clause
653
/**************************************************************************** * * Copyright (c) 2013 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file ms5611_i2c.cpp * * I2C interface for MS5611 */ /* XXX trim includes */ #include <px4_config.h> #include <px4_defines.h> #include <sys/types.h> #include <stdint.h> #include <stdbool.h> #include <assert.h> #include <errno.h> #include <unistd.h> #include <arch/board/board.h> #include <drivers/device/i2c.h> #include "ms5611.h" #include "board_config.h" #define MS5611_ADDRESS_1 0x76 /* address select pins pulled high (PX4FMU series v1.6+) */ #define MS5611_ADDRESS_2 0x77 /* address select pins pulled low (PX4FMU prototypes) */ device::Device *MS5611_i2c_interface(ms5611::prom_u &prom_buf); class MS5611_I2C : public device::I2C { public: MS5611_I2C(uint8_t bus, ms5611::prom_u &prom_buf); virtual ~MS5611_I2C(); virtual int init(); virtual int read(unsigned offset, void *data, unsigned count); virtual int ioctl(unsigned operation, unsigned &arg); protected: virtual int probe(); private: ms5611::prom_u &_prom; int _probe_address(uint8_t address); /** * Send a reset command to the MS5611. * * This is required after any bus reset. */ int _reset(); /** * Send a measure command to the MS5611. * * @param addr Which address to use for the measure operation. */ int _measure(unsigned addr); /** * Read the MS5611 PROM * * @return PX4_OK if the PROM reads successfully. */ int _read_prom(); }; device::Device * MS5611_i2c_interface(ms5611::prom_u &prom_buf, uint8_t busnum) { return new MS5611_I2C(busnum, prom_buf); } MS5611_I2C::MS5611_I2C(uint8_t bus, ms5611::prom_u &prom) : I2C("MS5611_I2C", nullptr, bus, 0, 400000), _prom(prom) { } MS5611_I2C::~MS5611_I2C() { } int MS5611_I2C::init() { /* this will call probe(), and thereby _probe_address */ return I2C::init(); } int MS5611_I2C::read(unsigned offset, void *data, unsigned count) { union _cvt { uint8_t b[4]; uint32_t w; } *cvt = (_cvt *)data; uint8_t buf[3]; /* read the most recent measurement */ uint8_t cmd = 0; int ret = transfer(&cmd, 1, &buf[0], 3); if (ret == PX4_OK) { /* fetch the raw value */ cvt->b[0] = buf[2]; cvt->b[1] = buf[1]; cvt->b[2] = buf[0]; cvt->b[3] = 0; } return ret; } int MS5611_I2C::ioctl(unsigned operation, unsigned &arg) { int ret; switch (operation) { case IOCTL_RESET: ret = _reset(); break; case IOCTL_MEASURE: ret = _measure(arg); break; default: ret = EINVAL; } return ret; } int MS5611_I2C::probe() { _retries = 10; if ((PX4_OK == _probe_address(MS5611_ADDRESS_1)) || (PX4_OK == _probe_address(MS5611_ADDRESS_2))) { /* * Disable retries; we may enable them selectively in some cases, * but the device gets confused if we retry some of the commands. */ _retries = 0; return PX4_OK; } return -EIO; } int MS5611_I2C::_probe_address(uint8_t address) { /* select the address we are going to try */ set_device_address(address); /* send reset command */ if (PX4_OK != _reset()) { return -EIO; } /* read PROM */ if (PX4_OK != _read_prom()) { return -EIO; } return PX4_OK; } int MS5611_I2C::_reset() { unsigned old_retrycount = _retries; uint8_t cmd = ADDR_RESET_CMD; int result; /* bump the retry count */ _retries = 10; result = transfer(&cmd, 1, nullptr, 0); _retries = old_retrycount; return result; } int MS5611_I2C::_measure(unsigned addr) { /* * Disable retries on this command; we can't know whether failure * means the device did or did not see the command. */ _retries = 0; uint8_t cmd = addr; return transfer(&cmd, 1, nullptr, 0); } int MS5611_I2C::_read_prom() { uint8_t prom_buf[2]; union { uint8_t b[2]; uint16_t w; } cvt; /* * Wait for PROM contents to be in the device (2.8 ms) in the case we are * called immediately after reset. */ usleep(3000); uint8_t last_val = 0; bool bits_stuck = true; /* read and convert PROM words */ for (int i = 0; i < 8; i++) { uint8_t cmd = ADDR_PROM_SETUP + (i * 2); if (PX4_OK != transfer(&cmd, 1, &prom_buf[0], 2)) { break; } /* check if all bytes are zero */ if (i == 0) { /* initialize to first byte read */ last_val = prom_buf[0]; } if (prom_buf[0] != last_val || prom_buf[1] != last_val) { bits_stuck = false; } /* assemble 16 bit value and convert from big endian (sensor) to little endian (MCU) */ cvt.b[0] = prom_buf[1]; cvt.b[1] = prom_buf[0]; _prom.c[i] = cvt.w; } /* calculate CRC and return success/failure accordingly */ return (ms5611::crc4(&_prom.c[0]) && !bits_stuck) ? PX4_OK : -EIO; }
mcgill-robotics/Firmware
src/drivers/barometer/ms5611/ms5611_i2c.cpp
C++
bsd-3-clause
6,253
<?php /* * ircPlanet Services for ircu * Copyright (c) 2005 Brian Cline. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of ircPlanet nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ if (!($chan = $this->getChannel($chan_name))) { $bot->noticef($user, "Nobody is on channel %s.", $chan_name); return false; } $reason = assemble($pargs, 2); $users = $this->getChannelUsersByMask($chan_name); foreach ($users as $numeric => $chan_user) { if (!$chan_user->isBot() && $chan_user != $user) $bot->kick($chan->getName(), $numeric, $reason); }
briancline/googlecode-ircplanet
Operator/commands/kickall.php
PHP
bsd-3-clause
1,980
<?php /* * $Id: 69074307e3d1aae5fbfaa03842f5a8fc14b49625 $ * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information please see * <http://phing.info>. */ require_once 'phing/tasks/system/condition/ConditionBase.php'; /** * <and> condition container. * * Iterates over all conditions and returns false as soon as one * evaluates to false. * * @author Hans Lellelid <[email protected]> * @author Andreas Aderhold <[email protected]> * @copyright 2001,2002 THYRELL. All rights reserved * @version $Id$ * @package phing.tasks.system.condition */ class AndCondition extends ConditionBase implements Condition { public function evaluate() { foreach($this as $c) { // ConditionBase implements IteratorAggregator if (!$c->evaluate()) { return false; } } return true; } }
theghostbel/pimcore
pimcore/lib/Deployment/Phing/classes/phing/tasks/system/condition/AndCondition.php
PHP
bsd-3-clause
1,749
<?php /** * Table Definition for folder. * * PHP version 5 * * Copyright (C) Villanova University 2017. * Copyright (C) University of Freiburg 2014. * Copyright (C) The National Library of Finland 2015. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category VuBib * @package Code * @author Falvey Library <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * * @link https:// */ namespace VuBib\Db\Table; use Zend\Db\Adapter\Adapter; use Zend\Db\Sql\Expression; use Zend\Paginator\Adapter\DbSelect; use Zend\Paginator\Paginator; /** * Table Definition for folder. * * @category VuBib * @package Code * @author Falvey Library <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * * @link https:// */ class Folder extends \Zend\Db\TableGateway\TableGateway { /** * Folder constructor. * * @param Adapter $adapter for db connection */ public function __construct($adapter) { parent::__construct('folder', $adapter); } /** * Find folders with no parent. * * @return Paginator $paginatorAdapter folder records as paginator */ public function findParent() { $select = $this->sql->select()->where(['parent_id' => null]); $paginatorAdapter = new DbSelect($select, $this->adapter); return new Paginator($paginatorAdapter); } /** * Export folders in a hierarchial way to a csv file. * * @return empty */ public function exportClassification() { $fl = new self($this->adapter); $callback = function ($select) { $select->columns(['*']); $select->where('parent_id IS NULL'); }; $row = $this->select($callback)->toArray(); $escaper = new \Zend\Escaper\Escaper('utf-8'); header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename=test_export.csv'); $file = fopen('php://output', 'w') or die('Unable to open file!'); //add BOM to fix UTF-8 in Excel fputs($file, $bom = (chr(0xEF) . chr(0xBB) . chr(0xBF))); foreach ($row as $t) { $content = $t['id'] . ' ' . $escaper->escapeHtml($t['text_fr']) . ' '; fputcsv($file, [$content]); $fl->getDepth($t['id'], $file, $content); } fflush($file); fclose($file); exit; } /** * Get the depth of each folder and write it to a file. * * @param Number $id id of the folder * @param string $file file to which folder hierarchy is to be written * @param string $content content to be written to file * * @return empty */ public function getDepth($id, $file, $content) { $fl = new self($this->adapter); $escaper = new \Zend\Escaper\Escaper('utf-8'); $con = $content; $current_parent_id = $id; $callback = function ($select) use ($current_parent_id) { $select->columns(['*']); $select->where->equalTo('parent_id', $current_parent_id); }; $rc = $this->select($callback)->toArray(); if (count($rc) != 0) { for ($i = 0; $i < count($rc); ++$i) { $con1 = ' ' . $escaper->escapeHtml($rc[$i]['text_fr']) . ' '; fputcsv($file, [$con . $con1]); $current_parent_id = $rc[$i]['id']; $fl->getDepth($current_parent_id, $file, $con . $con1); } } } /** * Get children of a parent folder. * * @param Number $parent parent id of a folder * * @return Array $rows folder child records */ public function getChild($parent) { $callback = function ($select) use ($parent) { $select->columns(['*']); $select->where->equalTo('parent_id', $parent); //$select->order(new Expression('case when sort_order is null //then 1 else 0 end, sort_order'),'text_fr'); $select->order('sort_order'); $select->order('text_fr'); }; $rows = $this->select($callback)->toArray(); return $rows; } /** * Get parent of a folder. * * @param Number $child id of a folder * * @return Array $row folder parent record */ public function getParent($child) { $rowset = $this->select(['id' => $child]); $row = $rowset->current(); return $row; } /** * Get folders with no parent. * * @return Array $rows folder records with no parent */ public function getFoldersWithNullParent() { $callback = function ($select) { $select->columns(['*']); $select->where('parent_id IS NULL'); }; $rows = $this->select($callback)->toArray(); return $rows; } /** * Get the hierarchial trail of a folder. * * @param Number $id id of the folder * @param string $r string to convert array * * @return string $r hierarchial trail of folder as a string */ public function getTrail($id, $r) { $str = ''; $str = $r; $fl = new self($this->adapter); $callback = function ($select) use ($id) { $select->columns(['*']); $select->join( ['b' => 'folder'], 'folder.id = b.parent_id', ['parent_id'] ); $select->where->equalTo('b.id', $id); }; $rc = $this->select($callback)->toArray(); if (count($rc) == 0) { return $str . ':' . 'Top'; } else { $r = $r . ':' . $rc[0]['text_fr'] . '*' . $rc[0]['id']; $r = $fl->getTrail($rc[0]['parent_id'], $r); return $r; } } /** * Find folder record. * * @param Number $id id of folder * * @return Array $row folder record */ public function findRecordById($id) { $rowset = $this->select(['id' => $id]); $row = $rowset->current(); return $row; } /** * Get the hierarchial parent chain for a folder. * * @param Number $id id of the folder * * @return Array $encounteredIds parent hierarchy of a folder */ public function getParentChain($id) { $fl = new self($this->adapter); $row = $fl->getParent($id); $encounteredIds = [$row['id']]; $current = $row['parent_id']; while ($current != null && !in_array($current, $encounteredIds)) { $row = $fl->getParent($current); $encounteredIds[] = $row['id']; $current = $row['parent_id']; } $encounteredIds = array_reverse($encounteredIds); return $encounteredIds; } /** * Get the hierarchial parent chain record for a folder. * * @param Number $id id of the folder * @param Boolean $reverse order of parent chain of the folder * * @return Array $parentList parent hierarchy of a folder */ public function getParentChainRecord($id, $reverse = false) { $parentList = []; $fl = new self($this->adapter); $row = $fl->getParent($id); $encounteredIds = [$row['id']]; $current = $row['parent_id']; while ($current != null && !in_array($current, $encounteredIds)) { $row = $fl->getParent($current); $encounteredIds[] = $row['id']; $parentList[] = $row; $current = $row['parent_id']; } if ($reverse) { $parentList = array_reverse($parentList); } return $parentList; } /** * Insert folder record. * * @param Number $parent_id id of parent of folder * @param String $text_en english name of folder * @param String $text_fr french name of folder * @param String $text_de german name of folder * @param String $text_nl dutch name of folder * @param String $text_es spanish name of folder * @param String $text_it italian name of folder * @param Number $sort_order order of the folder among its siblings * * @return empty */ public function insertRecords($parent_id, $text_en, $text_fr, $text_de, $text_nl, $text_es, $text_it, $sort_order ) { $this->insert( [ 'parent_id' => $parent_id, 'text_en' => $text_en, 'text_fr' => $text_fr, 'text_de' => $text_de, 'text_nl' => $text_nl, 'text_es' => $text_es, 'text_it' => $text_it, 'sort_order' => $sort_order, ] ); } /** * Update folder record. * * @param Number $id id of folder * @param String $text_en english name of folder * @param String $text_fr french name of folder * @param String $text_de german name of folder * @param String $text_nl dutch name of folder * @param String $text_es spanish name of folder * @param String $text_it italian name of folder * @param Number $sort_order order of the folder among its siblings * * @return empty */ public function updateRecord($id, $text_en, $text_fr, $text_de, $text_nl, $text_es, $text_it, $sort_order ) { $this->update( [ 'text_en' => $text_en, 'text_fr' => $text_fr, 'text_de' => $text_de, 'text_nl' => $text_nl, 'text_es' => $text_es, 'text_it' => $text_it, 'sort_order' => $sort_order, ], ['id' => $id] ); } /** * Move folder. * * @param Number $id id of folder * @param Number $parent_id parent id folder * * @return empty */ public function moveFolder($id, $parent_id) { $this->update( [ 'parent_id' => $parent_id, ], ['id' => $id] ); } /** * Merge folder. * * @param Number $sid id of folder * @param Number $did id folder * * @return empty */ public function mergeFolder($sid, $did) { $this->update( [ 'parent_id' => $did, ], ['parent_id' => $sid] ); } /** * Delete folder. * * @param Number $sid id of folder * * @return empty */ public function mergeDelete($sid) { $this->delete(['id' => $sid]); } /** * Get siblings of a folder. * * @param Number $pid parent id of the folder * * @return Array $rows folder records */ public function getSiblings($pid) { if (null === $pid) { $callback = function ($select) { $select->columns(['*']); $select->where('parent_id IS NULL'); }; } else { $callback = function ($select) use ($pid) { $select->columns(['*']); $select->where->equalTo('parent_id', $pid); }; } $rows = $this->select($callback)->toArray(); return $rows; } }
SravanthiVillanova/Learn_Bibliography
src/VuBib/Db/Table/Folder.php
PHP
bsd-3-clause
12,079
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE617_Reachable_Assertion__fscanf_82.h Label Definition File: CWE617_Reachable_Assertion.label.xml Template File: sources-sink-82.tmpl.h */ /* * @description * CWE: 617 Reachable Assertion * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Number greater than ASSERT_VALUE * BadSink : Assert if n is less than or equal to ASSERT_VALUE * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #include "std_testcase.h" #include <assert.h> #define ASSERT_VALUE 5 namespace CWE617_Reachable_Assertion__fscanf_82 { class CWE617_Reachable_Assertion__fscanf_82_base { public: /* pure virtual function */ virtual void action(int data) = 0; }; #ifndef OMITBAD class CWE617_Reachable_Assertion__fscanf_82_bad : public CWE617_Reachable_Assertion__fscanf_82_base { public: void action(int data); }; #endif /* OMITBAD */ #ifndef OMITGOOD class CWE617_Reachable_Assertion__fscanf_82_goodG2B : public CWE617_Reachable_Assertion__fscanf_82_base { public: void action(int data); }; #endif /* OMITGOOD */ }
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE617_Reachable_Assertion/CWE617_Reachable_Assertion__fscanf_82.h
C
bsd-3-clause
1,202
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.common.time; import com.facebook.common.internal.DoNotStrip; /** * A clock that returns number of milliseconds since boot. It guarantees that every next * call to now() will return a value that is not less that was returned from previous call to now(). * This happens regardless system time changes, time zone changes, daylight saving changes etc. */ @DoNotStrip public class RealtimeSinceBootClock implements MonotonicClock { private static final RealtimeSinceBootClock INSTANCE = new RealtimeSinceBootClock(); private RealtimeSinceBootClock() { } /** * Returns a singleton instance of this clock. * @return singleton instance */ @DoNotStrip public static RealtimeSinceBootClock get() { return INSTANCE; } @Override public long now() { // Guaranteed to be monotonic according to documentation. return android.os.SystemClock.elapsedRealtime(); } }
275288698/fresco
fbcore/src/main/java/com/facebook/common/time/RealtimeSinceBootClock.java
Java
bsd-3-clause
1,228
from itertools import repeat from nose.tools import eq_ from .helper import _do_test, MockXPI from validator.errorbundler import ErrorBundle from validator.testcases import packagelayout def test_blacklisted_files(): """Tests that the validator will throw warnings on extensions containing files that have extensions which are not considered safe.""" err = _do_test('tests/resources/packagelayout/ext_blacklist.xpi', packagelayout.test_blacklisted_files, True) assert err.metadata['contains_binary_extension'] assert not any(count for (key, count) in err.compat_summary.items()) # Run the compatibility test on this, but it shouldn't fail or produce # errors because the bianry content isn't in the appropriate directories. err = _do_test('tests/resources/packagelayout/ext_blacklist.xpi', packagelayout.test_compatibility_binary, False) print err.compat_summary assert not err.compat_summary['errors'] def test_java_jar_detection(): """ Test that Java archives are flagged as such so that they do not generate hundreds or thousands of errors. """ classes = ('c%d.class' % i for i in xrange(1000)) mock_xpi = MockXPI(dict(zip(classes, repeat('')))) err = ErrorBundle(None, True) packagelayout.test_blacklisted_files(err, mock_xpi) assert err.warnings eq_(err.warnings[0]['id'], ('testcases_packagelayout', 'test_blacklisted_files', 'java_jar')) def test_blacklisted_magic_numbers(): 'Tests that blacklisted magic numbers are banned' err = _do_test('tests/resources/packagelayout/magic_number.xpi', packagelayout.test_blacklisted_files, True) assert err.metadata['contains_binary_content'] # Same logic as above. err = _do_test('tests/resources/packagelayout/magic_number.xpi', packagelayout.test_compatibility_binary, False) print err.compat_summary assert not err.compat_summary['errors'] assert 'binary_components' not in err.metadata def test_compat_binary_extensions(): """ Test that the validator will throw compatibility errors for files that would otherwise require the add-on to be manually updated. """ # This time when the compatibility checks are run, they should fire off # compatibility errors because the files are the /components/ directory # of the package. err = _do_test('tests/resources/packagelayout/ext_blacklist_compat.xpi', packagelayout.test_compatibility_binary, False) print err.compat_summary assert err.compat_summary['errors'] assert err.metadata['binary_components'] def test_godlikea(): """Test that packages with a godlikea chrome namespaceget rejected.""" err = ErrorBundle() xpi = MockXPI({'chrome/godlikea.jar': True}) packagelayout.test_godlikea(err, xpi) assert err.failed() assert err.errors # These functions will test the code with manually constructed packages # that contain valid or failing versions of the specified package. The # remaining tests will simply emulate this behaviour (since it was # successfully tested with these functions). def test_theme_passing(): 'Tests the layout of a proper theme' _do_test('tests/resources/packagelayout/theme.jar', packagelayout.test_theme_layout, False) def test_extra_unimportant(): """Tests the layout of a theme that contains an unimportant but extra directory.""" _do_test('tests/resources/packagelayout/theme_extra_unimportant.jar', packagelayout.test_theme_layout, False) def _do_simulated_test(function, structure, failure=False, ff4=False): """"Performs a test on a function or set of functions without generating a full package.""" dict_structure = {'__MACOSX/foo.bar': True} for item in structure: dict_structure[item] = True err = ErrorBundle() err.save_resource('ff4', ff4) function(err, structure) err.print_summary(True) if failure: assert err.failed() else: assert not err.failed() return err def test_langpack_max(): """Tests the package layout module out on a simulated language pack containing the largest number of possible elements.""" _do_simulated_test(packagelayout.test_langpack_layout, ['install.rdf', 'chrome/foo.jar', 'chrome.manifest', 'chrome/bar.test.jar', 'foo.manifest', 'bar.rdf', 'abc.dtd', 'def.jar', 'chrome/asdf.properties', 'chrome/asdf.xhtml', 'chrome/asdf.css']) def test_langpack_sans_jars(): """ Test that language packs don't require JAR files to be present in the chrome/ directory. """ _do_simulated_test( packagelayout.test_langpack_layout, ['install.rdf', 'chrome.manifest', # Required files 'foo.manifest', 'bar.rdf', 'abc.dtd', 'def.jar', # Allowed files 'chrome/foo.properties', 'chrome/foo.xhtml', 'chrome/foo.css']) def test_dict_max(): """Tests the package layout module out on a simulated dictionary containing the largest number of possible elements.""" _do_simulated_test(packagelayout.test_dictionary_layout, ['install.rdf', 'dictionaries/foo.aff', 'dictionaries/bar.test.dic', 'install.js', 'dictionaries/foo.aff', 'dictionaries/bar.test.dic', 'chrome.manifest', 'chrome/whatever.jar']) def test_unknown_file(): """Tests that the unknown file detection function is working.""" # We test against langpack because it is incredibly strict in its # file format. _do_simulated_test(packagelayout.test_langpack_layout, ['install.rdf', 'chrome/foo.jar', 'chrome.manifest', 'chromelist.txt']) def test_disallowed_file(): """Tests that outright improper files are blocked.""" # We test against langpack because it is incredibly strict in its # file format. _do_simulated_test(packagelayout.test_langpack_layout, ['install.rdf', 'chrome/foo.jar', 'chrome.manifest', 'foo.bar'], True) def test_extra_obsolete(): """Tests that unnecessary, obsolete files are detected.""" err = ErrorBundle() # Tests that chromelist.txt is treated (with and without slashes in # the path) as an obsolete file. assert not packagelayout.test_unknown_file(err, 'x//whatever.txt') assert not packagelayout.test_unknown_file(err, 'whatever.txt') assert packagelayout.test_unknown_file(err, 'x//chromelist.txt') assert packagelayout.test_unknown_file(err, 'chromelist.txt') assert not err.failed() def test_has_installrdfs(): """Tests that install.rdf files are present and that subpackage rules are respected.""" # Test package to make sure has_install_rdf is set to True. assert not _do_config_test(packagelayout.test_layout_all) assert _do_config_test( packagelayout.test_layout_all, has_install_rdf=False) mock_xpi_subpack = MockXPI({}, subpackage=True) # Makes sure the above test is ignored if the package is a # subpackage. assert not _do_config_test(packagelayout.test_layout_all, has_install_rdf=False, xpi=mock_xpi_subpack) assert not _do_config_test(packagelayout.test_layout_all, has_install_rdf=True, xpi=mock_xpi_subpack) def test_has_package_json(): """Tests that having an install.rdf is not required with a package.json.""" assert not _do_config_test( packagelayout.test_layout_all, has_install_rdf=False, has_package_json=True), 'errors when only package.json present' def test_no_package_json(): """Tests that there are errors when there is not an install.rdf or a package.json""" assert _do_config_test( packagelayout.test_layout_all, has_install_rdf=False, has_package_json=False), ( 'no errors and no install.rdf or package.json') def test_has_manifest_json(): """Tests that having an install.rdf or package.json is not required with a manifest.json.""" assert not _do_config_test( packagelayout.test_layout_all, has_install_rdf=False, has_package_json=False, has_manifest_json=True), 'errors when only manifest.json present' def test_no_manifest_json(): """Tests that there are errors when there is not an install.rdf or a package.json or a manifest.json""" assert _do_config_test( packagelayout.test_layout_all, has_install_rdf=False, has_package_json=False, has_manifest_json=False), ( 'no errors and no install.rdf or package.json or manifest.json') class MockDupeZipFile(object): """Mock a ZipFile class, simulating duplicate filename entries.""" def namelist(self): return ['foo.bar', 'foo.bar'] class MockDupeXPI(object): """Mock the XPIManager class, simulating duplicate filename entries.""" def __init__(self): self.zf = MockDupeZipFile() self.subpackage = False def test_duplicate_files(): """Test that duplicate files in a package are caught.""" err = ErrorBundle() err.save_resource('has_install_rdf', True) packagelayout.test_layout_all(err, MockDupeXPI()) assert err.failed() def _do_config_test(function, has_install_rdf=True, has_package_json=False, has_manifest_json=False, xpi=None): 'Helps to test that install.rdf files are present' err = ErrorBundle() content = {} if has_install_rdf: content['install.rdf'] = True err.save_resource('has_install_rdf', True) if has_package_json: content['package.json'] = True err.save_resource('has_package_json', True) if has_manifest_json: content['manifest.json'] = True err.save_resource('has_manifest_json', True) if xpi is None: xpi = MockXPI(content) function(err, xpi) return err.failed()
kumar303/amo-validator
tests/test_packagelayout.py
Python
bsd-3-clause
10,737
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2019, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of 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 // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "Gaffer/NameSwitch.h" #include "Gaffer/NameValuePlug.h" #include "Gaffer/StringPlug.h" using namespace std; using namespace IECore; using namespace Gaffer; size_t NameSwitch::g_firstPlugIndex = 0; GAFFER_NODE_DEFINE_TYPE( NameSwitch ); NameSwitch::NameSwitch( const std::string &name ) : Switch( name ) { storeIndexOfNextChild( g_firstPlugIndex ); addChild( new StringPlug( "selector" ) ); addChild( new IntPlug( "__outIndex", Plug::Out ) ); indexPlug()->setName( "__index" ); indexPlug()->setInput( outIndexPlug() ); } NameSwitch::~NameSwitch() { } void NameSwitch::setup( const Plug *plug ) { if( inPlugs() ) { throw IECore::Exception( "Switch already has an \"in\" plug." ); } if( outPlug() ) { throw IECore::Exception( "Switch already has an \"out\" plug." ); } PlugPtr inElement = plug->createCounterpart( "value", Plug::In ); inElement->setFlags( Plug::Serialisable, true ); NameValuePlugPtr element = new NameValuePlug( "", inElement, /* defaultEnabled = */ true, "in0" ); ArrayPlugPtr in = new ArrayPlug( "in", Plug::In, element, 2, Imath::limits<size_t>::max(), Plug::Default, /* resizeWhenInputsChange = */ false ); addChild( in ); PlugPtr out = new NameValuePlug( "", plug->createCounterpart( "value", Plug::Out ), /* defaultEnabled = */ true, "out" ); addChild( out ); inPlugs()->getChild<NameValuePlug>( 0 )->namePlug()->setValue( "*" ); } StringPlug *NameSwitch::selectorPlug() { return getChild<StringPlug>( g_firstPlugIndex ); } const StringPlug *NameSwitch::selectorPlug() const { return getChild<StringPlug>( g_firstPlugIndex ); } IntPlug *NameSwitch::outIndexPlug() { return getChild<IntPlug>( g_firstPlugIndex + 1 ); } const IntPlug *NameSwitch::outIndexPlug() const { return getChild<IntPlug>( g_firstPlugIndex + 1 ); } void NameSwitch::affects( const Plug *input, DependencyNode::AffectedPlugsContainer &outputs ) const { Switch::affects( input, outputs ); auto nameValuePlug = input->parent<NameValuePlug>(); if( input == selectorPlug() || ( nameValuePlug && nameValuePlug->parent() == inPlugs() && ( input == nameValuePlug->namePlug() || input == nameValuePlug->enabledPlug() ) ) ) { outputs.push_back( outIndexPlug() ); } } void NameSwitch::hash( const ValuePlug *output, const Context *context, IECore::MurmurHash &h ) const { Switch::hash( output, context, h ); if( output == outIndexPlug() ) { selectorPlug()->hash( h ); const ArrayPlug *in = inPlugs(); for( int i = 1, e = in->children().size(); i < e; ++i ) { auto p = in->getChild<NameValuePlug>( i ); p->enabledPlug()->hash( h ); p->namePlug()->hash( h ); } } } void NameSwitch::compute( ValuePlug *output, const Context *context ) const { if( output == outIndexPlug() ) { int outIndex = 0; const string selector = selectorPlug()->getValue(); const ArrayPlug *in = inPlugs(); for( int i = 1, e = in->children().size(); i < e; ++i ) { auto p = in->getChild<NameValuePlug>( i ); if( !p->enabledPlug()->getValue() ) { continue; } const string name = p->namePlug()->getValue(); if( !name.empty() && StringAlgo::matchMultiple( selector, name ) ) { outIndex = i; break; } } static_cast<IntPlug *>( output )->setValue( outIndex ); return; } Switch::compute( output, context ); }
andrewkaufman/gaffer
src/Gaffer/NameSwitch.cpp
C++
bsd-3-clause
5,163
# -*- coding:utf-8 -*- import mock import unittest from ...auth.builder import UserFactory class UserFactoryTestCase(unittest.TestCase): def setUp(self): self.get_username_from_email = UserFactory.get_username_from_email def tearDown(self): UserFactory.get_username_from_email = self.get_username_from_email @mock.patch('libs.auth.builder.User.objects.filter') def test_user_exists_should_return_true_if_hashed_email_exists( self, user_filter): # setup email = '[email protected]' user_filter.return_value.count.return_value = 1 UserFactory.get_username_from_email = mock.Mock() # action returned_value = UserFactory.user_exists(email) # assert self.assertTupleEqual((email,), UserFactory.get_username_from_email.call_args[0]) self.assertDictEqual( dict(username=UserFactory.get_username_from_email(email)), user_filter.call_args[1]) self.assertTrue(returned_value) @mock.patch('libs.auth.builder.User.objects.filter') def test_user_exists_should_return_false_if_hashed_email_doesnt_exists( self, user_filter): # setup email = '[email protected]' user_filter.return_value.count.return_value = 0 UserFactory.get_username_from_email = mock.Mock() # action returned_value = UserFactory.user_exists(email) # assert self.assertTupleEqual((email,), UserFactory.get_username_from_email.call_args[0]) self.assertDictEqual( dict(username=UserFactory.get_username_from_email(email)), user_filter.call_args[1]) self.assertFalse(returned_value) @mock.patch('libs.auth.builder.User') def test_create_user_should_hash_email_use_it_as_username_set_password_and_returned_saved_user( self, user_class): # setup email = '[email protected]' password = 'password' UserFactory.get_username_from_email = mock.Mock() # action returned_value = UserFactory.create_user(email, password) # assert self.assertTupleEqual((email,), UserFactory.get_username_from_email.call_args[0]) self.assertDictEqual( dict(username=UserFactory.get_username_from_email.return_value, email=email), user_class.call_args[1]) self.assertTupleEqual((password,), user_class.return_value.set_password.call_args[0]) self.assertEqual(1, user_class.return_value.save.call_count) self.assertEqual(id(user_class.return_value), id(returned_value)) @mock.patch('libs.auth.builder.random.randint') @mock.patch('libs.auth.builder.hashlib.sha1') @mock.patch('libs.auth.builder.salt_b64encode') @mock.patch('libs.auth.builder.sha1_b64encode') def test_get_username_from_email_should_hash_and_normalize_email( self, sha1_b64encode, salt_b64encode, sha1, randint): # setup email = '[email protected]' normalized_email = 'a_verylargeemailexample.com' randint.return_value = 10 salt_b64encode.return_value = 'abcdefghijklmnopqrstuvwxyz0123456789ABCD' sha1_b64encode.return_value = 'abcdefghijklmnopqrstuvwxyz0123456789ABCD' # action returned_value = UserFactory.get_username_from_email(email) # assert self.assertTupleEqual((email,), sha1.call_args[0]) self.assertTupleEqual((sha1.return_value.digest.return_value,), sha1_b64encode.call_args[0]) self.assertTupleEqual((0, 2**64,), randint.call_args[0]) self.assertTupleEqual(('10',), salt_b64encode.call_args[0]) self.assertEqual( (normalized_email[:10] + salt_b64encode.return_value[:-10] \ + salt_b64encode.return_value)[:30], returned_value)
hellhovnd/dentexchange
dentexchange/apps/libs/tests/auth/test_user_factory.py
Python
bsd-3-clause
3,898
""" This package contains definitions for the geometric primitives in use in ``phantomas``. """ __all__ = ['fiber', 'models', 'utils', 'rois']
oesteban/phantomas
phantomas/geometry/__init__.py
Python
bsd-3-clause
145
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np from ..extern.six.moves import range __all__ = ['jackknife_resampling', 'jackknife_stats'] __doctest_requires__ = {'jackknife_stats': ['scipy.special']} def jackknife_resampling(data): """ Performs jackknife resampling on numpy arrays. Jackknife resampling is a technique to generate 'n' deterministic samples of size 'n-1' from a measured sample of size 'n'. Basically, the i-th sample, (1<=i<=n), is generated by means of removing the i-th measurement of the original sample. Like the bootstrap resampling, this statistical technique finds applications in estimating variance, bias, and confidence intervals. Parameters ---------- data : numpy.ndarray Original sample (1-D array) from which the jackknife resamples will be generated. Returns ------- resamples : numpy.ndarray The i-th row is the i-th jackknife sample, i.e., the original sample with the i-th measurement deleted. References ---------- .. [1] McIntosh, Avery. "The Jackknife Estimation Method". <http://people.bu.edu/aimcinto/jackknife.pdf> .. [2] Efron, Bradley. "The Jackknife, the Bootstrap, and other Resampling Plans". Technical Report No. 63, Division of Biostatistics, Stanford University, December, 1980. .. [3] Cowles, Kate. "Computing in Statistics: The Jackknife, Lecture 11". <http://homepage.stat.uiowa.edu/~kcowles/s166_2009/lect11.pdf>. September, 2009. """ n = data.shape[0] assert n > 0, "data must contain at least one measurement" resamples = np.empty([n, n-1]) for i in range(n): resamples[i] = np.delete(data, i) return resamples def jackknife_stats(data, statistic, conf_lvl=0.95): """ Performs jackknife estimation on the basis of jackknife resamples. This function requires `SciPy <http://www.scipy.org>`_ to be installed. Parameters ---------- data : numpy.ndarray Original sample (1-D array). statistic : function Any function (or vector of functions) on the basis of the measured data, e.g, sample mean, sample variance, etc. The jackknife estimate of this statistic will be returned. conf_lvl : float, optional Confidence level for the confidence interval of the Jackknife estimate. Must be a real-valued number in (0,1). Default value is 0.95. Returns ------- estimate : numpy.float64 or numpy.ndarray The i-th element is the bias-corrected "jackknifed" estimate. bias : numpy.float64 or numpy.ndarray The i-th element is the jackknife bias. std_err : numpy.float64 or numpy.ndarray The i-th element is the jackknife standard error. conf_interval : numpy.ndarray If ``statistic`` is single-valued, the first and second elements are the lower and upper bounds, respectively. If ``statistic`` is vector-valued, each column corresponds to the confidence interval for each component of ``statistic``. The first and second rows contain the lower and upper bounds, respectively. Examples -------- 1. Obtain Jackknife resamples: >>> import numpy as np >>> from astropy.stats import jackknife_resampling >>> from astropy.stats import jackknife_stats >>> data = np.array([1,2,3,4,5,6,7,8,9,0]) >>> resamples = jackknife_resampling(data) >>> resamples array([[ 2., 3., 4., 5., 6., 7., 8., 9., 0.], [ 1., 3., 4., 5., 6., 7., 8., 9., 0.], [ 1., 2., 4., 5., 6., 7., 8., 9., 0.], [ 1., 2., 3., 5., 6., 7., 8., 9., 0.], [ 1., 2., 3., 4., 6., 7., 8., 9., 0.], [ 1., 2., 3., 4., 5., 7., 8., 9., 0.], [ 1., 2., 3., 4., 5., 6., 8., 9., 0.], [ 1., 2., 3., 4., 5., 6., 7., 9., 0.], [ 1., 2., 3., 4., 5., 6., 7., 8., 0.], [ 1., 2., 3., 4., 5., 6., 7., 8., 9.]]) >>> resamples.shape (10, 9) 2. Obtain Jackknife estimate for the mean, its bias, its standard error, and its 95% confidence interval: >>> test_statistic = np.mean >>> estimate, bias, stderr, conf_interval = jackknife_stats( ... data, test_statistic, 0.95) >>> estimate 4.5 >>> bias 0.0 >>> stderr 0.95742710775633832 >>> conf_interval array([ 2.62347735, 6.37652265]) 3. Example for two estimates >>> test_statistic = lambda x: (np.mean(x), np.var(x)) >>> estimate, bias, stderr, conf_interval = jackknife_stats( ... data, test_statistic, 0.95) >>> estimate array([ 4.5 , 9.16666667]) >>> bias array([ 0. , -0.91666667]) >>> stderr array([ 0.95742711, 2.69124476]) >>> conf_interval array([[ 2.62347735, 3.89192387], [ 6.37652265, 14.44140947]]) IMPORTANT: Note that confidence intervals are given as columns """ from scipy.special import erfinv # make sure original data is proper n = data.shape[0] assert n > 0, "data must contain at least one measurement" resamples = jackknife_resampling(data) stat_data = statistic(data) jack_stat = np.apply_along_axis(statistic, 1, resamples) mean_jack_stat = np.mean(jack_stat, axis=0) # jackknife bias bias = (n-1)*(mean_jack_stat - stat_data) # jackknife standard error std_err = np.sqrt((n-1)*np.mean((jack_stat - mean_jack_stat)*(jack_stat - mean_jack_stat), axis=0)) # bias-corrected "jackknifed estimate" estimate = stat_data - bias # jackknife confidence interval assert (conf_lvl > 0 and conf_lvl < 1), ("confidence level must be in " "(0, 1).") z_score = np.sqrt(2.0)*erfinv(conf_lvl) conf_interval = estimate + z_score*np.array((-std_err, std_err)) return estimate, bias, std_err, conf_interval
joergdietrich/astropy
astropy/stats/jackknife.py
Python
bsd-3-clause
6,186
/* * Copyright (C) 2012 Google Inc. All rights reserved. * Copyright (C) 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "Internals.h" #include "HTMLNames.h" #include "InspectorFrontendClientLocal.h" #include "InternalRuntimeFlags.h" #include "InternalSettings.h" #include "MallocStatistics.h" #include "MockPagePopupDriver.h" #include "RuntimeEnabledFeatures.h" #include "TypeConversions.h" #include "bindings/v8/SerializedScriptValue.h" #include "core/css/StyleSheetContents.h" #include "core/dom/ClientRect.h" #include "core/dom/ClientRectList.h" #include "core/dom/DOMStringList.h" #include "core/dom/Document.h" #include "core/dom/DocumentMarker.h" #include "core/dom/DocumentMarkerController.h" #include "core/dom/Element.h" #include "core/dom/ExceptionCode.h" #include "core/dom/FullscreenController.h" #include "core/dom/NodeRenderingContext.h" #include "core/dom/PseudoElement.h" #include "core/dom/Range.h" #include "core/dom/StaticNodeList.h" #include "core/dom/TreeScope.h" #include "core/dom/ViewportArguments.h" #include "core/dom/shadow/ComposedShadowTreeWalker.h" #include "core/dom/shadow/ContentDistributor.h" #include "core/dom/shadow/ElementShadow.h" #include "core/dom/shadow/SelectRuleFeatureSet.h" #include "core/dom/shadow/ShadowRoot.h" #include "core/editing/Editor.h" #include "core/editing/SpellChecker.h" #include "core/editing/TextIterator.h" #include "core/history/BackForwardController.h" #include "core/history/HistoryItem.h" #include "core/html/FormController.h" #include "core/html/HTMLInputElement.h" #include "core/html/HTMLMediaElement.h" #include "core/html/HTMLSelectElement.h" #include "core/html/HTMLTextAreaElement.h" #include "core/html/shadow/HTMLContentElement.h" #include "core/inspector/InspectorClient.h" #include "core/inspector/InspectorConsoleAgent.h" #include "core/inspector/InspectorController.h" #include "core/inspector/InspectorCounters.h" #include "core/inspector/InspectorFrontendChannel.h" #include "core/inspector/InspectorInstrumentation.h" #include "core/inspector/InspectorOverlay.h" #include "core/inspector/InstrumentingAgents.h" #include "core/loader/FrameLoader.h" #include "core/loader/cache/CachedResourceLoader.h" #include "core/loader/cache/MemoryCache.h" #include "core/page/Chrome.h" #include "core/page/ChromeClient.h" #include "core/page/DOMPoint.h" #include "core/page/DOMWindow.h" #include "core/page/EventHandler.h" #include "core/page/Frame.h" #include "core/page/FrameView.h" #include "core/page/Page.h" #include "core/page/PrintContext.h" #include "core/page/Settings.h" #include "core/page/animation/AnimationController.h" #include "core/page/scrolling/ScrollingCoordinator.h" #include "core/platform/ColorChooser.h" #include "core/platform/Cursor.h" #include "core/platform/Language.h" #include "core/platform/graphics/IntRect.h" #include "core/rendering/RenderMenuList.h" #include "core/rendering/RenderObject.h" #include "core/rendering/RenderTreeAsText.h" #include "core/rendering/RenderView.h" #include "core/workers/WorkerThread.h" #include "weborigin/SchemeRegistry.h" #include "wtf/dtoa.h" #include "wtf/text/StringBuffer.h" #include "core/page/PagePopupController.h" #include "core/platform/graphics/GraphicsLayer.h" #include "core/platform/graphics/filters/FilterOperation.h" #include "core/platform/graphics/filters/FilterOperations.h" #include "core/rendering/RenderLayerBacking.h" #include "core/platform/mock/PlatformSpeechSynthesizerMock.h" #include "modules/speech/DOMWindowSpeechSynthesis.h" #include "modules/speech/SpeechSynthesis.h" namespace WebCore { static MockPagePopupDriver* s_pagePopupDriver = 0; using namespace HTMLNames; class InspectorFrontendChannelDummy : public InspectorFrontendChannel { public: explicit InspectorFrontendChannelDummy(Page*); virtual ~InspectorFrontendChannelDummy() { } virtual bool sendMessageToFrontend(const String& message) OVERRIDE; private: Page* m_frontendPage; }; InspectorFrontendChannelDummy::InspectorFrontendChannelDummy(Page* page) : m_frontendPage(page) { } bool InspectorFrontendChannelDummy::sendMessageToFrontend(const String& message) { return InspectorClient::doDispatchMessageOnFrontendPage(m_frontendPage, message); } static bool markerTypesFrom(const String& markerType, DocumentMarker::MarkerTypes& result) { if (markerType.isEmpty() || equalIgnoringCase(markerType, "all")) result = DocumentMarker::AllMarkers(); else if (equalIgnoringCase(markerType, "Spelling")) result = DocumentMarker::Spelling; else if (equalIgnoringCase(markerType, "Grammar")) result = DocumentMarker::Grammar; else if (equalIgnoringCase(markerType, "TextMatch")) result = DocumentMarker::TextMatch; else return false; return true; } static SpellChecker* spellchecker(Document* document) { if (!document || !document->frame() || !document->frame()->editor()) return 0; return document->frame()->editor()->spellChecker(); } const char* Internals::internalsId = "internals"; PassRefPtr<Internals> Internals::create(Document* document) { return adoptRef(new Internals(document)); } Internals::~Internals() { } void Internals::resetToConsistentState(Page* page) { ASSERT(page); page->setDeviceScaleFactor(1); page->setPageScaleFactor(1, IntPoint(0, 0)); page->setPagination(Pagination()); TextRun::setAllowsRoundingHacks(false); WebCore::overrideUserPreferredLanguages(Vector<String>()); WebCore::Settings::setUsesOverlayScrollbars(false); delete s_pagePopupDriver; s_pagePopupDriver = 0; page->chrome().client()->resetPagePopupDriver(); if (!page->mainFrame()->editor()->isContinuousSpellCheckingEnabled()) page->mainFrame()->editor()->toggleContinuousSpellChecking(); if (page->mainFrame()->editor()->isOverwriteModeEnabled()) page->mainFrame()->editor()->toggleOverwriteModeEnabled(); } Internals::Internals(Document* document) : ContextLifecycleObserver(document) , m_runtimeFlags(InternalRuntimeFlags::create()) { } Document* Internals::contextDocument() const { return toDocument(scriptExecutionContext()); } Frame* Internals::frame() const { if (!contextDocument()) return 0; return contextDocument()->frame(); } InternalSettings* Internals::settings() const { Document* document = contextDocument(); if (!document) return 0; Page* page = document->page(); if (!page) return 0; return InternalSettings::from(page); } InternalRuntimeFlags* Internals::runtimeFlags() const { return m_runtimeFlags.get(); } unsigned Internals::workerThreadCount() const { return WorkerThread::workerThreadCount(); } String Internals::address(Node* node) { char buf[32]; sprintf(buf, "%p", node); return String(buf); } bool Internals::isPreloaded(const String& url) { Document* document = contextDocument(); return document->cachedResourceLoader()->isPreloaded(url); } bool Internals::isLoadingFromMemoryCache(const String& url) { if (!contextDocument()) return false; CachedResource* resource = memoryCache()->resourceForURL(contextDocument()->completeURL(url)); return resource && resource->status() == CachedResource::Cached; } void Internals::crash() { CRASH(); } PassRefPtr<Element> Internals::createContentElement(ExceptionCode& ec) { Document* document = contextDocument(); if (!document) { ec = INVALID_ACCESS_ERR; return 0; } return HTMLContentElement::create(document); } bool Internals::isValidContentSelect(Element* insertionPoint, ExceptionCode& ec) { if (!insertionPoint || !insertionPoint->isInsertionPoint()) { ec = INVALID_ACCESS_ERR; return false; } return isHTMLContentElement(insertionPoint) && toHTMLContentElement(insertionPoint)->isSelectValid(); } Node* Internals::treeScopeRootNode(Node* node, ExceptionCode& ec) { if (!node) { ec = INVALID_ACCESS_ERR; return 0; } return node->treeScope()->rootNode(); } Node* Internals::parentTreeScope(Node* node, ExceptionCode& ec) { if (!node) { ec = INVALID_ACCESS_ERR; return 0; } const TreeScope* parentTreeScope = node->treeScope()->parentTreeScope(); return parentTreeScope ? parentTreeScope->rootNode() : 0; } bool Internals::hasSelectorForIdInShadow(Element* host, const String& idValue, ExceptionCode& ec) { if (!host || !host->shadow()) { ec = INVALID_ACCESS_ERR; return 0; } return host->shadow()->distributor().ensureSelectFeatureSet(host->shadow()).hasSelectorForId(idValue); } bool Internals::hasSelectorForClassInShadow(Element* host, const String& className, ExceptionCode& ec) { if (!host || !host->shadow()) { ec = INVALID_ACCESS_ERR; return 0; } return host->shadow()->distributor().ensureSelectFeatureSet(host->shadow()).hasSelectorForClass(className); } bool Internals::hasSelectorForAttributeInShadow(Element* host, const String& attributeName, ExceptionCode& ec) { if (!host || !host->shadow()) { ec = INVALID_ACCESS_ERR; return 0; } return host->shadow()->distributor().ensureSelectFeatureSet(host->shadow()).hasSelectorForAttribute(attributeName); } bool Internals::hasSelectorForPseudoClassInShadow(Element* host, const String& pseudoClass, ExceptionCode& ec) { if (!host || !host->shadow()) { ec = INVALID_ACCESS_ERR; return 0; } const SelectRuleFeatureSet& featureSet = host->shadow()->distributor().ensureSelectFeatureSet(host->shadow()); if (pseudoClass == "checked") return featureSet.hasSelectorForChecked(); if (pseudoClass == "enabled") return featureSet.hasSelectorForEnabled(); if (pseudoClass == "disabled") return featureSet.hasSelectorForDisabled(); if (pseudoClass == "indeterminate") return featureSet.hasSelectorForIndeterminate(); if (pseudoClass == "link") return featureSet.hasSelectorForLink(); if (pseudoClass == "target") return featureSet.hasSelectorForTarget(); if (pseudoClass == "visited") return featureSet.hasSelectorForVisited(); ASSERT_NOT_REACHED(); return false; } unsigned short Internals::compareTreeScopePosition(const Node* node1, const Node* node2, ExceptionCode& ec) const { if (!node1 || !node2) { ec = INVALID_ACCESS_ERR; return 0; } const TreeScope* treeScope1 = node1->isDocumentNode() ? static_cast<const TreeScope*>(toDocument(node1)) : node1->isShadowRoot() ? static_cast<const TreeScope*>(toShadowRoot(node1)) : 0; const TreeScope* treeScope2 = node2->isDocumentNode() ? static_cast<const TreeScope*>(toDocument(node2)) : node2->isShadowRoot() ? static_cast<const TreeScope*>(toShadowRoot(node2)) : 0; if (!treeScope1 || !treeScope2) { ec = INVALID_ACCESS_ERR; return 0; } return treeScope1->comparePosition(treeScope2); } unsigned Internals::numberOfActiveAnimations() const { Frame* contextFrame = frame(); if (AnimationController* controller = contextFrame->animation()) return controller->numberOfActiveAnimations(contextFrame->document()); return 0; } void Internals::suspendAnimations(Document* document, ExceptionCode& ec) const { if (!document || !document->frame()) { ec = INVALID_ACCESS_ERR; return; } AnimationController* controller = document->frame()->animation(); if (!controller) return; controller->suspendAnimations(); } void Internals::resumeAnimations(Document* document, ExceptionCode& ec) const { if (!document || !document->frame()) { ec = INVALID_ACCESS_ERR; return; } AnimationController* controller = document->frame()->animation(); if (!controller) return; controller->resumeAnimations(); } void Internals::pauseAnimations(double pauseTime, ExceptionCode& ec) { if (pauseTime < 0) { ec = INVALID_ACCESS_ERR; return; } frame()->animation()->pauseAnimationsForTesting(pauseTime); } bool Internals::hasShadowInsertionPoint(const Node* root, ExceptionCode& ec) const { if (root && root->isShadowRoot()) return ScopeContentDistribution::hasShadowElement(toShadowRoot(root)); ec = INVALID_ACCESS_ERR; return 0; } bool Internals::hasContentElement(const Node* root, ExceptionCode& ec) const { if (root && root->isShadowRoot()) return ScopeContentDistribution::hasContentElement(toShadowRoot(root)); ec = INVALID_ACCESS_ERR; return 0; } size_t Internals::countElementShadow(const Node* root, ExceptionCode& ec) const { if (!root || !root->isShadowRoot()) { ec = INVALID_ACCESS_ERR; return 0; } return ScopeContentDistribution::countElementShadow(toShadowRoot(root)); } bool Internals::attached(Node* node, ExceptionCode& ec) { if (!node) { ec = INVALID_ACCESS_ERR; return false; } return node->attached(); } Node* Internals::nextSiblingByWalker(Node* node, ExceptionCode& ec) { if (!node) { ec = INVALID_ACCESS_ERR; return 0; } ComposedShadowTreeWalker walker(node); walker.nextSibling(); return walker.get(); } Node* Internals::firstChildByWalker(Node* node, ExceptionCode& ec) { if (!node) { ec = INVALID_ACCESS_ERR; return 0; } ComposedShadowTreeWalker walker(node); walker.firstChild(); return walker.get(); } Node* Internals::lastChildByWalker(Node* node, ExceptionCode& ec) { if (!node) { ec = INVALID_ACCESS_ERR; return 0; } ComposedShadowTreeWalker walker(node); walker.lastChild(); return walker.get(); } Node* Internals::nextNodeByWalker(Node* node, ExceptionCode& ec) { if (!node) { ec = INVALID_ACCESS_ERR; return 0; } ComposedShadowTreeWalker walker(node); walker.next(); return walker.get(); } Node* Internals::previousNodeByWalker(Node* node, ExceptionCode& ec) { if (!node) { ec = INVALID_ACCESS_ERR; return 0; } ComposedShadowTreeWalker walker(node); walker.previous(); return walker.get(); } String Internals::elementRenderTreeAsText(Element* element, ExceptionCode& ec) { if (!element) { ec = INVALID_ACCESS_ERR; return String(); } String representation = externalRepresentation(element); if (representation.isEmpty()) { ec = INVALID_ACCESS_ERR; return String(); } return representation; } size_t Internals::numberOfScopedHTMLStyleChildren(const Node* scope, ExceptionCode& ec) const { if (scope && (scope->isElementNode() || scope->isShadowRoot())) return scope->numberOfScopedHTMLStyleChildren(); ec = INVALID_ACCESS_ERR; return 0; } PassRefPtr<CSSComputedStyleDeclaration> Internals::computedStyleIncludingVisitedInfo(Node* node, ExceptionCode& ec) const { if (!node) { ec = INVALID_ACCESS_ERR; return 0; } bool allowVisitedStyle = true; return CSSComputedStyleDeclaration::create(node, allowVisitedStyle); } ShadowRoot* Internals::ensureShadowRoot(Element* host, ExceptionCode& ec) { if (!host) { ec = INVALID_ACCESS_ERR; return 0; } if (ElementShadow* shadow = host->shadow()) return shadow->youngestShadowRoot(); return host->createShadowRoot(ec).get(); } ShadowRoot* Internals::shadowRoot(Element* host, ExceptionCode& ec) { // FIXME: Internals::shadowRoot() in tests should be converted to youngestShadowRoot() or oldestShadowRoot(). // https://bugs.webkit.org/show_bug.cgi?id=78465 return youngestShadowRoot(host, ec); } ShadowRoot* Internals::youngestShadowRoot(Element* host, ExceptionCode& ec) { if (!host) { ec = INVALID_ACCESS_ERR; return 0; } if (ElementShadow* shadow = host->shadow()) return shadow->youngestShadowRoot(); return 0; } ShadowRoot* Internals::oldestShadowRoot(Element* host, ExceptionCode& ec) { if (!host) { ec = INVALID_ACCESS_ERR; return 0; } if (ElementShadow* shadow = host->shadow()) return shadow->oldestShadowRoot(); return 0; } ShadowRoot* Internals::youngerShadowRoot(Node* shadow, ExceptionCode& ec) { if (!shadow || !shadow->isShadowRoot()) { ec = INVALID_ACCESS_ERR; return 0; } return toShadowRoot(shadow)->youngerShadowRoot(); } ShadowRoot* Internals::olderShadowRoot(Node* shadow, ExceptionCode& ec) { if (!shadow || !shadow->isShadowRoot()) { ec = INVALID_ACCESS_ERR; return 0; } return toShadowRoot(shadow)->olderShadowRoot(); } String Internals::shadowRootType(const Node* root, ExceptionCode& ec) const { if (!root || !root->isShadowRoot()) { ec = INVALID_ACCESS_ERR; return String(); } switch (toShadowRoot(root)->type()) { case ShadowRoot::UserAgentShadowRoot: return String("UserAgentShadowRoot"); case ShadowRoot::AuthorShadowRoot: return String("AuthorShadowRoot"); default: ASSERT_NOT_REACHED(); return String("Unknown"); } } Element* Internals::includerFor(Node* node, ExceptionCode& ec) { if (!node) { ec = INVALID_ACCESS_ERR; return 0; } return NodeRenderingContext(node).insertionPoint(); } String Internals::shadowPseudoId(Element* element, ExceptionCode& ec) { if (!element) { ec = INVALID_ACCESS_ERR; return String(); } return element->shadowPseudoId().string(); } void Internals::setShadowPseudoId(Element* element, const String& id, ExceptionCode& ec) { if (!element) { ec = INVALID_ACCESS_ERR; return; } return element->setPseudo(id); } String Internals::visiblePlaceholder(Element* element) { if (element && isHTMLTextFormControlElement(element)) { if (toHTMLTextFormControlElement(element)->placeholderShouldBeVisible()) return toHTMLTextFormControlElement(element)->placeholderElement()->textContent(); } return String(); } void Internals::selectColorInColorChooser(Element* element, const String& colorValue) { if (!element->hasTagName(inputTag)) return; toHTMLInputElement(element)->selectColorInColorChooser(Color(colorValue)); } Vector<String> Internals::formControlStateOfPreviousHistoryItem(ExceptionCode& ec) { HistoryItem* mainItem = frame()->loader()->history()->previousItem(); if (!mainItem) { ec = INVALID_ACCESS_ERR; return Vector<String>(); } String uniqueName = frame()->tree()->uniqueName(); if (mainItem->target() != uniqueName && !mainItem->childItemWithTarget(uniqueName)) { ec = INVALID_ACCESS_ERR; return Vector<String>(); } return mainItem->target() == uniqueName ? mainItem->documentState() : mainItem->childItemWithTarget(uniqueName)->documentState(); } void Internals::setFormControlStateOfPreviousHistoryItem(const Vector<String>& state, ExceptionCode& ec) { HistoryItem* mainItem = frame()->loader()->history()->previousItem(); if (!mainItem) { ec = INVALID_ACCESS_ERR; return; } String uniqueName = frame()->tree()->uniqueName(); if (mainItem->target() == uniqueName) mainItem->setDocumentState(state); else if (HistoryItem* subItem = mainItem->childItemWithTarget(uniqueName)) subItem->setDocumentState(state); else ec = INVALID_ACCESS_ERR; } void Internals::enableMockSpeechSynthesizer() { Document* document = contextDocument(); if (!document || !document->domWindow()) return; SpeechSynthesis* synthesis = DOMWindowSpeechSynthesis::speechSynthesis(document->domWindow()); if (!synthesis) return; synthesis->setPlatformSynthesizer(PlatformSpeechSynthesizerMock::create(synthesis)); } void Internals::setEnableMockPagePopup(bool enabled, ExceptionCode& ec) { Document* document = contextDocument(); if (!document || !document->page()) return; Page* page = document->page(); if (!enabled) { page->chrome().client()->resetPagePopupDriver(); return; } if (!s_pagePopupDriver) s_pagePopupDriver = MockPagePopupDriver::create(page->mainFrame()).leakPtr(); page->chrome().client()->setPagePopupDriver(s_pagePopupDriver); } PassRefPtr<PagePopupController> Internals::pagePopupController() { return s_pagePopupDriver ? s_pagePopupDriver->pagePopupController() : 0; } PassRefPtr<ClientRect> Internals::absoluteCaretBounds(ExceptionCode& ec) { Document* document = contextDocument(); if (!document || !document->frame() || !document->frame()->selection()) { ec = INVALID_ACCESS_ERR; return ClientRect::create(); } return ClientRect::create(document->frame()->selection()->absoluteCaretBounds()); } PassRefPtr<ClientRect> Internals::boundingBox(Element* element, ExceptionCode& ec) { if (!element) { ec = INVALID_ACCESS_ERR; return ClientRect::create(); } element->document()->updateLayoutIgnorePendingStylesheets(); RenderObject* renderer = element->renderer(); if (!renderer) return ClientRect::create(); return ClientRect::create(renderer->absoluteBoundingBoxRectIgnoringTransforms()); } PassRefPtr<ClientRectList> Internals::inspectorHighlightRects(Document* document, ExceptionCode& ec) { if (!document || !document->page() || !document->page()->inspectorController()) { ec = INVALID_ACCESS_ERR; return ClientRectList::create(); } Highlight highlight; document->page()->inspectorController()->getHighlight(&highlight); return ClientRectList::create(highlight.quads); } unsigned Internals::markerCountForNode(Node* node, const String& markerType, ExceptionCode& ec) { if (!node) { ec = INVALID_ACCESS_ERR; return 0; } DocumentMarker::MarkerTypes markerTypes = 0; if (!markerTypesFrom(markerType, markerTypes)) { ec = SYNTAX_ERR; return 0; } return node->document()->markers()->markersFor(node, markerTypes).size(); } DocumentMarker* Internals::markerAt(Node* node, const String& markerType, unsigned index, ExceptionCode& ec) { if (!node) { ec = INVALID_ACCESS_ERR; return 0; } DocumentMarker::MarkerTypes markerTypes = 0; if (!markerTypesFrom(markerType, markerTypes)) { ec = SYNTAX_ERR; return 0; } Vector<DocumentMarker*> markers = node->document()->markers()->markersFor(node, markerTypes); if (markers.size() <= index) return 0; return markers[index]; } PassRefPtr<Range> Internals::markerRangeForNode(Node* node, const String& markerType, unsigned index, ExceptionCode& ec) { DocumentMarker* marker = markerAt(node, markerType, index, ec); if (!marker) return 0; return Range::create(node->document(), node, marker->startOffset(), node, marker->endOffset()); } String Internals::markerDescriptionForNode(Node* node, const String& markerType, unsigned index, ExceptionCode& ec) { DocumentMarker* marker = markerAt(node, markerType, index, ec); if (!marker) return String(); return marker->description(); } void Internals::addTextMatchMarker(const Range* range, bool isActive) { range->ownerDocument()->updateLayoutIgnorePendingStylesheets(); range->ownerDocument()->markers()->addTextMatchMarker(range, isActive); } void Internals::setScrollViewPosition(Document* document, long x, long y, ExceptionCode& ec) { if (!document || !document->view()) { ec = INVALID_ACCESS_ERR; return; } FrameView* frameView = document->view(); bool constrainsScrollingToContentEdgeOldValue = frameView->constrainsScrollingToContentEdge(); bool scrollbarsSuppressedOldValue = frameView->scrollbarsSuppressed(); frameView->setConstrainsScrollingToContentEdge(false); frameView->setScrollbarsSuppressed(false); frameView->setScrollOffsetFromInternals(IntPoint(x, y)); frameView->setScrollbarsSuppressed(scrollbarsSuppressedOldValue); frameView->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdgeOldValue); } void Internals::setPagination(Document* document, const String& mode, int gap, int pageLength, ExceptionCode& ec) { if (!document || !document->page()) { ec = INVALID_ACCESS_ERR; return; } Page* page = document->page(); Pagination pagination; if (mode == "Unpaginated") pagination.mode = Pagination::Unpaginated; else if (mode == "LeftToRightPaginated") pagination.mode = Pagination::LeftToRightPaginated; else if (mode == "RightToLeftPaginated") pagination.mode = Pagination::RightToLeftPaginated; else if (mode == "TopToBottomPaginated") pagination.mode = Pagination::TopToBottomPaginated; else if (mode == "BottomToTopPaginated") pagination.mode = Pagination::BottomToTopPaginated; else { ec = SYNTAX_ERR; return; } pagination.gap = gap; pagination.pageLength = pageLength; page->setPagination(pagination); } String Internals::configurationForViewport(Document* document, float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight, ExceptionCode& ec) { if (!document || !document->page()) { ec = INVALID_ACCESS_ERR; return String(); } Page* page = document->page(); const int defaultLayoutWidthForNonMobilePages = 980; // FIXME(aelias): Remove this argument from all the fast/viewport tests. ASSERT(devicePixelRatio == 1); ViewportArguments arguments = page->viewportArguments(); PageScaleConstraints constraints = arguments.resolve(IntSize(availableWidth, availableHeight), FloatSize(deviceWidth, deviceHeight), defaultLayoutWidthForNonMobilePages); constraints.fitToContentsWidth(constraints.layoutSize.width(), availableWidth); return "viewport size " + String::number(constraints.layoutSize.width()) + "x" + String::number(constraints.layoutSize.height()) + " scale " + String::number(constraints.initialScale) + " with limits [" + String::number(constraints.minimumScale) + ", " + String::number(constraints.maximumScale) + "] and userScalable " + (arguments.userZoom ? "true" : "false"); } bool Internals::wasLastChangeUserEdit(Element* textField, ExceptionCode& ec) { if (!textField) { ec = INVALID_ACCESS_ERR; return false; } if (textField->hasTagName(inputTag)) return toHTMLInputElement(textField)->lastChangeWasUserEdit(); // FIXME: We should be using hasTagName instead but Windows port doesn't link QualifiedNames properly. if (textField->tagName() == "TEXTAREA") return static_cast<HTMLTextAreaElement*>(textField)->lastChangeWasUserEdit(); ec = INVALID_NODE_TYPE_ERR; return false; } bool Internals::elementShouldAutoComplete(Element* element, ExceptionCode& ec) { if (!element) { ec = INVALID_ACCESS_ERR; return false; } if (element->hasTagName(inputTag)) return toHTMLInputElement(element)->shouldAutocomplete(); ec = INVALID_NODE_TYPE_ERR; return false; } String Internals::suggestedValue(Element* element, ExceptionCode& ec) { if (!element) { ec = INVALID_ACCESS_ERR; return String(); } if (!element->hasTagName(inputTag)) { ec = INVALID_NODE_TYPE_ERR; return String(); } return toHTMLInputElement(element)->suggestedValue(); } void Internals::setSuggestedValue(Element* element, const String& value, ExceptionCode& ec) { if (!element) { ec = INVALID_ACCESS_ERR; return; } if (!element->hasTagName(inputTag)) { ec = INVALID_NODE_TYPE_ERR; return; } toHTMLInputElement(element)->setSuggestedValue(value); } void Internals::setEditingValue(Element* element, const String& value, ExceptionCode& ec) { if (!element) { ec = INVALID_ACCESS_ERR; return; } if (!element->hasTagName(inputTag)) { ec = INVALID_NODE_TYPE_ERR; return; } toHTMLInputElement(element)->setEditingValue(value); } void Internals::setAutofilled(Element* element, bool enabled, ExceptionCode& ec) { if (!element->hasTagName(inputTag)) { ec = INVALID_ACCESS_ERR; return; } toHTMLInputElement(element)->setAutofilled(enabled); } void Internals::scrollElementToRect(Element* element, long x, long y, long w, long h, ExceptionCode& ec) { if (!element || !element->document() || !element->document()->view()) { ec = INVALID_ACCESS_ERR; return; } FrameView* frameView = element->document()->view(); frameView->scrollElementToRect(element, IntRect(x, y, w, h)); } void Internals::paintControlTints(Document* document, ExceptionCode& ec) { if (!document || !document->view()) { ec = INVALID_ACCESS_ERR; return; } FrameView* frameView = document->view(); frameView->paintControlTints(); } PassRefPtr<Range> Internals::rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength, ExceptionCode& ec) { if (!scope) { ec = INVALID_ACCESS_ERR; return 0; } return TextIterator::rangeFromLocationAndLength(scope, rangeLocation, rangeLength); } unsigned Internals::locationFromRange(Element* scope, const Range* range, ExceptionCode& ec) { if (!scope || !range) { ec = INVALID_ACCESS_ERR; return 0; } size_t location = 0; size_t unusedLength = 0; TextIterator::getLocationAndLengthFromRange(scope, range, location, unusedLength); return location; } unsigned Internals::lengthFromRange(Element* scope, const Range* range, ExceptionCode& ec) { if (!scope || !range) { ec = INVALID_ACCESS_ERR; return 0; } size_t unusedLocation = 0; size_t length = 0; TextIterator::getLocationAndLengthFromRange(scope, range, unusedLocation, length); return length; } String Internals::rangeAsText(const Range* range, ExceptionCode& ec) { if (!range) { ec = INVALID_ACCESS_ERR; return String(); } return range->text(); } PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionCode& ec) { if (!document || !document->frame()) { ec = INVALID_ACCESS_ERR; return 0; } document->updateLayout(); IntSize radius(width / 2, height / 2); IntPoint point(x + radius.width(), y + radius.height()); Node* targetNode; IntPoint adjustedPoint; bool foundNode = document->frame()->eventHandler()->bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode); if (foundNode) return DOMPoint::create(adjustedPoint.x(), adjustedPoint.y()); return 0; } Node* Internals::touchNodeAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionCode& ec) { if (!document || !document->frame()) { ec = INVALID_ACCESS_ERR; return 0; } document->updateLayout(); IntSize radius(width / 2, height / 2); IntPoint point(x + radius.width(), y + radius.height()); Node* targetNode; IntPoint adjustedPoint; document->frame()->eventHandler()->bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode); return targetNode; } PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionCode& ec) { if (!document || !document->frame()) { ec = INVALID_ACCESS_ERR; return 0; } document->updateLayout(); IntSize radius(width / 2, height / 2); IntPoint point(x + radius.width(), y + radius.height()); Node* targetNode = 0; IntPoint adjustedPoint; bool foundNode = document->frame()->eventHandler()->bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode); if (foundNode) return DOMPoint::create(adjustedPoint.x(), adjustedPoint.y()); return DOMPoint::create(x, y); } Node* Internals::touchNodeAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionCode& ec) { if (!document || !document->frame()) { ec = INVALID_ACCESS_ERR; return 0; } document->updateLayout(); IntSize radius(width / 2, height / 2); IntPoint point(x + radius.width(), y + radius.height()); Node* targetNode = 0; IntPoint adjustedPoint; document->frame()->eventHandler()->bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode); return targetNode; } PassRefPtr<ClientRect> Internals::bestZoomableAreaForTouchPoint(long x, long y, long width, long height, Document* document, ExceptionCode& ec) { if (!document || !document->frame()) { ec = INVALID_ACCESS_ERR; return 0; } document->updateLayout(); IntSize radius(width / 2, height / 2); IntPoint point(x + radius.width(), y + radius.height()); Node* targetNode; IntRect zoomableArea; bool foundNode = document->frame()->eventHandler()->bestZoomableAreaForTouchPoint(point, radius, zoomableArea, targetNode); if (foundNode) return ClientRect::create(zoomableArea); return 0; } int Internals::lastSpellCheckRequestSequence(Document* document, ExceptionCode& ec) { SpellChecker* checker = spellchecker(document); if (!checker) { ec = INVALID_ACCESS_ERR; return -1; } return checker->lastRequestSequence(); } int Internals::lastSpellCheckProcessedSequence(Document* document, ExceptionCode& ec) { SpellChecker* checker = spellchecker(document); if (!checker) { ec = INVALID_ACCESS_ERR; return -1; } return checker->lastProcessedSequence(); } Vector<String> Internals::userPreferredLanguages() const { return WebCore::userPreferredLanguages(); } void Internals::setUserPreferredLanguages(const Vector<String>& languages) { WebCore::overrideUserPreferredLanguages(languages); } unsigned Internals::wheelEventHandlerCount(Document* document, ExceptionCode& ec) { if (!document) { ec = INVALID_ACCESS_ERR; return 0; } return document->wheelEventHandlerCount(); } unsigned Internals::touchEventHandlerCount(Document* document, ExceptionCode& ec) { if (!document) { ec = INVALID_ACCESS_ERR; return 0; } const TouchEventTargetSet* touchHandlers = document->touchEventTargets(); if (!touchHandlers) return 0; unsigned count = 0; for (TouchEventTargetSet::const_iterator iter = touchHandlers->begin(); iter != touchHandlers->end(); ++iter) count += iter->value; return count; } PassRefPtr<ClientRectList> Internals::touchEventTargetClientRects(Document* document, ExceptionCode& ec) { if (!document || !document->view() || !document->page()) { ec = INVALID_ACCESS_ERR; return 0; } if (!document->page()->scrollingCoordinator()) return ClientRectList::create(); document->updateLayoutIgnorePendingStylesheets(); Vector<IntRect> absoluteRects; document->page()->scrollingCoordinator()->computeAbsoluteTouchEventTargetRects(document, absoluteRects); Vector<FloatQuad> absoluteQuads(absoluteRects.size()); for (size_t i = 0; i < absoluteRects.size(); ++i) absoluteQuads[i] = FloatQuad(absoluteRects[i]); return ClientRectList::create(absoluteQuads); } PassRefPtr<NodeList> Internals::nodesFromRect(Document* document, int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent, bool allowChildFrameContent, ExceptionCode& ec) const { if (!document || !document->frame() || !document->frame()->view()) { ec = INVALID_ACCESS_ERR; return 0; } Frame* frame = document->frame(); FrameView* frameView = document->view(); RenderView* renderView = document->renderView(); if (!renderView) return 0; float zoomFactor = frame->pageZoomFactor(); LayoutPoint point = roundedLayoutPoint(FloatPoint(centerX * zoomFactor + frameView->scrollX(), centerY * zoomFactor + frameView->scrollY())); HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active; if (ignoreClipping) hitType |= HitTestRequest::IgnoreClipping; if (!allowShadowContent) hitType |= HitTestRequest::DisallowShadowContent; if (allowChildFrameContent) hitType |= HitTestRequest::AllowChildFrameContent; HitTestRequest request(hitType); // When ignoreClipping is false, this method returns null for coordinates outside of the viewport. if (!request.ignoreClipping() && !frameView->visibleContentRect().intersects(HitTestLocation::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding))) return 0; Vector<RefPtr<Node> > matches; // Need padding to trigger a rect based hit test, but we want to return a NodeList // so we special case this. if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) { HitTestResult result(point); renderView->hitTest(request, result); if (result.innerNode()) matches.append(result.innerNode()->deprecatedShadowAncestorNode()); } else { HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding); renderView->hitTest(request, result); copyToVector(result.rectBasedTestResult(), matches); } return StaticNodeList::adopt(matches); } void Internals::emitInspectorDidBeginFrame() { InspectorController* inspectorController = contextDocument()->frame()->page()->inspectorController(); inspectorController->didBeginFrame(); } void Internals::emitInspectorDidCancelFrame() { InspectorController* inspectorController = contextDocument()->frame()->page()->inspectorController(); inspectorController->didCancelFrame(); } bool Internals::hasSpellingMarker(Document* document, int from, int length, ExceptionCode&) { if (!document || !document->frame()) return 0; return document->frame()->editor()->selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length); } void Internals::setContinuousSpellCheckingEnabled(bool enabled, ExceptionCode&) { if (!contextDocument() || !contextDocument()->frame() || !contextDocument()->frame()->editor()) return; if (enabled != contextDocument()->frame()->editor()->isContinuousSpellCheckingEnabled()) contextDocument()->frame()->editor()->toggleContinuousSpellChecking(); } bool Internals::isOverwriteModeEnabled(Document* document, ExceptionCode&) { if (!document || !document->frame()) return 0; return document->frame()->editor()->isOverwriteModeEnabled(); } void Internals::toggleOverwriteModeEnabled(Document* document, ExceptionCode&) { if (!document || !document->frame()) return; document->frame()->editor()->toggleOverwriteModeEnabled(); } unsigned Internals::numberOfLiveNodes() const { return InspectorCounters::counterValue(InspectorCounters::NodeCounter); } unsigned Internals::numberOfLiveDocuments() const { return InspectorCounters::counterValue(InspectorCounters::DocumentCounter); } Vector<String> Internals::consoleMessageArgumentCounts(Document* document) const { InstrumentingAgents* instrumentingAgents = instrumentationForPage(document->page()); if (!instrumentingAgents) return Vector<String>(); InspectorConsoleAgent* consoleAgent = instrumentingAgents->inspectorConsoleAgent(); if (!consoleAgent) return Vector<String>(); Vector<unsigned> counts = consoleAgent->consoleMessageArgumentCounts(); Vector<String> result(counts.size()); for (size_t i = 0; i < counts.size(); i++) result[i] = String::number(counts[i]); return result; } PassRefPtr<DOMWindow> Internals::openDummyInspectorFrontend(const String& url) { Page* page = contextDocument()->frame()->page(); ASSERT(page); DOMWindow* window = page->mainFrame()->document()->domWindow(); ASSERT(window); m_frontendWindow = window->open(url, "", "", window, window); ASSERT(m_frontendWindow); Page* frontendPage = m_frontendWindow->document()->page(); ASSERT(frontendPage); OwnPtr<InspectorFrontendClientLocal> frontendClient = adoptPtr(new InspectorFrontendClientLocal(page->inspectorController(), frontendPage)); frontendPage->inspectorController()->setInspectorFrontendClient(frontendClient.release()); m_frontendChannel = adoptPtr(new InspectorFrontendChannelDummy(frontendPage)); page->inspectorController()->connectFrontend(m_frontendChannel.get()); return m_frontendWindow; } void Internals::closeDummyInspectorFrontend() { Page* page = contextDocument()->frame()->page(); ASSERT(page); ASSERT(m_frontendWindow); page->inspectorController()->disconnectFrontend(); m_frontendChannel.release(); m_frontendWindow->close(m_frontendWindow->scriptExecutionContext()); m_frontendWindow.release(); } Vector<unsigned long> Internals::setMemoryCacheCapacities(unsigned long minDeadBytes, unsigned long maxDeadBytes, unsigned long totalBytes) { Vector<unsigned long> result; result.append(memoryCache()->minDeadCapacity()); result.append(memoryCache()->maxDeadCapacity()); result.append(memoryCache()->capacity()); memoryCache()->setCapacities(minDeadBytes, maxDeadBytes, totalBytes); return result; } void Internals::setInspectorResourcesDataSizeLimits(int maximumResourcesContentSize, int maximumSingleResourceContentSize, ExceptionCode& ec) { Page* page = contextDocument()->frame()->page(); if (!page || !page->inspectorController()) { ec = INVALID_ACCESS_ERR; return; } page->inspectorController()->setResourcesDataSizeLimitsFromInternals(maximumResourcesContentSize, maximumSingleResourceContentSize); } bool Internals::hasGrammarMarker(Document* document, int from, int length, ExceptionCode&) { if (!document || !document->frame()) return 0; return document->frame()->editor()->selectionStartHasMarkerFor(DocumentMarker::Grammar, from, length); } unsigned Internals::numberOfScrollableAreas(Document* document, ExceptionCode&) { unsigned count = 0; Frame* frame = document->frame(); if (frame->view()->scrollableAreas()) count += frame->view()->scrollableAreas()->size(); for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) { if (child->view() && child->view()->scrollableAreas()) count += child->view()->scrollableAreas()->size(); } return count; } bool Internals::isPageBoxVisible(Document* document, int pageNumber, ExceptionCode& ec) { if (!document) { ec = INVALID_ACCESS_ERR; return false; } return document->isPageBoxVisible(pageNumber); } String Internals::layerTreeAsText(Document* document, ExceptionCode& ec) const { return layerTreeAsText(document, 0, ec); } String Internals::elementLayerTreeAsText(Element* element, ExceptionCode& ec) const { return elementLayerTreeAsText(element, 0, ec); } static PassRefPtr<NodeList> paintOrderList(Element* element, ExceptionCode& ec, RenderLayer::PaintOrderListType type) { if (!element) { ec = INVALID_ACCESS_ERR; return 0; } element->document()->updateLayout(); RenderObject* renderer = element->renderer(); if (!renderer || !renderer->isBox()) { ec = INVALID_ACCESS_ERR; return 0; } RenderLayer* layer = toRenderBox(renderer)->layer(); if (!layer) { ec = INVALID_ACCESS_ERR; return 0; } Vector<RefPtr<Node> > nodes; layer->computePaintOrderList(type, nodes); return StaticNodeList::adopt(nodes); } PassRefPtr<NodeList> Internals::paintOrderListBeforePromote(Element* element, ExceptionCode& ec) { return paintOrderList(element, ec, RenderLayer::BeforePromote); } PassRefPtr<NodeList> Internals::paintOrderListAfterPromote(Element* element, ExceptionCode& ec) { return paintOrderList(element, ec, RenderLayer::AfterPromote); } String Internals::layerTreeAsText(Document* document, unsigned flags, ExceptionCode& ec) const { if (!document || !document->frame()) { ec = INVALID_ACCESS_ERR; return String(); } return document->frame()->layerTreeAsText(flags); } String Internals::elementLayerTreeAsText(Element* element, unsigned flags, ExceptionCode& ec) const { if (!element) { ec = INVALID_ACCESS_ERR; return String(); } element->document()->updateLayout(); RenderObject* renderer = element->renderer(); if (!renderer || !renderer->isBox()) { ec = INVALID_ACCESS_ERR; return String(); } RenderLayer* layer = toRenderBox(renderer)->layer(); if (!layer) { ec = INVALID_ACCESS_ERR; return String(); } if (!layer->backing() || !layer->backing()->graphicsLayer()) { // Don't raise exception in these cases which may be normally used in tests. return String(); } return layer->backing()->graphicsLayer()->layerTreeAsText(flags); } void Internals::setNeedsCompositedScrolling(Element* element, unsigned needsCompositedScrolling, ExceptionCode& ec) { if (!element) { ec = INVALID_ACCESS_ERR; return; } element->document()->updateLayout(); RenderObject* renderer = element->renderer(); if (!renderer || !renderer->isBox()) { ec = INVALID_ACCESS_ERR; return; } RenderLayer* layer = toRenderBox(renderer)->layer(); if (!layer) { ec = INVALID_ACCESS_ERR; return; } layer->setForceNeedsCompositedScrolling(static_cast<RenderLayer::ForceNeedsCompositedScrollingMode>(needsCompositedScrolling)); } String Internals::repaintRectsAsText(Document* document, ExceptionCode& ec) const { if (!document || !document->frame()) { ec = INVALID_ACCESS_ERR; return String(); } return document->frame()->trackedRepaintRectsAsText(); } String Internals::scrollingStateTreeAsText(Document* document, ExceptionCode& ec) const { return String(); } String Internals::mainThreadScrollingReasons(Document* document, ExceptionCode& ec) const { if (!document || !document->frame()) { ec = INVALID_ACCESS_ERR; return String(); } Page* page = document->page(); if (!page) return String(); return page->mainThreadScrollingReasonsAsText(); } PassRefPtr<ClientRectList> Internals::nonFastScrollableRects(Document* document, ExceptionCode& ec) const { if (!document || !document->frame()) { ec = INVALID_ACCESS_ERR; return 0; } Page* page = document->page(); if (!page) return 0; return page->nonFastScrollableRects(document->frame()); } void Internals::garbageCollectDocumentResources(Document* document, ExceptionCode& ec) const { if (!document) { ec = INVALID_ACCESS_ERR; return; } CachedResourceLoader* cachedResourceLoader = document->cachedResourceLoader(); if (!cachedResourceLoader) return; cachedResourceLoader->garbageCollectDocumentResources(); } void Internals::allowRoundingHacks() const { TextRun::setAllowsRoundingHacks(true); } void Internals::insertAuthorCSS(Document* document, const String& css) const { RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(document); parsedSheet->setIsUserStyleSheet(false); parsedSheet->parseString(css); document->styleSheetCollection()->addAuthorSheet(parsedSheet); } void Internals::insertUserCSS(Document* document, const String& css) const { RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(document); parsedSheet->setIsUserStyleSheet(true); parsedSheet->parseString(css); document->styleSheetCollection()->addUserSheet(parsedSheet); } String Internals::counterValue(Element* element) { if (!element) return String(); return counterValueForElement(element); } int Internals::pageNumber(Element* element, float pageWidth, float pageHeight) { if (!element) return 0; return PrintContext::pageNumberForElement(element, FloatSize(pageWidth, pageHeight)); } Vector<String> Internals::iconURLs(Document* document, int iconTypesMask) const { Vector<IconURL> iconURLs = document->iconURLs(iconTypesMask); Vector<String> array; Vector<IconURL>::const_iterator iter(iconURLs.begin()); for (; iter != iconURLs.end(); ++iter) array.append(iter->m_iconURL.string()); return array; } Vector<String> Internals::shortcutIconURLs(Document* document) const { return iconURLs(document, Favicon); } Vector<String> Internals::allIconURLs(Document* document) const { return iconURLs(document, Favicon | TouchIcon | TouchPrecomposedIcon); } int Internals::numberOfPages(float pageWidth, float pageHeight) { if (!frame()) return -1; return PrintContext::numberOfPages(frame(), FloatSize(pageWidth, pageHeight)); } String Internals::pageProperty(String propertyName, int pageNumber, ExceptionCode& ec) const { if (!frame()) { ec = INVALID_ACCESS_ERR; return String(); } return PrintContext::pageProperty(frame(), propertyName.utf8().data(), pageNumber); } String Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft, ExceptionCode& ec) const { if (!frame()) { ec = INVALID_ACCESS_ERR; return String(); } return PrintContext::pageSizeAndMarginsInPixels(frame(), pageNumber, width, height, marginTop, marginRight, marginBottom, marginLeft); } void Internals::setDeviceScaleFactor(float scaleFactor, ExceptionCode& ec) { Document* document = contextDocument(); if (!document || !document->page()) { ec = INVALID_ACCESS_ERR; return; } Page* page = document->page(); page->setDeviceScaleFactor(scaleFactor); } void Internals::setPageScaleFactor(float scaleFactor, int x, int y, ExceptionCode& ec) { Document* document = contextDocument(); if (!document || !document->page()) { ec = INVALID_ACCESS_ERR; return; } Page* page = document->page(); page->setPageScaleFactor(scaleFactor, IntPoint(x, y)); } void Internals::setIsCursorVisible(Document* document, bool isVisible, ExceptionCode& ec) { if (!document || !document->page()) { ec = INVALID_ACCESS_ERR; return; } document->page()->setIsCursorVisible(isVisible); } void Internals::webkitWillEnterFullScreenForElement(Document* document, Element* element) { if (!document) return; FullscreenController::from(document)->webkitWillEnterFullScreenForElement(element); } void Internals::webkitDidEnterFullScreenForElement(Document* document, Element* element) { if (!document) return; FullscreenController::from(document)->webkitDidEnterFullScreenForElement(element); } void Internals::webkitWillExitFullScreenForElement(Document* document, Element* element) { if (!document) return; FullscreenController::from(document)->webkitWillExitFullScreenForElement(element); } void Internals::webkitDidExitFullScreenForElement(Document* document, Element* element) { if (!document) return; FullscreenController::from(document)->webkitDidExitFullScreenForElement(element); } void Internals::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme) { SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(scheme); } void Internals::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(const String& scheme) { SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(scheme); } PassRefPtr<MallocStatistics> Internals::mallocStatistics() const { return MallocStatistics::create(); } PassRefPtr<TypeConversions> Internals::typeConversions() const { return TypeConversions::create(); } Vector<String> Internals::getReferencedFilePaths() const { frame()->loader()->history()->saveDocumentAndScrollState(); return FormController::getReferencedFilePaths(frame()->loader()->history()->currentItem()->documentState()); } void Internals::startTrackingRepaints(Document* document, ExceptionCode& ec) { if (!document || !document->view()) { ec = INVALID_ACCESS_ERR; return; } FrameView* frameView = document->view(); frameView->setTracksRepaints(true); } void Internals::stopTrackingRepaints(Document* document, ExceptionCode& ec) { if (!document || !document->view()) { ec = INVALID_ACCESS_ERR; return; } FrameView* frameView = document->view(); frameView->setTracksRepaints(false); } static const char* cursorTypeToString(Cursor::Type cursorType) { switch (cursorType) { case Cursor::Pointer: return "Pointer"; case Cursor::Cross: return "Cross"; case Cursor::Hand: return "Hand"; case Cursor::IBeam: return "IBeam"; case Cursor::Wait: return "Wait"; case Cursor::Help: return "Help"; case Cursor::EastResize: return "EastResize"; case Cursor::NorthResize: return "NorthResize"; case Cursor::NorthEastResize: return "NorthEastResize"; case Cursor::NorthWestResize: return "NorthWestResize"; case Cursor::SouthResize: return "SouthResize"; case Cursor::SouthEastResize: return "SouthEastResize"; case Cursor::SouthWestResize: return "SouthWestResize"; case Cursor::WestResize: return "WestResize"; case Cursor::NorthSouthResize: return "NorthSouthResize"; case Cursor::EastWestResize: return "EastWestResize"; case Cursor::NorthEastSouthWestResize: return "NorthEastSouthWestResize"; case Cursor::NorthWestSouthEastResize: return "NorthWestSouthEastResize"; case Cursor::ColumnResize: return "ColumnResize"; case Cursor::RowResize: return "RowResize"; case Cursor::MiddlePanning: return "MiddlePanning"; case Cursor::EastPanning: return "EastPanning"; case Cursor::NorthPanning: return "NorthPanning"; case Cursor::NorthEastPanning: return "NorthEastPanning"; case Cursor::NorthWestPanning: return "NorthWestPanning"; case Cursor::SouthPanning: return "SouthPanning"; case Cursor::SouthEastPanning: return "SouthEastPanning"; case Cursor::SouthWestPanning: return "SouthWestPanning"; case Cursor::WestPanning: return "WestPanning"; case Cursor::Move: return "Move"; case Cursor::VerticalText: return "VerticalText"; case Cursor::Cell: return "Cell"; case Cursor::ContextMenu: return "ContextMenu"; case Cursor::Alias: return "Alias"; case Cursor::Progress: return "Progress"; case Cursor::NoDrop: return "NoDrop"; case Cursor::Copy: return "Copy"; case Cursor::None: return "None"; case Cursor::NotAllowed: return "NotAllowed"; case Cursor::ZoomIn: return "ZoomIn"; case Cursor::ZoomOut: return "ZoomOut"; case Cursor::Grab: return "Grab"; case Cursor::Grabbing: return "Grabbing"; case Cursor::Custom: return "Custom"; } ASSERT_NOT_REACHED(); return "UNKNOWN"; } String Internals::getCurrentCursorInfo(Document* document, ExceptionCode& ec) { if (!document || !document->frame()) { ec = INVALID_ACCESS_ERR; return String(); } Cursor cursor = document->frame()->eventHandler()->currentMouseCursor(); StringBuilder result; result.append("type="); result.append(cursorTypeToString(cursor.type())); result.append(" hotSpot="); result.appendNumber(cursor.hotSpot().x()); result.append(","); result.appendNumber(cursor.hotSpot().y()); if (cursor.image()) { IntSize size = cursor.image()->size(); result.append(" image="); result.appendNumber(size.width()); result.append("x"); result.appendNumber(size.height()); } if (cursor.imageScaleFactor() != 1) { result.append(" scale="); NumberToStringBuffer buffer; result.append(numberToFixedPrecisionString(cursor.imageScaleFactor(), 8, buffer, true)); } return result.toString(); } PassRefPtr<ArrayBuffer> Internals::serializeObject(PassRefPtr<SerializedScriptValue> value) const { String stringValue = value->toWireString(); return ArrayBuffer::create(static_cast<const void*>(stringValue.impl()->characters()), stringValue.sizeInBytes()); } PassRefPtr<SerializedScriptValue> Internals::deserializeBuffer(PassRefPtr<ArrayBuffer> buffer) const { String value(static_cast<const UChar*>(buffer->data()), buffer->byteLength() / sizeof(UChar)); return SerializedScriptValue::createFromWire(value); } void Internals::setUsesOverlayScrollbars(bool enabled) { WebCore::Settings::setUsesOverlayScrollbars(enabled); } void Internals::forceReload(bool endToEnd) { frame()->loader()->reload(endToEnd); } PassRefPtr<ClientRect> Internals::selectionBounds(ExceptionCode& ec) { Document* document = contextDocument(); if (!document || !document->frame() || !document->frame()->selection()) { ec = INVALID_ACCESS_ERR; return 0; } return ClientRect::create(document->frame()->selection()->bounds()); } String Internals::markerTextForListItem(Element* element, ExceptionCode& ec) { if (!element) { ec = INVALID_ACCESS_ERR; return String(); } return WebCore::markerTextForListItem(element); } String Internals::getImageSourceURL(Element* element, ExceptionCode& ec) { if (!element) { ec = INVALID_ACCESS_ERR; return String(); } return element->imageSourceURL(); } bool Internals::isSelectPopupVisible(Node* node) { if (!isHTMLSelectElement(node)) return false; HTMLSelectElement* select = toHTMLSelectElement(node); RenderObject* renderer = select->renderer(); if (!renderer->isMenuList()) return false; RenderMenuList* menuList = toRenderMenuList(renderer); return menuList->popupIsVisible(); } }
windyuuy/opera
chromium/src/third_party/WebKit/Source/core/testing/Internals.cpp
C++
bsd-3-clause
59,786
// // Copyright RIME Developers // Distributed under the BSD License // // 2011-04-06 Zou xu <[email protected]> // #include <gtest/gtest.h> #include <rime/component.h> #include <rime/config.h> using namespace rime; class RimeConfigTest : public ::testing::Test { protected: RimeConfigTest() = default; virtual void SetUp() { component_.reset(new ConfigComponent<ConfigLoader>); config_.reset(component_->Create("config_test")); } virtual void TearDown() { } the<Config::Component> component_; the<Config> config_; }; TEST(RimeConfigComponentTest, RoundTrip) { // registration Registry& r = Registry::instance(); r.Register( "test_config", new ConfigComponent<ConfigLoader, UserConfigResourceProvider>( [](ConfigLoader* loader) { loader->set_auto_save(true); })); // find component Config::Component* cc = Config::Require("test_config"); ASSERT_TRUE(cc != NULL); // create config and write modifications to file { the<Config> config(cc->Create("config_round_trip_test")); EXPECT_TRUE(bool(config)); EXPECT_TRUE(config->SetString("key", "value")); } // read from file and verify contents { the<Config> config(cc->Create("config_round_trip_test")); EXPECT_TRUE(bool(config)); string value; EXPECT_TRUE(config->GetString("key", &value)); EXPECT_EQ("value", value); } r.Unregister("test_config"); } TEST(RimeConfigItemTest, NullItem) { ConfigItem item; EXPECT_EQ(ConfigItem::kNull, item.type()); } TEST_F(RimeConfigTest, Config_IsNull) { bool is_null = config_->IsNull("terrans/tank"); EXPECT_FALSE(is_null); is_null = config_->IsNull("protoss/tank"); EXPECT_TRUE(is_null); } TEST_F(RimeConfigTest, Config_GetBool) { bool ret, value; ret = config_->GetBool("terrans/tank/seiged", &value); EXPECT_TRUE(ret); EXPECT_FALSE(value); ret = config_->GetBool("zerg/lurker/burrowed", &value); EXPECT_TRUE(ret); EXPECT_TRUE(value); } TEST_F(RimeConfigTest, Config_GetInt) { bool ret; int value; ret = config_->GetInt("terrans/supply/produced", &value); EXPECT_TRUE(ret); EXPECT_EQ(28, value); ret = config_->GetInt("zerg/zergling/lost", &value); EXPECT_TRUE(ret); EXPECT_EQ(1234, value); } TEST_F(RimeConfigTest, Config_GetDouble) { bool ret; double value; ret = config_->GetDouble("terrans/math/pi", &value); EXPECT_TRUE(ret); EXPECT_EQ(3.1415926, value); ret = config_->GetDouble("protoss/battery/energy", &value); EXPECT_TRUE(ret); EXPECT_EQ(10.111, value); } TEST_F(RimeConfigTest, Config_GetString) { bool ret; string value; ret = config_->GetString("protoss/residence", &value); EXPECT_TRUE(ret); EXPECT_EQ("Aiur", value); ret = config_->GetString("zerg/queen", &value); EXPECT_TRUE(ret); EXPECT_EQ("Kerrigan", value); } TEST_F(RimeConfigTest, Config_GetList) { an<ConfigList> p; p = config_->GetList("protoss/air_force"); ASSERT_TRUE(bool(p)); ASSERT_EQ(4, p->size()); an<ConfigValue> element; string value; element = p->GetValueAt(0); ASSERT_TRUE(bool(element)); ASSERT_TRUE(element->GetString(&value)); EXPECT_EQ("scout", value); element = p->GetValueAt(3); ASSERT_TRUE(bool(element)); ASSERT_TRUE(element->GetString(&value)); EXPECT_EQ("arbiter", value); } TEST_F(RimeConfigTest, Config_GetMap) { an<ConfigMap> p; p = config_->GetMap("terrans/tank/cost"); ASSERT_TRUE(bool(p)); EXPECT_FALSE(p->HasKey("rime")); ASSERT_TRUE(p->HasKey("time")); an<ConfigValue> item; string time; int mineral = 0; int gas = 0; item = p->GetValue("time"); ASSERT_TRUE(bool(item)); ASSERT_TRUE(item->GetString(&time)); EXPECT_EQ("30 seconds", time); item = p->GetValue("mineral"); ASSERT_TRUE(bool(item)); ASSERT_TRUE(item->GetInt(&mineral)); EXPECT_EQ(150, mineral); item = p->GetValue("gas"); ASSERT_TRUE(bool(item)); ASSERT_TRUE(item->GetInt(&gas)); EXPECT_EQ(100, gas); } TEST(RimeConfigWriterTest, Greetings) { the<Config> config(new Config); ASSERT_TRUE(bool(config)); // creating contents EXPECT_TRUE(config->SetItem("/", New<ConfigMap>())); an<ConfigItem> terran_greetings = New<ConfigValue>("Greetings, Terrans!"); an<ConfigItem> zerg_greetings = New<ConfigValue>("Zergsss are coming!"); an<ConfigItem> zergs_coming = New<ConfigValue>(true); an<ConfigItem> zergs_population = New<ConfigValue>(1000000); EXPECT_TRUE(config->SetItem("greetings", terran_greetings)); EXPECT_TRUE(config->SetItem("zergs/overmind/greetings", zerg_greetings)); EXPECT_TRUE(config->SetItem("zergs/going", zergs_coming)); EXPECT_TRUE(config->SetItem("zergs/statistics/population", zergs_population)); // will not create subkeys over an existing value node EXPECT_FALSE(config->SetItem("zergs/going/home", zerg_greetings)); // saving EXPECT_TRUE(config->SaveToFile("config_writer_test.yaml")); // verify the<Config> config2(new Config); ASSERT_TRUE(bool(config2)); EXPECT_TRUE(config2->LoadFromFile("config_writer_test.yaml")); string the_greetings; EXPECT_TRUE(config2->GetString("greetings", &the_greetings)); EXPECT_EQ("Greetings, Terrans!", the_greetings); EXPECT_TRUE(config2->GetString("zergs/overmind/greetings", &the_greetings)); EXPECT_EQ("Zergsss are coming!", the_greetings); bool coming = false; EXPECT_TRUE(config2->GetBool("zergs/going", &coming)); EXPECT_TRUE(coming); int population = 0; EXPECT_TRUE(config2->GetInt("zergs/statistics/population", &population)); EXPECT_EQ(1000000, population); EXPECT_FALSE(config2->GetString("zergs/going/home", &the_greetings)); // modifying tree EXPECT_TRUE(config2->SetInt("zergs/statistics/population", population / 2)); EXPECT_TRUE(config2->SetString("protoss/residence", "Aiur")); EXPECT_TRUE(config2->SetItem("zergs/overmind", nullptr)); EXPECT_TRUE(config2->SaveToFile("config_rewriter_test.yaml")); // verify the<Config> config3(new Config); ASSERT_TRUE(bool(config3)); EXPECT_TRUE(config3->LoadFromFile("config_rewriter_test.yaml")); EXPECT_TRUE(config3->GetInt("zergs/statistics/population", &population)); EXPECT_EQ(500000, population); string value; EXPECT_TRUE(config3->GetString("protoss/residence", &value)); EXPECT_EQ("Aiur", value); // deleted EXPECT_FALSE(config3->GetString("zergs/overmind/greetings", &value)); EXPECT_FALSE(config3->GetMap("zergs/overmind")); } TEST(RimeConfigxxTest, Operations) { Config config; config["str"] = "STR"; config["nested"]["bool"] = true; config["nested"]["int"] = 1000000; config["nested"]["greetings"] = New<ConfigValue>("Hello!"); config["list"][0] = New<ConfigMap>(); config["list"][0]["abc"] = "ABC"; config["list"].Append(New<ConfigMap>()); config["list"][1]["abc"] = "ZYX"; config["list"][2] = config["nested"]["greetings"]; config["list"][3]["abc"] = "123"; config["str"].Clear(); EXPECT_TRUE(config["str"].IsNull()); EXPECT_EQ(true, config["nested"]["bool"].ToBool()); EXPECT_EQ(1000000, config["nested"]["int"].ToInt()); EXPECT_EQ("Hello!", config["nested"]["greetings"].ToString()); EXPECT_TRUE(config["list"].IsList()); EXPECT_EQ(4, config["list"].size()); EXPECT_EQ("123", config["list"][3]["abc"].ToString()); EXPECT_EQ("Hello!", config["list"][2].ToString()); an<ConfigItem> v1(config["list"][2]); an<ConfigItem> v2(config["nested"]["greetings"]); EXPECT_EQ(v1, v2); EXPECT_TRUE(config.modified()); EXPECT_TRUE(config.SaveToFile("rime_configxx_test.yaml")); EXPECT_TRUE(config.LoadFromFile("rime_configxx_test.yaml")); EXPECT_TRUE(config["str"].IsNull()); EXPECT_FALSE(config.modified()); EXPECT_EQ("Hello!", config["nested"]["greetings"].ToString()); config["list"].Append(New<ConfigValue>("orz")); EXPECT_TRUE(config.modified()); ConfigMapEntryRef r(config["nested"]["greetings"]); EXPECT_EQ("Hello!", r.ToString()); } TEST(RimeConfigListKeyPathTest, Greetings) { int id = 0; int value = 0; the<Config> config(new Config); ASSERT_TRUE(bool(config)); // append items EXPECT_TRUE(config->SetInt("list/@next/id", 1)); EXPECT_TRUE(config->SetInt("list/@last/value", 100)); EXPECT_TRUE(config->SetInt("list/@next/id", 2)); EXPECT_TRUE(config->SetInt("list/@last/value", 200)); ASSERT_TRUE(bool(config->GetList("list"))); ASSERT_EQ(2, config->GetList("list")->size()); value = 0; EXPECT_TRUE(config->GetInt("list/@0/value", &value)); EXPECT_EQ(100, value); value = 0; EXPECT_TRUE(config->GetInt("list/@1/value", &value)); EXPECT_EQ(200, value); // insert items EXPECT_TRUE(config->SetInt("list/@before 0/id", 3)); EXPECT_TRUE(config->SetInt("list/@0/value", 50)); EXPECT_TRUE(config->SetInt("list/@after last/id", 4)); EXPECT_TRUE(config->SetInt("list/@last/value", 400)); ASSERT_EQ(4, config->GetList("list")->size()); value = 0; EXPECT_TRUE(config->GetInt("list/@0/value", &value)); EXPECT_EQ(50, value); value = 0; EXPECT_TRUE(config->GetInt("list/@1/value", &value)); EXPECT_EQ(100, value); value = 0; EXPECT_TRUE(config->GetInt("list/@2/value", &value)); EXPECT_EQ(200, value); value = 0; EXPECT_TRUE(config->GetInt("list/@3/value", &value)); EXPECT_EQ(400, value); // refer to last item in an empty list config->GetList("list")->Clear(); ASSERT_EQ(0, config->GetList("list")->size()); config->SetInt("list/@after last/id", 5); EXPECT_EQ(1, config->GetList("list")->size()); id = 0; EXPECT_TRUE(config->GetInt("list/@last/id", &id)); EXPECT_EQ(5, id); config->GetList("list")->Clear(); ASSERT_EQ(0, config->GetList("list")->size()); config->SetInt("list/@before last/id", 6); EXPECT_EQ(1, config->GetList("list")->size()); id = 0; EXPECT_TRUE(config->GetInt("list/@last/id", &id)); EXPECT_EQ(6, id); }
Prcuvu/librime
test/config_test.cc
C++
bsd-3-clause
9,735
/* * $RCSfile: SerializerFactory.java,v $ * * Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved. * * Use is subject to license terms. * * $Revision: 1.1 $ * $Date: 2005/02/11 04:57:54 $ * $State: Exp $ */ package com.lightcrafts.mediax.jai.remote; import java.awt.RenderingHints; import java.io.Serializable; import java.util.ArrayList; import java.util.Hashtable; import java.util.Vector; import com.lightcrafts.media.jai.rmi.SerializerImpl; import com.lightcrafts.media.jai.rmi.InterfaceState; /** * A utility class which provides factory methods for obtaining * <code>Serializer</code> instances. * * <p> The <code>Serializer</code>s are maintained in a centralized repository * which is organized based on the classes supported by the * <code>Serializer</code>s and the order in which the <code>Serializer</code>s * were registered. Convenience methods similar to those defined in the * <code>Serializer</code> class are also provided. These enable * functionality equivalent to a single <code>Serializer</code> which * supports all the classes supported by the aggregate of all * <code>Serializer</code>s resident in the repository. * * <p> By default <code>Serializer</code>s for the following classes * are registered by JAI: * * <ul> * <li><code>java.awt.RenderingHints</code> * <br>(entries which are neither <code>Serializable</code> nor supported by * <code>SerializerFactory</code> are omitted; support for specific * <code>RenderingHints.Key</code> subclasses may be added by new * <code>Serializer</code>s);</li> * <li><code>java.awt.RenderingHints.Key</code> * <br>(limited to <code>RenderingHints.Key</code>s defined in * <code>java.awt.RenderingHints</code> and <code>com.lightcrafts.mediax.jai.JAI</code>); * </li> * <li><code>java.awt.Shape</code>;</li> * <li><code>java.awt.image.DataBufferByte</code>;</li> * <li><code>java.awt.image.DataBufferShort</code>;</li> * <li><code>java.awt.image.DataBufferUShort</code>;</li> * <li><code>java.awt.image.DataBufferInt</code>;</li> * <li><code>com.lightcrafts.mediax.jai.DataBufferFloat</code>;</li> * <li><code>com.lightcrafts.mediax.jai.DataBufferDouble</code>;</li> * <li><code>java.awt.image.ComponentSampleModel</code>;</li> * <li><code>java.awt.image.BandedSampleModel</code>;</li> * <li><code>java.awt.image.PixelInterleavedSampleModel</code>;</li> * <li><code>java.awt.image.SinglePixelPackedSampleModel</code>;</li> * <li><code>java.awt.image.MultiPixelPackedSampleModel</code>;</li> * <li><code>com.lightcrafts.mediax.jai.ComponentSampleModelJAI</code>;</li> * <li><code>java.awt.image.Raster</code> * <br>(limited to <code>Raster</code>s which have a <code>DataBuffer</code> * and <code>SampleModel</code> supported by a <code>Serializer</code>);</li> * <li><code>java.awt.image.WritableRaster</code> * <br>(limited to <code>WritableRaster</code>s which have a * <code>DataBuffer</code> and <code>SampleModel</code> supported by a * <code>Serializer</code>);</li> * <li><code>java.awt.image.ComponentColorModel</code>;</li> * <li><code>java.awt.image.IndexColorModel</code>;</li> * <li><code>java.awt.image.DirectColorModel</code>;</li> * <li><code>com.lightcrafts.mediax.jai.FloatColorModel</code>;</li> * <li><code>java.awt.image.renderable.RenderContext</code>;</li> * <br>(constrained by the aforementioned limitations of * the <code>RenderingHints</code> <code>Serializer</code>);</li> * <li><code>java.awt.image.RenderedImage</code> * <br>(limited to <code>RenderedImage</code>s which have <code>Raster</code>s * and a <code>ColorModel</code> supported by a <code>Serializer</code>);</li> * <li><code>java.awt.image.WritableRenderedImage</code> * <br>(limited to <code>WritableRenderedImage</code>s which have * <code>Raster</code>s and a <code>ColorModel</code> supported by a * <code>Serializer</code>);</li> * <li><code>java.io.Serializable</code>;</li> * <li><code>java.util.HashSet</code> * <br>(elements which are neither <code>Serializable</code> nor supported by * <code>SerializerFactory</code> are omitted);</li> * <li><code>java.util.Hashtable</code> * <br>(entries which are neither <code>Serializable</code> nor supported by * <code>SerializerFactory</code> are omitted);</li> * <li><code>java.util.Vector</code> * <br>(elements which are neither <code>Serializable</code> nor supported by * <code>SerializerFactory</code> are omitted);</li> * </ul> * * @see SerializableState * @see Serializer * @see java.io.Serializable * * @since JAI 1.1 */ public final class SerializerFactory { /** * <code>Serializer</code> hashed by supported <code>Class</code>. * The value is a <code>Serializer</code> if there is only one for the * given <code>Class</code> or a <code>Vector</code> if there are more. */ private static Hashtable repository = new Hashtable(); /** * Singleton instance of <code>Serializer</code> for use with already * <code>Serializable</code> classes. */ private static Serializer serializableSerializer = new SerSerializer(); static final SerializableState NULL_STATE = new SerializableState() { public Class getObjectClass() { return Object.class; } public Object getObject() { return null; } }; static { // Load all <code>Serializer</code>s defined in com.lightcrafts.media.jai.rmi. SerializerImpl.registerSerializers(); } protected SerializerFactory() {} /** * Adds a <code>Serializer</code> to the repository. * * @param s The <code>Serializer</code>s to be added to the repository. * @exception IllegalArgumentException if <code>s</code> is * <code>null</code> */ public static synchronized void registerSerializer(Serializer s) { if(s == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } Class c = s.getSupportedClass(); if(repository.containsKey(c)) { Object value = repository.get(c); if(value instanceof Vector) { ((Vector)value).add(0, s); } else { Vector v = new Vector(2); v.add(0, s); v.add(1, value); repository.put(c, v); } } else { repository.put(c, s); } } /** * Removes a <code>Serializer</code> from the repository. * * @param s The <code>Serializer</code>s to be removed from the repository. * @exception IllegalArgumentException if <code>s</code> is * <code>null</code> */ public static synchronized void unregisterSerializer(Serializer s) { if(s == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } Class c = s.getSupportedClass(); Object value = repository.get(c); if(value != null) { if(value instanceof Vector) { Vector v = (Vector)value; v.remove(s); if(v.size() == 1) { repository.put(c, v.get(0)); } } else { repository.remove(c); } } } /** * Retrieves an array of all <code>Serializer</code>s currently * resident in the repository which directly support the specified * <code>Class</code>. <code>Serializer</code>s which support * a superclass of the specified class and permit subclass * serialization will not be included. * * @param c The class for which <code>Serializer</code>s will be * retrieved. * @exception IllegalArgumentException if <code>c</code> is * <code>null</code>. */ public static synchronized Serializer[] getSerializers(Class c) { if(c == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } Object value = repository.get(c); Serializer[] result = null; if(value == null && Serializable.class.isAssignableFrom(c)) { result = new Serializer[] {serializableSerializer}; } else if(value instanceof Vector) { result = (Serializer[])((Vector)value).toArray(new Serializer[0]); } else if(value != null) { result = new Serializer[] {(Serializer)value}; } return result; } /** * Retrieves a <code>Serializer</code> for a given class <code>c</code>. * If more than one <code>Serializer</code> is available for the class * then the most recently registered <code>Serializer</code> will be * returned. If no registered <code>Serializer</code> exists which * directly supports the specified class, i.e., one for which the * <code>getSupportedClass()</code> returns a value equal to the * specified class, then a <code>Serializer</code> may be returned * which is actually registered against a superclass but permits * subclass serialization. * * @param c The class for which <code>Serializer</code>s will be * retrieved. * @return A <code>Serializer</code> which supports the specified class. * or <code>null</code> if none is available. * @exception IllegalArgumentException if <code>c</code> is * <code>null</code>. * * @see java.awt.image.BandedSampleModel * @see java.awt.image.ComponentSampleModel */ public static synchronized Serializer getSerializer(Class c) { if(c == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } // Get the value from the repository. Object value = repository.get(c); // If null, attempt to find a superclass Serializer. if(value == null) { Class theClass = c; while(theClass != java.lang.Object.class) { Class theSuperclass = theClass.getSuperclass(); if(isSupportedClass(theSuperclass)) { Serializer s = getSerializer(theSuperclass); if(s.permitsSubclasses()) { value = s; break; } } theClass = theSuperclass; } } if(value == null && Serializable.class.isAssignableFrom(c)) { value = serializableSerializer; } // Return the highest priority Serializer or null. return value instanceof Vector ? (Serializer)((Vector)value).get(0) : (Serializer)value; } /** * Whether there is currently resident in the repository a * <code>Serializer</code> the <code>getSupportedClass()</code> * method of which returns a value equal to the parameter supplied * to this method according to <code>equals()</code>. * * @param c The class to be tested for compatibility. * @return Whether the specified class is directly supported. * @exception IllegalArgumentException if <code>c</code> is * <code>null</code> */ public static boolean isSupportedClass(Class c) { if(c == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } else if(Serializable.class.isAssignableFrom(c)) { return true; } return repository.containsKey(c); } /** * Returns an array listing all classes and interfaces on which the * <code>isSupportedClass()</code> method of this class may be invoked * and return <code>true</code>. * * @return An array of all supported classes and interfaces. */ public static Class[] getSupportedClasses() { Class[] classes = new Class[repository.size() + 1]; repository.keySet().toArray(classes); classes[classes.length-1] = Serializable.class; return classes; } /** * Determines the <code>Class</code> of which the deserialized form of the * supplied <code>Class</code> will be an instance. Specifically, this * method returns the <code>Class</code> of the <code>Object</code> * returned by invoking <code>getObject()</code> on the * <code>SerializableState</code> returned by <code>getState()</code> * after the state object has been serialized and deserialized. The * returned value will equal the supplied argument unless there is no * <code>Serializer</code> explicitly registered for this class but there * is a <code>Serializer</code> registered for a superclass with a * <code>permitsSubclasses()</code> method that returns * <code>true</code>. * * @param The <code>Class</code> for which the deserialized class type is * requested. * @return The deserialized <code>Class</code> or <code>null</code>. * @exception IllegalArgumentException if <code>c</code> is * <code>null</code> */ public static Class getDeserializedClass(Class c) { if(c == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } Class deserializedClass = null; // Try to find a superclass Serializer. if(isSupportedClass(c)) { deserializedClass = c; } else { Class theClass = c; while(theClass != java.lang.Object.class) { Class theSuperclass = theClass.getSuperclass(); if(isSupportedClass(theSuperclass)) { Serializer s = getSerializer(theSuperclass); if(s.permitsSubclasses()) { deserializedClass = theSuperclass; break; } } theClass = theSuperclass; } } return deserializedClass; } /** * Converts an object into a state-preserving object which may * be serialized. If the class of the object parameter is supported * explicitly, i.e., <code>isSupportedClass(o.getClass())</code> * returns <code>true</code>, then the object will be converted into * a form which may be deserialized into an instance of the same class. * If the class is not supported explicitly but implements one or * more supported interfaces, then it will be converted into a * form which may be deserialized into an instance of an unspecified * class which implements all interfaces which are both implemented by * the class of the object and supported by some <code>Serializer</code> * currently resident in the repository. If the object is * <code>null</code>, the returned <code>SerializableState</code> will * return <code>null</code> from its <code>getObject()</code> method * and <code>java.lang.Object.class</code> from its * <code>getObjectClass()</code> method. * * @param o The object to be converted into a serializable form. * @param h Configuration parameters the exact nature of which is * <code>Serializer</code>-dependent. If <code>null</code>, * reasonable default settings should be used. * @return A serializable form of the supplied object. * @exception IllegalArgumentException if <code>o</code> is * non-<code>null</code> and either * <code>isSupportedClass(o.getClass())</code> returns * <code>false</code>, or <code>o</code> * is not an instance of a class supported by a * <code>Serializer</code> in the repository or which * implements at least one interface supported by some * <code>Serializer</code>s in the repository. */ public static SerializableState getState(Object o, RenderingHints h) { if(o == null) { return NULL_STATE; } Class c = o.getClass(); SerializableState state = null; if(isSupportedClass(c)) { // Found an explicit Serializer. Serializer s = getSerializer(c); state = s.getState(o, h); } else { // Try to find a superclass Serializer. Class theClass = c; while(theClass != java.lang.Object.class) { Class theSuperclass = theClass.getSuperclass(); if(isSupportedClass(theSuperclass)) { Serializer s = getSerializer(theSuperclass); if(s.permitsSubclasses()) { state = s.getState(o, h); break; } } theClass = theSuperclass; } if(state == null) { // Try an interface Serializer. Class[] interfaces = getInterfaces(c); Vector serializers = null; int numInterfaces = (interfaces == null) ? 0: interfaces.length; for(int i = 0; i < numInterfaces; i++) { Class iface = interfaces[i]; if(isSupportedClass(iface)) { if(serializers == null) { serializers = new Vector(); } serializers.add(getSerializer(iface)); } } int numSupportedInterfaces = serializers == null ? 0 : serializers.size(); if(numSupportedInterfaces == 0) { throw new IllegalArgumentException( JaiI18N.getString("SerializerFactory1")); } else if(numSupportedInterfaces == 1) { state = ((Serializer)serializers.get(0)).getState(o, h); } else { Serializer[] sArray = (Serializer[])serializers.toArray(new Serializer[0]); state = new InterfaceState(o, sArray, h); } } } return state; } /** * Retrieve the interfaces implemented by the specified class and all * its superclasses. */ private static Class[] getInterfaces(Class c) { if(c == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } ArrayList interfaces = new ArrayList(); Class laClasse = c; while(!(laClasse == java.lang.Object.class)) { Class[] iFaces = laClasse.getInterfaces(); if(iFaces != null) { for(int i = 0; i < iFaces.length; i++) { interfaces.add(iFaces[i]); } } laClasse = laClasse.getSuperclass(); } return interfaces.size() == 0 ? null : (Class[])interfaces.toArray(new Class[interfaces.size()]); } /** * A convenience wrapper around * <code>getState(Object o,&nbsp;RenderingHints h)</code> with * the <code>RenderingHints</code> parameter <code>h</code> set * to <code>null</code>. */ public static final SerializableState getState(Object o) { return getState(o, null); } } /** * A <code>Serializer</code> for <code>Serializable</code> objects. */ class SerSerializer implements Serializer { SerSerializer() {} public Class getSupportedClass() { return Serializable.class; } public boolean permitsSubclasses() { return true; } public SerializableState getState(Object o, RenderingHints h) { if(o == null) { return SerializerFactory.NULL_STATE; } else if(!(o instanceof Serializable)) { throw new IllegalArgumentException(JaiI18N.getString("SerializerFactory2")); } return new SerState((Serializable)o); } } /** * <code>SerializableState</code> which simply wraps an object that is * already an instance of <code>Serializable</code>. */ class SerState implements SerializableState { private Serializable object; SerState(Serializable object) { if(object == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } this.object = object; } public Class getObjectClass() { return object.getClass(); } public Object getObject() { return object; } }
MarinnaCole/LightZone
lightcrafts/extsrc/com/lightcrafts/mediax/jai/remote/SerializerFactory.java
Java
bsd-3-clause
20,530
package uk.ac.lkl.client.mopix.editor; import uk.ac.lkl.client.Modeller; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.MenuBar; import com.google.gwt.user.client.ui.PopupPanel; public class LabelOperator extends Label { static TPanel parentPanel = null; public LabelOperator() { super(); parentPanel = ((TPanel) this.getParent()); this.sinkEvents(Event.ONDBLCLICK); } public void onBrowserEvent(Event event) { super.onBrowserEvent(event); int type = DOM.eventGetType(event); switch (type) { case Event.ONDBLCLICK: { // createPopUp (); break; } } } protected void createPopUp() { final PopupPanel popupMenu = new PopupPanel(true); popupMenu.setAnimationEnabled(true); { final MenuBar menuBar = new MenuBar(true); menuBar.setAnimationEnabled(true); popupMenu.setWidget(menuBar); // RootPanel.get().add(menuBar, // this.getAbsoluteLeft(),this.getAbsoluteTop()); menuBar.addItem(Modeller.constants.delete(), new Command() { public void execute() { popupMenu.hide(); menuBar.setVisible(false); } }); menuBar.addItem(" ", new Command() { public void execute() { popupMenu.hide(); menuBar.setVisible(false); }; }); popupMenu.show(); popupMenu.setPopupPosition(this.getAbsoluteLeft(), this.getAbsoluteTop()); } } }
ToonTalk/mopix2
MoPiX/src/uk/ac/lkl/client/mopix/editor/LabelOperator.java
Java
bsd-3-clause
1,522
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_22) on Wed Mar 02 16:45:48 EST 2011 --> <TITLE> ReportIndexDaoTest </TITLE> <META NAME="keywords" CONTENT="gov.nih.nci.cabig.caaers.dao.index.ReportIndexDaoTest class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="ReportIndexDaoTest"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ReportIndexDaoTest.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="../../../../../../../gov/nih/nci/cabig/caaers/dao/index/ReportIndexDao.html" title="class in gov.nih.nci.cabig.caaers.dao.index"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../gov/nih/nci/cabig/caaers/dao/index/ReportingPeriodIndexDao.html" title="class in gov.nih.nci.cabig.caaers.dao.index"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?gov/nih/nci/cabig/caaers/dao/index/ReportIndexDaoTest.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ReportIndexDaoTest.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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> gov.nih.nci.cabig.caaers.dao.index</FONT> <BR> Class ReportIndexDaoTest</H2> <PRE> java.lang.Object <IMG SRC="../../../../../../../resources/inherit.gif" ALT="extended by ">junit.framework.Assert <IMG SRC="../../../../../../../resources/inherit.gif" ALT="extended by ">junit.framework.TestCase <IMG SRC="../../../../../../../resources/inherit.gif" ALT="extended by "><B>gov.nih.nci.cabig.caaers.dao.index.ReportIndexDaoTest</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD>junit.framework.Test</DD> </DL> <HR> <DL> <DT><PRE>public class <B>ReportIndexDaoTest</B><DT>extends junit.framework.TestCase</DL> </PRE> <P> ReportIndexDao Tester. <P> <P> <DL> <DT><B>Since:</B></DT> <DD><pre>12/08/2010</pre></DD> <DT><B>Author:</B></DT> <DD>Biju Joseph</DD> </DL> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../../../gov/nih/nci/cabig/caaers/dao/index/ReportIndexDaoTest.html#ReportIndexDaoTest()">ReportIndexDaoTest</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../../gov/nih/nci/cabig/caaers/dao/index/ReportIndexDaoTest.html#setUp()">setUp</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../../gov/nih/nci/cabig/caaers/dao/index/ReportIndexDaoTest.html#testEntityIdColumnName()">testEntityIdColumnName</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../../gov/nih/nci/cabig/caaers/dao/index/ReportIndexDaoTest.html#testIndexTableName()">testIndexTableName</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../../gov/nih/nci/cabig/caaers/dao/index/ReportIndexDaoTest.html#testSequenceName()">testSequenceName</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_junit.framework.TestCase"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class junit.framework.TestCase</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>countTestCases, createResult, getName, run, run, runBare, runTest, setName, tearDown, toString</CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_junit.framework.Assert"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class junit.framework.Assert</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail</CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="ReportIndexDaoTest()"><!-- --></A><H3> ReportIndexDaoTest</H3> <PRE> public <B>ReportIndexDaoTest</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="setUp()"><!-- --></A><H3> setUp</H3> <PRE> protected void <B>setUp</B>() throws java.lang.Exception</PRE> <DL> <DD><DL> <DT><B>Overrides:</B><DD><CODE>setUp</CODE> in class <CODE>junit.framework.TestCase</CODE></DL> </DD> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE></DL> </DD> </DL> <HR> <A NAME="testEntityIdColumnName()"><!-- --></A><H3> testEntityIdColumnName</H3> <PRE> public void <B>testEntityIdColumnName</B>() throws java.lang.Exception</PRE> <DL> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE></DL> </DD> </DL> <HR> <A NAME="testIndexTableName()"><!-- --></A><H3> testIndexTableName</H3> <PRE> public void <B>testIndexTableName</B>() throws java.lang.Exception</PRE> <DL> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE></DL> </DD> </DL> <HR> <A NAME="testSequenceName()"><!-- --></A><H3> testSequenceName</H3> <PRE> public void <B>testSequenceName</B>() throws java.lang.Exception</PRE> <DL> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE></DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <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="navbar_bottom_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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ReportIndexDaoTest.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="../../../../../../../gov/nih/nci/cabig/caaers/dao/index/ReportIndexDao.html" title="class in gov.nih.nci.cabig.caaers.dao.index"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../gov/nih/nci/cabig/caaers/dao/index/ReportingPeriodIndexDao.html" title="class in gov.nih.nci.cabig.caaers.dao.index"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?gov/nih/nci/cabig/caaers/dao/index/ReportIndexDaoTest.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ReportIndexDaoTest.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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
NCIP/caaers
caAERS/software/docs/gov/nih/nci/cabig/caaers/dao/index/ReportIndexDaoTest.html
HTML
bsd-3-clause
14,451
<?php /** * The following variables are available in this template: * - $this: the BootCrudCode object * * @category YupeGiiTemplate * @package yupe * @author Yupe Team <[email protected]> * @license https://github.com/yupe/yupe/blob/master/LICENSE BSD * @link http://yupe.ru */ ?> <?php $nameColumn = $this->guessNameColumn($this->tableSchema->columns); $label = $this->mb_ucfirst($this->mim); $labelIm = $this->mb_ucfirst($this->im); echo <<<EOF <?php /** * Отображение для update: * * @category YupeView * @package yupe * @author Yupe Team <[email protected]> * @license https://github.com/yupe/yupe/blob/master/LICENSE BSD * @link http://yupe.ru **/ \$this->breadcrumbs = array( Yii::app()->getModule('{$this->mid}')->getCategory() => array(), Yii::t('{$this->mid}', '$label') => array('/{$this->mid}/{$this->controller}/index'), \$model->{$nameColumn} => array('/{$this->mid}/{$this->controller}/view', 'id' => \$model->{$this->tableSchema->primaryKey}), Yii::t('{$this->mid}', 'Редактирование'), ); \$this->pageTitle = Yii::t('{$this->mid}', '{$label} - редактирование'); \$this->menu = array( array('icon' => 'fa fa-fw fa-list-alt', 'label' => Yii::t('{$this->mid}', 'Управление {$this->mtvor}'), 'url' => array('/{$this->mid}/{$this->controller}/index')), array('icon' => 'fa fa-fw fa-plus-square', 'label' => Yii::t('{$this->mid}', 'Добавить {$this->vin}'), 'url' => array('/{$this->mid}/{$this->controller}/create')), array('label' => Yii::t('{$this->mid}', '{$labelIm}') . ' «' . mb_substr(\$model->{$this->tableSchema->primaryKey}, 0, 32) . '»'), array('icon' => 'fa fa-fw fa-pencil', 'label' => Yii::t('{$this->mid}', 'Редактирование {$this->rod}'), 'url' => array( '/{$this->mid}/{$this->controller}/update', 'id' => \$model->{$this->tableSchema->primaryKey} )), array('icon' => 'fa fa-fw fa-eye', 'label' => Yii::t('{$this->mid}', 'Просмотреть {$this->vin}'), 'url' => array( '/{$this->mid}/{$this->controller}/view', 'id' => \$model->{$this->tableSchema->primaryKey} )), array('icon' => 'fa fa-fw fa-trash-o', 'label' => Yii::t('{$this->mid}', 'Удалить {$this->vin}'), 'url' => '#', 'linkOptions' => array( 'submit' => array('/{$this->mid}/{$this->controller}/delete', 'id' => \$model->{$this->tableSchema->primaryKey}), 'confirm' => Yii::t('{$this->mid}', 'Вы уверены, что хотите удалить {$this->vin}?'), 'params' => array(Yii::app()->getRequest()->csrfTokenName => Yii::app()->getRequest()->csrfToken), )), ); ?> EOF; ?> <div class="page-header"> <h1> <?php echo "<?php echo Yii::t('{$this->mid}', 'Редактирование') . ' ' . Yii::t('{$this->mid}', '{$this->rod}'); ?>"; ?> <br/> <small>&laquo;<?php echo "<?php echo \$model->{$nameColumn}; ?>"; ?>&raquo;</small> </h1> </div> <?php echo "<?php echo \$this->renderPartial('_form', array('model' => \$model)); ?>"; ?>
otis22/yupe-test
protected/modules/yupe/extensions/yupe/gii/yupe/templates/default/update.php
PHP
bsd-3-clause
3,194
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: Friederike Bock, Daniel Mühlheim * * Version 1.0 * * * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //*************************************************************************************** //This AddTask is supposed to set up the main task //($ALIPHYSICS/PWGGA/GammaConv/AliAnalysisTaskNeutralMesonToPiPlPiMiPiZero.cxx) for //pp together with all supporting classes //*************************************************************************************** //*************************************************************************************** //CutHandler contains all cuts for a certain analysis and trainconfig, //it automatically checks length of cutStrings and takes care of the number of added cuts, //no specification of the variable 'numberOfCuts' needed anymore. //*************************************************************************************** class CutHandlerNeutralCalo{ public: CutHandlerNeutralCalo(Int_t nMax=10){ nCuts=0; nMaxCuts=nMax; validCuts = true; eventCutArray = new TString[nMaxCuts]; clusterCutArray = new TString[nMaxCuts]; pionCutArray = new TString[nMaxCuts]; neutralPionCutArray = new TString[nMaxCuts]; mesonCutArray = new TString[nMaxCuts]; for(Int_t i=0; i<nMaxCuts; i++) {eventCutArray[i] = ""; clusterCutArray[i] = ""; pionCutArray[i] = ""; neutralPionCutArray[i] = ""; mesonCutArray[i] = "";} } void AddCut(TString eventCut, TString clusterCut, TString pionCut, TString neutralPionCut, TString mesonCut){ if(nCuts>=nMaxCuts) {cout << "ERROR in CutHandlerNeutralCalo: Exceeded maximum number of cuts!" << endl; validCuts = false; return;} if( eventCut.Length()!=8 || clusterCut.Length()!=19 || pionCut.Length()!=9 || neutralPionCut.Length()!=16 || mesonCut.Length()!=16 ) {cout << "ERROR in CutHandlerNeutralCalo: Incorrect length of cut string!" << endl; validCuts = false; return;} eventCutArray[nCuts]=eventCut; clusterCutArray[nCuts]=clusterCut; pionCutArray[nCuts]=pionCut; neutralPionCutArray[nCuts]=neutralPionCut; mesonCutArray[nCuts]=mesonCut; nCuts++; return; } Bool_t AreValid(){return validCuts;} Int_t GetNCuts(){if(validCuts) return nCuts; else return 0;} TString GetEventCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return eventCutArray[i]; else{cout << "ERROR in CutHandlerNeutralCalo: GetEventCut wrong index i" << endl;return "";}} TString GetClusterCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return clusterCutArray[i]; else {cout << "ERROR in CutHandlerNeutralCalo: GetClusterCut wrong index i" << endl;return "";}} TString GetPionCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return pionCutArray[i]; else {cout << "ERROR in CutHandlerNeutralCalo: GetPionCut wrong index i" << endl;return "";}} TString GetNeutralPionCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return neutralPionCutArray[i]; else {cout << "ERROR in CutHandlerNeutralCalo: GetNeutralPionCut wrong index i" << endl;return "";}} TString GetMesonCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return mesonCutArray[i]; else {cout << "ERROR in CutHandlerNeutralCalo: GetMesonCut wrong index i" << endl;return "";}} private: Bool_t validCuts; Int_t nCuts; Int_t nMaxCuts; TString* eventCutArray; TString* clusterCutArray; TString* pionCutArray; TString* neutralPionCutArray; TString* mesonCutArray; }; //*************************************************************************************** //main function //*************************************************************************************** void AddTask_GammaConvNeutralMesonPiPlPiMiPiZero_CaloMode_pp( Int_t trainConfig = 1, Bool_t isMC = kFALSE, //run MC Bool_t enableQAMesonTask = kTRUE, //enable QA in AliAnalysisTaskNeutralMesonToPiPlPiMiPiZero TString fileNameInputForWeighting = "MCSpectraInput.root", // path to file for weigting input Bool_t doWeighting = kFALSE, //enable Weighting TString generatorName = "HIJING", TString cutnumberAODBranch = "000000006008400001001500000", Double_t tolerance = -1, TString additionalTrainConfig = "0" // additional counter for trainconfig, this has to be always the last parameter ) { //parse additionalTrainConfig flag TObjArray *rAddConfigArr = additionalTrainConfig.Tokenize("_"); if(rAddConfigArr->GetEntries()<1){cout << "ERROR during parsing of additionalTrainConfig String '" << additionalTrainConfig.Data() << "'" << endl; return;} TObjString* rAdditionalTrainConfig; for(Int_t i = 0; i<rAddConfigArr->GetEntries() ; i++){ if(i==0) rAdditionalTrainConfig = (TObjString*)rAddConfigArr->At(i); else{ TObjString* temp = (TObjString*) rAddConfigArr->At(i); TString tempStr = temp->GetString(); cout << "INFO: nothing to do, no definition available!" << endl; } } TString sAdditionalTrainConfig = rAdditionalTrainConfig->GetString(); if (sAdditionalTrainConfig.Atoi() > 0){ trainConfig = trainConfig + sAdditionalTrainConfig.Atoi(); cout << "INFO: AddTask_GammaConvNeutralMesonPiPlPiMiPiZero_CaloMode_pp running additionalTrainConfig '" << sAdditionalTrainConfig.Atoi() << "', train config: '" << trainConfig << "'" << endl; } Int_t isHeavyIon = 0; Int_t neutralPionMode = 2; // ================== GetAnalysisManager =============================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error(Form("AddTask_GammaConvNeutralMesonPiPlPiMiPiZero_CaloMode_pp_%i",trainConfig), "No analysis manager found."); return ; } // ================== GetInputEventHandler ============================= AliVEventHandler *inputHandler=mgr->GetInputEventHandler(); //========= Add PID Reponse to ANALYSIS manager ==== if(!(AliPIDResponse*)mgr->GetTask("PIDResponseTask")){ gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C"); AddTaskPIDResponse(isMC); } //========= Set Cutnumber for V0Reader ================================ TString cutnumberPhoton = "06000008400100001500000000"; TString cutnumberEvent = "00000003"; TString PionCuts = "000000200"; //Electron Cuts AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); //========= Add V0 Reader to ANALYSIS manager if not yet existent ===== TString V0ReaderName = Form("V0ReaderV1_%s_%s",cutnumberEvent.Data(),cutnumberPhoton.Data()); if( !(AliV0ReaderV1*)mgr->GetTask(V0ReaderName.Data()) ){ AliV0ReaderV1 *fV0ReaderV1 = new AliV0ReaderV1(V0ReaderName.Data()); fV0ReaderV1->SetUseOwnXYZCalculation(kTRUE); fV0ReaderV1->SetCreateAODs(kFALSE);// AOD Output fV0ReaderV1->SetUseAODConversionPhoton(kTRUE); if (!mgr) { Error("AddTask_V0ReaderV1", "No analysis manager found."); return; } AliConvEventCuts *fEventCuts=NULL; if(cutnumberEvent!=""){ fEventCuts= new AliConvEventCuts(cutnumberEvent.Data(),cutnumberEvent.Data()); fEventCuts->SetPreSelectionCutFlag(kTRUE); fEventCuts->SetV0ReaderName(V0ReaderName); if(fEventCuts->InitializeCutsFromCutString(cutnumberEvent.Data())){ fV0ReaderV1->SetEventCuts(fEventCuts); fEventCuts->SetFillCutHistograms("",kTRUE); } } // Set AnalysisCut Number AliConversionPhotonCuts *fCuts=NULL; if(cutnumberPhoton!=""){ fCuts= new AliConversionPhotonCuts(cutnumberPhoton.Data(),cutnumberPhoton.Data()); fCuts->SetPreSelectionCutFlag(kTRUE); fCuts->SetIsHeavyIon(isHeavyIon); fCuts->SetV0ReaderName(V0ReaderName); if(fCuts->InitializeCutsFromCutString(cutnumberPhoton.Data())){ fV0ReaderV1->SetConversionCuts(fCuts); fCuts->SetFillCutHistograms("",kTRUE); } } if(inputHandler->IsA()==AliAODInputHandler::Class()){ // AOD mode fV0ReaderV1->SetDeltaAODBranchName(Form("GammaConv_%s_gamma",cutnumberAODBranch.Data())); } fV0ReaderV1->Init(); AliLog::SetGlobalLogLevel(AliLog::kFatal); //connect input V0Reader mgr->AddTask(fV0ReaderV1); mgr->ConnectInput(fV0ReaderV1,0,cinput); } //================================================ //========= Add Pion Selector ==================== if( !(AliPrimaryPionSelector*)mgr->GetTask("PionSelector") ){ AliPrimaryPionSelector *fPionSelector = new AliPrimaryPionSelector("PionSelector"); AliPrimaryPionCuts *fPionCuts=0; if( PionCuts!=""){ fPionCuts= new AliPrimaryPionCuts(PionCuts.Data(),PionCuts.Data()); if(fPionCuts->InitializeCutsFromCutString(PionCuts.Data())){ fPionSelector->SetPrimaryPionCuts(fPionCuts); fPionCuts->SetFillCutHistograms("",kTRUE); } } fPionSelector->Init(); mgr->AddTask(fPionSelector); AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer(); mgr->ConnectInput (fPionSelector,0,cinput1); } AliAnalysisTaskNeutralMesonToPiPlPiMiPiZero *task=NULL; task= new AliAnalysisTaskNeutralMesonToPiPlPiMiPiZero(Form("GammaConvNeutralMesonPiPlPiMiPiZero_%i_%i",neutralPionMode, trainConfig)); task->SetIsHeavyIon(isHeavyIon); task->SetIsMC(isMC); task->SetV0ReaderName(V0ReaderName); task->SetTolerance(tolerance); CutHandlerNeutralCalo cuts; // 7 TeV // EMCAL modes if( trainConfig == 1 ) { // everything open cuts.AddCut("00000113","1111111067032230000","000010400","0103503000000000","0103503000000000"); } else if( trainConfig == 2 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, min pt charged pi = 100 MeV cuts.AddCut("00000113","1111111067032230000","002010700","0103503000000000","0103503000000000"); } else if( trainConfig == 3 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, ITS dEdx = \pm 5 sigma, min pt charged pi = 100 MeV cuts.AddCut("00000113","1111111067032230000","002013700","0103503000000000","0103503000000000"); } else if( trainConfig == 4 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, ITS dEdx = \pm 4 sigma, min pt charged pi = 100 MeV cuts.AddCut("00000113","1111111067032230000","002016700","0103503000000000","0103503000000000"); } else if( trainConfig == 5 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, ITS dEdx = \pm 4 sigma, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","1111111067032230000","002016700","0103503400000000","0103503000000000"); } else if( trainConfig == 6 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, ITS dEdx = \pm 4 sigma, min pt charged pi = 100 MeV // closing neural pion cuts, 0.11 < M_gamma,gamma < 0.145 cuts.AddCut("00000113","1111111067032230000","002016700","0103503200000000","0103503000000000"); } else if( trainConfig == 7 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, ITS dEdx = \pm 4 sigma, min pt charged pi = 100 MeV // closing neural pion cuts, 0.12 < M_gamma,gamma < 0.145 cuts.AddCut("00000113","1111111067032230000","002016700","0103503300000000","0103503000000000"); } else if( trainConfig == 8 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, ITS dEdx = \pm 5 sigma, min pt charged pi = 100 MeV // closing neural pion cuts, 0.12 < M_gamma,gamma < 0.145 cuts.AddCut("00000113","1111111067032230000","002013700","0103503300000000","0103503000000000"); } else if( trainConfig == 9 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.65, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","1111111067032230000","002010706","0103503400000000","0103503000000000"); } else if( trainConfig == 10 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.6, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","1111111067032230000","002010703","0103503400000000","0103503000000000"); } else if( trainConfig == 11 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.5, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","1111111067032230000","002010705","0103503400000000","0103503000000000"); } else if( trainConfig == 20 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.65, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","1111111067032230000","002010706","0103503400000000","0103503000000000"); } else if( trainConfig == 21 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.65, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","1111111067032230000","002010706","0103503400000000","0103503000000000"); } else if( trainConfig == 22 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.65, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","1111111067032230000","002010706","0103503400000000","0103503000000000"); } else if( trainConfig == 23 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.65, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","1111111067032230000","002010706","0103503400000000","0103503000000000"); } else if( trainConfig == 24 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.65, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","1111111067032230000","002010706","0103503400000000","0103503000000000"); } else if( trainConfig == 25 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.65, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","1111111067032230000","002010706","0103503400000000","0103503000000000"); } else if( trainConfig == 26 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.65, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","1111111067032230000","002010706","0103503400000000","0103503000000000"); } else if( trainConfig == 27 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.65, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","1111111067032230000","002010706","0103503400000000","0103503000000000"); // PHOS modes } else if( trainConfig == 31 ) { // everything open cuts.AddCut("00000113","2444400030022000000","000010400","0103503000000000","0103503000000000"); } else if( trainConfig == 32 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, min pt charged pi = 100 MeV cuts.AddCut("00000113","2444400030022000000","002010700","0103503000000000","0103503000000000"); } else if( trainConfig == 33 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, ITS dEdx = \pm 5 sigma, min pt charged pi = 100 MeV cuts.AddCut("00000113","2444400030022000000","002013700","0103503000000000","0103503000000000"); } else if( trainConfig == 34 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, ITS dEdx = \pm 4 sigma, min pt charged pi = 100 MeV cuts.AddCut("00000113","2444400030022000000","002016700","0103503000000000","0103503000000000"); } else if( trainConfig == 35 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, ITS dEdx = \pm 4 sigma, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","2444400030022000000","002016700","0103503400000000","0103503000000000"); } else if( trainConfig == 36 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, ITS dEdx = \pm 4 sigma, min pt charged pi = 100 MeV // closing neural pion cuts, 0.11 < M_gamma,gamma < 0.145 cuts.AddCut("00000113","2444400030022000000","002016700","0103503200000000","0103503000000000"); } else if( trainConfig == 37 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, ITS dEdx = \pm 4 sigma, min pt charged pi = 100 MeV // closing neural pion cuts, 0.12 < M_gamma,gamma < 0.145 cuts.AddCut("00000113","2444400030022000000","002016700","0103503300000000","0103503000000000"); } else if( trainConfig == 38 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, ITS dEdx = \pm 5 sigma, min pt charged pi = 100 MeV // closing neural pion cuts, 0.12 < M_gamma,gamma < 0.145 cuts.AddCut("00000113","2444400030022000000","002013700","0103503300000000","0103503000000000"); } else if( trainConfig == 39 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.65, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00000113","2444400030022000000","002010706","0103503400000000","0103503000000000"); //8 TeV } else if( trainConfig == 101 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.65, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00010113","1111111063032230000","002010706","0163103400000010","0163503000000000"); cuts.AddCut("00052113","1111111063032230000","002010706","0163103400000010","0163503000000000"); cuts.AddCut("00081113","1111111063032230000","002010706","0163103400000010","0163503000000000"); } else if( trainConfig == 102 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.65/0.7/0.75, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00010113","1111111063032230000","002010706","0163103400000010","0163503000000000"); cuts.AddCut("00010113","1111111063032230000","002010707","0163103400000010","0163503000000000"); cuts.AddCut("00010113","1111111063032230000","002010702","0163103400000010","0163503000000000"); } else if( trainConfig == 103 ) { // closing charged pion cuts, minimum TPC cluster = 80, TPC dEdx pi = \pm 3 sigma, pi+pi- mass Cut at 0.65/0.7/0.75, min pt charged pi = 100 MeV // closing neural pion cuts, 0.1 < M_gamma,gamma < 0.15 cuts.AddCut("00052113","1111111063032230000","002010706","0163103400000010","0163503000000000"); cuts.AddCut("00052113","1111111063032230000","002010707","0163103400000010","0163503000000000"); cuts.AddCut("00052113","1111111063032230000","002010702","0163103400000010","0163503000000000"); } else { Error(Form("GammaConvNeutralMeson_CaloMode_%i",trainConfig), "wrong trainConfig variable no cuts have been specified for the configuration"); return; } if(!cuts.AreValid()){ cout << "\n\n****************************************************" << endl; cout << "ERROR: No valid cuts stored in CutHandlerNeutralCalo! Returning..." << endl; cout << "****************************************************\n\n" << endl; return; } Int_t numberOfCuts = cuts.GetNCuts(); TList *EventCutList = new TList(); TList *ClusterCutList = new TList(); TList *NeutralPionCutList = new TList(); TList *MesonCutList = new TList(); TList *PionCutList = new TList(); TList *HeaderList = new TList(); TObjString *Header1 = new TObjString("pi0_1"); HeaderList->Add(Header1); TObjString *Header3 = new TObjString("eta_2"); HeaderList->Add(Header3); EventCutList->SetOwner(kTRUE); AliConvEventCuts **analysisEventCuts = new AliConvEventCuts*[numberOfCuts]; ClusterCutList->SetOwner(kTRUE); AliCaloPhotonCuts **analysisClusterCuts = new AliCaloPhotonCuts*[numberOfCuts]; NeutralPionCutList->SetOwner(kTRUE); AliConversionMesonCuts **analysisNeutralPionCuts = new AliConversionMesonCuts*[numberOfCuts]; MesonCutList->SetOwner(kTRUE); AliConversionMesonCuts **analysisMesonCuts = new AliConversionMesonCuts*[numberOfCuts]; PionCutList->SetOwner(kTRUE); AliPrimaryPionCuts **analysisPionCuts = new AliPrimaryPionCuts*[numberOfCuts]; for(Int_t i = 0; i<numberOfCuts; i++){ //create AliCaloTrackMatcher instance, if there is none present TString caloCutPos = cuts.GetClusterCut(i); caloCutPos.Resize(1); TString TrackMatcherName = Form("CaloTrackMatcher_%s",caloCutPos.Data()); if( !(AliCaloTrackMatcher*)mgr->GetTask(TrackMatcherName.Data()) ){ AliCaloTrackMatcher* fTrackMatcher = new AliCaloTrackMatcher(TrackMatcherName.Data(),caloCutPos.Atoi()); fTrackMatcher->SetV0ReaderName(V0ReaderName); mgr->AddTask(fTrackMatcher); mgr->ConnectInput(fTrackMatcher,0,cinput); } analysisEventCuts[i] = new AliConvEventCuts(); analysisEventCuts[i]->SetV0ReaderName(V0ReaderName); analysisEventCuts[i]->InitializeCutsFromCutString((cuts.GetEventCut(i)).Data()); EventCutList->Add(analysisEventCuts[i]); analysisEventCuts[i]->SetFillCutHistograms("",kFALSE); analysisClusterCuts[i] = new AliCaloPhotonCuts(); analysisClusterCuts[i]->SetV0ReaderName(V0ReaderName); analysisClusterCuts[i]->SetCaloTrackMatcherName(TrackMatcherName); if( ! analysisClusterCuts[i]->InitializeCutsFromCutString((cuts.GetClusterCut(i)).Data()) ) { cout<<"ERROR: analysisClusterCuts [" <<i<<"]"<<endl; return 0; } else { ClusterCutList->Add(analysisClusterCuts[i]); analysisClusterCuts[i]->SetFillCutHistograms(""); } analysisNeutralPionCuts[i] = new AliConversionMesonCuts(); if( ! analysisNeutralPionCuts[i]->InitializeCutsFromCutString((cuts.GetNeutralPionCut(i)).Data()) ) { cout<<"ERROR: analysisMesonCuts [ " <<i<<" ] "<<endl; return 0; } else { NeutralPionCutList->Add(analysisNeutralPionCuts[i]); analysisNeutralPionCuts[i]->SetFillCutHistograms(""); } analysisMesonCuts[i] = new AliConversionMesonCuts(); if( ! analysisMesonCuts[i]->InitializeCutsFromCutString((cuts.GetMesonCut(i)).Data()) ) { cout<<"ERROR: analysisMesonCuts [ " <<i<<" ] "<<endl; return 0; } else { MesonCutList->Add(analysisMesonCuts[i]); analysisMesonCuts[i]->SetFillCutHistograms(""); } analysisEventCuts[i]->SetAcceptedHeader(HeaderList); TString cutName( Form("%s_%s_%s_%s_%s",(cuts.GetEventCut(i)).Data(), (cuts.GetClusterCut(i)).Data(),(cuts.GetPionCut(i)).Data(),(cuts.GetNeutralPionCut(i)).Data(), (cuts.GetMesonCut(i)).Data() ) ); analysisPionCuts[i] = new AliPrimaryPionCuts(); if( !analysisPionCuts[i]->InitializeCutsFromCutString((cuts.GetPionCut(i)).Data())) { cout<< "ERROR: analysisPionCuts [ " <<i<<" ] "<<endl; return 0; } else { PionCutList->Add(analysisPionCuts[i]); analysisPionCuts[i]->SetFillCutHistograms("",kFALSE,cutName); } } task->SetNeutralPionMode(neutralPionMode); task->SetEventCutList(numberOfCuts,EventCutList); task->SetClusterCutList(ClusterCutList); task->SetNeutralPionCutList(NeutralPionCutList); task->SetMesonCutList(MesonCutList); task->SetPionCutList(PionCutList); task->SetMoveParticleAccordingToVertex(kTRUE); if(enableQAMesonTask) task->SetDoMesonQA(kTRUE); //connect containers AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("GammaConvNeutralMesonPiPlPiMiPiZero_%i_%i",neutralPionMode, trainConfig), TList::Class(), AliAnalysisManager::kOutputContainer,Form("GammaConvNeutralMesonPiPlPiMiPiZero_%i_%i.root",neutralPionMode, trainConfig)); mgr->AddTask(task); mgr->ConnectInput(task,0,cinput); mgr->ConnectOutput(task,1,coutput); return; }
pbatzing/AliPhysics
PWGGA/GammaConv/macros/AddTask_GammaConvNeutralMesonPiPlPiMiPiZero_CaloMode_pp.C
C++
bsd-3-clause
25,686
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.net; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * This is a base class for DNS to Switch mappings. <p/> It is not mandatory to * derive {@link DNSToSwitchMapping} implementations from it, but it is strongly * recommended, as it makes it easy for the Hadoop developers to add new methods * to this base class that are automatically picked up by all implementations. * <p/> * * This class does not extend the <code>Configured</code> * base class, and should not be changed to do so, as it causes problems * for subclasses. The constructor of the <code>Configured</code> calls * the {@link #setConf(Configuration)} method, which will call into the * subclasses before they have been fully constructed. * */ @InterfaceAudience.Public @InterfaceStability.Evolving public abstract class AbstractDNSToSwitchMapping implements DNSToSwitchMapping, Configurable { private Configuration conf; /** * Create an unconfigured instance */ protected AbstractDNSToSwitchMapping() { } /** * Create an instance, caching the configuration file. * This constructor does not call {@link #setConf(Configuration)}; if * a subclass extracts information in that method, it must call it explicitly. * @param conf the configuration */ protected AbstractDNSToSwitchMapping(Configuration conf) { this.conf = conf; } @Override public Configuration getConf() { return conf; } @Override public void setConf(Configuration conf) { this.conf = conf; } /** * Predicate that indicates that the switch mapping is known to be * single-switch. The base class returns false: it assumes all mappings are * multi-rack. Subclasses may override this with methods that are more aware * of their topologies. * * <p/> * * This method is used when parts of Hadoop need know whether to apply * single rack vs multi-rack policies, such as during block placement. * Such algorithms behave differently if they are on multi-switch systems. * </p> * * @return true if the mapping thinks that it is on a single switch */ public boolean isSingleSwitch() { return false; } /** * Get a copy of the map (for diagnostics) * @return a clone of the map or null for none known */ public Map<String, String> getSwitchMap() { return null; } /** * Generate a string listing the switch mapping implementation, * the mapping for every known node and the number of nodes and * unique switches known about -each entry to a separate line. * @return a string that can be presented to the ops team or used in * debug messages. */ public String dumpTopology() { Map<String, String> rack = getSwitchMap(); StringBuilder builder = new StringBuilder(); builder.append("Mapping: ").append(toString()).append("\n"); if (rack != null) { builder.append("Map:\n"); Set<String> switches = new HashSet<String>(); for (Map.Entry<String, String> entry : rack.entrySet()) { builder.append(" ") .append(entry.getKey()) .append(" -> ") .append(entry.getValue()) .append("\n"); switches.add(entry.getValue()); } builder.append("Nodes: ").append(rack.size()).append("\n"); builder.append("Switches: ").append(switches.size()).append("\n"); } else { builder.append("No topology information"); } return builder.toString(); } protected boolean isSingleSwitchByScriptPolicy() { return conf != null && conf.get(CommonConfigurationKeys.NET_TOPOLOGY_SCRIPT_FILE_NAME_KEY) == null; } /** * Query for a {@link DNSToSwitchMapping} instance being on a single * switch. * <p/> * This predicate simply assumes that all mappings not derived from * this class are multi-switch. * @param mapping the mapping to query * @return true if the base class says it is single switch, or the mapping * is not derived from this class. */ public static boolean isMappingSingleSwitch(DNSToSwitchMapping mapping) { return mapping != null && mapping instanceof AbstractDNSToSwitchMapping && ((AbstractDNSToSwitchMapping) mapping).isSingleSwitch(); } }
linpawslitap/mds_scaling
hadoop/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/net/AbstractDNSToSwitchMapping.java
Java
bsd-3-clause
5,362
from __future__ import absolute_import, unicode_literals, print_function from io import BytesIO # Yes, there is an io module in Python 2 import cgi import codecs import gzip import operator import os import re import warnings try: from collections import OrderedDict except ImportError: # pragma: no cover # some old python 2.6 thing then, eh? from ordereddict import OrderedDict import sys if sys.version_info >= (3,): # pragma: no cover # As in, Python 3 from io import StringIO from urllib.request import urlopen from urllib.parse import urljoin STR_TYPE = str else: # Python 2 try: from cStringIO import StringIO except ImportError: # pragma: no cover from StringIO import StringIO StringIO = StringIO # shut up pyflakes from urllib2 import urlopen from urlparse import urljoin STR_TYPE = basestring import cssutils from lxml import etree from lxml.cssselect import CSSSelector from premailer.merge_style import merge_styles, csstext_to_pairs from premailer.cache import function_cache __all__ = ['PremailerError', 'Premailer', 'transform'] class PremailerError(Exception): pass class ExternalNotFoundError(ValueError): pass def make_important(bulk): """makes every property in a string !important. """ return ';'.join('%s !important' % p if not p.endswith('!important') else p for p in bulk.split(';')) def get_or_create_head(root): """Ensures that `root` contains a <head> element and returns it. """ head = CSSSelector('head')(root) if not head: head = etree.Element('head') body = CSSSelector('body')(root)[0] body.getparent().insert(0, head) return head else: return head[0] @function_cache() def _cache_parse_css_string(css_body, validate=True): """ This function will cache the result from cssutils It is a big gain when number of rules is big Maximum cache entries are 1000. This is mainly for protecting memory leak in case something gone wild. Be aware that you can turn the cache off in Premailer Args: css_body(str): css rules in string format validate(bool): if cssutils should validate Returns: cssutils.css.cssstylesheet.CSSStyleSheet """ return cssutils.parseString(css_body, validate=validate) _element_selector_regex = re.compile(r'(^|\s)\w') _cdata_regex = re.compile(r'\<\!\[CDATA\[(.*?)\]\]\>', re.DOTALL) _importants = re.compile('\s*!important') # These selectors don't apply to all elements. Rather, they specify # which elements to apply to. FILTER_PSEUDOSELECTORS = [':last-child', ':first-child', 'nth-child'] class Premailer(object): attribute_name = 'data-premailer' def __init__(self, html, base_url=None, preserve_internal_links=False, preserve_inline_attachments=True, exclude_pseudoclasses=True, keep_style_tags=False, include_star_selectors=False, remove_classes=True, strip_important=True, external_styles=None, css_text=None, method="html", base_path=None, disable_basic_attributes=None, disable_validation=False, cache_css_parsing=True): self.html = html self.base_url = base_url self.preserve_internal_links = preserve_internal_links self.preserve_inline_attachments = preserve_inline_attachments self.exclude_pseudoclasses = exclude_pseudoclasses # whether to delete the <style> tag once it's been processed # this will always preserve the original css self.keep_style_tags = keep_style_tags self.remove_classes = remove_classes # whether to process or ignore selectors like '* { foo:bar; }' self.include_star_selectors = include_star_selectors if isinstance(external_styles, STR_TYPE): external_styles = [external_styles] self.external_styles = external_styles if isinstance(css_text, STR_TYPE): css_text = [css_text] self.css_text = css_text self.strip_important = strip_important self.method = method self.base_path = base_path if disable_basic_attributes is None: disable_basic_attributes = [] self.disable_basic_attributes = disable_basic_attributes self.disable_validation = disable_validation self.cache_css_parsing = cache_css_parsing def _parse_css_string(self, css_body, validate=True): if self.cache_css_parsing: return _cache_parse_css_string(css_body, validate=validate) return cssutils.parseString(css_body, validate=validate) def _parse_style_rules(self, css_body, ruleset_index): """Returns a list of rules to apply to this doc and a list of rules that won't be used because e.g. they are pseudoclasses. Rules look like: (specificity, selector, bulk) for example: ((0, 1, 0, 0, 0), u'.makeblue', u'color:blue'). The bulk of the rule should not end in a semicolon. """ def join_css_properties(properties): """ Accepts a list of cssutils Property objects and returns a semicolon delimitted string like 'color: red; font-size: 12px' """ return ';'.join( u'{0}:{1}'.format(prop.name, prop.value) for prop in properties ) leftover = [] rules = [] # empty string if not css_body: return rules, leftover sheet = self._parse_css_string( css_body, validate=not self.disable_validation ) for rule in sheet: # handle media rule if rule.type == rule.MEDIA_RULE: leftover.append(rule) continue # only proceed for things we recognize if rule.type != rule.STYLE_RULE: continue # normal means it doesn't have "!important" normal_properties = [ prop for prop in rule.style.getProperties() if prop.priority != 'important' ] important_properties = [ prop for prop in rule.style.getProperties() if prop.priority == 'important' ] # Create three strings that we can use to add to the `rules` # list later as ready blocks of css. bulk_normal = join_css_properties(normal_properties) bulk_important = join_css_properties(important_properties) bulk_all = join_css_properties( normal_properties + important_properties ) selectors = ( x.strip() for x in rule.selectorText.split(',') if x.strip() and not x.strip().startswith('@') ) for selector in selectors: if (':' in selector and self.exclude_pseudoclasses and ':' + selector.split(':', 1)[1] not in FILTER_PSEUDOSELECTORS): # a pseudoclass leftover.append((selector, bulk_all)) continue elif '*' in selector and not self.include_star_selectors: continue # Crudely calculate specificity id_count = selector.count('#') class_count = selector.count('.') element_count = len(_element_selector_regex.findall(selector)) # Within one rule individual properties have different # priority depending on !important. # So we split each rule into two: one that includes all # the !important declarations and another that doesn't. for is_important, bulk in ( (1, bulk_important), (0, bulk_normal) ): if not bulk: # don't bother adding empty css rules continue specificity = ( is_important, id_count, class_count, element_count, ruleset_index, len(rules) # this is the rule's index number ) rules.append((specificity, selector, bulk)) return rules, leftover def transform(self, pretty_print=True, **kwargs): """change the self.html and return it with CSS turned into style attributes. """ if hasattr(self.html, "getroottree"): # skip the next bit root = self.html.getroottree() page = root tree = root else: if self.method == 'xml': parser = etree.XMLParser( ns_clean=False, resolve_entities=False ) else: parser = etree.HTMLParser() stripped = self.html.strip() tree = etree.fromstring(stripped, parser).getroottree() page = tree.getroot() # lxml inserts a doctype if none exists, so only include it in # the root if it was in the original html. root = tree if stripped.startswith(tree.docinfo.doctype) else page assert page is not None head = get_or_create_head(tree) # # style selectors # rules = [] index = 0 for element in CSSSelector('style,link[rel~=stylesheet]')(page): # If we have a media attribute whose value is anything other than # 'screen', ignore the ruleset. media = element.attrib.get('media') if media and media != 'screen': continue data_attribute = element.attrib.get(self.attribute_name) if data_attribute: if data_attribute == 'ignore': del element.attrib[self.attribute_name] continue else: warnings.warn( 'Unrecognized %s attribute (%r)' % ( self.attribute_name, data_attribute, ) ) is_style = element.tag == 'style' if is_style: css_body = element.text else: href = element.attrib.get('href') css_body = self._load_external(href) these_rules, these_leftover = self._parse_style_rules( css_body, index ) index += 1 rules.extend(these_rules) parent_of_element = element.getparent() if these_leftover or self.keep_style_tags: if is_style: style = element else: style = etree.Element('style') style.attrib['type'] = 'text/css' if self.keep_style_tags: style.text = css_body else: style.text = self._css_rules_to_string(these_leftover) if self.method == 'xml': style.text = etree.CDATA(style.text) if not is_style: element.addprevious(style) parent_of_element.remove(element) elif not self.keep_style_tags or not is_style: parent_of_element.remove(element) # external style files if self.external_styles: for stylefile in self.external_styles: css_body = self._load_external(stylefile) self._process_css_text(css_body, index, rules, head) index += 1 # css text if self.css_text: for css_body in self.css_text: self._process_css_text(css_body, index, rules, head) index += 1 # rules is a tuple of (specificity, selector, styles), where # specificity is a tuple ordered such that more specific # rules sort larger. rules.sort(key=operator.itemgetter(0)) # collecting all elements that we need to apply rules on # id is unique for the lifetime of the object # and lxml should give us the same everytime during this run # item id -> {item: item, classes: [], style: []} elements = {} for _, selector, style in rules: new_selector = selector class_ = '' if ':' in selector: new_selector, class_ = re.split(':', selector, 1) class_ = ':%s' % class_ # Keep filter-type selectors untouched. if class_ in FILTER_PSEUDOSELECTORS: class_ = '' else: selector = new_selector sel = CSSSelector(selector) items = sel(page) if len(items): # same so process it first processed_style = csstext_to_pairs(style) for item in items: item_id = id(item) if item_id not in elements: elements[item_id] = { 'item': item, 'classes': [], 'style': [], } elements[item_id]['style'].append(processed_style) elements[item_id]['classes'].append(class_) # Now apply inline style # merge style only once for each element # crucial when you have a lot of pseudo/classes # and a long list of elements for _, element in elements.items(): final_style = merge_styles(element['item'].attrib.get('style', ''), element['style'], element['classes']) element['item'].attrib['style'] = final_style self._style_to_basic_html_attributes( element['item'], final_style, force=True ) if self.remove_classes: # now we can delete all 'class' attributes for item in page.xpath('//@class'): parent = item.getparent() del parent.attrib['class'] # # URLs # if self.base_url: if not self.base_url.endswith('/'): self.base_url += '/' for attr in ('href', 'src'): for item in page.xpath("//@%s" % attr): parent = item.getparent() if ( attr == 'href' and self.preserve_internal_links and parent.attrib[attr].startswith('#') ): continue if ( attr == 'src' and self.preserve_inline_attachments and parent.attrib[attr].startswith('cid:') ): continue parent.attrib[attr] = urljoin( self.base_url, parent.attrib[attr].lstrip('/') ) if hasattr(self.html, "getroottree"): return root else: kwargs.setdefault('method', self.method) kwargs.setdefault('pretty_print', pretty_print) kwargs.setdefault('encoding', 'utf-8') # As Ken Thompson intended out = etree.tostring(root, **kwargs).decode(kwargs['encoding']) if self.method == 'xml': out = _cdata_regex.sub( lambda m: '/*<![CDATA[*/%s/*]]>*/' % m.group(1), out ) if self.strip_important: out = _importants.sub('', out) return out def _load_external_url(self, url): r = urlopen(url) _, params = cgi.parse_header(r.headers.get('Content-Type', '')) encoding = params.get('charset', 'utf-8') if 'gzip' in r.info().get('Content-Encoding', ''): buf = BytesIO(r.read()) f = gzip.GzipFile(fileobj=buf) out = f.read().decode(encoding) else: out = r.read().decode(encoding) return out def _load_external(self, url): """loads an external stylesheet from a remote url or local path """ if url.startswith('//'): # then we have to rely on the base_url if self.base_url and 'https://' in self.base_url: url = 'https:' + url else: url = 'http:' + url if url.startswith('http://') or url.startswith('https://'): css_body = self._load_external_url(url) else: stylefile = url if not os.path.isabs(stylefile): stylefile = os.path.abspath( os.path.join(self.base_path or '', stylefile) ) if os.path.exists(stylefile): with codecs.open(stylefile, encoding='utf-8') as f: css_body = f.read() elif self.base_url: url = urljoin(self.base_url, url) return self._load_external(url) else: raise ExternalNotFoundError(stylefile) return css_body def _style_to_basic_html_attributes(self, element, style_content, force=False): """given an element and styles like 'background-color:red; font-family:Arial' turn some of that into HTML attributes. like 'bgcolor', etc. Note, the style_content can contain pseudoclasses like: '{color:red; border:1px solid green} :visited{border:1px solid green}' """ if ( style_content.count('}') and style_content.count('{') == style_content.count('}') ): style_content = style_content.split('}')[0][1:] attributes = OrderedDict() for key, value in [x.split(':') for x in style_content.split(';') if len(x.split(':')) == 2]: key = key.strip() if key == 'text-align': attributes['align'] = value.strip() elif key == 'vertical-align': attributes['valign'] = value.strip() elif key == 'background-color': attributes['bgcolor'] = value.strip() elif key == 'width' or key == 'height': value = value.strip() if value.endswith('px'): value = value[:-2] attributes[key] = value for key, value in attributes.items(): if ( key in element.attrib and not force or key in self.disable_basic_attributes ): # already set, don't dare to overwrite continue element.attrib[key] = value def _css_rules_to_string(self, rules): """given a list of css rules returns a css string """ lines = [] for item in rules: if isinstance(item, tuple): k, v = item lines.append('%s {%s}' % (k, make_important(v))) # media rule else: for rule in item.cssRules: if isinstance(rule, cssutils.css.csscomment.CSSComment): continue for key in rule.style.keys(): rule.style[key] = ( rule.style.getPropertyValue(key, False), '!important' ) lines.append(item.cssText) return '\n'.join(lines) def _process_css_text(self, css_text, index, rules, head): """processes the given css_text by adding rules that can be in-lined to the given rules list and adding any that cannot be in-lined to the given `<head>` element. """ these_rules, these_leftover = self._parse_style_rules(css_text, index) rules.extend(these_rules) if these_leftover or self.keep_style_tags: style = etree.Element('style') style.attrib['type'] = 'text/css' if self.keep_style_tags: style.text = css_text else: style.text = self._css_rules_to_string(these_leftover) head.append(style) def transform(html, base_url=None): return Premailer(html, base_url=base_url).transform() if __name__ == '__main__': # pragma: no cover html = """<html> <head> <title>Test</title> <style> h1, h2 { color:red; } strong { text-decoration:none } p { font-size:2px } p.footer { font-size: 1px} </style> </head> <body> <h1>Hi!</h1> <p><strong>Yes!</strong></p> <p class="footer" style="color:red">Feetnuts</p> </body> </html>""" p = Premailer(html) print (p.transform())
kengruven/premailer
premailer/premailer.py
Python
bsd-3-clause
21,468
import traceback from lektor.types import Type from lektor.environment import Expression, FormatExpression, PRIMARY_ALT from lektor.i18n import get_i18n_block def _reflow_and_split_labels(labels): rv = [] for lang, string in labels.iteritems(): for idx, item in enumerate(string.split(',')): try: d = rv[idx] except LookupError: d = {} rv.append(d) d[lang] = item.strip() return rv def _parse_choices(options): s = options.get('choices') if not s: return None choices = [] items = s.split(',') user_labels = get_i18n_block(options, 'choice_labels') implied_labels = [] for item in items: if '=' in item: choice, value = item.split('=', 1) choice = choice.strip() if choice.isdigit(): choice = int(choice) implied_labels.append(value.strip()) choices.append(choice) else: choices.append(item.strip()) implied_labels.append(item.strip()) if user_labels: rv = list(zip(choices, _reflow_and_split_labels(user_labels))) else: rv = [(key, {'en': label}) for key, label in zip(choices, implied_labels)] return rv class ChoiceSource(object): def __init__(self, env, options): source = options.get('source') if source is not None: self.source = Expression(env, source) self.choices = None item_key = options.get('item_key') or '{{ this._id }}' item_label = options.get('item_label') else: self.source = None self.choices = _parse_choices(options) item_key = options.get('item_key') or '{{ this.0 }}' item_label = options.get('item_label') self.item_key = FormatExpression(env, item_key) if item_label is not None: item_label = FormatExpression(env, item_label) self.item_label = item_label @property def has_choices(self): return self.source is not None or self.choices is not None def iter_choices(self, pad, record=None, alt=PRIMARY_ALT): values = {} if record is not None: values['record'] = record if self.choices is not None: iterable = self.choices else: try: iterable = self.source.evaluate(pad, alt=alt, values=values) except Exception: traceback.print_exc() iterable = () for item in iterable or (): key = self.item_key.evaluate(pad, this=item, alt=alt, values=values) # If there is a label expression, use it. Since in that case # we only have one language to fill in, we fill it in for the # default language if self.item_label is not None: label = { 'en': self.item_label.evaluate(pad, this=item, alt=alt, values=values) } # Otherwise we create a proper internationalized key out of # our target label else: if isinstance(item, (tuple, list)) and len(item) == 2: label = item[1] elif hasattr(item, 'get_record_label_i18n'): label = item.get_record_label_i18n() else: label = {'en': item['_id']} yield key, label class MultiType(Type): def __init__(self, env, options): Type.__init__(self, env, options) self.source = ChoiceSource(env, options) def get_labels(self, pad, record=None, alt=PRIMARY_ALT): return dict(self.source.iter_choices(pad, record, alt)) def to_json(self, pad, record=None, alt=PRIMARY_ALT): rv = Type.to_json(self, pad, record, alt) if self.source.has_choices: rv['choices'] = list(self.source.iter_choices(pad, record, alt)) return rv class SelectType(MultiType): def value_from_raw(self, raw): if raw.value is None: return raw.missing_value('Missing select value') return raw.value class CheckboxesType(MultiType): def value_from_raw(self, raw): rv = [x.strip() for x in (raw.value or '').split(',')] if rv == ['']: rv = [] return rv
lektor/lektor-archive
lektor/types/multi.py
Python
bsd-3-clause
4,506
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head><meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>WSConstants xref</title> <link type="text/css" rel="stylesheet" href="../../../../../../stylesheet.css" /> </head> <body> <div id="overview"><a href="../../../../../../../apidocs/com/ericsson/research/transport/ws/spi/WSConstants.html">View Javadoc</a></div><pre> <a class="jxr_linenumber" name="L1" href="#L1">1</a> <strong class="jxr_keyword">package</strong> com.ericsson.research.transport.ws.spi; <a class="jxr_linenumber" name="L2" href="#L2">2</a> <a class="jxr_linenumber" name="L3" href="#L3">3</a> <em class="jxr_comment">/*</em> <a class="jxr_linenumber" name="L4" href="#L4">4</a> <em class="jxr_comment"> * ##_BEGIN_LICENSE_##</em> <a class="jxr_linenumber" name="L5" href="#L5">5</a> <em class="jxr_comment"> * Transport Abstraction Package (trap)</em> <a class="jxr_linenumber" name="L6" href="#L6">6</a> <em class="jxr_comment"> * ----------</em> <a class="jxr_linenumber" name="L7" href="#L7">7</a> <em class="jxr_comment"> * Copyright (C) 2014 Ericsson AB</em> <a class="jxr_linenumber" name="L8" href="#L8">8</a> <em class="jxr_comment"> * ----------</em> <a class="jxr_linenumber" name="L9" href="#L9">9</a> <em class="jxr_comment"> * Redistribution and use in source and binary forms, with or without modification,</em> <a class="jxr_linenumber" name="L10" href="#L10">10</a> <em class="jxr_comment"> * are permitted provided that the following conditions are met:</em> <a class="jxr_linenumber" name="L11" href="#L11">11</a> <em class="jxr_comment"> * </em> <a class="jxr_linenumber" name="L12" href="#L12">12</a> <em class="jxr_comment"> * 1. Redistributions of source code must retain the above copyright notice, this</em> <a class="jxr_linenumber" name="L13" href="#L13">13</a> <em class="jxr_comment"> * list of conditions and the following disclaimer.</em> <a class="jxr_linenumber" name="L14" href="#L14">14</a> <em class="jxr_comment"> * </em> <a class="jxr_linenumber" name="L15" href="#L15">15</a> <em class="jxr_comment"> * 2. Redistributions in binary form must reproduce the above copyright notice,</em> <a class="jxr_linenumber" name="L16" href="#L16">16</a> <em class="jxr_comment"> * this list of conditions and the following disclaimer in the documentation</em> <a class="jxr_linenumber" name="L17" href="#L17">17</a> <em class="jxr_comment"> * and/or other materials provided with the distribution.</em> <a class="jxr_linenumber" name="L18" href="#L18">18</a> <em class="jxr_comment"> * </em> <a class="jxr_linenumber" name="L19" href="#L19">19</a> <em class="jxr_comment"> * 3. Neither the name of the Ericsson AB nor the names of its contributors</em> <a class="jxr_linenumber" name="L20" href="#L20">20</a> <em class="jxr_comment"> * may be used to endorse or promote products derived from this software without</em> <a class="jxr_linenumber" name="L21" href="#L21">21</a> <em class="jxr_comment"> * specific prior written permission.</em> <a class="jxr_linenumber" name="L22" href="#L22">22</a> <em class="jxr_comment"> * </em> <a class="jxr_linenumber" name="L23" href="#L23">23</a> <em class="jxr_comment"> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND</em> <a class="jxr_linenumber" name="L24" href="#L24">24</a> <em class="jxr_comment"> * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED</em> <a class="jxr_linenumber" name="L25" href="#L25">25</a> <em class="jxr_comment"> * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.</em> <a class="jxr_linenumber" name="L26" href="#L26">26</a> <em class="jxr_comment"> * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,</em> <a class="jxr_linenumber" name="L27" href="#L27">27</a> <em class="jxr_comment"> * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,</em> <a class="jxr_linenumber" name="L28" href="#L28">28</a> <em class="jxr_comment"> * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,</em> <a class="jxr_linenumber" name="L29" href="#L29">29</a> <em class="jxr_comment"> * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF</em> <a class="jxr_linenumber" name="L30" href="#L30">30</a> <em class="jxr_comment"> * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE</em> <a class="jxr_linenumber" name="L31" href="#L31">31</a> <em class="jxr_comment"> * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED</em> <a class="jxr_linenumber" name="L32" href="#L32">32</a> <em class="jxr_comment"> * OF THE POSSIBILITY OF SUCH DAMAGE.</em> <a class="jxr_linenumber" name="L33" href="#L33">33</a> <em class="jxr_comment"> * ##_END_LICENSE_##</em> <a class="jxr_linenumber" name="L34" href="#L34">34</a> <em class="jxr_comment"> */</em> <a class="jxr_linenumber" name="L35" href="#L35">35</a> <a class="jxr_linenumber" name="L36" href="#L36">36</a> <a class="jxr_linenumber" name="L37" href="#L37">37</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">interface</strong> <a href="../../../../../../com/ericsson/research/transport/ws/spi/WSConstants.html">WSConstants</a> { <a class="jxr_linenumber" name="L38" href="#L38">38</a> <a class="jxr_linenumber" name="L39" href="#L39">39</a> String ISO_8859_1 = <span class="jxr_string">"iso-8859-1"</span>; <a class="jxr_linenumber" name="L40" href="#L40">40</a> String UTF_8 = <span class="jxr_string">"UTF-8"</span>; <a class="jxr_linenumber" name="L41" href="#L41">41</a> String HTTP11 = <span class="jxr_string">"HTTP/1.1"</span>; <a class="jxr_linenumber" name="L42" href="#L42">42</a> String CRLF = <span class="jxr_string">"\r\n"</span>; <a class="jxr_linenumber" name="L43" href="#L43">43</a> String COLON_SPACE = <span class="jxr_string">": "</span>; <a class="jxr_linenumber" name="L44" href="#L44">44</a> String CRLFCRLF = <span class="jxr_string">"\r\n\r\n"</span>; <a class="jxr_linenumber" name="L45" href="#L45">45</a> String GET = <span class="jxr_string">"GET"</span>; <a class="jxr_linenumber" name="L46" href="#L46">46</a> String WS_SCHEMA = <span class="jxr_string">"ws://"</span>; <a class="jxr_linenumber" name="L47" href="#L47">47</a> String WSS_SCHEMA = <span class="jxr_string">"wss://"</span>; <a class="jxr_linenumber" name="L48" href="#L48">48</a> String ILLEGAL_STATE = <span class="jxr_string">"Illegal state"</span>; <a class="jxr_linenumber" name="L49" href="#L49">49</a> byte[] empty = <strong class="jxr_keyword">new</strong> byte[0]; <a class="jxr_linenumber" name="L50" href="#L50">50</a> <strong class="jxr_keyword">long</strong> CLOSE_TIMEOUT = 5000; <a class="jxr_linenumber" name="L51" href="#L51">51</a> <a class="jxr_linenumber" name="L52" href="#L52">52</a> <em class="jxr_comment">// Common</em> <a class="jxr_linenumber" name="L53" href="#L53">53</a> String HOST_HEADER = <span class="jxr_string">"Host"</span>; <a class="jxr_linenumber" name="L54" href="#L54">54</a> String UPGRADE_HEADER = <span class="jxr_string">"Upgrade"</span>; <a class="jxr_linenumber" name="L55" href="#L55">55</a> String CONNECTION_HEADER = <span class="jxr_string">"Connection"</span>; <a class="jxr_linenumber" name="L56" href="#L56">56</a> String WEBSOCKET_VALUE = <span class="jxr_string">"WebSocket"</span>; <a class="jxr_linenumber" name="L57" href="#L57">57</a> String UPGRADE_VALUE = <span class="jxr_string">"Upgrade"</span>; <a class="jxr_linenumber" name="L58" href="#L58">58</a> <a class="jxr_linenumber" name="L59" href="#L59">59</a> <em class="jxr_comment">// Hixie-75</em> <a class="jxr_linenumber" name="L60" href="#L60">60</a> String ORIGIN_HEADER = <span class="jxr_string">"Origin"</span>; <em class="jxr_comment">// Also RFC 6455</em> <a class="jxr_linenumber" name="L61" href="#L61">61</a> String WEBSOCKET_LOCATION_HEADER = <span class="jxr_string">"WebSocket-Location"</span>; <a class="jxr_linenumber" name="L62" href="#L62">62</a> String WEBSOCKET_ORIGIN_HEADER = <span class="jxr_string">"WebSocket-Origin"</span>; <a class="jxr_linenumber" name="L63" href="#L63">63</a> <a class="jxr_linenumber" name="L64" href="#L64">64</a> <em class="jxr_comment">// Hixie-76</em> <a class="jxr_linenumber" name="L65" href="#L65">65</a> String SEC_WEBSOCKET_KEY1_HEADER = <span class="jxr_string">"Sec-WebSocket-Key1"</span>; <a class="jxr_linenumber" name="L66" href="#L66">66</a> String SEC_WEBSOCKET_KEY2_HEADER = <span class="jxr_string">"Sec-WebSocket-Key2"</span>; <a class="jxr_linenumber" name="L67" href="#L67">67</a> String SEC_WEBSOCKET_ORIGIN_HEADER = <span class="jxr_string">"Sec-WebSocket-Origin"</span>; <a class="jxr_linenumber" name="L68" href="#L68">68</a> String SEC_WEBSOCKET_LOCATION_HEADER = <span class="jxr_string">"Sec-WebSocket-Location"</span>; <a class="jxr_linenumber" name="L69" href="#L69">69</a> <a class="jxr_linenumber" name="L70" href="#L70">70</a> <em class="jxr_comment">// Hybi-10</em> <a class="jxr_linenumber" name="L71" href="#L71">71</a> String GUID = <span class="jxr_string">"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"</span>; <a class="jxr_linenumber" name="L72" href="#L72">72</a> String SEC_WEBSOCKET_KEY_HEADER = <span class="jxr_string">"Sec-WebSocket-Key"</span>; <a class="jxr_linenumber" name="L73" href="#L73">73</a> String SEC_WEBSOCKET_PROTOCOL_HEADER = <span class="jxr_string">"Sec-WebSocket-Protocol"</span>; <a class="jxr_linenumber" name="L74" href="#L74">74</a> String SEC_WEBSOCKET_VERSION_HEADER = <span class="jxr_string">"Sec-WebSocket-Version"</span>; <a class="jxr_linenumber" name="L75" href="#L75">75</a> String SEC_WEBSOCKET_ACCEPT_HEADER = <span class="jxr_string">"Sec-WebSocket-Accept"</span>; <a class="jxr_linenumber" name="L76" href="#L76">76</a> <a class="jxr_linenumber" name="L77" href="#L77">77</a> } </pre> <hr/> <div id="footer">Copyright &#169; 2014 <a href="https://www.ericsson.com">Ericsson AB</a>. All rights reserved.</div> </body> </html>
princeofdarkness76/trap
xref/com/ericsson/research/transport/ws/spi/WSConstants.html
HTML
bsd-3-clause
10,310
/** @file * * @ingroup dspFilterLib * * @brief Unit test for the FilterLib TTAllpass2b class. * * @details Currently this test is just a stub * * @authors Trond Lossius, Tim Place * * @copyright Copyright © 2012 by Trond Lossius & Timothy Place @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTAllpass2b.h" TTErr TTAllpass2b::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; // Wrap up the test results to pass back to whoever called this test return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); }
jamoma/JamomaCore
DSP/extensions/FilterLib/tests/TTAllpass2b.test.cpp
C++
bsd-3-clause
664
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__unsigned_int_fscanf_multiply_82_goodG2B.cpp Label Definition File: CWE190_Integer_Overflow.label.xml Template File: sources-sinks-82_goodG2B.tmpl.cpp */ /* * @description * CWE: 190 Integer Overflow * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Set data to a small, non-zero number (two) * Sinks: multiply * GoodSink: Ensure there will not be an overflow before multiplying data by 2 * BadSink : If data is positive, multiply by 2, which can cause an overflow * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE190_Integer_Overflow__unsigned_int_fscanf_multiply_82.h" namespace CWE190_Integer_Overflow__unsigned_int_fscanf_multiply_82 { void CWE190_Integer_Overflow__unsigned_int_fscanf_multiply_82_goodG2B::action(unsigned int data) { if(data > 0) /* ensure we won't have an underflow */ { /* POTENTIAL FLAW: if (data*2) > UINT_MAX, this will overflow */ unsigned int result = data * 2; printUnsignedLine(result); } } } #endif /* OMITGOOD */
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE190_Integer_Overflow/s05/CWE190_Integer_Overflow__unsigned_int_fscanf_multiply_82_goodG2B.cpp
C++
bsd-3-clause
1,247
import typing import weakref if typing.TYPE_CHECKING: from .server import Server from .client import Channel servers: 'weakref.WeakSet[Server]' = weakref.WeakSet() channels: 'weakref.WeakSet[Channel]' = weakref.WeakSet()
vmagamedov/grpclib
grpclib/_registry.py
Python
bsd-3-clause
231
namespace IoC.UI { using System; [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class ComponentAttribute : Attribute { private readonly string name; public ComponentAttribute(string name) { this.name = name; } public string Name { get { return name; } } } }
codechip/rhino-tools
SampleApplications/Blog.Viewer/Backup/IoC.UI/ComponentAttribute.cs
C#
bsd-3-clause
328
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.models import File, Release, ReleaseFile from sentry.testutils import APITestCase class ReleaseDetailsTest(APITestCase): def test_simple(self): self.login_as(user=self.user) project = self.create_project(name='foo') release = Release.objects.create( project=project, version='1', ) url = reverse('sentry-api-0-release-details', kwargs={ 'organization_slug': project.organization.slug, 'project_slug': project.slug, 'version': release.version, }) response = self.client.get(url) assert response.status_code == 200, response.content assert response.data['version'] == release.version class UpdateReleaseDetailsTest(APITestCase): def test_simple(self): self.login_as(user=self.user) project = self.create_project(name='foo') release = Release.objects.create( project=project, version='1', ) url = reverse('sentry-api-0-release-details', kwargs={ 'organization_slug': project.organization.slug, 'project_slug': project.slug, 'version': release.version, }) response = self.client.put(url, {'ref': 'master'}) assert response.status_code == 200, response.content assert response.data['version'] == release.version release = Release.objects.get(id=release.id) assert release.ref == 'master' class ReleaseDeleteTest(APITestCase): def test_simple(self): self.login_as(user=self.user) project = self.create_project(name='foo') release = Release.objects.create( project=project, version='1', ) ReleaseFile.objects.create( project=project, release=release, file=File.objects.create( name='application.js', type='release.file', ), name='http://example.com/application.js' ) url = reverse('sentry-api-0-release-details', kwargs={ 'organization_slug': project.organization.slug, 'project_slug': project.slug, 'version': release.version, }) response = self.client.delete(url) assert response.status_code == 204, response.content assert not Release.objects.filter(id=release.id).exists() def test_existing_group(self): self.login_as(user=self.user) project = self.create_project(name='foo') release = Release.objects.create( project=project, version='1', ) self.create_group(first_release=release) url = reverse('sentry-api-0-release-details', kwargs={ 'organization_slug': project.organization.slug, 'project_slug': project.slug, 'version': release.version, }) response = self.client.delete(url) assert response.status_code == 400, response.content assert Release.objects.filter(id=release.id).exists()
mitsuhiko/sentry
tests/sentry/api/endpoints/test_release_details.py
Python
bsd-3-clause
3,182
<!-- @license Copyright (c) 2014 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt --> <script> /** * Supports `listeners` object. * * Example: * * * Polymer({ * * listeners: { * // `click` events on the host are delegated to `clickHandler` * 'click': 'clickHandler' * }, * * ... * * }); * * * @class standard feature: events * */ Polymer.Base._addFeature({ /** * Object containing entries specifying event listeners to create on each * instance of this element, where keys specify the event name and values * specify the name of the handler method to call on this prototype. * * Example: * * * Polymer({ * * listeners: { * // `click` events on the host are delegated to `clickHandler` * 'tap': 'tapHandler' * }, * * ... * * }); */ listeners: {}, _listenListeners: function(listeners) { var node, name, key; for (key in listeners) { if (key.indexOf('.') < 0) { node = this; name = key; } else { name = key.split('.'); node = this.$[name[0]]; name = name[1]; } this.listen(node, name, listeners[key]); } }, /** * Convenience method to add an event listener on a given element, * late bound to a named method on this element. * * @method listen * @param {Element} node Element to add event listener to. * @param {string} eventName Name of event to listen for. * @param {string} methodName Name of handler method on `this` to call. */ listen: function(node, eventName, methodName) { var handler = this._recallEventHandler(this, eventName, node, methodName); // reuse cache'd handler if (!handler) { handler = this._createEventHandler(node, eventName, methodName); } // don't call _listen if we are already listening if (handler._listening) { return; } this._listen(node, eventName, handler); handler._listening = true; }, _boundListenerKey: function(eventName, methodName) { return (eventName + ':' + methodName); }, _recordEventHandler: function(host, eventName, target, methodName, handler) { var hbl = host.__boundListeners; if (!hbl) { hbl = host.__boundListeners = new WeakMap(); } var bl = hbl.get(target); if (!bl) { bl = {}; hbl.set(target, bl); } var key = this._boundListenerKey(eventName, methodName); bl[key] = handler; }, _recallEventHandler: function(host, eventName, target, methodName) { var hbl = host.__boundListeners; if (!hbl) { return; } var bl = hbl.get(target); if (!bl) { return; } var key = this._boundListenerKey(eventName, methodName); return bl[key]; }, _createEventHandler: function(node, eventName, methodName) { var host = this; var handler = function(e) { if (host[methodName]) { host[methodName](e, e.detail); } else { host._warn(host._logf('_createEventHandler', 'listener method `' + methodName + '` not defined')); } }; handler._listening = false; this._recordEventHandler(host, eventName, node, methodName, handler); return handler; }, /** * Convenience method to remove an event listener from a given element, * late bound to a named method on this element. * * @method unlisten * @param {Element} node Element to remove event listener from. * @param {string} eventName Name of event to stop listening to. * @param {string} methodName Name of handler method on `this` to not call anymore. */ unlisten: function(node, eventName, methodName) { // leave handler in map for cache purposes var handler = this._recallEventHandler(this, eventName, node, methodName); if (handler) { this._unlisten(node, eventName, handler); handler._listening = false; } }, _listen: function(node, eventName, handler) { node.addEventListener(eventName, handler); }, _unlisten: function(node, eventName, handler) { node.removeEventListener(eventName, handler); } }); </script>
filaraujo/polymer
src/standard/events.html
HTML
bsd-3-clause
4,896
""" radar_collection.py Classes for interaction with files. """ # Load the needed packages import code import pyart import sys import os path = os.path.dirname(sys.modules[__name__].__file__) path = os.path.join(path, '...') sys.path.insert(0, path) import artview from ..core import Component, Variable, common, QtWidgets, QtCore # get list of read functions import inspect aux_read_functions = inspect.getmembers(pyart.aux_io, inspect.isfunction) read_functions = [ pyart.io.read, pyart.io.read_grid, pyart.io.read_grid_mdv] + [a[1] for a in aux_read_functions] try: read_functions.append(pyart.io.read_legacy_grid) except: pass # test for missing dependency broken_read_functions = [] try: for func in read_functions: try: func(None) except pyart.exceptions.MissingOptionalDependency: broken_read_functions.append(func) except: pass except: pass class RadarCollectionView(Component): ''' Add and remove files from a RadarCollection. ''' VradarCollection = None #: see :ref:`shared_variable` @classmethod def guiStart(self, parent=None): '''Graphical interface for starting this class.''' kwargs, independent = \ common._SimplePluginStart("RadarCollectionView").startDisplay() kwargs['parent'] = parent return self(**kwargs), independent return self(), False def __init__(self, dirIn=None, VradarCollection=None , name="RadarCollectionView", parent=None): '''Initialize the class to create the interface. Parameters ---------- [Optional] dirIn: string Initial directory path to open. VradarCollection: py:class:`~artview.core.core.Variable` instance radar collection signal variable. A value of None will instantiate a empty list variable. name : string Window name. parent : PyQt instance Parent instance to associate to this class. If None, then Qt owns, otherwise associated with parent PyQt instance. ''' super(RadarCollectionView, self).__init__(name=name, parent=parent) self.directoryView = QtWidgets.QListView() self.collectionView = QtWidgets.QListView() # set up directoryView try: directoryModel = QtGui.QFileSystemModel() except: # PyQt5 directoryModel = QtCore.QFileSystemModel() directoryModel.setFilter(QtCore.QDir.AllEntries | QtCore.QDir.AllDirs | QtCore.QDir.NoDot) directoryModel.setRootPath(QtCore.QDir.currentPath()) self.directoryView.setModel(directoryModel) if dirIn is None: # avoid reference to path while building doc dirIn = os.getcwd() index = directoryModel.index(dirIn) self.directoryView.setRootIndex(index) # self.clicked.connect(self.test) self.directoryView.doubleClicked.connect(self.doubleClick) # context (right-click) menu # self.directoryView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # set up collectionView try: collectionModel = QtGui.QStringListModel() except: # PyQt5 collectionModel = QtCore.QStringListModel() self.collectionView.setModel(collectionModel) self.collectionView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.collectionView.customContextMenuRequested.connect( self.collectionContextMenu) # setup widget self.central_widget = QtWidgets.QWidget() self.setCentralWidget(self.central_widget) self.layout = QtWidgets.QGridLayout(self.central_widget) self.layout.addWidget(self.directoryView, 0, 0) self.layout.addWidget(self.collectionView, 0, 1) # self.directoryView.customContextMenuRequested.connect( # self.directoryContextMenu) if VradarCollection: self.VradarCollection = VradarCollection else: self.VradarCollection = Variable([]) self.sharedVariables = {"VradarCollection": self.NewRadarCollection} self.connectAllVariables() self.NewRadarCollection(None, True) self.show() def doubleClick(self, index): '''Open Directory or File on double click.''' model = self.directoryView.model() indexItem = model.index(index.row(), 0, index.parent()) if model.fileName(indexItem) == '..': if index.parent().parent().isValid(): self.directoryView.setRootIndex(index.parent().parent()) elif model.isDir(index): self.directoryView.setRootIndex(index) else: self.open(model.filePath(indexItem)) def open(self, path): '''Open file.''' # try several open print("open: %s" % path) self.filename = str(path) try: radar = pyart.io.read(self.filename, delay_field_loading=True) # Add the filename for Display radar.filename = self.filename self.VradarCollection.value.append(radar) self.VradarCollection.update() return except: try: radar = pyart.io.read(self.filename) # Add the filename for Display radar.filename = self.filename self.VradarCollection.value.append(radar) self.VradarCollection.update() return except: import traceback print(traceback.format_exc()) radar_warning = True if grid_warning or radar_warning: msg = "Py-ART didn't recognize this file!" common.ShowWarning(msg) return def directoryContextMenu(self, pos): '''Contruct right-click menu.''' menu = QtWidgets.QMenu(self) index = self.directoryView.currentIndex() path = str(self.directoryView.model().filePath(index)) for func in read_functions: action = QtWidgets.QAction("Open with: %s" % func.__name__, self) # lambda inside loop: problem with variable capturing if func not in broken_read_functions: f = lambda boo, func=func: self.open_with(func, path) action.triggered.connect(f) else: action.setEnabled(False) menu.addAction(action) menu.exec_(self.directoryView.mapToGlobal(pos)) def collectionContextMenu(self, pos): '''Contruct right-click menu.''' print("menu") menu = QtWidgets.QMenu(self) index = self.collectionView.currentIndex().row() action = QtWidgets.QAction("remove", self) f = lambda: self.remove_radar(index) action.triggered.connect(f) menu.addAction(action) menu.exec_(self.collectionView.mapToGlobal(pos)) def open_with(self, func, path): '''Open file using a given function.''' try: container = func(path, delay_field_loading=True) if isinstance(container, pyart.core.Radar): self.Vradar.change(container) elif isinstance(container, pyart.core.Grid): self.Vgrid.change(container) else: raise NotImplementedError("Unknown container type %s\n" % container) return except: import traceback error = traceback.format_exc() common.ShowLongText(("Opening file %s with %s fails\n\n" % (path, func.__name__)) + error) traceback.format_exc() def remove_radar(self, index): self.VradarCollection.value.pop(index) self.VradarCollection.update() def NewRadarCollection(self, variable, strong): ''' Slot for 'ValueChanged' signal of :py:class:`Vradar <artview.core.core.Variable>`. This will: * Update list of radar ''' # test for None str_list = [] for radar in self.VradarCollection.value: if hasattr(radar, 'filename'): str_list.append(radar.filename) else: str_list.append(radar.__str__()) self.collectionView.model().setStringList(str_list) _plugins = [RadarCollectionView]
gamaanderson/artview
artview/plugins/radar_collection.py
Python
bsd-3-clause
8,544
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/settings/device_settings_cache.h" #include <string> #include "base/base64.h" #include "base/bind.h" #include "base/prefs/pref_registry_simple.h" #include "base/prefs/pref_service.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/policy/cloud/proto/device_management_backend.pb.h" #include "chrome/common/pref_names.h" namespace em = enterprise_management; namespace chromeos { namespace device_settings_cache { void RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterStringPref(prefs::kDeviceSettingsCache, "invalid"); } bool Store(const em::PolicyData& policy, PrefService* local_state) { if (local_state) { std::string policy_string = policy.SerializeAsString(); std::string encoded; if (!base::Base64Encode(policy_string, &encoded)) { LOG(ERROR) << "Can't encode policy in base64."; return false; } local_state->SetString(prefs::kDeviceSettingsCache, encoded); return true; } return false; } bool Retrieve(em::PolicyData *policy, PrefService* local_state) { if (local_state) { std::string encoded = local_state->GetString(prefs::kDeviceSettingsCache); std::string policy_string; if (!base::Base64Decode(encoded, &policy_string)) { // This is normal and happens on first boot. VLOG(1) << "Can't decode policy from base64."; return false; } return policy->ParseFromString(policy_string); } return false; } } // namespace device_settings_cache } // namespace chromeos
timopulkkinen/BubbleFish
chrome/browser/chromeos/settings/device_settings_cache.cc
C++
bsd-3-clause
1,731
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry import benchmark from telemetry.core import util from telemetry.page import page_measurement from telemetry.page import page_set from telemetry.value import list_of_scalar_values def _CreatePageSetFromPath(path): assert os.path.exists(path) page_urls = [] serving_dirs = set() def _AddPage(path): if not path.endswith('.html'): return if '../' in open(path, 'r').read(): # If the page looks like it references its parent dir, include it. serving_dirs.add(os.path.dirname(os.path.dirname(path))) page_urls.append('file://' + path.replace('\\', '/')) def _AddDir(dir_path, skipped): for candidate_path in os.listdir(dir_path): if candidate_path == 'resources': continue candidate_path = os.path.join(dir_path, candidate_path) if candidate_path.startswith(tuple([os.path.join(path, s) for s in skipped])): continue if os.path.isdir(candidate_path): _AddDir(candidate_path, skipped) else: _AddPage(candidate_path) if os.path.isdir(path): skipped = [] skipped_file = os.path.join(path, 'Skipped') if os.path.exists(skipped_file): for line in open(skipped_file, 'r').readlines(): line = line.strip() if line and not line.startswith('#'): skipped.append(line.replace('/', os.sep)) _AddDir(path, skipped) else: _AddPage(path) ps = page_set.PageSet(file_path=os.getcwd()+os.sep, serving_dirs=serving_dirs) for url in page_urls: ps.AddPageWithDefaultRunNavigate(url) return ps class _BlinkPerfMeasurement(page_measurement.PageMeasurement): """Tuns a blink performance test and reports the results.""" def __init__(self): super(_BlinkPerfMeasurement, self).__init__('') with open(os.path.join(os.path.dirname(__file__), 'blink_perf.js'), 'r') as f: self._blink_perf_js = f.read() @property def results_are_the_same_on_every_page(self): return False def WillNavigateToPage(self, page, tab): page.script_to_evaluate_on_commit = self._blink_perf_js def CustomizeBrowserOptions(self, options): options.AppendExtraBrowserArgs([ '--js-flags=--expose_gc', '--enable-experimental-web-platform-features', '--disable-gesture-requirement-for-media-playback' ]) def MeasurePage(self, page, tab, results): tab.WaitForJavaScriptExpression('testRunner.isDone', 600) log = tab.EvaluateJavaScript('document.getElementById("log").innerHTML') for line in log.splitlines(): if not line.startswith('values '): continue parts = line.split() values = [float(v.replace(',', '')) for v in parts[1:-1]] units = parts[-1] metric = page.display_name.split('.')[0].replace('/', '_') results.AddValue(list_of_scalar_values.ListOfScalarValues( results.current_page, metric, units, values)) break print log class BlinkPerfAll(benchmark.Benchmark): tag = 'all' test = _BlinkPerfMeasurement def CreatePageSet(self, options): path = os.path.join(util.GetChromiumSrcDir(), 'third_party', 'WebKit', 'PerformanceTests') return _CreatePageSetFromPath(path) @benchmark.Disabled class BlinkPerfAnimation(benchmark.Benchmark): tag = 'animation' test = _BlinkPerfMeasurement def CreatePageSet(self, options): path = os.path.join(util.GetChromiumSrcDir(), 'third_party', 'WebKit', 'PerformanceTests', 'Animation') return _CreatePageSetFromPath(path)
chromium2014/src
tools/perf/benchmarks/blink_perf.py
Python
bsd-3-clause
3,735
#ifdef HAVE_ADIOS #include "OhmmsData/AttributeSet.h" #include "Configuration.h" #include <cstdlib> #include "Particle/AdiosWalkerInput.h" namespace qmcplusplus { void check_adios_error() { if (adios_errno < 0) { app_error() << adios_errmsg() << endl; } } AdiosWalkerInput::AdiosWalkerInput(MCWalkerConfiguration& w, Communicate* c): targetW(w),myComm(c) { FileRoot = ""; } AdiosWalkerInput::~AdiosWalkerInput() { } string AdiosWalkerInput::getFileRoot() { return FileRoot; } bool AdiosWalkerInput::put(vector<xmlNodePtr>& wset) { //Get our mpi proc rank int rank = myComm->rank(); //Check if their are any wsetwalker tags in the xml file if (wset.empty()) return false; int walker_win = 0; //This will accumalate the walkers we will be reading from the file string bpFileName; //Number of walkers per process vector<int> nw(myComm->size(), 0); //iterate through the mcwalkerset tags for (int i = 0; i < wset.size(); i++) { //We have multiple tags corresponding to mcWalkerset xmlNodePtr curr = wset[i]; //set up a parse of the xml node curr string froot, file, href; int nprocs; OhmmsAttributeSet pAttrib; //full file name could either be href or file pAttrib.add(href, "href"); pAttrib.add(file, "file"); //<fileroot>.config.bp pAttrib.add(froot, "fileroot"); //Get the attributes pAttrib.put(curr); //Check to see if any file attributes were set if (froot.empty() && href.empty() && file.empty()) return false; //We default to using froot if all of them were supplied //followed by file and then href if (!froot.empty()) { bpFileName = froot + ".config.bp"; app_log() << "Using froot: ignoring href and file tags" << endl; } else if (!file.empty()) { bpFileName = file; app_log() << "Using file: ignoring href" << endl; } else if (!href.empty()) { bpFileName = href; app_log() << "Using href tag" << endl; } else app_error() << "No file associated tag in mcwalkerset tag" << endl; app_log() << "Reading walker configurations from: " << bpFileName << endl; //Open the bp file ADIOS_FILE* adios_file_handle = adios_read_open_file(bpFileName.c_str(), ADIOS_READ_METHOD_BP, myComm->getMPI()); //Did the bp file open successfully check_adios_error(); //Inquire about the number of proccess ADIOS_VARINFO* var_info = adios_inq_var(adios_file_handle, "walkers"); nprocs = *var_info->nblocks; app_log() << "Number of procs that wrote " << nprocs << endl; adios_free_varinfo(var_info); //read in the data read(nprocs, adios_file_handle, walker_win, nw); } FileRoot = bpFileName; //Set mcwalker data setMCWalker( nw); return true; } void AdiosWalkerInput::setMCWalker(vector<int> nw) { //Now we generate the walker offsets int np = myComm->size(); vector<int> nwoff(myComm->size() + 1, 0); for(int ip=0; ip<np; ++ip) nwoff[ip+1]=nwoff[ip]+nw[ip]; app_log() << "Number of walkers " << nwoff[np] << endl; targetW.setGlobalNumWalkers(nwoff[np]); targetW.setWalkerOffsets(nwoff); } void AdiosWalkerInput::read(int nprocs, ADIOS_FILE* file_handle, int& walker_win, vector<int>& nw) { //iterate over the number of blocks in the adios file vector<int> walker_num(nprocs, 0); int total_walker_num = 0; ADIOS_SELECTION* sel; for (int i = 0; i < nprocs; i++) { //Find out how many walkers are in each writeblock from the last proc sel = adios_selection_writeblock(i); adios_schedule_read(file_handle, sel, "walker_num", 0, 1, &(walker_num[i])); } //Force reads to finish adios_perform_reads(file_handle, 1); check_adios_error(); for (int i = 0; i < nprocs; i++) total_walker_num += walker_num[i]; for (int j = 0; j < walker_num.size(); j++) app_log() << walker_num[j] << ", "; app_log() << endl; //The number of proccess to add 1 extra walker too int walker_wrap = total_walker_num % myComm->size(); //Buffer for each block in the adios R_t block_buff((total_walker_num / nprocs + 1) * targetW.getParticleNum()); //Calculate how many walkers each proccess should read and from which files // this proccess should read int current_adios_block = 0; int current_offset = 0; int next_offset; int next_adios_block; for (int i = 0; i < myComm->size(); i++) { int walkers_to_read; if ( (walker_win <= i && i < walker_win + walker_wrap) || (i < (walker_win + walker_wrap) % myComm->size() && (walker_win + walker_wrap) % myComm->size() <= walker_win)) walkers_to_read = total_walker_num / myComm->size() + 1; else walkers_to_read = total_walker_num / myComm->size(); app_log() << "walkers_to_read " << walkers_to_read << " proc=" << i <<endl; //Keep track of how many walkers each proccess has nw[i] += walkers_to_read; while (walkers_to_read != 0) { for (int j = 0; j < walker_num.size(); j++) app_log() << walker_num[j] << ", "; app_log() << endl; int read_size; if (walker_num[current_adios_block] > walkers_to_read) { read_size = walkers_to_read; next_offset = read_size + current_offset; walker_num[current_adios_block] -= read_size; next_adios_block = current_adios_block; } else { read_size = walker_num[current_adios_block]; next_offset = 0; walker_num[current_adios_block] = 0; next_adios_block = current_adios_block + 1; } walkers_to_read -= read_size; app_log() << "Read Size=" << read_size << endl; app_log() << "Offset=" << current_offset << endl; app_log() << "Adios Block=" << current_adios_block << endl; app_log() << "Next Block=" << next_adios_block << endl; app_log() << " Next Offset=" << next_offset << endl; if (i == myComm->rank()) { //Select a region of the walker buffer sel = adios_selection_writeblock(current_adios_block); adios_schedule_read(file_handle, sel, "walkers", 0, 1, &(block_buff[0])); adios_selection_delete(sel); adios_perform_reads(file_handle, 1); append_walkers(block_buff, read_size, current_offset); } current_adios_block = next_adios_block; current_offset = next_offset; } } check_adios_error(); //Move the window walker_win = (walker_win + walker_wrap) % myComm->size(); //Append the walkers we read from the buffer to the walkers list } void AdiosWalkerInput::append_walkers(R_t& walker_buff, int read_size, int current_offset) { int offset = current_offset * targetW.getParticleNum(); int cw = targetW.getActiveWalkers(); targetW.createWalkers(read_size); int pn = targetW.getParticleNum(); //Now lets append all those walkers to the walker list for (int w = cw; w < (cw + read_size); w++) //through walkers for ( int i = 0; i < pn; i++) //through R { targetW.WalkerList[w]->R[i] = walker_buff[offset + w * pn + i]; } } } #endif
habanero-rice/hcpp
test/performance-regression/full-apps/qmcpack/src/Particle/AdiosWalkerInput.cpp
C++
bsd-3-clause
7,271