text
stringlengths 2
100k
| meta
dict |
---|---|
/*
* Copyright 2011-2013 Intel Corporation
* Modifications Copyright 2014, Blender Foundation.
*
* Licensed under the Apache License, Version 2.0(the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __UTIL_SSEF_H__
#define __UTIL_SSEF_H__
CCL_NAMESPACE_BEGIN
#ifdef __KERNEL_SSE2__
struct sseb;
struct ssef;
/*! 4-wide SSE float type. */
struct ssef {
typedef sseb Mask; // mask type
typedef ssei Int; // int type
typedef ssef Float; // float type
enum { size = 4 }; // number of SIMD elements
union {
__m128 m128;
float f[4];
int i[4];
}; // data
////////////////////////////////////////////////////////////////////////////////
/// Constructors, Assignment & Cast Operators
////////////////////////////////////////////////////////////////////////////////
__forceinline ssef()
{
}
__forceinline ssef(const ssef &other)
{
m128 = other.m128;
}
__forceinline ssef &operator=(const ssef &other)
{
m128 = other.m128;
return *this;
}
__forceinline ssef(const __m128 a) : m128(a)
{
}
__forceinline operator const __m128 &() const
{
return m128;
}
__forceinline operator __m128 &()
{
return m128;
}
__forceinline ssef(float a) : m128(_mm_set1_ps(a))
{
}
__forceinline ssef(float a, float b, float c, float d) : m128(_mm_setr_ps(a, b, c, d))
{
}
__forceinline explicit ssef(const __m128i a) : m128(_mm_cvtepi32_ps(a))
{
}
////////////////////////////////////////////////////////////////////////////////
/// Loads and Stores
////////////////////////////////////////////////////////////////////////////////
# if defined(__KERNEL_AVX__)
static __forceinline ssef broadcast(const void *const a)
{
return _mm_broadcast_ss((float *)a);
}
# else
static __forceinline ssef broadcast(const void *const a)
{
return _mm_set1_ps(*(float *)a);
}
# endif
////////////////////////////////////////////////////////////////////////////////
/// Array Access
////////////////////////////////////////////////////////////////////////////////
__forceinline const float &operator[](const size_t i) const
{
assert(i < 4);
return f[i];
}
__forceinline float &operator[](const size_t i)
{
assert(i < 4);
return f[i];
}
};
////////////////////////////////////////////////////////////////////////////////
/// Unary Operators
////////////////////////////////////////////////////////////////////////////////
__forceinline const ssef cast(const __m128i &a)
{
return _mm_castsi128_ps(a);
}
__forceinline const ssef operator+(const ssef &a)
{
return a;
}
__forceinline const ssef operator-(const ssef &a)
{
return _mm_xor_ps(a.m128, _mm_castsi128_ps(_mm_set1_epi32(0x80000000)));
}
__forceinline const ssef abs(const ssef &a)
{
return _mm_and_ps(a.m128, _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff)));
}
# if defined(__KERNEL_SSE41__)
__forceinline const ssef sign(const ssef &a)
{
return _mm_blendv_ps(ssef(1.0f), -ssef(1.0f), _mm_cmplt_ps(a, ssef(0.0f)));
}
# endif
__forceinline const ssef signmsk(const ssef &a)
{
return _mm_and_ps(a.m128, _mm_castsi128_ps(_mm_set1_epi32(0x80000000)));
}
__forceinline const ssef rcp(const ssef &a)
{
const ssef r = _mm_rcp_ps(a.m128);
return _mm_sub_ps(_mm_add_ps(r, r), _mm_mul_ps(_mm_mul_ps(r, r), a));
}
__forceinline const ssef sqr(const ssef &a)
{
return _mm_mul_ps(a, a);
}
__forceinline const ssef mm_sqrt(const ssef &a)
{
return _mm_sqrt_ps(a.m128);
}
__forceinline const ssef rsqrt(const ssef &a)
{
const ssef r = _mm_rsqrt_ps(a.m128);
return _mm_add_ps(
_mm_mul_ps(_mm_set_ps(1.5f, 1.5f, 1.5f, 1.5f), r),
_mm_mul_ps(_mm_mul_ps(_mm_mul_ps(a, _mm_set_ps(-0.5f, -0.5f, -0.5f, -0.5f)), r),
_mm_mul_ps(r, r)));
}
////////////////////////////////////////////////////////////////////////////////
/// Binary Operators
////////////////////////////////////////////////////////////////////////////////
__forceinline const ssef operator+(const ssef &a, const ssef &b)
{
return _mm_add_ps(a.m128, b.m128);
}
__forceinline const ssef operator+(const ssef &a, const float &b)
{
return a + ssef(b);
}
__forceinline const ssef operator+(const float &a, const ssef &b)
{
return ssef(a) + b;
}
__forceinline const ssef operator-(const ssef &a, const ssef &b)
{
return _mm_sub_ps(a.m128, b.m128);
}
__forceinline const ssef operator-(const ssef &a, const float &b)
{
return a - ssef(b);
}
__forceinline const ssef operator-(const float &a, const ssef &b)
{
return ssef(a) - b;
}
__forceinline const ssef operator*(const ssef &a, const ssef &b)
{
return _mm_mul_ps(a.m128, b.m128);
}
__forceinline const ssef operator*(const ssef &a, const float &b)
{
return a * ssef(b);
}
__forceinline const ssef operator*(const float &a, const ssef &b)
{
return ssef(a) * b;
}
__forceinline const ssef operator/(const ssef &a, const ssef &b)
{
return _mm_div_ps(a.m128, b.m128);
}
__forceinline const ssef operator/(const ssef &a, const float &b)
{
return a / ssef(b);
}
__forceinline const ssef operator/(const float &a, const ssef &b)
{
return ssef(a) / b;
}
__forceinline const ssef operator^(const ssef &a, const ssef &b)
{
return _mm_xor_ps(a.m128, b.m128);
}
__forceinline const ssef operator^(const ssef &a, const ssei &b)
{
return _mm_xor_ps(a.m128, _mm_castsi128_ps(b.m128));
}
__forceinline const ssef operator&(const ssef &a, const ssef &b)
{
return _mm_and_ps(a.m128, b.m128);
}
__forceinline const ssef operator&(const ssef &a, const ssei &b)
{
return _mm_and_ps(a.m128, _mm_castsi128_ps(b.m128));
}
__forceinline const ssef operator|(const ssef &a, const ssef &b)
{
return _mm_or_ps(a.m128, b.m128);
}
__forceinline const ssef operator|(const ssef &a, const ssei &b)
{
return _mm_or_ps(a.m128, _mm_castsi128_ps(b.m128));
}
__forceinline const ssef andnot(const ssef &a, const ssef &b)
{
return _mm_andnot_ps(a.m128, b.m128);
}
__forceinline const ssef min(const ssef &a, const ssef &b)
{
return _mm_min_ps(a.m128, b.m128);
}
__forceinline const ssef min(const ssef &a, const float &b)
{
return _mm_min_ps(a.m128, ssef(b));
}
__forceinline const ssef min(const float &a, const ssef &b)
{
return _mm_min_ps(ssef(a), b.m128);
}
__forceinline const ssef max(const ssef &a, const ssef &b)
{
return _mm_max_ps(a.m128, b.m128);
}
__forceinline const ssef max(const ssef &a, const float &b)
{
return _mm_max_ps(a.m128, ssef(b));
}
__forceinline const ssef max(const float &a, const ssef &b)
{
return _mm_max_ps(ssef(a), b.m128);
}
# if defined(__KERNEL_SSE41__)
__forceinline ssef mini(const ssef &a, const ssef &b)
{
const ssei ai = _mm_castps_si128(a);
const ssei bi = _mm_castps_si128(b);
const ssei ci = _mm_min_epi32(ai, bi);
return _mm_castsi128_ps(ci);
}
# endif
# if defined(__KERNEL_SSE41__)
__forceinline ssef maxi(const ssef &a, const ssef &b)
{
const ssei ai = _mm_castps_si128(a);
const ssei bi = _mm_castps_si128(b);
const ssei ci = _mm_max_epi32(ai, bi);
return _mm_castsi128_ps(ci);
}
# endif
////////////////////////////////////////////////////////////////////////////////
/// Ternary Operators
////////////////////////////////////////////////////////////////////////////////
# if defined(__KERNEL_AVX2__)
__forceinline const ssef madd(const ssef &a, const ssef &b, const ssef &c)
{
return _mm_fmadd_ps(a, b, c);
}
__forceinline const ssef msub(const ssef &a, const ssef &b, const ssef &c)
{
return _mm_fmsub_ps(a, b, c);
}
__forceinline const ssef nmadd(const ssef &a, const ssef &b, const ssef &c)
{
return _mm_fnmadd_ps(a, b, c);
}
__forceinline const ssef nmsub(const ssef &a, const ssef &b, const ssef &c)
{
return _mm_fnmsub_ps(a, b, c);
}
# else
__forceinline const ssef madd(const ssef &a, const ssef &b, const ssef &c)
{
return a * b + c;
}
__forceinline const ssef msub(const ssef &a, const ssef &b, const ssef &c)
{
return a * b - c;
}
__forceinline const ssef nmadd(const ssef &a, const ssef &b, const ssef &c)
{
return c - a * b;
}
__forceinline const ssef nmsub(const ssef &a, const ssef &b, const ssef &c)
{
return -a * b - c;
}
# endif
////////////////////////////////////////////////////////////////////////////////
/// Assignment Operators
////////////////////////////////////////////////////////////////////////////////
__forceinline ssef &operator+=(ssef &a, const ssef &b)
{
return a = a + b;
}
__forceinline ssef &operator+=(ssef &a, const float &b)
{
return a = a + b;
}
__forceinline ssef &operator-=(ssef &a, const ssef &b)
{
return a = a - b;
}
__forceinline ssef &operator-=(ssef &a, const float &b)
{
return a = a - b;
}
__forceinline ssef &operator*=(ssef &a, const ssef &b)
{
return a = a * b;
}
__forceinline ssef &operator*=(ssef &a, const float &b)
{
return a = a * b;
}
__forceinline ssef &operator/=(ssef &a, const ssef &b)
{
return a = a / b;
}
__forceinline ssef &operator/=(ssef &a, const float &b)
{
return a = a / b;
}
////////////////////////////////////////////////////////////////////////////////
/// Comparison Operators + Select
////////////////////////////////////////////////////////////////////////////////
__forceinline const sseb operator==(const ssef &a, const ssef &b)
{
return _mm_cmpeq_ps(a.m128, b.m128);
}
__forceinline const sseb operator==(const ssef &a, const float &b)
{
return a == ssef(b);
}
__forceinline const sseb operator==(const float &a, const ssef &b)
{
return ssef(a) == b;
}
__forceinline const sseb operator!=(const ssef &a, const ssef &b)
{
return _mm_cmpneq_ps(a.m128, b.m128);
}
__forceinline const sseb operator!=(const ssef &a, const float &b)
{
return a != ssef(b);
}
__forceinline const sseb operator!=(const float &a, const ssef &b)
{
return ssef(a) != b;
}
__forceinline const sseb operator<(const ssef &a, const ssef &b)
{
return _mm_cmplt_ps(a.m128, b.m128);
}
__forceinline const sseb operator<(const ssef &a, const float &b)
{
return a < ssef(b);
}
__forceinline const sseb operator<(const float &a, const ssef &b)
{
return ssef(a) < b;
}
__forceinline const sseb operator>=(const ssef &a, const ssef &b)
{
return _mm_cmpnlt_ps(a.m128, b.m128);
}
__forceinline const sseb operator>=(const ssef &a, const float &b)
{
return a >= ssef(b);
}
__forceinline const sseb operator>=(const float &a, const ssef &b)
{
return ssef(a) >= b;
}
__forceinline const sseb operator>(const ssef &a, const ssef &b)
{
return _mm_cmpnle_ps(a.m128, b.m128);
}
__forceinline const sseb operator>(const ssef &a, const float &b)
{
return a > ssef(b);
}
__forceinline const sseb operator>(const float &a, const ssef &b)
{
return ssef(a) > b;
}
__forceinline const sseb operator<=(const ssef &a, const ssef &b)
{
return _mm_cmple_ps(a.m128, b.m128);
}
__forceinline const sseb operator<=(const ssef &a, const float &b)
{
return a <= ssef(b);
}
__forceinline const sseb operator<=(const float &a, const ssef &b)
{
return ssef(a) <= b;
}
__forceinline const ssef select(const sseb &m, const ssef &t, const ssef &f)
{
# ifdef __KERNEL_SSE41__
return _mm_blendv_ps(f, t, m);
# else
return _mm_or_ps(_mm_and_ps(m, t), _mm_andnot_ps(m, f));
# endif
}
__forceinline const ssef select(const ssef &m, const ssef &t, const ssef &f)
{
# ifdef __KERNEL_SSE41__
return _mm_blendv_ps(f, t, m);
# else
return _mm_or_ps(_mm_and_ps(m, t), _mm_andnot_ps(m, f));
# endif
}
__forceinline const ssef select(const int mask, const ssef &t, const ssef &f)
{
# if defined(__KERNEL_SSE41__) && \
((!defined(__clang__) && !defined(_MSC_VER)) || defined(__INTEL_COMPILER))
return _mm_blend_ps(f, t, mask);
# else
return select(sseb(mask), t, f);
# endif
}
////////////////////////////////////////////////////////////////////////////////
/// Rounding Functions
////////////////////////////////////////////////////////////////////////////////
# if defined(__KERNEL_SSE41__)
__forceinline const ssef round_even(const ssef &a)
{
return _mm_round_ps(a, _MM_FROUND_TO_NEAREST_INT);
}
__forceinline const ssef round_down(const ssef &a)
{
return _mm_round_ps(a, _MM_FROUND_TO_NEG_INF);
}
__forceinline const ssef round_up(const ssef &a)
{
return _mm_round_ps(a, _MM_FROUND_TO_POS_INF);
}
__forceinline const ssef round_zero(const ssef &a)
{
return _mm_round_ps(a, _MM_FROUND_TO_ZERO);
}
__forceinline const ssef floor(const ssef &a)
{
return _mm_round_ps(a, _MM_FROUND_TO_NEG_INF);
}
__forceinline const ssef ceil(const ssef &a)
{
return _mm_round_ps(a, _MM_FROUND_TO_POS_INF);
}
# endif
__forceinline ssei truncatei(const ssef &a)
{
return _mm_cvttps_epi32(a.m128);
}
/* This is about 25% faster than straightforward floor to integer conversion
* due to better pipelining.
*
* Unsaturated add 0xffffffff (a < 0) is the same as subtract -1.
*/
__forceinline ssei floori(const ssef &a)
{
return truncatei(a) + cast((a < 0.0f).m128);
}
__forceinline ssef floorfrac(const ssef &x, ssei *i)
{
*i = floori(x);
return x - ssef(*i);
}
////////////////////////////////////////////////////////////////////////////////
/// Common Functions
////////////////////////////////////////////////////////////////////////////////
__forceinline ssef mix(const ssef &a, const ssef &b, const ssef &t)
{
return madd(t, b, (ssef(1.0f) - t) * a);
}
////////////////////////////////////////////////////////////////////////////////
/// Movement/Shifting/Shuffling Functions
////////////////////////////////////////////////////////////////////////////////
__forceinline ssef unpacklo(const ssef &a, const ssef &b)
{
return _mm_unpacklo_ps(a.m128, b.m128);
}
__forceinline ssef unpackhi(const ssef &a, const ssef &b)
{
return _mm_unpackhi_ps(a.m128, b.m128);
}
template<size_t i0, size_t i1, size_t i2, size_t i3>
__forceinline const ssef shuffle(const ssef &b)
{
return _mm_castsi128_ps(_mm_shuffle_epi32(_mm_castps_si128(b), _MM_SHUFFLE(i3, i2, i1, i0)));
}
template<> __forceinline const ssef shuffle<0, 1, 0, 1>(const ssef &a)
{
return _mm_movelh_ps(a, a);
}
template<> __forceinline const ssef shuffle<2, 3, 2, 3>(const ssef &a)
{
return _mm_movehl_ps(a, a);
}
template<size_t i0, size_t i1, size_t i2, size_t i3>
__forceinline const ssef shuffle(const ssef &a, const ssef &b)
{
return _mm_shuffle_ps(a, b, _MM_SHUFFLE(i3, i2, i1, i0));
}
template<size_t i0> __forceinline const ssef shuffle(const ssef &a, const ssef &b)
{
return _mm_shuffle_ps(a, b, _MM_SHUFFLE(i0, i0, i0, i0));
}
template<> __forceinline const ssef shuffle<0, 1, 0, 1>(const ssef &a, const ssef &b)
{
return _mm_movelh_ps(a, b);
}
template<> __forceinline const ssef shuffle<2, 3, 2, 3>(const ssef &a, const ssef &b)
{
return _mm_movehl_ps(b, a);
}
# if defined(__KERNEL_SSSE3__)
__forceinline const ssef shuffle8(const ssef &a, const ssei &shuf)
{
return _mm_castsi128_ps(_mm_shuffle_epi8(_mm_castps_si128(a), shuf));
}
# endif
# if defined(__KERNEL_SSE3__)
template<> __forceinline const ssef shuffle<0, 0, 2, 2>(const ssef &b)
{
return _mm_moveldup_ps(b);
}
template<> __forceinline const ssef shuffle<1, 1, 3, 3>(const ssef &b)
{
return _mm_movehdup_ps(b);
}
# endif
template<size_t i0> __forceinline const ssef shuffle(const ssef &b)
{
return shuffle<i0, i0, i0, i0>(b);
}
# if defined(__KERNEL_AVX__)
__forceinline const ssef shuffle(const ssef &a, const ssei &shuf)
{
return _mm_permutevar_ps(a, shuf);
}
# endif
template<size_t i> __forceinline float extract(const ssef &a)
{
return _mm_cvtss_f32(shuffle<i, i, i, i>(a));
}
template<> __forceinline float extract<0>(const ssef &a)
{
return _mm_cvtss_f32(a);
}
# if defined(__KERNEL_SSE41__)
template<size_t dst, size_t src, size_t clr>
__forceinline const ssef insert(const ssef &a, const ssef &b)
{
return _mm_insert_ps(a, b, (dst << 4) | (src << 6) | clr);
}
template<size_t dst, size_t src> __forceinline const ssef insert(const ssef &a, const ssef &b)
{
return insert<dst, src, 0>(a, b);
}
template<size_t dst> __forceinline const ssef insert(const ssef &a, const float b)
{
return insert<dst, 0>(a, _mm_set_ss(b));
}
# else
template<size_t dst> __forceinline const ssef insert(const ssef &a, const float b)
{
ssef c = a;
c[dst] = b;
return c;
}
# endif
////////////////////////////////////////////////////////////////////////////////
/// Transpose
////////////////////////////////////////////////////////////////////////////////
__forceinline void transpose(const ssef &r0,
const ssef &r1,
const ssef &r2,
const ssef &r3,
ssef &c0,
ssef &c1,
ssef &c2,
ssef &c3)
{
ssef l02 = unpacklo(r0, r2);
ssef h02 = unpackhi(r0, r2);
ssef l13 = unpacklo(r1, r3);
ssef h13 = unpackhi(r1, r3);
c0 = unpacklo(l02, l13);
c1 = unpackhi(l02, l13);
c2 = unpacklo(h02, h13);
c3 = unpackhi(h02, h13);
}
__forceinline void transpose(
const ssef &r0, const ssef &r1, const ssef &r2, const ssef &r3, ssef &c0, ssef &c1, ssef &c2)
{
ssef l02 = unpacklo(r0, r2);
ssef h02 = unpackhi(r0, r2);
ssef l13 = unpacklo(r1, r3);
ssef h13 = unpackhi(r1, r3);
c0 = unpacklo(l02, l13);
c1 = unpackhi(l02, l13);
c2 = unpacklo(h02, h13);
}
////////////////////////////////////////////////////////////////////////////////
/// Reductions
////////////////////////////////////////////////////////////////////////////////
__forceinline const ssef vreduce_min(const ssef &v)
{
ssef h = min(shuffle<1, 0, 3, 2>(v), v);
return min(shuffle<2, 3, 0, 1>(h), h);
}
__forceinline const ssef vreduce_max(const ssef &v)
{
ssef h = max(shuffle<1, 0, 3, 2>(v), v);
return max(shuffle<2, 3, 0, 1>(h), h);
}
__forceinline const ssef vreduce_add(const ssef &v)
{
ssef h = shuffle<1, 0, 3, 2>(v) + v;
return shuffle<2, 3, 0, 1>(h) + h;
}
__forceinline float reduce_min(const ssef &v)
{
return _mm_cvtss_f32(vreduce_min(v));
}
__forceinline float reduce_max(const ssef &v)
{
return _mm_cvtss_f32(vreduce_max(v));
}
__forceinline float reduce_add(const ssef &v)
{
return _mm_cvtss_f32(vreduce_add(v));
}
__forceinline size_t select_min(const ssef &v)
{
return __bsf(movemask(v == vreduce_min(v)));
}
__forceinline size_t select_max(const ssef &v)
{
return __bsf(movemask(v == vreduce_max(v)));
}
__forceinline size_t select_min(const sseb &valid, const ssef &v)
{
const ssef a = select(valid, v, ssef(pos_inf));
return __bsf(movemask(valid & (a == vreduce_min(a))));
}
__forceinline size_t select_max(const sseb &valid, const ssef &v)
{
const ssef a = select(valid, v, ssef(neg_inf));
return __bsf(movemask(valid & (a == vreduce_max(a))));
}
__forceinline size_t movemask(const ssef &a)
{
return _mm_movemask_ps(a);
}
////////////////////////////////////////////////////////////////////////////////
/// Memory load and store operations
////////////////////////////////////////////////////////////////////////////////
__forceinline ssef load4f(const float4 &a)
{
# ifdef __KERNEL_WITH_SSE_ALIGN__
return _mm_load_ps(&a.x);
# else
return _mm_loadu_ps(&a.x);
# endif
}
__forceinline ssef load4f(const float3 &a)
{
# ifdef __KERNEL_WITH_SSE_ALIGN__
return _mm_load_ps(&a.x);
# else
return _mm_loadu_ps(&a.x);
# endif
}
__forceinline ssef load4f(const void *const a)
{
return _mm_load_ps((float *)a);
}
__forceinline ssef load1f_first(const float a)
{
return _mm_set_ss(a);
}
__forceinline void store4f(void *ptr, const ssef &v)
{
_mm_store_ps((float *)ptr, v);
}
__forceinline ssef loadu4f(const void *const a)
{
return _mm_loadu_ps((float *)a);
}
__forceinline void storeu4f(void *ptr, const ssef &v)
{
_mm_storeu_ps((float *)ptr, v);
}
__forceinline void store4f(const sseb &mask, void *ptr, const ssef &f)
{
# if defined(__KERNEL_AVX__)
_mm_maskstore_ps((float *)ptr, (__m128i)mask, f);
# else
*(ssef *)ptr = select(mask, f, *(ssef *)ptr);
# endif
}
__forceinline ssef load4f_nt(void *ptr)
{
# if defined(__KERNEL_SSE41__)
return _mm_castsi128_ps(_mm_stream_load_si128((__m128i *)ptr));
# else
return _mm_load_ps((float *)ptr);
# endif
}
__forceinline void store4f_nt(void *ptr, const ssef &v)
{
# if defined(__KERNEL_SSE41__)
_mm_stream_ps((float *)ptr, v);
# else
_mm_store_ps((float *)ptr, v);
# endif
}
////////////////////////////////////////////////////////////////////////////////
/// Euclidian Space Operators
////////////////////////////////////////////////////////////////////////////////
__forceinline float dot(const ssef &a, const ssef &b)
{
return reduce_add(a * b);
}
/* calculate shuffled cross product, useful when order of components does not matter */
__forceinline ssef cross_zxy(const ssef &a, const ssef &b)
{
const ssef a0 = a;
const ssef b0 = shuffle<1, 2, 0, 3>(b);
const ssef a1 = shuffle<1, 2, 0, 3>(a);
const ssef b1 = b;
return msub(a0, b0, a1 * b1);
}
__forceinline ssef cross(const ssef &a, const ssef &b)
{
return shuffle<1, 2, 0, 3>(cross_zxy(a, b));
}
ccl_device_inline const ssef dot3_splat(const ssef &a, const ssef &b)
{
# ifdef __KERNEL_SSE41__
return _mm_dp_ps(a.m128, b.m128, 0x7f);
# else
ssef t = a * b;
return ssef(((float *)&t)[0] + ((float *)&t)[1] + ((float *)&t)[2]);
# endif
}
/* squared length taking only specified axes into account */
template<size_t X, size_t Y, size_t Z, size_t W> ccl_device_inline float len_squared(const ssef &a)
{
# ifndef __KERNEL_SSE41__
float4 &t = (float4 &)a;
return (X ? t.x * t.x : 0.0f) + (Y ? t.y * t.y : 0.0f) + (Z ? t.z * t.z : 0.0f) +
(W ? t.w * t.w : 0.0f);
# else
return extract<0>(
ssef(_mm_dp_ps(a.m128, a.m128, (X << 4) | (Y << 5) | (Z << 6) | (W << 7) | 0xf)));
# endif
}
ccl_device_inline float dot3(const ssef &a, const ssef &b)
{
# ifdef __KERNEL_SSE41__
return extract<0>(ssef(_mm_dp_ps(a.m128, b.m128, 0x7f)));
# else
ssef t = a * b;
return ((float *)&t)[0] + ((float *)&t)[1] + ((float *)&t)[2];
# endif
}
ccl_device_inline const ssef len3_squared_splat(const ssef &a)
{
return dot3_splat(a, a);
}
ccl_device_inline float len3_squared(const ssef &a)
{
return dot3(a, a);
}
ccl_device_inline float len3(const ssef &a)
{
return extract<0>(mm_sqrt(dot3_splat(a, a)));
}
/* SSE shuffle utility functions */
# ifdef __KERNEL_SSSE3__
/* faster version for SSSE3 */
typedef ssei shuffle_swap_t;
ccl_device_inline shuffle_swap_t shuffle_swap_identity()
{
return _mm_set_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
}
ccl_device_inline shuffle_swap_t shuffle_swap_swap()
{
return _mm_set_epi8(7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8);
}
ccl_device_inline const ssef shuffle_swap(const ssef &a, const shuffle_swap_t &shuf)
{
return cast(_mm_shuffle_epi8(cast(a), shuf));
}
# else
/* somewhat slower version for SSE2 */
typedef int shuffle_swap_t;
ccl_device_inline shuffle_swap_t shuffle_swap_identity()
{
return 0;
}
ccl_device_inline shuffle_swap_t shuffle_swap_swap()
{
return 1;
}
ccl_device_inline const ssef shuffle_swap(const ssef &a, shuffle_swap_t shuf)
{
/* shuffle value must be a constant, so we need to branch */
if (shuf)
return ssef(_mm_shuffle_ps(a.m128, a.m128, _MM_SHUFFLE(1, 0, 3, 2)));
else
return ssef(_mm_shuffle_ps(a.m128, a.m128, _MM_SHUFFLE(3, 2, 1, 0)));
}
# endif
# ifdef __KERNEL_SSE41__
ccl_device_inline void gen_idirsplat_swap(const ssef &pn,
const shuffle_swap_t &shuf_identity,
const shuffle_swap_t &shuf_swap,
const float3 &idir,
ssef idirsplat[3],
shuffle_swap_t shufflexyz[3])
{
const __m128 idirsplat_raw[] = {_mm_set_ps1(idir.x), _mm_set_ps1(idir.y), _mm_set_ps1(idir.z)};
idirsplat[0] = _mm_xor_ps(idirsplat_raw[0], pn);
idirsplat[1] = _mm_xor_ps(idirsplat_raw[1], pn);
idirsplat[2] = _mm_xor_ps(idirsplat_raw[2], pn);
const ssef signmask = cast(ssei(0x80000000));
const ssef shuf_identity_f = cast(shuf_identity);
const ssef shuf_swap_f = cast(shuf_swap);
shufflexyz[0] = _mm_castps_si128(
_mm_blendv_ps(shuf_identity_f, shuf_swap_f, _mm_and_ps(idirsplat_raw[0], signmask)));
shufflexyz[1] = _mm_castps_si128(
_mm_blendv_ps(shuf_identity_f, shuf_swap_f, _mm_and_ps(idirsplat_raw[1], signmask)));
shufflexyz[2] = _mm_castps_si128(
_mm_blendv_ps(shuf_identity_f, shuf_swap_f, _mm_and_ps(idirsplat_raw[2], signmask)));
}
# else
ccl_device_inline void gen_idirsplat_swap(const ssef &pn,
const shuffle_swap_t &shuf_identity,
const shuffle_swap_t &shuf_swap,
const float3 &idir,
ssef idirsplat[3],
shuffle_swap_t shufflexyz[3])
{
idirsplat[0] = ssef(idir.x) ^ pn;
idirsplat[1] = ssef(idir.y) ^ pn;
idirsplat[2] = ssef(idir.z) ^ pn;
shufflexyz[0] = (idir.x >= 0) ? shuf_identity : shuf_swap;
shufflexyz[1] = (idir.y >= 0) ? shuf_identity : shuf_swap;
shufflexyz[2] = (idir.z >= 0) ? shuf_identity : shuf_swap;
}
# endif
ccl_device_inline const ssef uint32_to_float(const ssei &in)
{
ssei a = _mm_srli_epi32(in, 16);
ssei b = _mm_and_si128(in, _mm_set1_epi32(0x0000ffff));
ssei c = _mm_or_si128(a, _mm_set1_epi32(0x53000000));
ssef d = _mm_cvtepi32_ps(b);
ssef e = _mm_sub_ps(_mm_castsi128_ps(c), _mm_castsi128_ps(_mm_set1_epi32(0x53000000)));
return _mm_add_ps(e, d);
}
template<size_t S1, size_t S2, size_t S3, size_t S4>
ccl_device_inline const ssef set_sign_bit(const ssef &a)
{
return cast(cast(a) ^ ssei(S1 << 31, S2 << 31, S3 << 31, S4 << 31));
}
////////////////////////////////////////////////////////////////////////////////
/// Debug Functions
////////////////////////////////////////////////////////////////////////////////
ccl_device_inline void print_ssef(const char *label, const ssef &a)
{
printf(
"%s: %.8f %.8f %.8f %.8f\n", label, (double)a[0], (double)a[1], (double)a[2], (double)a[3]);
}
#endif
CCL_NAMESPACE_END
#endif
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<?page title="WCAG: Barcode"?>
<?root-attributes lang="en"?>
<!--
barcode.zul
Purpose:
Description:
History:
Thu Jun 4 16:00:23 CST 2020, Created by jameschu
Copyright (C) 2020 Potix Corporation. All Rights Reserved.
-->
<zk xmlns:n="native" xmlns:ca="client/attribute">
<n:header>
<n:h1>Barcode</n:h1>
</n:header>
<n:main>
<barcode type="ean13" value="0000000000000" displayValue="true" height="100px" width="300px"
ca:aria-label="Barcode presents 0000000000000" />
</n:main>
</zk> | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:bottom="129dp"
android:drawable="@drawable/shape_room"
android:left="5dp"
android:right="255dp"
android:top="230dp"/>
<item android:drawable="@drawable/room_aw1"/>
</layer-list> | {
"pile_set_name": "Github"
} |
/* ______ ___ ___
* /\ _ \ /\_ \ /\_ \
* \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___
* \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\
* \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \
* \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/
* \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/
* /\____/
* \_/__/
*
* DirectDraw bitmap management routines.
*
* By Stefan Schimanski.
*
* Improved page flipping mechanism by Robin Burrows.
*
* Improved video bitmap allocation scheme by Eric Botcazou.
*
* See readme.txt for copyright information.
*/
#include "wddraw.h"
#define PREFIX_I "al-wddbmp INFO: "
#define PREFIX_W "al-wddbmp WARNING: "
#define PREFIX_E "al-wddbmp ERROR: "
/* The video bitmap allocation scheme works as follows:
* - the screen is allocated as a single DirectDraw surface (primary or overlay,
* depending on the driver) at startup,
* - the first video bitmap reuses the DirectDraw surface of the screen which is
* then assigned to flipping_page[0],
* - the second video bitmap allocates flipping_page[1] and uses it as its
* DirectDraw surface; it also destroys the single surface pointed to by
* flipping_page[0] and creates a DirectDraw flipping chain whose frontbuffer
* is connected back to flipping_page[0] and backbuffer to flipping_page[1],
* - the third video bitmap allocates flipping_page[2] and uses it as its
* DirectDraw surface; it also destroys the flipping chain pointed to by
* flipping_page[0] and flipping_page[1] and creates a new flipping chain
* whose frontbuffer is connected back to flipping_page[0], first backbuffer
* back to flipping_page[1] and second backbuffer to flipping_page[2].
*
* When a video bitmap is to be destroyed, the flipping chain (if it exists) is
* destroyed and recreated with one less backbuffer, and its surfaces are assigned
* back to the flipping_page[] array in order. If the video bitmap is not attached
* to the surface that was just destroyed, its surface is assigned to the video
* bitmap parent of the just destroyed surface.
*
* After triple buffering setup:
*
* screen video_bmp[0] video_bmp[1] video_bmp[2]
* \ | | |
* \ | | |
* page_flipping[0] page_flipping[1] page_flipping[2]
* (frontbuffer)-----(backbuffer1)-----(backbuffer2)
*
* After request_video_bitmap(video_bmp[1]):
*
* screen video_bmp[0] video_bmp[1] video_bmp[2]
* \ \/ |
* \ /\ |
* page_flipping[0] page_flipping[1] page_flipping[2]
* (frontbuffer)-----(backbuffer1)-----(backbuffer2)
*
* This ensures that every video bitmap keeps track of the actual part of the
* video memory it represents (see the documentation of DirectDrawSurface::Flip).
*/
static DDRAW_SURFACE *flipping_page[3] = {NULL, NULL, NULL};
static int n_flipping_pages = 0;
/* dd_err:
* Returns a DirectDraw error string.
*/
#ifdef DEBUGMODE
static char *dd_err(long err)
{
static char err_str[64];
switch (err) {
case DD_OK:
_al_sane_strncpy(err_str, "DD_OK", sizeof(err_str));
break;
case DDERR_GENERIC:
_al_sane_strncpy(err_str, "DDERR_GENERIC", sizeof(err_str));
break;
case DDERR_INCOMPATIBLEPRIMARY:
_al_sane_strncpy(err_str, "DDERR_INCOMPATIBLEPRIMARY", sizeof(err_str));
break;
case DDERR_INVALIDCAPS:
_al_sane_strncpy(err_str, "DDERR_INVALIDCAPS", sizeof(err_str));
break;
case DDERR_INVALIDOBJECT:
_al_sane_strncpy(err_str, "DDERR_INVALIDOBJECT", sizeof(err_str));
break;
case DDERR_INVALIDPARAMS:
_al_sane_strncpy(err_str, "DDERR_INVALIDPARAMS", sizeof(err_str));
break;
case DDERR_INVALIDPIXELFORMAT:
_al_sane_strncpy(err_str, "DDERR_INVALIDPIXELFORMAT", sizeof(err_str));
break;
case DDERR_NOFLIPHW:
_al_sane_strncpy(err_str, "DDERR_NOFLIPHW", sizeof(err_str));
break;
case DDERR_NOTFLIPPABLE:
_al_sane_strncpy(err_str, "DDERR_NOTFLIPPABLE", sizeof(err_str));
break;
case DDERR_OUTOFMEMORY:
_al_sane_strncpy(err_str, "DDERR_OUTOFMEMORY", sizeof(err_str));
break;
case DDERR_OUTOFVIDEOMEMORY:
_al_sane_strncpy(err_str, "DDERR_OUTOFVIDEOMEMORY", sizeof(err_str));
break;
case DDERR_PRIMARYSURFACEALREADYEXISTS:
_al_sane_strncpy(err_str, "DDERR_PRIMARYSURFACEALREADYEXISTS", sizeof(err_str));
break;
case DDERR_SURFACEBUSY:
_al_sane_strncpy(err_str, "DDERR_SURFACEBUSY", sizeof(err_str));
break;
case DDERR_SURFACELOST:
_al_sane_strncpy(err_str, "DDERR_SURFACELOST", sizeof(err_str));
break;
case DDERR_UNSUPPORTED:
_al_sane_strncpy(err_str, "DDERR_UNSUPPORTED", sizeof(err_str));
break;
case DDERR_UNSUPPORTEDMODE:
_al_sane_strncpy(err_str, "DDERR_UNSUPPORTEDMODE", sizeof(err_str));
break;
case DDERR_WASSTILLDRAWING:
_al_sane_strncpy(err_str, "DDERR_WASSTILLDRAWING", sizeof(err_str));
break;
default:
_al_sane_strncpy(err_str, "DDERR_UNKNOWN", sizeof(err_str));
break;
}
return err_str;
}
#else
#define dd_err(hr) "\0"
#endif
/* create_directdraw2_surface:
* Wrapper around DirectDraw2::CreateSurface taking the surface characteristics
* as parameters. Returns a DirectDrawSurface2 interface if successful.
*/
static LPDIRECTDRAWSURFACE2 create_directdraw2_surface(int w, int h, LPDDPIXELFORMAT pixel_format, int type, int n_backbuffers)
{
DDSURFACEDESC ddsurf_desc;
LPDIRECTDRAWSURFACE ddsurf1;
LPVOID ddsurf2;
HRESULT hr;
/* describe surface characteristics */
memset(&ddsurf_desc, 0, sizeof(DDSURFACEDESC));
ddsurf_desc.dwSize = sizeof(DDSURFACEDESC);
ddsurf_desc.dwFlags = DDSD_CAPS;
switch (type) {
case DDRAW_SURFACE_PRIMARY:
ddsurf_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
_TRACE(PREFIX_I "Creating primary surface...");
break;
case DDRAW_SURFACE_OVERLAY:
ddsurf_desc.ddsCaps.dwCaps = DDSCAPS_VIDEOMEMORY | DDSCAPS_OVERLAY;
ddsurf_desc.dwFlags |= DDSD_HEIGHT | DDSD_WIDTH;
ddsurf_desc.dwHeight = h;
ddsurf_desc.dwWidth = w;
if (pixel_format) { /* use pixel format */
ddsurf_desc.dwFlags |= DDSD_PIXELFORMAT;
ddsurf_desc.ddpfPixelFormat = *pixel_format;
}
_TRACE(PREFIX_I "Creating overlay surface...");
break;
case DDRAW_SURFACE_VIDEO:
ddsurf_desc.ddsCaps.dwCaps = DDSCAPS_VIDEOMEMORY | DDSCAPS_OFFSCREENPLAIN;
ddsurf_desc.dwFlags |= DDSD_HEIGHT | DDSD_WIDTH;
ddsurf_desc.dwHeight = h;
ddsurf_desc.dwWidth = w;
_TRACE(PREFIX_I "Creating video surface...");
break;
case DDRAW_SURFACE_SYSTEM:
ddsurf_desc.ddsCaps.dwCaps = DDSCAPS_SYSTEMMEMORY | DDSCAPS_OFFSCREENPLAIN;
ddsurf_desc.dwFlags |= DDSD_HEIGHT | DDSD_WIDTH;
ddsurf_desc.dwHeight = h;
ddsurf_desc.dwWidth = w;
if (pixel_format) { /* use pixel format */
ddsurf_desc.dwFlags |= DDSD_PIXELFORMAT;
ddsurf_desc.ddpfPixelFormat = *pixel_format;
}
_TRACE(PREFIX_I "Creating system surface...");
break;
default:
_TRACE(PREFIX_E "Unknown surface type\n");
return NULL;
}
/* set backbuffer requirements */
if (n_backbuffers > 0) {
ddsurf_desc.ddsCaps.dwCaps |= DDSCAPS_COMPLEX | DDSCAPS_FLIP;
ddsurf_desc.dwFlags |= DDSD_BACKBUFFERCOUNT;
ddsurf_desc.dwBackBufferCount = n_backbuffers;
_TRACE("...with %d backbuffer(s)\n", n_backbuffers);
}
/* create the surface */
hr = IDirectDraw2_CreateSurface(directdraw, &ddsurf_desc, &ddsurf1, NULL);
if (FAILED(hr)) {
_TRACE(PREFIX_E "Unable to create the surface (%s)\n", dd_err(hr));
return NULL;
}
/* retrieve the DirectDrawSurface2 interface */
hr = IDirectDrawSurface_QueryInterface(ddsurf1, &IID_IDirectDrawSurface2, &ddsurf2);
/* there is a bug in the COM part of DirectX 3:
* If we release the DirectSurface interface, the actual
* object is also released. It is fixed in DirectX 5.
*/
if (_dx_ver >= 0x500)
IDirectDrawSurface_Release(ddsurf1);
if (FAILED(hr)) {
_TRACE(PREFIX_E "Unable to retrieve the DirectDrawSurface2 interface (%s)\n", dd_err(hr));
return NULL;
}
return (LPDIRECTDRAWSURFACE2)ddsurf2;
}
/* gfx_directx_create_surface:
* Creates a DirectDraw surface.
*/
DDRAW_SURFACE *gfx_directx_create_surface(int w, int h, LPDDPIXELFORMAT pixel_format, int type)
{
DDRAW_SURFACE *surf;
surf = _AL_MALLOC(sizeof(DDRAW_SURFACE));
if (!surf)
return NULL;
/* create the surface with the specified characteristics */
surf->id = create_directdraw2_surface(w, h, pixel_format,type, 0);
if (!surf->id) {
_AL_FREE(surf);
return NULL;
}
surf->flags = type;
surf->lock_nesting = 0;
register_ddraw_surface(surf);
return surf;
}
/* gfx_directx_destroy_surface:
* Destroys a DirectDraw surface.
*/
void gfx_directx_destroy_surface(DDRAW_SURFACE *surf)
{
IDirectDrawSurface2_Release(surf->id);
unregister_ddraw_surface(surf);
_AL_FREE(surf);
}
/* gfx_directx_make_bitmap_from_surface:
* Connects a DirectDraw surface with an Allegro bitmap.
*/
BITMAP *gfx_directx_make_bitmap_from_surface(DDRAW_SURFACE *surf, int w, int h, int id)
{
BITMAP *bmp;
int i;
bmp = (BITMAP *) _AL_MALLOC(sizeof(BITMAP) + sizeof(char *) * h);
if (!bmp)
return NULL;
bmp->w =w;
bmp->cr = w;
bmp->h = h;
bmp->cb = h;
bmp->clip = TRUE;
bmp->cl = 0;
bmp->ct = 0;
bmp->vtable = &_screen_vtable;
bmp->write_bank = gfx_directx_write_bank;
bmp->read_bank = gfx_directx_write_bank;
bmp->dat = NULL;
bmp->id = id;
bmp->extra = NULL;
bmp->x_ofs = 0;
bmp->y_ofs = 0;
bmp->seg = _video_ds();
for (i = 0; i < h; i++)
bmp->line[i] = pseudo_surf_mem;
bmp->extra = surf;
return bmp;
}
/* gfx_directx_created_sub_bitmap:
*/
void gfx_directx_created_sub_bitmap(BITMAP *bmp, BITMAP *parent)
{
bmp->extra = parent;
}
/* recreate_flipping_chain:
* Destroys the previous flipping chain and creates a new one.
*/
static int recreate_flipping_chain(int n_pages)
{
int w, h, type, n_backbuffers;
DDSCAPS ddscaps;
HRESULT hr;
ASSERT(n_pages > 0);
/* set flipping chain characteristics */
w = gfx_directx_forefront_bitmap->w;
h = gfx_directx_forefront_bitmap->h;
type = flipping_page[0]->flags & DDRAW_SURFACE_TYPE_MASK;
n_backbuffers = n_pages - 1;
/* release existing flipping chain */
if (flipping_page[0]->id) {
hr = IDirectDrawSurface2_Release(flipping_page[0]->id);
if (FAILED(hr)) {
_TRACE(PREFIX_E "Unable to release the primary surface (%s)", dd_err(hr));
return -1;
}
}
/* create the new flipping chain with the specified characteristics */
flipping_page[0]->id = create_directdraw2_surface(w, h, ddpixel_format, type, n_backbuffers);
if (!flipping_page[0]->id)
return -1;
/* retrieve the backbuffers */
if (n_backbuffers > 0) {
memset(&ddscaps, 0, sizeof(DDSCAPS));
/* first backbuffer */
ddscaps.dwCaps = DDSCAPS_BACKBUFFER;
hr = IDirectDrawSurface2_GetAttachedSurface(flipping_page[0]->id, &ddscaps, &flipping_page[1]->id);
if (FAILED(hr)) {
_TRACE(PREFIX_E "Unable to retrieve the first backbuffer (%s)", dd_err(hr));
return -1;
}
flipping_page[1]->flags = flipping_page[0]->flags;
flipping_page[1]->lock_nesting = 0;
if (n_backbuffers > 1) {
/* second backbuffer */
ddscaps.dwCaps = DDSCAPS_FLIP;
hr = IDirectDrawSurface2_GetAttachedSurface(flipping_page[1]->id, &ddscaps, &flipping_page[2]->id);
if (FAILED(hr)) {
_TRACE(PREFIX_E "Unable to retrieve the second backbuffer (%s)", dd_err(hr));
return -1;
}
flipping_page[2]->flags = flipping_page[0]->flags;
flipping_page[2]->lock_nesting = 0;
}
}
/* attach the global palette if needed */
if (flipping_page[0]->flags & DDRAW_SURFACE_INDEXED) {
hr = IDirectDrawSurface2_SetPalette(flipping_page[0]->id, ddpalette);
if (FAILED(hr)) {
_TRACE(PREFIX_E "Unable to attach the global palette (%s)", dd_err(hr));
return -1;
}
}
return 0;
}
/* gfx_directx_create_video_bitmap:
*/
BITMAP *gfx_directx_create_video_bitmap(int width, int height)
{
DDRAW_SURFACE *surf;
BITMAP *bmp;
/* try to detect page flipping and triple buffering patterns */
if ((width == gfx_directx_forefront_bitmap->w) && (height == gfx_directx_forefront_bitmap->h)) {
switch (n_flipping_pages) {
case 0:
/* recycle the forefront surface as the first flipping page */
flipping_page[0] = DDRAW_SURFACE_OF(gfx_directx_forefront_bitmap);
bmp = gfx_directx_make_bitmap_from_surface(flipping_page[0], width, height, BMP_ID_VIDEO);
if (bmp) {
flipping_page[0]->parent_bmp = bmp;
n_flipping_pages++;
return bmp;
}
else {
flipping_page[0] = NULL;
return NULL;
}
case 1:
case 2:
/* try to attach an additional page to the flipping chain */
flipping_page[n_flipping_pages] = _AL_MALLOC(sizeof(DDRAW_SURFACE));
if (recreate_flipping_chain(n_flipping_pages+1) == 0) {
bmp = gfx_directx_make_bitmap_from_surface(flipping_page[n_flipping_pages], width, height, BMP_ID_VIDEO);
if (bmp) {
flipping_page[n_flipping_pages]->parent_bmp = bmp;
n_flipping_pages++;
return bmp;
}
}
recreate_flipping_chain(n_flipping_pages);
_AL_FREE(flipping_page[n_flipping_pages]);
flipping_page[n_flipping_pages] = NULL;
return NULL;
}
}
/* create the DirectDraw surface */
if (ddpixel_format)
surf = gfx_directx_create_surface(width, height, ddpixel_format, DDRAW_SURFACE_SYSTEM);
else
surf = gfx_directx_create_surface(width, height, NULL, DDRAW_SURFACE_VIDEO);
if (!surf)
return NULL;
/* create the bitmap that wraps up the surface */
bmp = gfx_directx_make_bitmap_from_surface(surf, width, height, BMP_ID_VIDEO);
if (!bmp) {
gfx_directx_destroy_surface(surf);
return NULL;
}
return bmp;
}
/* gfx_directx_destroy_video_bitmap:
*/
void gfx_directx_destroy_video_bitmap(BITMAP *bmp)
{
DDRAW_SURFACE *surf, *tail_page;
surf = DDRAW_SURFACE_OF(bmp);
if ((surf == flipping_page[0]) || (surf == flipping_page[1]) || (surf == flipping_page[2])) {
/* handle surfaces belonging to the flipping chain */
if (--n_flipping_pages > 0) {
tail_page = flipping_page[n_flipping_pages];
/* If the surface attached to the bitmap is not the tail page
* that is to be destroyed, attach it to the bitmap whose
* attached surface is the tail page.
*/
if (surf != tail_page) {
surf->parent_bmp = tail_page->parent_bmp;
surf->parent_bmp->extra = surf;
}
/* remove the tail page from the flipping chain */
recreate_flipping_chain(n_flipping_pages);
_AL_FREE(tail_page);
}
flipping_page[n_flipping_pages] = NULL;
}
else {
/* destroy the surface */
gfx_directx_destroy_surface(surf);
}
_AL_FREE(bmp);
}
/* flip_with_forefront_bitmap:
* Worker function for DirectDraw page flipping.
*/
static int flip_with_forefront_bitmap(BITMAP *bmp, int wait)
{
DDRAW_SURFACE *surf;
HRESULT hr;
/* flip only in the foreground */
if (!_win_app_foreground) {
_win_thread_switch_out();
return 0;
}
/* retrieve the underlying surface */
surf = DDRAW_SURFACE_OF(bmp);
if (surf == flipping_page[0])
return 0;
ASSERT((surf == flipping_page[1]) || (surf == flipping_page[2]));
/* flip the contents of the surfaces */
hr = IDirectDrawSurface2_Flip(flipping_page[0]->id, surf->id, wait ? DDFLIP_WAIT : 0);
/* if the surface has been lost, try to restore all surfaces */
if (hr == DDERR_SURFACELOST) {
if (restore_all_ddraw_surfaces() == 0)
hr = IDirectDrawSurface2_Flip(flipping_page[0]->id, surf->id, wait ? DDFLIP_WAIT : 0);
}
if (FAILED(hr)) {
_TRACE(PREFIX_E "Can't flip (%s)\n", dd_err(hr));
return -1;
}
/* attach the surface to the former forefront bitmap */
surf->parent_bmp = flipping_page[0]->parent_bmp;
surf->parent_bmp->extra = surf;
/* make the bitmap point to the forefront surface */
flipping_page[0]->parent_bmp = bmp;
bmp->extra = flipping_page[0];
return 0;
}
/* gfx_directx_show_video_bitmap:
*/
int gfx_directx_show_video_bitmap(BITMAP *bmp)
{
/* guard against show_video_bitmap(screen); */
if (bmp == gfx_directx_forefront_bitmap)
return 0;
return flip_with_forefront_bitmap(bmp, _wait_for_vsync);
}
/* gfx_directx_request_video_bitmap:
*/
int gfx_directx_request_video_bitmap(BITMAP *bmp)
{
/* guard against request_video_bitmap(screen); */
if (bmp == gfx_directx_forefront_bitmap)
return 0;
return flip_with_forefront_bitmap(bmp, FALSE);
}
/* gfx_directx_poll_scroll:
*/
int gfx_directx_poll_scroll(void)
{
HRESULT hr;
ASSERT(n_flipping_pages == 3);
hr = IDirectDrawSurface2_GetFlipStatus(flipping_page[0]->id, DDGFS_ISFLIPDONE);
/* if the surface has been lost, try to restore all surfaces */
if (hr == DDERR_SURFACELOST) {
if (restore_all_ddraw_surfaces() == 0)
hr = IDirectDrawSurface2_GetFlipStatus(flipping_page[0]->id, DDGFS_ISFLIPDONE);
}
if (FAILED(hr))
return -1;
return 0;
}
/* gfx_directx_create_system_bitmap:
*/
BITMAP *gfx_directx_create_system_bitmap(int width, int height)
{
DDRAW_SURFACE *surf;
BITMAP *bmp;
/* create the DirectDraw surface */
surf = gfx_directx_create_surface(width, height, ddpixel_format, DDRAW_SURFACE_SYSTEM);
if (!surf)
return NULL;
/* create the bitmap that wraps up the surface */
bmp = gfx_directx_make_bitmap_from_surface(surf, width, height, BMP_ID_SYSTEM);
if (!bmp) {
gfx_directx_destroy_surface(surf);
return NULL;
}
return bmp;
}
/* gfx_directx_destroy_system_bitmap:
*/
void gfx_directx_destroy_system_bitmap(BITMAP *bmp)
{
/* Special case: use normal destroy_bitmap() for subbitmaps of system
* bitmaps. Checked here rather than in destroy_bitmap() because that
* function should not make assumptions about the relation between system
* bitmaps and subbitmaps thereof. This duplicates code though and a
* different solution would be better.
*/
if (is_sub_bitmap(bmp)) {
if (system_driver->destroy_bitmap) {
if (system_driver->destroy_bitmap(bmp))
return;
}
if (bmp->dat)
_AL_FREE(bmp->dat);
_AL_FREE(bmp);
return;
}
/* destroy the surface */
gfx_directx_destroy_surface(DDRAW_SURFACE_OF(bmp));
_AL_FREE(bmp);
}
/* win_get_dc: (WinAPI)
* Returns device context of a video or system bitmap.
*/
HDC win_get_dc(BITMAP *bmp)
{
LPDIRECTDRAWSURFACE2 ddsurf;
HDC dc;
HRESULT hr;
if (bmp) {
if (bmp->id & (BMP_ID_SYSTEM | BMP_ID_VIDEO)) {
ddsurf = DDRAW_SURFACE_OF(bmp)->id;
hr = IDirectDrawSurface2_GetDC(ddsurf, &dc);
/* If the surface has been lost, try to restore all surfaces
* and, on success, try again to get the DC.
*/
if (hr == DDERR_SURFACELOST) {
if (restore_all_ddraw_surfaces() == 0)
hr = IDirectDrawSurface2_GetDC(ddsurf, &dc);
}
if (hr == DD_OK)
return dc;
}
}
return NULL;
}
/* win_release_dc: (WinAPI)
* Releases device context of a video or system bitmap.
*/
void win_release_dc(BITMAP *bmp, HDC dc)
{
LPDIRECTDRAWSURFACE2 ddsurf;
HRESULT hr;
if (bmp) {
if (bmp->id & (BMP_ID_SYSTEM | BMP_ID_VIDEO)) {
ddsurf = DDRAW_SURFACE_OF(bmp)->id;
hr = IDirectDrawSurface2_ReleaseDC(ddsurf, dc);
/* If the surface has been lost, try to restore all surfaces
* and, on success, try again to release the DC.
*/
if (hr == DDERR_SURFACELOST) {
if (restore_all_ddraw_surfaces() == 0)
hr = IDirectDrawSurface2_ReleaseDC(ddsurf, dc);
}
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* 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.druid.timeline.partition;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Range;
import com.google.common.collect.RangeSet;
import org.apache.druid.data.input.InputRow;
import org.apache.druid.java.util.common.ISE;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* {@link ShardSpec} for range partitioning based on a single dimension
*/
public class SingleDimensionShardSpec implements ShardSpec
{
public static final int UNKNOWN_NUM_CORE_PARTITIONS = -1;
private final String dimension;
@Nullable
private final String start;
@Nullable
private final String end;
private final int partitionNum;
private final int numCorePartitions;
/**
* @param dimension partition dimension
* @param start inclusive start of this range
* @param end exclusive end of this range
* @param partitionNum unique ID for this shard
*/
@JsonCreator
public SingleDimensionShardSpec(
@JsonProperty("dimension") String dimension,
@JsonProperty("start") @Nullable String start,
@JsonProperty("end") @Nullable String end,
@JsonProperty("partitionNum") int partitionNum,
@JsonProperty("numCorePartitions") @Nullable Integer numCorePartitions // nullable for backward compatibility
)
{
Preconditions.checkArgument(partitionNum >= 0, "partitionNum >= 0");
this.dimension = Preconditions.checkNotNull(dimension, "dimension");
this.start = start;
this.end = end;
this.partitionNum = partitionNum;
this.numCorePartitions = numCorePartitions == null ? UNKNOWN_NUM_CORE_PARTITIONS : numCorePartitions;
}
@JsonProperty("dimension")
public String getDimension()
{
return dimension;
}
@Nullable
@JsonProperty("start")
public String getStart()
{
return start;
}
@Nullable
@JsonProperty("end")
public String getEnd()
{
return end;
}
@Override
@JsonProperty("partitionNum")
public int getPartitionNum()
{
return partitionNum;
}
@Override
@JsonProperty
public int getNumCorePartitions()
{
return numCorePartitions;
}
@Override
public ShardSpecLookup getLookup(final List<? extends ShardSpec> shardSpecs)
{
return createLookup(shardSpecs);
}
static ShardSpecLookup createLookup(List<? extends ShardSpec> shardSpecs)
{
return (long timestamp, InputRow row) -> {
for (ShardSpec spec : shardSpecs) {
if (((SingleDimensionShardSpec) spec).isInChunk(row)) {
return spec;
}
}
throw new ISE("row[%s] doesn't fit in any shard[%s]", row, shardSpecs);
};
}
@Override
public List<String> getDomainDimensions()
{
return ImmutableList.of(dimension);
}
private Range<String> getRange()
{
Range<String> range;
if (start == null && end == null) {
range = Range.all();
} else if (start == null) {
range = Range.atMost(end);
} else if (end == null) {
range = Range.atLeast(start);
} else {
range = Range.closed(start, end);
}
return range;
}
@Override
public boolean possibleInDomain(Map<String, RangeSet<String>> domain)
{
RangeSet<String> rangeSet = domain.get(dimension);
if (rangeSet == null) {
return true;
}
return !rangeSet.subRangeSet(getRange()).isEmpty();
}
@Override
public <T> PartitionChunk<T> createChunk(T obj)
{
if (numCorePartitions == UNKNOWN_NUM_CORE_PARTITIONS) {
return new StringPartitionChunk<>(start, end, partitionNum, obj);
} else {
return new NumberedPartitionChunk<>(partitionNum, numCorePartitions, obj);
}
}
@VisibleForTesting
boolean isInChunk(InputRow inputRow)
{
return isInChunk(dimension, start, end, inputRow);
}
private static boolean checkValue(@Nullable String start, @Nullable String end, String value)
{
if (value == null) {
return start == null;
}
if (start == null) {
return end == null || value.compareTo(end) < 0;
}
return value.compareTo(start) >= 0 &&
(end == null || value.compareTo(end) < 0);
}
public static boolean isInChunk(
String dimension,
@Nullable String start,
@Nullable String end,
InputRow inputRow
)
{
final List<String> values = inputRow.getDimension(dimension);
if (values == null || values.size() != 1) {
return checkValue(start, end, null);
} else {
return checkValue(start, end, values.get(0));
}
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SingleDimensionShardSpec shardSpec = (SingleDimensionShardSpec) o;
return partitionNum == shardSpec.partitionNum &&
numCorePartitions == shardSpec.numCorePartitions &&
Objects.equals(dimension, shardSpec.dimension) &&
Objects.equals(start, shardSpec.start) &&
Objects.equals(end, shardSpec.end);
}
@Override
public int hashCode()
{
return Objects.hash(dimension, start, end, partitionNum, numCorePartitions);
}
@Override
public String toString()
{
return "SingleDimensionShardSpec{" +
"dimension='" + dimension + '\'' +
", start='" + start + '\'' +
", end='" + end + '\'' +
", partitionNum=" + partitionNum +
", numCorePartitions=" + numCorePartitions +
'}';
}
}
| {
"pile_set_name": "Github"
} |
from glob import glob
import operator
import os
import humanize
import numpy
from pyspark import RDD
from scipy.sparse import csr_matrix
from sourced.ml.models import BOW, OrderedDocumentFrequencies
from sourced.ml.transformers import Indexer, Uast2BagFeatures
from sourced.ml.transformers.transformer import Transformer
class BOWWriter(Transformer):
DEFAULT_CHUNK_SIZE = 2 * 1000 * 1000 * 1000
def __init__(self, document_indexer: Indexer, df: OrderedDocumentFrequencies,
filename: str, chunk_size: int = DEFAULT_CHUNK_SIZE, **kwargs):
super().__init__(**kwargs)
self.document_indexer = document_indexer
self.df = df
self.filename = filename
self.chunk_size = chunk_size
def __getstate__(self):
state = super().__getstate__()
del state["document_indexer"]
del state["token_indexer"]
del state["df"]
return state
def __call__(self, head: RDD):
c = Uast2BagFeatures.Columns
self._log.info("Estimating the average bag size...")
avglen = head \
.map(lambda x: (x[c.document], 1)) \
.reduceByKey(operator.add) \
.map(lambda x: x[1])
if self.explained:
self._log.info("toDebugString():\n%s", avglen.toDebugString().decode())
avglen = avglen.mean()
self._log.info("Result: %.0f", avglen)
avgdocnamelen = numpy.mean([len(v) for v in self.document_indexer.value_to_index])
nparts = int(numpy.ceil(
len(self.document_indexer) * (avglen * (4 + 4) + avgdocnamelen) / self.chunk_size))
self._log.info("Estimated number of partitions: %d", nparts)
doc_index_to_name = {
index: name for name, index in self.document_indexer.value_to_index.items()}
tokens = self.df.tokens()
it = head \
.map(lambda x: (x[c.document], (x[c.token], x[c.value]))) \
.groupByKey() \
.repartition(nparts) \
.glom() \
.toLocalIterator()
if self.explained:
self._log.info("toDebugString():\n%s", it.toDebugString().decode())
ndocs = 0
self._log.info("Writing files to %s", self.filename)
for i, part in enumerate(it):
docs = [doc_index_to_name[p[0]] for p in part]
if not len(docs):
self._log.info("Batch %d is empty, skipping.", i + 1)
continue
size = sum(len(p[1]) for p in part)
data = numpy.zeros(size, dtype=numpy.float32)
indices = numpy.zeros(size, dtype=numpy.int32)
indptr = numpy.zeros(len(docs) + 1, dtype=numpy.int32)
pos = 0
for pi, (_, bag) in enumerate(part):
for tok, val in sorted(bag):
indices[pos] = tok
data[pos] = val
pos += 1
indptr[pi + 1] = indptr[pi] + len(bag)
assert pos == size
matrix = csr_matrix((data, indices, indptr), shape=(len(docs), len(tokens)))
filename = self.get_bow_file_name(self.filename, i)
BOW() \
.construct(docs, tokens, matrix) \
.save(filename, deps=(self.df,))
self._log.info("%d -> %s with %d documents, %d nnz (%s)",
i + 1, filename, len(docs), size,
humanize.naturalsize(os.path.getsize(filename)))
ndocs += len(docs)
self._log.info("Final number of documents: %d", ndocs)
def get_bow_file_name(self, base: str, index: int):
parent, full_name = os.path.split(base)
name, ext = os.path.splitext(full_name)
return os.path.join(parent, "%s_%03d%s" % (name, index + 1, ext))
class BOWLoader:
def __init__(self, glob_path):
self.files = glob(glob_path)
def __len__(self):
return len(self.files)
def __bool__(self):
return bool(self.files)
def __iter__(self):
return (BOW().load(path) for path in self.files)
| {
"pile_set_name": "Github"
} |
//
// Created by Akshay on 2/15/16.
//
#ifndef ANALYSIS_VERIFY_H
#define ANALYSIS_VERIFY_H
#include <iostream>
#include <fstream>
#include <unordered_set>
#include <unordered_map>
#include <vector>
#include <string>
#include <ctime>
#include "../protos/pvisit.pb.h"
#include "../protos/penums.pb.h"
#include <sys/fcntl.h>
#include <unistd.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include "glog/logging.h"
#include "../pystring/pystring.h"
#include "leveldb/db.h"
#include "../audit/auditor.h"
#include "../json11/json11.hpp"
namespace verify {
void code_verify(json11::Json config,std::string dataset);
void quick_verify(json11::Json config,std::string dataset);
}
#endif //ANALYSIS_VERIFY_H
| {
"pile_set_name": "Github"
} |
%module extern_throws
%{
#if defined(_MSC_VER)
#pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
#endif
%}
%inline %{
#include <exception>
extern int get() throw(std::exception);
%}
%{
int get() throw(std::exception) { return 0; }
%}
| {
"pile_set_name": "Github"
} |
---
layout: default
description: A one stop resource for fully identifying, exploiting, and escalating SQL injection vulnerabilities across various Database Management Systems.
title: NetSPI SQL Injection Wiki
---
<h2 id="header">Welcome to the NetSPI SQL Injection Wiki!</h2>
<div id="homeWrapper">
<p class="readableText">This wiki's mission is to be a one stop resource for fully identifying, exploiting, and escalating SQL injection vulnerabilities across various Database Management Systems (DBMS). This wiki assumes you have a basic understanding of SQL injection, please
go <a href="https://www.owasp.org/index.php/SQL_Injection" rel="noopener" target="_blank">here</a> for an introduction if you are unfamiliar.</p>
<p class="readableText">Below is an outline of the wiki's structure, laid out in the order of a normal escalation path. Certain queries may be version specific.</p>
<h3>Step 1: <a href="{{site.pagebase}}/detection">Injection Detection</a></h3>
<h3>Step 2: <a href="{{site.pagebase}}/dbmsIdentification/">DBMS Identification</a></h3>
<h3>Step 3: <a href="{{site.pagebase}}/injectionTypes/">Injection Types</a></h3>
<h3>Step 4: <a href="{{site.pagebase}}/injectionTechniques/">Injection Techniques</a></h3>
<h3>Step 5: <a href="{{site.pagebase}}/attackQueries/">Attack Queries</a></h3>
<p></p>
<h3>Contributing</h3>
<p>Please feel free to submit pull requests or issues on our <a href="https://github.com/NetSPI/SQLInjectionWiki" target="_blank" rel="noopener">Github</a> if you notice something that is missing or inaccurate.</p>
</div>
| {
"pile_set_name": "Github"
} |
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*
* @category Shopware
* @package Customer
* @subpackage CustumerStream
* @version $Id$
* @author shopware AG
*/
// {namespace name="backend/customer/view/main"}
// {block name="backend/customer/view/customer_stream/conditions/field/attribute_value"}
Ext.define('Shopware.apps.Customer.view.customer_stream.conditions.field.AttributeValue', {
extend: 'Ext.form.FieldContainer',
layout: { type: 'vbox', align: 'stretch' },
mixins: {
formField: 'Ext.form.field.Base'
},
initComponent: function() {
var me = this;
me.items = me.createItems();
me.operator = me.operatorField.getValue();
me.operatorField.on('change', function (field, value) {
me.operator = value;
if (value === 'BETWEEN') {
me.betweenContainer.show();
me.valueField.hide();
me.fromField.setDisabled(false);
me.toField.setDisabled(false);
me.valueField.setDisabled(true);
} else {
me.betweenContainer.hide();
me.valueField.show();
me.fromField.setDisabled(true);
me.toField.setDisabled(true);
me.valueField.setDisabled(false);
}
});
me.callParent(arguments);
},
createItems: function () {
var me = this;
return [
me.createValueField(),
me.createBetweenContainer()
];
},
getValue: function() {
var value = this.valueField.getValue();
if (this.operator === 'BETWEEN') {
return {
min: this.fromField.getValue(),
max: this.toField.getValue()
};
} else if (this.operator === 'IN') {
return value.split(',');
}
return value;
},
setValue: function(value) {
var me = this;
if (Ext.isObject(value)) {
me.fromField.setValue(value.min);
me.toField.setValue(value.max);
return;
}
me.valueField.setValue(value);
},
getSubmitData: function() {
var result = {};
result[this.name] = this.getValue();
return result;
},
createFromField: function() {
var me = this;
me.fromField = Ext.create('Ext.form.field.Number', {
fieldLabel: '{s name="attribute/from_text"}{/s}',
allowBlank: false,
width: '100%',
listeners: {
change: function() {
me.toField.setMinValue(this.getValue() + 1);
}
}
});
return me.fromField;
},
createToField: function() {
var me = this;
me.toField = Ext.create('Ext.form.field.Number', {
fieldLabel: '{s name="attribute/to_text"}{/s}',
allowBlank: false,
width: '100%',
listeners: {
change: function() {
me.fromField.setMaxValue(this.getValue() - 1);
}
}
});
return me.toField;
},
createValueField: function () {
var me = this;
me.valueField = Ext.create('Ext.form.field.Text', {
fieldLabel: '{s name="attribute/value"}{/s}',
allowBlank: false,
name: 'value'
});
return me.valueField;
},
createBetweenContainer: function () {
var me = this;
me.betweenContainer = Ext.create('Ext.container.Container', {
layout: { type: 'vbox' },
hidden: true,
items: [me.createFromField(), me.createToField()]
});
return me.betweenContainer;
}
});
// {/block}
| {
"pile_set_name": "Github"
} |
package secrets
import (
"context"
"errors"
"testing"
"github.com/kyma-project/kyma/components/application-registry/internal/apperrors"
"github.com/kyma-project/kyma/components/application-registry/internal/metadata/secrets/mocks"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
)
func TestRepository_Create(t *testing.T) {
t.Run("should create secret", func(t *testing.T) {
// given
secretsManagerMock := &mocks.Manager{}
repository := NewRepository(secretsManagerMock)
secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(secret, nil)
// when
err := repository.Create("app", "appUID", "new-secret", "secretId", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
// then
assert.NoError(t, err)
secretsManagerMock.AssertExpectations(t)
})
t.Run("should fail if unable to create secret", func(t *testing.T) {
// given
secretsManagerMock := &mocks.Manager{}
repository := NewRepository(secretsManagerMock)
secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(nil, errors.New("some error"))
// when
err := repository.Create("app", "appUID", "new-secret", "secretId", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
// then
require.Error(t, err)
assert.Equal(t, apperrors.CodeInternal, err.Code())
secretsManagerMock.AssertExpectations(t)
})
t.Run("should return already exists if secret was already created", func(t *testing.T) {
// given
secretsManagerMock := &mocks.Manager{}
repository := NewRepository(secretsManagerMock)
secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(nil, k8serrors.NewAlreadyExists(schema.GroupResource{}, ""))
// when
err := repository.Create("app", "appUID", "new-secret", "secretId", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
// then
require.Error(t, err)
assert.Equal(t, apperrors.CodeAlreadyExists, err.Code())
secretsManagerMock.AssertExpectations(t)
})
}
func TestRepository_Get(t *testing.T) {
t.Run("should get given secret", func(t *testing.T) {
// given
secretsManagerMock := &mocks.Manager{}
repository := NewRepository(secretsManagerMock)
secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
secretsManagerMock.On("Get", context.Background(), "new-secret", metav1.GetOptions{}).Return(secret, nil)
// when
data, err := repository.Get("new-secret")
// then
assert.NoError(t, err)
assert.Equal(t, []byte("testValue1"), data["testKey1"])
assert.Equal(t, []byte("testValue2"), data["testKey2"])
secretsManagerMock.AssertExpectations(t)
})
t.Run("should return an error in case fetching fails", func(t *testing.T) {
// given
secretsManagerMock := &mocks.Manager{}
repository := NewRepository(secretsManagerMock)
secretsManagerMock.On("Get", context.Background(), "secret-name", metav1.GetOptions{}).Return(
nil,
errors.New("some error"))
// when
data, err := repository.Get("secret-name")
// then
assert.Error(t, err)
assert.Equal(t, apperrors.CodeInternal, err.Code())
assert.NotEmpty(t, err.Error())
assert.Equal(t, []byte(nil), data["testKey1"])
assert.Equal(t, []byte(nil), data["testKey2"])
secretsManagerMock.AssertExpectations(t)
})
t.Run("should return not found if secret does not exist", func(t *testing.T) {
// given
secretsManagerMock := &mocks.Manager{}
repository := NewRepository(secretsManagerMock)
secretsManagerMock.On("Get", context.Background(), "secret-name", metav1.GetOptions{}).Return(
nil,
k8serrors.NewNotFound(schema.GroupResource{},
""))
// when
data, err := repository.Get("secret-name")
// then
assert.Error(t, err)
assert.Equal(t, apperrors.CodeNotFound, err.Code())
assert.NotEmpty(t, err.Error())
assert.Equal(t, []byte(nil), data["testKey1"])
assert.Equal(t, []byte(nil), data["testKey2"])
secretsManagerMock.AssertExpectations(t)
})
}
func TestRepository_Delete(t *testing.T) {
t.Run("should delete given secret", func(t *testing.T) {
// given
secretsManagerMock := &mocks.Manager{}
repository := NewRepository(secretsManagerMock)
secretsManagerMock.On("Delete", context.Background(), "test-secret", metav1.DeleteOptions{}).Return(
nil)
// when
err := repository.Delete("test-secret")
// then
assert.NoError(t, err)
secretsManagerMock.AssertExpectations(t)
})
t.Run("should return error if deletion fails", func(t *testing.T) {
// given
secretsManagerMock := &mocks.Manager{}
repository := NewRepository(secretsManagerMock)
secretsManagerMock.On("Delete", context.Background(), "test-secret", metav1.DeleteOptions{}).Return(
errors.New("some error"))
// when
err := repository.Delete("test-secret")
// then
assert.Error(t, err)
assert.Equal(t, apperrors.CodeInternal, err.Code())
assert.NotEmpty(t, err.Error())
secretsManagerMock.AssertExpectations(t)
})
t.Run("should not return error if secret does not exist", func(t *testing.T) {
// given
secretsManagerMock := &mocks.Manager{}
repository := NewRepository(secretsManagerMock)
secretsManagerMock.On("Delete", context.Background(), "test-secret", metav1.DeleteOptions{}).Return(
k8serrors.NewNotFound(schema.GroupResource{}, ""))
// when
err := repository.Delete("test-secret")
// then
assert.NoError(t, err)
secretsManagerMock.AssertExpectations(t)
})
}
func TestRepository_Upsert(t *testing.T) {
t.Run("should update secret if it exists", func(t *testing.T) {
// given
secretsManagerMock := &mocks.Manager{}
repository := NewRepository(secretsManagerMock)
secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
secretsManagerMock.On("Update", context.Background(), secret, metav1.UpdateOptions{}).Return(
secret, nil)
// when
err := repository.Upsert("app", "appUID", "new-secret", "secretId", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
// then
assert.NoError(t, err)
secretsManagerMock.AssertExpectations(t)
})
t.Run("should create secret if it does not exist", func(t *testing.T) {
// given
secretsManagerMock := &mocks.Manager{}
repository := NewRepository(secretsManagerMock)
secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
secretsManagerMock.On("Update", context.Background(), secret, metav1.UpdateOptions{}).Return(
nil, k8serrors.NewNotFound(schema.GroupResource{}, ""))
secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(secret, nil)
// when
err := repository.Upsert("app", "appUID", "new-secret", "secretId", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
// then
assert.NoError(t, err)
secretsManagerMock.AssertExpectations(t)
})
t.Run("should return an error if update fails", func(t *testing.T) {
// given
secretsManagerMock := &mocks.Manager{}
repository := NewRepository(secretsManagerMock)
secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
secretsManagerMock.On("Update", context.Background(), secret, metav1.UpdateOptions{}).Return(nil, errors.New("some error"))
// when
err := repository.Upsert("app", "appUID", "new-secret", "secretId", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
// then
assert.Error(t, err)
assert.Equal(t, apperrors.CodeInternal, err.Code())
assert.NotEmpty(t, err.Error())
secretsManagerMock.AssertNotCalled(t, "Create", mock.AnythingOfType("*v1.Secret"))
secretsManagerMock.AssertExpectations(t)
})
t.Run("should return an error if create fails", func(t *testing.T) {
// given
secretsManagerMock := &mocks.Manager{}
repository := NewRepository(secretsManagerMock)
secret := makeSecret("new-secret", "secretId", "app", "appUID", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
secretsManagerMock.On("Update", context.Background(), secret, metav1.UpdateOptions{}).Return(
nil, k8serrors.NewNotFound(schema.GroupResource{}, ""))
secretsManagerMock.On("Create", context.Background(), secret, metav1.CreateOptions{}).Return(secret, errors.New("some error"))
// when
err := repository.Upsert("app", "appUID", "new-secret", "secretId", map[string][]byte{
"testKey1": []byte("testValue1"),
"testKey2": []byte("testValue2"),
})
// then
assert.Error(t, err)
assert.Equal(t, apperrors.CodeInternal, err.Code())
assert.NotEmpty(t, err.Error())
secretsManagerMock.AssertExpectations(t)
})
}
| {
"pile_set_name": "Github"
} |
input AddTodoInput {
id: String!
text: String!
userId: ID!
clientMutationId: String
}
type AddTodoPayload {
todoEdge: TodoEdge!
user: User!
clientMutationId: String
}
input ChangeTodoStatusInput {
complete: Boolean!
id: ID!
userId: ID!
clientMutationId: String
}
type ChangeTodoStatusPayload {
todo: Todo!
user: User!
clientMutationId: String
}
input MarkAllTodosInput {
complete: Boolean!
userId: ID!
clientMutationId: String
}
type MarkAllTodosPayload {
changedTodos: [Todo!]
user: User!
clientMutationId: String
}
type Mutation {
addTodo(input: AddTodoInput!): AddTodoPayload
changeTodoStatus(input: ChangeTodoStatusInput!): ChangeTodoStatusPayload
markAllTodos(input: MarkAllTodosInput!): MarkAllTodosPayload
removeCompletedTodos(input: RemoveCompletedTodosInput!): RemoveCompletedTodosPayload
removeTodo(input: RemoveTodoInput!): RemoveTodoPayload
renameTodo(input: RenameTodoInput!): RenameTodoPayload
}
"""An object with an ID"""
interface Node {
"""The id of the object."""
id: ID!
}
"""Information about pagination in a connection."""
type PageInfo {
"""When paginating forwards, are there more items?"""
hasNextPage: Boolean!
"""When paginating backwards, are there more items?"""
hasPreviousPage: Boolean!
"""When paginating backwards, the cursor to continue."""
startCursor: String
"""When paginating forwards, the cursor to continue."""
endCursor: String
}
type Query {
user(id: String): User
"""Fetches an object given its ID"""
node(
"""The ID of an object"""
id: ID!
): Node
}
input RemoveCompletedTodosInput {
userId: ID!
clientMutationId: String
}
type RemoveCompletedTodosPayload {
deletedTodoIds: [String!]
user: User!
clientMutationId: String
}
input RemoveTodoInput {
id: ID!
userId: ID!
clientMutationId: String
}
type RemoveTodoPayload {
deletedTodoId: ID!
user: User!
clientMutationId: String
}
input RenameTodoInput {
id: ID!
text: String!
clientMutationId: String
}
type RenameTodoPayload {
todo: Todo!
clientMutationId: String
}
type Todo {
"""The ID of an object"""
id: String!
text: String!
complete: Boolean!
}
"""A connection to a list of items."""
type TodoConnection {
"""Information to aid in pagination."""
pageInfo: PageInfo!
"""A list of edges."""
edges: [TodoEdge]
}
"""An edge in a connection."""
type TodoEdge {
"""The item at the end of the edge"""
node: Todo
"""A cursor for use in pagination"""
cursor: String!
}
type User implements Node {
"""The ID of an object"""
id: ID!
userId: String!
todos(status: String = "any", after: String, first: Int, before: String, last: Int): TodoConnection
totalCount: Int!
completedCount: Int!
}
| {
"pile_set_name": "Github"
} |
<footer>
<p class="copyright text-muted">{{ .Site.Params.copyright | default "© All rights reserved. Powered by [Hugo](https://gohugo.io) and [Minimal](https://github.com/calintat/minimal)" | markdownify }}</p>
</footer>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#define test(x) _Generic((x), _Bool : 1, char : 2, int : 3, default : 4)
void test_typename(void) {
char s;
int y;
int x = test(s);
int z = test(y);
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) Facebook, Inc. and its affiliates.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="qunit.css" type="text/css"/>
<script type="text/javascript" src="qunit.js"></script>
<script type="text/javascript" src="../dist/es5/uri.all.min.js"></script>
<script type="text/javascript" src="tests.js"></script>
</head>
<body>
<h1 id="qunit-header">URI.js Test Suite</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
</body>
</html>
| {
"pile_set_name": "Github"
} |
// ***************************************************************************
// bamtools_random.cpp (c) 2010 Derek Barnett, Erik Garrison
// Marth Lab, Department of Biology, Boston College
// ---------------------------------------------------------------------------
// Last modified: 10 December 2012 (DB)
// ---------------------------------------------------------------------------
// Grab a random subset of alignments (testing tool)
// ***************************************************************************
#include "bamtools_random.h"
#include <api/BamMultiReader.h>
#include <api/BamWriter.h>
#include <utils/bamtools_options.h>
#include <utils/bamtools_utilities.h>
using namespace BamTools;
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
namespace BamTools {
// define constants
const unsigned int RANDOM_MAX_ALIGNMENT_COUNT = 10000;
// utility methods for RandomTool
int getRandomInt(const int& lowerBound, const int& upperBound) {
const int range = (upperBound - lowerBound) + 1;
return ( lowerBound + (int)(range * (double)rand()/((double)RAND_MAX + 1)) );
}
} // namespace BamTools
// ---------------------------------------------
// RandomSettings implementation
struct RandomTool::RandomSettings {
// flags
bool HasAlignmentCount;
bool HasInput;
bool HasInputFilelist;
bool HasOutput;
bool HasRegion;
bool IsForceCompression;
// parameters
unsigned int AlignmentCount;
vector<string> InputFiles;
string InputFilelist;
string OutputFilename;
string Region;
// constructor
RandomSettings(void)
: HasAlignmentCount(false)
, HasInput(false)
, HasInputFilelist(false)
, HasOutput(false)
, HasRegion(false)
, IsForceCompression(false)
, AlignmentCount(RANDOM_MAX_ALIGNMENT_COUNT)
, OutputFilename(Options::StandardOut())
{ }
};
// ---------------------------------------------
// RandomToolPrivate implementation
struct RandomTool::RandomToolPrivate {
// ctor & dtor
public:
RandomToolPrivate(RandomTool::RandomSettings* settings)
: m_settings(settings)
{ }
~RandomToolPrivate(void) { }
// interface
public:
bool Run(void);
// data members
private:
RandomTool::RandomSettings* m_settings;
};
bool RandomTool::RandomToolPrivate::Run(void) {
// set to default stdin if no input files provided
if ( !m_settings->HasInput && !m_settings->HasInputFilelist )
m_settings->InputFiles.push_back(Options::StandardIn());
// add files in the filelist to the input file list
if ( m_settings->HasInputFilelist ) {
ifstream filelist(m_settings->InputFilelist.c_str(), ios::in);
if ( !filelist.is_open() ) {
cerr << "bamtools random ERROR: could not open input BAM file list... Aborting." << endl;
return false;
}
string line;
while ( getline(filelist, line) )
m_settings->InputFiles.push_back(line);
}
// open our reader
BamMultiReader reader;
if ( !reader.Open(m_settings->InputFiles) ) {
cerr << "bamtools random ERROR: could not open input BAM file(s)... Aborting." << endl;
return false;
}
// look up index files for all BAM files
reader.LocateIndexes();
// make sure index data is available
if ( !reader.HasIndexes() ) {
cerr << "bamtools random ERROR: could not load index data for all input BAM file(s)... Aborting." << endl;
reader.Close();
return false;
}
// get BamReader metadata
const string headerText = reader.GetHeaderText();
const RefVector references = reader.GetReferenceData();
if ( references.empty() ) {
cerr << "bamtools random ERROR: no reference data available... Aborting." << endl;
reader.Close();
return false;
}
// determine compression mode for BamWriter
bool writeUncompressed = ( m_settings->OutputFilename == Options::StandardOut() &&
!m_settings->IsForceCompression );
BamWriter::CompressionMode compressionMode = BamWriter::Compressed;
if ( writeUncompressed ) compressionMode = BamWriter::Uncompressed;
// open BamWriter
BamWriter writer;
writer.SetCompressionMode(compressionMode);
if ( !writer.Open(m_settings->OutputFilename, headerText, references) ) {
cerr << "bamtools random ERROR: could not open " << m_settings->OutputFilename
<< " for writing... Aborting." << endl;
reader.Close();
return false;
}
// if user specified a REGION constraint, attempt to parse REGION string
BamRegion region;
if ( m_settings->HasRegion && !Utilities::ParseRegionString(m_settings->Region, reader, region) ) {
cerr << "bamtools random ERROR: could not parse REGION: " << m_settings->Region << endl;
cerr << "Check that REGION is in valid format (see documentation) and that the coordinates are valid"
<< endl;
reader.Close();
writer.Close();
return false;
}
// seed our random number generator
srand( time(NULL) );
// grab random alignments
BamAlignment al;
unsigned int i = 0;
while ( i < m_settings->AlignmentCount ) {
int randomRefId = 0;
int randomPosition = 0;
// use REGION constraints to select random refId & position
if ( m_settings->HasRegion ) {
// select a random refId
randomRefId = getRandomInt(region.LeftRefID, region.RightRefID);
// select a random position based on randomRefId
const int lowerBoundPosition = ( (randomRefId == region.LeftRefID)
? region.LeftPosition
: 0 );
const int upperBoundPosition = ( (randomRefId == region.RightRefID)
? region.RightPosition
: (references.at(randomRefId).RefLength - 1) );
randomPosition = getRandomInt(lowerBoundPosition, upperBoundPosition);
}
// otherwise select from all possible random refId & position
else {
// select random refId
randomRefId = getRandomInt(0, (int)references.size() - 1);
// select random position based on randomRefId
const int lowerBoundPosition = 0;
const int upperBoundPosition = references.at(randomRefId).RefLength - 1;
randomPosition = getRandomInt(lowerBoundPosition, upperBoundPosition);
}
// if jump & read successful, save first alignment that overlaps random refId & position
if ( reader.Jump(randomRefId, randomPosition) ) {
while ( reader.GetNextAlignmentCore(al) ) {
if ( al.RefID == randomRefId && al.Position >= randomPosition ) {
writer.SaveAlignment(al);
++i;
break;
}
}
}
}
// cleanup & exit
reader.Close();
writer.Close();
return true;
}
// ---------------------------------------------
// RandomTool implementation
RandomTool::RandomTool(void)
: AbstractTool()
, m_settings(new RandomSettings)
, m_impl(0)
{
// set program details
Options::SetProgramInfo("bamtools random", "grab a random subset of alignments",
"[-in <filename> -in <filename> ... | -list <filelist>] [-out <filename>] [-forceCompression] [-n] [-region <REGION>]");
// set up options
OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
Options::AddValueOption("-in", "BAM filename", "the input BAM file", "", m_settings->HasInput, m_settings->InputFiles, IO_Opts, Options::StandardIn());
Options::AddValueOption("-list", "filename", "the input BAM file list, one line per file", "", m_settings->HasInputFilelist, m_settings->InputFilelist, IO_Opts);
Options::AddValueOption("-out", "BAM filename", "the output BAM file", "", m_settings->HasOutput, m_settings->OutputFilename, IO_Opts, Options::StandardOut());
Options::AddOption("-forceCompression", "if results are sent to stdout (like when piping to another tool), default behavior is to leave output uncompressed. Use this flag to override and force compression", m_settings->IsForceCompression, IO_Opts);
Options::AddValueOption("-region", "REGION", "only pull random alignments from within this genomic region. Index file is recommended for better performance, and is used automatically if it exists. See \'bamtools help index\' for more details on creating one", "", m_settings->HasRegion, m_settings->Region, IO_Opts);
OptionGroup* SettingsOpts = Options::CreateOptionGroup("Settings");
Options::AddValueOption("-n", "count", "number of alignments to grab. Note - no duplicate checking is performed", "", m_settings->HasAlignmentCount, m_settings->AlignmentCount, SettingsOpts, RANDOM_MAX_ALIGNMENT_COUNT);
}
RandomTool::~RandomTool(void) {
delete m_settings;
m_settings = 0;
delete m_impl;
m_impl = 0;
}
int RandomTool::Help(void) {
Options::DisplayHelp();
return 0;
}
int RandomTool::Run(int argc, char* argv[]) {
// parse command line arguments
Options::Parse(argc, argv, 1);
// initialize RandomTool with settings
m_impl = new RandomToolPrivate(m_settings);
// run RandomTool, return success/fail
if ( m_impl->Run() )
return 0;
else
return 1;
}
| {
"pile_set_name": "Github"
} |
/*
* ALSA driver for ICEnsemble VT17xx
*
* Lowlevel functions for WM8776 codec
*
* Copyright (c) 2012 Ondrej Zary <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/delay.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/tlv.h>
#include "wm8776.h"
/* low-level access */
static void snd_wm8776_write(struct snd_wm8776 *wm, u16 addr, u16 data)
{
u8 bus_addr = addr << 1 | data >> 8; /* addr + 9th data bit */
u8 bus_data = data & 0xff; /* remaining 8 data bits */
if (addr < WM8776_REG_RESET)
wm->regs[addr] = data;
wm->ops.write(wm, bus_addr, bus_data);
}
/* register-level functions */
static void snd_wm8776_activate_ctl(struct snd_wm8776 *wm,
const char *ctl_name,
bool active)
{
struct snd_card *card = wm->card;
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
struct snd_ctl_elem_id elem_id;
unsigned int index_offset;
memset(&elem_id, 0, sizeof(elem_id));
strlcpy(elem_id.name, ctl_name, sizeof(elem_id.name));
elem_id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
kctl = snd_ctl_find_id(card, &elem_id);
if (!kctl)
return;
index_offset = snd_ctl_get_ioff(kctl, &kctl->id);
vd = &kctl->vd[index_offset];
if (active)
vd->access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
else
vd->access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_INFO, &kctl->id);
}
static void snd_wm8776_update_agc_ctl(struct snd_wm8776 *wm)
{
int i, flags_on = 0, flags_off = 0;
switch (wm->agc_mode) {
case WM8776_AGC_OFF:
flags_off = WM8776_FLAG_LIM | WM8776_FLAG_ALC;
break;
case WM8776_AGC_LIM:
flags_off = WM8776_FLAG_ALC;
flags_on = WM8776_FLAG_LIM;
break;
case WM8776_AGC_ALC_R:
case WM8776_AGC_ALC_L:
case WM8776_AGC_ALC_STEREO:
flags_off = WM8776_FLAG_LIM;
flags_on = WM8776_FLAG_ALC;
break;
}
for (i = 0; i < WM8776_CTL_COUNT; i++)
if (wm->ctl[i].flags & flags_off)
snd_wm8776_activate_ctl(wm, wm->ctl[i].name, false);
else if (wm->ctl[i].flags & flags_on)
snd_wm8776_activate_ctl(wm, wm->ctl[i].name, true);
}
static void snd_wm8776_set_agc(struct snd_wm8776 *wm, u16 agc, u16 nothing)
{
u16 alc1 = wm->regs[WM8776_REG_ALCCTRL1] & ~WM8776_ALC1_LCT_MASK;
u16 alc2 = wm->regs[WM8776_REG_ALCCTRL2] & ~WM8776_ALC2_LCEN;
switch (agc) {
case 0: /* Off */
wm->agc_mode = WM8776_AGC_OFF;
break;
case 1: /* Limiter */
alc2 |= WM8776_ALC2_LCEN;
wm->agc_mode = WM8776_AGC_LIM;
break;
case 2: /* ALC Right */
alc1 |= WM8776_ALC1_LCSEL_ALCR;
alc2 |= WM8776_ALC2_LCEN;
wm->agc_mode = WM8776_AGC_ALC_R;
break;
case 3: /* ALC Left */
alc1 |= WM8776_ALC1_LCSEL_ALCL;
alc2 |= WM8776_ALC2_LCEN;
wm->agc_mode = WM8776_AGC_ALC_L;
break;
case 4: /* ALC Stereo */
alc1 |= WM8776_ALC1_LCSEL_ALCSTEREO;
alc2 |= WM8776_ALC2_LCEN;
wm->agc_mode = WM8776_AGC_ALC_STEREO;
break;
}
snd_wm8776_write(wm, WM8776_REG_ALCCTRL1, alc1);
snd_wm8776_write(wm, WM8776_REG_ALCCTRL2, alc2);
snd_wm8776_update_agc_ctl(wm);
}
static void snd_wm8776_get_agc(struct snd_wm8776 *wm, u16 *mode, u16 *nothing)
{
*mode = wm->agc_mode;
}
/* mixer controls */
static const DECLARE_TLV_DB_SCALE(wm8776_hp_tlv, -7400, 100, 1);
static const DECLARE_TLV_DB_SCALE(wm8776_dac_tlv, -12750, 50, 1);
static const DECLARE_TLV_DB_SCALE(wm8776_adc_tlv, -10350, 50, 1);
static const DECLARE_TLV_DB_SCALE(wm8776_lct_tlv, -1600, 100, 0);
static const DECLARE_TLV_DB_SCALE(wm8776_maxgain_tlv, 0, 400, 0);
static const DECLARE_TLV_DB_SCALE(wm8776_ngth_tlv, -7800, 600, 0);
static const DECLARE_TLV_DB_SCALE(wm8776_maxatten_lim_tlv, -1200, 100, 0);
static const DECLARE_TLV_DB_SCALE(wm8776_maxatten_alc_tlv, -2100, 400, 0);
static struct snd_wm8776_ctl snd_wm8776_default_ctl[WM8776_CTL_COUNT] = {
[WM8776_CTL_DAC_VOL] = {
.name = "Master Playback Volume",
.type = SNDRV_CTL_ELEM_TYPE_INTEGER,
.tlv = wm8776_dac_tlv,
.reg1 = WM8776_REG_DACLVOL,
.reg2 = WM8776_REG_DACRVOL,
.mask1 = WM8776_DACVOL_MASK,
.mask2 = WM8776_DACVOL_MASK,
.max = 0xff,
.flags = WM8776_FLAG_STEREO | WM8776_FLAG_VOL_UPDATE,
},
[WM8776_CTL_DAC_SW] = {
.name = "Master Playback Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_DACCTRL1,
.reg2 = WM8776_REG_DACCTRL1,
.mask1 = WM8776_DAC_PL_LL,
.mask2 = WM8776_DAC_PL_RR,
.flags = WM8776_FLAG_STEREO,
},
[WM8776_CTL_DAC_ZC_SW] = {
.name = "Master Zero Cross Detect Playback Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_DACCTRL1,
.mask1 = WM8776_DAC_DZCEN,
},
[WM8776_CTL_HP_VOL] = {
.name = "Headphone Playback Volume",
.type = SNDRV_CTL_ELEM_TYPE_INTEGER,
.tlv = wm8776_hp_tlv,
.reg1 = WM8776_REG_HPLVOL,
.reg2 = WM8776_REG_HPRVOL,
.mask1 = WM8776_HPVOL_MASK,
.mask2 = WM8776_HPVOL_MASK,
.min = 0x2f,
.max = 0x7f,
.flags = WM8776_FLAG_STEREO | WM8776_FLAG_VOL_UPDATE,
},
[WM8776_CTL_HP_SW] = {
.name = "Headphone Playback Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_PWRDOWN,
.mask1 = WM8776_PWR_HPPD,
.flags = WM8776_FLAG_INVERT,
},
[WM8776_CTL_HP_ZC_SW] = {
.name = "Headphone Zero Cross Detect Playback Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_HPLVOL,
.reg2 = WM8776_REG_HPRVOL,
.mask1 = WM8776_VOL_HPZCEN,
.mask2 = WM8776_VOL_HPZCEN,
.flags = WM8776_FLAG_STEREO,
},
[WM8776_CTL_AUX_SW] = {
.name = "AUX Playback Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_OUTMUX,
.mask1 = WM8776_OUTMUX_AUX,
},
[WM8776_CTL_BYPASS_SW] = {
.name = "Bypass Playback Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_OUTMUX,
.mask1 = WM8776_OUTMUX_BYPASS,
},
[WM8776_CTL_DAC_IZD_SW] = {
.name = "Infinite Zero Detect Playback Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_DACCTRL1,
.mask1 = WM8776_DAC_IZD,
},
[WM8776_CTL_PHASE_SW] = {
.name = "Phase Invert Playback Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_PHASESWAP,
.reg2 = WM8776_REG_PHASESWAP,
.mask1 = WM8776_PHASE_INVERTL,
.mask2 = WM8776_PHASE_INVERTR,
.flags = WM8776_FLAG_STEREO,
},
[WM8776_CTL_DEEMPH_SW] = {
.name = "Deemphasis Playback Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_DACCTRL2,
.mask1 = WM8776_DAC2_DEEMPH,
},
[WM8776_CTL_ADC_VOL] = {
.name = "Input Capture Volume",
.type = SNDRV_CTL_ELEM_TYPE_INTEGER,
.tlv = wm8776_adc_tlv,
.reg1 = WM8776_REG_ADCLVOL,
.reg2 = WM8776_REG_ADCRVOL,
.mask1 = WM8776_ADC_GAIN_MASK,
.mask2 = WM8776_ADC_GAIN_MASK,
.max = 0xff,
.flags = WM8776_FLAG_STEREO | WM8776_FLAG_VOL_UPDATE,
},
[WM8776_CTL_ADC_SW] = {
.name = "Input Capture Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_ADCMUX,
.reg2 = WM8776_REG_ADCMUX,
.mask1 = WM8776_ADC_MUTEL,
.mask2 = WM8776_ADC_MUTER,
.flags = WM8776_FLAG_STEREO | WM8776_FLAG_INVERT,
},
[WM8776_CTL_INPUT1_SW] = {
.name = "AIN1 Capture Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_ADCMUX,
.mask1 = WM8776_ADC_MUX_AIN1,
},
[WM8776_CTL_INPUT2_SW] = {
.name = "AIN2 Capture Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_ADCMUX,
.mask1 = WM8776_ADC_MUX_AIN2,
},
[WM8776_CTL_INPUT3_SW] = {
.name = "AIN3 Capture Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_ADCMUX,
.mask1 = WM8776_ADC_MUX_AIN3,
},
[WM8776_CTL_INPUT4_SW] = {
.name = "AIN4 Capture Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_ADCMUX,
.mask1 = WM8776_ADC_MUX_AIN4,
},
[WM8776_CTL_INPUT5_SW] = {
.name = "AIN5 Capture Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_ADCMUX,
.mask1 = WM8776_ADC_MUX_AIN5,
},
[WM8776_CTL_AGC_SEL] = {
.name = "AGC Select Capture Enum",
.type = SNDRV_CTL_ELEM_TYPE_ENUMERATED,
.enum_names = { "Off", "Limiter", "ALC Right", "ALC Left",
"ALC Stereo" },
.max = 5, /* .enum_names item count */
.set = snd_wm8776_set_agc,
.get = snd_wm8776_get_agc,
},
[WM8776_CTL_LIM_THR] = {
.name = "Limiter Threshold Capture Volume",
.type = SNDRV_CTL_ELEM_TYPE_INTEGER,
.tlv = wm8776_lct_tlv,
.reg1 = WM8776_REG_ALCCTRL1,
.mask1 = WM8776_ALC1_LCT_MASK,
.max = 15,
.flags = WM8776_FLAG_LIM,
},
[WM8776_CTL_LIM_ATK] = {
.name = "Limiter Attack Time Capture Enum",
.type = SNDRV_CTL_ELEM_TYPE_ENUMERATED,
.enum_names = { "0.25 ms", "0.5 ms", "1 ms", "2 ms", "4 ms",
"8 ms", "16 ms", "32 ms", "64 ms", "128 ms", "256 ms" },
.max = 11, /* .enum_names item count */
.reg1 = WM8776_REG_ALCCTRL3,
.mask1 = WM8776_ALC3_ATK_MASK,
.flags = WM8776_FLAG_LIM,
},
[WM8776_CTL_LIM_DCY] = {
.name = "Limiter Decay Time Capture Enum",
.type = SNDRV_CTL_ELEM_TYPE_ENUMERATED,
.enum_names = { "1.2 ms", "2.4 ms", "4.8 ms", "9.6 ms",
"19.2 ms", "38.4 ms", "76.8 ms", "154 ms", "307 ms",
"614 ms", "1.23 s" },
.max = 11, /* .enum_names item count */
.reg1 = WM8776_REG_ALCCTRL3,
.mask1 = WM8776_ALC3_DCY_MASK,
.flags = WM8776_FLAG_LIM,
},
[WM8776_CTL_LIM_TRANWIN] = {
.name = "Limiter Transient Window Capture Enum",
.type = SNDRV_CTL_ELEM_TYPE_ENUMERATED,
.enum_names = { "0 us", "62.5 us", "125 us", "250 us", "500 us",
"1 ms", "2 ms", "4 ms" },
.max = 8, /* .enum_names item count */
.reg1 = WM8776_REG_LIMITER,
.mask1 = WM8776_LIM_TRANWIN_MASK,
.flags = WM8776_FLAG_LIM,
},
[WM8776_CTL_LIM_MAXATTN] = {
.name = "Limiter Maximum Attenuation Capture Volume",
.type = SNDRV_CTL_ELEM_TYPE_INTEGER,
.tlv = wm8776_maxatten_lim_tlv,
.reg1 = WM8776_REG_LIMITER,
.mask1 = WM8776_LIM_MAXATTEN_MASK,
.min = 3,
.max = 12,
.flags = WM8776_FLAG_LIM | WM8776_FLAG_INVERT,
},
[WM8776_CTL_ALC_TGT] = {
.name = "ALC Target Level Capture Volume",
.type = SNDRV_CTL_ELEM_TYPE_INTEGER,
.tlv = wm8776_lct_tlv,
.reg1 = WM8776_REG_ALCCTRL1,
.mask1 = WM8776_ALC1_LCT_MASK,
.max = 15,
.flags = WM8776_FLAG_ALC,
},
[WM8776_CTL_ALC_ATK] = {
.name = "ALC Attack Time Capture Enum",
.type = SNDRV_CTL_ELEM_TYPE_ENUMERATED,
.enum_names = { "8.40 ms", "16.8 ms", "33.6 ms", "67.2 ms",
"134 ms", "269 ms", "538 ms", "1.08 s", "2.15 s",
"4.3 s", "8.6 s" },
.max = 11, /* .enum_names item count */
.reg1 = WM8776_REG_ALCCTRL3,
.mask1 = WM8776_ALC3_ATK_MASK,
.flags = WM8776_FLAG_ALC,
},
[WM8776_CTL_ALC_DCY] = {
.name = "ALC Decay Time Capture Enum",
.type = SNDRV_CTL_ELEM_TYPE_ENUMERATED,
.enum_names = { "33.5 ms", "67.0 ms", "134 ms", "268 ms",
"536 ms", "1.07 s", "2.14 s", "4.29 s", "8.58 s",
"17.2 s", "34.3 s" },
.max = 11, /* .enum_names item count */
.reg1 = WM8776_REG_ALCCTRL3,
.mask1 = WM8776_ALC3_DCY_MASK,
.flags = WM8776_FLAG_ALC,
},
[WM8776_CTL_ALC_MAXGAIN] = {
.name = "ALC Maximum Gain Capture Volume",
.type = SNDRV_CTL_ELEM_TYPE_INTEGER,
.tlv = wm8776_maxgain_tlv,
.reg1 = WM8776_REG_ALCCTRL1,
.mask1 = WM8776_ALC1_MAXGAIN_MASK,
.min = 1,
.max = 7,
.flags = WM8776_FLAG_ALC,
},
[WM8776_CTL_ALC_MAXATTN] = {
.name = "ALC Maximum Attenuation Capture Volume",
.type = SNDRV_CTL_ELEM_TYPE_INTEGER,
.tlv = wm8776_maxatten_alc_tlv,
.reg1 = WM8776_REG_LIMITER,
.mask1 = WM8776_LIM_MAXATTEN_MASK,
.min = 10,
.max = 15,
.flags = WM8776_FLAG_ALC | WM8776_FLAG_INVERT,
},
[WM8776_CTL_ALC_HLD] = {
.name = "ALC Hold Time Capture Enum",
.type = SNDRV_CTL_ELEM_TYPE_ENUMERATED,
.enum_names = { "0 ms", "2.67 ms", "5.33 ms", "10.6 ms",
"21.3 ms", "42.7 ms", "85.3 ms", "171 ms", "341 ms",
"683 ms", "1.37 s", "2.73 s", "5.46 s", "10.9 s",
"21.8 s", "43.7 s" },
.max = 16, /* .enum_names item count */
.reg1 = WM8776_REG_ALCCTRL2,
.mask1 = WM8776_ALC2_HOLD_MASK,
.flags = WM8776_FLAG_ALC,
},
[WM8776_CTL_NGT_SW] = {
.name = "Noise Gate Capture Switch",
.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN,
.reg1 = WM8776_REG_NOISEGATE,
.mask1 = WM8776_NGAT_ENABLE,
.flags = WM8776_FLAG_ALC,
},
[WM8776_CTL_NGT_THR] = {
.name = "Noise Gate Threshold Capture Volume",
.type = SNDRV_CTL_ELEM_TYPE_INTEGER,
.tlv = wm8776_ngth_tlv,
.reg1 = WM8776_REG_NOISEGATE,
.mask1 = WM8776_NGAT_THR_MASK,
.max = 7,
.flags = WM8776_FLAG_ALC,
},
};
/* exported functions */
void snd_wm8776_init(struct snd_wm8776 *wm)
{
int i;
static const u16 default_values[] = {
0x000, 0x100, 0x000,
0x000, 0x100, 0x000,
0x000, 0x090, 0x000, 0x000,
0x022, 0x022, 0x022,
0x008, 0x0cf, 0x0cf, 0x07b, 0x000,
0x032, 0x000, 0x0a6, 0x001, 0x001
};
memcpy(wm->ctl, snd_wm8776_default_ctl, sizeof(wm->ctl));
snd_wm8776_write(wm, WM8776_REG_RESET, 0x00); /* reset */
udelay(10);
/* load defaults */
for (i = 0; i < ARRAY_SIZE(default_values); i++)
snd_wm8776_write(wm, i, default_values[i]);
}
void snd_wm8776_resume(struct snd_wm8776 *wm)
{
int i;
for (i = 0; i < WM8776_REG_COUNT; i++)
snd_wm8776_write(wm, i, wm->regs[i]);
}
void snd_wm8776_set_power(struct snd_wm8776 *wm, u16 power)
{
snd_wm8776_write(wm, WM8776_REG_PWRDOWN, power);
}
void snd_wm8776_volume_restore(struct snd_wm8776 *wm)
{
u16 val = wm->regs[WM8776_REG_DACRVOL];
/* restore volume after MCLK stopped */
snd_wm8776_write(wm, WM8776_REG_DACRVOL, val | WM8776_VOL_UPDATE);
}
/* mixer callbacks */
static int snd_wm8776_volume_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct snd_wm8776 *wm = snd_kcontrol_chip(kcontrol);
int n = kcontrol->private_value;
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = (wm->ctl[n].flags & WM8776_FLAG_STEREO) ? 2 : 1;
uinfo->value.integer.min = wm->ctl[n].min;
uinfo->value.integer.max = wm->ctl[n].max;
return 0;
}
static int snd_wm8776_enum_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct snd_wm8776 *wm = snd_kcontrol_chip(kcontrol);
int n = kcontrol->private_value;
return snd_ctl_enum_info(uinfo, 1, wm->ctl[n].max,
wm->ctl[n].enum_names);
}
static int snd_wm8776_ctl_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_wm8776 *wm = snd_kcontrol_chip(kcontrol);
int n = kcontrol->private_value;
u16 val1, val2;
if (wm->ctl[n].get)
wm->ctl[n].get(wm, &val1, &val2);
else {
val1 = wm->regs[wm->ctl[n].reg1] & wm->ctl[n].mask1;
val1 >>= __ffs(wm->ctl[n].mask1);
if (wm->ctl[n].flags & WM8776_FLAG_STEREO) {
val2 = wm->regs[wm->ctl[n].reg2] & wm->ctl[n].mask2;
val2 >>= __ffs(wm->ctl[n].mask2);
if (wm->ctl[n].flags & WM8776_FLAG_VOL_UPDATE)
val2 &= ~WM8776_VOL_UPDATE;
}
}
if (wm->ctl[n].flags & WM8776_FLAG_INVERT) {
val1 = wm->ctl[n].max - (val1 - wm->ctl[n].min);
if (wm->ctl[n].flags & WM8776_FLAG_STEREO)
val2 = wm->ctl[n].max - (val2 - wm->ctl[n].min);
}
ucontrol->value.integer.value[0] = val1;
if (wm->ctl[n].flags & WM8776_FLAG_STEREO)
ucontrol->value.integer.value[1] = val2;
return 0;
}
static int snd_wm8776_ctl_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_wm8776 *wm = snd_kcontrol_chip(kcontrol);
int n = kcontrol->private_value;
u16 val, regval1, regval2;
/* this also works for enum because value is a union */
regval1 = ucontrol->value.integer.value[0];
regval2 = ucontrol->value.integer.value[1];
if (wm->ctl[n].flags & WM8776_FLAG_INVERT) {
regval1 = wm->ctl[n].max - (regval1 - wm->ctl[n].min);
regval2 = wm->ctl[n].max - (regval2 - wm->ctl[n].min);
}
if (wm->ctl[n].set)
wm->ctl[n].set(wm, regval1, regval2);
else {
val = wm->regs[wm->ctl[n].reg1] & ~wm->ctl[n].mask1;
val |= regval1 << __ffs(wm->ctl[n].mask1);
/* both stereo controls in one register */
if (wm->ctl[n].flags & WM8776_FLAG_STEREO &&
wm->ctl[n].reg1 == wm->ctl[n].reg2) {
val &= ~wm->ctl[n].mask2;
val |= regval2 << __ffs(wm->ctl[n].mask2);
}
snd_wm8776_write(wm, wm->ctl[n].reg1, val);
/* stereo controls in different registers */
if (wm->ctl[n].flags & WM8776_FLAG_STEREO &&
wm->ctl[n].reg1 != wm->ctl[n].reg2) {
val = wm->regs[wm->ctl[n].reg2] & ~wm->ctl[n].mask2;
val |= regval2 << __ffs(wm->ctl[n].mask2);
if (wm->ctl[n].flags & WM8776_FLAG_VOL_UPDATE)
val |= WM8776_VOL_UPDATE;
snd_wm8776_write(wm, wm->ctl[n].reg2, val);
}
}
return 0;
}
static int snd_wm8776_add_control(struct snd_wm8776 *wm, int num)
{
struct snd_kcontrol_new cont;
struct snd_kcontrol *ctl;
memset(&cont, 0, sizeof(cont));
cont.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
cont.private_value = num;
cont.name = wm->ctl[num].name;
cont.access = SNDRV_CTL_ELEM_ACCESS_READWRITE;
if (wm->ctl[num].flags & WM8776_FLAG_LIM ||
wm->ctl[num].flags & WM8776_FLAG_ALC)
cont.access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
cont.tlv.p = NULL;
cont.get = snd_wm8776_ctl_get;
cont.put = snd_wm8776_ctl_put;
switch (wm->ctl[num].type) {
case SNDRV_CTL_ELEM_TYPE_INTEGER:
cont.info = snd_wm8776_volume_info;
cont.access |= SNDRV_CTL_ELEM_ACCESS_TLV_READ;
cont.tlv.p = wm->ctl[num].tlv;
break;
case SNDRV_CTL_ELEM_TYPE_BOOLEAN:
wm->ctl[num].max = 1;
if (wm->ctl[num].flags & WM8776_FLAG_STEREO)
cont.info = snd_ctl_boolean_stereo_info;
else
cont.info = snd_ctl_boolean_mono_info;
break;
case SNDRV_CTL_ELEM_TYPE_ENUMERATED:
cont.info = snd_wm8776_enum_info;
break;
default:
return -EINVAL;
}
ctl = snd_ctl_new1(&cont, wm);
if (!ctl)
return -ENOMEM;
return snd_ctl_add(wm->card, ctl);
}
int snd_wm8776_build_controls(struct snd_wm8776 *wm)
{
int err, i;
for (i = 0; i < WM8776_CTL_COUNT; i++)
if (wm->ctl[i].name) {
err = snd_wm8776_add_control(wm, i);
if (err < 0)
return err;
}
return 0;
}
| {
"pile_set_name": "Github"
} |
{
"type": "bundle",
"id": "bundle--f0f505f8-650a-4867-aa71-cce9f5868d95",
"spec_version": "2.0",
"objects": [
{
"id": "x-mitre-tactic--d418cdeb-1b9f-4a6b-a15d-2f89f549f8c1",
"created_by_ref": "identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5",
"name": "Discovery",
"description": "The adversary is trying to figure out your environment.\n\nDiscovery consists of techniques that allow the adversary to gain knowledge about the characteristics of the mobile device and potentially other networked systems. When adversaries gain access to a new system, they must orient themselves to what they now have control of and what benefits operating from that system give to their current objective or overall goals during the intrusion. The operating system may provide capabilities that aid in this post-compromise information-gathering phase.",
"external_references": [
{
"external_id": "TA0032",
"url": "https://attack.mitre.org/tactics/TA0032",
"source_name": "mitre-attack"
}
],
"object_marking_refs": [
"marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168"
],
"x_mitre_shortname": "discovery",
"type": "x-mitre-tactic",
"modified": "2020-01-27T16:09:00.466Z",
"created": "2018-10-17T00:14:20.652Z"
}
]
} | {
"pile_set_name": "Github"
} |
/**
* \file
*
* \brief Instance description for TC3
*
* Copyright (c) 2014 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* 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. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef _SAMD20_TC3_INSTANCE_
#define _SAMD20_TC3_INSTANCE_
/* ========== Register definition for TC3 peripheral ========== */
#if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
#define REG_TC3_CTRLA (0x42002C00U) /**< \brief (TC3) Control A */
#define REG_TC3_READREQ (0x42002C02U) /**< \brief (TC3) Read Request */
#define REG_TC3_CTRLBCLR (0x42002C04U) /**< \brief (TC3) Control B Clear */
#define REG_TC3_CTRLBSET (0x42002C05U) /**< \brief (TC3) Control B Set */
#define REG_TC3_CTRLC (0x42002C06U) /**< \brief (TC3) Control C */
#define REG_TC3_DBGCTRL (0x42002C08U) /**< \brief (TC3) Debug Control */
#define REG_TC3_EVCTRL (0x42002C0AU) /**< \brief (TC3) Event Control */
#define REG_TC3_INTENCLR (0x42002C0CU) /**< \brief (TC3) Interrupt Enable Clear */
#define REG_TC3_INTENSET (0x42002C0DU) /**< \brief (TC3) Interrupt Enable Set */
#define REG_TC3_INTFLAG (0x42002C0EU) /**< \brief (TC3) Interrupt Flag Status and Clear */
#define REG_TC3_STATUS (0x42002C0FU) /**< \brief (TC3) Status */
#define REG_TC3_COUNT16_COUNT (0x42002C10U) /**< \brief (TC3) COUNT16 Counter Value */
#define REG_TC3_COUNT16_CC0 (0x42002C18U) /**< \brief (TC3) COUNT16 Compare/Capture 0 */
#define REG_TC3_COUNT16_CC1 (0x42002C1AU) /**< \brief (TC3) COUNT16 Compare/Capture 1 */
#define REG_TC3_COUNT32_COUNT (0x42002C10U) /**< \brief (TC3) COUNT32 Counter Value */
#define REG_TC3_COUNT32_CC0 (0x42002C18U) /**< \brief (TC3) COUNT32 Compare/Capture 0 */
#define REG_TC3_COUNT32_CC1 (0x42002C1CU) /**< \brief (TC3) COUNT32 Compare/Capture 1 */
#define REG_TC3_COUNT8_COUNT (0x42002C10U) /**< \brief (TC3) COUNT8 Counter Value */
#define REG_TC3_COUNT8_PER (0x42002C14U) /**< \brief (TC3) COUNT8 Period Value */
#define REG_TC3_COUNT8_CC0 (0x42002C18U) /**< \brief (TC3) COUNT8 Compare/Capture 0 */
#define REG_TC3_COUNT8_CC1 (0x42002C19U) /**< \brief (TC3) COUNT8 Compare/Capture 1 */
#else
#define REG_TC3_CTRLA (*(RwReg16*)0x42002C00U) /**< \brief (TC3) Control A */
#define REG_TC3_READREQ (*(RwReg16*)0x42002C02U) /**< \brief (TC3) Read Request */
#define REG_TC3_CTRLBCLR (*(RwReg8 *)0x42002C04U) /**< \brief (TC3) Control B Clear */
#define REG_TC3_CTRLBSET (*(RwReg8 *)0x42002C05U) /**< \brief (TC3) Control B Set */
#define REG_TC3_CTRLC (*(RwReg8 *)0x42002C06U) /**< \brief (TC3) Control C */
#define REG_TC3_DBGCTRL (*(RwReg8 *)0x42002C08U) /**< \brief (TC3) Debug Control */
#define REG_TC3_EVCTRL (*(RwReg16*)0x42002C0AU) /**< \brief (TC3) Event Control */
#define REG_TC3_INTENCLR (*(RwReg8 *)0x42002C0CU) /**< \brief (TC3) Interrupt Enable Clear */
#define REG_TC3_INTENSET (*(RwReg8 *)0x42002C0DU) /**< \brief (TC3) Interrupt Enable Set */
#define REG_TC3_INTFLAG (*(RwReg8 *)0x42002C0EU) /**< \brief (TC3) Interrupt Flag Status and Clear */
#define REG_TC3_STATUS (*(RoReg8 *)0x42002C0FU) /**< \brief (TC3) Status */
#define REG_TC3_COUNT16_COUNT (*(RwReg16*)0x42002C10U) /**< \brief (TC3) COUNT16 Counter Value */
#define REG_TC3_COUNT16_CC0 (*(RwReg16*)0x42002C18U) /**< \brief (TC3) COUNT16 Compare/Capture 0 */
#define REG_TC3_COUNT16_CC1 (*(RwReg16*)0x42002C1AU) /**< \brief (TC3) COUNT16 Compare/Capture 1 */
#define REG_TC3_COUNT32_COUNT (*(RwReg *)0x42002C10U) /**< \brief (TC3) COUNT32 Counter Value */
#define REG_TC3_COUNT32_CC0 (*(RwReg *)0x42002C18U) /**< \brief (TC3) COUNT32 Compare/Capture 0 */
#define REG_TC3_COUNT32_CC1 (*(RwReg *)0x42002C1CU) /**< \brief (TC3) COUNT32 Compare/Capture 1 */
#define REG_TC3_COUNT8_COUNT (*(RwReg8 *)0x42002C10U) /**< \brief (TC3) COUNT8 Counter Value */
#define REG_TC3_COUNT8_PER (*(RwReg8 *)0x42002C14U) /**< \brief (TC3) COUNT8 Period Value */
#define REG_TC3_COUNT8_CC0 (*(RwReg8 *)0x42002C18U) /**< \brief (TC3) COUNT8 Compare/Capture 0 */
#define REG_TC3_COUNT8_CC1 (*(RwReg8 *)0x42002C19U) /**< \brief (TC3) COUNT8 Compare/Capture 1 */
#endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
/* ========== Instance parameters for TC3 peripheral ========== */
#define TC3_CC8_NUM 2
#define TC3_CC16_NUM 2
#define TC3_CC32_NUM 2
#define TC3_DITHERING_EXT 0
#define TC3_GCLK_ID 20
#define TC3_MASTER 0
#define TC3_OW_NUM 2
#define TC3_PERIOD_EXT 0
#define TC3_SHADOW_EXT 0
#endif /* _SAMD20_TC3_INSTANCE_ */
| {
"pile_set_name": "Github"
} |
During a route transition, the Ember Router passes a transition
object to the various hooks on the routes involved in the transition.
Any hook that has access to this transition object has the ability
to immediately abort the transition by calling `transition.abort()`,
and if the transition object is stored, it can be re-attempted at a
later time by calling `transition.retry()`.
### Preventing Transitions via `willTransition`
When a transition is attempted, whether via `{{link-to}}`, `transitionTo`,
or a URL change, a `willTransition` action is fired on the currently
active routes. This gives each active route, starting with the leaf-most
route, the opportunity to decide whether or not the transition should occur.
Imagine your app is in a route that's displaying a complex form for the user
to fill out and the user accidentally navigates backwards. Unless the
transition is prevented, the user might lose all of the progress they
made on the form, which can make for a pretty frustrating user experience.
Here's one way this situation could be handled:
```javascript {data-filename=app/routes/form.js}
export default Ember.Route.extend({
actions: {
willTransition(transition) {
if (this.controller.get('userHasEnteredData') &&
!confirm('Are you sure you want to abandon progress?')) {
transition.abort();
} else {
// Bubble the `willTransition` action so that
// parent routes can decide whether or not to abort.
return true;
}
}
}
});
```
When the user clicks on a `{{link-to}}` helper, or when the app initiates a
transition by using `transitionTo`, the transition will be aborted and the URL
will remain unchanged. However, if the browser back button is used to
navigate away from `route:form`, or if the user manually changes the URL, the
new URL will be navigated to before the `willTransition` action is
called. This will result in the browser displaying the new URL, even if
`willTransition` calls `transition.abort()`.
### Aborting Transitions Within `model`, `beforeModel`, `afterModel`
The `model`, `beforeModel`, and `afterModel` hooks described in
[Asynchronous Routing](../asynchronous-routing/)
each get called with a transition object. This makes it possible for
destination routes to abort attempted transitions.
```javascript {data-filename=app/routes/disco.js}
export default Ember.Route.extend({
beforeModel(transition) {
if (new Date() > new Date('January 1, 1980')) {
alert('Sorry, you need a time machine to enter this route.');
transition.abort();
}
}
});
```
### Storing and Retrying a Transition
Aborted transitions can be retried at a later time. A common use case
for this is having an authenticated route redirect the user to a login
page, and then redirecting them back to the authenticated route once
they've logged in.
```javascript {data-filename=app/routes/some-authenticated.js}
export default Ember.Route.extend({
beforeModel(transition) {
if (!this.controllerFor('auth').get('userIsLoggedIn')) {
var loginController = this.controllerFor('login');
loginController.set('previousTransition', transition);
this.transitionTo('login');
}
}
});
```
```javascript {data-filename=app/controllers/login.js}
export default Ember.Controller.extend({
actions: {
login() {
// Log the user in, then reattempt previous transition if it exists.
var previousTransition = this.get('previousTransition');
if (previousTransition) {
this.set('previousTransition', null);
previousTransition.retry();
} else {
// Default back to homepage
this.transitionToRoute('index');
}
}
}
});
```
<!-- eof - needed for pages that end in a code block -->
| {
"pile_set_name": "Github"
} |
# Copyright 2015-2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Entry points for YAPF.
The main APIs that YAPF exposes to drive the reformatting.
FormatFile(): reformat a file.
FormatCode(): reformat a string of code.
These APIs have some common arguments:
style_config: (string) Either a style name or a path to a file that contains
formatting style settings. If None is specified, use the default style
as set in style.DEFAULT_STYLE_FACTORY
lines: (list of tuples of integers) A list of tuples of lines, [start, end],
that we want to format. The lines are 1-based indexed. It can be used by
third-party code (e.g., IDEs) when reformatting a snippet of code rather
than a whole file.
print_diff: (bool) Instead of returning the reformatted source, return a
diff that turns the formatted source into reformatter source.
verify: (bool) True if reformatted code should be verified for syntax.
"""
import difflib
import re
import sys
from lib2to3.pgen2 import tokenize
from yapf.yapflib import blank_line_calculator
from yapf.yapflib import comment_splicer
from yapf.yapflib import continuation_splicer
from yapf.yapflib import file_resources
from yapf.yapflib import py3compat
from yapf.yapflib import pytree_unwrapper
from yapf.yapflib import pytree_utils
from yapf.yapflib import reformatter
from yapf.yapflib import split_penalty
from yapf.yapflib import style
from yapf.yapflib import subtype_assigner
def FormatFile(filename,
style_config=None,
lines=None,
print_diff=False,
verify=False,
in_place=False,
logger=None):
"""Format a single Python file and return the formatted code.
Arguments:
filename: (unicode) The file to reformat.
in_place: (bool) If True, write the reformatted code back to the file.
logger: (io streamer) A stream to output logging.
remaining arguments: see comment at the top of this module.
Returns:
Tuple of (reformatted_code, encoding, changed). reformatted_code is None if
the file is sucessfully written to (having used in_place). reformatted_code
is a diff if print_diff is True.
Raises:
IOError: raised if there was an error reading the file.
ValueError: raised if in_place and print_diff are both specified.
"""
_CheckPythonVersion()
if in_place and print_diff:
raise ValueError('Cannot pass both in_place and print_diff.')
original_source, newline, encoding = ReadFile(filename, logger)
reformatted_source, changed = FormatCode(
original_source,
style_config=style_config,
filename=filename,
lines=lines,
print_diff=print_diff,
verify=verify)
if reformatted_source.rstrip('\n'):
lines = reformatted_source.rstrip('\n').split('\n')
reformatted_source = newline.join(line for line in lines) + newline
if in_place:
if original_source and original_source != reformatted_source:
file_resources.WriteReformattedCode(filename, reformatted_source,
in_place, encoding)
return None, encoding, changed
return reformatted_source, encoding, changed
def FormatCode(unformatted_source,
filename='<unknown>',
style_config=None,
lines=None,
print_diff=False,
verify=False):
"""Format a string of Python code.
This provides an alternative entry point to YAPF.
Arguments:
unformatted_source: (unicode) The code to format.
filename: (unicode) The name of the file being reformatted.
remaining arguments: see comment at the top of this module.
Returns:
Tuple of (reformatted_source, changed). reformatted_source conforms to the
desired formatting style. changed is True if the source changed.
"""
_CheckPythonVersion()
style.SetGlobalStyle(style.CreateStyleFromConfig(style_config))
if not unformatted_source.endswith('\n'):
unformatted_source += '\n'
tree = pytree_utils.ParseCodeToTree(unformatted_source)
# Run passes on the tree, modifying it in place.
comment_splicer.SpliceComments(tree)
continuation_splicer.SpliceContinuations(tree)
subtype_assigner.AssignSubtypes(tree)
split_penalty.ComputeSplitPenalties(tree)
blank_line_calculator.CalculateBlankLines(tree)
uwlines = pytree_unwrapper.UnwrapPyTree(tree)
for uwl in uwlines:
uwl.CalculateFormattingInformation()
_MarkLinesToFormat(uwlines, lines)
reformatted_source = reformatter.Reformat(uwlines, verify)
if unformatted_source == reformatted_source:
return '' if print_diff else reformatted_source, False
code_diff = _GetUnifiedDiff(
unformatted_source, reformatted_source, filename=filename)
if print_diff:
return code_diff, code_diff != ''
return reformatted_source, True
def _CheckPythonVersion(): # pragma: no cover
errmsg = 'yapf is only supported for Python 2.7 or 3.4+'
if sys.version_info[0] == 2:
if sys.version_info[1] < 7:
raise RuntimeError(errmsg)
elif sys.version_info[0] == 3:
if sys.version_info[1] < 4:
raise RuntimeError(errmsg)
def ReadFile(filename, logger=None):
"""Read the contents of the file.
An optional logger can be specified to emit messages to your favorite logging
stream. If specified, then no exception is raised. This is external so that it
can be used by third-party applications.
Arguments:
filename: (unicode) The name of the file.
logger: (function) A function or lambda that takes a string and emits it.
Returns:
The contents of filename.
Raises:
IOError: raised if there was an error reading the file.
"""
try:
with open(filename, 'rb') as fd:
encoding = tokenize.detect_encoding(fd.readline)[0]
except IOError as err:
if logger:
logger(err)
raise
try:
# Preserves line endings.
with py3compat.open_with_encoding(
filename, mode='r', encoding=encoding, newline='') as fd:
lines = fd.readlines()
line_ending = file_resources.LineEnding(lines)
source = '\n'.join(line.rstrip('\r\n') for line in lines) + '\n'
return source, line_ending, encoding
except IOError as err: # pragma: no cover
if logger:
logger(err)
raise
DISABLE_PATTERN = r'^#.*\byapf:\s*disable\b'
ENABLE_PATTERN = r'^#.*\byapf:\s*enable\b'
def _MarkLinesToFormat(uwlines, lines):
"""Skip sections of code that we shouldn't reformat."""
if lines:
for uwline in uwlines:
uwline.disable = True
# Sort and combine overlapping ranges.
lines = sorted(lines)
line_ranges = [lines[0]] if len(lines[0]) else []
index = 1
while index < len(lines):
current = line_ranges[-1]
if lines[index][0] <= current[1]:
# The ranges overlap, so combine them.
line_ranges[-1] = (current[0], max(lines[index][1], current[1]))
else:
line_ranges.append(lines[index])
index += 1
# Mark lines to format as not being disabled.
index = 0
for start, end in sorted(line_ranges):
while index < len(uwlines) and uwlines[index].last.lineno < start:
index += 1
if index >= len(uwlines):
break
while index < len(uwlines):
if uwlines[index].lineno > end:
break
if (uwlines[index].lineno >= start or
uwlines[index].last.lineno >= start):
uwlines[index].disable = False
index += 1
# Now go through the lines and disable any lines explicitly marked as
# disabled.
index = 0
while index < len(uwlines):
uwline = uwlines[index]
if uwline.is_comment:
if _DisableYAPF(uwline.first.value.strip()):
index += 1
while index < len(uwlines):
uwline = uwlines[index]
if uwline.is_comment and _EnableYAPF(uwline.first.value.strip()):
break
uwline.disable = True
index += 1
elif re.search(DISABLE_PATTERN, uwline.last.value.strip(), re.IGNORECASE):
uwline.disable = True
index += 1
def _DisableYAPF(line):
return (
re.search(DISABLE_PATTERN, line.split('\n')[0].strip(), re.IGNORECASE) or
re.search(DISABLE_PATTERN, line.split('\n')[-1].strip(), re.IGNORECASE))
def _EnableYAPF(line):
return (
re.search(ENABLE_PATTERN, line.split('\n')[0].strip(), re.IGNORECASE) or
re.search(ENABLE_PATTERN, line.split('\n')[-1].strip(), re.IGNORECASE))
def _GetUnifiedDiff(before, after, filename='code'):
"""Get a unified diff of the changes.
Arguments:
before: (unicode) The original source code.
after: (unicode) The reformatted source code.
filename: (unicode) The code's filename.
Returns:
The unified diff text.
"""
before = before.splitlines()
after = after.splitlines()
return '\n'.join(
difflib.unified_diff(
before,
after,
filename,
filename,
'(original)',
'(reformatted)',
lineterm='')) + '\n'
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View Tree ( Click to highlight view, or double click to change frame of view )</title>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/index.css">
<script type="text/javascript" src="js/modjs.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script>
window.modjs = {debug:1};
use("index",function(){});
</script>
</head>
<body>
<div id="viewtree">
<h1>View Tree ( Click to highlight view, or double click to change frame of view )</h1>
<article></article>
</div>
</body>
</html> | {
"pile_set_name": "Github"
} |
global class RenameQuipFolder {
@InvocableMethod(label='Rename Quip Folder' description='Renames Quips folder located under the path specified')
global static List<Response> RenameQuipFolder(List<Request> requests) {
List<Response> responses = new List<Response>();
IQuip quip = new Quip(new QuipAPI());
for (Request request : requests) {
Response response = RenameQuipFolder.RenameQuipFolderImpl(quip, request);
responses.add(response);
}
return responses;
}
public static Response RenameQuipFolderImpl(IQuip quip, Request request) {
Response response = new Response();
try {
Folder folder = quip.getFolderByPath(request.FolderPath, false);
if (folder == null) {
folder = quip.findFolder(request.FolderPath);
}
if (folder == null) {
response.IsSuccess = false;
response.ErrorMessage = 'Specified folder doesn\'t exist';
}
quip.renameFolder(folder, request.NewFolderName);
}
catch (QuipException ex) {
response.IsSuccess = false;
response.ErrorMessage = ex.getMessage();
}
return response;
}
global class Request {
@InvocableVariable(required=True label='Folder Name' description='A name of the folder or a path to the folder')
global String FolderPath;
@InvocableVariable(required=True label='New Name')
global String NewFolderName;
}
global class Response {
global Response() {
IsSuccess = true;
ErrorMessage = '';
}
@InvocableVariable(label='Is Success' description='"True" if action was successful, otherwise "False"')
global Boolean IsSuccess;
@InvocableVariable(label='Error Message' description='Contains the description of error if action was not successfull"')
global String ErrorMessage;
}
} | {
"pile_set_name": "Github"
} |
# Data Agreement File for Myers/HudsonAlpha ChIP-seq experiments
# Lab info
grant BadGrant
lab HudsonAlpha
dataType ChipSeq
variables cell, antibody, badvariable
assembly hg17
dafVersion 0.2.2.2
# Track/view definition
view Peaks
longLabelPrefix HudsonAlpha ChIP/Seq Peaks
type narrowPeak
hasReplicates no
required yes
badField blah
view Signal
longLabelPrefix HudsonAlpha ChIP/Seq Signal
type wig
hasReplicates no
required no
view RawSignal
longLabelPrefix HudsonAlpha ChIP-Seq Raw Signal
type wig
hasReplicates yes
required no
view Alignments
longLabelPrefix HudsonAlpha ChIP-Seq Sites
type tagAlign
hasReplicates yes
required yes
view RawData
type fastq
hasReplicates yes
required blah
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="SDL2main"
ProjectGUID="{DA956FD3-E142-46F2-9DD5-C78BEBB56B7A}"
RootNamespace="SDLmain"
TargetFrameworkVersion="131072"
>
<Platforms>
<Platform
Name="Win32"
/>
<Platform
Name="x64"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
CommandLine=""
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories="$(SolutionDir)/../include"
AdditionalUsingDirectories=""
PreprocessorDefinitions="WIN32,NDEBUG,_WINDOWS"
StringPooling="true"
RuntimeLibrary="2"
BufferSecurityCheck="false"
EnableEnhancedInstructionSet="1"
WarningLevel="3"
DebugInformationFormat="1"
OmitDefaultLibName="true"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|x64"
OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories="$(SolutionDir)/../include"
AdditionalUsingDirectories=""
PreprocessorDefinitions="WIN32,NDEBUG,_WINDOWS"
StringPooling="true"
RuntimeLibrary="2"
BufferSecurityCheck="false"
WarningLevel="3"
DebugInformationFormat="1"
OmitDefaultLibName="true"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
CommandLine=""
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="$(SolutionDir)/../include"
AdditionalUsingDirectories=""
PreprocessorDefinitions="WIN32,_DEBUG,_WINDOWS"
RuntimeLibrary="2"
BufferSecurityCheck="false"
EnableEnhancedInstructionSet="1"
WarningLevel="3"
DebugInformationFormat="1"
OmitDefaultLibName="true"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|x64"
OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="$(SolutionDir)/../include"
AdditionalUsingDirectories=""
PreprocessorDefinitions="WIN32,_DEBUG,_WINDOWS"
RuntimeLibrary="2"
BufferSecurityCheck="false"
WarningLevel="3"
DebugInformationFormat="1"
OmitDefaultLibName="true"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<File
RelativePath="..\..\src\main\windows\SDL_windows_main.c"
>
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
| {
"pile_set_name": "Github"
} |
/*
* make_socket.java
*
* Copyright (C) 2004 Peter Graves
* $Id$
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under
* terms of your choice, provided that you also meet, for each linked
* independent module, the terms and conditions of the license of that
* module. An independent module is a module which is not derived from
* or based on this library. If you modify this library, you may extend
* this exception to your version of the library, but you are not
* obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
package org.armedbear.lisp;
import static org.armedbear.lisp.Lisp.*;
import java.net.Socket;
// ### %make-socket
public final class make_socket extends Primitive
{
private make_socket()
{
super("%make-socket", PACKAGE_SYS, false, "host port");
}
@Override
public LispObject execute(LispObject first, LispObject second)
{
String host = first.getStringValue();
int port = Fixnum.getValue(second);
try {
Socket socket = new Socket(host, port);
return new JavaObject(socket);
}
catch (Exception e) {
return error(new LispError(e.getMessage()));
}
}
private static final Primitive MAKE_SOCKET = new make_socket();
}
| {
"pile_set_name": "Github"
} |
{
"$id": "docs/spec/rum_v3_user.json",
"title": "User",
"type": [
"object",
"null"
],
"properties": {
"id": {
"description": "Identifier of the logged in user, e.g. the primary key of the user",
"type": [
"string",
"integer",
"null"
],
"maxLength": 1024
},
"em": {
"description": "Email of the logged in user",
"type": [
"string",
"null"
],
"maxLength": 1024
},
"un": {
"description": "The username of the logged in user",
"type": [
"string",
"null"
],
"maxLength": 1024
}
}
} | {
"pile_set_name": "Github"
} |
(**************************************************************************)
(* *)
(* This file is part of the Frama-C's E-ACSL plug-in. *)
(* *)
(* Copyright (C) 2012-2019 *)
(* CEA (Commissariat à l'énergie atomique et aux énergies *)
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
(* Lesser General Public License as published by the Free Software *)
(* Foundation, version 2.1. *)
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
(* See the GNU Lesser General Public License version 2.1 *)
(* for more details (enclosed in the file licenses/LGPLv2.1). *)
(* *)
(**************************************************************************)
exception Typing_error of string
let untypable s = raise (Typing_error s)
exception Not_yet of string
let not_yet s = raise (Not_yet s)
module Nb_typing =
State_builder.Ref
(Datatype.Int)
(struct
let name = "E_ACSL.Error.Nb_typing"
let default () = 0
let dependencies = [ Ast.self ]
end)
let nb_untypable = Nb_typing.get
module Nb_not_yet =
State_builder.Ref
(Datatype.Int)
(struct
let name = "E_ACSL.Error.Nb_not_yet"
let default () = 0
let dependencies = [ Ast.self ]
end)
let nb_not_yet = Nb_not_yet.get
let generic_handle f res x =
try
f x
with
| Typing_error s ->
let msg = Format.sprintf "@[invalid E-ACSL construct@ `%s'.@]" s in
Options.warning ~once:true ~current:true "@[%s@ Ignoring annotation.@]" msg;
Nb_typing.set (Nb_typing.get () + 1);
res
| Not_yet s ->
let msg =
Format.sprintf "@[E-ACSL construct@ `%s'@ is not yet supported.@]" s
in
Options.warning ~once:true ~current:true "@[%s@ Ignoring annotation.@]" msg;
Nb_not_yet.set (Nb_not_yet.get () + 1);
res
let handle f x = generic_handle f x x
(*
Local Variables:
compile-command: "make"
End:
*)
| {
"pile_set_name": "Github"
} |
<p>Implement <strong>next permutation</strong>, which rearranges numbers into the lexicographically next greater permutation of numbers.</p>
<p>If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).</p>
<p>The replacement must be <strong><a href="http://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in-place</a></strong> and use only constant extra memory.</p>
<p>Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.</p>
<p><code>1,2,3</code> → <code>1,3,2</code><br />
<code>3,2,1</code> → <code>1,2,3</code><br />
<code>1,1,5</code> → <code>1,5,1</code></p>
| {
"pile_set_name": "Github"
} |
# accept a filename on the commandline, read it and print it out to screen
# only ascii right now, just like the rest of Mu
#
# To run:
# $ ./translate_mu apps/print-file.mu
# $ echo abc > x
# $ ./a.elf x
# abc
fn main _args: (addr array addr array byte) -> exit-status/ebx: int {
var args/eax: (addr array addr array byte) <- copy _args
$main-body: {
var n/ecx: int <- length args
compare n, 1
{
break-if->
print-string 0, "usage: cat <filename>\n"
break $main-body
}
{
break-if-<=
var filename/edx: (addr addr array byte) <- index args 1
var in: (handle buffered-file)
{
var addr-in/eax: (addr handle buffered-file) <- address in
open *filename, 0, addr-in
}
var _in-addr/eax: (addr buffered-file) <- lookup in
var in-addr/ecx: (addr buffered-file) <- copy _in-addr
{
var c/eax: byte <- read-byte-buffered in-addr
compare c, 0xffffffff # EOF marker
break-if-=
var g/eax: grapheme <- copy c
print-grapheme 0, g
loop
}
}
}
exit-status <- copy 0
}
| {
"pile_set_name": "Github"
} |
Merge request JS54SBOKPUWZB5KD26UULXWQG5U2XX76 passed against revision 282e41acd6bbd98c75b75e7d8c44087ea7a79e13
<details><summary>Log</summary><p>```
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 7 tests
test ext_unavailable ... ok
test ext_sit_path ... ok
test ext_modules_over_path ... ok
test ext_modules_path ... ok
test ext_modules_cli ... ok
test ext_cli_over_modules_cli_and_path ... ok
test ext_cli ... ok
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 11 tests
test repo_init_repo_path ... ok
test repo_init_repo_directory ... ok
test repo_init_workdir ... ok
test repo_init_custom_working_directory ... ok
test repo_init_fail ... ok
test repo_init_emptydir_relative ... ok
test repo_init ... ok
test repo_init_path_concat ... ok
test repo_init_working_directory ... ok
test repo_init_emptydir_absolute ... ok
test repo_reinit ... ok
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 3 tests
test item_named ... ok
test item ... ok
test item_existing ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 10 tests
test item_repo_over_named_user_query ... ok
test no_items ... ok
test item_query ... ok
test item_named_query ... ok
test item_named_user_query ... ok
test item_filter ... ok
test item_named_user_filter ... ok
test item_named_filter ... ok
test item_repo_over_named_user_filter ... ok
test item ... ok
test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 2 tests
test jmespath_pretty ... ok
test jmespath ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 4 tests
test modules_convention_link ... ok
test modules_convention_ext_invalid ... ok
test modules_convention_ext ... ok
test modules_convention_dir ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 15 tests
test record_should_record_files ... ok
test record_no_authorship_no_git ... ok
test record_authorship ... ok
test record_no_authorship_no_author ... ok
test record_should_record_timestamp ... ok
test record_should_not_record_timestamp ... ok
test record_should_not_record_if_files_are_missing ... ok
test record_should_merge_types ... ok
test record_should_fail_if_no_type ... ok
test record_no_authorship_user_git ... ok
test record_no_authorship_local_over_user_git ... ok
test record_dot_type_sufficiency ... ok
test record_no_authorship_local_git ... ok
test record_should_sign_if_configured ... test record_should_sign_if_configured has been running for over 60 seconds
test record_should_sign_if_instructed_cmdline ... test record_should_sign_if_instructed_cmdline has been running for over 60 seconds
test record_should_sign_if_instructed_cmdline ... ok
test record_should_sign_if_configured ... ok
test result: ok. 15 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 13 tests
test repo_over_named_user_query ... ok
test named_user_query ... ok
test no_records ... ok
test query ... ok
test named_query ... ok
test record ... ok
test pgp_no_signature ... ok
test named_user_filter ... ok
test named_filter ... ok
test repo_over_named_user_filter ... ok
test filter ... ok
test pgp_signature ... test pgp_signature has been running for over 60 seconds
test pgp_signature_wrong_data ... test pgp_signature_wrong_data has been running for over 60 seconds
test pgp_signature_wrong_data ... ok
test pgp_signature ... ok
test result: ok. 13 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 6 tests
test no_item ... ok
test item ... ok
test item_named_user_query ... ok
test item_named_query ... ok
test item_repo_over_named_user_query ... ok
test item_query ... ok
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 61 tests
test hash::tests::blake2 ... ok
test hash::tests::sha1 ... ok
test record::ordered_files_tests::ordered_files_normalizes ... ok
test duktape::bindings::bindgen_test_layout_duk_time_components ... ok
test reducers::duktape::tests::module_export_non_function_error ... ok
test reducers::duktape::tests::mistyped_result ... ok
test reducers::duktape::tests::invalid_syntax ... ok
test reducers::duktape::tests::anonymous_function_error ... ok
test reducers::tests::chained_reducer ... ok
test repository::tests::new_record ... ok
test repository::tests::link_module_relative ... ok
test repository::tests::issues_to_items_upgrade ... ok
test duktape::bindings::bindgen_test_layout___va_list_tag ... ok
test reducers::duktape::tests::require_not_found ... ok
test duktape::bindings::bindgen_test_layout_duk_function_list_entry ... ok
test duktape::bindings::bindgen_test_layout_duk_number_list_entry ... ok
test reducers::duktape::tests::require_external_absolute ... ok
test duktape::bindings::bindgen_test_layout_duk_memory_functions ... ok
test duktape::bindings::bindgen_test_layout_duk_thread_state ... ok
test reducers::duktape::tests::require_in_module ... ok
test reducers::duktape::tests::require_external_relative ... ok
test reducers::duktape::tests::cesu8_input ... ok
test reducers::duktape::tests::require_path_modification ... ok
test reducers::duktape::tests::undefined_result ... ok
test reducers::duktape::tests::reducer_state ... ok
test reducers::duktape::tests::module_closure ... ok
test repository::tests::new_item ... ok
test repository::tests::new_named_item ... ok
test repository::tests::new_repo ... ok
test repository::tests::find_item ... ok
test repository::tests::new_record_parents_linking ... ok
test reducers::duktape::tests::module_export_props ... ok
test reducers::duktape::tests::record_contents ... ok
test reducers::duktape::tests::record_hash ... ok
test reducers::duktape::tests::require ... ok
test reducers::duktape::tests::cesu8_output ... ok
test reducers::duktape::tests::module_reducers ... ok
test reducers::duktape::tests::multiple_reducers ... ok
test repository::tests::find_repo_in_itself ... ok
test repository::tests::find_repo ... ok
test reducers::duktape::tests::runtime_error ... ok
test repository::tests::modules ... ok
test repository::tests::new_named_item_dup ... ok
test reducers::duktape::tests::require_in_linked_module ... ok
test repository::tests::chaining_module_iterator ... ok
test repository::tests::link_module_absolute ... ok
test reducers::duktape::tests::cloned ... ok
test repository::tests::new_repo_already_exists ... ok
test repository::tests::open_repo ... ok
test repository::tests::multilevel_parents ... ok
test reducers::duktape::tests::resetting_state ... ok
test repository::tests::record_outside_naming_scheme ... ok
test repository::tests::record_files_path ... ok
test repository::tests::partial_ordering ... ok
test repository::tests::record_ordering ... ok
test repository::tests::record_deterministic_hashing ... ok
test record::ordered_files_tests::add_includes_iter ... ok
test record::ordered_files_tests::sorted ... ok
test record::ordered_files_tests::add_sorted ... ok
test record::ordered_files_tests::add_includes ... ok
test record::ordered_files_tests::sub_excludes ... ok
test result: ok. 61 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
running 2 tests
test /home/travis/build/sit-fyi/sit/target/debug/build/sit-core-36c2546e715396b8/out/default_files.rs - repository::default_files::Dir::walk (line 70) ... ignored
test src/record.rs - record::OrderedFiles<'a, F>::boxed (line 54) ... ok
test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out```
</p></details> | {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <SearchFoundation/NSObject-Protocol.h>
@class NSData, NSDictionary, NSString, NSTimeZone, SFLatLng;
@protocol SFAirport <NSObject>
@property(readonly, nonatomic) NSData *jsonData;
@property(readonly, nonatomic) NSDictionary *dictionaryRepresentation;
@property(copy, nonatomic) NSString *name;
@property(copy, nonatomic) NSString *country;
@property(copy, nonatomic) NSString *countryCode;
@property(copy, nonatomic) NSString *postalCode;
@property(copy, nonatomic) NSString *state;
@property(copy, nonatomic) NSString *district;
@property(copy, nonatomic) NSString *street;
@property(copy, nonatomic) NSString *city;
@property(retain, nonatomic) SFLatLng *location;
@property(copy, nonatomic) NSTimeZone *timezone;
@property(copy, nonatomic) NSString *code;
@end
| {
"pile_set_name": "Github"
} |
MODULE = api-ms-win-core-realtime-l1-1-0.dll
| {
"pile_set_name": "Github"
} |
package backup
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// JobCancellationsClient is the open API 2.0 Specs for Azure RecoveryServices Backup service
type JobCancellationsClient struct {
BaseClient
}
// NewJobCancellationsClient creates an instance of the JobCancellationsClient client.
func NewJobCancellationsClient(subscriptionID string) JobCancellationsClient {
return NewJobCancellationsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewJobCancellationsClientWithBaseURI creates an instance of the JobCancellationsClient client using a custom
// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure
// stack).
func NewJobCancellationsClientWithBaseURI(baseURI string, subscriptionID string) JobCancellationsClient {
return JobCancellationsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Trigger cancels a job. This is an asynchronous operation. To know the status of the cancellation, call
// GetCancelOperationResult API.
// Parameters:
// vaultName - the name of the recovery services vault.
// resourceGroupName - the name of the resource group where the recovery services vault is present.
// jobName - name of the job to cancel.
func (client JobCancellationsClient) Trigger(ctx context.Context, vaultName string, resourceGroupName string, jobName string) (result autorest.Response, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/JobCancellationsClient.Trigger")
defer func() {
sc := -1
if result.Response != nil {
sc = result.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.TriggerPreparer(ctx, vaultName, resourceGroupName, jobName)
if err != nil {
err = autorest.NewErrorWithError(err, "backup.JobCancellationsClient", "Trigger", nil, "Failure preparing request")
return
}
resp, err := client.TriggerSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "backup.JobCancellationsClient", "Trigger", resp, "Failure sending request")
return
}
result, err = client.TriggerResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "backup.JobCancellationsClient", "Trigger", resp, "Failure responding to request")
}
return
}
// TriggerPreparer prepares the Trigger request.
func (client JobCancellationsClient) TriggerPreparer(ctx context.Context, vaultName string, resourceGroupName string, jobName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"jobName": autorest.Encode("path", jobName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"vaultName": autorest.Encode("path", vaultName),
}
const APIVersion = "2019-06-15"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupJobs/{jobName}/cancel", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// TriggerSender sends the Trigger request. The method will close the
// http.Response Body if it receives an error.
func (client JobCancellationsClient) TriggerSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// TriggerResponder handles the response to the Trigger request. The method always
// closes the http.Response Body.
func (client JobCancellationsClient) TriggerResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByClosing())
result.Response = resp
return
}
| {
"pile_set_name": "Github"
} |
# visual configuration for EVEX DB data (http://evexdb.org/)
[labels]
GGP | Gene or gene product | GGP
Regulation | Regulation | Reg
Positive_regulation | Positive regulation | +Regulation | +Reg
Negative_regulation | Negative regulation | -Regulation | -Reg
Binding | Binding | Bind
Gene_expression | Gene expression | Expression
Transcription | Transcription | Trns
Localization | Localization | Locl
Protein_catabolism | Protein catabolism | Catabolism | Catab
Phosphorylation | Phosphorylation | Phos
PhosphorylationEPI | Phosphorylation | Phos
Dephosphorylation | Dephosphorylation | -Phos
Acetylation | Acetylation | Acet
Deacetylation | Deacetylation | -Acet
Hydroxylation | Hydroxylation | Hydr
Dehydroxylation | Dehydroxylation | -Hydr
Glycosylation | Glycosylation | Glyc
Deglycosylation | Deglycosylation | -Glyc
Methylation | Methylation | Meth
Demethylation | Demethylation | -Meth
Ubiquitination | Ubiquitination | Ubiq
Deubiquitination | Deubiquitination | -Ubiq
DNA_methylation | DNA methylation | DNA meth
DNA_demethylation | DNA demethylation | DNA -meth
Catalysis | Catalysis | Catal
[drawing]
SPAN_DEFAULT fgColor:black, bgColor:lightgreen, borderColor:darken
ARC_DEFAULT color:black, arrowHead:triangle-5
ATTRIBUTE_DEFAULT glyph:*
# entities
GGP bgColor:#7fa2ff
Entity bgColor:#b4c8ff
# events
Positive_regulation bgColor:#e0ff00
Catalysis bgColor:#e0ff00
Regulation bgColor:#ffff00
Negative_regulation bgColor:#ffe000
Deacetylation bgColor:#18c59a
Deglycosylation bgColor:#18c59a
Dehydroxylation bgColor:#18c59a
Demethylation bgColor:#18c59a
Dephosphorylation bgColor:#18c59a
Deubiquitination bgColor:#18c59a
DNA_demethylation bgColor:#18c59a
Deacylation bgColor:#18c59a
Dealkylation bgColor:#18c59a
Depalmitoylation bgColor:#18c59a
Delipidation bgColor:#18c59a
Deprenylation bgColor:#18c59a
Deneddylation bgColor:#18c59a
Desumoylation bgColor:#18c59a
# attributes
Negation box:crossed, glyph:<NONE>, dashArray:<NONE>
Speculation dashArray:3-3, glyph:<NONE>
Confidence glyph:↑|↔|↓
| {
"pile_set_name": "Github"
} |
---
title: "UserAgent view"
ms.reviewer:
ms.author: v-lanac
author: lanachin
manager: serdars
ms.date: 3/9/2015
audience: ITPro
ms.topic: article
ms.prod: skype-for-business-itpro
f1.keywords:
- NOCSH
localization_priority: Normal
ms.assetid: b986f76f-f16e-4e5e-96cb-6e8f7f9b42ee
description: "The UserAgent View stores information about the user agents that have been involved in sessions that have records in the database. This view was introduced in Microsoft Lync Server 2013."
---
# UserAgent view
The UserAgent View stores information about the user agents that have been involved in sessions that have records in the database. This view was introduced in Microsoft Lync Server 2013.
|**Column**|**Data Type**|**Details**|
|:-----|:-----|:-----|
|UserAgentKey <br/> |int <br/> |Unique number identifying this user agent. <br/> |
|UserAgent <br/> |nvarchar(256) <br/> |User agent string. <br/> |
|UAType <br/> |smallint <br/> |Type of user agent. See the [UserAgent table](useragent.md) for more details. <br/> |
|UACategory <br/> |nvarchar(64) <br/> |Category that the user agent belongs to. For example, the user agent Conferencing_Attendant_1.0 belongs to the UACategory CAA. <br/> |
| {
"pile_set_name": "Github"
} |
#------------------------------------------------------------------------------
#
# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
# Copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
#------------------------------------------------------------------------------
#include <AsmMacroIoLibV8.h>
ASM_FUNC(GccSemihostCall)
hlt #0xf000
ret
| {
"pile_set_name": "Github"
} |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for tensorflow.python.ops.linalg_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
from absl.testing import parameterized
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops.linalg import linalg
from tensorflow.python.platform import test
def _AddTest(test_class, op_name, testcase_name, fn):
test_name = "_".join(["test", op_name, testcase_name])
if hasattr(test_class, test_name):
raise RuntimeError("Test %s defined more than once" % test_name)
setattr(test_class, test_name, fn)
def _RandomPDMatrix(n, rng, dtype=np.float64):
"""Random positive definite matrix."""
temp = rng.randn(n, n).astype(dtype)
if dtype in [np.complex64, np.complex128]:
temp.imag = rng.randn(n, n)
return np.conj(temp).dot(temp.T)
class CholeskySolveTest(test.TestCase):
def setUp(self):
self.rng = np.random.RandomState(0)
@test_util.run_deprecated_v1
def test_works_with_five_different_random_pos_def_matrices(self):
for n in range(1, 6):
for np_type, atol in [(np.float32, 0.05), (np.float64, 1e-5)]:
with self.session(use_gpu=True):
# Create 2 x n x n matrix
array = np.array(
[_RandomPDMatrix(n, self.rng),
_RandomPDMatrix(n, self.rng)]).astype(np_type)
chol = linalg_ops.cholesky(array)
for k in range(1, 3):
with self.subTest(n=n, np_type=np_type, atol=atol, k=k):
rhs = self.rng.randn(2, n, k).astype(np_type)
x = linalg_ops.cholesky_solve(chol, rhs)
self.assertAllClose(rhs, math_ops.matmul(array, x), atol=atol)
class LogdetTest(test.TestCase):
def setUp(self):
self.rng = np.random.RandomState(42)
@test_util.run_deprecated_v1
def test_works_with_five_different_random_pos_def_matrices(self):
for n in range(1, 6):
for np_dtype, atol in [(np.float32, 0.05), (np.float64, 1e-5),
(np.complex64, 0.05), (np.complex128, 1e-5)]:
with self.subTest(n=n, np_dtype=np_dtype, atol=atol):
matrix = _RandomPDMatrix(n, self.rng, np_dtype)
_, logdet_np = np.linalg.slogdet(matrix)
with self.session(use_gpu=True):
# Create 2 x n x n matrix
# matrix = np.array(
# [_RandomPDMatrix(n, self.rng, np_dtype),
# _RandomPDMatrix(n, self.rng, np_dtype)]).astype(np_dtype)
logdet_tf = linalg.logdet(matrix)
self.assertAllClose(logdet_np, self.evaluate(logdet_tf), atol=atol)
def test_works_with_underflow_case(self):
for np_dtype, atol in [(np.float32, 0.05), (np.float64, 1e-5),
(np.complex64, 0.05), (np.complex128, 1e-5)]:
with self.subTest(np_dtype=np_dtype, atol=atol):
matrix = (np.eye(20) * 1e-6).astype(np_dtype)
_, logdet_np = np.linalg.slogdet(matrix)
with self.session(use_gpu=True):
logdet_tf = linalg.logdet(matrix)
self.assertAllClose(logdet_np, self.evaluate(logdet_tf), atol=atol)
class SlogdetTest(test.TestCase):
def setUp(self):
self.rng = np.random.RandomState(42)
@test_util.run_deprecated_v1
def test_works_with_five_different_random_pos_def_matrices(self):
for n in range(1, 6):
for np_dtype, atol in [(np.float32, 0.05), (np.float64, 1e-5),
(np.complex64, 0.05), (np.complex128, 1e-5)]:
with self.subTest(n=n, np_dtype=np_dtype, atol=atol):
matrix = _RandomPDMatrix(n, self.rng, np_dtype)
sign_np, log_abs_det_np = np.linalg.slogdet(matrix)
with self.session(use_gpu=True):
sign_tf, log_abs_det_tf = linalg.slogdet(matrix)
self.assertAllClose(
log_abs_det_np, self.evaluate(log_abs_det_tf), atol=atol)
self.assertAllClose(sign_np, self.evaluate(sign_tf), atol=atol)
def test_works_with_underflow_case(self):
for np_dtype, atol in [(np.float32, 0.05), (np.float64, 1e-5),
(np.complex64, 0.05), (np.complex128, 1e-5)]:
with self.subTest(np_dtype=np_dtype, atol=atol):
matrix = (np.eye(20) * 1e-6).astype(np_dtype)
sign_np, log_abs_det_np = np.linalg.slogdet(matrix)
with self.session(use_gpu=True):
sign_tf, log_abs_det_tf = linalg.slogdet(matrix)
self.assertAllClose(
log_abs_det_np, self.evaluate(log_abs_det_tf), atol=atol)
self.assertAllClose(sign_np, self.evaluate(sign_tf), atol=atol)
class AdjointTest(test.TestCase):
def test_compare_to_numpy(self):
for dtype in np.float64, np.float64, np.complex64, np.complex128:
with self.subTest(dtype=dtype):
matrix_np = np.array([[1 + 1j, 2 + 2j, 3 + 3j], [4 + 4j, 5 + 5j,
6 + 6j]]).astype(dtype)
expected_transposed = np.conj(matrix_np.T)
with self.session():
matrix = ops.convert_to_tensor(matrix_np)
transposed = linalg.adjoint(matrix)
self.assertEqual((3, 2), transposed.get_shape())
self.assertAllEqual(expected_transposed, self.evaluate(transposed))
class EyeTest(parameterized.TestCase, test.TestCase):
def testShapeInferenceNoBatch(self):
self.assertEqual((2, 2), linalg_ops.eye(num_rows=2).shape)
self.assertEqual((2, 3), linalg_ops.eye(num_rows=2, num_columns=3).shape)
def testShapeInferenceStaticBatch(self):
batch_shape = (2, 3)
self.assertEqual(
(2, 3, 2, 2),
linalg_ops.eye(num_rows=2, batch_shape=batch_shape).shape)
self.assertEqual(
(2, 3, 2, 3),
linalg_ops.eye(
num_rows=2, num_columns=3, batch_shape=batch_shape).shape)
@parameterized.named_parameters(
("DynamicRow",
lambda: array_ops.placeholder_with_default(2, shape=None),
lambda: None),
("DynamicRowStaticColumn",
lambda: array_ops.placeholder_with_default(2, shape=None),
lambda: 3),
("StaticRowDynamicColumn",
lambda: 2,
lambda: array_ops.placeholder_with_default(3, shape=None)),
("DynamicRowDynamicColumn",
lambda: array_ops.placeholder_with_default(2, shape=None),
lambda: array_ops.placeholder_with_default(3, shape=None)))
def testShapeInferenceStaticBatchWith(self, num_rows_fn, num_columns_fn):
num_rows = num_rows_fn()
num_columns = num_columns_fn()
batch_shape = (2, 3)
identity_matrix = linalg_ops.eye(
num_rows=num_rows,
num_columns=num_columns,
batch_shape=batch_shape)
self.assertEqual(4, identity_matrix.shape.ndims)
self.assertEqual((2, 3), identity_matrix.shape[:2])
if num_rows is not None and not isinstance(num_rows, ops.Tensor):
self.assertEqual(2, identity_matrix.shape[-2])
if num_columns is not None and not isinstance(num_columns, ops.Tensor):
self.assertEqual(3, identity_matrix.shape[-1])
@parameterized.parameters(
itertools.product(
# num_rows
[0, 1, 2, 5],
# num_columns
[None, 0, 1, 2, 5],
# batch_shape
[None, [], [2], [2, 3]],
# dtype
[
dtypes.int32,
dtypes.int64,
dtypes.float32,
dtypes.float64,
dtypes.complex64,
dtypes.complex128
])
)
def test_eye_no_placeholder(self, num_rows, num_columns, batch_shape, dtype):
eye_np = np.eye(num_rows, M=num_columns, dtype=dtype.as_numpy_dtype)
if batch_shape is not None:
eye_np = np.tile(eye_np, batch_shape + [1, 1])
eye_tf = self.evaluate(linalg_ops.eye(
num_rows,
num_columns=num_columns,
batch_shape=batch_shape,
dtype=dtype))
self.assertAllEqual(eye_np, eye_tf)
@parameterized.parameters(
itertools.product(
# num_rows
[0, 1, 2, 5],
# num_columns
[0, 1, 2, 5],
# batch_shape
[[], [2], [2, 3]],
# dtype
[
dtypes.int32,
dtypes.int64,
dtypes.float32,
dtypes.float64,
dtypes.complex64,
dtypes.complex128
])
)
@test_util.run_deprecated_v1
def test_eye_with_placeholder(
self, num_rows, num_columns, batch_shape, dtype):
eye_np = np.eye(num_rows, M=num_columns, dtype=dtype.as_numpy_dtype)
eye_np = np.tile(eye_np, batch_shape + [1, 1])
num_rows_placeholder = array_ops.placeholder(
dtypes.int32, name="num_rows")
num_columns_placeholder = array_ops.placeholder(
dtypes.int32, name="num_columns")
batch_shape_placeholder = array_ops.placeholder(
dtypes.int32, name="batch_shape")
eye = linalg_ops.eye(
num_rows_placeholder,
num_columns=num_columns_placeholder,
batch_shape=batch_shape_placeholder,
dtype=dtype)
with self.session(use_gpu=True) as sess:
eye_tf = sess.run(
eye,
feed_dict={
num_rows_placeholder: num_rows,
num_columns_placeholder: num_columns,
batch_shape_placeholder: batch_shape
})
self.assertAllEqual(eye_np, eye_tf)
class _MatrixRankTest(object):
def test_batch_default_tolerance(self):
x_ = np.array(
[
[
[2, 3, -2], # = row2+row3
[-1, 1, -2],
[3, 2, 0]
],
[
[0, 2, 0], # = 2*row2
[0, 1, 0],
[0, 3, 0]
], # = 3*row2
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
],
self.dtype)
x = array_ops.placeholder_with_default(
x_, shape=x_.shape if self.use_static_shape else None)
self.assertAllEqual([2, 1, 3], self.evaluate(linalg.matrix_rank(x)))
def test_custom_tolerance_broadcasts(self):
q = linalg.qr(random_ops.random_uniform([3, 3], dtype=self.dtype))[0]
e = constant_op.constant([0.1, 0.2, 0.3], dtype=self.dtype)
a = linalg.solve(q, linalg.transpose(a=e * q), adjoint=True)
self.assertAllEqual([3, 2, 1, 0],
self.evaluate(
linalg.matrix_rank(
a, tol=[[0.09], [0.19], [0.29], [0.31]])))
def test_nonsquare(self):
x_ = np.array(
[
[
[2, 3, -2, 2], # = row2+row3
[-1, 1, -2, 4],
[3, 2, 0, -2]
],
[
[0, 2, 0, 6], # = 2*row2
[0, 1, 0, 3],
[0, 3, 0, 9]
]
], # = 3*row2
self.dtype)
x = array_ops.placeholder_with_default(
x_, shape=x_.shape if self.use_static_shape else None)
self.assertAllEqual([2, 1], self.evaluate(linalg.matrix_rank(x)))
@test_util.run_all_in_graph_and_eager_modes
class MatrixRankStatic32Test(test.TestCase, _MatrixRankTest):
dtype = np.float32
use_static_shape = True
@test_util.run_all_in_graph_and_eager_modes
class MatrixRankDynamic64Test(test.TestCase, _MatrixRankTest):
dtype = np.float64
use_static_shape = False
class _PinvTest(object):
def expected_pinv(self, a, rcond):
"""Calls `np.linalg.pinv` but corrects its broken batch semantics."""
if a.ndim < 3:
return np.linalg.pinv(a, rcond)
if rcond is None:
rcond = 10. * max(a.shape[-2], a.shape[-1]) * np.finfo(a.dtype).eps
s = np.concatenate([a.shape[:-2], [a.shape[-1], a.shape[-2]]])
a_pinv = np.zeros(s, dtype=a.dtype)
for i in np.ndindex(a.shape[:(a.ndim - 2)]):
a_pinv[i] = np.linalg.pinv(
a[i], rcond=rcond if isinstance(rcond, float) else rcond[i])
return a_pinv
def test_symmetric(self):
a_ = self.dtype([[1., .4, .5], [.4, .2, .25], [.5, .25, .35]])
a_ = np.stack([a_ + 1., a_], axis=0) # Batch of matrices.
a = array_ops.placeholder_with_default(
a_, shape=a_.shape if self.use_static_shape else None)
if self.use_default_rcond:
rcond = None
else:
rcond = self.dtype([0., 0.01]) # Smallest 1 component is forced to zero.
expected_a_pinv_ = self.expected_pinv(a_, rcond)
a_pinv = linalg.pinv(a, rcond, validate_args=True)
a_pinv_ = self.evaluate(a_pinv)
self.assertAllClose(expected_a_pinv_, a_pinv_, atol=2e-5, rtol=2e-5)
if not self.use_static_shape:
return
self.assertAllEqual(expected_a_pinv_.shape, a_pinv.shape)
def test_nonsquare(self):
a_ = self.dtype([[1., .4, .5, 1.], [.4, .2, .25, 2.], [.5, .25, .35, 3.]])
a_ = np.stack([a_ + 0.5, a_], axis=0) # Batch of matrices.
a = array_ops.placeholder_with_default(
a_, shape=a_.shape if self.use_static_shape else None)
if self.use_default_rcond:
rcond = None
else:
# Smallest 2 components are forced to zero.
rcond = self.dtype([0., 0.25])
expected_a_pinv_ = self.expected_pinv(a_, rcond)
a_pinv = linalg.pinv(a, rcond, validate_args=True)
a_pinv_ = self.evaluate(a_pinv)
self.assertAllClose(expected_a_pinv_, a_pinv_, atol=1e-5, rtol=1e-4)
if not self.use_static_shape:
return
self.assertAllEqual(expected_a_pinv_.shape, a_pinv.shape)
@test_util.run_all_in_graph_and_eager_modes
class PinvTestDynamic32DefaultRcond(test.TestCase, _PinvTest):
dtype = np.float32
use_static_shape = False
use_default_rcond = True
@test_util.run_all_in_graph_and_eager_modes
class PinvTestStatic64DefaultRcond(test.TestCase, _PinvTest):
dtype = np.float64
use_static_shape = True
use_default_rcond = True
@test_util.run_all_in_graph_and_eager_modes
class PinvTestDynamic32CustomtRcond(test.TestCase, _PinvTest):
dtype = np.float32
use_static_shape = False
use_default_rcond = False
@test_util.run_all_in_graph_and_eager_modes
class PinvTestStatic64CustomRcond(test.TestCase, _PinvTest):
dtype = np.float64
use_static_shape = True
use_default_rcond = False
def make_tensor_hiding_attributes(value, hide_shape, hide_value=True):
if not hide_value:
return ops.convert_to_tensor(value)
shape = None if hide_shape else getattr(value, "shape", None)
return array_ops.placeholder_with_default(value, shape=shape)
class _LUReconstruct(object):
dtype = np.float32
use_static_shape = True
def test_non_batch(self):
x_ = np.array([[3, 4], [1, 2]], dtype=self.dtype)
x = array_ops.placeholder_with_default(
x_, shape=x_.shape if self.use_static_shape else None)
y = linalg.lu_reconstruct(*linalg.lu(x), validate_args=True)
y_ = self.evaluate(y)
if self.use_static_shape:
self.assertAllEqual(x_.shape, y.shape)
self.assertAllClose(x_, y_, atol=0., rtol=1e-3)
def test_batch(self):
x_ = np.array([
[[3, 4], [1, 2]],
[[7, 8], [3, 4]],
], dtype=self.dtype)
x = array_ops.placeholder_with_default(
x_, shape=x_.shape if self.use_static_shape else None)
y = linalg.lu_reconstruct(*linalg.lu(x), validate_args=True)
y_ = self.evaluate(y)
if self.use_static_shape:
self.assertAllEqual(x_.shape, y.shape)
self.assertAllClose(x_, y_, atol=0., rtol=1e-3)
@test_util.run_all_in_graph_and_eager_modes
class LUReconstructStatic(test.TestCase, _LUReconstruct):
use_static_shape = True
@test_util.run_all_in_graph_and_eager_modes
class LUReconstructDynamic(test.TestCase, _LUReconstruct):
use_static_shape = False
class _LUMatrixInverse(object):
dtype = np.float32
use_static_shape = True
def test_non_batch(self):
x_ = np.array([[1, 2], [3, 4]], dtype=self.dtype)
x = array_ops.placeholder_with_default(
x_, shape=x_.shape if self.use_static_shape else None)
y = linalg.lu_matrix_inverse(*linalg.lu(x), validate_args=True)
y_ = self.evaluate(y)
if self.use_static_shape:
self.assertAllEqual(x_.shape, y.shape)
self.assertAllClose(np.linalg.inv(x_), y_, atol=0., rtol=1e-3)
def test_batch(self):
x_ = np.array([
[[1, 2], [3, 4]],
[[7, 8], [3, 4]],
[[0.25, 0.5], [0.75, -2.]],
],
dtype=self.dtype)
x = array_ops.placeholder_with_default(
x_, shape=x_.shape if self.use_static_shape else None)
y = linalg.lu_matrix_inverse(*linalg.lu(x), validate_args=True)
y_ = self.evaluate(y)
if self.use_static_shape:
self.assertAllEqual(x_.shape, y.shape)
self.assertAllClose(np.linalg.inv(x_), y_, atol=0., rtol=1e-3)
@test_util.run_all_in_graph_and_eager_modes
class LUMatrixInverseStatic(test.TestCase, _LUMatrixInverse):
use_static_shape = True
@test_util.run_all_in_graph_and_eager_modes
class LUMatrixInverseDynamic(test.TestCase, _LUMatrixInverse):
use_static_shape = False
class _LUSolve(object):
dtype = np.float32
use_static_shape = True
def test_non_batch(self):
x_ = np.array([[1, 2], [3, 4]], dtype=self.dtype)
x = array_ops.placeholder_with_default(
x_, shape=x_.shape if self.use_static_shape else None)
rhs_ = np.array([[1, 1]], dtype=self.dtype).T
rhs = array_ops.placeholder_with_default(
rhs_, shape=rhs_.shape if self.use_static_shape else None)
lower_upper, perm = linalg.lu(x)
y = linalg.lu_solve(lower_upper, perm, rhs, validate_args=True)
y_, perm_ = self.evaluate([y, perm])
self.assertAllEqual([1, 0], perm_)
expected_ = np.linalg.solve(x_, rhs_)
if self.use_static_shape:
self.assertAllEqual(expected_.shape, y.shape)
self.assertAllClose(expected_, y_, atol=0., rtol=1e-3)
def test_batch_broadcast(self):
x_ = np.array([
[[1, 2], [3, 4]],
[[7, 8], [3, 4]],
[[0.25, 0.5], [0.75, -2.]],
],
dtype=self.dtype)
x = array_ops.placeholder_with_default(
x_, shape=x_.shape if self.use_static_shape else None)
rhs_ = np.array([[1, 1]], dtype=self.dtype).T
rhs = array_ops.placeholder_with_default(
rhs_, shape=rhs_.shape if self.use_static_shape else None)
lower_upper, perm = linalg.lu(x)
y = linalg.lu_solve(lower_upper, perm, rhs, validate_args=True)
y_, perm_ = self.evaluate([y, perm])
self.assertAllEqual([[1, 0], [0, 1], [1, 0]], perm_)
expected_ = np.linalg.solve(x_, rhs_[np.newaxis])
if self.use_static_shape:
self.assertAllEqual(expected_.shape, y.shape)
self.assertAllClose(expected_, y_, atol=0., rtol=1e-3)
@test_util.run_all_in_graph_and_eager_modes
class LUSolveStatic(test.TestCase, _LUSolve):
use_static_shape = True
@test_util.run_all_in_graph_and_eager_modes
class LUSolveDynamic(test.TestCase, _LUSolve):
use_static_shape = False
if __name__ == "__main__":
test.main()
| {
"pile_set_name": "Github"
} |
package ieproxy
import "golang.org/x/sys/windows"
var winHttp = windows.NewLazySystemDLL("winhttp.dll")
var winHttpGetProxyForURL = winHttp.NewProc("WinHttpGetProxyForUrl")
var winHttpOpen = winHttp.NewProc("WinHttpOpen")
var winHttpCloseHandle = winHttp.NewProc("WinHttpCloseHandle")
var winHttpGetIEProxyConfigForCurrentUser = winHttp.NewProc("WinHttpGetIEProxyConfigForCurrentUser")
type tWINHTTP_AUTOPROXY_OPTIONS struct {
dwFlags autoProxyFlag
dwAutoDetectFlags autoDetectFlag
lpszAutoConfigUrl *uint16
lpvReserved *uint16
dwReserved uint32
fAutoLogonIfChallenged bool
}
type autoProxyFlag uint32
const (
fWINHTTP_AUTOPROXY_AUTO_DETECT = autoProxyFlag(0x00000001)
fWINHTTP_AUTOPROXY_CONFIG_URL = autoProxyFlag(0x00000002)
fWINHTTP_AUTOPROXY_NO_CACHE_CLIENT = autoProxyFlag(0x00080000)
fWINHTTP_AUTOPROXY_NO_CACHE_SVC = autoProxyFlag(0x00100000)
fWINHTTP_AUTOPROXY_NO_DIRECTACCESS = autoProxyFlag(0x00040000)
fWINHTTP_AUTOPROXY_RUN_INPROCESS = autoProxyFlag(0x00010000)
fWINHTTP_AUTOPROXY_RUN_OUTPROCESS_ONLY = autoProxyFlag(0x00020000)
fWINHTTP_AUTOPROXY_SORT_RESULTS = autoProxyFlag(0x00400000)
)
type autoDetectFlag uint32
const (
fWINHTTP_AUTO_DETECT_TYPE_DHCP = autoDetectFlag(0x00000001)
fWINHTTP_AUTO_DETECT_TYPE_DNS_A = autoDetectFlag(0x00000002)
)
type tWINHTTP_PROXY_INFO struct {
dwAccessType uint32
lpszProxy *uint16
lpszProxyBypass *uint16
}
type tWINHTTP_CURRENT_USER_IE_PROXY_CONFIG struct {
fAutoDetect bool
lpszAutoConfigUrl *uint16
lpszProxy *uint16
lpszProxyBypass *uint16
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* ZenTaoPHP的baseHelper类。
* The baseHelper class file of ZenTaoPHP framework.
*
* @package framework
*
* The author disclaims copyright to this source code. In place of
* a legal notice, here is a blessing:
*
* May you do good and not evil.
* May you find forgiveness for yourself and forgive others.
* May you share freely, never taking more than you give.
*/
class baseHelper
{
/**
* 设置一个对象的成员变量。
* Set the member's value of one object.
* <code>
* <?php
* $lang->db->user = 'wwccss';
* helper::setMember('lang', 'db.user', 'chunsheng.wang');
* ?>
* </code>
* @param string $objName the var name of the object.
* @param string $key the key of the member, can be parent.child.
* @param mixed $value the value to be set.
* @static
* @access public
* @return bool
*/
static public function setMember($objName, $key, $value)
{
global $$objName;
if(!is_object($$objName) or empty($key)) return false;
$key = str_replace('.', '->', $key);
$value = serialize($value);
$code = ("\$${objName}->{$key}=unserialize(<<<EOT\n$value\nEOT\n);");
eval($code);
return true;
}
/**
* 生成一个模块方法的链接。control类的createLink实际上调用的是这个方法。
* Create a link to a module's method, mapped in control class to call conveniently.
*
* <code>
* <?php
* helper::createLink('hello', 'index', 'var1=value1&var2=value2');
* helper::createLink('hello', 'index', array('var1' => 'value1', 'var2' => 'value2');
* ?>
* </code>
* @param string $moduleName module name, can pass appName like app.module.
* @param string $methodName method name
* @param string|array $vars the params passed to the method, can be array('key' => 'value') or key1=value1&key2=value2) or key1=value1&key2=value2
* @param string $viewType the view type
* @param bool $onlyBody pass onlyBody=yes to the link thus the app can control the header and footer hide or show..
* @static
* @access public
* @return string the link string.
*/
static public function createLink($moduleName, $methodName = 'index', $vars = '', $viewType = '', $onlyBody = false)
{
/* 设置$appName和$moduleName。Set appName and moduleName. */
global $app, $config;
if(strpos($moduleName, '.') !== false)
{
list($appName, $moduleName) = explode('.', $moduleName);
}
else
{
$appName = $app->getAppName();
}
if(!empty($appName)) $appName .= '/';
/* 处理$viewType和$vars。Set $viewType and $vars. */
if(empty($viewType)) $viewType = $app->getViewType();
if(!is_array($vars)) parse_str($vars, $vars);
/* 生成url链接的开始部分。Set the begin parts of the link. */
if($config->requestType == 'PATH_INFO') $link = $config->webRoot . $appName;
if($config->requestType != 'PATH_INFO') $link = $config->webRoot . $appName . basename($_SERVER['SCRIPT_NAME']);
if($config->requestType == 'PATH_INFO2') $link .= '/';
/**
* #1: RequestType为GET。When the requestType is GET.
* Input: moduleName=article&methodName=index&var1=value1. Output: ?m=article&f=index&var1=value1.
*
*/
if($config->requestType == 'GET')
{
$link .= "?{$config->moduleVar}=$moduleName&{$config->methodVar}=$methodName";
if($viewType != 'html') $link .= "&{$config->viewVar}=" . $viewType;
foreach($vars as $key => $value) $link .= "&$key=$value";
return self::processOnlyBodyParam($link, $onlyBody);
}
/**
* #2: 方法名不是默认值或者是默认值,但有传参。MethodName equals the default method or vars not empty.
* Input: moduleName=article&methodName=view. Output: article-view.html
* Input: moduleName=article&methodName=view. Output: article-index-abc.html
*
*/
if($methodName != $config->default->method or !empty($vars))
{
$link .= "$moduleName{$config->requestFix}$methodName";
foreach($vars as $value) $link .= "{$config->requestFix}$value";
$link .= '.' . $viewType;
return self::processOnlyBodyParam($link, $onlyBody);
}
/**
* #3: 方法名为默认值且没有传参且模块名为默认值。MethodName is the default and moduleName is default and vars empty.
* Input: moduleName=index&methodName=index. Output: index.html
*
*/
if($moduleName == $config->default->module)
{
$link .= $config->default->method . '.' . $viewType;
return self::processOnlyBodyParam($link, $onlyBody);
}
/**
* #4: 方法名为默认值且没有传参且模块名不为默认值,viewType和app指定的相等。MethodName is default but moduleName not and viewType equal app's viewType..
* Input: moduleName=article&methodName=index&viewType=html. Output: /article/
*
*/
if($viewType == $app->getViewType())
{
$link .= $moduleName . '/';
return self::processOnlyBodyParam($link, $onlyBody);
}
/**
* #5: 方法名为默认值且没有传参且模块名不为默认值,viewType有另外指定。MethodName is default but moduleName not and viewType no equls app's viewType.
* Input: moduleName=article&methodName=index&viewType=json. Output: /article.json
*
*/
$link .= $moduleName . '.' . $viewType;
return self::processOnlyBodyParam($link, $onlyBody);
}
/**
* 处理onlyBody 参数。
* Process the onlyBody param in url.
*
* 如果传参的时候设定了$onlyBody为真,或者当前页面请求中包含了onlybody=yes,在生成链接的时候继续追加。
* If $onlyBody set to true or onlybody=yes in the url, append onlyBody param to the link.
*
* @param string $link
* @param bool $onlyBody
* @static
* @access public
* @return string
*/
public static function processOnlyBodyParam($link, $onlyBody = false)
{
global $config;
if(!$onlyBody and !self::inOnlyBodyMode()) return $link;
$onlybodyString = $config->requestType != 'GET' ? "?onlybody=yes" : "&onlybody=yes";
return $link . $onlybodyString;
}
/**
* 检查是否是onlybody模式。
* Check in only body mode or not.
*
* @access public
* @return void
*/
public static function inOnlyBodyMode()
{
return (isset($_GET['onlybody']) and $_GET['onlybody'] == 'yes');
}
/**
* 使用helper::import()来引入文件,不要直接使用include或者require.
* Using helper::import() to import a file, instead of include or require.
*
* @param string $file the file to be imported.
* @static
* @access public
* @return bool
*/
static public function import($file)
{
$file = realpath($file);
if(!is_file($file)) return false;
static $includedFiles = array();
if(!isset($includedFiles[$file]))
{
include $file;
$includedFiles[$file] = true;
return true;
}
return true;
}
/**
* 将数组或者列表转化成 IN( 'a', 'b') 的形式。
* Convert a list to IN('a', 'b') string.
*
* @param string|array $idList 列表,可以是数组或者用逗号隔开的列表。The id lists, can be a array or a string joined with comma.
* @static
* @access public
* @return string the string like IN('a', 'b').
*/
static public function dbIN($idList)
{
if(is_array($idList))
{
if(!function_exists('get_magic_quotes_gpc') or !get_magic_quotes_gpc())
{
foreach ($idList as $key=>$value) $idList[$key] = addslashes($value);
}
return "IN ('" . join("','", $idList) . "')";
}
if(!function_exists('get_magic_quotes_gpc') or !get_magic_quotes_gpc()) $idList = addslashes($idList);
return "IN ('" . str_replace(',', "','", str_replace(' ', '', $idList)) . "')";
}
/**
* 安全的Base64编码,框架对'/'字符比较敏感,转换为'.'。
* Create safe base64 encoded string for the framework.
*
* @param string $string the string to encode.
* @static
* @access public
* @return string encoded string.
*/
static public function safe64Encode($string)
{
return strtr(base64_encode($string), '/', '.');
}
/**
* 解码base64,先将之前的'.' 转换回'/'
* Decode the string encoded by safe64Encode.
*
* @param string $string the string to decode
* @static
* @access public
* @return string decoded string.
*/
static public function safe64Decode($string)
{
return base64_decode(strtr($string, '.', '/'));
}
/**
* JSON编码,自动处理转义的问题。
* JSON encode, process the slashes.
*
* @param mixed $data the object to encode
* @static
* @access public
* @return string decoded string.
*/
static public function jsonEncode($data)
{
return (function_exists('get_magic_quotes_gpc') and get_magic_quotes_gpc()) ? addslashes(json_encode($data)) : json_encode($data);
}
/**
* 判断是否是utf8编码
* Judge a string is utf-8 or not.
*
* @author [email protected]
* @param string $string
* @see http://php.net/manual/en/function.mb-detect-encoding.php
* @static
* @access public
* @return bool
*/
static public function isUTF8($string)
{
$c = 0;
$b = 0;
$bits = 0;
$len = strlen($string);
for($i=0; $i<$len; $i++)
{
$c = ord($string[$i]);
if($c > 128)
{
if(($c >= 254)) return false;
elseif($c >= 252) $bits=6;
elseif($c >= 248) $bits=5;
elseif($c >= 240) $bits=4;
elseif($c >= 224) $bits=3;
elseif($c >= 192) $bits=2;
else return false;
if(($i+$bits) > $len) return false;
while($bits > 1)
{
$i++;
$b=ord($string[$i]);
if($b < 128 || $b > 191) return false;
$bits--;
}
}
}
return true;
}
/**
* 去掉UTF-8 Bom头。
* Remove UTF-8 Bom.
*
* @param string $string
* @access public
* @return string
*/
public static function removeUTF8Bom($string)
{
if(substr($string, 0, 3) == pack('CCC', 239, 187, 191)) return substr($string, 3);
return $string;
}
/**
* 增强substr方法:支持多字节语言,比如中文。
* Enhanced substr version: support multibyte languages like Chinese.
*
* @param string $string
* @param int $length
* @param string $append
* @return string
*/
public static function substr($string, $length, $append = '')
{
$rawString = $string;
if(function_exists('mb_substr')) $string = mb_substr($string, 0, $length, 'utf-8');
preg_match_all("/./su", $string, $data);
$string = join("", array_slice($data[0], 0, $length));
return ($string != $rawString) ? $string . $append : $string;
}
/**
* Get browser name and version.
*
* @access public
* @return array
*/
public static function getBrowser()
{
$browser = array('name'=>'unknown', 'version'=>'unknown');
if(empty($_SERVER['HTTP_USER_AGENT'])) return $browser;
$agent = $_SERVER["HTTP_USER_AGENT"];
/* Chrome should checked before safari.*/
if(strpos($agent, 'Firefox') !== false) $browser['name'] = "firefox";
if(strpos($agent, 'Opera') !== false) $browser['name'] = 'opera';
if(strpos($agent, 'Safari') !== false) $browser['name'] = 'safari';
if(strpos($agent, 'Chrome') !== false) $browser['name'] = "chrome";
/* Check the name of browser */
if(strpos($agent, 'MSIE') !== false || strpos($agent, 'rv:11.0')) $browser['name'] = 'ie';
if(strpos($agent, 'Edge') !== false) $browser['name'] = 'edge';
/* Check the version of browser */
if(preg_match('/MSIE\s(\d+)\..*/i', $agent, $regs)) $browser['version'] = $regs[1];
if(preg_match('/FireFox\/(\d+)\..*/i', $agent, $regs)) $browser['version'] = $regs[1];
if(preg_match('/Opera[\s|\/](\d+)\..*/i', $agent, $regs)) $browser['version'] = $regs[1];
if(preg_match('/Chrome\/(\d+)\..*/i', $agent, $regs)) $browser['version'] = $regs[1];
if((strpos($agent, 'Chrome') == false) && preg_match('/Safari\/(\d+)\..*$/i', $agent, $regs)) $browser['version'] = $regs[1];
if(preg_match('/rv:(\d+)\..*/i', $agent, $regs)) $browser['version'] = $regs[1];
if(preg_match('/Edge\/(\d+)\..*/i', $agent, $regs)) $browser['version'] = $regs[1];
return $browser;
}
/**
* Get client os from agent info.
*
* @static
* @access public
* @return string
*/
public static function getOS()
{
if(empty($_SERVER['HTTP_USER_AGENT'])) return 'unknow';
$osList = array();
$osList['/windows nt 10/i'] = 'Windows 10';
$osList['/windows nt 6.3/i'] = 'Windows 8.1';
$osList['/windows nt 6.2/i'] = 'Windows 8';
$osList['/windows nt 6.1/i'] = 'Windows 7';
$osList['/windows nt 6.0/i'] = 'Windows Vista';
$osList['/windows nt 5.2/i'] = 'Windows Server 2003/XP x64';
$osList['/windows nt 5.1/i'] = 'Windows XP';
$osList['/windows xp/i'] = 'Windows XP';
$osList['/windows nt 5.0/i'] = 'Windows 2000';
$osList['/windows me/i'] = 'Windows ME';
$osList['/win98/i'] = 'Windows 98';
$osList['/win95/i'] = 'Windows 95';
$osList['/win16/i'] = 'Windows 3.11';
$osList['/macintosh|mac os x/i'] = 'Mac OS X';
$osList['/mac_powerpc/i'] = 'Mac OS 9';
$osList['/linux/i'] = 'Linux';
$osList['/ubuntu/i'] = 'Ubuntu';
$osList['/iphone/i'] = 'iPhone';
$osList['/ipod/i'] = 'iPod';
$osList['/ipad/i'] = 'iPad';
$osList['/android/i'] = 'Android';
$osList['/blackberry/i'] = 'BlackBerry';
$osList['/webos/i'] = 'Mobile';
foreach ($osList as $regex => $value)
{
if(preg_match($regex, $_SERVER['HTTP_USER_AGENT'])) return $value;
}
return 'unknown';
}
/**
* 计算两个日期相差的天数,取整。
* Compute the diff days of two date.
*
* @param string $date1 the first date.
* @param string $date2 the sencond date.
* @access public
* @return int the diff of the two days.
*/
static public function diffDate($date1, $date2)
{
return round((strtotime($date1) - strtotime($date2)) / 86400, 0);
}
/**
* 获取当前时间,使用common语言文件定义的DT_DATETIME1常量。
* Get now time use the DT_DATETIME1 constant defined in the lang file.
*
* @access public
* @return datetime now
*/
static public function now()
{
return date(DT_DATETIME1);
}
/**
* 获取当前日期,使用common语言文件定义的DT_DATE1常量。
* Get today according to the DT_DATE1 constant defined in the lang file.
*
* @access public
* @return date today
*/
static public function today()
{
return date(DT_DATE1);
}
/**
* 获取当前日期,使用common语言文件定义的DT_TIME1常量。
* Get now time use the DT_TIME1 constant defined in the lang file.
*
* @access public
* @return date today
*/
static public function time()
{
return date(DT_TIME1);
}
/**
* 判断日期是不是零。
* Judge a date is zero or not.
*
* @access public
* @return bool
*/
static public function isZeroDate($date)
{
return substr($date, 0, 4) == '0000';
}
/**
* 列出目录中符合该正则表达式的文件。
* Get files match the pattern under a directory.
*
* @access public
* @return array the files match the pattern
*/
static public function ls($dir, $pattern = '')
{
if(empty($dir)) return array();
$files = array();
$dir = realpath($dir);
if(is_dir($dir)) $files = glob($dir . DIRECTORY_SEPARATOR . '*' . $pattern);
return empty($files) ? array() : $files;
}
/**
* 切换目录。第一次调用的时候记录当前的路径,再次调用的时候切换回之前的路径。
* Change directory: first call, save the $cwd, secend call, change to $cwd.
*
* @param string $path
* @static
* @access public
* @return void
*/
static function cd($path = '')
{
static $cwd = '';
if($path) $cwd = getcwd();
!empty($path) ? chdir($path) : chdir($cwd);
}
/**
* 通过域名获取站点代号。
* Get siteCode for a domain.
*
* www.xirang.com => xirang
* xirang.com => xirang
* xirang.com.cn => xirang
* xirang.cn => xirang
* xirang => xirang
*
* @param string $domain
* @return string $siteCode
**/
public static function parseSiteCode($domain)
{
global $config;
/* 去除域名中的端口部分。Remove the port part of the domain. */
if(strpos($domain, ':') !== false) $domain = substr($domain, 0, strpos($domain, ':'));
$domain = strtolower($domain);
/* $config里面有定义或者是localhost,直接返回。 Return directly if defined in $config or is localhost. */
if(isset($config->siteCodeList[$domain])) return $config->siteCodeList[$domain];
if($domain == 'localhost') return $domain;
/* 将域名中的-改为_。Replace '-' with '_' in the domain. */
$domain = str_replace('-', '_', $domain);
$items = explode('.', $domain);
/* 类似a.com的形式。 Domain like a.com. */
$postfix = str_replace($items[0] . '.', '', $domain);
if(isset($config->domainPostfix) and strpos($config->domainPostfix, "|$postfix|") !== false) return $items[0];
/* 类似www.a.com的形式。 Domain like www.a.com. */
$postfix = str_replace($items[0] . '.' . $items[1] . '.', '', $domain);
if(isset($config->domainPostfix) and strpos($config->domainPostfix, "|$postfix|") !== false) return $items[1];
/* 类似xxx.sub.a.com的形式。 Domain like xxx.sub.a.com. */
$postfix = str_replace($items[0] . '.' . $items[1] . '.' . $items[2] . '.', '', $domain);
if(isset($config->domainPostfix) and strpos($config->domainPostfix, "|$postfix|") !== false) return $items[0];
return '';
}
/**
* 检查是否是AJAX请求。
* Check is ajax request.
*
* @static
* @access public
* @return bool
*/
public static function isAjaxRequest()
{
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') return true;
if(isset($_GET['HTTP_X_REQUESTED_WITH']) && $_GET['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') return true;
return false;
}
/**
* 301跳转。
* Header 301 Moved Permanently.
*
* @param string $locate
* @access public
* @return void
*/
public static function header301($locate)
{
header('HTTP/1.1 301 Moved Permanently');
die(header('Location:' . $locate));
}
/**
* 获取远程IP。
* Get remote ip.
*
* @access public
* @return string
*/
public static function getRemoteIp()
{
$ip = '';
if(!empty($_SERVER["REMOTE_ADDR"])) $ip = $_SERVER["REMOTE_ADDR"];
if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
if(!empty($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP'];
return $ip;
}
}
//------------------------------- 常用函数。Some tool functions.-------------------------------//
/**
* helper::createLink()的别名,方便创建本模块方法的链接。
* The short alias of helper::createLink() method to create link to control method of current module.
*
* @param string $methodName the method name
* @param string|array $vars the params passed to the method, can be array('key' => 'value') or key1=value1&key2=value2)
* @param string $viewType
* @return string the link string.
*/
function inLink($methodName = 'index', $vars = '', $viewType = '')
{
global $app;
return helper::createLink($app->getModuleName(), $methodName, $vars, $viewType);
}
/**
* 通过一个静态游标,可以遍历数组。
* Static cycle a array.
*
* @param array $items the array to be cycled.
* @return mixed
*/
function cycle($items)
{
static $i = 0;
if(!is_array($items)) $items = explode(',', $items);
if(!isset($items[$i])) $i = 0;
return $items[$i++];
}
/**
* 获取当前时间的Unix时间戳,精确到微妙。
* Get current microtime.
*
* @access public
* @return float current time.
*/
function getTime()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
/**
* 打印变量的信息
* dump a var.
*
* @param mixed $var
* @access public
* @return void
*/
function a($var)
{
echo "<xmp class='a-left'>";
print_r($var);
echo "</xmp>";
}
/**
* 判断是否内外IP。
* Judge the server ip is local or not.
*
* @access public
* @return void
*/
function isLocalIP()
{
global $config;
if(isset($config->islocalIP)) return $config->isLocalIP;
$serverIP = $_SERVER['SERVER_ADDR'];
if($serverIP == '127.0.0.1') return true;
if(strpos($serverIP, '10.70') !== false) return false;
return !filter_var($serverIP, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);
}
/**
* 获取webRoot。
* Get web root.
*
* @access public
* @return string
*/
function getWebRoot($full = false)
{
$path = $_SERVER['SCRIPT_NAME'];
if(PHP_SAPI == 'cli')
{
if(isset($_SERVER['argv'][1]))
{
$url = parse_url($_SERVER['argv'][1]);
$path = empty($url['path']) ? '/' : rtrim($url['path'], '/');
}
$path = empty($path) ? '/' : preg_replace('/\/www$/', '/www/', $path);
}
if($full)
{
$http = (isset($_SERVER['HTTPS']) and strtolower($_SERVER['HTTPS']) != 'off') ? 'https://' : 'http://';
return $http . $_SERVER['HTTP_HOST'] . substr($path, 0, (strrpos($path, '/') + 1));
}
$path = substr($path, 0, (strrpos($path, '/') + 1));
$path = str_replace('\\', '/', $path);
return $path;
}
/**
* 当数组/对象变量$var存在$key项时,返回存在的对应值或设定值,否则返回$key或不存在的设定值。
* When the $var has the $key, return it, esle result one default value.
*
* @param array|object $var
* @param string|int $key
* @param mixed $valueWhenNone value when the key not exits.
* @param mixed $valueWhenExists value when the key exits.
* @access public
* @return string
*/
function zget($var, $key, $valueWhenNone = false, $valueWhenExists = false)
{
if(!is_array($var) and !is_object($var)) return false;
$type = is_array($var) ? 'array' : 'object';
$checkExists = $type == 'array' ? isset($var[$key]) : isset($var->$key);
if($checkExists)
{
if($valueWhenExists !== false) return $valueWhenExists;
return $type == 'array' ? $var[$key] : $var->$key;
}
if($valueWhenNone !== false) return $valueWhenNone;
return $key;
}
| {
"pile_set_name": "Github"
} |
// ie9- setTimeout & setInterval additional parameters fix
var global = require('./$.global')
, $export = require('./$.export')
, invoke = require('./$.invoke')
, partial = require('./$.partial')
, navigator = global.navigator
, MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
var wrap = function(set){
return MSIE ? function(fn, time /*, ...args */){
return set(invoke(
partial,
[].slice.call(arguments, 2),
typeof fn == 'function' ? fn : Function(fn)
), time);
} : set;
};
$export($export.G + $export.B + $export.F * MSIE, {
setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
}); | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">{
"Info": [
{
"IsSuccess": "True",
"InAddress": "嘉義縣新港鄉宮前村中山路167號",
"InSRS": "EPSG:4326",
"InFuzzyType": "[單雙號機制]+[最近門牌號機制]",
"InFuzzyBuffer": "0",
"InIsOnlyFullMatch": "False",
"InIsLockCounty": "True",
"InIsLockTown": "False",
"InIsLockVillage": "False",
"InIsLockRoadSection": "False",
"InIsLockLane": "False",
"InIsLockAlley": "False",
"InIsLockArea": "False",
"InIsSameNumber_SubNumber": "True",
"InCanIgnoreVillage": "True",
"InCanIgnoreNeighborhood": "True",
"InReturnMaxCount": "0",
"OutTotal": "1",
"OutMatchType": "完全比對",
"OutMatchCode": "[嘉義縣]\tFULL:1",
"OutTraceInfo": "[嘉義縣]\t { 完全比對 } 找到符合的門牌地址"
}
],
"AddressList": [
{
"FULL_ADDR": "嘉義縣新港鄉宮前村23鄰中山路167號",
"COUNTY": "嘉義縣",
"TOWN": "新港鄉",
"VILLAGE": "宮前村",
"NEIGHBORHOOD": "23鄰",
"ROAD": "中山路",
"SECTION": "",
"LANE": "",
"ALLEY": "",
"SUB_ALLEY": "",
"TONG": "",
"NUMBER": "167號",
"X": 120.347671,
"Y": 23.552354
}
]
}</string> | {
"pile_set_name": "Github"
} |
<?php defined('SYSPATH') or die('No direct script access.');
/*************************************************************************
* Copyright (C) 2012 Michel A. Mayer *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
class emboss_event_Core {
static function admin_menu($menu,$theme) {
module::set_var('emboss','admin_menu',1);
$menu->get('content_menu')
->append(
Menu::factory('link')
->id('emboss')
->label(t('Emboss'))
->url(url::site('admin/emboss')));
}
static function item_moved($item,$olddir)
{
if( ! ($item->is_photo() || $item->is_album()) ) {
return;
}
$name = $item->name;
$old_path = $olddir->file_path() . '/' . $name;
$new_path = $item->file_path();
if( $new_path == $old_path) {
return;
}
$old_orig = str_replace(VARPATH . 'albums/', VARPATH . 'originals/', $old_path);
$new_orig = str_replace(VARPATH . 'albums/', VARPATH . 'originals/', $new_path);
$new_dir = str_replace('/'.$name , '',$new_orig);
if( file_exists($old_orig))
{
emboss::mkdir_recursive($new_dir);
@rename($old_orig,$new_orig);
log::info('emboss','Moved '.$item->name.' to '.str_replace(VARPATH,'',$new_dir));
}
}
static function item_updated($original,$item)
{
if( ! ($item->is_photo() || $item->is_album()) ) {
return;
}
$oldpath = $original->file_path();
$newpath = $item->file_path();
if( $oldpath != $newpath ) {
$oldorig = str_replace(VARPATH.'albums/',VARPATH.'originals/',$oldpath);
$neworig = str_replace(VARPATH.'albums/',VARPATH.'originals/',$newpath);
log::info('emboss',"rename $oldorig to $neworig");
@rename($oldorig,$neworig);
}
}
static function item_deleted($item)
{
if( ! $item->is_photo() ) {
return;
}
$name = $item->name;
$id = $item->id;
$path = $item->file_path();
$orig = str_replace(VARPATH.'albums/',VARPATH.'originals/',$path);
@unlink($orig);
db::build()
->from('emboss_mappings')
->where('image_id','=',$id)
->delete()
->execute();
log::info('emboss',"item_deleted: $name");
}
static function item_created($item)
{
if( ! $item->is_photo() ) {
return;
}
$path = $item->file_path();
$dirs = explode('/',$path);
array_pop($dirs);
$dir = implode('/',$dirs);
$orig = str_replace(VARPATH.'albums/',VARPATH.'originals/',$path);
$origdir = str_replace(VARPATH.'albums/',VARPATH.'originals/',$dir);
emboss::mkdir_recursive($origdir);
@copy($path,$orig);
$q = ORM::factory('emboss_mapping');
$q->image_id = $item->id;
$q->best_overlay_id = emboss::determine_best_overlay($item);
$q->cur_overlay_id = -1;
$q->cur_gravity = '';
$q->cur_transparency = -1;
$q->save();
emboss::check_for_dirty();
}
}
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0+ */
/*
* c67x00.h: Cypress C67X00 USB register and field definitions
*
* Copyright (C) 2006-2008 Barco N.V.
* Derived from the Cypress cy7c67200/300 ezusb linux driver and
* based on multiple host controller drivers inside the linux kernel.
*/
#ifndef _USB_C67X00_H
#define _USB_C67X00_H
#include <linux/spinlock.h>
#include <linux/platform_device.h>
#include <linux/completion.h>
#include <linux/mutex.h>
/* ---------------------------------------------------------------------
* Cypress C67x00 register definitions
*/
/* Hardware Revision Register */
#define HW_REV_REG 0xC004
/* General USB registers */
/* ===================== */
/* USB Control Register */
#define USB_CTL_REG(x) ((x) ? 0xC0AA : 0xC08A)
#define LOW_SPEED_PORT(x) ((x) ? 0x0800 : 0x0400)
#define HOST_MODE 0x0200
#define PORT_RES_EN(x) ((x) ? 0x0100 : 0x0080)
#define SOF_EOP_EN(x) ((x) ? 0x0002 : 0x0001)
/* USB status register - Notice it has different content in hcd/udc mode */
#define USB_STAT_REG(x) ((x) ? 0xC0B0 : 0xC090)
#define EP0_IRQ_FLG 0x0001
#define EP1_IRQ_FLG 0x0002
#define EP2_IRQ_FLG 0x0004
#define EP3_IRQ_FLG 0x0008
#define EP4_IRQ_FLG 0x0010
#define EP5_IRQ_FLG 0x0020
#define EP6_IRQ_FLG 0x0040
#define EP7_IRQ_FLG 0x0080
#define RESET_IRQ_FLG 0x0100
#define SOF_EOP_IRQ_FLG 0x0200
#define ID_IRQ_FLG 0x4000
#define VBUS_IRQ_FLG 0x8000
/* USB Host only registers */
/* ======================= */
/* Host n Control Register */
#define HOST_CTL_REG(x) ((x) ? 0xC0A0 : 0xC080)
#define PREAMBLE_EN 0x0080 /* Preamble enable */
#define SEQ_SEL 0x0040 /* Data Toggle Sequence Bit Select */
#define ISO_EN 0x0010 /* Isochronous enable */
#define ARM_EN 0x0001 /* Arm operation */
/* Host n Interrupt Enable Register */
#define HOST_IRQ_EN_REG(x) ((x) ? 0xC0AC : 0xC08C)
#define SOF_EOP_IRQ_EN 0x0200 /* SOF/EOP Interrupt Enable */
#define SOF_EOP_TMOUT_IRQ_EN 0x0800 /* SOF/EOP Timeout Interrupt Enable */
#define ID_IRQ_EN 0x4000 /* ID interrupt enable */
#define VBUS_IRQ_EN 0x8000 /* VBUS interrupt enable */
#define DONE_IRQ_EN 0x0001 /* Done Interrupt Enable */
/* USB status register */
#define HOST_STAT_MASK 0x02FD
#define PORT_CONNECT_CHANGE(x) ((x) ? 0x0020 : 0x0010)
#define PORT_SE0_STATUS(x) ((x) ? 0x0008 : 0x0004)
/* Host Frame Register */
#define HOST_FRAME_REG(x) ((x) ? 0xC0B6 : 0xC096)
#define HOST_FRAME_MASK 0x07FF
/* USB Peripheral only registers */
/* ============================= */
/* Device n Port Sel reg */
#define DEVICE_N_PORT_SEL(x) ((x) ? 0xC0A4 : 0xC084)
/* Device n Interrupt Enable Register */
#define DEVICE_N_IRQ_EN_REG(x) ((x) ? 0xC0AC : 0xC08C)
#define DEVICE_N_ENDPOINT_N_CTL_REG(dev, ep) ((dev) \
? (0x0280 + (ep << 4)) \
: (0x0200 + (ep << 4)))
#define DEVICE_N_ENDPOINT_N_STAT_REG(dev, ep) ((dev) \
? (0x0286 + (ep << 4)) \
: (0x0206 + (ep << 4)))
#define DEVICE_N_ADDRESS(dev) ((dev) ? (0xC0AE) : (0xC08E))
/* HPI registers */
/* ============= */
/* HPI Status register */
#define SOFEOP_FLG(x) (1 << ((x) ? 12 : 10))
#define SIEMSG_FLG(x) (1 << (4 + (x)))
#define RESET_FLG(x) ((x) ? 0x0200 : 0x0002)
#define DONE_FLG(x) (1 << (2 + (x)))
#define RESUME_FLG(x) (1 << (6 + (x)))
#define MBX_OUT_FLG 0x0001 /* Message out available */
#define MBX_IN_FLG 0x0100
#define ID_FLG 0x4000
#define VBUS_FLG 0x8000
/* Interrupt routing register */
#define HPI_IRQ_ROUTING_REG 0x0142
#define HPI_SWAP_ENABLE(x) ((x) ? 0x0100 : 0x0001)
#define RESET_TO_HPI_ENABLE(x) ((x) ? 0x0200 : 0x0002)
#define DONE_TO_HPI_ENABLE(x) ((x) ? 0x0008 : 0x0004)
#define RESUME_TO_HPI_ENABLE(x) ((x) ? 0x0080 : 0x0040)
#define SOFEOP_TO_HPI_EN(x) ((x) ? 0x2000 : 0x0800)
#define SOFEOP_TO_CPU_EN(x) ((x) ? 0x1000 : 0x0400)
#define ID_TO_HPI_ENABLE 0x4000
#define VBUS_TO_HPI_ENABLE 0x8000
/* SIE msg registers */
#define SIEMSG_REG(x) ((x) ? 0x0148 : 0x0144)
#define HUSB_TDListDone 0x1000
#define SUSB_EP0_MSG 0x0001
#define SUSB_EP1_MSG 0x0002
#define SUSB_EP2_MSG 0x0004
#define SUSB_EP3_MSG 0x0008
#define SUSB_EP4_MSG 0x0010
#define SUSB_EP5_MSG 0x0020
#define SUSB_EP6_MSG 0x0040
#define SUSB_EP7_MSG 0x0080
#define SUSB_RST_MSG 0x0100
#define SUSB_SOF_MSG 0x0200
#define SUSB_CFG_MSG 0x0400
#define SUSB_SUS_MSG 0x0800
#define SUSB_ID_MSG 0x4000
#define SUSB_VBUS_MSG 0x8000
/* BIOS interrupt routines */
#define SUSBx_RECEIVE_INT(x) ((x) ? 97 : 81)
#define SUSBx_SEND_INT(x) ((x) ? 96 : 80)
#define SUSBx_DEV_DESC_VEC(x) ((x) ? 0x00D4 : 0x00B4)
#define SUSBx_CONF_DESC_VEC(x) ((x) ? 0x00D6 : 0x00B6)
#define SUSBx_STRING_DESC_VEC(x) ((x) ? 0x00D8 : 0x00B8)
#define CY_HCD_BUF_ADDR 0x500 /* Base address for host */
#define SIE_TD_SIZE 0x200 /* size of the td list */
#define SIE_TD_BUF_SIZE 0x400 /* size of the data buffer */
#define SIE_TD_OFFSET(host) ((host) ? (SIE_TD_SIZE+SIE_TD_BUF_SIZE) : 0)
#define SIE_BUF_OFFSET(host) (SIE_TD_OFFSET(host) + SIE_TD_SIZE)
/* Base address of HCD + 2 x TD_SIZE + 2 x TD_BUF_SIZE */
#define CY_UDC_REQ_HEADER_BASE 0x1100
/* 8- byte request headers for IN/OUT transfers */
#define CY_UDC_REQ_HEADER_SIZE 8
#define CY_UDC_REQ_HEADER_ADDR(ep_num) (CY_UDC_REQ_HEADER_BASE + \
((ep_num) * CY_UDC_REQ_HEADER_SIZE))
#define CY_UDC_DESC_BASE_ADDRESS (CY_UDC_REQ_HEADER_ADDR(8))
#define CY_UDC_BIOS_REPLACE_BASE 0x1800
#define CY_UDC_REQ_BUFFER_BASE 0x2000
#define CY_UDC_REQ_BUFFER_SIZE 0x0400
#define CY_UDC_REQ_BUFFER_ADDR(ep_num) (CY_UDC_REQ_BUFFER_BASE + \
((ep_num) * CY_UDC_REQ_BUFFER_SIZE))
/* ---------------------------------------------------------------------
* Driver data structures
*/
struct c67x00_device;
/**
* struct c67x00_sie - Common data associated with a SIE
* @lock: lock to protect this struct and the associated chip registers
* @private_data: subdriver dependent data
* @irq: subdriver dependent irq handler, set NULL when not used
* @dev: link to common driver structure
* @sie_num: SIE number on chip, starting from 0
* @mode: SIE mode (host/peripheral/otg/not used)
*/
struct c67x00_sie {
/* Entries to be used by the subdrivers */
spinlock_t lock; /* protect this structure */
void *private_data;
void (*irq) (struct c67x00_sie *sie, u16 int_status, u16 msg);
/* Read only: */
struct c67x00_device *dev;
int sie_num;
int mode;
};
#define sie_dev(s) (&(s)->dev->pdev->dev)
/**
* struct c67x00_lcp
*/
struct c67x00_lcp {
/* Internal use only */
struct mutex mutex;
struct completion msg_received;
u16 last_msg;
};
/*
* struct c67x00_hpi
*/
struct c67x00_hpi {
void __iomem *base;
int regstep;
spinlock_t lock;
struct c67x00_lcp lcp;
};
#define C67X00_SIES 2
#define C67X00_PORTS 2
/**
* struct c67x00_device - Common data associated with a c67x00 instance
* @hpi: hpi addresses
* @sie: array of sie's on this chip
* @pdev: platform device of instance
* @pdata: configuration provided by the platform
*/
struct c67x00_device {
struct c67x00_hpi hpi;
struct c67x00_sie sie[C67X00_SIES];
struct platform_device *pdev;
struct c67x00_platform_data *pdata;
};
/* ---------------------------------------------------------------------
* Low level interface functions
*/
/* Host Port Interface (HPI) functions */
u16 c67x00_ll_hpi_status(struct c67x00_device *dev);
void c67x00_ll_hpi_reg_init(struct c67x00_device *dev);
void c67x00_ll_hpi_enable_sofeop(struct c67x00_sie *sie);
void c67x00_ll_hpi_disable_sofeop(struct c67x00_sie *sie);
/* General functions */
u16 c67x00_ll_fetch_siemsg(struct c67x00_device *dev, int sie_num);
u16 c67x00_ll_get_usb_ctl(struct c67x00_sie *sie);
void c67x00_ll_usb_clear_status(struct c67x00_sie *sie, u16 bits);
u16 c67x00_ll_usb_get_status(struct c67x00_sie *sie);
void c67x00_ll_write_mem_le16(struct c67x00_device *dev, u16 addr,
void *data, int len);
void c67x00_ll_read_mem_le16(struct c67x00_device *dev, u16 addr,
void *data, int len);
/* Host specific functions */
void c67x00_ll_set_husb_eot(struct c67x00_device *dev, u16 value);
void c67x00_ll_husb_reset(struct c67x00_sie *sie, int port);
void c67x00_ll_husb_set_current_td(struct c67x00_sie *sie, u16 addr);
u16 c67x00_ll_husb_get_current_td(struct c67x00_sie *sie);
u16 c67x00_ll_husb_get_frame(struct c67x00_sie *sie);
void c67x00_ll_husb_init_host_port(struct c67x00_sie *sie);
void c67x00_ll_husb_reset_port(struct c67x00_sie *sie, int port);
/* Called by c67x00_irq to handle lcp interrupts */
void c67x00_ll_irq(struct c67x00_device *dev, u16 int_status);
/* Setup and teardown */
void c67x00_ll_init(struct c67x00_device *dev);
void c67x00_ll_release(struct c67x00_device *dev);
int c67x00_ll_reset(struct c67x00_device *dev);
#endif /* _USB_C67X00_H */
| {
"pile_set_name": "Github"
} |
# Lines starting with '#' and sections without content
# are not displayed by a call to 'details'
#
[Website]
http://www.siteslike.com/
[filters]
http://www.siteslike.com/js/fpa.js
[other]
# Any other details
[comments]
fanboy | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{2F91BD07-2CEE-47FA-8486-457B54612B4C}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>DnsServerSystemTrayApp</RootNamespace>
<AssemblyName>DnsServerSystemTrayApp</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>false</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>logo2.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Drawing" />
<Reference Include="System.Management" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Windows.Forms" />
<Reference Include="TechnitiumLibrary.IO, Version=2.5.4.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\TechnitiumLibrary\bin\TechnitiumLibrary.IO.dll</HintPath>
</Reference>
<Reference Include="TechnitiumLibrary.Net">
<HintPath>..\..\TechnitiumLibrary\bin\TechnitiumLibrary.Net.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="DnsProvider.cs" />
<Compile Include="frmAbout.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="frmAbout.Designer.cs">
<DependentUpon>frmAbout.cs</DependentUpon>
</Compile>
<Compile Include="frmManageDnsProviders.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="frmManageDnsProviders.Designer.cs">
<DependentUpon>frmManageDnsProviders.cs</DependentUpon>
</Compile>
<Compile Include="NotifyIconExtension.cs" />
<Compile Include="MainApplicationContext.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="frmAbout.resx">
<DependentUpon>frmAbout.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="frmManageDnsProviders.resx">
<DependentUpon>frmManageDnsProviders.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="App.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<Content Include="logo2.ico" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> | {
"pile_set_name": "Github"
} |
/**
* 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 com.datatorrent.bufferserver.packet;
/**
* <p>BeginWindowTuple class.</p>
*
* @since 0.3.2
*/
public class BeginWindowTuple extends WindowIdTuple
{
private static final byte[][] serializedTuples = new byte[16000][];
static {
for (int i = serializedTuples.length; i-- > 0;) {
serializedTuples[i] = WindowIdTuple.getSerializedTuple(i);
serializedTuples[i][0] = MessageType.BEGIN_WINDOW_VALUE;
}
}
public BeginWindowTuple(byte[] array, int offset, int length)
{
super(array, offset, length);
}
public static byte[] getSerializedTuple(int windowId)
{
return serializedTuples[windowId % serializedTuples.length];
}
}
| {
"pile_set_name": "Github"
} |
/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* The origin of this IDL file is
* http://www.whatwg.org/specs/web-apps/current-work/#htmlformelement
*
* © Copyright 2004-2011 Apple Computer, Inc., Mozilla Foundation, and
* Opera Software ASA. You are granted a license to use, reproduce
* and create derivative works of this document.
*/
[OverrideBuiltins, LegacyUnenumerableNamedProperties, HTMLConstructor]
interface HTMLFormElement : HTMLElement {
[CEReactions, Pure, SetterThrows]
attribute DOMString acceptCharset;
[CEReactions, Pure, SetterThrows]
attribute DOMString action;
[CEReactions, Pure, SetterThrows]
attribute DOMString autocomplete;
[CEReactions, Pure, SetterThrows]
attribute DOMString enctype;
[CEReactions, Pure, SetterThrows]
attribute DOMString encoding;
[CEReactions, Pure, SetterThrows]
attribute DOMString method;
[CEReactions, Pure, SetterThrows]
attribute DOMString name;
[CEReactions, Pure, SetterThrows]
attribute boolean noValidate;
[CEReactions, Pure, SetterThrows]
attribute DOMString target;
[Constant]
readonly attribute HTMLCollection elements;
[Pure]
readonly attribute long length;
getter Element (unsigned long index);
// TODO this should be: getter (RadioNodeList or HTMLInputElement or HTMLImageElement) (DOMString name);
getter nsISupports (DOMString name);
[Throws]
void submit();
[CEReactions]
void reset();
boolean checkValidity();
boolean reportValidity();
};
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2009-2010 Lockheed Martin Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.eurekastreams.server.persistence.mappers.requests;
/**
* Request object for use with DeleteActivity DAO.
*
*/
public class DeleteActivityRequest
{
/**
* The current user's id.
*/
private Long userId;
/**
* The id of activity to delete.
*/
private Long activityId;
/**
*
* @param inUserId The current user's id.
* @param inActivityId The id of activity to delete.
*/
public DeleteActivityRequest(final Long inUserId, final Long inActivityId)
{
userId = inUserId;
activityId = inActivityId;
}
/**
* @return the userId
*/
public Long getUserId()
{
return userId;
}
/**
* @param inUserId the userId to set
*/
public void setUserId(final Long inUserId)
{
this.userId = inUserId;
}
/**
* @return the activityId
*/
public Long getActivityId()
{
return activityId;
}
/**
* @param inActivityId the activityId to set
*/
public void setActivityId(final Long inActivityId)
{
this.activityId = inActivityId;
}
}
| {
"pile_set_name": "Github"
} |
/* @flow */
import {batchInsertMessages} from './batchInsertMessages'
import {ElementProxy} from './ElementProxy'
import {VirtualElement} from './VirtualElement'
import {isDefined} from './is'
import {$$root} from './symbol'
import {get} from './get'
import {set} from './set'
export function render (vnode: VirtualElement, node: HTMLElement): void {
const containerProxy: ElementProxy = ElementProxy.fromElement(node)
const previous: VirtualElement = get(node, $$root)
if (isDefined(previous)) {
if (previous.tagName === vnode.tagName) {
previous.patch(vnode)
} else {
previous.destroy()
}
}
batchInsertMessages(queue => {
vnode.initialize()
containerProxy.replaceChild(vnode.getProxy(), 0)
queue.push(vnode)
})
set(node, $$root, vnode)
}
| {
"pile_set_name": "Github"
} |
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
# the next line can be removed after installation
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
import nngen as ng
import veriloggen
import matrix_add_ipxact
a_shape = (15, 15)
b_shape = (15, 15)
a_dtype = ng.int32
b_dtype = ng.int32
c_dtype = ng.int32
par = 1
axi_datawidth = 32
def test(request, silent=True):
veriloggen.reset()
simtype = request.config.getoption('--sim')
rslt = matrix_add_ipxact.run(a_shape, b_shape,
a_dtype, b_dtype, c_dtype,
par, axi_datawidth, silent,
filename=None, simtype=simtype,
outputfile=os.path.splitext(os.path.basename(__file__))[0] + '.out')
verify_rslt = rslt.splitlines()[-1]
assert(verify_rslt == '# verify: PASSED')
if __name__ == '__main__':
rslt = matrix_add_ipxact.run(a_shape, b_shape,
a_dtype, b_dtype, c_dtype,
par, axi_datawidth, silent=False,
filename='tmp.v',
outputfile=os.path.splitext(os.path.basename(__file__))[0] + '.out')
print(rslt)
| {
"pile_set_name": "Github"
} |
//===--- DependencyGraph.cpp - Track intra-module dependencies ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "polarphp/basic/ReferenceDependencyKeys.h"
#include "polarphp/basic/Statistic.h"
#include "polarphp/driver/DependencyGraph.h"
#include "polarphp/demangling/Demangle.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/YAMLParser.h"
using namespace polar;
enum class DependencyGraphImpl::DependencyKind : uint8_t {
TopLevelName = 1 << 0,
DynamicLookupName = 1 << 1,
NominalType = 1 << 2,
NominalTypeMember = 1 << 3,
ExternalFile = 1 << 4,
};
enum class DependencyGraphImpl::DependencyFlags : uint8_t {
IsCascading = 1 << 0
};
class DependencyGraphImpl::MarkTracerImpl::Entry {
public:
const void *Node;
StringRef Name;
DependencyMaskTy KindMask;
};
DependencyGraphImpl::MarkTracerImpl::MarkTracerImpl(UnifiedStatsReporter *Stats)
: Stats(Stats) {}
DependencyGraphImpl::MarkTracerImpl::~MarkTracerImpl() = default;
using LoadResult = DependencyGraphImpl::LoadResult;
using DependencyKind = DependencyGraphImpl::DependencyKind;
using DependencyCallbackTy = LoadResult(StringRef, DependencyKind, bool);
using InterfaceHashCallbackTy = LoadResult(StringRef);
static LoadResult
parseDependencyFile(llvm::MemoryBuffer &buffer,
llvm::function_ref<DependencyCallbackTy> providesCallback,
llvm::function_ref<DependencyCallbackTy> dependsCallback,
llvm::function_ref<InterfaceHashCallbackTy> interfaceHashCallback) {
namespace yaml = llvm::yaml;
// FIXME: Switch to a format other than YAML.
llvm::SourceMgr SM;
yaml::Stream stream(buffer.getMemBufferRef(), SM);
auto I = stream.begin();
if (I == stream.end() || !I->getRoot())
return LoadResult::HadError;
auto *topLevelMap = dyn_cast<yaml::MappingNode>(I->getRoot());
if (!topLevelMap) {
if (isa<yaml::NullNode>(I->getRoot()))
return LoadResult::UpToDate;
return LoadResult::HadError;
}
LoadResult result = LoadResult::UpToDate;
SmallString<64> scratch;
// After an entry, we know more about the node as a whole.
// Update the "result" variable above.
// This is a macro rather than a lambda because it contains a return.
#define UPDATE_RESULT(update) switch (update) {\
case LoadResult::HadError: \
return LoadResult::HadError; \
case LoadResult::UpToDate: \
break; \
case LoadResult::AffectsDownstream: \
result = LoadResult::AffectsDownstream; \
break; \
} \
// FIXME: LLVM's YAML support does incremental parsing in such a way that
// for-range loops break.
for (auto i = topLevelMap->begin(), e = topLevelMap->end(); i != e; ++i) {
if (isa<yaml::NullNode>(i->getValue()))
continue;
auto *key = dyn_cast<yaml::ScalarNode>(i->getKey());
if (!key)
return LoadResult::HadError;
StringRef keyString = key->getValue(scratch);
using namespace referencedependencykeys;
if (keyString == interfaceHash) {
auto *value = dyn_cast<yaml::ScalarNode>(i->getValue());
if (!value)
return LoadResult::HadError;
StringRef valueString = value->getValue(scratch);
UPDATE_RESULT(interfaceHashCallback(valueString));
} else {
enum class DependencyDirection : bool {
Depends,
Provides
};
using KindPair = std::pair<DependencyKind, DependencyDirection>;
KindPair dirAndKind = llvm::StringSwitch<KindPair>(key->getValue(scratch))
.Case(dependsTopLevel,
std::make_pair(DependencyKind::TopLevelName,
DependencyDirection::Depends))
.Case(dependsNominal,
std::make_pair(DependencyKind::NominalType,
DependencyDirection::Depends))
.Case(dependsMember,
std::make_pair(DependencyKind::NominalTypeMember,
DependencyDirection::Depends))
.Case(dependsDynamicLookup,
std::make_pair(DependencyKind::DynamicLookupName,
DependencyDirection::Depends))
.Case(dependsExternal,
std::make_pair(DependencyKind::ExternalFile,
DependencyDirection::Depends))
.Case(providesTopLevel,
std::make_pair(DependencyKind::TopLevelName,
DependencyDirection::Provides))
.Case(providesNominal,
std::make_pair(DependencyKind::NominalType,
DependencyDirection::Provides))
.Case(providesMember,
std::make_pair(DependencyKind::NominalTypeMember,
DependencyDirection::Provides))
.Case(providesDynamicLookup,
std::make_pair(DependencyKind::DynamicLookupName,
DependencyDirection::Provides))
.Default(std::make_pair(DependencyKind(),
DependencyDirection::Depends));
if (dirAndKind.first == DependencyKind())
return LoadResult::HadError;
auto *entries = dyn_cast<yaml::SequenceNode>(i->getValue());
if (!entries)
return LoadResult::HadError;
if (dirAndKind.first == DependencyKind::NominalTypeMember) {
// Handle member dependencies specially. Rather than being a single
// string, they come in the form ["{MangledBaseName}", "memberName"].
for (yaml::Node &rawEntry : *entries) {
bool isCascading = rawEntry.getRawTag() != "!private";
auto *entry = dyn_cast<yaml::SequenceNode>(&rawEntry);
if (!entry)
return LoadResult::HadError;
auto iter = entry->begin();
auto *base = dyn_cast<yaml::ScalarNode>(&*iter);
if (!base)
return LoadResult::HadError;
++iter;
auto *member = dyn_cast<yaml::ScalarNode>(&*iter);
if (!member)
return LoadResult::HadError;
++iter;
// FIXME: LLVM's YAML support doesn't implement == correctly for end
// iterators.
assert(!(iter != entry->end()));
bool isDepends = dirAndKind.second == DependencyDirection::Depends;
auto &callback = isDepends ? dependsCallback : providesCallback;
// Smash the type and member names together so we can continue using
// StringMap.
SmallString<64> appended;
appended += base->getValue(scratch);
appended.push_back('\0');
appended += member->getValue(scratch);
UPDATE_RESULT(callback(appended.str(), dirAndKind.first,
isCascading));
}
} else {
for (const yaml::Node &rawEntry : *entries) {
auto *entry = dyn_cast<yaml::ScalarNode>(&rawEntry);
if (!entry)
return LoadResult::HadError;
bool isDepends = dirAndKind.second == DependencyDirection::Depends;
auto &callback = isDepends ? dependsCallback : providesCallback;
UPDATE_RESULT(callback(entry->getValue(scratch), dirAndKind.first,
entry->getRawTag() != "!private"));
}
}
}
}
return result;
}
LoadResult DependencyGraphImpl::loadFromPath(const void *node, StringRef path) {
auto buffer = llvm::MemoryBuffer::getFile(path);
if (!buffer)
return LoadResult::HadError;
return loadFromBuffer(node, *buffer.get());
}
LoadResult
DependencyGraphImpl::loadFromString(const void *node, StringRef data) {
auto buffer = llvm::MemoryBuffer::getMemBuffer(data);
return loadFromBuffer(node, *buffer);
}
LoadResult DependencyGraphImpl::loadFromBuffer(const void *node,
llvm::MemoryBuffer &buffer) {
auto &provides = Provides[node];
auto dependsCallback = [this, node](StringRef name, DependencyKind kind,
bool isCascading) -> LoadResult {
if (kind == DependencyKind::ExternalFile)
ExternalDependencies.insert(name);
auto &entries = Dependencies[name];
auto iter = std::find_if(entries.first.begin(), entries.first.end(),
[node](const DependencyEntryTy &entry) -> bool {
return node == entry.node;
});
DependencyFlagsTy flags;
if (isCascading)
flags |= DependencyFlags::IsCascading;
if (iter == entries.first.end()) {
entries.first.push_back({node, kind, flags});
} else {
iter->kindMask |= kind;
iter->flags |= flags;
}
if (isCascading && (entries.second & kind))
return LoadResult::AffectsDownstream;
return LoadResult::UpToDate;
};
auto providesCallback =
[&provides](StringRef name, DependencyKind kind,
bool isCascading) -> LoadResult {
assert(isCascading);
auto iter = std::find_if(provides.begin(), provides.end(),
[name](const ProvidesEntryTy &entry) -> bool {
return name == entry.name;
});
if (iter == provides.end())
provides.push_back({name, kind});
else
iter->kindMask |= kind;
return LoadResult::UpToDate;
};
auto interfaceHashCallback = [this, node](StringRef hash) -> LoadResult {
auto insertResult = InterfaceHashes.insert(std::make_pair(node, hash));
if (insertResult.second) {
// Treat a newly-added hash as up-to-date. This includes the initial
// load of the file.
return LoadResult::UpToDate;
}
auto iter = insertResult.first;
if (hash != iter->second) {
iter->second = hash;
return LoadResult::AffectsDownstream;
}
return LoadResult::UpToDate;
};
return parseDependencyFile(buffer, providesCallback, dependsCallback,
interfaceHashCallback);
}
void DependencyGraphImpl::markExternal(SmallVectorImpl<const void *> &visited,
StringRef externalDependency) {
forEachUnmarkedJobDirectlyDependentOnExternalPHPdeps(
externalDependency, [&](const void *node) {
visited.push_back(node);
markTransitive(visited, node);
});
}
void DependencyGraphImpl::forEachUnmarkedJobDirectlyDependentOnExternalPHPdeps(
StringRef externalPHPDeps, function_ref<void(const void *node)> fn) {
auto allDependents = Dependencies.find(externalPHPDeps);
assert(allDependents != Dependencies.end() && "not a dependency!");
allDependents->second.second |= DependencyKind::ExternalFile;
for (const auto &dependent : allDependents->second.first) {
if (!dependent.kindMask.contains(DependencyKind::ExternalFile))
continue;
if (isMarked(dependent.node))
continue;
assert(dependent.flags & DependencyFlags::IsCascading);
fn(dependent.node);
}
}
void
DependencyGraphImpl::markTransitive(SmallVectorImpl<const void *> &visited,
const void *node, MarkTracerImpl *tracer) {
assert(Provides.count(node) && "node is not in the graph");
llvm::SpecificBumpPtrAllocator<MarkTracerImpl::Entry> scratchAlloc;
struct WorklistEntry {
ArrayRef<MarkTracerImpl::Entry> Reason;
const void *Node;
bool IsCascading;
};
SmallVector<WorklistEntry, 16> worklist;
SmallPtrSet<const void *, 16> visitedSet;
auto addDependentsToWorklist = [&](const void *next,
ArrayRef<MarkTracerImpl::Entry> reason) {
auto allProvided = Provides.find(next);
if (allProvided == Provides.end())
return;
for (const auto &provided : allProvided->second) {
auto allDependents = Dependencies.find(provided.name);
if (allDependents == Dependencies.end())
continue;
if (allDependents->second.second.contains(provided.kindMask))
continue;
// Record that we've traversed this dependency.
allDependents->second.second |= provided.kindMask;
for (const auto &dependent : allDependents->second.first) {
if (dependent.node == next)
continue;
auto intersectingKinds = provided.kindMask & dependent.kindMask;
if (!intersectingKinds)
continue;
if (isMarked(dependent.node))
continue;
bool isCascading{dependent.flags & DependencyFlags::IsCascading};
MutableArrayRef<MarkTracerImpl::Entry> newReason;
if (tracer) {
tracer->countStatsForNodeMarking(intersectingKinds, isCascading);
newReason = {scratchAlloc.Allocate(reason.size()+1), reason.size()+1};
std::uninitialized_copy(reason.begin(), reason.end(),
newReason.begin());
new (&newReason.back()) MarkTracerImpl::Entry({next, provided.name,
intersectingKinds});
}
worklist.push_back({ newReason, dependent.node, isCascading });
}
}
};
auto record = [&](WorklistEntry next) {
if (!visitedSet.insert(next.Node).second)
return;
visited.push_back(next.Node);
if (tracer) {
auto &savedReason = tracer->Table[next.Node];
savedReason.clear();
savedReason.append(next.Reason.begin(), next.Reason.end());
}
};
// Always mark through the starting node, even if it's already marked.
markIntransitive(node);
addDependentsToWorklist(node, {});
while (!worklist.empty()) {
auto next = worklist.pop_back_val();
// Is this a non-cascading dependency?
if (!next.IsCascading) {
if (!isMarked(next.Node))
record(next);
continue;
}
addDependentsToWorklist(next.Node, next.Reason);
if (!markIntransitive(next.Node))
continue;
record(next);
}
}
void DependencyGraphImpl::MarkTracerImpl::countStatsForNodeMarking(
const OptionSet<DependencyKind> &Kind, bool IsCascading) const {
if (!Stats)
return;
auto &D = Stats->getDriverCounters();
if (IsCascading) {
if (Kind & DependencyKind::TopLevelName)
D.DriverDepCascadingTopLevel++;
if (Kind & DependencyKind::DynamicLookupName)
D.DriverDepCascadingDynamic++;
if (Kind & DependencyKind::NominalType)
D.DriverDepCascadingNominal++;
if (Kind & DependencyKind::NominalTypeMember)
D.DriverDepCascadingMember++;
if (Kind & DependencyKind::NominalTypeMember)
D.DriverDepCascadingExternal++;
} else {
if (Kind & DependencyKind::TopLevelName)
D.DriverDepTopLevel++;
if (Kind & DependencyKind::DynamicLookupName)
D.DriverDepDynamic++;
if (Kind & DependencyKind::NominalType)
D.DriverDepNominal++;
if (Kind & DependencyKind::NominalTypeMember)
D.DriverDepMember++;
if (Kind & DependencyKind::NominalTypeMember)
D.DriverDepExternal++;
}
}
void DependencyGraphImpl::MarkTracerImpl::printPath(
raw_ostream &out,
const void *item,
llvm::function_ref<void (const void *)> printItem) const {
for (const Entry &entry : Table.lookup(item)) {
out << "\t";
printItem(entry.Node);
if (entry.KindMask.contains(DependencyKind::TopLevelName)) {
out << " provides top-level name '" << entry.Name << "'\n";
} else if (entry.KindMask.contains(DependencyKind::NominalType)) {
SmallString<64> name{entry.Name};
if (name.front() == 'P')
name.push_back('_');
out << " provides type '"
// TODO
// << polar::demangling::demangleTypeAsString(name.str())
<< "'\n";
} else if (entry.KindMask.contains(DependencyKind::NominalTypeMember)) {
SmallString<64> name{entry.Name};
size_t splitPoint = name.find('\0');
assert(splitPoint != StringRef::npos);
StringRef typePart;
if (name.front() == 'P') {
name[splitPoint] = '_';
typePart = name.str().slice(0, splitPoint+1);
} else {
typePart = name.str().slice(0, splitPoint);
}
StringRef memberPart = name.str().substr(splitPoint+1);
if (memberPart.empty()) {
out << " provides non-private members of type '"
/// TODO
// << polar::demangling::demangleTypeAsString(typePart)
<< "'\n";
} else {
out << " provides member '" << memberPart << "' of type '"
/// TODO
// << polar::demangling::demangleTypeAsString(typePart)
<< "'\n";
}
} else if (entry.KindMask.contains(DependencyKind::DynamicLookupName)) {
out << " provides AnyObject member '" << entry.Name << "'\n";
} else {
llvm_unreachable("not a dependency kind between nodes");
}
}
}
| {
"pile_set_name": "Github"
} |
<refentry xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xi="http://www.w3.org/2001/XInclude"
xmlns:src="http://nwalsh.com/xmlns/litprog/fragment"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="5.0" xml:id="olink.outline.ext">
<refmeta>
<refentrytitle>olink.outline.ext</refentrytitle>
<refmiscinfo class="other" otherclass="datatype">string</refmiscinfo>
</refmeta>
<refnamediv>
<refname>olink.outline.ext</refname>
<refpurpose>The extension of OLink outline files</refpurpose>
</refnamediv>
<refsynopsisdiv>
<src:fragment xml:id="olink.outline.ext.frag">
<xsl:param name="olink.outline.ext">.olink</xsl:param>
</src:fragment>
</refsynopsisdiv>
<refsection><info><title>Description</title></info>
<para>The extension to be expected for OLink outline files</para>
<para>Bob has this parameter as dead. Please don't use</para>
</refsection>
</refentry>
| {
"pile_set_name": "Github"
} |
syntax = "proto3";
package envoy.config.metrics.v4alpha;
import "envoy/config/core/v4alpha/config_source.proto";
import "envoy/config/core/v4alpha/grpc_service.proto";
import "google/protobuf/wrappers.proto";
import "udpa/annotations/status.proto";
import "udpa/annotations/versioning.proto";
import "validate/validate.proto";
option java_package = "io.envoyproxy.envoy.config.metrics.v4alpha";
option java_outer_classname = "MetricsServiceProto";
option java_multiple_files = true;
option (udpa.annotations.file_status).package_version_status = NEXT_MAJOR_VERSION_CANDIDATE;
// [#protodoc-title: Metrics service]
// Metrics Service is configured as a built-in *envoy.stat_sinks.metrics_service* :ref:`StatsSink
// <envoy_api_msg_config.metrics.v4alpha.StatsSink>`. This opaque configuration will be used to create
// Metrics Service.
// [#extension: envoy.stat_sinks.metrics_service]
message MetricsServiceConfig {
option (udpa.annotations.versioning).previous_message_type =
"envoy.config.metrics.v3.MetricsServiceConfig";
// The upstream gRPC cluster that hosts the metrics service.
core.v4alpha.GrpcService grpc_service = 1 [(validate.rules).message = {required: true}];
// API version for metric service transport protocol. This describes the metric service gRPC
// endpoint and version of messages used on the wire.
core.v4alpha.ApiVersion transport_api_version = 3 [(validate.rules).enum = {defined_only: true}];
// If true, counters are reported as the delta between flushing intervals. Otherwise, the current
// counter value is reported. Defaults to false.
// Eventually (https://github.com/envoyproxy/envoy/issues/10968) if this value is not set, the
// sink will take updates from the :ref:`MetricsResponse <envoy_api_msg_service.metrics.v3.StreamMetricsResponse>`.
google.protobuf.BoolValue report_counters_as_deltas = 2;
}
| {
"pile_set_name": "Github"
} |
# LaunchMe
## DESCRIPTION:
+ The LaunchMe sample application demonstrates how to implement a custom URL scheme to allow other applications to interact with your application. It registers the "launchme" URL scheme, of which URLs contain an HTML color code (for example, #FF0000 or #F00). The sample shows how to handle an incoming URL request by overriding -application:openURL:sourceApplication:annotation: to properly parse and extract information from the requested URL before updating the user interface.
+ Refer to the "Implementing Custom URL Schemes" section of the "iOS App Programming Guide" for information about registering a custom URL scheme, including an overview of the necessary info.plist keys.
<https://developer.apple.com/library/ios/redirect/DTS/CustomURLSchemes>
## BUILD REQUIREMENTS:
+ iOS 8.0 SDK or later
## RUNTIME REQUIREMENTS:
+ iOS 7.0 or later
Copyright (C) 2008-2015 Apple Inc. All rights reserved. | {
"pile_set_name": "Github"
} |
{"text": ["$", "cat", ":", "the", "dows", "top", "3", "stocks", "of", "2014", "URL"], "created_at": "Tue May 27 09:18:36 +0000 2014", "user_id_str": "2358944184"}
| {
"pile_set_name": "Github"
} |
/*
* (C) Copyright 2010-2013
* NVIDIA Corporation <www.nvidia.com>
*
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef _ASM_ARCH_SPL_H_
#define _ASM_ARCH_SPL_H_
#define BOOT_DEVICE_RAM 1
#endif /* _ASM_ARCH_SPL_H_ */
| {
"pile_set_name": "Github"
} |
package com.codestream.protocols.webview
import com.codestream.protocols.CodemarkType
import org.eclipse.lsp4j.Range
interface WebViewNotification {
fun getMethod(): String
}
object EditorNotifications {
class DidChangeVisibleRanges(
val uri: String?,
val selections: List<EditorSelection>,
val visibleRanges: List<Range>,
val lineCount: Number
) : WebViewNotification {
override fun getMethod() = "webview/editor/didChangeVisibleRanges"
}
class DidChangeSelection(
val uri: String?,
val selections: List<EditorSelection>?,
val visibleRanges: List<Range>?,
val lineCount: Number
) : WebViewNotification {
override fun getMethod() = "webview/editor/didChangeSelection"
}
class DidChangeActive(val editor: EditorInformation?) : WebViewNotification {
override fun getMethod() = "webview/editor/didChangeActive"
}
}
object CodemarkNotifications {
class Show(
val codemarkId: String,
val sourceUri: String? = null,
val simulated: Boolean? = null
) : WebViewNotification {
override fun getMethod() = "webview/codemark/show"
}
class New(
val uri: String?,
val range: Range,
val type: CodemarkType,
val source: String?
) : WebViewNotification {
override fun getMethod() = "webview/codemark/new"
}
}
object ReviewNotifications {
class Show(
val reviewId: String,
val sourceUri: String? = null,
val simulated: Boolean? = null
) : WebViewNotification {
override fun getMethod() = "webview/review/show"
}
class New(
val uri: String?,
val range: Range,
val source: String?
) : WebViewNotification {
override fun getMethod() = "webview/review/new"
}
}
object WorkNotifications {
class Start(
val uri: String?,
val source: String?
) : WebViewNotification {
override fun getMethod() = "webview/work/start"
}
}
object PullRequestNotifications {
class New(
val uri: String?,
val range: Range,
val source: String?
) : WebViewNotification {
override fun getMethod() = "webview/pullRequest/new"
}
}
object StreamNotifications {
class Show(
val streamId: String,
val threadId: String? = null
) : WebViewNotification {
override fun getMethod(): String = "webview/stream/show"
}
}
object FocusNotifications {
class DidChange(
val focused: Boolean
) : WebViewNotification {
override fun getMethod(): String = "webview/focus/didChange"
}
}
object HostNotifications {
class DidReceiveRequest(
val url: String?
) : WebViewNotification {
override fun getMethod(): String = "webview/request/parse"
}
}
class DidChangeApiVersionCompatibility : WebViewNotification {
override fun getMethod(): String = "codestream/didChangeApiVersionCompatibility"
}
class DidLogout() : WebViewNotification {
override fun getMethod(): String = "webview/didLogout"
}
| {
"pile_set_name": "Github"
} |
// license:BSD-3-Clause
// copyright-holders:David Haywood, MetalliC
/*
ARM AIC (Advanced Interrupt Controller) from Atmel
typically integrated into the AM91SAM series of chips
current implementation was tested in pgm2 (pgm2.cpp) only, there might be mistakes if more advanced usage.
if this peripheral is not available as a standalone chip it could also be moved to
the CPU folder alongside the ARM instead
TODO:
low/high input source types
check if level/edge input source types logic correct
FIQ output
*/
#include "emu.h"
#include "atmel_arm_aic.h"
DEFINE_DEVICE_TYPE(ARM_AIC, arm_aic_device, "arm_aic", "ARM Advanced Interrupt Controller")
void arm_aic_device::regs_map(address_map &map)
{
map(0x000, 0x07f).rw(FUNC(arm_aic_device::aic_smr_r), FUNC(arm_aic_device::aic_smr_w)); // AIC_SMR[32] (AIC_SMR) Source Mode Register
map(0x080, 0x0ff).rw(FUNC(arm_aic_device::aic_svr_r), FUNC(arm_aic_device::aic_svr_w)); // AIC_SVR[32] (AIC_SVR) Source Vector Register
map(0x100, 0x103).r(FUNC(arm_aic_device::irq_vector_r)); // AIC_IVR IRQ Vector Register
map(0x104, 0x107).r(FUNC(arm_aic_device::firq_vector_r)); // AIC_FVR FIQ Vector Register
map(0x108, 0x10b).r(FUNC(arm_aic_device::aic_isr_r)); // AIC_ISR Interrupt Status Register
map(0x10c, 0x10f).r(FUNC(arm_aic_device::aic_ipr_r)); // AIC_IPR Interrupt Pending Register
map(0x110, 0x113).r(FUNC(arm_aic_device::aic_imr_r)); // AIC_IMR Interrupt Mask Register
map(0x114, 0x117).r(FUNC(arm_aic_device::aic_cisr_r)); // AIC_CISR Core Interrupt Status Register
map(0x120, 0x123).w(FUNC(arm_aic_device::aic_iecr_w)); // AIC_IECR Interrupt Enable Command Register
map(0x124, 0x127).w(FUNC(arm_aic_device::aic_idcr_w)); // AIC_IDCR Interrupt Disable Command Register
map(0x128, 0x12b).w(FUNC(arm_aic_device::aic_iccr_w)); // AIC_ICCR Interrupt Clear Command Register
map(0x12c, 0x12f).w(FUNC(arm_aic_device::aic_iscr_w)); // AIC_ISCR Interrupt Set Command Register
map(0x130, 0x133).w(FUNC(arm_aic_device::aic_eoicr_w)); // AIC_EOICR End of Interrupt Command Register
map(0x134, 0x137).w(FUNC(arm_aic_device::aic_spu_w)); // AIC_SPU Spurious Vector Register
map(0x138, 0x13b).w(FUNC(arm_aic_device::aic_dcr_w)); // AIC_DCR Debug Control Register (Protect)
map(0x140, 0x143).w(FUNC(arm_aic_device::aic_ffer_w)); // AIC_FFER Fast Forcing Enable Register
map(0x144, 0x147).w(FUNC(arm_aic_device::aic_ffdr_w)); // AIC_FFDR Fast Forcing Disable Register
map(0x148, 0x14b).r(FUNC(arm_aic_device::aic_ffsr_r)); // AIC_FFSR Fast Forcing Status Register
}
uint32_t arm_aic_device::irq_vector_r()
{
uint32_t mask = m_irqs_enabled & m_irqs_pending & ~m_fast_irqs;
m_current_irq_vector = m_spurious_vector;
if (mask)
{
// looking for highest level pending interrupt, bigger than current
int pri = get_level();
int midx = -1;
do
{
uint8_t idx = 31 - count_leading_zeros(mask);
if ((int)(m_aic_smr[idx] & 7) >= pri)
{
midx = idx;
pri = m_aic_smr[idx] & 7;
}
mask ^= 1 << idx;
} while (mask);
if (midx > 0)
{
m_status = midx;
m_current_irq_vector = m_aic_svr[midx];
// note: Debug PROTect mode not implemented (new level pushed on stack and pending line clear only when this register writen after read)
push_level(m_aic_smr[midx] & 7);
if (m_aic_smr[midx] & 0x20) // auto clear pending if edge trigger mode
m_irqs_pending ^= 1 << midx;
}
}
m_core_status &= ~2;
set_lines();
return m_current_irq_vector;
}
uint32_t arm_aic_device::firq_vector_r()
{
m_current_firq_vector = (m_irqs_enabled & m_irqs_pending & m_fast_irqs) ? m_aic_svr[0] : m_spurious_vector;
return m_current_firq_vector;
}
void arm_aic_device::device_start()
{
m_irq_out.resolve_safe();
save_item(NAME(m_irqs_enabled));
save_item(NAME(m_irqs_pending));
save_item(NAME(m_current_irq_vector));
save_item(NAME(m_current_firq_vector));
save_item(NAME(m_status));
save_item(NAME(m_core_status));
save_item(NAME(m_spurious_vector));
save_item(NAME(m_debug));
save_item(NAME(m_fast_irqs));
save_item(NAME(m_lvlidx));
save_item(NAME(m_aic_smr));
save_item(NAME(m_aic_svr));
save_item(NAME(m_level_stack));
}
void arm_aic_device::device_reset()
{
m_irqs_enabled = 0;
m_irqs_pending = 0;
m_current_irq_vector = 0;
m_current_firq_vector = 0;
m_status = 0;
m_core_status = 0;
m_spurious_vector = 0;
m_debug = 0;
m_fast_irqs = 1;
m_lvlidx = 0;
for(auto & elem : m_aic_smr) { elem = 0; }
for(auto & elem : m_aic_svr) { elem = 0; }
for(auto & elem : m_level_stack) { elem = 0; }
m_level_stack[0] = -1;
}
void arm_aic_device::set_irq(int line, int state)
{
// note: might be incorrect if edge triggered mode set
if (state == ASSERT_LINE)
m_irqs_pending |= 1 << line;
else
if (m_aic_smr[line] & 0x40)
m_irqs_pending &= ~(1 << line);
check_irqs();
}
void arm_aic_device::check_irqs()
{
m_core_status = 0;
uint32_t mask = m_irqs_enabled & m_irqs_pending & ~m_fast_irqs;
if (mask)
{
// check if we have pending interrupt with level more than current
int pri = get_level();
do
{
uint8_t idx = 31 - count_leading_zeros(mask);
if ((int)(m_aic_smr[idx] & 7) > pri)
{
m_core_status |= 2;
break;
}
mask ^= 1 << idx;
} while (mask);
}
if (m_irqs_enabled & m_irqs_pending & m_fast_irqs)
m_core_status |= 1;
set_lines();
}
| {
"pile_set_name": "Github"
} |
require('../../modules/es6.object.freeze');
module.exports = require('../../modules/$.core').Object.freeze; | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<com.android.browser.BrowserYesNoPreference
android:key="privacy_clear_cache"
android:title="@string/pref_privacy_clear_cache"
android:summary="@string/pref_privacy_clear_cache_summary"
android:dialogMessage="@string/pref_privacy_clear_cache_dlg"
android:dialogIcon="@android:drawable/ic_dialog_alert" />
<com.android.browser.BrowserYesNoPreference
android:key="privacy_clear_history"
android:title="@string/pref_privacy_clear_history"
android:summary="@string/pref_privacy_clear_history_summary"
android:dialogMessage="@string/pref_privacy_clear_history_dlg"
android:dialogIcon="@android:drawable/ic_dialog_alert"/>
<CheckBoxPreference
android:key="show_security_warnings"
android:defaultValue="true"
android:title="@string/pref_security_show_security_warning"
android:summary="@string/pref_security_show_security_warning_summary" />
<PreferenceCategory android:title="@string/pref_privacy_cookies_title">
<CheckBoxPreference
android:key="accept_cookies"
android:defaultValue="true"
android:title="@string/pref_security_accept_cookies"
android:summary="@string/pref_security_accept_cookies_summary" />
<com.android.browser.BrowserYesNoPreference
android:key="privacy_clear_cookies"
android:title="@string/pref_privacy_clear_cookies"
android:summary="@string/pref_privacy_clear_cookies_summary"
android:dialogMessage="@string/pref_privacy_clear_cookies_dlg"
android:dialogIcon="@android:drawable/ic_dialog_alert"/>
</PreferenceCategory>
<PreferenceCategory android:title="@string/pref_privacy_formdata_title">
<CheckBoxPreference
android:key="save_formdata"
android:defaultValue="true"
android:title="@string/pref_security_save_form_data"
android:summary="@string/pref_security_save_form_data_summary" />
<com.android.browser.BrowserYesNoPreference
android:key="privacy_clear_form_data"
android:title="@string/pref_privacy_clear_form_data"
android:summary="@string/pref_privacy_clear_form_data_summary"
android:dialogMessage="@string/pref_privacy_clear_form_data_dlg"
android:dialogIcon="@android:drawable/ic_dialog_alert"/>
</PreferenceCategory>
<PreferenceCategory android:title="@string/pref_privacy_location_title">
<CheckBoxPreference
android:key="enable_geolocation"
android:defaultValue="true"
android:title="@string/pref_privacy_enable_geolocation"
android:summary="@string/pref_privacy_enable_geolocation_summary" />
<com.android.browser.BrowserYesNoPreference
android:key="privacy_clear_geolocation_access"
android:dependency="enable_geolocation"
android:title="@string/pref_privacy_clear_geolocation_access"
android:summary="@string/pref_privacy_clear_geolocation_access_summary"
android:dialogMessage="@string/pref_privacy_clear_geolocation_access_dlg"
android:dialogIcon="@android:drawable/ic_dialog_alert"/>
</PreferenceCategory>
<PreferenceCategory android:title="@string/pref_security_passwords_title">
<CheckBoxPreference
android:key="remember_passwords"
android:defaultValue="true"
android:title="@string/pref_security_remember_passwords"
android:summary="@string/pref_security_remember_passwords_summary" />
<com.android.browser.BrowserYesNoPreference
android:key="privacy_clear_passwords"
android:title="@string/pref_privacy_clear_passwords"
android:summary="@string/pref_privacy_clear_passwords_summary"
android:dialogMessage="@string/pref_privacy_clear_passwords_dlg"
android:dialogIcon="@android:drawable/ic_dialog_alert"/>
</PreferenceCategory>
</PreferenceScreen>
| {
"pile_set_name": "Github"
} |
'use strict';
var path = require('./$.path')
, invoke = require('./$.invoke')
, aFunction = require('./$.a-function');
module.exports = function(/* ...pargs */){
var fn = aFunction(this)
, length = arguments.length
, pargs = Array(length)
, i = 0
, _ = path._
, holder = false;
while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true;
return function(/* ...args */){
var that = this
, $$ = arguments
, $$len = $$.length
, j = 0, k = 0, args;
if(!holder && !$$len)return invoke(fn, pargs, that);
args = pargs.slice();
if(holder)for(;length > j; j++)if(args[j] === _)args[j] = $$[k++];
while($$len > k)args.push($$[k++]);
return invoke(fn, args, that);
};
}; | {
"pile_set_name": "Github"
} |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .Loss import Loss
from .MarginLoss import MarginLoss
from .SoftplusLoss import SoftplusLoss
from .SigmoidLoss import SigmoidLoss
__all__ = [
'Loss',
'MarginLoss',
'SoftplusLoss',
'SigmoidLoss',
] | {
"pile_set_name": "Github"
} |
var test = require('tap').test;
var browserify = require('browserify');
var through = require('through');
var vm = require('vm');
var fs = require('fs');
var path = require('path');
test('parse non-js, non-json files', function (t) {
t.plan(2);
var b = browserify();
b.add(__dirname + '/files/tr.beep');
b.transform(function (file) {
var buffers = [];
if (!/\.beep$/.test(file)) return through();
return through(write, end);
function write (buf) { buffers.push(buf) }
function end () {
var src = Buffer.concat(buffers).toString('utf8');
this.queue(src.replace(/\bFN\b/g, 'function'));
this.queue(null);
}
});
b.transform(path.dirname(__dirname));
var bs = b.bundle(function (err, src) {
if (err) t.fail(err);
vm.runInNewContext(src, { console: { log: log } });
});
bs.on('transform', function (tr) {
tr.on('file', function (file) {
t.equal(file, __dirname + '/files/tr.html');
});
});
function log (msg) {
t.equal(13, msg);
}
});
| {
"pile_set_name": "Github"
} |
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
# GB2312 most frequently used character table
#
# Char to FreqOrder table , from hz6763
# 512 --> 0.79 -- 0.79
# 1024 --> 0.92 -- 0.13
# 2048 --> 0.98 -- 0.06
# 6768 --> 1.00 -- 0.02
#
# Ideal Distribution Ratio = 0.79135/(1-0.79135) = 3.79
# Random Distribution Ration = 512 / (3755 - 512) = 0.157
#
# Typical Distribution Ratio about 25% of Ideal one, still much higher that RDR
GB2312_TYPICAL_DISTRIBUTION_RATIO = 0.9
GB2312_TABLE_SIZE = 3760
GB2312CharToFreqOrder = (
1671, 749,1443,2364,3924,3807,2330,3921,1704,3463,2691,1511,1515, 572,3191,2205,
2361, 224,2558, 479,1711, 963,3162, 440,4060,1905,2966,2947,3580,2647,3961,3842,
2204, 869,4207, 970,2678,5626,2944,2956,1479,4048, 514,3595, 588,1346,2820,3409,
249,4088,1746,1873,2047,1774, 581,1813, 358,1174,3590,1014,1561,4844,2245, 670,
1636,3112, 889,1286, 953, 556,2327,3060,1290,3141, 613, 185,3477,1367, 850,3820,
1715,2428,2642,2303,2732,3041,2562,2648,3566,3946,1349, 388,3098,2091,1360,3585,
152,1687,1539, 738,1559, 59,1232,2925,2267,1388,1249,1741,1679,2960, 151,1566,
1125,1352,4271, 924,4296, 385,3166,4459, 310,1245,2850, 70,3285,2729,3534,3575,
2398,3298,3466,1960,2265, 217,3647, 864,1909,2084,4401,2773,1010,3269,5152, 853,
3051,3121,1244,4251,1895, 364,1499,1540,2313,1180,3655,2268, 562, 715,2417,3061,
544, 336,3768,2380,1752,4075, 950, 280,2425,4382, 183,2759,3272, 333,4297,2155,
1688,2356,1444,1039,4540, 736,1177,3349,2443,2368,2144,2225, 565, 196,1482,3406,
927,1335,4147, 692, 878,1311,1653,3911,3622,1378,4200,1840,2969,3149,2126,1816,
2534,1546,2393,2760, 737,2494, 13, 447, 245,2747, 38,2765,2129,2589,1079, 606,
360, 471,3755,2890, 404, 848, 699,1785,1236, 370,2221,1023,3746,2074,2026,2023,
2388,1581,2119, 812,1141,3091,2536,1519, 804,2053, 406,1596,1090, 784, 548,4414,
1806,2264,2936,1100, 343,4114,5096, 622,3358, 743,3668,1510,1626,5020,3567,2513,
3195,4115,5627,2489,2991, 24,2065,2697,1087,2719, 48,1634, 315, 68, 985,2052,
198,2239,1347,1107,1439, 597,2366,2172, 871,3307, 919,2487,2790,1867, 236,2570,
1413,3794, 906,3365,3381,1701,1982,1818,1524,2924,1205, 616,2586,2072,2004, 575,
253,3099, 32,1365,1182, 197,1714,2454,1201, 554,3388,3224,2748, 756,2587, 250,
2567,1507,1517,3529,1922,2761,2337,3416,1961,1677,2452,2238,3153, 615, 911,1506,
1474,2495,1265,1906,2749,3756,3280,2161, 898,2714,1759,3450,2243,2444, 563, 26,
3286,2266,3769,3344,2707,3677, 611,1402, 531,1028,2871,4548,1375, 261,2948, 835,
1190,4134, 353, 840,2684,1900,3082,1435,2109,1207,1674, 329,1872,2781,4055,2686,
2104, 608,3318,2423,2957,2768,1108,3739,3512,3271,3985,2203,1771,3520,1418,2054,
1681,1153, 225,1627,2929, 162,2050,2511,3687,1954, 124,1859,2431,1684,3032,2894,
585,4805,3969,2869,2704,2088,2032,2095,3656,2635,4362,2209, 256, 518,2042,2105,
3777,3657, 643,2298,1148,1779, 190, 989,3544, 414, 11,2135,2063,2979,1471, 403,
3678, 126, 770,1563, 671,2499,3216,2877, 600,1179, 307,2805,4937,1268,1297,2694,
252,4032,1448,1494,1331,1394, 127,2256, 222,1647,1035,1481,3056,1915,1048, 873,
3651, 210, 33,1608,2516, 200,1520, 415, 102, 0,3389,1287, 817, 91,3299,2940,
836,1814, 549,2197,1396,1669,2987,3582,2297,2848,4528,1070, 687, 20,1819, 121,
1552,1364,1461,1968,2617,3540,2824,2083, 177, 948,4938,2291, 110,4549,2066, 648,
3359,1755,2110,2114,4642,4845,1693,3937,3308,1257,1869,2123, 208,1804,3159,2992,
2531,2549,3361,2418,1350,2347,2800,2568,1291,2036,2680, 72, 842,1990, 212,1233,
1154,1586, 75,2027,3410,4900,1823,1337,2710,2676, 728,2810,1522,3026,4995, 157,
755,1050,4022, 710, 785,1936,2194,2085,1406,2777,2400, 150,1250,4049,1206, 807,
1910, 534, 529,3309,1721,1660, 274, 39,2827, 661,2670,1578, 925,3248,3815,1094,
4278,4901,4252, 41,1150,3747,2572,2227,4501,3658,4902,3813,3357,3617,2884,2258,
887, 538,4187,3199,1294,2439,3042,2329,2343,2497,1255, 107, 543,1527, 521,3478,
3568, 194,5062, 15, 961,3870,1241,1192,2664, 66,5215,3260,2111,1295,1127,2152,
3805,4135, 901,1164,1976, 398,1278, 530,1460, 748, 904,1054,1966,1426, 53,2909,
509, 523,2279,1534, 536,1019, 239,1685, 460,2353, 673,1065,2401,3600,4298,2272,
1272,2363, 284,1753,3679,4064,1695, 81, 815,2677,2757,2731,1386, 859, 500,4221,
2190,2566, 757,1006,2519,2068,1166,1455, 337,2654,3203,1863,1682,1914,3025,1252,
1409,1366, 847, 714,2834,2038,3209, 964,2970,1901, 885,2553,1078,1756,3049, 301,
1572,3326, 688,2130,1996,2429,1805,1648,2930,3421,2750,3652,3088, 262,1158,1254,
389,1641,1812, 526,1719, 923,2073,1073,1902, 468, 489,4625,1140, 857,2375,3070,
3319,2863, 380, 116,1328,2693,1161,2244, 273,1212,1884,2769,3011,1775,1142, 461,
3066,1200,2147,2212, 790, 702,2695,4222,1601,1058, 434,2338,5153,3640, 67,2360,
4099,2502, 618,3472,1329, 416,1132, 830,2782,1807,2653,3211,3510,1662, 192,2124,
296,3979,1739,1611,3684, 23, 118, 324, 446,1239,1225, 293,2520,3814,3795,2535,
3116, 17,1074, 467,2692,2201, 387,2922, 45,1326,3055,1645,3659,2817, 958, 243,
1903,2320,1339,2825,1784,3289, 356, 576, 865,2315,2381,3377,3916,1088,3122,1713,
1655, 935, 628,4689,1034,1327, 441, 800, 720, 894,1979,2183,1528,5289,2702,1071,
4046,3572,2399,1571,3281, 79, 761,1103, 327, 134, 758,1899,1371,1615, 879, 442,
215,2605,2579, 173,2048,2485,1057,2975,3317,1097,2253,3801,4263,1403,1650,2946,
814,4968,3487,1548,2644,1567,1285, 2, 295,2636, 97, 946,3576, 832, 141,4257,
3273, 760,3821,3521,3156,2607, 949,1024,1733,1516,1803,1920,2125,2283,2665,3180,
1501,2064,3560,2171,1592, 803,3518,1416, 732,3897,4258,1363,1362,2458, 119,1427,
602,1525,2608,1605,1639,3175, 694,3064, 10, 465, 76,2000,4846,4208, 444,3781,
1619,3353,2206,1273,3796, 740,2483, 320,1723,2377,3660,2619,1359,1137,1762,1724,
2345,2842,1850,1862, 912, 821,1866, 612,2625,1735,2573,3369,1093, 844, 89, 937,
930,1424,3564,2413,2972,1004,3046,3019,2011, 711,3171,1452,4178, 428, 801,1943,
432, 445,2811, 206,4136,1472, 730, 349, 73, 397,2802,2547, 998,1637,1167, 789,
396,3217, 154,1218, 716,1120,1780,2819,4826,1931,3334,3762,2139,1215,2627, 552,
3664,3628,3232,1405,2383,3111,1356,2652,3577,3320,3101,1703, 640,1045,1370,1246,
4996, 371,1575,2436,1621,2210, 984,4033,1734,2638, 16,4529, 663,2755,3255,1451,
3917,2257,1253,1955,2234,1263,2951, 214,1229, 617, 485, 359,1831,1969, 473,2310,
750,2058, 165, 80,2864,2419, 361,4344,2416,2479,1134, 796,3726,1266,2943, 860,
2715, 938, 390,2734,1313,1384, 248, 202, 877,1064,2854, 522,3907, 279,1602, 297,
2357, 395,3740, 137,2075, 944,4089,2584,1267,3802, 62,1533,2285, 178, 176, 780,
2440, 201,3707, 590, 478,1560,4354,2117,1075, 30, 74,4643,4004,1635,1441,2745,
776,2596, 238,1077,1692,1912,2844, 605, 499,1742,3947, 241,3053, 980,1749, 936,
2640,4511,2582, 515,1543,2162,5322,2892,2993, 890,2148,1924, 665,1827,3581,1032,
968,3163, 339,1044,1896, 270, 583,1791,1720,4367,1194,3488,3669, 43,2523,1657,
163,2167, 290,1209,1622,3378, 550, 634,2508,2510, 695,2634,2384,2512,1476,1414,
220,1469,2341,2138,2852,3183,2900,4939,2865,3502,1211,3680, 854,3227,1299,2976,
3172, 186,2998,1459, 443,1067,3251,1495, 321,1932,3054, 909, 753,1410,1828, 436,
2441,1119,1587,3164,2186,1258, 227, 231,1425,1890,3200,3942, 247, 959, 725,5254,
2741, 577,2158,2079, 929, 120, 174, 838,2813, 591,1115, 417,2024, 40,3240,1536,
1037, 291,4151,2354, 632,1298,2406,2500,3535,1825,1846,3451, 205,1171, 345,4238,
18,1163, 811, 685,2208,1217, 425,1312,1508,1175,4308,2552,1033, 587,1381,3059,
2984,3482, 340,1316,4023,3972, 792,3176, 519, 777,4690, 918, 933,4130,2981,3741,
90,3360,2911,2200,5184,4550, 609,3079,2030, 272,3379,2736, 363,3881,1130,1447,
286, 779, 357,1169,3350,3137,1630,1220,2687,2391, 747,1277,3688,2618,2682,2601,
1156,3196,5290,4034,3102,1689,3596,3128, 874, 219,2783, 798, 508,1843,2461, 269,
1658,1776,1392,1913,2983,3287,2866,2159,2372, 829,4076, 46,4253,2873,1889,1894,
915,1834,1631,2181,2318, 298, 664,2818,3555,2735, 954,3228,3117, 527,3511,2173,
681,2712,3033,2247,2346,3467,1652, 155,2164,3382, 113,1994, 450, 899, 494, 994,
1237,2958,1875,2336,1926,3727, 545,1577,1550, 633,3473, 204,1305,3072,2410,1956,
2471, 707,2134, 841,2195,2196,2663,3843,1026,4940, 990,3252,4997, 368,1092, 437,
3212,3258,1933,1829, 675,2977,2893, 412, 943,3723,4644,3294,3283,2230,2373,5154,
2389,2241,2661,2323,1404,2524, 593, 787, 677,3008,1275,2059, 438,2709,2609,2240,
2269,2246,1446, 36,1568,1373,3892,1574,2301,1456,3962, 693,2276,5216,2035,1143,
2720,1919,1797,1811,2763,4137,2597,1830,1699,1488,1198,2090, 424,1694, 312,3634,
3390,4179,3335,2252,1214, 561,1059,3243,2295,2561, 975,5155,2321,2751,3772, 472,
1537,3282,3398,1047,2077,2348,2878,1323,3340,3076, 690,2906, 51, 369, 170,3541,
1060,2187,2688,3670,2541,1083,1683, 928,3918, 459, 109,4427, 599,3744,4286, 143,
2101,2730,2490, 82,1588,3036,2121, 281,1860, 477,4035,1238,2812,3020,2716,3312,
1530,2188,2055,1317, 843, 636,1808,1173,3495, 649, 181,1002, 147,3641,1159,2414,
3750,2289,2795, 813,3123,2610,1136,4368, 5,3391,4541,2174, 420, 429,1728, 754,
1228,2115,2219, 347,2223,2733, 735,1518,3003,2355,3134,1764,3948,3329,1888,2424,
1001,1234,1972,3321,3363,1672,1021,1450,1584, 226, 765, 655,2526,3404,3244,2302,
3665, 731, 594,2184, 319,1576, 621, 658,2656,4299,2099,3864,1279,2071,2598,2739,
795,3086,3699,3908,1707,2352,2402,1382,3136,2475,1465,4847,3496,3865,1085,3004,
2591,1084, 213,2287,1963,3565,2250, 822, 793,4574,3187,1772,1789,3050, 595,1484,
1959,2770,1080,2650, 456, 422,2996, 940,3322,4328,4345,3092,2742, 965,2784, 739,
4124, 952,1358,2498,2949,2565, 332,2698,2378, 660,2260,2473,4194,3856,2919, 535,
1260,2651,1208,1428,1300,1949,1303,2942, 433,2455,2450,1251,1946, 614,1269, 641,
1306,1810,2737,3078,2912, 564,2365,1419,1415,1497,4460,2367,2185,1379,3005,1307,
3218,2175,1897,3063, 682,1157,4040,4005,1712,1160,1941,1399, 394, 402,2952,1573,
1151,2986,2404, 862, 299,2033,1489,3006, 346, 171,2886,3401,1726,2932, 168,2533,
47,2507,1030,3735,1145,3370,1395,1318,1579,3609,4560,2857,4116,1457,2529,1965,
504,1036,2690,2988,2405, 745,5871, 849,2397,2056,3081, 863,2359,3857,2096, 99,
1397,1769,2300,4428,1643,3455,1978,1757,3718,1440, 35,4879,3742,1296,4228,2280,
160,5063,1599,2013, 166, 520,3479,1646,3345,3012, 490,1937,1545,1264,2182,2505,
1096,1188,1369,1436,2421,1667,2792,2460,1270,2122, 727,3167,2143, 806,1706,1012,
1800,3037, 960,2218,1882, 805, 139,2456,1139,1521, 851,1052,3093,3089, 342,2039,
744,5097,1468,1502,1585,2087, 223, 939, 326,2140,2577, 892,2481,1623,4077, 982,
3708, 135,2131, 87,2503,3114,2326,1106, 876,1616, 547,2997,2831,2093,3441,4530,
4314, 9,3256,4229,4148, 659,1462,1986,1710,2046,2913,2231,4090,4880,5255,3392,
3274,1368,3689,4645,1477, 705,3384,3635,1068,1529,2941,1458,3782,1509, 100,1656,
2548, 718,2339, 408,1590,2780,3548,1838,4117,3719,1345,3530, 717,3442,2778,3220,
2898,1892,4590,3614,3371,2043,1998,1224,3483, 891, 635, 584,2559,3355, 733,1766,
1729,1172,3789,1891,2307, 781,2982,2271,1957,1580,5773,2633,2005,4195,3097,1535,
3213,1189,1934,5693,3262, 586,3118,1324,1598, 517,1564,2217,1868,1893,4445,3728,
2703,3139,1526,1787,1992,3882,2875,1549,1199,1056,2224,1904,2711,5098,4287, 338,
1993,3129,3489,2689,1809,2815,1997, 957,1855,3898,2550,3275,3057,1105,1319, 627,
1505,1911,1883,3526, 698,3629,3456,1833,1431, 746, 77,1261,2017,2296,1977,1885,
125,1334,1600, 525,1798,1109,2222,1470,1945, 559,2236,1186,3443,2476,1929,1411,
2411,3135,1777,3372,2621,1841,1613,3229, 668,1430,1839,2643,2916, 195,1989,2671,
2358,1387, 629,3205,2293,5256,4439, 123,1310, 888,1879,4300,3021,3605,1003,1162,
3192,2910,2010, 140,2395,2859, 55,1082,2012,2901, 662, 419,2081,1438, 680,2774,
4654,3912,1620,1731,1625,5035,4065,2328, 512,1344, 802,5443,2163,2311,2537, 524,
3399, 98,1155,2103,1918,2606,3925,2816,1393,2465,1504,3773,2177,3963,1478,4346,
180,1113,4655,3461,2028,1698, 833,2696,1235,1322,1594,4408,3623,3013,3225,2040,
3022, 541,2881, 607,3632,2029,1665,1219, 639,1385,1686,1099,2803,3231,1938,3188,
2858, 427, 676,2772,1168,2025, 454,3253,2486,3556, 230,1950, 580, 791,1991,1280,
1086,1974,2034, 630, 257,3338,2788,4903,1017, 86,4790, 966,2789,1995,1696,1131,
259,3095,4188,1308, 179,1463,5257, 289,4107,1248, 42,3413,1725,2288, 896,1947,
774,4474,4254, 604,3430,4264, 392,2514,2588, 452, 237,1408,3018, 988,4531,1970,
3034,3310, 540,2370,1562,1288,2990, 502,4765,1147, 4,1853,2708, 207, 294,2814,
4078,2902,2509, 684, 34,3105,3532,2551, 644, 709,2801,2344, 573,1727,3573,3557,
2021,1081,3100,4315,2100,3681, 199,2263,1837,2385, 146,3484,1195,2776,3949, 997,
1939,3973,1008,1091,1202,1962,1847,1149,4209,5444,1076, 493, 117,5400,2521, 972,
1490,2934,1796,4542,2374,1512,2933,2657, 413,2888,1135,2762,2314,2156,1355,2369,
766,2007,2527,2170,3124,2491,2593,2632,4757,2437, 234,3125,3591,1898,1750,1376,
1942,3468,3138, 570,2127,2145,3276,4131, 962, 132,1445,4196, 19, 941,3624,3480,
3366,1973,1374,4461,3431,2629, 283,2415,2275, 808,2887,3620,2112,2563,1353,3610,
955,1089,3103,1053, 96, 88,4097, 823,3808,1583, 399, 292,4091,3313, 421,1128,
642,4006, 903,2539,1877,2082, 596, 29,4066,1790, 722,2157, 130, 995,1569, 769,
1485, 464, 513,2213, 288,1923,1101,2453,4316, 133, 486,2445, 50, 625, 487,2207,
57, 423, 481,2962, 159,3729,1558, 491, 303, 482, 501, 240,2837, 112,3648,2392,
1783, 362, 8,3433,3422, 610,2793,3277,1390,1284,1654, 21,3823, 734, 367, 623,
193, 287, 374,1009,1483, 816, 476, 313,2255,2340,1262,2150,2899,1146,2581, 782,
2116,1659,2018,1880, 255,3586,3314,1110,2867,2137,2564, 986,2767,5185,2006, 650,
158, 926, 762, 881,3157,2717,2362,3587, 306,3690,3245,1542,3077,2427,1691,2478,
2118,2985,3490,2438, 539,2305, 983, 129,1754, 355,4201,2386, 827,2923, 104,1773,
2838,2771, 411,2905,3919, 376, 767, 122,1114, 828,2422,1817,3506, 266,3460,1007,
1609,4998, 945,2612,4429,2274, 726,1247,1964,2914,2199,2070,4002,4108, 657,3323,
1422, 579, 455,2764,4737,1222,2895,1670, 824,1223,1487,2525, 558, 861,3080, 598,
2659,2515,1967, 752,2583,2376,2214,4180, 977, 704,2464,4999,2622,4109,1210,2961,
819,1541, 142,2284, 44, 418, 457,1126,3730,4347,4626,1644,1876,3671,1864, 302,
1063,5694, 624, 723,1984,3745,1314,1676,2488,1610,1449,3558,3569,2166,2098, 409,
1011,2325,3704,2306, 818,1732,1383,1824,1844,3757, 999,2705,3497,1216,1423,2683,
2426,2954,2501,2726,2229,1475,2554,5064,1971,1794,1666,2014,1343, 783, 724, 191,
2434,1354,2220,5065,1763,2752,2472,4152, 131, 175,2885,3434, 92,1466,4920,2616,
3871,3872,3866, 128,1551,1632, 669,1854,3682,4691,4125,1230, 188,2973,3290,1302,
1213, 560,3266, 917, 763,3909,3249,1760, 868,1958, 764,1782,2097, 145,2277,3774,
4462, 64,1491,3062, 971,2132,3606,2442, 221,1226,1617, 218, 323,1185,3207,3147,
571, 619,1473,1005,1744,2281, 449,1887,2396,3685, 275, 375,3816,1743,3844,3731,
845,1983,2350,4210,1377, 773, 967,3499,3052,3743,2725,4007,1697,1022,3943,1464,
3264,2855,2722,1952,1029,2839,2467, 84,4383,2215, 820,1391,2015,2448,3672, 377,
1948,2168, 797,2545,3536,2578,2645, 94,2874,1678, 405,1259,3071, 771, 546,1315,
470,1243,3083, 895,2468, 981, 969,2037, 846,4181, 653,1276,2928, 14,2594, 557,
3007,2474, 156, 902,1338,1740,2574, 537,2518, 973,2282,2216,2433,1928, 138,2903,
1293,2631,1612, 646,3457, 839,2935, 111, 496,2191,2847, 589,3186, 149,3994,2060,
4031,2641,4067,3145,1870, 37,3597,2136,1025,2051,3009,3383,3549,1121,1016,3261,
1301, 251,2446,2599,2153, 872,3246, 637, 334,3705, 831, 884, 921,3065,3140,4092,
2198,1944, 246,2964, 108,2045,1152,1921,2308,1031, 203,3173,4170,1907,3890, 810,
1401,2003,1690, 506, 647,1242,2828,1761,1649,3208,2249,1589,3709,2931,5156,1708,
498, 666,2613, 834,3817,1231, 184,2851,1124, 883,3197,2261,3710,1765,1553,2658,
1178,2639,2351, 93,1193, 942,2538,2141,4402, 235,1821, 870,1591,2192,1709,1871,
3341,1618,4126,2595,2334, 603, 651, 69, 701, 268,2662,3411,2555,1380,1606, 503,
448, 254,2371,2646, 574,1187,2309,1770, 322,2235,1292,1801, 305, 566,1133, 229,
2067,2057, 706, 167, 483,2002,2672,3295,1820,3561,3067, 316, 378,2746,3452,1112,
136,1981, 507,1651,2917,1117, 285,4591, 182,2580,3522,1304, 335,3303,1835,2504,
1795,1792,2248, 674,1018,2106,2449,1857,2292,2845, 976,3047,1781,2600,2727,1389,
1281, 52,3152, 153, 265,3950, 672,3485,3951,4463, 430,1183, 365, 278,2169, 27,
1407,1336,2304, 209,1340,1730,2202,1852,2403,2883, 979,1737,1062, 631,2829,2542,
3876,2592, 825,2086,2226,3048,3625, 352,1417,3724, 542, 991, 431,1351,3938,1861,
2294, 826,1361,2927,3142,3503,1738, 463,2462,2723, 582,1916,1595,2808, 400,3845,
3891,2868,3621,2254, 58,2492,1123, 910,2160,2614,1372,1603,1196,1072,3385,1700,
3267,1980, 696, 480,2430, 920, 799,1570,2920,1951,2041,4047,2540,1321,4223,2469,
3562,2228,1271,2602, 401,2833,3351,2575,5157, 907,2312,1256, 410, 263,3507,1582,
996, 678,1849,2316,1480, 908,3545,2237, 703,2322, 667,1826,2849,1531,2604,2999,
2407,3146,2151,2630,1786,3711, 469,3542, 497,3899,2409, 858, 837,4446,3393,1274,
786, 620,1845,2001,3311, 484, 308,3367,1204,1815,3691,2332,1532,2557,1842,2020,
2724,1927,2333,4440, 567, 22,1673,2728,4475,1987,1858,1144,1597, 101,1832,3601,
12, 974,3783,4391, 951,1412, 1,3720, 453,4608,4041, 528,1041,1027,3230,2628,
1129, 875,1051,3291,1203,2262,1069,2860,2799,2149,2615,3278, 144,1758,3040, 31,
475,1680, 366,2685,3184, 311,1642,4008,2466,5036,1593,1493,2809, 216,1420,1668,
233, 304,2128,3284, 232,1429,1768,1040,2008,3407,2740,2967,2543, 242,2133, 778,
1565,2022,2620, 505,2189,2756,1098,2273, 372,1614, 708, 553,2846,2094,2278, 169,
3626,2835,4161, 228,2674,3165, 809,1454,1309, 466,1705,1095, 900,3423, 880,2667,
3751,5258,2317,3109,2571,4317,2766,1503,1342, 866,4447,1118, 63,2076, 314,1881,
1348,1061, 172, 978,3515,1747, 532, 511,3970, 6, 601, 905,2699,3300,1751, 276,
1467,3725,2668, 65,4239,2544,2779,2556,1604, 578,2451,1802, 992,2331,2624,1320,
3446, 713,1513,1013, 103,2786,2447,1661, 886,1702, 916, 654,3574,2031,1556, 751,
2178,2821,2179,1498,1538,2176, 271, 914,2251,2080,1325, 638,1953,2937,3877,2432,
2754, 95,3265,1716, 260,1227,4083, 775, 106,1357,3254, 426,1607, 555,2480, 772,
1985, 244,2546, 474, 495,1046,2611,1851,2061, 71,2089,1675,2590, 742,3758,2843,
3222,1433, 267,2180,2576,2826,2233,2092,3913,2435, 956,1745,3075, 856,2113,1116,
451, 3,1988,2896,1398, 993,2463,1878,2049,1341,2718,2721,2870,2108, 712,2904,
4363,2753,2324, 277,2872,2349,2649, 384, 987, 435, 691,3000, 922, 164,3939, 652,
1500,1184,4153,2482,3373,2165,4848,2335,3775,3508,3154,2806,2830,1554,2102,1664,
2530,1434,2408, 893,1547,2623,3447,2832,2242,2532,3169,2856,3223,2078, 49,3770,
3469, 462, 318, 656,2259,3250,3069, 679,1629,2758, 344,1138,1104,3120,1836,1283,
3115,2154,1437,4448, 934, 759,1999, 794,2862,1038, 533,2560,1722,2342, 855,2626,
1197,1663,4476,3127, 85,4240,2528, 25,1111,1181,3673, 407,3470,4561,2679,2713,
768,1925,2841,3986,1544,1165, 932, 373,1240,2146,1930,2673, 721,4766, 354,4333,
391,2963, 187, 61,3364,1442,1102, 330,1940,1767, 341,3809,4118, 393,2496,2062,
2211, 105, 331, 300, 439, 913,1332, 626, 379,3304,1557, 328, 689,3952, 309,1555,
931, 317,2517,3027, 325, 569, 686,2107,3084, 60,1042,1333,2794, 264,3177,4014,
1628, 258,3712, 7,4464,1176,1043,1778, 683, 114,1975, 78,1492, 383,1886, 510,
386, 645,5291,2891,2069,3305,4138,3867,2939,2603,2493,1935,1066,1848,3588,1015,
1282,1289,4609, 697,1453,3044,2666,3611,1856,2412, 54, 719,1330, 568,3778,2459,
1748, 788, 492, 551,1191,1000, 488,3394,3763, 282,1799, 348,2016,1523,3155,2390,
1049, 382,2019,1788,1170, 729,2968,3523, 897,3926,2785,2938,3292, 350,2319,3238,
1718,1717,2655,3453,3143,4465, 161,2889,2980,2009,1421, 56,1908,1640,2387,2232,
1917,1874,2477,4921, 148, 83,3438, 592,4245,2882,1822,1055, 741, 115,1496,1624,
381,1638,4592,1020, 516,3214, 458, 947,4575,1432, 211,1514,2926,1865,2142, 189,
852,1221,1400,1486, 882,2299,4036, 351, 28,1122, 700,6479,6480,6481,6482,6483, # last 512
#Everything below is of no interest for detection purpose
5508,6484,3900,3414,3974,4441,4024,3537,4037,5628,5099,3633,6485,3148,6486,3636,
5509,3257,5510,5973,5445,5872,4941,4403,3174,4627,5873,6276,2286,4230,5446,5874,
5122,6102,6103,4162,5447,5123,5323,4849,6277,3980,3851,5066,4246,5774,5067,6278,
3001,2807,5695,3346,5775,5974,5158,5448,6487,5975,5976,5776,3598,6279,5696,4806,
4211,4154,6280,6488,6489,6490,6281,4212,5037,3374,4171,6491,4562,4807,4722,4827,
5977,6104,4532,4079,5159,5324,5160,4404,3858,5359,5875,3975,4288,4610,3486,4512,
5325,3893,5360,6282,6283,5560,2522,4231,5978,5186,5449,2569,3878,6284,5401,3578,
4415,6285,4656,5124,5979,2506,4247,4449,3219,3417,4334,4969,4329,6492,4576,4828,
4172,4416,4829,5402,6286,3927,3852,5361,4369,4830,4477,4867,5876,4173,6493,6105,
4657,6287,6106,5877,5450,6494,4155,4868,5451,3700,5629,4384,6288,6289,5878,3189,
4881,6107,6290,6495,4513,6496,4692,4515,4723,5100,3356,6497,6291,3810,4080,5561,
3570,4430,5980,6498,4355,5697,6499,4724,6108,6109,3764,4050,5038,5879,4093,3226,
6292,5068,5217,4693,3342,5630,3504,4831,4377,4466,4309,5698,4431,5777,6293,5778,
4272,3706,6110,5326,3752,4676,5327,4273,5403,4767,5631,6500,5699,5880,3475,5039,
6294,5562,5125,4348,4301,4482,4068,5126,4593,5700,3380,3462,5981,5563,3824,5404,
4970,5511,3825,4738,6295,6501,5452,4516,6111,5881,5564,6502,6296,5982,6503,4213,
4163,3454,6504,6112,4009,4450,6113,4658,6297,6114,3035,6505,6115,3995,4904,4739,
4563,4942,4110,5040,3661,3928,5362,3674,6506,5292,3612,4791,5565,4149,5983,5328,
5259,5021,4725,4577,4564,4517,4364,6298,5405,4578,5260,4594,4156,4157,5453,3592,
3491,6507,5127,5512,4709,4922,5984,5701,4726,4289,6508,4015,6116,5128,4628,3424,
4241,5779,6299,4905,6509,6510,5454,5702,5780,6300,4365,4923,3971,6511,5161,3270,
3158,5985,4100, 867,5129,5703,6117,5363,3695,3301,5513,4467,6118,6512,5455,4232,
4242,4629,6513,3959,4478,6514,5514,5329,5986,4850,5162,5566,3846,4694,6119,5456,
4869,5781,3779,6301,5704,5987,5515,4710,6302,5882,6120,4392,5364,5705,6515,6121,
6516,6517,3736,5988,5457,5989,4695,2457,5883,4551,5782,6303,6304,6305,5130,4971,
6122,5163,6123,4870,3263,5365,3150,4871,6518,6306,5783,5069,5706,3513,3498,4409,
5330,5632,5366,5458,5459,3991,5990,4502,3324,5991,5784,3696,4518,5633,4119,6519,
4630,5634,4417,5707,4832,5992,3418,6124,5993,5567,4768,5218,6520,4595,3458,5367,
6125,5635,6126,4202,6521,4740,4924,6307,3981,4069,4385,6308,3883,2675,4051,3834,
4302,4483,5568,5994,4972,4101,5368,6309,5164,5884,3922,6127,6522,6523,5261,5460,
5187,4164,5219,3538,5516,4111,3524,5995,6310,6311,5369,3181,3386,2484,5188,3464,
5569,3627,5708,6524,5406,5165,4677,4492,6312,4872,4851,5885,4468,5996,6313,5709,
5710,6128,2470,5886,6314,5293,4882,5785,3325,5461,5101,6129,5711,5786,6525,4906,
6526,6527,4418,5887,5712,4808,2907,3701,5713,5888,6528,3765,5636,5331,6529,6530,
3593,5889,3637,4943,3692,5714,5787,4925,6315,6130,5462,4405,6131,6132,6316,5262,
6531,6532,5715,3859,5716,5070,4696,5102,3929,5788,3987,4792,5997,6533,6534,3920,
4809,5000,5998,6535,2974,5370,6317,5189,5263,5717,3826,6536,3953,5001,4883,3190,
5463,5890,4973,5999,4741,6133,6134,3607,5570,6000,4711,3362,3630,4552,5041,6318,
6001,2950,2953,5637,4646,5371,4944,6002,2044,4120,3429,6319,6537,5103,4833,6538,
6539,4884,4647,3884,6003,6004,4758,3835,5220,5789,4565,5407,6540,6135,5294,4697,
4852,6320,6321,3206,4907,6541,6322,4945,6542,6136,6543,6323,6005,4631,3519,6544,
5891,6545,5464,3784,5221,6546,5571,4659,6547,6324,6137,5190,6548,3853,6549,4016,
4834,3954,6138,5332,3827,4017,3210,3546,4469,5408,5718,3505,4648,5790,5131,5638,
5791,5465,4727,4318,6325,6326,5792,4553,4010,4698,3439,4974,3638,4335,3085,6006,
5104,5042,5166,5892,5572,6327,4356,4519,5222,5573,5333,5793,5043,6550,5639,5071,
4503,6328,6139,6551,6140,3914,3901,5372,6007,5640,4728,4793,3976,3836,4885,6552,
4127,6553,4451,4102,5002,6554,3686,5105,6555,5191,5072,5295,4611,5794,5296,6556,
5893,5264,5894,4975,5466,5265,4699,4976,4370,4056,3492,5044,4886,6557,5795,4432,
4769,4357,5467,3940,4660,4290,6141,4484,4770,4661,3992,6329,4025,4662,5022,4632,
4835,4070,5297,4663,4596,5574,5132,5409,5895,6142,4504,5192,4664,5796,5896,3885,
5575,5797,5023,4810,5798,3732,5223,4712,5298,4084,5334,5468,6143,4052,4053,4336,
4977,4794,6558,5335,4908,5576,5224,4233,5024,4128,5469,5225,4873,6008,5045,4729,
4742,4633,3675,4597,6559,5897,5133,5577,5003,5641,5719,6330,6560,3017,2382,3854,
4406,4811,6331,4393,3964,4946,6561,2420,3722,6562,4926,4378,3247,1736,4442,6332,
5134,6333,5226,3996,2918,5470,4319,4003,4598,4743,4744,4485,3785,3902,5167,5004,
5373,4394,5898,6144,4874,1793,3997,6334,4085,4214,5106,5642,4909,5799,6009,4419,
4189,3330,5899,4165,4420,5299,5720,5227,3347,6145,4081,6335,2876,3930,6146,3293,
3786,3910,3998,5900,5300,5578,2840,6563,5901,5579,6147,3531,5374,6564,6565,5580,
4759,5375,6566,6148,3559,5643,6336,6010,5517,6337,6338,5721,5902,3873,6011,6339,
6567,5518,3868,3649,5722,6568,4771,4947,6569,6149,4812,6570,2853,5471,6340,6341,
5644,4795,6342,6012,5723,6343,5724,6013,4349,6344,3160,6150,5193,4599,4514,4493,
5168,4320,6345,4927,3666,4745,5169,5903,5005,4928,6346,5725,6014,4730,4203,5046,
4948,3395,5170,6015,4150,6016,5726,5519,6347,5047,3550,6151,6348,4197,4310,5904,
6571,5581,2965,6152,4978,3960,4291,5135,6572,5301,5727,4129,4026,5905,4853,5728,
5472,6153,6349,4533,2700,4505,5336,4678,3583,5073,2994,4486,3043,4554,5520,6350,
6017,5800,4487,6351,3931,4103,5376,6352,4011,4321,4311,4190,5136,6018,3988,3233,
4350,5906,5645,4198,6573,5107,3432,4191,3435,5582,6574,4139,5410,6353,5411,3944,
5583,5074,3198,6575,6354,4358,6576,5302,4600,5584,5194,5412,6577,6578,5585,5413,
5303,4248,5414,3879,4433,6579,4479,5025,4854,5415,6355,4760,4772,3683,2978,4700,
3797,4452,3965,3932,3721,4910,5801,6580,5195,3551,5907,3221,3471,3029,6019,3999,
5908,5909,5266,5267,3444,3023,3828,3170,4796,5646,4979,4259,6356,5647,5337,3694,
6357,5648,5338,4520,4322,5802,3031,3759,4071,6020,5586,4836,4386,5048,6581,3571,
4679,4174,4949,6154,4813,3787,3402,3822,3958,3215,3552,5268,4387,3933,4950,4359,
6021,5910,5075,3579,6358,4234,4566,5521,6359,3613,5049,6022,5911,3375,3702,3178,
4911,5339,4521,6582,6583,4395,3087,3811,5377,6023,6360,6155,4027,5171,5649,4421,
4249,2804,6584,2270,6585,4000,4235,3045,6156,5137,5729,4140,4312,3886,6361,4330,
6157,4215,6158,3500,3676,4929,4331,3713,4930,5912,4265,3776,3368,5587,4470,4855,
3038,4980,3631,6159,6160,4132,4680,6161,6362,3923,4379,5588,4255,6586,4121,6587,
6363,4649,6364,3288,4773,4774,6162,6024,6365,3543,6588,4274,3107,3737,5050,5803,
4797,4522,5589,5051,5730,3714,4887,5378,4001,4523,6163,5026,5522,4701,4175,2791,
3760,6589,5473,4224,4133,3847,4814,4815,4775,3259,5416,6590,2738,6164,6025,5304,
3733,5076,5650,4816,5590,6591,6165,6592,3934,5269,6593,3396,5340,6594,5804,3445,
3602,4042,4488,5731,5732,3525,5591,4601,5196,6166,6026,5172,3642,4612,3202,4506,
4798,6366,3818,5108,4303,5138,5139,4776,3332,4304,2915,3415,4434,5077,5109,4856,
2879,5305,4817,6595,5913,3104,3144,3903,4634,5341,3133,5110,5651,5805,6167,4057,
5592,2945,4371,5593,6596,3474,4182,6367,6597,6168,4507,4279,6598,2822,6599,4777,
4713,5594,3829,6169,3887,5417,6170,3653,5474,6368,4216,2971,5228,3790,4579,6369,
5733,6600,6601,4951,4746,4555,6602,5418,5475,6027,3400,4665,5806,6171,4799,6028,
5052,6172,3343,4800,4747,5006,6370,4556,4217,5476,4396,5229,5379,5477,3839,5914,
5652,5807,4714,3068,4635,5808,6173,5342,4192,5078,5419,5523,5734,6174,4557,6175,
4602,6371,6176,6603,5809,6372,5735,4260,3869,5111,5230,6029,5112,6177,3126,4681,
5524,5915,2706,3563,4748,3130,6178,4018,5525,6604,6605,5478,4012,4837,6606,4534,
4193,5810,4857,3615,5479,6030,4082,3697,3539,4086,5270,3662,4508,4931,5916,4912,
5811,5027,3888,6607,4397,3527,3302,3798,2775,2921,2637,3966,4122,4388,4028,4054,
1633,4858,5079,3024,5007,3982,3412,5736,6608,3426,3236,5595,3030,6179,3427,3336,
3279,3110,6373,3874,3039,5080,5917,5140,4489,3119,6374,5812,3405,4494,6031,4666,
4141,6180,4166,6032,5813,4981,6609,5081,4422,4982,4112,3915,5653,3296,3983,6375,
4266,4410,5654,6610,6181,3436,5082,6611,5380,6033,3819,5596,4535,5231,5306,5113,
6612,4952,5918,4275,3113,6613,6376,6182,6183,5814,3073,4731,4838,5008,3831,6614,
4888,3090,3848,4280,5526,5232,3014,5655,5009,5737,5420,5527,6615,5815,5343,5173,
5381,4818,6616,3151,4953,6617,5738,2796,3204,4360,2989,4281,5739,5174,5421,5197,
3132,5141,3849,5142,5528,5083,3799,3904,4839,5480,2880,4495,3448,6377,6184,5271,
5919,3771,3193,6034,6035,5920,5010,6036,5597,6037,6378,6038,3106,5422,6618,5423,
5424,4142,6619,4889,5084,4890,4313,5740,6620,3437,5175,5307,5816,4199,5198,5529,
5817,5199,5656,4913,5028,5344,3850,6185,2955,5272,5011,5818,4567,4580,5029,5921,
3616,5233,6621,6622,6186,4176,6039,6379,6380,3352,5200,5273,2908,5598,5234,3837,
5308,6623,6624,5819,4496,4323,5309,5201,6625,6626,4983,3194,3838,4167,5530,5922,
5274,6381,6382,3860,3861,5599,3333,4292,4509,6383,3553,5481,5820,5531,4778,6187,
3955,3956,4324,4389,4218,3945,4325,3397,2681,5923,4779,5085,4019,5482,4891,5382,
5383,6040,4682,3425,5275,4094,6627,5310,3015,5483,5657,4398,5924,3168,4819,6628,
5925,6629,5532,4932,4613,6041,6630,4636,6384,4780,4204,5658,4423,5821,3989,4683,
5822,6385,4954,6631,5345,6188,5425,5012,5384,3894,6386,4490,4104,6632,5741,5053,
6633,5823,5926,5659,5660,5927,6634,5235,5742,5824,4840,4933,4820,6387,4859,5928,
4955,6388,4143,3584,5825,5346,5013,6635,5661,6389,5014,5484,5743,4337,5176,5662,
6390,2836,6391,3268,6392,6636,6042,5236,6637,4158,6638,5744,5663,4471,5347,3663,
4123,5143,4293,3895,6639,6640,5311,5929,5826,3800,6189,6393,6190,5664,5348,3554,
3594,4749,4603,6641,5385,4801,6043,5827,4183,6642,5312,5426,4761,6394,5665,6191,
4715,2669,6643,6644,5533,3185,5427,5086,5930,5931,5386,6192,6044,6645,4781,4013,
5745,4282,4435,5534,4390,4267,6045,5746,4984,6046,2743,6193,3501,4087,5485,5932,
5428,4184,4095,5747,4061,5054,3058,3862,5933,5600,6646,5144,3618,6395,3131,5055,
5313,6396,4650,4956,3855,6194,3896,5202,4985,4029,4225,6195,6647,5828,5486,5829,
3589,3002,6648,6397,4782,5276,6649,6196,6650,4105,3803,4043,5237,5830,6398,4096,
3643,6399,3528,6651,4453,3315,4637,6652,3984,6197,5535,3182,3339,6653,3096,2660,
6400,6654,3449,5934,4250,4236,6047,6401,5831,6655,5487,3753,4062,5832,6198,6199,
6656,3766,6657,3403,4667,6048,6658,4338,2897,5833,3880,2797,3780,4326,6659,5748,
5015,6660,5387,4351,5601,4411,6661,3654,4424,5935,4339,4072,5277,4568,5536,6402,
6662,5238,6663,5349,5203,6200,5204,6201,5145,4536,5016,5056,4762,5834,4399,4957,
6202,6403,5666,5749,6664,4340,6665,5936,5177,5667,6666,6667,3459,4668,6404,6668,
6669,4543,6203,6670,4276,6405,4480,5537,6671,4614,5205,5668,6672,3348,2193,4763,
6406,6204,5937,5602,4177,5669,3419,6673,4020,6205,4443,4569,5388,3715,3639,6407,
6049,4058,6206,6674,5938,4544,6050,4185,4294,4841,4651,4615,5488,6207,6408,6051,
5178,3241,3509,5835,6208,4958,5836,4341,5489,5278,6209,2823,5538,5350,5206,5429,
6675,4638,4875,4073,3516,4684,4914,4860,5939,5603,5389,6052,5057,3237,5490,3791,
6676,6409,6677,4821,4915,4106,5351,5058,4243,5539,4244,5604,4842,4916,5239,3028,
3716,5837,5114,5605,5390,5940,5430,6210,4332,6678,5540,4732,3667,3840,6053,4305,
3408,5670,5541,6410,2744,5240,5750,6679,3234,5606,6680,5607,5671,3608,4283,4159,
4400,5352,4783,6681,6411,6682,4491,4802,6211,6412,5941,6413,6414,5542,5751,6683,
4669,3734,5942,6684,6415,5943,5059,3328,4670,4144,4268,6685,6686,6687,6688,4372,
3603,6689,5944,5491,4373,3440,6416,5543,4784,4822,5608,3792,4616,5838,5672,3514,
5391,6417,4892,6690,4639,6691,6054,5673,5839,6055,6692,6056,5392,6212,4038,5544,
5674,4497,6057,6693,5840,4284,5675,4021,4545,5609,6418,4454,6419,6213,4113,4472,
5314,3738,5087,5279,4074,5610,4959,4063,3179,4750,6058,6420,6214,3476,4498,4716,
5431,4960,4685,6215,5241,6694,6421,6216,6695,5841,5945,6422,3748,5946,5179,3905,
5752,5545,5947,4374,6217,4455,6423,4412,6218,4803,5353,6696,3832,5280,6219,4327,
4702,6220,6221,6059,4652,5432,6424,3749,4751,6425,5753,4986,5393,4917,5948,5030,
5754,4861,4733,6426,4703,6697,6222,4671,5949,4546,4961,5180,6223,5031,3316,5281,
6698,4862,4295,4934,5207,3644,6427,5842,5950,6428,6429,4570,5843,5282,6430,6224,
5088,3239,6060,6699,5844,5755,6061,6431,2701,5546,6432,5115,5676,4039,3993,3327,
4752,4425,5315,6433,3941,6434,5677,4617,4604,3074,4581,6225,5433,6435,6226,6062,
4823,5756,5116,6227,3717,5678,4717,5845,6436,5679,5846,6063,5847,6064,3977,3354,
6437,3863,5117,6228,5547,5394,4499,4524,6229,4605,6230,4306,4500,6700,5951,6065,
3693,5952,5089,4366,4918,6701,6231,5548,6232,6702,6438,4704,5434,6703,6704,5953,
4168,6705,5680,3420,6706,5242,4407,6066,3812,5757,5090,5954,4672,4525,3481,5681,
4618,5395,5354,5316,5955,6439,4962,6707,4526,6440,3465,4673,6067,6441,5682,6708,
5435,5492,5758,5683,4619,4571,4674,4804,4893,4686,5493,4753,6233,6068,4269,6442,
6234,5032,4705,5146,5243,5208,5848,6235,6443,4963,5033,4640,4226,6236,5849,3387,
6444,6445,4436,4437,5850,4843,5494,4785,4894,6709,4361,6710,5091,5956,3331,6237,
4987,5549,6069,6711,4342,3517,4473,5317,6070,6712,6071,4706,6446,5017,5355,6713,
6714,4988,5436,6447,4734,5759,6715,4735,4547,4456,4754,6448,5851,6449,6450,3547,
5852,5318,6451,6452,5092,4205,6716,6238,4620,4219,5611,6239,6072,4481,5760,5957,
5958,4059,6240,6453,4227,4537,6241,5761,4030,4186,5244,5209,3761,4457,4876,3337,
5495,5181,6242,5959,5319,5612,5684,5853,3493,5854,6073,4169,5613,5147,4895,6074,
5210,6717,5182,6718,3830,6243,2798,3841,6075,6244,5855,5614,3604,4606,5496,5685,
5118,5356,6719,6454,5960,5357,5961,6720,4145,3935,4621,5119,5962,4261,6721,6455,
4786,5963,4375,4582,6245,6246,6247,6076,5437,4877,5856,3376,4380,6248,4160,6722,
5148,6456,5211,6457,6723,4718,6458,6724,6249,5358,4044,3297,6459,6250,5857,5615,
5497,5245,6460,5498,6725,6251,6252,5550,3793,5499,2959,5396,6461,6462,4572,5093,
5500,5964,3806,4146,6463,4426,5762,5858,6077,6253,4755,3967,4220,5965,6254,4989,
5501,6464,4352,6726,6078,4764,2290,5246,3906,5438,5283,3767,4964,2861,5763,5094,
6255,6256,4622,5616,5859,5860,4707,6727,4285,4708,4824,5617,6257,5551,4787,5212,
4965,4935,4687,6465,6728,6466,5686,6079,3494,4413,2995,5247,5966,5618,6729,5967,
5764,5765,5687,5502,6730,6731,6080,5397,6467,4990,6258,6732,4538,5060,5619,6733,
4719,5688,5439,5018,5149,5284,5503,6734,6081,4607,6259,5120,3645,5861,4583,6260,
4584,4675,5620,4098,5440,6261,4863,2379,3306,4585,5552,5689,4586,5285,6735,4864,
6736,5286,6082,6737,4623,3010,4788,4381,4558,5621,4587,4896,3698,3161,5248,4353,
4045,6262,3754,5183,4588,6738,6263,6739,6740,5622,3936,6741,6468,6742,6264,5095,
6469,4991,5968,6743,4992,6744,6083,4897,6745,4256,5766,4307,3108,3968,4444,5287,
3889,4343,6084,4510,6085,4559,6086,4898,5969,6746,5623,5061,4919,5249,5250,5504,
5441,6265,5320,4878,3242,5862,5251,3428,6087,6747,4237,5624,5442,6266,5553,4539,
6748,2585,3533,5398,4262,6088,5150,4736,4438,6089,6267,5505,4966,6749,6268,6750,
6269,5288,5554,3650,6090,6091,4624,6092,5690,6751,5863,4270,5691,4277,5555,5864,
6752,5692,4720,4865,6470,5151,4688,4825,6753,3094,6754,6471,3235,4653,6755,5213,
5399,6756,3201,4589,5865,4967,6472,5866,6473,5019,3016,6757,5321,4756,3957,4573,
6093,4993,5767,4721,6474,6758,5625,6759,4458,6475,6270,6760,5556,4994,5214,5252,
6271,3875,5768,6094,5034,5506,4376,5769,6761,2120,6476,5253,5770,6762,5771,5970,
3990,5971,5557,5558,5772,6477,6095,2787,4641,5972,5121,6096,6097,6272,6763,3703,
5867,5507,6273,4206,6274,4789,6098,6764,3619,3646,3833,3804,2394,3788,4936,3978,
4866,4899,6099,6100,5559,6478,6765,3599,5868,6101,5869,5870,6275,6766,4527,6767)
# flake8: noqa
| {
"pile_set_name": "Github"
} |
<?php
/*
* status.php
*
* part of pfSense (https://www.pfsense.org)
* Copyright (c) 2004-2013 BSD Perimeter
* Copyright (c) 2013-2016 Electric Sheep Fencing
* Copyright (c) 2014-2020 Rubicon Communications, LLC (Netgate)
* All rights reserved.
*
* originally based on m0n0wall (http://neon1.net/m0n0wall)
* Copyright (c) 2003 Jim McBeath <[email protected]>
* Copyright (c) 2003-2004 Manuel Kasper <[email protected]>.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
##|+PRIV
##|*IDENT=page-hidden-detailedstatus
##|*NAME=Hidden: Detailed Status
##|*DESCR=Allow access to the 'Hidden: Detailed Status' page.
##|*MATCH=status.php*
##|-PRIV
/* Execute a command, with a title, and generate an HTML table
* showing the results.
*/
global $console;
global $show_output;
$console = false;
$show_output = !isset($_GET['archiveonly']);
if ((php_sapi_name() == 'cli') || (defined('STDIN'))) {
/* Running from console/shell, not web */
$console = true;
$show_output = false;
parse_str($argv[1], $_GET);
}
/* include all configuration functions */
if ($console) {
require_once("config.inc");
} else {
require_once("guiconfig.inc");
}
require_once("functions.inc");
require_once("gwlb.inc");
$output_path = "/tmp/status_output/";
$output_file = "/tmp/status_output.tgz";
$filtered_tags = array(
'accountkey', 'authorizedkeys', 'auth_pass', 'auth_user',
'barnyard_dbpwd', 'bcrypt-hash', 'cert_key', 'community', 'crypto_password',
'crypto_password2', 'dns_nsupdatensupdate_key', 'encryption_password',
'etpro_code', 'etprocode', 'gold_encryption_password', 'gold_password',
'influx_pass', 'ipsecpsk', 'ldap_bindpw', 'ldapbindpass', 'ldap_pass',
'lighttpd_ls_password', 'maxmind_geoipdb_key', 'maxmind_key', 'md5-hash',
'md5password', 'md5sigkey', 'md5sigpass', 'nt-hash', 'oinkcode',
'oinkmastercode', 'passphrase', 'password', 'passwordagain',
'pkcs11pin', 'postgresqlpasswordenc', 'pre-shared-key', 'proxypass',
'proxy_passwd', 'proxyuser', 'proxy_user', 'prv', 'radius_secret',
'redis_password', 'redis_passwordagain', 'rocommunity', 'secret',
'shared_key', 'stats_password', 'tls', 'tlspskidentity', 'tlspskfile',
'varclientpasswordinput', 'varclientsharedsecret', 'varsqlconfpassword',
'varsqlconf2password', 'varsyncpassword', 'varmodulesldappassword', 'varmodulesldap2password',
'varusersmotpinitsecret', 'varusersmotppin', 'varuserspassword', 'webrootftppassword'
);
$acme_filtered_tags = array('key', 'password', 'secret', 'token', 'pwd', 'pw');
if ($_POST['submit'] == "DOWNLOAD" && file_exists($output_file)) {
session_cache_limiter('public');
send_user_download('file', $output_file);
}
if (is_dir($output_path)) {
unlink_if_exists("{$output_path}/*");
@rmdir($output_path);
}
unlink_if_exists($output_file);
mkdir($output_path);
function doCmdT($title, $command, $method) {
global $output_path, $output_file, $filtered_tags, $acme_filtered_tags, $show_output;
/* Fixup output directory */
if ($show_output) {
$rubbish = array('|', '-', '/', '.', ' '); /* fixes the <a> tag to be W3C compliant */
echo "\n<a name=\"" . str_replace($rubbish, '', $title) . "\" id=\"" . str_replace($rubbish, '', $title) . "\"></a>\n";
print('<div class="panel panel-default">');
print('<div class="panel-heading"><h2 class="panel-title">' . $title . '</h2></div>');
print('<div class="panel-body">');
print('<pre>');
}
if ($command == "dumpconfigxml") {
$ofd = @fopen("{$output_path}/config-sanitized.xml", "w");
$fd = @fopen("/conf/config.xml", "r");
if ($fd) {
while (!feof($fd)) {
$line = fgets($fd);
/* remove sensitive contents */
foreach ($filtered_tags as $tag) {
$line = preg_replace("/<{$tag}>.*?<\\/{$tag}>/", "<{$tag}>xxxxx</{$tag}>", $line);
}
/* remove ACME pkg sensitive contents */
foreach ($acme_filtered_tags as $tag) {
$line = preg_replace("/<dns_(.+){$tag}>.*?<\\/dns_(.+){$tag}>/", "<dns_$1{$tag}>xxxxx</dns_$1{$tag}>", $line);
}
if ($show_output) {
echo htmlspecialchars(str_replace("\t", " ", $line), ENT_NOQUOTES);
}
fwrite($ofd, $line);
}
}
fclose($fd);
fclose($ofd);
} else {
$execOutput = "";
$execStatus = "";
$fn = "{$output_path}/{$title}.txt";
if ($method == "exec") {
exec($command . " > " . escapeshellarg($fn) . " 2>&1", $execOutput, $execStatus);
if ($show_output) {
$ofd = @fopen($fn, "r");
if ($ofd) {
while (!feof($ofd)) {
echo htmlspecialchars(fgets($ofd), ENT_NOQUOTES);
}
}
fclose($ofd);
}
} elseif ($method == "php_func") {
$execOutput = $command();
if ($show_output) {
echo htmlspecialchars($execOutput, ENT_NOQUOTES);
}
file_put_contents($fn, $execOutput);
}
}
if ($show_output) {
print('</pre>');
print('</div>');
print('</div>');
}
}
/* Define a command, with a title, to be executed later. */
function defCmdT($title, $command, $method = "exec") {
global $commands;
$title = htmlspecialchars($title, ENT_NOQUOTES);
$commands[] = array($title, $command, $method);
}
/* List all of the commands as an index. */
function listCmds() {
global $currentDate;
global $commands;
$rubbish = array('|', '-', '/', '.', ' '); /* fixes the <a> tag to be W3C compliant */
print('<div class="panel panel-default">');
print('<div class="panel-heading"><h2 class="panel-title">' . sprintf(gettext("Firewall Status on %s"), $currentDate) . '</h2></div>');
print('<div class="panel-body">');
print(' <div class="content">');
print("\n<p>" . gettext("This status page includes the following information") . ":\n");
print("<ul>\n");
for ($i = 0; isset($commands[$i]); $i++) {
print("\t<li><strong><a href=\"#" . str_replace($rubbish, '', $commands[$i][0]) . "\">" . $commands[$i][0] . "</a></strong></li>\n");
}
print("</ul>\n");
print(' </div>');
print(' </div>');
print('</div>');
}
/* Execute all of the commands which were defined by a call to defCmd. */
function execCmds() {
global $commands;
for ($i = 0; isset($commands[$i]); $i++) {
doCmdT($commands[$i][0], $commands[$i][1], $commands[$i][2]);
}
}
function get_firewall_info() {
global $g, $output_path;
/* Firewall Platform/Serial */
$firewall_info = "Product Name: " . htmlspecialchars($g['product_name']);
$platform = system_identify_specific_platform();
if (!empty($platform['descr'])) {
$firewall_info .= "<br/>Platform: " . htmlspecialchars($platform['descr']);
}
if (file_exists('/var/db/uniqueid')) {
$ngid = file_get_contents('/var/db/uniqueid');
if (!empty($ngid)) {
$firewall_info .= "<br/>Netgate Device ID: " . htmlspecialchars($ngid);
}
}
if (function_exists("system_get_thothid") &&
(php_uname("m") == "arm64")) {
$thothid = system_get_thothid();
if (!empty($thothid)) {
$firewall_info .= "<br/>Netgate Crypto ID: " . htmlspecialchars(chop($thothid));
}
}
$serial = system_get_serial();
if (!empty($serial)) {
$firewall_info .= "<br/>Serial: " . htmlspecialchars($serial);
}
if (!empty($g['product_version_string'])) {
$firewall_info .= "<br/>" . htmlspecialchars($g['product_name']) .
" version: " . htmlspecialchars($g['product_version_string']);
}
if (file_exists('/etc/version.buildtime')) {
$build_time = file_get_contents('/etc/version.buildtime');
if (!empty($build_time)) {
$firewall_info .= "<br/>Built On: " . htmlspecialchars($build_time);
}
}
if (file_exists('/etc/version.lastcommit')) {
$build_commit = file_get_contents('/etc/version.lastcommit');
if (!empty($build_commit)) {
$firewall_info .= "<br/>Last Commit: " . htmlspecialchars($build_commit);
}
}
if (file_exists('/etc/version.gitsync')) {
$gitsync = file_get_contents('/etc/version.gitsync');
if (!empty($gitsync)) {
$firewall_info .= "<br/>A gitsync was performed at " .
date("D M j G:i:s T Y", filemtime('/etc/version.gitsync')) .
" to commit " . htmlspecialchars($gitsync);
}
}
file_put_contents("{$output_path}/Product-Info.txt", str_replace("<br/>", "\n", $firewall_info) . "\n");
return $firewall_info;
}
function get_gateway_status() {
return return_gateways_status_text(true, false);
}
global $g, $config;
/* Set up all of the commands we want to execute. */
/* OS stats/info */
if (function_exists("system_get_thothid") &&
(php_uname("m") == "arm64")) {
$thothid = system_get_thothid();
if (!empty($thothid)) {
defCmdT("Product-Public Key", "/usr/local/sbin/ping-auth -p");
}
}
defCmdT("OS-Uptime", "/usr/bin/uptime");
defCmdT("Network-Interfaces", "/sbin/ifconfig -vvvvvam");
defCmdT("Network-Interface Statistics", "/usr/bin/netstat -nWi");
defCmdT("Process-Top Usage", "/usr/bin/top | /usr/bin/head -n5");
defCmdT("Process-List", "/bin/ps xauwwd");
defCmdT("Disk-Mounted Filesystems", "/sbin/mount");
defCmdT("Disk-Free Space", "/bin/df -hi");
defCmdT("Network-Routing tables", "/usr/bin/netstat -nWr");
defCmdT("Network-Gateway Status", 'get_gateway_status', "php_func");
defCmdT("Network-Mbuf Usage", "/usr/bin/netstat -mb");
defCmdT("Network-Protocol Statistics", "/usr/bin/netstat -s");
defCmdT("Network-Buffer and Timer Statistics", "/usr/bin/netstat -nWx");
defCmdT("Network-Listen Queues", "/usr/bin/netstat -LaAn");
defCmdT("Network-Sockets", "/usr/bin/sockstat");
defCmdT("Network-ARP Table", "/usr/sbin/arp -an");
defCmdT("Network-NDP Table", "/usr/sbin/ndp -na");
defCmdT("OS-Kernel Modules", "/sbin/kldstat -v");
defCmdT("OS-Kernel VMStat", "/usr/bin/vmstat -afimsz");
/* If a device has a switch, put the switch configuration in the status output */
if (file_exists("/dev/etherswitch0")) {
defCmdT("Network-Switch Configuration", "/sbin/etherswitchcfg -f /dev/etherswitch0 info");
}
/* Firewall rules and info */
defCmdT("Firewall-Generated Ruleset", "/bin/cat {$g['tmp_path']}/rules.debug");
defCmdT("Firewall-Generated Ruleset Limiters", "/bin/cat {$g['tmp_path']}/rules.limiter");
defCmdT("Firewall-Generated Ruleset Limits", "/bin/cat {$g['tmp_path']}/rules.limits");
defCmdT("Firewall-pf NAT Rules", "/sbin/pfctl -vvsn");
defCmdT("Firewall-pf Firewall Rules", "/sbin/pfctl -vvsr");
defCmdT("Firewall-pf Tables", "/sbin/pfctl -vs Tables");
defCmdT("Firewall-pf State Table Contents", "/sbin/pfctl -vvss");
defCmdT("Firewall-pf Info", "/sbin/pfctl -si");
defCmdT("Firewall-pf Show All", "/sbin/pfctl -sa");
defCmdT("Firewall-pf Queues", "/sbin/pfctl -s queue -v");
defCmdT("Firewall-pf OSFP", "/sbin/pfctl -s osfp");
defCmdT("Firewall-pftop Default", "/usr/local/sbin/pftop -a -b");
defCmdT("Firewall-pftop Long", "/usr/local/sbin/pftop -w 150 -a -b -v long");
defCmdT("Firewall-pftop Queue", "/usr/local/sbin/pftop -w 150 -a -b -v queue");
defCmdT("Firewall-pftop Rules", "/usr/local/sbin/pftop -w 150 -a -b -v rules");
defCmdT("Firewall-pftop Size", "/usr/local/sbin/pftop -w 150 -a -b -v size");
defCmdT("Firewall-pftop Speed", "/usr/local/sbin/pftop -w 150 -a -b -v speed");
defCmdT("Firewall-IPFW Rules for Captive Portal", "/sbin/ipfw show");
defCmdT("Firewall-IPFW Limiter Info", "/sbin/ipfw pipe show");
defCmdT("Firewall-IPFW Queue Info", "/sbin/ipfw queue show");
defCmdT("Firewall-IPFW Tables", "/sbin/ipfw table all list");
/* Configuration Files */
defCmdT("Disk-Contents of var run", "/bin/ls /var/run");
defCmdT("Disk-Contents of conf", "/bin/ls /conf");
defCmdT("config.xml", "dumpconfigxml");
defCmdT("DNS-Resolution Configuration", "/bin/cat /etc/resolv.conf");
defCmdT("DNS-Resolver Access Lists", "/bin/cat /var/unbound/access_lists.conf");
defCmdT("DNS-Resolver Configuration", "/bin/cat /var/unbound/unbound.conf");
defCmdT("DNS-Resolver Domain Overrides", "/bin/cat /var/unbound/domainoverrides.conf");
defCmdT("DNS-Resolver Host Overrides", "/bin/cat /var/unbound/host_entries.conf");
defCmdT("DHCP-IPv4 Configuration", "/bin/cat /var/dhcpd/etc/dhcpd.conf");
defCmdT("DHCP-IPv6-Configuration", "/bin/cat /var/dhcpd/etc/dhcpdv6.conf");
defCmdT("IPsec-strongSwan Configuration", '/usr/bin/sed "s/\([[:blank:]]secret = \).*/\1<redacted>/" /var/etc/ipsec/strongswan.conf');
defCmdT("IPsec-Configuration", '/usr/bin/sed "s/\([[:blank:]]secret = \).*/\1<redacted>/" /var/etc/ipsec/swanctl.conf');
defCmdT("IPsec-Status-Statistics", "/usr/local/sbin/swanctl --stats --pretty");
defCmdT("IPsec-Status-Connections", "/usr/local/sbin/swanctl --list-conns");
defCmdT("IPsec-Status-Active SAs", "/usr/local/sbin/swanctl --list-sas");
defCmdT("IPsec-Status-Policies", "/usr/local/sbin/swanctl --list-pols");
defCmdT("IPsec-Status-Certificates", "/usr/local/sbin/swanctl --list-certs --utc");
defCmdT("IPsec-Status-Pools", "/usr/local/sbin/swanctl --list-pools --leases");
defCmdT("IPsec-SPD", "/sbin/setkey -DP");
defCmdT("IPsec-SAD", "/sbin/setkey -D");
if (file_exists("/cf/conf/upgrade_log.txt")) {
defCmdT("OS-Upgrade Log", "/bin/cat /cf/conf/upgrade_log.txt");
}
if (file_exists("/cf/conf/upgrade_log.latest.txt")) {
defCmdT("OS-Upgrade Log Latest", "/bin/cat /cf/conf/upgrade_log.latest.txt");
}
if (file_exists("/boot/loader.conf")) {
defCmdT("OS-Boot Loader Configuration", "/bin/cat /boot/loader.conf");
}
if (file_exists("/boot/loader.conf.local")) {
defCmdT("OS-Boot Loader Configuration (Local)", "/bin/cat /boot/loader.conf.local");
}
if (file_exists("/var/etc/filterdns.conf")) {
defCmdT("DNS-filterdns Daemon Configuration", "/bin/cat /var/etc/filterdns.conf");
}
if (is_dir("/var/etc/openvpn")) {
foreach(glob('/var/etc/openvpn/*/config.ovpn') as $file) {
$ovpnfile = explode('/', $file);
if (!count($ovpnfile) || (count($ovpnfile) < 6)) {
continue;
}
defCmdT("OpenVPN-Configuration {$ovpnfile[4]}", "/bin/cat " . escapeshellarg($file));
}
}
if (file_exists("/var/etc/l2tp-vpn/mpd.conf")) {
defCmdT("L2TP-Configuration", '/usr/bin/sed -E "s/([[:blank:]](secret|radius server .*) ).*/\1<redacted>/" /var/etc/l2tp-vpn/mpd.conf');
}
/* Config History */
$confvers = get_backups();
unset($confvers['versions']);
if (count($confvers) != 0) {
for ($c = count($confvers)-1; $c >= 0; $c--) {
$conf_history .= backup_info($confvers[$c], $c+1);
$conf_history .= "\n";
}
defCmdT("Config History", "echo " . escapeshellarg($conf_history));
}
/* Logs */
function status_add_log($name, $logfile, $number = 1000) {
if (!file_exists($logfile)) {
return;
}
$descr = "Log-{$name}";
$tail = '';
if ($number != "all") {
$descr .= "-Last {$number} entries";
$tail = ' | tail -n ' . escapeshellarg($number);
}
defCmdT($descr, system_log_get_cat() . ' ' . sort_related_log_files($logfile, true, true) . $tail);
}
status_add_log("System", '/var/log/system.log');
status_add_log("DHCP", '/var/log/dhcpd.log');
status_add_log("Filter", '/var/log/filter.log');
status_add_log("Gateways", '/var/log/gateways.log');
status_add_log("IPsec", '/var/log/ipsec.log');
status_add_log("L2TP", '/var/log/l2tps.log');
status_add_log("NTP", '/var/log/ntpd.log');
status_add_log("OpenVPN", '/var/log/openvpn.log');
status_add_log("Captive Portal Authentication", '/var/log/portalauth.log');
status_add_log("PPP", '/var/log/ppp.log');
status_add_log("PPPoE Server", '/var/log/poes.log');
status_add_log("DNS", '/var/log/resolver.log');
status_add_log("Routing", '/var/log/routing.log');
status_add_log("Wireless", '/var/log/wireless.log');
status_add_log("PHP Errors", '/tmp/PHP_errors.log', 'all');
defCmdT("OS-Message Buffer", "/sbin/dmesg -a");
defCmdT("OS-Message Buffer (Boot)", "/bin/cat /var/log/dmesg.boot");
/* OS/Hardware Status */
defCmdT("OS-sysctl values", "/sbin/sysctl -aq");
defCmdT("OS-Kernel Environment", "/bin/kenv");
defCmdT("OS-Kernel Memory Usage", "/usr/local/sbin/kmemusage.sh");
defCmdT("OS-Installed Packages", "/usr/local/sbin/pkg-static info");
defCmdT("OS-Package Manager Configuration", "/usr/local/sbin/pkg-static -vv");
defCmdT("Hardware-PCI Devices", "/usr/sbin/pciconf -lvb");
defCmdT("Hardware-USB Devices", "/usr/sbin/usbconfig dump_device_desc");
if (is_module_loaded("zfs.ko")) {
defCmdT("Disk-ZFS List", "/sbin/zfs list");
defCmdT("Disk-ZFS Properties", "/sbin/zfs get all");
defCmdT("Disk-ZFS Pool List", "/sbin/zpool list");
defCmdT("Disk-ZFS Pool Status", "/sbin/zpool status");
}
defCmdT("Disk-GEOM Mirror Status", "/sbin/gmirror status");
exec("/bin/date", $dateOutput, $dateStatus);
$currentDate = $dateOutput[0];
$pgtitle = array($g['product_name'], "Status");
if (!$console):
include("head.inc"); ?>
<form action="status.php" method="post">
<?php print_info_box(
gettext("Make sure all sensitive information is removed! (Passwords, etc.) before posting information from this page in public places such as forum or social media sites.") .
'<br />' .
gettext("Common password and other private fields in config.xml have been automatically redacted.") .
'<br />' .
sprintf(gettext('When the page has finished loading, the output is stored in %1$s. It may be downloaded via scp or using this button: '), $output_file) .
' <button name="submit" type="submit" class="btn btn-primary btn-sm" id="download" value="DOWNLOAD">' .
'<i class="fa fa-download icon-embed-btn"></i>' .
gettext("Download") .
'</button>'); ?>
</form>
<?php print_info_box(get_firewall_info(), 'info', false);
if ($show_output) {
listCmds();
} else {
print_info_box(gettext("Status output suppressed. Download archive to view."), 'info', false);
}
endif;
if ($console) {
print(gettext("Gathering status data...") . "\n");
get_firewall_info();
}
execCmds();
print(gettext("Saving output to archive..."));
if (is_dir($output_path)) {
mwexec("/usr/bin/tar czpf " . escapeshellarg($output_file) . " -C " . escapeshellarg(dirname($output_path)) . " " . escapeshellarg(basename($output_path)));
if (!isset($_GET["nocleanup"])) {
unlink_if_exists("{$output_path}/*");
@rmdir($output_path);
}
}
print(gettext("Done.") . "\n");
if (!$console) {
include("foot.inc");
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2013 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.
#include <string>
#ifndef __GLIBCXX__
#error expected std library: libstdc++
#endif
int main() { return 0; }
| {
"pile_set_name": "Github"
} |
import sys
if sys.version_info[:2] < (2, 7): # pragma: no cover
import unittest2 as unittest
else:
import unittest
try:
from unittest import mock
except ImportError:
import mock
# flake8: noqa
| {
"pile_set_name": "Github"
} |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// TODO(jba): test that OnError is getting called appropriately.
package logging_test
import (
"flag"
"fmt"
"log"
"os"
"strings"
"testing"
"time"
gax "github.com/googleapis/gax-go"
cinternal "cloud.google.com/go/internal"
"cloud.google.com/go/internal/testutil"
"cloud.google.com/go/logging"
ltesting "cloud.google.com/go/logging/internal/testing"
"cloud.google.com/go/logging/logadmin"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
mrpb "google.golang.org/genproto/googleapis/api/monitoredres"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const testLogIDPrefix = "GO-LOGGING-CLIENT/TEST-LOG"
var uids = testutil.NewUIDSpace(testLogIDPrefix)
var (
client *logging.Client
aclient *logadmin.Client
testProjectID string
testLogID string
testFilter string
errorc chan error
ctx context.Context
// Adjust the fields of a FullEntry received from the production service
// before comparing it with the expected result. We can't correctly
// compare certain fields, like times or server-generated IDs.
clean func(*logging.Entry)
// Create a new client with the given project ID.
newClients func(ctx context.Context, projectID string) (*logging.Client, *logadmin.Client)
)
func testNow() time.Time {
return time.Unix(1000, 0)
}
// If true, this test is using the production service, not a fake.
var integrationTest bool
func TestMain(m *testing.M) {
flag.Parse() // needed for testing.Short()
ctx = context.Background()
testProjectID = testutil.ProjID()
errorc = make(chan error, 100)
if testProjectID == "" || testing.Short() {
integrationTest = false
if testProjectID != "" {
log.Print("Integration tests skipped in short mode (using fake instead)")
}
testProjectID = "PROJECT_ID"
clean = func(e *logging.Entry) {
// Remove the insert ID for consistency with the integration test.
e.InsertID = ""
}
addr, err := ltesting.NewServer()
if err != nil {
log.Fatalf("creating fake server: %v", err)
}
logging.SetNow(testNow)
newClients = func(ctx context.Context, parent string) (*logging.Client, *logadmin.Client) {
conn, err := grpc.Dial(addr, grpc.WithInsecure())
if err != nil {
log.Fatalf("dialing %q: %v", addr, err)
}
c, err := logging.NewClient(ctx, parent, option.WithGRPCConn(conn))
if err != nil {
log.Fatalf("creating client for fake at %q: %v", addr, err)
}
ac, err := logadmin.NewClient(ctx, parent, option.WithGRPCConn(conn))
if err != nil {
log.Fatalf("creating client for fake at %q: %v", addr, err)
}
return c, ac
}
} else {
integrationTest = true
clean = func(e *logging.Entry) {
// We cannot compare timestamps, so set them to the test time.
// Also, remove the insert ID added by the service.
e.Timestamp = testNow().UTC()
e.InsertID = ""
}
ts := testutil.TokenSource(ctx, logging.AdminScope)
if ts == nil {
log.Fatal("The project key must be set. See CONTRIBUTING.md for details")
}
log.Printf("running integration tests with project %s", testProjectID)
newClients = func(ctx context.Context, parent string) (*logging.Client, *logadmin.Client) {
c, err := logging.NewClient(ctx, parent, option.WithTokenSource(ts))
if err != nil {
log.Fatalf("creating prod client: %v", err)
}
ac, err := logadmin.NewClient(ctx, parent, option.WithTokenSource(ts))
if err != nil {
log.Fatalf("creating prod client: %v", err)
}
return c, ac
}
}
client, aclient = newClients(ctx, testProjectID)
client.OnError = func(e error) { errorc <- e }
exit := m.Run()
client.Close()
os.Exit(exit)
}
func initLogs(ctx context.Context) {
testLogID = uids.New()
testFilter = fmt.Sprintf(`logName = "projects/%s/logs/%s"`, testProjectID,
strings.Replace(testLogID, "/", "%2F", -1))
}
// Testing of Logger.Log is done in logadmin_test.go, TestEntries.
func TestLogSync(t *testing.T) {
initLogs(ctx) // Generate new testLogID
ctx := context.Background()
lg := client.Logger(testLogID)
err := lg.LogSync(ctx, logging.Entry{Payload: "hello"})
if err != nil {
t.Fatal(err)
}
err = lg.LogSync(ctx, logging.Entry{Payload: "goodbye"})
if err != nil {
t.Fatal(err)
}
// Allow overriding the MonitoredResource.
err = lg.LogSync(ctx, logging.Entry{Payload: "mr", Resource: &mrpb.MonitoredResource{Type: "global"}})
if err != nil {
t.Fatal(err)
}
want := []*logging.Entry{
entryForTesting("hello"),
entryForTesting("goodbye"),
entryForTesting("mr"),
}
var got []*logging.Entry
ok := waitFor(func() bool {
got, err = allTestLogEntries(ctx)
if err != nil {
t.Log("fetching log entries: ", err)
return false
}
return len(got) == len(want)
})
if !ok {
t.Fatalf("timed out; got: %d, want: %d\n", len(got), len(want))
}
if msg, ok := compareEntries(got, want); !ok {
t.Error(msg)
}
}
func TestLogAndEntries(t *testing.T) {
initLogs(ctx) // Generate new testLogID
ctx := context.Background()
payloads := []string{"p1", "p2", "p3", "p4", "p5"}
lg := client.Logger(testLogID)
for _, p := range payloads {
// Use the insert ID to guarantee iteration order.
lg.Log(logging.Entry{Payload: p, InsertID: p})
}
lg.Flush()
var want []*logging.Entry
for _, p := range payloads {
want = append(want, entryForTesting(p))
}
var got []*logging.Entry
ok := waitFor(func() bool {
var err error
got, err = allTestLogEntries(ctx)
if err != nil {
t.Log("fetching log entries: ", err)
return false
}
return len(got) == len(want)
})
if !ok {
t.Fatalf("timed out; got: %d, want: %d\n", len(got), len(want))
}
if msg, ok := compareEntries(got, want); !ok {
t.Error(msg)
}
}
// compareEntries compares most fields list of Entries against expected. compareEntries does not compare:
// - HTTPRequest
// - Operation
// - Resource
func compareEntries(got, want []*logging.Entry) (string, bool) {
if len(got) != len(want) {
return fmt.Sprintf("got %d entries, want %d", len(got), len(want)), false
}
for i := range got {
if !compareEntry(got[i], want[i]) {
return fmt.Sprintf("#%d:\ngot %+v\nwant %+v", i, got[i], want[i]), false
}
}
return "", true
}
func compareEntry(got, want *logging.Entry) bool {
if got.Timestamp.Unix() != want.Timestamp.Unix() {
return false
}
if got.Severity != want.Severity {
return false
}
if !ltesting.PayloadEqual(got.Payload, want.Payload) {
return false
}
if !testutil.Equal(got.Labels, want.Labels) {
return false
}
if got.InsertID != want.InsertID {
return false
}
if got.LogName != want.LogName {
return false
}
return true
}
func entryForTesting(payload interface{}) *logging.Entry {
return &logging.Entry{
Timestamp: testNow().UTC(),
Payload: payload,
LogName: "projects/" + testProjectID + "/logs/" + testLogID,
Resource: &mrpb.MonitoredResource{Type: "global", Labels: map[string]string{"project_id": testProjectID}},
}
}
func countLogEntries(ctx context.Context, filter string) int {
it := aclient.Entries(ctx, logadmin.Filter(filter))
n := 0
for {
_, err := it.Next()
if err == iterator.Done {
return n
}
if err != nil {
log.Fatalf("counting log entries: %v", err)
}
n++
}
}
func allTestLogEntries(ctx context.Context) ([]*logging.Entry, error) {
return allEntries(ctx, aclient, testFilter)
}
func allEntries(ctx context.Context, aclient *logadmin.Client, filter string) ([]*logging.Entry, error) {
var es []*logging.Entry
it := aclient.Entries(ctx, logadmin.Filter(filter))
for {
e, err := cleanNext(it)
switch err {
case nil:
es = append(es, e)
case iterator.Done:
return es, nil
default:
return nil, err
}
}
}
func cleanNext(it *logadmin.EntryIterator) (*logging.Entry, error) {
e, err := it.Next()
if err != nil {
return nil, err
}
clean(e)
return e, nil
}
func TestStandardLogger(t *testing.T) {
initLogs(ctx) // Generate new testLogID
ctx := context.Background()
lg := client.Logger(testLogID)
slg := lg.StandardLogger(logging.Info)
if slg != lg.StandardLogger(logging.Info) {
t.Error("There should be only one standard logger at each severity.")
}
if slg == lg.StandardLogger(logging.Debug) {
t.Error("There should be a different standard logger for each severity.")
}
slg.Print("info")
lg.Flush()
var got []*logging.Entry
ok := waitFor(func() bool {
var err error
got, err = allTestLogEntries(ctx)
if err != nil {
t.Log("fetching log entries: ", err)
return false
}
return len(got) == 1
})
if !ok {
t.Fatalf("timed out; got: %d, want: %d\n", len(got), 1)
}
if len(got) != 1 {
t.Fatalf("expected non-nil request with one entry; got:\n%+v", got)
}
if got, want := got[0].Payload.(string), "info\n"; got != want {
t.Errorf("payload: got %q, want %q", got, want)
}
if got, want := logging.Severity(got[0].Severity), logging.Info; got != want {
t.Errorf("severity: got %s, want %s", got, want)
}
}
func TestSeverity(t *testing.T) {
if got, want := logging.Info.String(), "Info"; got != want {
t.Errorf("got %q, want %q", got, want)
}
if got, want := logging.Severity(-99).String(), "-99"; got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestParseSeverity(t *testing.T) {
for _, test := range []struct {
in string
want logging.Severity
}{
{"", logging.Default},
{"whatever", logging.Default},
{"Default", logging.Default},
{"ERROR", logging.Error},
{"Error", logging.Error},
{"error", logging.Error},
} {
got := logging.ParseSeverity(test.in)
if got != test.want {
t.Errorf("%q: got %s, want %s\n", test.in, got, test.want)
}
}
}
func TestErrors(t *testing.T) {
initLogs(ctx) // Generate new testLogID
// Drain errors already seen.
loop:
for {
select {
case <-errorc:
default:
break loop
}
}
// Try to log something that can't be JSON-marshalled.
lg := client.Logger(testLogID)
lg.Log(logging.Entry{Payload: func() {}})
// Expect an error from Flush.
err := lg.Flush()
if err == nil {
t.Fatal("expected error, got nil")
}
}
type badTokenSource struct{}
func (badTokenSource) Token() (*oauth2.Token, error) {
return &oauth2.Token{}, nil
}
func TestPing(t *testing.T) {
// Ping twice, in case the service's InsertID logic messes with the error code.
ctx := context.Background()
// The global client should be valid.
if err := client.Ping(ctx); err != nil {
t.Errorf("project %s: got %v, expected nil", testProjectID, err)
}
if err := client.Ping(ctx); err != nil {
t.Errorf("project %s, #2: got %v, expected nil", testProjectID, err)
}
// nonexistent project
c, _ := newClients(ctx, testProjectID+"-BAD")
if err := c.Ping(ctx); err == nil {
t.Errorf("nonexistent project: want error pinging logging api, got nil")
}
if err := c.Ping(ctx); err == nil {
t.Errorf("nonexistent project, #2: want error pinging logging api, got nil")
}
// Bad creds. We cannot test this with the fake, since it doesn't do auth.
if integrationTest {
c, err := logging.NewClient(ctx, testProjectID, option.WithTokenSource(badTokenSource{}))
if err != nil {
t.Fatal(err)
}
if err := c.Ping(ctx); err == nil {
t.Errorf("bad creds: want error pinging logging api, got nil")
}
if err := c.Ping(ctx); err == nil {
t.Errorf("bad creds, #2: want error pinging logging api, got nil")
}
if err := c.Close(); err != nil {
t.Fatalf("error closing client: %v", err)
}
}
}
func TestLogsAndDelete(t *testing.T) {
// This function tests both the Logs and DeleteLog methods. We only try to
// delete those logs that we can observe and that were generated by this
// test. This may not include the logs generated from the current test run,
// because the logging service is only eventually consistent. It's
// therefore possible that on some runs, this test will do nothing.
ctx := context.Background()
it := aclient.Logs(ctx)
nDeleted := 0
for {
logID, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
t.Fatal(err)
}
if strings.HasPrefix(logID, testLogIDPrefix) {
if err := aclient.DeleteLog(ctx, logID); err != nil {
t.Fatalf("deleting %q: %v", logID, err)
}
nDeleted++
}
}
t.Logf("deleted %d logs", nDeleted)
}
func TestNonProjectParent(t *testing.T) {
ctx := context.Background()
initLogs(ctx)
const orgID = "433637338589" // org ID for google.com
parent := "organizations/" + orgID
c, a := newClients(ctx, parent)
lg := c.Logger(testLogID)
err := lg.LogSync(ctx, logging.Entry{Payload: "hello"})
if integrationTest {
// We don't have permission to log to the organization.
if got, want := status.Code(err), codes.PermissionDenied; got != want {
t.Errorf("got code %s, want %s", got, want)
}
return
}
// Continue test against fake.
if err != nil {
t.Fatal(err)
}
want := []*logging.Entry{{
Timestamp: testNow().UTC(),
Payload: "hello",
LogName: parent + "/logs/" + testLogID,
Resource: &mrpb.MonitoredResource{
Type: "organization",
Labels: map[string]string{"organization_id": orgID},
},
}}
var got []*logging.Entry
ok := waitFor(func() bool {
got, err = allEntries(ctx, a, fmt.Sprintf(`logName = "%s/logs/%s"`, parent,
strings.Replace(testLogID, "/", "%2F", -1)))
if err != nil {
t.Log("fetching log entries: ", err)
return false
}
return len(got) == len(want)
})
if !ok {
t.Fatalf("timed out; got: %d, want: %d\n", len(got), len(want))
}
if msg, ok := compareEntries(got, want); !ok {
t.Error(msg)
}
}
// waitFor calls f repeatedly with exponential backoff, blocking until it returns true.
// It returns false after a while (if it times out).
func waitFor(f func() bool) bool {
// TODO(shadams): Find a better way to deflake these tests.
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
err := cinternal.Retry(ctx,
gax.Backoff{Initial: time.Second, Multiplier: 2},
func() (bool, error) { return f(), nil })
return err == nil
}
| {
"pile_set_name": "Github"
} |
---
# This file is licensed under the MIT License (MIT) available on
# http://opensource.org/licenses/MIT.
type: posts
layout: post
category: blog
title: "A New Design for Wallet Pages"
permalink: /en/posts/new-design-for-wallet-pages.html
date: 2019-09-24
author: |
<a href="https://github.com/wbnns">Will Binns</a>
---
A new, more user-friendly and simple set of pages designed to help people find
an ideal bitcoin wallet is now available. It includes a step-by-step wizard to
help people become more familiar with wallets, ratings to compare how they stack
up alongside other wallets, as well as explanations of features they provide
in order to help people make their own informed decisions. Aside from the
wizard, a completely new comparative table and selector is available so people
can see how wallets fare against one another. This is designed to help
people quickly find a wallet to meet their needs.
[Check out the new wallet pages and curate your own list of
wallets.](https://bitcoin.org/en/choose-your-wallet)
## The Old Design
While the old wallet pages presented an assortment of wallets people could
choose from, the experience of doing so was cumbersome and tedious. In order to
see how wallets were rated one would need to navigate to each individual wallet
and then browse back to the overview page to select another wallet to see how
the two might compare. It was not possible to see these comparisons side by
side. One would need to use multiple tabs or browser windows and toggle back and
forth, or a single window, navigating backward and forward.
In addition to the comparative difficulties, millions of people visit
bitcoin.org, many of whom are new to Bitcoin, and have little to no familiarity
with how it works. This is further complicated when a person needs to choose a
bitcoin wallet and has no idea what makes one an optimal choice, what the
features are and what they do, or what they need.
The new design resolves these issues by allowing people to easily compare
wallets, see how they're rated and subsequently generate a list of wallets based
on available features - in addition to explaining things each step along the
way.
## Wallet Ratings
Wallets are given one of four ratings - good, acceptable, caution or neutral.
These ratings are applied across six categories:
+ **Control:** Some wallets give you full control over your bitcoin. This means
no third party can freeze or take away your funds. You are still responsible,
however, for securing and backing up your wallet.
+ **Validation:** Some wallets have the ability to operate as a full node. This
means no trust in a third party is required when processing transactions. Full
nodes provide a high level of security, but they require a large amount of
memory.
+ **Transparency:** Some wallets are open-source and can be built
deterministically, a process of compiling software which ensures the resulting
code can be reproduced to help ensure it hasn't been tampered with.
+ **Environment:** Some wallets can be loaded on computers which are vulnerable
to malware. Securing your computer, using a strong passphrase, moving most of
your funds to cold store or enabling 2FA or multifactor authentication can help
you protect your bitcoin.
+ **Privacy:** Some wallets make it harder to spy on your transactions by
rotating addresses. They do not disclose information to peers on the network.
They can also optionally let you setup and use Tor as a proxy to prevent others
from associating transactions with your IP address.
+ **Fees:** Some wallets give you full control over setting the fee paid to the
bitcoin network before making a transaction, or modifying it afterward, to
ensure that your transactions are confirmed in a timely manner without paying
more than you have to.
These ratings are available to review both on the overview page that includes
all wallets, as well as the individual landing pages for each wallet.
## Wallet Features
There are nine features people can choose from to sort wallets by. These
features are:
+ **2FA:** Two-factor authentication (2FA) is a way to add additional security
to your wallet. The first 'factor' is your password for your wallet. The
second 'factor' is a verification code retrieved via text message or from an app
on a mobile device. 2FA is conceptually similar to a security token device that
banks in some countries require for online banking. It likely requires relying
on the availability of a third party to provide the service.
+ **Bech32:** Bech32 is a special address format made possible by SegWit (see
the feature description for SegWit for more info). This address format is also
known as 'bc1 addresses'. Some bitcoin wallets and services do not yet support
sending or receiving to Bech32 addresses.
+ **Full Node:** Some wallets fully validate transactions and blocks. Almost all
full nodes help the network by accepting transactions and blocks from other
full nodes, validating those transactions and blocks, and then relaying them to
further full nodes.
+ **Hardware Wallet Compatibility:** Some wallets can pair and connect to a
hardware wallet in addition to being able to send to them. While sending to a
hardware wallet is something most all wallets can do, being able to pair with
one is a unique feature. This feature enables you to be able to send and receive
directly to and from a hardware wallet.
+ **Legacy Addresses:** Most wallets have the ability to send and receive legacy
bitcoin addresses. Legacy addresses start with 1 or 3 (as opposed to starting
with bc1). Without legacy address support you may not be able to receive bitcoin
from older wallets or exchanges.
+ **Lightning:** Some wallets support transactions on the Lightning Network. The
Lightning Network is new and somewhat experimental. It supports transferring
bitcoin without having to record each transaction on the blockchain, resulting
in faster transactions and lower fees.
+ **Multisig:** Some wallets have the ability to require more than one key to
authorize a transaction. This can be used to divide responsibility and control
over multiple parties.
+ **SegWit:** Some wallets support SegWit, which uses block chain space more
efficiently. This helps reduce fees paid by helping the Bitcoin network scale
and sets the foundation for second layer solutions such as the Lightning
Network.
People can select features that are important to them alongside the ratings
described above, based on their operating system and/or environment.
## Acknowledgments
The new wallet page improvements wouldn't have been possible without donations
from the community, as well as community feedback that we received as various
milestones were passed and presented along the way. A special thanks is also
due to several people who spent a significant amount of their personal time on
this project - Craig Watkins, Cøbra, Natalia Kirejczyk, Alex Cherman, and
Maxwell Mons. Lastly, we appreciate the efforts of many contributors that spent
time reporting issues on GitHub with regard to both the old and new design, that
we were able to resolve as part of this work:
+ [1986](https://github.com/bitcoin-dot-org/bitcoin.org/issues/1986)
+ [2723](https://github.com/bitcoin-dot-org/bitcoin.org/issues/2723)
+ [2861](https://github.com/bitcoin-dot-org/bitcoin.org/issues/2861)
+ [2892](https://github.com/bitcoin-dot-org/bitcoin.org/issues/2892)
+ [3020](https://github.com/bitcoin-dot-org/bitcoin.org/issues/3020)
+ [3022](https://github.com/bitcoin-dot-org/bitcoin.org/issues/3022)
+ [3023](https://github.com/bitcoin-dot-org/bitcoin.org/issues/3023)
+ [3032](https://github.com/bitcoin-dot-org/bitcoin.org/issues/3032)
+ [3051](https://github.com/bitcoin-dot-org/bitcoin.org/issues/3051)
## Adding a Wallet
For people who would like to submit a wallet that isn't listed on the site for
potential inclusion, [documentation is
available](https://github.com/bitcoin-dot-org/bitcoin.org/blob/master/docs/managing-wallets.md)
for review.
## Feedback
If you have any feedback on the new wallet pages, ideas on how they can be made
better, or if you've encountered a problem, please let us know by [opening an
issue on GitHub](https://github.com/bitcoin-dot-org/bitcoin.org/issues/new).
## About bitcoin.org
Bitcoin.org was originally registered and owned by Satoshi Nakamoto and Martti
Malmi. When Satoshi left the project, he gave ownership of the domain to
additional people, separate from the Bitcoin developers, to spread
responsibility and prevent any one person or group from easily gaining control
over the Bitcoin project. Since then, the site has been developed and maintained
by different members of the Bitcoin community.
Despite being a privately owned site, its code is open-source and there have
been thousands of commits from hundreds of contributors from all over the world.
In addition to this, over a thousand translators have helped to make the site
display natively to visitors in their own languages — now 25 different languages
and growing.
Bitcoin.org receives millions of visitors a year from people all over the world
who want to get started with and learn more about Bitcoin.
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <linux/pci.h>
#include "amdgpu.h"
#include "amdgpu_ih.h"
#include "soc15.h"
#include "oss/osssys_4_0_offset.h"
#include "oss/osssys_4_0_sh_mask.h"
#include "soc15_common.h"
#include "vega10_ih.h"
#define MAX_REARM_RETRY 10
static void vega10_ih_set_interrupt_funcs(struct amdgpu_device *adev);
/**
* vega10_ih_enable_interrupts - Enable the interrupt ring buffer
*
* @adev: amdgpu_device pointer
*
* Enable the interrupt ring buffer (VEGA10).
*/
static void vega10_ih_enable_interrupts(struct amdgpu_device *adev)
{
u32 ih_rb_cntl = RREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL, RB_ENABLE, 1);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL, ENABLE_INTR, 1);
if (amdgpu_sriov_vf(adev)) {
if (psp_reg_program(&adev->psp, PSP_REG_IH_RB_CNTL, ih_rb_cntl)) {
DRM_ERROR("PSP program IH_RB_CNTL failed!\n");
return;
}
} else {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL, ih_rb_cntl);
}
adev->irq.ih.enabled = true;
if (adev->irq.ih1.ring_size) {
ih_rb_cntl = RREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL_RING1);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL_RING1,
RB_ENABLE, 1);
if (amdgpu_sriov_vf(adev)) {
if (psp_reg_program(&adev->psp, PSP_REG_IH_RB_CNTL_RING1,
ih_rb_cntl)) {
DRM_ERROR("program IH_RB_CNTL_RING1 failed!\n");
return;
}
} else {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL_RING1, ih_rb_cntl);
}
adev->irq.ih1.enabled = true;
}
if (adev->irq.ih2.ring_size) {
ih_rb_cntl = RREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL_RING2);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL_RING2,
RB_ENABLE, 1);
if (amdgpu_sriov_vf(adev)) {
if (psp_reg_program(&adev->psp, PSP_REG_IH_RB_CNTL_RING2,
ih_rb_cntl)) {
DRM_ERROR("program IH_RB_CNTL_RING2 failed!\n");
return;
}
} else {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL_RING2, ih_rb_cntl);
}
adev->irq.ih2.enabled = true;
}
}
/**
* vega10_ih_disable_interrupts - Disable the interrupt ring buffer
*
* @adev: amdgpu_device pointer
*
* Disable the interrupt ring buffer (VEGA10).
*/
static void vega10_ih_disable_interrupts(struct amdgpu_device *adev)
{
u32 ih_rb_cntl = RREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL, RB_ENABLE, 0);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL, ENABLE_INTR, 0);
if (amdgpu_sriov_vf(adev)) {
if (psp_reg_program(&adev->psp, PSP_REG_IH_RB_CNTL, ih_rb_cntl)) {
DRM_ERROR("PSP program IH_RB_CNTL failed!\n");
return;
}
} else {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL, ih_rb_cntl);
}
/* set rptr, wptr to 0 */
WREG32_SOC15(OSSSYS, 0, mmIH_RB_RPTR, 0);
WREG32_SOC15(OSSSYS, 0, mmIH_RB_WPTR, 0);
adev->irq.ih.enabled = false;
adev->irq.ih.rptr = 0;
if (adev->irq.ih1.ring_size) {
ih_rb_cntl = RREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL_RING1);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL_RING1,
RB_ENABLE, 0);
if (amdgpu_sriov_vf(adev)) {
if (psp_reg_program(&adev->psp, PSP_REG_IH_RB_CNTL_RING1,
ih_rb_cntl)) {
DRM_ERROR("program IH_RB_CNTL_RING1 failed!\n");
return;
}
} else {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL_RING1, ih_rb_cntl);
}
/* set rptr, wptr to 0 */
WREG32_SOC15(OSSSYS, 0, mmIH_RB_RPTR_RING1, 0);
WREG32_SOC15(OSSSYS, 0, mmIH_RB_WPTR_RING1, 0);
adev->irq.ih1.enabled = false;
adev->irq.ih1.rptr = 0;
}
if (adev->irq.ih2.ring_size) {
ih_rb_cntl = RREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL_RING2);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL_RING2,
RB_ENABLE, 0);
if (amdgpu_sriov_vf(adev)) {
if (psp_reg_program(&adev->psp, PSP_REG_IH_RB_CNTL_RING2,
ih_rb_cntl)) {
DRM_ERROR("program IH_RB_CNTL_RING2 failed!\n");
return;
}
} else {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL_RING2, ih_rb_cntl);
}
/* set rptr, wptr to 0 */
WREG32_SOC15(OSSSYS, 0, mmIH_RB_RPTR_RING2, 0);
WREG32_SOC15(OSSSYS, 0, mmIH_RB_WPTR_RING2, 0);
adev->irq.ih2.enabled = false;
adev->irq.ih2.rptr = 0;
}
}
static uint32_t vega10_ih_rb_cntl(struct amdgpu_ih_ring *ih, uint32_t ih_rb_cntl)
{
int rb_bufsz = order_base_2(ih->ring_size / 4);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL,
MC_SPACE, ih->use_bus_addr ? 1 : 4);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL,
WPTR_OVERFLOW_CLEAR, 1);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL,
WPTR_OVERFLOW_ENABLE, 1);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL, RB_SIZE, rb_bufsz);
/* Ring Buffer write pointer writeback. If enabled, IH_RB_WPTR register
* value is written to memory
*/
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL,
WPTR_WRITEBACK_ENABLE, 1);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL, MC_SNOOP, 1);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL, MC_RO, 0);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL, MC_VMID, 0);
return ih_rb_cntl;
}
static uint32_t vega10_ih_doorbell_rptr(struct amdgpu_ih_ring *ih)
{
u32 ih_doorbell_rtpr = 0;
if (ih->use_doorbell) {
ih_doorbell_rtpr = REG_SET_FIELD(ih_doorbell_rtpr,
IH_DOORBELL_RPTR, OFFSET,
ih->doorbell_index);
ih_doorbell_rtpr = REG_SET_FIELD(ih_doorbell_rtpr,
IH_DOORBELL_RPTR,
ENABLE, 1);
} else {
ih_doorbell_rtpr = REG_SET_FIELD(ih_doorbell_rtpr,
IH_DOORBELL_RPTR,
ENABLE, 0);
}
return ih_doorbell_rtpr;
}
/**
* vega10_ih_irq_init - init and enable the interrupt ring
*
* @adev: amdgpu_device pointer
*
* Allocate a ring buffer for the interrupt controller,
* enable the RLC, disable interrupts, enable the IH
* ring buffer and enable it (VI).
* Called at device load and reume.
* Returns 0 for success, errors for failure.
*/
static int vega10_ih_irq_init(struct amdgpu_device *adev)
{
struct amdgpu_ih_ring *ih;
u32 ih_rb_cntl, ih_chicken;
int ret = 0;
u32 tmp;
/* disable irqs */
vega10_ih_disable_interrupts(adev);
adev->nbio.funcs->ih_control(adev);
ih = &adev->irq.ih;
/* Ring Buffer base. [39:8] of 40-bit address of the beginning of the ring buffer*/
WREG32_SOC15(OSSSYS, 0, mmIH_RB_BASE, ih->gpu_addr >> 8);
WREG32_SOC15(OSSSYS, 0, mmIH_RB_BASE_HI, (ih->gpu_addr >> 40) & 0xff);
ih_rb_cntl = RREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL);
ih_rb_cntl = vega10_ih_rb_cntl(ih, ih_rb_cntl);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL, RPTR_REARM,
!!adev->irq.msi_enabled);
if (amdgpu_sriov_vf(adev)) {
if (psp_reg_program(&adev->psp, PSP_REG_IH_RB_CNTL, ih_rb_cntl)) {
DRM_ERROR("PSP program IH_RB_CNTL failed!\n");
return -ETIMEDOUT;
}
} else {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL, ih_rb_cntl);
}
if ((adev->asic_type == CHIP_ARCTURUS &&
adev->firmware.load_type == AMDGPU_FW_LOAD_DIRECT) ||
adev->asic_type == CHIP_RENOIR) {
ih_chicken = RREG32_SOC15(OSSSYS, 0, mmIH_CHICKEN);
if (adev->irq.ih.use_bus_addr) {
ih_chicken = REG_SET_FIELD(ih_chicken, IH_CHICKEN,
MC_SPACE_GPA_ENABLE, 1);
} else {
ih_chicken = REG_SET_FIELD(ih_chicken, IH_CHICKEN,
MC_SPACE_FBPA_ENABLE, 1);
}
WREG32_SOC15(OSSSYS, 0, mmIH_CHICKEN, ih_chicken);
}
/* set the writeback address whether it's enabled or not */
WREG32_SOC15(OSSSYS, 0, mmIH_RB_WPTR_ADDR_LO,
lower_32_bits(ih->wptr_addr));
WREG32_SOC15(OSSSYS, 0, mmIH_RB_WPTR_ADDR_HI,
upper_32_bits(ih->wptr_addr) & 0xFFFF);
/* set rptr, wptr to 0 */
WREG32_SOC15(OSSSYS, 0, mmIH_RB_WPTR, 0);
WREG32_SOC15(OSSSYS, 0, mmIH_RB_RPTR, 0);
WREG32_SOC15(OSSSYS, 0, mmIH_DOORBELL_RPTR,
vega10_ih_doorbell_rptr(ih));
ih = &adev->irq.ih1;
if (ih->ring_size) {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_BASE_RING1, ih->gpu_addr >> 8);
WREG32_SOC15(OSSSYS, 0, mmIH_RB_BASE_HI_RING1,
(ih->gpu_addr >> 40) & 0xff);
ih_rb_cntl = RREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL_RING1);
ih_rb_cntl = vega10_ih_rb_cntl(ih, ih_rb_cntl);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL,
WPTR_OVERFLOW_ENABLE, 0);
ih_rb_cntl = REG_SET_FIELD(ih_rb_cntl, IH_RB_CNTL,
RB_FULL_DRAIN_ENABLE, 1);
if (amdgpu_sriov_vf(adev)) {
if (psp_reg_program(&adev->psp, PSP_REG_IH_RB_CNTL_RING1,
ih_rb_cntl)) {
DRM_ERROR("program IH_RB_CNTL_RING1 failed!\n");
return -ETIMEDOUT;
}
} else {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL_RING1, ih_rb_cntl);
}
/* set rptr, wptr to 0 */
WREG32_SOC15(OSSSYS, 0, mmIH_RB_WPTR_RING1, 0);
WREG32_SOC15(OSSSYS, 0, mmIH_RB_RPTR_RING1, 0);
WREG32_SOC15(OSSSYS, 0, mmIH_DOORBELL_RPTR_RING1,
vega10_ih_doorbell_rptr(ih));
}
ih = &adev->irq.ih2;
if (ih->ring_size) {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_BASE_RING2, ih->gpu_addr >> 8);
WREG32_SOC15(OSSSYS, 0, mmIH_RB_BASE_HI_RING2,
(ih->gpu_addr >> 40) & 0xff);
ih_rb_cntl = RREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL_RING2);
ih_rb_cntl = vega10_ih_rb_cntl(ih, ih_rb_cntl);
if (amdgpu_sriov_vf(adev)) {
if (psp_reg_program(&adev->psp, PSP_REG_IH_RB_CNTL_RING2,
ih_rb_cntl)) {
DRM_ERROR("program IH_RB_CNTL_RING2 failed!\n");
return -ETIMEDOUT;
}
} else {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_CNTL_RING2, ih_rb_cntl);
}
/* set rptr, wptr to 0 */
WREG32_SOC15(OSSSYS, 0, mmIH_RB_WPTR_RING2, 0);
WREG32_SOC15(OSSSYS, 0, mmIH_RB_RPTR_RING2, 0);
WREG32_SOC15(OSSSYS, 0, mmIH_DOORBELL_RPTR_RING2,
vega10_ih_doorbell_rptr(ih));
}
tmp = RREG32_SOC15(OSSSYS, 0, mmIH_STORM_CLIENT_LIST_CNTL);
tmp = REG_SET_FIELD(tmp, IH_STORM_CLIENT_LIST_CNTL,
CLIENT18_IS_STORM_CLIENT, 1);
WREG32_SOC15(OSSSYS, 0, mmIH_STORM_CLIENT_LIST_CNTL, tmp);
tmp = RREG32_SOC15(OSSSYS, 0, mmIH_INT_FLOOD_CNTL);
tmp = REG_SET_FIELD(tmp, IH_INT_FLOOD_CNTL, FLOOD_CNTL_ENABLE, 1);
WREG32_SOC15(OSSSYS, 0, mmIH_INT_FLOOD_CNTL, tmp);
pci_set_master(adev->pdev);
/* enable interrupts */
vega10_ih_enable_interrupts(adev);
return ret;
}
/**
* vega10_ih_irq_disable - disable interrupts
*
* @adev: amdgpu_device pointer
*
* Disable interrupts on the hw (VEGA10).
*/
static void vega10_ih_irq_disable(struct amdgpu_device *adev)
{
vega10_ih_disable_interrupts(adev);
/* Wait and acknowledge irq */
mdelay(1);
}
/**
* vega10_ih_get_wptr - get the IH ring buffer wptr
*
* @adev: amdgpu_device pointer
*
* Get the IH ring buffer wptr from either the register
* or the writeback memory buffer (VEGA10). Also check for
* ring buffer overflow and deal with it.
* Returns the value of the wptr.
*/
static u32 vega10_ih_get_wptr(struct amdgpu_device *adev,
struct amdgpu_ih_ring *ih)
{
u32 wptr, reg, tmp;
wptr = le32_to_cpu(*ih->wptr_cpu);
if (!REG_GET_FIELD(wptr, IH_RB_WPTR, RB_OVERFLOW))
goto out;
/* Double check that the overflow wasn't already cleared. */
if (ih == &adev->irq.ih)
reg = SOC15_REG_OFFSET(OSSSYS, 0, mmIH_RB_WPTR);
else if (ih == &adev->irq.ih1)
reg = SOC15_REG_OFFSET(OSSSYS, 0, mmIH_RB_WPTR_RING1);
else if (ih == &adev->irq.ih2)
reg = SOC15_REG_OFFSET(OSSSYS, 0, mmIH_RB_WPTR_RING2);
else
BUG();
wptr = RREG32_NO_KIQ(reg);
if (!REG_GET_FIELD(wptr, IH_RB_WPTR, RB_OVERFLOW))
goto out;
wptr = REG_SET_FIELD(wptr, IH_RB_WPTR, RB_OVERFLOW, 0);
/* When a ring buffer overflow happen start parsing interrupt
* from the last not overwritten vector (wptr + 32). Hopefully
* this should allow us to catchup.
*/
tmp = (wptr + 32) & ih->ptr_mask;
dev_warn(adev->dev, "IH ring buffer overflow "
"(0x%08X, 0x%08X, 0x%08X)\n",
wptr, ih->rptr, tmp);
ih->rptr = tmp;
if (ih == &adev->irq.ih)
reg = SOC15_REG_OFFSET(OSSSYS, 0, mmIH_RB_CNTL);
else if (ih == &adev->irq.ih1)
reg = SOC15_REG_OFFSET(OSSSYS, 0, mmIH_RB_CNTL_RING1);
else if (ih == &adev->irq.ih2)
reg = SOC15_REG_OFFSET(OSSSYS, 0, mmIH_RB_CNTL_RING2);
else
BUG();
tmp = RREG32_NO_KIQ(reg);
tmp = REG_SET_FIELD(tmp, IH_RB_CNTL, WPTR_OVERFLOW_CLEAR, 1);
WREG32_NO_KIQ(reg, tmp);
out:
return (wptr & ih->ptr_mask);
}
/**
* vega10_ih_decode_iv - decode an interrupt vector
*
* @adev: amdgpu_device pointer
*
* Decodes the interrupt vector at the current rptr
* position and also advance the position.
*/
static void vega10_ih_decode_iv(struct amdgpu_device *adev,
struct amdgpu_ih_ring *ih,
struct amdgpu_iv_entry *entry)
{
/* wptr/rptr are in bytes! */
u32 ring_index = ih->rptr >> 2;
uint32_t dw[8];
dw[0] = le32_to_cpu(ih->ring[ring_index + 0]);
dw[1] = le32_to_cpu(ih->ring[ring_index + 1]);
dw[2] = le32_to_cpu(ih->ring[ring_index + 2]);
dw[3] = le32_to_cpu(ih->ring[ring_index + 3]);
dw[4] = le32_to_cpu(ih->ring[ring_index + 4]);
dw[5] = le32_to_cpu(ih->ring[ring_index + 5]);
dw[6] = le32_to_cpu(ih->ring[ring_index + 6]);
dw[7] = le32_to_cpu(ih->ring[ring_index + 7]);
entry->client_id = dw[0] & 0xff;
entry->src_id = (dw[0] >> 8) & 0xff;
entry->ring_id = (dw[0] >> 16) & 0xff;
entry->vmid = (dw[0] >> 24) & 0xf;
entry->vmid_src = (dw[0] >> 31);
entry->timestamp = dw[1] | ((u64)(dw[2] & 0xffff) << 32);
entry->timestamp_src = dw[2] >> 31;
entry->pasid = dw[3] & 0xffff;
entry->pasid_src = dw[3] >> 31;
entry->src_data[0] = dw[4];
entry->src_data[1] = dw[5];
entry->src_data[2] = dw[6];
entry->src_data[3] = dw[7];
/* wptr/rptr are in bytes! */
ih->rptr += 32;
}
/**
* vega10_ih_irq_rearm - rearm IRQ if lost
*
* @adev: amdgpu_device pointer
*
*/
static void vega10_ih_irq_rearm(struct amdgpu_device *adev,
struct amdgpu_ih_ring *ih)
{
uint32_t reg_rptr = 0;
uint32_t v = 0;
uint32_t i = 0;
if (ih == &adev->irq.ih)
reg_rptr = SOC15_REG_OFFSET(OSSSYS, 0, mmIH_RB_RPTR);
else if (ih == &adev->irq.ih1)
reg_rptr = SOC15_REG_OFFSET(OSSSYS, 0, mmIH_RB_RPTR_RING1);
else if (ih == &adev->irq.ih2)
reg_rptr = SOC15_REG_OFFSET(OSSSYS, 0, mmIH_RB_RPTR_RING2);
else
return;
/* Rearm IRQ / re-wwrite doorbell if doorbell write is lost */
for (i = 0; i < MAX_REARM_RETRY; i++) {
v = RREG32_NO_KIQ(reg_rptr);
if ((v < ih->ring_size) && (v != ih->rptr))
WDOORBELL32(ih->doorbell_index, ih->rptr);
else
break;
}
}
/**
* vega10_ih_set_rptr - set the IH ring buffer rptr
*
* @adev: amdgpu_device pointer
*
* Set the IH ring buffer rptr.
*/
static void vega10_ih_set_rptr(struct amdgpu_device *adev,
struct amdgpu_ih_ring *ih)
{
if (ih->use_doorbell) {
/* XXX check if swapping is necessary on BE */
*ih->rptr_cpu = ih->rptr;
WDOORBELL32(ih->doorbell_index, ih->rptr);
if (amdgpu_sriov_vf(adev))
vega10_ih_irq_rearm(adev, ih);
} else if (ih == &adev->irq.ih) {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_RPTR, ih->rptr);
} else if (ih == &adev->irq.ih1) {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_RPTR_RING1, ih->rptr);
} else if (ih == &adev->irq.ih2) {
WREG32_SOC15(OSSSYS, 0, mmIH_RB_RPTR_RING2, ih->rptr);
}
}
/**
* vega10_ih_self_irq - dispatch work for ring 1 and 2
*
* @adev: amdgpu_device pointer
* @source: irq source
* @entry: IV with WPTR update
*
* Update the WPTR from the IV and schedule work to handle the entries.
*/
static int vega10_ih_self_irq(struct amdgpu_device *adev,
struct amdgpu_irq_src *source,
struct amdgpu_iv_entry *entry)
{
uint32_t wptr = cpu_to_le32(entry->src_data[0]);
switch (entry->ring_id) {
case 1:
*adev->irq.ih1.wptr_cpu = wptr;
schedule_work(&adev->irq.ih1_work);
break;
case 2:
*adev->irq.ih2.wptr_cpu = wptr;
schedule_work(&adev->irq.ih2_work);
break;
default: break;
}
return 0;
}
static const struct amdgpu_irq_src_funcs vega10_ih_self_irq_funcs = {
.process = vega10_ih_self_irq,
};
static void vega10_ih_set_self_irq_funcs(struct amdgpu_device *adev)
{
adev->irq.self_irq.num_types = 0;
adev->irq.self_irq.funcs = &vega10_ih_self_irq_funcs;
}
static int vega10_ih_early_init(void *handle)
{
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
vega10_ih_set_interrupt_funcs(adev);
vega10_ih_set_self_irq_funcs(adev);
return 0;
}
static int vega10_ih_sw_init(void *handle)
{
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
int r;
r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_IH, 0,
&adev->irq.self_irq);
if (r)
return r;
r = amdgpu_ih_ring_init(adev, &adev->irq.ih, 256 * 1024, true);
if (r)
return r;
adev->irq.ih.use_doorbell = true;
adev->irq.ih.doorbell_index = adev->doorbell_index.ih << 1;
r = amdgpu_ih_ring_init(adev, &adev->irq.ih1, PAGE_SIZE, true);
if (r)
return r;
adev->irq.ih1.use_doorbell = true;
adev->irq.ih1.doorbell_index = (adev->doorbell_index.ih + 1) << 1;
r = amdgpu_ih_ring_init(adev, &adev->irq.ih2, PAGE_SIZE, true);
if (r)
return r;
adev->irq.ih2.use_doorbell = true;
adev->irq.ih2.doorbell_index = (adev->doorbell_index.ih + 2) << 1;
r = amdgpu_irq_init(adev);
return r;
}
static int vega10_ih_sw_fini(void *handle)
{
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
amdgpu_irq_fini(adev);
amdgpu_ih_ring_fini(adev, &adev->irq.ih2);
amdgpu_ih_ring_fini(adev, &adev->irq.ih1);
amdgpu_ih_ring_fini(adev, &adev->irq.ih);
return 0;
}
static int vega10_ih_hw_init(void *handle)
{
int r;
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
r = vega10_ih_irq_init(adev);
if (r)
return r;
return 0;
}
static int vega10_ih_hw_fini(void *handle)
{
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
vega10_ih_irq_disable(adev);
return 0;
}
static int vega10_ih_suspend(void *handle)
{
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
return vega10_ih_hw_fini(adev);
}
static int vega10_ih_resume(void *handle)
{
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
return vega10_ih_hw_init(adev);
}
static bool vega10_ih_is_idle(void *handle)
{
/* todo */
return true;
}
static int vega10_ih_wait_for_idle(void *handle)
{
/* todo */
return -ETIMEDOUT;
}
static int vega10_ih_soft_reset(void *handle)
{
/* todo */
return 0;
}
static void vega10_ih_update_clockgating_state(struct amdgpu_device *adev,
bool enable)
{
uint32_t data, def, field_val;
if (adev->cg_flags & AMD_CG_SUPPORT_IH_CG) {
def = data = RREG32_SOC15(OSSSYS, 0, mmIH_CLK_CTRL);
field_val = enable ? 0 : 1;
/**
* Vega10 does not have IH_RETRY_INT_CAM_MEM_CLK_SOFT_OVERRIDE
* and IH_BUFFER_MEM_CLK_SOFT_OVERRIDE field.
*/
if (adev->asic_type > CHIP_VEGA10) {
data = REG_SET_FIELD(data, IH_CLK_CTRL,
IH_RETRY_INT_CAM_MEM_CLK_SOFT_OVERRIDE, field_val);
data = REG_SET_FIELD(data, IH_CLK_CTRL,
IH_BUFFER_MEM_CLK_SOFT_OVERRIDE, field_val);
}
data = REG_SET_FIELD(data, IH_CLK_CTRL,
DBUS_MUX_CLK_SOFT_OVERRIDE, field_val);
data = REG_SET_FIELD(data, IH_CLK_CTRL,
OSSSYS_SHARE_CLK_SOFT_OVERRIDE, field_val);
data = REG_SET_FIELD(data, IH_CLK_CTRL,
LIMIT_SMN_CLK_SOFT_OVERRIDE, field_val);
data = REG_SET_FIELD(data, IH_CLK_CTRL,
DYN_CLK_SOFT_OVERRIDE, field_val);
data = REG_SET_FIELD(data, IH_CLK_CTRL,
REG_CLK_SOFT_OVERRIDE, field_val);
if (def != data)
WREG32_SOC15(OSSSYS, 0, mmIH_CLK_CTRL, data);
}
}
static int vega10_ih_set_clockgating_state(void *handle,
enum amd_clockgating_state state)
{
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
vega10_ih_update_clockgating_state(adev,
state == AMD_CG_STATE_GATE);
return 0;
}
static int vega10_ih_set_powergating_state(void *handle,
enum amd_powergating_state state)
{
return 0;
}
const struct amd_ip_funcs vega10_ih_ip_funcs = {
.name = "vega10_ih",
.early_init = vega10_ih_early_init,
.late_init = NULL,
.sw_init = vega10_ih_sw_init,
.sw_fini = vega10_ih_sw_fini,
.hw_init = vega10_ih_hw_init,
.hw_fini = vega10_ih_hw_fini,
.suspend = vega10_ih_suspend,
.resume = vega10_ih_resume,
.is_idle = vega10_ih_is_idle,
.wait_for_idle = vega10_ih_wait_for_idle,
.soft_reset = vega10_ih_soft_reset,
.set_clockgating_state = vega10_ih_set_clockgating_state,
.set_powergating_state = vega10_ih_set_powergating_state,
};
static const struct amdgpu_ih_funcs vega10_ih_funcs = {
.get_wptr = vega10_ih_get_wptr,
.decode_iv = vega10_ih_decode_iv,
.set_rptr = vega10_ih_set_rptr
};
static void vega10_ih_set_interrupt_funcs(struct amdgpu_device *adev)
{
adev->irq.ih_funcs = &vega10_ih_funcs;
}
const struct amdgpu_ip_block_version vega10_ih_ip_block =
{
.type = AMD_IP_BLOCK_TYPE_IH,
.major = 4,
.minor = 0,
.rev = 0,
.funcs = &vega10_ih_ip_funcs,
};
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
@class NSString, Protocol;
@protocol NSObject
@property(readonly, copy) NSString *description;
@property(readonly) Class superclass;
@property(readonly) unsigned long long hash;
- (struct _NSZone *)zone;
- (unsigned long long)retainCount;
- (id)autorelease;
- (oneway void)release;
- (id)retain;
- (BOOL)respondsToSelector:(SEL)arg1;
- (BOOL)conformsToProtocol:(Protocol *)arg1;
- (BOOL)isMemberOfClass:(Class)arg1;
- (BOOL)isKindOfClass:(Class)arg1;
- (BOOL)isProxy;
- (id)performSelector:(SEL)arg1 withObject:(id)arg2 withObject:(id)arg3;
- (id)performSelector:(SEL)arg1 withObject:(id)arg2;
- (id)performSelector:(SEL)arg1;
- (id)self;
- (Class)class;
- (BOOL)isEqual:(id)arg1;
@optional
@property(readonly, copy) NSString *debugDescription;
@end
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Effects - Easing demo</title>
<link rel="stylesheet" href="../../themes/base/jquery.ui.all.css">
<script src="../../jquery-1.10.2.js"></script>
<script src="../../ui/jquery.ui.effect.js"></script>
<link rel="stylesheet" href="../demos.css">
<style>
.graph {
float: left;
margin-left: 10px;
}
</style>
<script>
$(function() {
if ( !$( "<canvas>" )[0].getContext ) {
$( "<div>" ).text(
"Your browser doesn't support canvas, which is required for this demo."
).appendTo( "#graphs" );
return;
}
var i = 0,
width = 100,
height = 100;
$.each( $.easing, function( name, impl ) {
var graph = $( "<div>" ).addClass( "graph" ).appendTo( "#graphs" ),
text = $( "<div>" ).text( ++i + ". " + name ).appendTo( graph ),
wrap = $( "<div>" ).appendTo( graph ).css( 'overflow', 'hidden' ),
canvas = $( "<canvas>" ).appendTo( wrap )[ 0 ];
canvas.width = width;
canvas.height = height;
var drawHeight = height * 0.8,
cradius = 10;
ctx = canvas.getContext( "2d" );
ctx.fillStyle = "black";
// draw background
ctx.beginPath();
ctx.moveTo( cradius, 0 );
ctx.quadraticCurveTo( 0, 0, 0, cradius );
ctx.lineTo( 0, height - cradius );
ctx.quadraticCurveTo( 0, height, cradius, height );
ctx.lineTo( width - cradius, height );
ctx.quadraticCurveTo( width, height, width, height - cradius );
ctx.lineTo( width, 0 );
ctx.lineTo( cradius, 0 );
ctx.fill();
// draw bottom line
ctx.strokeStyle = "#555";
ctx.beginPath();
ctx.moveTo( width * 0.1, drawHeight + .5 );
ctx.lineTo( width * 0.9, drawHeight + .5 );
ctx.stroke();
// draw top line
ctx.strokeStyle = "#555";
ctx.beginPath();
ctx.moveTo( width * 0.1, drawHeight * .3 - .5 );
ctx.lineTo( width * 0.9, drawHeight * .3 - .5 );
ctx.stroke();
// plot easing
ctx.strokeStyle = "white";
ctx.beginPath();
ctx.lineWidth = 2;
ctx.moveTo( width * 0.1, drawHeight );
$.each( new Array( width ), function( position ) {
var state = position / width,
val = impl( state, position, 0, 1, width );
ctx.lineTo( position * 0.8 + width * 0.1,
drawHeight - drawHeight * val * 0.7 );
});
ctx.stroke();
// animate on click
graph.click(function() {
wrap
.animate( { height: "hide" }, 2000, name )
.delay( 800 )
.animate( { height: "show" }, 2000, name );
});
graph.width( width ).height( height + text.height() + 10 );
});
});
</script>
</head>
<body>
<div id="graphs"></div>
<div class="demo-description">
<p><strong>All easings provided by jQuery UI are drawn above, using a HTML canvas element</strong>. Click a diagram to see the easing in action.</p>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
def SampleFunction():
raise Exception('I should never be called!')
| {
"pile_set_name": "Github"
} |
/***************************************************************************
copyright : (C) 2012 by Lukas Lalinsky
email : [email protected]
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <string>
#include <stdio.h>
#include <tag.h>
#include <tstringlist.h>
#include <tbytevectorlist.h>
#include <flacunknownmetadatablock.h>
#include <cppunit/extensions/HelperMacros.h>
#include "utils.h"
using namespace std;
using namespace TagLib;
class TestFLACUnknownMetadataBlock : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(TestFLACUnknownMetadataBlock);
CPPUNIT_TEST(testAccessors);
CPPUNIT_TEST_SUITE_END();
public:
void testAccessors()
{
ByteVector data("abc\x01", 4);
FLAC::UnknownMetadataBlock block(42, data);
CPPUNIT_ASSERT_EQUAL(42, block.code());
CPPUNIT_ASSERT_EQUAL(data, block.data());
CPPUNIT_ASSERT_EQUAL(data, block.render());
ByteVector data2("xxx", 3);
block.setCode(13);
block.setData(data2);
CPPUNIT_ASSERT_EQUAL(13, block.code());
CPPUNIT_ASSERT_EQUAL(data2, block.data());
CPPUNIT_ASSERT_EQUAL(data2, block.render());
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestFLACUnknownMetadataBlock);
| {
"pile_set_name": "Github"
} |
apiVersion: argoproj.io/v1alpha1
kind: AnalysisRun
metadata:
name: canary-demo-analysis-template-6c6bb7cf6f-btpgc
namespace: default
spec:
analysisSpec:
metrics:
- failureCondition: result < 92
interval: 10
name: memory-usage
provider:
prometheus:
address: 'http://prometheus-operator-prometheus.prometheus-operator:9090'
query: >
sum(rate(nginx_ingress_controller_requests{ingress="canary-demo-preview",status!~"[4-5].*"}[2m]))
/
sum(rate(nginx_ingress_controller_requests{ingress="canary-demo-preview"}[2m]))
successCondition: result > 95
status:
message: "Status Message: Assessed as Error"
metricResults:
- consecutiveError: 5
error: 5
measurements:
- finishedAt: '2019-10-28T18:13:01Z'
startedAt: '2019-10-28T18:13:01Z'
phase: Error
value: '[0.9832775919732442]'
- finishedAt: '2019-10-28T18:13:11Z'
startedAt: '2019-10-28T18:13:11Z'
phase: Error
value: '[0.9832775919732442]'
- finishedAt: '2019-10-28T18:13:21Z'
startedAt: '2019-10-28T18:13:21Z'
phase: Error
value: '[0.9722530521642618]'
- finishedAt: '2019-10-28T18:13:31Z'
startedAt: '2019-10-28T18:13:31Z'
phase: Error
value: '[0.9722530521642618]'
- finishedAt: '2019-10-28T18:13:41Z'
startedAt: '2019-10-28T18:13:41Z'
phase: Error
value: '[0.9722530521642618]'
name: memory-usage
phase: Error
phase: Error
| {
"pile_set_name": "Github"
} |
var Geometry = require('../lib/geometry');
var Point = require('../lib/point');
var assert = require('assert');
describe('wkx', function () {
describe('parseTwkb', function () {
it('includes size', function () {
assert.deepEqual(Geometry.parseTwkb(
new Buffer('0102020204', 'hex')),
new Point(1, 2));
});
it('includes bounding box', function () {
assert.deepEqual(Geometry.parseTwkb(
new Buffer('0101020004000204', 'hex')),
new Point(1, 2));
});
it('includes extended precision', function () {
assert.deepEqual(Geometry.parseTwkb(
new Buffer('01080302040608', 'hex')),
new Point(1, 2, 3, 4));
});
it('includes extended precision and bounding box', function () {
assert.deepEqual(Geometry.parseTwkb(
new Buffer('010903020004000600080002040608', 'hex')),
new Point(1, 2, 3, 4));
});
});
describe('toTwkb', function () {
it('Point small', function () {
assert.equal(new Point(1, 2).toTwkb().toString('hex'), 'a100c09a0c80b518');
});
it('Point large', function () {
assert.equal(new Point(10000, 20000).toTwkb().toString('hex'), 'a10080a8d6b90780d0acf30e');
});
});
});
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For further information on the license, see the LICENSE.txt file #
# For further information please visit http://www.aiida.net #
###########################################################################
# pylint: disable=redefined-builtin
"""Module with resources common to the repository."""
import enum
import warnings
from aiida.common.warnings import AiidaDeprecationWarning
__all__ = ('File', 'FileType')
class FileType(enum.Enum):
"""Enumeration to represent the type of a file object."""
DIRECTORY = 0
FILE = 1
class File:
"""Data class representing a file object."""
def __init__(self, name: str = '', file_type: FileType = FileType.DIRECTORY, type=None):
"""
.. deprecated:: 1.4.0
The argument `type` has been deprecated and will be removed in `v2.0.0`, use `file_type` instead.
"""
if type is not None:
warnings.warn(
'argument `type` is deprecated and will be removed in `v2.0.0`. Use `file_type` instead.',
AiidaDeprecationWarning
) # pylint: disable=no-member"""
file_type = type
if not isinstance(name, str):
raise TypeError('name should be a string.')
if not isinstance(file_type, FileType):
raise TypeError('file_type should be an instance of `FileType`.')
self._name = name
self._file_type = file_type
@property
def name(self) -> str:
"""Return the name of the file object."""
return self._name
@property
def type(self) -> FileType:
"""Return the file type of the file object.
.. deprecated:: 1.4.0
Will be removed in `v2.0.0`, use `file_type` instead.
"""
warnings.warn('property is deprecated, use `file_type` instead', AiidaDeprecationWarning) # pylint: disable=no-member"""
return self.file_type
@property
def file_type(self) -> FileType:
"""Return the file type of the file object."""
return self._file_type
def __iter__(self):
"""Iterate over the properties."""
warnings.warn(
'`File` has changed from named tuple into class and from `v2.0.0` will no longer be iterable',
AiidaDeprecationWarning
)
yield self.name
yield self.file_type
def __eq__(self, other):
return self.file_type == other.file_type and self.name == other.name
| {
"pile_set_name": "Github"
} |
#!/usr/local/bin/perl
# Show a form for editing a generic attribute or adding one
require './zones-lib.pl';
do 'forms-lib.pl';
&ReadParse();
$zinfo = &get_zone($in{'zone'});
$zinfo || &error($text{'edit_egone'});
if (!$in{'new'}) {
# Find the filesystem object
($attr) = grep { $_->{'name'} eq $in{'old'} } @{$zinfo->{'attr'}};
$attr || &error($text{'attr_egone'});
}
$p = new WebminUI::Page(&zone_title($in{'zone'}),
$in{'new'} ? $text{'attr_title1'} : $text{'attr_title2'},
"attr");
$p->add_form(&get_attr_form(\%in, $zinfo, $attr));
$p->add_footer("edit_zone.cgi?zone=$in{'zone'}", $text{'edit_return'});
$p->print();
| {
"pile_set_name": "Github"
} |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the ecr-2015-09-21.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ECR.Model
{
/// <summary>
/// An object representing a filter on a <a>DescribeImages</a> operation.
/// </summary>
public partial class DescribeImagesFilter
{
private TagStatus _tagStatus;
/// <summary>
/// Gets and sets the property TagStatus.
/// <para>
/// The tag status with which to filter your <a>DescribeImages</a> results. You can filter
/// results based on whether they are <code>TAGGED</code> or <code>UNTAGGED</code>.
/// </para>
/// </summary>
public TagStatus TagStatus
{
get { return this._tagStatus; }
set { this._tagStatus = value; }
}
// Check to see if TagStatus property is set
internal bool IsSetTagStatus()
{
return this._tagStatus != null;
}
}
} | {
"pile_set_name": "Github"
} |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package syscall
const _SYS_dup = SYS_DUP2
//sys Dup2(oldfd int, newfd int) (err error)
//sys Fchown(fd int, uid int, gid int) (err error)
//sys Fstat(fd int, stat *Stat_t) (err error)
//sys Fstatfs(fd int, buf *Statfs_t) (err error)
//sys Ftruncate(fd int, length int64) (err error)
//sysnb Getegid() (egid int)
//sysnb Geteuid() (euid int)
//sysnb Getgid() (gid int)
//sysnb Getrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Getuid() (uid int)
//sysnb InotifyInit() (fd int, err error)
//sys Ioperm(from int, num int, on int) (err error)
//sys Iopl(level int) (err error)
//sys Lchown(path string, uid int, gid int) (err error)
//sys Listen(s int, n int) (err error)
//sys Lstat(path string, stat *Stat_t) (err error)
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
//sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
//sys Setfsgid(gid int) (err error)
//sys Setfsuid(uid int) (err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
//sys Stat(path string, stat *Stat_t) (err error)
//sys Statfs(path string, buf *Statfs_t) (err error)
//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
//sys Truncate(path string, length int64) (err error)
//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error)
//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error)
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sysnb getgroups(n int, list *_Gid_t) (nn int, err error)
//sysnb setgroups(n int, list *_Gid_t) (err error)
//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error)
//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error)
//sysnb socket(domain int, typ int, proto int) (fd int, err error)
//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error)
//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error)
//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error)
//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error)
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error)
//go:noescape
func gettimeofday(tv *Timeval) (err Errno)
func Gettimeofday(tv *Timeval) (err error) {
errno := gettimeofday(tv)
if errno != 0 {
return errno
}
return nil
}
func Getpagesize() int { return 4096 }
func Time(t *Time_t) (tt Time_t, err error) {
var tv Timeval
errno := gettimeofday(&tv)
if errno != 0 {
return 0, errno
}
if t != nil {
*t = Time_t(tv.Sec)
}
return Time_t(tv.Sec), nil
}
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
func NsecToTimespec(nsec int64) (ts Timespec) {
ts.Sec = nsec / 1e9
ts.Nsec = nsec % 1e9
return
}
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
func NsecToTimeval(nsec int64) (tv Timeval) {
nsec += 999 // round up to microsecond
tv.Sec = nsec / 1e9
tv.Usec = nsec % 1e9 / 1e3
return
}
//sysnb pipe(p *[2]_C_int) (err error)
func Pipe(p []int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
err = pipe(&pp)
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
//sysnb pipe2(p *[2]_C_int, flags int) (err error)
func Pipe2(p []int, flags int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
err = pipe2(&pp, flags)
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
func (r *PtraceRegs) PC() uint64 { return r.Rip }
func (r *PtraceRegs) SetPC(pc uint64) { r.Rip = pc }
func (iov *Iovec) SetLen(length int) {
iov.Len = uint64(length)
}
func (msghdr *Msghdr) SetControllen(length int) {
msghdr.Controllen = uint64(length)
}
func (cmsg *Cmsghdr) SetLen(length int) {
cmsg.Len = uint64(length)
}
| {
"pile_set_name": "Github"
} |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// CodeMirror2 mode/perl/perl.js (text/x-perl) beta 0.10 (2011-11-08)
// This is a part of CodeMirror from https://github.com/sabaca/CodeMirror_mode_perl ([email protected])
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("perl",function(){
// http://perldoc.perl.org
var PERL={ // null - magic touch
// 1 - keyword
// 2 - def
// 3 - atom
// 4 - operator
// 5 - variable-2 (predefined)
// [x,y] - x=1,2,3; y=must be defined if x{...}
// PERL operators
'->' : 4,
'++' : 4,
'--' : 4,
'**' : 4,
// ! ~ \ and unary + and -
'=~' : 4,
'!~' : 4,
'*' : 4,
'/' : 4,
'%' : 4,
'x' : 4,
'+' : 4,
'-' : 4,
'.' : 4,
'<<' : 4,
'>>' : 4,
// named unary operators
'<' : 4,
'>' : 4,
'<=' : 4,
'>=' : 4,
'lt' : 4,
'gt' : 4,
'le' : 4,
'ge' : 4,
'==' : 4,
'!=' : 4,
'<=>' : 4,
'eq' : 4,
'ne' : 4,
'cmp' : 4,
'~~' : 4,
'&' : 4,
'|' : 4,
'^' : 4,
'&&' : 4,
'||' : 4,
'//' : 4,
'..' : 4,
'...' : 4,
'?' : 4,
':' : 4,
'=' : 4,
'+=' : 4,
'-=' : 4,
'*=' : 4, // etc. ???
',' : 4,
'=>' : 4,
'::' : 4,
// list operators (rightward)
'not' : 4,
'and' : 4,
'or' : 4,
'xor' : 4,
// PERL predefined variables (I know, what this is a paranoid idea, but may be needed for people, who learn PERL, and for me as well, ...and may be for you?;)
'BEGIN' : [5,1],
'END' : [5,1],
'PRINT' : [5,1],
'PRINTF' : [5,1],
'GETC' : [5,1],
'READ' : [5,1],
'READLINE' : [5,1],
'DESTROY' : [5,1],
'TIE' : [5,1],
'TIEHANDLE' : [5,1],
'UNTIE' : [5,1],
'STDIN' : 5,
'STDIN_TOP' : 5,
'STDOUT' : 5,
'STDOUT_TOP' : 5,
'STDERR' : 5,
'STDERR_TOP' : 5,
'$ARG' : 5,
'$_' : 5,
'@ARG' : 5,
'@_' : 5,
'$LIST_SEPARATOR' : 5,
'$"' : 5,
'$PROCESS_ID' : 5,
'$PID' : 5,
'$$' : 5,
'$REAL_GROUP_ID' : 5,
'$GID' : 5,
'$(' : 5,
'$EFFECTIVE_GROUP_ID' : 5,
'$EGID' : 5,
'$)' : 5,
'$PROGRAM_NAME' : 5,
'$0' : 5,
'$SUBSCRIPT_SEPARATOR' : 5,
'$SUBSEP' : 5,
'$;' : 5,
'$REAL_USER_ID' : 5,
'$UID' : 5,
'$<' : 5,
'$EFFECTIVE_USER_ID' : 5,
'$EUID' : 5,
'$>' : 5,
'$a' : 5,
'$b' : 5,
'$COMPILING' : 5,
'$^C' : 5,
'$DEBUGGING' : 5,
'$^D' : 5,
'${^ENCODING}' : 5,
'$ENV' : 5,
'%ENV' : 5,
'$SYSTEM_FD_MAX' : 5,
'$^F' : 5,
'@F' : 5,
'${^GLOBAL_PHASE}' : 5,
'$^H' : 5,
'%^H' : 5,
'@INC' : 5,
'%INC' : 5,
'$INPLACE_EDIT' : 5,
'$^I' : 5,
'$^M' : 5,
'$OSNAME' : 5,
'$^O' : 5,
'${^OPEN}' : 5,
'$PERLDB' : 5,
'$^P' : 5,
'$SIG' : 5,
'%SIG' : 5,
'$BASETIME' : 5,
'$^T' : 5,
'${^TAINT}' : 5,
'${^UNICODE}' : 5,
'${^UTF8CACHE}' : 5,
'${^UTF8LOCALE}' : 5,
'$PERL_VERSION' : 5,
'$^V' : 5,
'${^WIN32_SLOPPY_STAT}' : 5,
'$EXECUTABLE_NAME' : 5,
'$^X' : 5,
'$1' : 5, // - regexp $1, $2...
'$MATCH' : 5,
'$&' : 5,
'${^MATCH}' : 5,
'$PREMATCH' : 5,
'$`' : 5,
'${^PREMATCH}' : 5,
'$POSTMATCH' : 5,
"$'" : 5,
'${^POSTMATCH}' : 5,
'$LAST_PAREN_MATCH' : 5,
'$+' : 5,
'$LAST_SUBMATCH_RESULT' : 5,
'$^N' : 5,
'@LAST_MATCH_END' : 5,
'@+' : 5,
'%LAST_PAREN_MATCH' : 5,
'%+' : 5,
'@LAST_MATCH_START' : 5,
'@-' : 5,
'%LAST_MATCH_START' : 5,
'%-' : 5,
'$LAST_REGEXP_CODE_RESULT' : 5,
'$^R' : 5,
'${^RE_DEBUG_FLAGS}' : 5,
'${^RE_TRIE_MAXBUF}' : 5,
'$ARGV' : 5,
'@ARGV' : 5,
'ARGV' : 5,
'ARGVOUT' : 5,
'$OUTPUT_FIELD_SEPARATOR' : 5,
'$OFS' : 5,
'$,' : 5,
'$INPUT_LINE_NUMBER' : 5,
'$NR' : 5,
'$.' : 5,
'$INPUT_RECORD_SEPARATOR' : 5,
'$RS' : 5,
'$/' : 5,
'$OUTPUT_RECORD_SEPARATOR' : 5,
'$ORS' : 5,
'$\\' : 5,
'$OUTPUT_AUTOFLUSH' : 5,
'$|' : 5,
'$ACCUMULATOR' : 5,
'$^A' : 5,
'$FORMAT_FORMFEED' : 5,
'$^L' : 5,
'$FORMAT_PAGE_NUMBER' : 5,
'$%' : 5,
'$FORMAT_LINES_LEFT' : 5,
'$-' : 5,
'$FORMAT_LINE_BREAK_CHARACTERS' : 5,
'$:' : 5,
'$FORMAT_LINES_PER_PAGE' : 5,
'$=' : 5,
'$FORMAT_TOP_NAME' : 5,
'$^' : 5,
'$FORMAT_NAME' : 5,
'$~' : 5,
'${^CHILD_ERROR_NATIVE}' : 5,
'$EXTENDED_OS_ERROR' : 5,
'$^E' : 5,
'$EXCEPTIONS_BEING_CAUGHT' : 5,
'$^S' : 5,
'$WARNING' : 5,
'$^W' : 5,
'${^WARNING_BITS}' : 5,
'$OS_ERROR' : 5,
'$ERRNO' : 5,
'$!' : 5,
'%OS_ERROR' : 5,
'%ERRNO' : 5,
'%!' : 5,
'$CHILD_ERROR' : 5,
'$?' : 5,
'$EVAL_ERROR' : 5,
'$@' : 5,
'$OFMT' : 5,
'$#' : 5,
'$*' : 5,
'$ARRAY_BASE' : 5,
'$[' : 5,
'$OLD_PERL_VERSION' : 5,
'$]' : 5,
// PERL blocks
'if' :[1,1],
elsif :[1,1],
'else' :[1,1],
'while' :[1,1],
unless :[1,1],
'for' :[1,1],
foreach :[1,1],
// PERL functions
'abs' :1, // - absolute value function
accept :1, // - accept an incoming socket connect
alarm :1, // - schedule a SIGALRM
'atan2' :1, // - arctangent of Y/X in the range -PI to PI
bind :1, // - binds an address to a socket
binmode :1, // - prepare binary files for I/O
bless :1, // - create an object
bootstrap :1, //
'break' :1, // - break out of a "given" block
caller :1, // - get context of the current subroutine call
chdir :1, // - change your current working directory
chmod :1, // - changes the permissions on a list of files
chomp :1, // - remove a trailing record separator from a string
chop :1, // - remove the last character from a string
chown :1, // - change the owership on a list of files
chr :1, // - get character this number represents
chroot :1, // - make directory new root for path lookups
close :1, // - close file (or pipe or socket) handle
closedir :1, // - close directory handle
connect :1, // - connect to a remote socket
'continue' :[1,1], // - optional trailing block in a while or foreach
'cos' :1, // - cosine function
crypt :1, // - one-way passwd-style encryption
dbmclose :1, // - breaks binding on a tied dbm file
dbmopen :1, // - create binding on a tied dbm file
'default' :1, //
defined :1, // - test whether a value, variable, or function is defined
'delete' :1, // - deletes a value from a hash
die :1, // - raise an exception or bail out
'do' :1, // - turn a BLOCK into a TERM
dump :1, // - create an immediate core dump
each :1, // - retrieve the next key/value pair from a hash
endgrent :1, // - be done using group file
endhostent :1, // - be done using hosts file
endnetent :1, // - be done using networks file
endprotoent :1, // - be done using protocols file
endpwent :1, // - be done using passwd file
endservent :1, // - be done using services file
eof :1, // - test a filehandle for its end
'eval' :1, // - catch exceptions or compile and run code
'exec' :1, // - abandon this program to run another
exists :1, // - test whether a hash key is present
exit :1, // - terminate this program
'exp' :1, // - raise I to a power
fcntl :1, // - file control system call
fileno :1, // - return file descriptor from filehandle
flock :1, // - lock an entire file with an advisory lock
fork :1, // - create a new process just like this one
format :1, // - declare a picture format with use by the write() function
formline :1, // - internal function used for formats
getc :1, // - get the next character from the filehandle
getgrent :1, // - get next group record
getgrgid :1, // - get group record given group user ID
getgrnam :1, // - get group record given group name
gethostbyaddr :1, // - get host record given its address
gethostbyname :1, // - get host record given name
gethostent :1, // - get next hosts record
getlogin :1, // - return who logged in at this tty
getnetbyaddr :1, // - get network record given its address
getnetbyname :1, // - get networks record given name
getnetent :1, // - get next networks record
getpeername :1, // - find the other end of a socket connection
getpgrp :1, // - get process group
getppid :1, // - get parent process ID
getpriority :1, // - get current nice value
getprotobyname :1, // - get protocol record given name
getprotobynumber :1, // - get protocol record numeric protocol
getprotoent :1, // - get next protocols record
getpwent :1, // - get next passwd record
getpwnam :1, // - get passwd record given user login name
getpwuid :1, // - get passwd record given user ID
getservbyname :1, // - get services record given its name
getservbyport :1, // - get services record given numeric port
getservent :1, // - get next services record
getsockname :1, // - retrieve the sockaddr for a given socket
getsockopt :1, // - get socket options on a given socket
given :1, //
glob :1, // - expand filenames using wildcards
gmtime :1, // - convert UNIX time into record or string using Greenwich time
'goto' :1, // - create spaghetti code
grep :1, // - locate elements in a list test true against a given criterion
hex :1, // - convert a string to a hexadecimal number
'import' :1, // - patch a module's namespace into your own
index :1, // - find a substring within a string
'int' :1, // - get the integer portion of a number
ioctl :1, // - system-dependent device control system call
'join' :1, // - join a list into a string using a separator
keys :1, // - retrieve list of indices from a hash
kill :1, // - send a signal to a process or process group
last :1, // - exit a block prematurely
lc :1, // - return lower-case version of a string
lcfirst :1, // - return a string with just the next letter in lower case
length :1, // - return the number of bytes in a string
'link' :1, // - create a hard link in the filesytem
listen :1, // - register your socket as a server
local : 2, // - create a temporary value for a global variable (dynamic scoping)
localtime :1, // - convert UNIX time into record or string using local time
lock :1, // - get a thread lock on a variable, subroutine, or method
'log' :1, // - retrieve the natural logarithm for a number
lstat :1, // - stat a symbolic link
m :null, // - match a string with a regular expression pattern
map :1, // - apply a change to a list to get back a new list with the changes
mkdir :1, // - create a directory
msgctl :1, // - SysV IPC message control operations
msgget :1, // - get SysV IPC message queue
msgrcv :1, // - receive a SysV IPC message from a message queue
msgsnd :1, // - send a SysV IPC message to a message queue
my : 2, // - declare and assign a local variable (lexical scoping)
'new' :1, //
next :1, // - iterate a block prematurely
no :1, // - unimport some module symbols or semantics at compile time
oct :1, // - convert a string to an octal number
open :1, // - open a file, pipe, or descriptor
opendir :1, // - open a directory
ord :1, // - find a character's numeric representation
our : 2, // - declare and assign a package variable (lexical scoping)
pack :1, // - convert a list into a binary representation
'package' :1, // - declare a separate global namespace
pipe :1, // - open a pair of connected filehandles
pop :1, // - remove the last element from an array and return it
pos :1, // - find or set the offset for the last/next m//g search
print :1, // - output a list to a filehandle
printf :1, // - output a formatted list to a filehandle
prototype :1, // - get the prototype (if any) of a subroutine
push :1, // - append one or more elements to an array
q :null, // - singly quote a string
qq :null, // - doubly quote a string
qr :null, // - Compile pattern
quotemeta :null, // - quote regular expression magic characters
qw :null, // - quote a list of words
qx :null, // - backquote quote a string
rand :1, // - retrieve the next pseudorandom number
read :1, // - fixed-length buffered input from a filehandle
readdir :1, // - get a directory from a directory handle
readline :1, // - fetch a record from a file
readlink :1, // - determine where a symbolic link is pointing
readpipe :1, // - execute a system command and collect standard output
recv :1, // - receive a message over a Socket
redo :1, // - start this loop iteration over again
ref :1, // - find out the type of thing being referenced
rename :1, // - change a filename
require :1, // - load in external functions from a library at runtime
reset :1, // - clear all variables of a given name
'return' :1, // - get out of a function early
reverse :1, // - flip a string or a list
rewinddir :1, // - reset directory handle
rindex :1, // - right-to-left substring search
rmdir :1, // - remove a directory
s :null, // - replace a pattern with a string
say :1, // - print with newline
scalar :1, // - force a scalar context
seek :1, // - reposition file pointer for random-access I/O
seekdir :1, // - reposition directory pointer
select :1, // - reset default output or do I/O multiplexing
semctl :1, // - SysV semaphore control operations
semget :1, // - get set of SysV semaphores
semop :1, // - SysV semaphore operations
send :1, // - send a message over a socket
setgrent :1, // - prepare group file for use
sethostent :1, // - prepare hosts file for use
setnetent :1, // - prepare networks file for use
setpgrp :1, // - set the process group of a process
setpriority :1, // - set a process's nice value
setprotoent :1, // - prepare protocols file for use
setpwent :1, // - prepare passwd file for use
setservent :1, // - prepare services file for use
setsockopt :1, // - set some socket options
shift :1, // - remove the first element of an array, and return it
shmctl :1, // - SysV shared memory operations
shmget :1, // - get SysV shared memory segment identifier
shmread :1, // - read SysV shared memory
shmwrite :1, // - write SysV shared memory
shutdown :1, // - close down just half of a socket connection
'sin' :1, // - return the sine of a number
sleep :1, // - block for some number of seconds
socket :1, // - create a socket
socketpair :1, // - create a pair of sockets
'sort' :1, // - sort a list of values
splice :1, // - add or remove elements anywhere in an array
'split' :1, // - split up a string using a regexp delimiter
sprintf :1, // - formatted print into a string
'sqrt' :1, // - square root function
srand :1, // - seed the random number generator
stat :1, // - get a file's status information
state :1, // - declare and assign a state variable (persistent lexical scoping)
study :1, // - optimize input data for repeated searches
'sub' :1, // - declare a subroutine, possibly anonymously
'substr' :1, // - get or alter a portion of a stirng
symlink :1, // - create a symbolic link to a file
syscall :1, // - execute an arbitrary system call
sysopen :1, // - open a file, pipe, or descriptor
sysread :1, // - fixed-length unbuffered input from a filehandle
sysseek :1, // - position I/O pointer on handle used with sysread and syswrite
system :1, // - run a separate program
syswrite :1, // - fixed-length unbuffered output to a filehandle
tell :1, // - get current seekpointer on a filehandle
telldir :1, // - get current seekpointer on a directory handle
tie :1, // - bind a variable to an object class
tied :1, // - get a reference to the object underlying a tied variable
time :1, // - return number of seconds since 1970
times :1, // - return elapsed time for self and child processes
tr :null, // - transliterate a string
truncate :1, // - shorten a file
uc :1, // - return upper-case version of a string
ucfirst :1, // - return a string with just the next letter in upper case
umask :1, // - set file creation mode mask
undef :1, // - remove a variable or function definition
unlink :1, // - remove one link to a file
unpack :1, // - convert binary structure into normal perl variables
unshift :1, // - prepend more elements to the beginning of a list
untie :1, // - break a tie binding to a variable
use :1, // - load in a module at compile time
utime :1, // - set a file's last access and modify times
values :1, // - return a list of the values in a hash
vec :1, // - test or set particular bits in a string
wait :1, // - wait for any child process to die
waitpid :1, // - wait for a particular child process to die
wantarray :1, // - get void vs scalar vs list context of current subroutine call
warn :1, // - print debugging info
when :1, //
write :1, // - print a picture record
y :null}; // - transliterate a string
var RXstyle="string-2";
var RXmodifiers=/[goseximacplud]/; // NOTE: "m", "s", "y" and "tr" need to correct real modifiers for each regexp type
function tokenChain(stream,state,chain,style,tail){ // NOTE: chain.length > 2 is not working now (it's for s[...][...]geos;)
state.chain=null; // 12 3tail
state.style=null;
state.tail=null;
state.tokenize=function(stream,state){
var e=false,c,i=0;
while(c=stream.next()){
if(c===chain[i]&&!e){
if(chain[++i]!==undefined){
state.chain=chain[i];
state.style=style;
state.tail=tail;}
else if(tail)
stream.eatWhile(tail);
state.tokenize=tokenPerl;
return style;}
e=!e&&c=="\\";}
return style;};
return state.tokenize(stream,state);}
function tokenSOMETHING(stream,state,string){
state.tokenize=function(stream,state){
if(stream.string==string)
state.tokenize=tokenPerl;
stream.skipToEnd();
return "string";};
return state.tokenize(stream,state);}
function tokenPerl(stream,state){
if(stream.eatSpace())
return null;
if(state.chain)
return tokenChain(stream,state,state.chain,state.style,state.tail);
if(stream.match(/^\-?[\d\.]/,false))
if(stream.match(/^(\-?(\d*\.\d+(e[+-]?\d+)?|\d+\.\d*)|0x[\da-fA-F]+|0b[01]+|\d+(e[+-]?\d+)?)/))
return 'number';
if(stream.match(/^<<(?=\w)/)){ // NOTE: <<SOMETHING\n...\nSOMETHING\n
stream.eatWhile(/\w/);
return tokenSOMETHING(stream,state,stream.current().substr(2));}
if(stream.sol()&&stream.match(/^\=item(?!\w)/)){// NOTE: \n=item...\n=cut\n
return tokenSOMETHING(stream,state,'=cut');}
var ch=stream.next();
if(ch=='"'||ch=="'"){ // NOTE: ' or " or <<'SOMETHING'\n...\nSOMETHING\n or <<"SOMETHING"\n...\nSOMETHING\n
if(prefix(stream, 3)=="<<"+ch){
var p=stream.pos;
stream.eatWhile(/\w/);
var n=stream.current().substr(1);
if(n&&stream.eat(ch))
return tokenSOMETHING(stream,state,n);
stream.pos=p;}
return tokenChain(stream,state,[ch],"string");}
if(ch=="q"){
var c=look(stream, -2);
if(!(c&&/\w/.test(c))){
c=look(stream, 0);
if(c=="x"){
c=look(stream, 1);
if(c=="("){
eatSuffix(stream, 2);
return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);}
if(c=="["){
eatSuffix(stream, 2);
return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);}
if(c=="{"){
eatSuffix(stream, 2);
return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);}
if(c=="<"){
eatSuffix(stream, 2);
return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}
if(/[\^'"!~\/]/.test(c)){
eatSuffix(stream, 1);
return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}}
else if(c=="q"){
c=look(stream, 1);
if(c=="("){
eatSuffix(stream, 2);
return tokenChain(stream,state,[")"],"string");}
if(c=="["){
eatSuffix(stream, 2);
return tokenChain(stream,state,["]"],"string");}
if(c=="{"){
eatSuffix(stream, 2);
return tokenChain(stream,state,["}"],"string");}
if(c=="<"){
eatSuffix(stream, 2);
return tokenChain(stream,state,[">"],"string");}
if(/[\^'"!~\/]/.test(c)){
eatSuffix(stream, 1);
return tokenChain(stream,state,[stream.eat(c)],"string");}}
else if(c=="w"){
c=look(stream, 1);
if(c=="("){
eatSuffix(stream, 2);
return tokenChain(stream,state,[")"],"bracket");}
if(c=="["){
eatSuffix(stream, 2);
return tokenChain(stream,state,["]"],"bracket");}
if(c=="{"){
eatSuffix(stream, 2);
return tokenChain(stream,state,["}"],"bracket");}
if(c=="<"){
eatSuffix(stream, 2);
return tokenChain(stream,state,[">"],"bracket");}
if(/[\^'"!~\/]/.test(c)){
eatSuffix(stream, 1);
return tokenChain(stream,state,[stream.eat(c)],"bracket");}}
else if(c=="r"){
c=look(stream, 1);
if(c=="("){
eatSuffix(stream, 2);
return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);}
if(c=="["){
eatSuffix(stream, 2);
return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);}
if(c=="{"){
eatSuffix(stream, 2);
return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);}
if(c=="<"){
eatSuffix(stream, 2);
return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}
if(/[\^'"!~\/]/.test(c)){
eatSuffix(stream, 1);
return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}}
else if(/[\^'"!~\/(\[{<]/.test(c)){
if(c=="("){
eatSuffix(stream, 1);
return tokenChain(stream,state,[")"],"string");}
if(c=="["){
eatSuffix(stream, 1);
return tokenChain(stream,state,["]"],"string");}
if(c=="{"){
eatSuffix(stream, 1);
return tokenChain(stream,state,["}"],"string");}
if(c=="<"){
eatSuffix(stream, 1);
return tokenChain(stream,state,[">"],"string");}
if(/[\^'"!~\/]/.test(c)){
return tokenChain(stream,state,[stream.eat(c)],"string");}}}}
if(ch=="m"){
var c=look(stream, -2);
if(!(c&&/\w/.test(c))){
c=stream.eat(/[(\[{<\^'"!~\/]/);
if(c){
if(/[\^'"!~\/]/.test(c)){
return tokenChain(stream,state,[c],RXstyle,RXmodifiers);}
if(c=="("){
return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);}
if(c=="["){
return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);}
if(c=="{"){
return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);}
if(c=="<"){
return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}}}}
if(ch=="s"){
var c=/[\/>\]})\w]/.test(look(stream, -2));
if(!c){
c=stream.eat(/[(\[{<\^'"!~\/]/);
if(c){
if(c=="[")
return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
if(c=="{")
return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
if(c=="<")
return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
if(c=="(")
return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}
if(ch=="y"){
var c=/[\/>\]})\w]/.test(look(stream, -2));
if(!c){
c=stream.eat(/[(\[{<\^'"!~\/]/);
if(c){
if(c=="[")
return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
if(c=="{")
return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
if(c=="<")
return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
if(c=="(")
return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}
if(ch=="t"){
var c=/[\/>\]})\w]/.test(look(stream, -2));
if(!c){
c=stream.eat("r");if(c){
c=stream.eat(/[(\[{<\^'"!~\/]/);
if(c){
if(c=="[")
return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
if(c=="{")
return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
if(c=="<")
return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
if(c=="(")
return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}}
if(ch=="`"){
return tokenChain(stream,state,[ch],"variable-2");}
if(ch=="/"){
if(!/~\s*$/.test(prefix(stream)))
return "operator";
else
return tokenChain(stream,state,[ch],RXstyle,RXmodifiers);}
if(ch=="$"){
var p=stream.pos;
if(stream.eatWhile(/\d/)||stream.eat("{")&&stream.eatWhile(/\d/)&&stream.eat("}"))
return "variable-2";
else
stream.pos=p;}
if(/[$@%]/.test(ch)){
var p=stream.pos;
if(stream.eat("^")&&stream.eat(/[A-Z]/)||!/[@$%&]/.test(look(stream, -2))&&stream.eat(/[=|\\\-#?@;:&`~\^!\[\]*'"$+.,\/<>()]/)){
var c=stream.current();
if(PERL[c])
return "variable-2";}
stream.pos=p;}
if(/[$@%&]/.test(ch)){
if(stream.eatWhile(/[\w$\[\]]/)||stream.eat("{")&&stream.eatWhile(/[\w$\[\]]/)&&stream.eat("}")){
var c=stream.current();
if(PERL[c])
return "variable-2";
else
return "variable";}}
if(ch=="#"){
if(look(stream, -2)!="$"){
stream.skipToEnd();
return "comment";}}
if(/[:+\-\^*$&%@=<>!?|\/~\.]/.test(ch)){
var p=stream.pos;
stream.eatWhile(/[:+\-\^*$&%@=<>!?|\/~\.]/);
if(PERL[stream.current()])
return "operator";
else
stream.pos=p;}
if(ch=="_"){
if(stream.pos==1){
if(suffix(stream, 6)=="_END__"){
return tokenChain(stream,state,['\0'],"comment");}
else if(suffix(stream, 7)=="_DATA__"){
return tokenChain(stream,state,['\0'],"variable-2");}
else if(suffix(stream, 7)=="_C__"){
return tokenChain(stream,state,['\0'],"string");}}}
if(/\w/.test(ch)){
var p=stream.pos;
if(look(stream, -2)=="{"&&(look(stream, 0)=="}"||stream.eatWhile(/\w/)&&look(stream, 0)=="}"))
return "string";
else
stream.pos=p;}
if(/[A-Z]/.test(ch)){
var l=look(stream, -2);
var p=stream.pos;
stream.eatWhile(/[A-Z_]/);
if(/[\da-z]/.test(look(stream, 0))){
stream.pos=p;}
else{
var c=PERL[stream.current()];
if(!c)
return "meta";
if(c[1])
c=c[0];
if(l!=":"){
if(c==1)
return "keyword";
else if(c==2)
return "def";
else if(c==3)
return "atom";
else if(c==4)
return "operator";
else if(c==5)
return "variable-2";
else
return "meta";}
else
return "meta";}}
if(/[a-zA-Z_]/.test(ch)){
var l=look(stream, -2);
stream.eatWhile(/\w/);
var c=PERL[stream.current()];
if(!c)
return "meta";
if(c[1])
c=c[0];
if(l!=":"){
if(c==1)
return "keyword";
else if(c==2)
return "def";
else if(c==3)
return "atom";
else if(c==4)
return "operator";
else if(c==5)
return "variable-2";
else
return "meta";}
else
return "meta";}
return null;}
return {
startState: function() {
return {
tokenize: tokenPerl,
chain: null,
style: null,
tail: null
};
},
token: function(stream, state) {
return (state.tokenize || tokenPerl)(stream, state);
},
lineComment: '#'
};
});
CodeMirror.registerHelper("wordChars", "perl", /[\w$]/);
CodeMirror.defineMIME("text/x-perl", "perl");
// it's like "peek", but need for look-ahead or look-behind if index < 0
function look(stream, c){
return stream.string.charAt(stream.pos+(c||0));
}
// return a part of prefix of current stream from current position
function prefix(stream, c){
if(c){
var x=stream.pos-c;
return stream.string.substr((x>=0?x:0),c);}
else{
return stream.string.substr(0,stream.pos-1);
}
}
// return a part of suffix of current stream from current position
function suffix(stream, c){
var y=stream.string.length;
var x=y-stream.pos+1;
return stream.string.substr(stream.pos,(c&&c<y?c:x));
}
// eating and vomiting a part of stream from current position
function eatSuffix(stream, c){
var x=stream.pos+c;
var y;
if(x<=0)
stream.pos=0;
else if(x>=(y=stream.string.length-1))
stream.pos=y;
else
stream.pos=x;
}
});
| {
"pile_set_name": "Github"
} |
/* Check compatibility of CET-enabled executable with dlopened legacy
shared object.
Copyright (C) 2019-2020 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <error.h>
#include <stdio.h>
#include <stdlib.h>
extern void foo (void);
int
test (void)
{
foo ();
return 0;
}
| {
"pile_set_name": "Github"
} |
---
title: KSPROPERTY\_MEDIASEEKING\_POSITION
description: KSPROPERTY\_MEDIASEEKING\_POSITION retrieves the media time of a filter.
ms.assetid: 46b246c6-63e9-4f38-91cc-eed762126097
keywords: ["KSPROPERTY_MEDIASEEKING_POSITION Streaming Media Devices"]
topic_type:
- apiref
api_name:
- KSPROPERTY_MEDIASEEKING_POSITION
api_location:
- ks.h
api_type:
- HeaderDef
ms.date: 11/28/2017
ms.localizationpriority: medium
---
# KSPROPERTY\_MEDIASEEKING\_POSITION
KSPROPERTY\_MEDIASEEKING\_POSITION retrieves the media time of a filter.
## <span id="ddk_ksproperty_mediaseeking_position_ks"></span><span id="DDK_KSPROPERTY_MEDIASEEKING_POSITION_KS"></span>
### Usage Summary Table
<table>
<colgroup>
<col width="20%" />
<col width="20%" />
<col width="20%" />
<col width="20%" />
<col width="20%" />
</colgroup>
<thead>
<tr class="header">
<th>Get</th>
<th>Set</th>
<th>Target</th>
<th>Property Descriptor Type</th>
<th>Property Value Type</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><p>Yes</p></td>
<td><p>No</p></td>
<td><p>Filter</p></td>
<td><p><a href="/windows-hardware/drivers/ddi/ks/ns-ks-ksidentifier" data-raw-source="[<strong>KSPROPERTY</strong>](/windows-hardware/drivers/ddi/ks/ns-ks-ksidentifier)"><strong>KSPROPERTY</strong></a></p></td>
<td><p>LONGLONG</p></td>
</tr>
</tbody>
</table>
Remarks
-------
The media time is returned as a value of type LONGLONG.
Requirements
------------
<table>
<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>
<tbody>
<tr class="odd">
<td><p>Header</p></td>
<td>Ks.h (include Ks.h)</td>
</tr>
</tbody>
</table>
## See also
[KSPROPSETID\_MediaSeeking](kspropsetid-mediaseeking.md)
| {
"pile_set_name": "Github"
} |
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2016.03.16 um 01:52:47 PM CET
//
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.onvif.org/ver10/events/wsdl", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.onvif.ver10.events.wsdl;
| {
"pile_set_name": "Github"
} |
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file autoconf.lua
--
-- imports
import("core.base.option")
import("core.project.config")
-- get configs
function _get_configs(package, configs)
-- add prefix
local configs = configs or {}
table.insert(configs, "--prefix=" .. package:installdir())
-- add host for cross-complation
if not configs.host and not package:is_plat(os.subhost()) then
if package:is_plat("iphoneos") then
local triples =
{
arm64 = "aarch64-apple-darwin",
arm64e = "aarch64-apple-darwin",
armv7 = "armv7-apple-darwin",
armv7s = "armv7s-apple-darwin",
i386 = "i386-apple-darwin",
x86_64 = "x86_64-apple-darwin"
}
table.insert(configs, "--host=" .. (triples[package:arch()] or triples.arm64))
elseif package:is_plat("android") then
-- @see https://developer.android.com/ndk/guides/other_build_systems#autoconf
local triples =
{
["armv5te"] = "arm-linux-androideabi", -- deprecated
["armv7-a"] = "arm-linux-androideabi", -- deprecated
["armeabi"] = "arm-linux-androideabi", -- removed in ndk r17
["armeabi-v7a"] = "arm-linux-androideabi",
["arm64-v8a"] = "aarch64-linux-android",
i386 = "i686-linux-android", -- deprecated
x86 = "i686-linux-android",
x86_64 = "x86_64-linux-android",
mips = "mips-linux-android", -- removed in ndk r17
mips64 = "mips64-linux-android" -- removed in ndk r17
}
table.insert(configs, "--host=" .. (triples[package:arch()] or triples["armeabi-v7a"]))
elseif package:is_plat("mingw") then
local triples =
{
i386 = "i686-w64-mingw32",
x86_64 = "x86_64-w64-mingw32"
}
table.insert(configs, "--host=" .. (triples[package:arch()] or triples.i386))
else
raise("autoconf: unknown platform(%s)!", package:plat())
end
end
return configs
end
-- get the build environments
function buildenvs(package)
local envs = {}
if package:is_plat(os.subhost()) then
local cflags = table.join(table.wrap(package:config("cxflags")), package:config("cflags"))
local cxxflags = table.join(table.wrap(package:config("cxflags")), package:config("cxxflags"))
local asflags = table.copy(table.wrap(package:config("asflags")))
local ldflags = table.copy(table.wrap(package:config("ldflags")))
if package:is_plat("linux") and package:is_arch("i386") then
table.insert(cflags, "-m32")
table.insert(cxxflags, "-m32")
table.insert(asflags, "-m32")
table.insert(ldflags, "-m32")
end
envs.CFLAGS = table.concat(cflags, ' ')
envs.CXXFLAGS = table.concat(cxxflags, ' ')
envs.ASFLAGS = table.concat(asflags, ' ')
envs.LDFLAGS = table.concat(ldflags, ' ')
else
local cflags = table.join(table.wrap(package:build_getenv("cxflags")), package:build_getenv("cflags"))
local cxxflags = table.join(table.wrap(package:build_getenv("cxflags")), package:build_getenv("cxxflags"))
envs.CC = package:build_getenv("cc")
envs.AS = package:build_getenv("as")
envs.AR = package:build_getenv("ar")
envs.LD = package:build_getenv("ld")
envs.LDSHARED = package:build_getenv("sh")
envs.CPP = package:build_getenv("cpp")
envs.RANLIB = package:build_getenv("ranlib")
envs.CFLAGS = table.concat(cflags, ' ')
envs.CXXFLAGS = table.concat(cxxflags, ' ')
envs.ASFLAGS = table.concat(table.wrap(package:build_getenv("asflags")), ' ')
envs.ARFLAGS = table.concat(table.wrap(package:build_getenv("arflags")), ' ')
envs.LDFLAGS = table.concat(table.wrap(package:build_getenv("ldflags")), ' ')
envs.SHFLAGS = table.concat(table.wrap(package:build_getenv("shflags")), ' ')
if package:is_plat("mingw") then
-- fix linker error, @see https://github.com/xmake-io/xmake/issues/574
-- libtool: line 1855: lib: command not found
envs.ARFLAGS = nil
local ld = envs.LD
if ld then
if ld:endswith("x86_64-w64-mingw32-g++") then
envs.LD = path.join(path.directory(ld), "x86_64-w64-mingw32-ld")
elseif ld:endswith("i686-w64-mingw32-g++") then
envs.LD = path.join(path.directory(ld), "i686-w64-mingw32-ld")
end
end
end
end
local ACLOCAL_PATH = {}
local PKG_CONFIG_PATH = {}
for _, dep in ipairs(package:orderdeps()) do
local pkgconfig = path.join(dep:installdir(), "lib", "pkgconfig")
if os.isdir(pkgconfig) then
table.insert(PKG_CONFIG_PATH, pkgconfig)
end
local aclocal = path.join(dep:installdir(), "share", "aclocal")
if os.isdir(aclocal) then
table.insert(ACLOCAL_PATH, aclocal)
end
end
envs.ACLOCAL_PATH = path.joinenv(ACLOCAL_PATH)
envs.PKG_CONFIG_PATH = path.joinenv(PKG_CONFIG_PATH)
return envs
end
-- configure package
function configure(package, configs, opt)
-- init options
opt = opt or {}
-- generate configure file
if not os.isfile("configure") then
if os.isfile("autogen.sh") then
os.vrunv("sh", {"./autogen.sh"})
elseif os.isfile("configure.ac") then
os.vrun("autoreconf --install --symlink")
end
end
-- pass configurations
local argv = {}
for name, value in pairs(_get_configs(package, configs)) do
value = tostring(value):trim()
if value ~= "" then
if type(name) == "number" then
table.insert(argv, value)
else
table.insert(argv, "--" .. name .. "=" .. value)
end
end
end
-- do configure
os.vrunv("./configure", argv, {envs = opt.envs or buildenvs(package)})
end
-- install package
function install(package, configs, opt)
-- do configure
configure(package, configs, opt)
-- do make and install
local njob = tostring(math.ceil(os.cpuinfo().ncpu * 3 / 2))
local argv = {"-j" .. njob}
if option.get("verbose") then
table.insert(argv, "V=1")
end
if is_host("bsd") then
os.vrunv("gmake", argv)
os.vrun("gmake install")
else
os.vrunv("make", argv)
os.vrun("make install")
end
end
| {
"pile_set_name": "Github"
} |
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.
*/
export const IntersectionObserverSupport = {
name: 'IntersectionObserver',
supported: async () => {
return 'IntersectionObserver' in self &&
'IntersectionObserverEntry' in self;
}
};
| {
"pile_set_name": "Github"
} |
const Logger = require('@hkube/logger');
const { taskStatuses } = require('@hkube/consts');
const aigle = require('aigle');
const _ = require('lodash');
const components = require('./consts/component-name');
const log = Logger.GetLogFromContainer();
class heuristicRunner {
constructor() {
aigle.mixin(_);
this.config = null;
this.heuristicMap = [];
}
init(heuristicsWeights) {
// this.config = config;
this.heuristicsWeights = heuristicsWeights;
log.info('heuristic wights was set', { component: components.HEURISTIC_RUNNER });
}
// add heuristic
addHeuristicToQueue(heuristic) {
if (this.heuristicsWeights[heuristic.name]) {
this.heuristicMap.push({ name: heuristic.name, heuristic: heuristic.algorithm(this.heuristicsWeights[heuristic.name]), weight: this.heuristicsWeights[heuristic.name] });
}
else {
log.info('couldnt find weight for heuristic ', { component: components.HEURISTIC_RUNNER });
}
}
async run(job) {
let score = 0;
if (job.status !== taskStatuses.PRESCHEDULE) {
log.debug('start running heuristic for ', { component: components.HEURISTIC_RUNNER });
score = await this.heuristicMap.reduce((result, algorithm) => {
const heuristicScore = algorithm.heuristic(job);
job.calculated.latestScores[algorithm.name] = heuristicScore; // eslint-disable-line
log.debug(
`during score calculation for ${algorithm.name} in ${job.jobId}
score:${heuristicScore} calculated:${result + heuristicScore}`,
{ component: components.HEURISTIC_RUNNER }
);
return result + heuristicScore;
}, 0);
}
return { ...job, calculated: { ...job.calculated, score } };
}
}
module.exports = heuristicRunner;
| {
"pile_set_name": "Github"
} |
ace.define("ace/theme/crimson_editor",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
exports.isDark = false;
exports.cssText = ".ace-crimson-editor .ace_gutter {\
background: #ebebeb;\
color: #333;\
overflow : hidden;\
}\
.ace-crimson-editor .ace_gutter-layer {\
width: 100%;\
text-align: right;\
}\
.ace-crimson-editor .ace_print-margin {\
width: 1px;\
background: #e8e8e8;\
}\
.ace-crimson-editor {\
background-color: #FFFFFF;\
color: rgb(64, 64, 64);\
}\
.ace-crimson-editor .ace_cursor {\
color: black;\
}\
.ace-crimson-editor .ace_invisible {\
color: rgb(191, 191, 191);\
}\
.ace-crimson-editor .ace_identifier {\
color: black;\
}\
.ace-crimson-editor .ace_keyword {\
color: blue;\
}\
.ace-crimson-editor .ace_constant.ace_buildin {\
color: rgb(88, 72, 246);\
}\
.ace-crimson-editor .ace_constant.ace_language {\
color: rgb(255, 156, 0);\
}\
.ace-crimson-editor .ace_constant.ace_library {\
color: rgb(6, 150, 14);\
}\
.ace-crimson-editor .ace_invalid {\
text-decoration: line-through;\
color: rgb(224, 0, 0);\
}\
.ace-crimson-editor .ace_fold {\
}\
.ace-crimson-editor .ace_support.ace_function {\
color: rgb(192, 0, 0);\
}\
.ace-crimson-editor .ace_support.ace_constant {\
color: rgb(6, 150, 14);\
}\
.ace-crimson-editor .ace_support.ace_type,\
.ace-crimson-editor .ace_support.ace_class {\
color: rgb(109, 121, 222);\
}\
.ace-crimson-editor .ace_keyword.ace_operator {\
color: rgb(49, 132, 149);\
}\
.ace-crimson-editor .ace_string {\
color: rgb(128, 0, 128);\
}\
.ace-crimson-editor .ace_comment {\
color: rgb(76, 136, 107);\
}\
.ace-crimson-editor .ace_comment.ace_doc {\
color: rgb(0, 102, 255);\
}\
.ace-crimson-editor .ace_comment.ace_doc.ace_tag {\
color: rgb(128, 159, 191);\
}\
.ace-crimson-editor .ace_constant.ace_numeric {\
color: rgb(0, 0, 64);\
}\
.ace-crimson-editor .ace_variable {\
color: rgb(0, 64, 128);\
}\
.ace-crimson-editor .ace_xml-pe {\
color: rgb(104, 104, 91);\
}\
.ace-crimson-editor .ace_marker-layer .ace_selection {\
background: rgb(181, 213, 255);\
}\
.ace-crimson-editor .ace_marker-layer .ace_step {\
background: rgb(252, 255, 0);\
}\
.ace-crimson-editor .ace_marker-layer .ace_stack {\
background: rgb(164, 229, 101);\
}\
.ace-crimson-editor .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgb(192, 192, 192);\
}\
.ace-crimson-editor .ace_marker-layer .ace_active-line {\
background: rgb(232, 242, 254);\
}\
.ace-crimson-editor .ace_gutter-active-line {\
background-color : #dcdcdc;\
}\
.ace-crimson-editor .ace_meta.ace_tag {\
color:rgb(28, 2, 255);\
}\
.ace-crimson-editor .ace_marker-layer .ace_selected-word {\
background: rgb(250, 250, 255);\
border: 1px solid rgb(200, 200, 250);\
}\
.ace-crimson-editor .ace_string.ace_regex {\
color: rgb(192, 0, 192);\
}\
.ace-crimson-editor .ace_indent-guide {\
background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\
}";
exports.cssClass = "ace-crimson-editor";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
| {
"pile_set_name": "Github"
} |
<testcase>
<info>
<keywords>
HTTP
HTTP POST
followlocation
</keywords>
</info>
#
# Server-side
<reply>
<data>
HTTP/1.1 301 OK swsclose
Location: moo.html&testcase=/10120002
Date: Thu, 09 Nov 2010 14:49:00 GMT
Connection: close
</data>
<data2>
HTTP/1.1 200 OK swsclose
Location: this should be ignored
Date: Thu, 09 Nov 2010 14:49:00 GMT
Connection: close
body
</data2>
<datacheck>
HTTP/1.1 301 OK swsclose
Location: moo.html&testcase=/10120002
Date: Thu, 09 Nov 2010 14:49:00 GMT
Connection: close
HTTP/1.1 200 OK swsclose
Location: this should be ignored
Date: Thu, 09 Nov 2010 14:49:00 GMT
Connection: close
body
</datacheck>
</reply>
#
# Client-side
<client>
<server>
http
</server>
<name>
HTTP POST with 301 redirect and --post301
</name>
<command>
http://%HOSTIP:%HTTPPORT/blah/1012 -L -d "moo" --post301
</command>
</client>
#
# Verify data after the test has been "shot"
<verify>
<strip>
^User-Agent:.*
</strip>
<protocol nonewline="yes">
POST /blah/1012 HTTP/1.1
Host: %HOSTIP:%HTTPPORT
Accept: */*
Content-Length: 3
Content-Type: application/x-www-form-urlencoded
mooPOST /blah/moo.html&testcase=/10120002 HTTP/1.1
User-Agent: curl/7.10 (i686-pc-linux-gnu) libcurl/7.10 OpenSSL/0.9.6c ipv6 zlib/1.1.3
Host: %HOSTIP:%HTTPPORT
Accept: */*
Content-Length: 3
Content-Type: application/x-www-form-urlencoded
moo
</protocol>
</verify>
</testcase>
| {
"pile_set_name": "Github"
} |
package typings.devtoolsProtocol.mod.Protocol.Debugger
import typings.devtoolsProtocol.devtoolsProtocolStrings.all
import typings.devtoolsProtocol.devtoolsProtocolStrings.none_
import typings.devtoolsProtocol.devtoolsProtocolStrings.uncaught
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation._
/* Rewritten from type alias, can be one of:
- typings.devtoolsProtocol.devtoolsProtocolStrings.none_
- typings.devtoolsProtocol.devtoolsProtocolStrings.uncaught
- typings.devtoolsProtocol.devtoolsProtocolStrings.all
*/
trait SetPauseOnExceptionsRequestState extends js.Object
object SetPauseOnExceptionsRequestState {
@scala.inline
def All: all = "all".asInstanceOf[all]
@scala.inline
def None: none_ = "none".asInstanceOf[none_]
@scala.inline
def Uncaught: uncaught = "uncaught".asInstanceOf[uncaught]
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: [email protected]
* Site: http://se.solovyev.org
*/
package org.solovyev.android.keyboard;
import android.content.Context;
import android.inputmethodservice.Keyboard;
import javax.annotation.Nonnull;
/**
* User: serso
* Date: 11/3/12
* Time: 5:57 PM
*/
public class CalculatorKeyboardController extends DragKeyboardController {
@Override
protected DragAKeyboard createKeyboardDef(@Nonnull Context context) {
final int operatorButtonColor = R.drawable.metro_dark_button;
final DragAKeyboard.KeyboardDef result = new DragAKeyboard.KeyboardDef();
final DragAKeyboard.RowDef firstRow = new DragAKeyboard.RowDef();
firstRow.add(DragAKeyboardButtonDefImpl.newInstance("7", "i", null, "!", "ob:"));
firstRow.add(DragAKeyboardButtonDefImpl.newInstance("8", "ln", null, "lg", "od:"));
firstRow.add(DragAKeyboardButtonDefImpl.newInstance("9", "PI", null, "e", "ox:"));
firstRow.add(DragAKeyboardButtonDefImpl.newInstance("*", "^", null, "^2", null, operatorButtonColor));
firstRow.add(DragAKeyboardButtonDefImpl.newInstance("C", CalculatorKeyboardController.KEYCODE_CLEAR));
result.add(firstRow);
final DragAKeyboard.RowDef secondRow = new DragAKeyboard.RowDef();
secondRow.add(DragAKeyboardButtonDefImpl.newInstance("4", "x", null, "y", "D"));
secondRow.add(DragAKeyboardButtonDefImpl.newInstance("5", "t", null, "j", "E"));
secondRow.add(DragAKeyboardButtonDefImpl.newInstance("6", null, null, null, "F"));
secondRow.add(DragAKeyboardButtonDefImpl.newInstance("/", "%", null, null, null, operatorButtonColor));
secondRow.add(DragAKeyboardButtonDefImpl.newDrawableInstance(R.drawable.kb_delete, Keyboard.KEYCODE_DELETE));
result.add(secondRow);
final DragAKeyboard.RowDef thirdRow = new DragAKeyboard.RowDef();
thirdRow.add(DragAKeyboardButtonDefImpl.newInstance("1", "sin", null, "asin", "A"));
thirdRow.add(DragAKeyboardButtonDefImpl.newInstance("2", "cos", null, "acos", "B"));
thirdRow.add(DragAKeyboardButtonDefImpl.newInstance("3", "tan", null, "atan", "C"));
thirdRow.add(DragAKeyboardButtonDefImpl.newInstance("+", null, null, "E", null, operatorButtonColor));
thirdRow.add(DragAKeyboardButtonDefImpl.newDrawableInstance(R.drawable.kb_copy, CalculatorKeyboardController.KEYCODE_COPY));
result.add(thirdRow);
final DragAKeyboard.RowDef fourthRow = new DragAKeyboard.RowDef();
fourthRow.add(DragAKeyboardButtonDefImpl.newInstance("()", "(", null, ")", null));
fourthRow.add(DragAKeyboardButtonDefImpl.newInstance("0", "00", null, "000", null));
fourthRow.add(DragAKeyboardButtonDefImpl.newInstance(".", ",", null, null, null));
fourthRow.add(DragAKeyboardButtonDefImpl.newInstance("-", null, null, null, null, operatorButtonColor));
fourthRow.add(DragAKeyboardButtonDefImpl.newDrawableInstance(R.drawable.kb_paste, CalculatorKeyboardController.KEYCODE_PASTE));
result.add(fourthRow);
return new DragAKeyboard("calculator", result);
}
}
| {
"pile_set_name": "Github"
} |
var webpack = require("webpack");
var glob = require("glob")
var path = require("path");
var staticPath = path.join(__dirname , "static");
var array = glob.sync( "static/**/load.*.js") ;
var entryMap = {};
for(var i = 0 ; i <array.length ; i ++){
var filePath = array[i];
var entryName = filePath.match(/load\.(.+)\.js/i , filePath )[1];
entryMap["entry." + entryName + ""] = filePath.replace("static" , ".");
}
entryMap["common"] = [
"underscore" ,
"./lib/underscore/underscore.ext" ,
"jquery",
"expose?moment!moment",
"./lib/bootstrap/bootstrap",
"./lib/bootstrap/bootstrap-datetimepicker.min"
]
module.exports = {
context: staticPath,
entry: entryMap,
output: {
path: path.join(__dirname , "static"),
filename: './[name].js'
},
resolve: {
modulesDirectories : [ 'node_modules' , path.join( __dirname, "static/common" ) , path.join( __dirname, "static/lib" ) , staticPath]
},
module : {
loaders: [
{ test: /\.css/, loader: "css!style" },
{ test: /\.ejs/, loader: "ejs" },
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin( 'common' , 'common.js' ) ,
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
_: 'underscore'
})
]
}; | {
"pile_set_name": "Github"
} |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_NESTBYVALUE_H
#define EIGEN_NESTBYVALUE_H
namespace Eigen {
namespace internal {
template<typename ExpressionType>
struct traits<NestByValue<ExpressionType> > : public traits<ExpressionType>
{};
}
/** \class NestByValue
* \ingroup Core_Module
*
* \brief Expression which must be nested by value
*
* \tparam ExpressionType the type of the object of which we are requiring nesting-by-value
*
* This class is the return type of MatrixBase::nestByValue()
* and most of the time this is the only way it is used.
*
* \sa MatrixBase::nestByValue()
*/
template<typename ExpressionType> class NestByValue
: public internal::dense_xpr_base< NestByValue<ExpressionType> >::type
{
public:
typedef typename internal::dense_xpr_base<NestByValue>::type Base;
EIGEN_DENSE_PUBLIC_INTERFACE(NestByValue)
EIGEN_DEVICE_FUNC explicit inline NestByValue(const ExpressionType& matrix) : m_expression(matrix) {}
EIGEN_DEVICE_FUNC inline Index rows() const { return m_expression.rows(); }
EIGEN_DEVICE_FUNC inline Index cols() const { return m_expression.cols(); }
EIGEN_DEVICE_FUNC inline Index outerStride() const { return m_expression.outerStride(); }
EIGEN_DEVICE_FUNC inline Index innerStride() const { return m_expression.innerStride(); }
EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index row, Index col) const
{
return m_expression.coeff(row, col);
}
EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index row, Index col)
{
return m_expression.const_cast_derived().coeffRef(row, col);
}
EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index index) const
{
return m_expression.coeff(index);
}
EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index index)
{
return m_expression.const_cast_derived().coeffRef(index);
}
template<int LoadMode>
inline const PacketScalar packet(Index row, Index col) const
{
return m_expression.template packet<LoadMode>(row, col);
}
template<int LoadMode>
inline void writePacket(Index row, Index col, const PacketScalar& x)
{
m_expression.const_cast_derived().template writePacket<LoadMode>(row, col, x);
}
template<int LoadMode>
inline const PacketScalar packet(Index index) const
{
return m_expression.template packet<LoadMode>(index);
}
template<int LoadMode>
inline void writePacket(Index index, const PacketScalar& x)
{
m_expression.const_cast_derived().template writePacket<LoadMode>(index, x);
}
EIGEN_DEVICE_FUNC operator const ExpressionType&() const { return m_expression; }
protected:
const ExpressionType m_expression;
};
/** \returns an expression of the temporary version of *this.
*/
template<typename Derived>
inline const NestByValue<Derived>
DenseBase<Derived>::nestByValue() const
{
return NestByValue<Derived>(derived());
}
} // end namespace Eigen
#endif // EIGEN_NESTBYVALUE_H
| {
"pile_set_name": "Github"
} |
import createReactContext from 'create-react-context'
/* eslint-disable no-console */
const defaultContextState = {
subscribeToMouseOver: () => {
console.warn('"subscribeToMouseOver" default func is being used')
}
}
/* eslint-enable */
const { Consumer, Provider } = createReactContext(defaultContextState)
export const MarkerCanvasProvider = Provider
export const MarkerCanvasConsumer = Consumer
| {
"pile_set_name": "Github"
} |
/*
* contrib/btree_gist/btree_time.c
*/
#include "postgres.h"
#include "btree_gist.h"
#include "btree_utils_num.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/timestamp.h"
typedef struct
{
TimeADT lower;
TimeADT upper;
} timeKEY;
/*
** time ops
*/
PG_FUNCTION_INFO_V1(gbt_time_compress);
PG_FUNCTION_INFO_V1(gbt_timetz_compress);
PG_FUNCTION_INFO_V1(gbt_time_fetch);
PG_FUNCTION_INFO_V1(gbt_time_union);
PG_FUNCTION_INFO_V1(gbt_time_picksplit);
PG_FUNCTION_INFO_V1(gbt_time_consistent);
PG_FUNCTION_INFO_V1(gbt_time_distance);
PG_FUNCTION_INFO_V1(gbt_timetz_consistent);
PG_FUNCTION_INFO_V1(gbt_time_penalty);
PG_FUNCTION_INFO_V1(gbt_time_same);
#ifdef USE_FLOAT8_BYVAL
#define TimeADTGetDatumFast(X) TimeADTGetDatum(X)
#else
#define TimeADTGetDatumFast(X) PointerGetDatum(&(X))
#endif
static bool
gbt_timegt(const void *a, const void *b, FmgrInfo *flinfo)
{
const TimeADT *aa = (const TimeADT *) a;
const TimeADT *bb = (const TimeADT *) b;
return DatumGetBool(DirectFunctionCall2(time_gt,
TimeADTGetDatumFast(*aa),
TimeADTGetDatumFast(*bb)));
}
static bool
gbt_timege(const void *a, const void *b, FmgrInfo *flinfo)
{
const TimeADT *aa = (const TimeADT *) a;
const TimeADT *bb = (const TimeADT *) b;
return DatumGetBool(DirectFunctionCall2(time_ge,
TimeADTGetDatumFast(*aa),
TimeADTGetDatumFast(*bb)));
}
static bool
gbt_timeeq(const void *a, const void *b, FmgrInfo *flinfo)
{
const TimeADT *aa = (const TimeADT *) a;
const TimeADT *bb = (const TimeADT *) b;
return DatumGetBool(DirectFunctionCall2(time_eq,
TimeADTGetDatumFast(*aa),
TimeADTGetDatumFast(*bb)));
}
static bool
gbt_timele(const void *a, const void *b, FmgrInfo *flinfo)
{
const TimeADT *aa = (const TimeADT *) a;
const TimeADT *bb = (const TimeADT *) b;
return DatumGetBool(DirectFunctionCall2(time_le,
TimeADTGetDatumFast(*aa),
TimeADTGetDatumFast(*bb)));
}
static bool
gbt_timelt(const void *a, const void *b, FmgrInfo *flinfo)
{
const TimeADT *aa = (const TimeADT *) a;
const TimeADT *bb = (const TimeADT *) b;
return DatumGetBool(DirectFunctionCall2(time_lt,
TimeADTGetDatumFast(*aa),
TimeADTGetDatumFast(*bb)));
}
static int
gbt_timekey_cmp(const void *a, const void *b, FmgrInfo *flinfo)
{
timeKEY *ia = (timeKEY *) (((const Nsrt *) a)->t);
timeKEY *ib = (timeKEY *) (((const Nsrt *) b)->t);
int res;
res = DatumGetInt32(DirectFunctionCall2(time_cmp, TimeADTGetDatumFast(ia->lower), TimeADTGetDatumFast(ib->lower)));
if (res == 0)
return DatumGetInt32(DirectFunctionCall2(time_cmp, TimeADTGetDatumFast(ia->upper), TimeADTGetDatumFast(ib->upper)));
return res;
}
static float8
gbt_time_dist(const void *a, const void *b, FmgrInfo *flinfo)
{
const TimeADT *aa = (const TimeADT *) a;
const TimeADT *bb = (const TimeADT *) b;
Interval *i;
i = DatumGetIntervalP(DirectFunctionCall2(time_mi_time,
TimeADTGetDatumFast(*aa),
TimeADTGetDatumFast(*bb)));
return (float8) Abs(INTERVAL_TO_SEC(i));
}
static const gbtree_ninfo tinfo =
{
gbt_t_time,
sizeof(TimeADT),
16, /* sizeof(gbtreekey16) */
gbt_timegt,
gbt_timege,
gbt_timeeq,
gbt_timele,
gbt_timelt,
gbt_timekey_cmp,
gbt_time_dist
};
PG_FUNCTION_INFO_V1(time_dist);
Datum
time_dist(PG_FUNCTION_ARGS)
{
Datum diff = DirectFunctionCall2(time_mi_time,
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1));
PG_RETURN_INTERVAL_P(abs_interval(DatumGetIntervalP(diff)));
}
/**************************************************
* time ops
**************************************************/
Datum
gbt_time_compress(PG_FUNCTION_ARGS)
{
GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
PG_RETURN_POINTER(gbt_num_compress(entry, &tinfo));
}
Datum
gbt_timetz_compress(PG_FUNCTION_ARGS)
{
GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
GISTENTRY *retval;
if (entry->leafkey)
{
timeKEY *r = (timeKEY *) palloc(sizeof(timeKEY));
TimeTzADT *tz = DatumGetTimeTzADTP(entry->key);
TimeADT tmp;
retval = palloc(sizeof(GISTENTRY));
/* We are using the time + zone only to compress */
tmp = tz->time + (tz->zone * INT64CONST(1000000));
r->lower = r->upper = tmp;
gistentryinit(*retval, PointerGetDatum(r),
entry->rel, entry->page,
entry->offset, false);
}
else
retval = entry;
PG_RETURN_POINTER(retval);
}
Datum
gbt_time_fetch(PG_FUNCTION_ARGS)
{
GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
PG_RETURN_POINTER(gbt_num_fetch(entry, &tinfo));
}
Datum
gbt_time_consistent(PG_FUNCTION_ARGS)
{
GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
TimeADT query = PG_GETARG_TIMEADT(1);
StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
/* Oid subtype = PG_GETARG_OID(3); */
bool *recheck = (bool *) PG_GETARG_POINTER(4);
timeKEY *kkk = (timeKEY *) DatumGetPointer(entry->key);
GBT_NUMKEY_R key;
/* All cases served by this function are exact */
*recheck = false;
key.lower = (GBT_NUMKEY *) &kkk->lower;
key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_BOOL(gbt_num_consistent(&key, (void *) &query, &strategy,
GIST_LEAF(entry), &tinfo, fcinfo->flinfo));
}
Datum
gbt_time_distance(PG_FUNCTION_ARGS)
{
GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
TimeADT query = PG_GETARG_TIMEADT(1);
/* Oid subtype = PG_GETARG_OID(3); */
timeKEY *kkk = (timeKEY *) DatumGetPointer(entry->key);
GBT_NUMKEY_R key;
key.lower = (GBT_NUMKEY *) &kkk->lower;
key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_FLOAT8(gbt_num_distance(&key, (void *) &query, GIST_LEAF(entry),
&tinfo, fcinfo->flinfo));
}
Datum
gbt_timetz_consistent(PG_FUNCTION_ARGS)
{
GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
TimeTzADT *query = PG_GETARG_TIMETZADT_P(1);
StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
/* Oid subtype = PG_GETARG_OID(3); */
bool *recheck = (bool *) PG_GETARG_POINTER(4);
timeKEY *kkk = (timeKEY *) DatumGetPointer(entry->key);
TimeADT qqq;
GBT_NUMKEY_R key;
/* All cases served by this function are inexact */
*recheck = true;
qqq = query->time + (query->zone * INT64CONST(1000000));
key.lower = (GBT_NUMKEY *) &kkk->lower;
key.upper = (GBT_NUMKEY *) &kkk->upper;
PG_RETURN_BOOL(gbt_num_consistent(&key, (void *) &qqq, &strategy,
GIST_LEAF(entry), &tinfo, fcinfo->flinfo));
}
Datum
gbt_time_union(PG_FUNCTION_ARGS)
{
GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
void *out = palloc(sizeof(timeKEY));
*(int *) PG_GETARG_POINTER(1) = sizeof(timeKEY);
PG_RETURN_POINTER(gbt_num_union((void *) out, entryvec, &tinfo, fcinfo->flinfo));
}
Datum
gbt_time_penalty(PG_FUNCTION_ARGS)
{
timeKEY *origentry = (timeKEY *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(0))->key);
timeKEY *newentry = (timeKEY *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(1))->key);
float *result = (float *) PG_GETARG_POINTER(2);
Interval *intr;
double res;
double res2;
intr = DatumGetIntervalP(DirectFunctionCall2(time_mi_time,
TimeADTGetDatumFast(newentry->upper),
TimeADTGetDatumFast(origentry->upper)));
res = INTERVAL_TO_SEC(intr);
res = Max(res, 0);
intr = DatumGetIntervalP(DirectFunctionCall2(time_mi_time,
TimeADTGetDatumFast(origentry->lower),
TimeADTGetDatumFast(newentry->lower)));
res2 = INTERVAL_TO_SEC(intr);
res2 = Max(res2, 0);
res += res2;
*result = 0.0;
if (res > 0)
{
intr = DatumGetIntervalP(DirectFunctionCall2(time_mi_time,
TimeADTGetDatumFast(origentry->upper),
TimeADTGetDatumFast(origentry->lower)));
*result += FLT_MIN;
*result += (float) (res / (res + INTERVAL_TO_SEC(intr)));
*result *= (FLT_MAX / (((GISTENTRY *) PG_GETARG_POINTER(0))->rel->rd_att->natts + 1));
}
PG_RETURN_POINTER(result);
}
Datum
gbt_time_picksplit(PG_FUNCTION_ARGS)
{
PG_RETURN_POINTER(gbt_num_picksplit((GistEntryVector *) PG_GETARG_POINTER(0),
(GIST_SPLITVEC *) PG_GETARG_POINTER(1),
&tinfo, fcinfo->flinfo));
}
Datum
gbt_time_same(PG_FUNCTION_ARGS)
{
timeKEY *b1 = (timeKEY *) PG_GETARG_POINTER(0);
timeKEY *b2 = (timeKEY *) PG_GETARG_POINTER(1);
bool *result = (bool *) PG_GETARG_POINTER(2);
*result = gbt_num_same((void *) b1, (void *) b2, &tinfo, fcinfo->flinfo);
PG_RETURN_POINTER(result);
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.hash;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import java.util.Random;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
/**
* Benchmarks for comparing {@link Checksum}s and {@link HashFunction}s that wrap {@link Checksum}s.
*
* <p>Parameters for the benchmark are:
*
* <ul>
* <li>size: The length of the byte array to hash.
* </ul>
*
* @author Colin Decker
*/
public class ChecksumBenchmark {
// Use a constant seed for all of the benchmarks to ensure apples to apples comparisons.
private static final int RANDOM_SEED = new Random().nextInt();
@Param({"10", "1000", "100000", "1000000"})
private int size;
private byte[] testBytes;
@BeforeExperiment
void setUp() {
testBytes = new byte[size];
new Random(RANDOM_SEED).nextBytes(testBytes);
}
// CRC32
@Benchmark
byte crc32HashFunction(int reps) {
return runHashFunction(reps, Hashing.crc32());
}
@Benchmark
byte crc32Checksum(int reps) throws Exception {
byte result = 0x01;
for (int i = 0; i < reps; i++) {
CRC32 checksum = new CRC32();
checksum.update(testBytes);
result = (byte) (result ^ checksum.getValue());
}
return result;
}
// Adler32
@Benchmark
byte adler32HashFunction(int reps) {
return runHashFunction(reps, Hashing.adler32());
}
@Benchmark
byte adler32Checksum(int reps) throws Exception {
byte result = 0x01;
for (int i = 0; i < reps; i++) {
Adler32 checksum = new Adler32();
checksum.update(testBytes);
result = (byte) (result ^ checksum.getValue());
}
return result;
}
// Helpers + main
private byte runHashFunction(int reps, HashFunction hashFunction) {
byte result = 0x01;
// Trick the JVM to prevent it from using the hash function non-polymorphically
result ^= Hashing.crc32().hashInt(reps).asBytes()[0];
result ^= Hashing.adler32().hashInt(reps).asBytes()[0];
for (int i = 0; i < reps; i++) {
result ^= hashFunction.hashBytes(testBytes).asBytes()[0];
}
return result;
}
}
| {
"pile_set_name": "Github"
} |
var mapping = require('./_mapping'),
fallbackHolder = require('./placeholder');
/** Built-in value reference. */
var push = Array.prototype.push;
/**
* Creates a function, with an arity of `n`, that invokes `func` with the
* arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} n The arity of the new function.
* @returns {Function} Returns the new function.
*/
function baseArity(func, n) {
return n == 2
? function(a, b) { return func.apply(undefined, arguments); }
: function(a) { return func.apply(undefined, arguments); };
}
/**
* Creates a function that invokes `func`, with up to `n` arguments, ignoring
* any additional arguments.
*
* @private
* @param {Function} func The function to cap arguments for.
* @param {number} n The arity cap.
* @returns {Function} Returns the new function.
*/
function baseAry(func, n) {
return n == 2
? function(a, b) { return func(a, b); }
: function(a) { return func(a); };
}
/**
* Creates a clone of `array`.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the cloned array.
*/
function cloneArray(array) {
var length = array ? array.length : 0,
result = Array(length);
while (length--) {
result[length] = array[length];
}
return result;
}
/**
* Creates a function that clones a given object using the assignment `func`.
*
* @private
* @param {Function} func The assignment function.
* @returns {Function} Returns the new cloner function.
*/
function createCloner(func) {
return function(object) {
return func({}, object);
};
}
/**
* A specialized version of `_.spread` which flattens the spread array into
* the arguments of the invoked `func`.
*
* @private
* @param {Function} func The function to spread arguments over.
* @param {number} start The start position of the spread.
* @returns {Function} Returns the new function.
*/
function flatSpread(func, start) {
return function() {
var length = arguments.length,
lastIndex = length - 1,
args = Array(length);
while (length--) {
args[length] = arguments[length];
}
var array = args[start],
otherArgs = args.slice(0, start);
if (array) {
push.apply(otherArgs, array);
}
if (start != lastIndex) {
push.apply(otherArgs, args.slice(start + 1));
}
return func.apply(this, otherArgs);
};
}
/**
* Creates a function that wraps `func` and uses `cloner` to clone the first
* argument it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} cloner The function to clone arguments.
* @returns {Function} Returns the new immutable function.
*/
function wrapImmutable(func, cloner) {
return function() {
var length = arguments.length;
if (!length) {
return;
}
var args = Array(length);
while (length--) {
args[length] = arguments[length];
}
var result = args[0] = cloner.apply(undefined, args);
func.apply(undefined, args);
return result;
};
}
/**
* The base implementation of `convert` which accepts a `util` object of methods
* required to perform conversions.
*
* @param {Object} util The util object.
* @param {string} name The name of the function to convert.
* @param {Function} func The function to convert.
* @param {Object} [options] The options object.
* @param {boolean} [options.cap=true] Specify capping iteratee arguments.
* @param {boolean} [options.curry=true] Specify currying.
* @param {boolean} [options.fixed=true] Specify fixed arity.
* @param {boolean} [options.immutable=true] Specify immutable operations.
* @param {boolean} [options.rearg=true] Specify rearranging arguments.
* @returns {Function|Object} Returns the converted function or object.
*/
function baseConvert(util, name, func, options) {
var setPlaceholder,
isLib = typeof name == 'function',
isObj = name === Object(name);
if (isObj) {
options = func;
func = name;
name = undefined;
}
if (func == null) {
throw new TypeError;
}
options || (options = {});
var config = {
'cap': 'cap' in options ? options.cap : true,
'curry': 'curry' in options ? options.curry : true,
'fixed': 'fixed' in options ? options.fixed : true,
'immutable': 'immutable' in options ? options.immutable : true,
'rearg': 'rearg' in options ? options.rearg : true
};
var forceCurry = ('curry' in options) && options.curry,
forceFixed = ('fixed' in options) && options.fixed,
forceRearg = ('rearg' in options) && options.rearg,
placeholder = isLib ? func : fallbackHolder,
pristine = isLib ? func.runInContext() : undefined;
var helpers = isLib ? func : {
'ary': util.ary,
'assign': util.assign,
'clone': util.clone,
'curry': util.curry,
'forEach': util.forEach,
'isArray': util.isArray,
'isFunction': util.isFunction,
'iteratee': util.iteratee,
'keys': util.keys,
'rearg': util.rearg,
'toInteger': util.toInteger,
'toPath': util.toPath
};
var ary = helpers.ary,
assign = helpers.assign,
clone = helpers.clone,
curry = helpers.curry,
each = helpers.forEach,
isArray = helpers.isArray,
isFunction = helpers.isFunction,
keys = helpers.keys,
rearg = helpers.rearg,
toInteger = helpers.toInteger,
toPath = helpers.toPath;
var aryMethodKeys = keys(mapping.aryMethod);
var wrappers = {
'castArray': function(castArray) {
return function() {
var value = arguments[0];
return isArray(value)
? castArray(cloneArray(value))
: castArray.apply(undefined, arguments);
};
},
'iteratee': function(iteratee) {
return function() {
var func = arguments[0],
arity = arguments[1],
result = iteratee(func, arity),
length = result.length;
if (config.cap && typeof arity == 'number') {
arity = arity > 2 ? (arity - 2) : 1;
return (length && length <= arity) ? result : baseAry(result, arity);
}
return result;
};
},
'mixin': function(mixin) {
return function(source) {
var func = this;
if (!isFunction(func)) {
return mixin(func, Object(source));
}
var pairs = [];
each(keys(source), function(key) {
if (isFunction(source[key])) {
pairs.push([key, func.prototype[key]]);
}
});
mixin(func, Object(source));
each(pairs, function(pair) {
var value = pair[1];
if (isFunction(value)) {
func.prototype[pair[0]] = value;
} else {
delete func.prototype[pair[0]];
}
});
return func;
};
},
'nthArg': function(nthArg) {
return function(n) {
var arity = n < 0 ? 1 : (toInteger(n) + 1);
return curry(nthArg(n), arity);
};
},
'rearg': function(rearg) {
return function(func, indexes) {
var arity = indexes ? indexes.length : 0;
return curry(rearg(func, indexes), arity);
};
},
'runInContext': function(runInContext) {
return function(context) {
return baseConvert(util, runInContext(context), options);
};
}
};
/*--------------------------------------------------------------------------*/
/**
* Casts `func` to a function with an arity capped iteratee if needed.
*
* @private
* @param {string} name The name of the function to inspect.
* @param {Function} func The function to inspect.
* @returns {Function} Returns the cast function.
*/
function castCap(name, func) {
if (config.cap) {
var indexes = mapping.iterateeRearg[name];
if (indexes) {
return iterateeRearg(func, indexes);
}
var n = !isLib && mapping.iterateeAry[name];
if (n) {
return iterateeAry(func, n);
}
}
return func;
}
/**
* Casts `func` to a curried function if needed.
*
* @private
* @param {string} name The name of the function to inspect.
* @param {Function} func The function to inspect.
* @param {number} n The arity of `func`.
* @returns {Function} Returns the cast function.
*/
function castCurry(name, func, n) {
return (forceCurry || (config.curry && n > 1))
? curry(func, n)
: func;
}
/**
* Casts `func` to a fixed arity function if needed.
*
* @private
* @param {string} name The name of the function to inspect.
* @param {Function} func The function to inspect.
* @param {number} n The arity cap.
* @returns {Function} Returns the cast function.
*/
function castFixed(name, func, n) {
if (config.fixed && (forceFixed || !mapping.skipFixed[name])) {
var data = mapping.methodSpread[name],
start = data && data.start;
return start === undefined ? ary(func, n) : flatSpread(func, start);
}
return func;
}
/**
* Casts `func` to an rearged function if needed.
*
* @private
* @param {string} name The name of the function to inspect.
* @param {Function} func The function to inspect.
* @param {number} n The arity of `func`.
* @returns {Function} Returns the cast function.
*/
function castRearg(name, func, n) {
return (config.rearg && n > 1 && (forceRearg || !mapping.skipRearg[name]))
? rearg(func, mapping.methodRearg[name] || mapping.aryRearg[n])
: func;
}
/**
* Creates a clone of `object` by `path`.
*
* @private
* @param {Object} object The object to clone.
* @param {Array|string} path The path to clone by.
* @returns {Object} Returns the cloned object.
*/
function cloneByPath(object, path) {
path = toPath(path);
var index = -1,
length = path.length,
lastIndex = length - 1,
result = clone(Object(object)),
nested = result;
while (nested != null && ++index < length) {
var key = path[index],
value = nested[key];
if (value != null) {
nested[path[index]] = clone(index == lastIndex ? value : Object(value));
}
nested = nested[key];
}
return result;
}
/**
* Converts `lodash` to an immutable auto-curried iteratee-first data-last
* version with conversion `options` applied.
*
* @param {Object} [options] The options object. See `baseConvert` for more details.
* @returns {Function} Returns the converted `lodash`.
*/
function convertLib(options) {
return _.runInContext.convert(options)(undefined);
}
/**
* Create a converter function for `func` of `name`.
*
* @param {string} name The name of the function to convert.
* @param {Function} func The function to convert.
* @returns {Function} Returns the new converter function.
*/
function createConverter(name, func) {
var realName = mapping.aliasToReal[name] || name,
methodName = mapping.remap[realName] || realName,
oldOptions = options;
return function(options) {
var newUtil = isLib ? pristine : helpers,
newFunc = isLib ? pristine[methodName] : func,
newOptions = assign(assign({}, oldOptions), options);
return baseConvert(newUtil, realName, newFunc, newOptions);
};
}
/**
* Creates a function that wraps `func` to invoke its iteratee, with up to `n`
* arguments, ignoring any additional arguments.
*
* @private
* @param {Function} func The function to cap iteratee arguments for.
* @param {number} n The arity cap.
* @returns {Function} Returns the new function.
*/
function iterateeAry(func, n) {
return overArg(func, function(func) {
return typeof func == 'function' ? baseAry(func, n) : func;
});
}
/**
* Creates a function that wraps `func` to invoke its iteratee with arguments
* arranged according to the specified `indexes` where the argument value at
* the first index is provided as the first argument, the argument value at
* the second index is provided as the second argument, and so on.
*
* @private
* @param {Function} func The function to rearrange iteratee arguments for.
* @param {number[]} indexes The arranged argument indexes.
* @returns {Function} Returns the new function.
*/
function iterateeRearg(func, indexes) {
return overArg(func, function(func) {
var n = indexes.length;
return baseArity(rearg(baseAry(func, n), indexes), n);
});
}
/**
* Creates a function that invokes `func` with its first argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function() {
var length = arguments.length;
if (!length) {
return func();
}
var args = Array(length);
while (length--) {
args[length] = arguments[length];
}
var index = config.rearg ? 0 : (length - 1);
args[index] = transform(args[index]);
return func.apply(undefined, args);
};
}
/**
* Creates a function that wraps `func` and applys the conversions
* rules by `name`.
*
* @private
* @param {string} name The name of the function to wrap.
* @param {Function} func The function to wrap.
* @returns {Function} Returns the converted function.
*/
function wrap(name, func) {
var result,
realName = mapping.aliasToReal[name] || name,
wrapped = func,
wrapper = wrappers[realName];
if (wrapper) {
wrapped = wrapper(func);
}
else if (config.immutable) {
if (mapping.mutate.array[realName]) {
wrapped = wrapImmutable(func, cloneArray);
}
else if (mapping.mutate.object[realName]) {
wrapped = wrapImmutable(func, createCloner(func));
}
else if (mapping.mutate.set[realName]) {
wrapped = wrapImmutable(func, cloneByPath);
}
}
each(aryMethodKeys, function(aryKey) {
each(mapping.aryMethod[aryKey], function(otherName) {
if (realName == otherName) {
var data = mapping.methodSpread[realName],
afterRearg = data && data.afterRearg;
result = afterRearg
? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey)
: castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey);
result = castCap(realName, result);
result = castCurry(realName, result, aryKey);
return false;
}
});
return !result;
});
result || (result = wrapped);
if (result == func) {
result = forceCurry ? curry(result, 1) : function() {
return func.apply(this, arguments);
};
}
result.convert = createConverter(realName, func);
if (mapping.placeholder[realName]) {
setPlaceholder = true;
result.placeholder = func.placeholder = placeholder;
}
return result;
}
/*--------------------------------------------------------------------------*/
if (!isObj) {
return wrap(name, func);
}
var _ = func;
// Convert methods by ary cap.
var pairs = [];
each(aryMethodKeys, function(aryKey) {
each(mapping.aryMethod[aryKey], function(key) {
var func = _[mapping.remap[key] || key];
if (func) {
pairs.push([key, wrap(key, func)]);
}
});
});
// Convert remaining methods.
each(keys(_), function(key) {
var func = _[key];
if (typeof func == 'function') {
var length = pairs.length;
while (length--) {
if (pairs[length][0] == key) {
return;
}
}
func.convert = createConverter(key, func);
pairs.push([key, func]);
}
});
// Assign to `_` leaving `_.prototype` unchanged to allow chaining.
each(pairs, function(pair) {
_[pair[0]] = pair[1];
});
_.convert = convertLib;
if (setPlaceholder) {
_.placeholder = placeholder;
}
// Assign aliases.
each(keys(_), function(key) {
each(mapping.realToAlias[key] || [], function(alias) {
_[alias] = _[key];
});
});
return _;
}
module.exports = baseConvert;
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0 */
/* This file is automatically generated. Do not edit. */
static const char *initial_sid_to_string[] =
{
"null",
"kernel",
"security",
"unlabeled",
"fs",
"file",
"file_labels",
"init",
"any_socket",
"port",
"netif",
"netmsg",
"node",
"igmp_packet",
"icmp_socket",
"tcp_socket",
"sysctl_modprobe",
"sysctl",
"sysctl_fs",
"sysctl_kernel",
"sysctl_net",
"sysctl_net_unix",
"sysctl_vm",
"sysctl_dev",
"kmod",
"policy",
"scmp_packet",
"devnull",
};
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.