code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
import std.stdio: readln, writeln;
import std.string: chomp;
import std.conv: to;
void main() {
int n = readln.chomp.to!int;
writeln(n/2 + n%2);
}
| D |
import core.bitop, std.algorithm, std.ascii, std.bigint, std.conv,
std.functional, std.math, std.numeric, std.range, std.stdio, std.string,
std.random, std.typecons, std.container;
ulong MAX = 1_000_100, MOD = 1_000_000_007, INF = 1_000_000_000_000;
alias sread = () => readln.chomp();
alias lread(T = long) = () => readln.chomp.to!(T);
alias aryread(T = long) = () => readln.split.to!(T[]);
alias Clue = Tuple!(long, "x", long, "y", long, "h");
alias PQueue(T, alias less = "a<b") = BinaryHeap!(Array!T, less);
void main()
{
long n, m;
scan(n, m);
auto a = 100 * (n - m) + 1900 * m;
writeln(a * 2 ^^ m);
}
void scan(TList...)(ref TList Args)
{
auto line = readln.split();
foreach (i, T; TList)
{
T val = line[i].to!(T);
Args[i] = val;
}
}
| D |
//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.typecons;
final class InputReader {
private:
ubyte[] p, buffer;
bool eof;
bool rawRead () {
if (eof) {
return false;
}
p = stdin.rawRead (buffer);
if (p.empty) {
eof = true;
return false;
}
return true;
}
ubyte nextByte(bool check) () {
static if (check) {
if (p.empty) {
if (!rawRead ()) {
return 0;
}
}
}
auto r = p.front;
p.popFront ();
return r;
}
public:
this () {
buffer = uninitializedArray!(ubyte[])(16<<20);
}
bool seekByte (in ubyte lo) {
while (true) {
p = p.find! (c => c >= lo);
if (!p.empty) {
return false;
}
if (!rawRead ()) {
return true;
}
}
}
template next(T) if (isSigned!T) {
T next () {
if (seekByte (45)) {
return 0;
}
T res;
ubyte b = nextByte!false ();
if (b == 45) {
while (true) {
b = nextByte!true ();
if (b < 48 || b >= 58) {
return res;
}
res = res * 10 - (b - 48);
}
} else {
res = b - 48;
while (true) {
b = nextByte!true ();
if (b < 48 || b >= 58) {
return res;
}
res = res * 10 + (b - 48);
}
}
}
}
template next(T) if (isUnsigned!T) {
T next () {
if (seekByte (48)) {
return 0;
}
T res = nextByte!false () - 48;
while (true) {
ubyte b = nextByte!true ();
if (b < 48 || b >= 58) {
break;
}
res = res * 10 + (b - 48);
}
return res;
}
}
T[] nextA(T) (in int n) {
auto a = uninitializedArray!(T[]) (n);
foreach (i; 0 .. n) {
a[i] = next!T;
}
return a;
}
}
alias T = Tuple!(long, uint);
void main() {
auto r = new InputReader ();
const n = r.next!uint;
auto a = r.nextA!int (n);
const s = sum (a, 0L);
//prefix[i] + suffix[j] + a[i .. j] == s
//prefix[i] + suffix[j] == s
auto pr = new long[n+1];
pr[0] = 0;
foreach (i; 1 .. n + 1) pr[i] = pr[i-1] + a[i-1];
/*
auto sf = new long[n+1];
sf[n] = 0;
foreach_reverse (i; 0 .. n) sf[i] = sf[i+1] + a[i];
*/
T[] x;
x.reserve (n + 1);
foreach (i; 0 .. n + 1) x ~= tuple (pr[i], i);
sort (x);
debug stderr.writeln ("pr = ", pr);
debug stderr.writeln ("x = ", x);
int i;
auto z = new uint[n+1];
z[] = uint.max;
while (i < x.length) {
int j = i + 1;
while (j < x.length && x[i][0] == x[j][0]) ++j;
uint last = uint.max;
foreach_reverse (const ref q; x[i .. j]) {
debug stderr.writeln (q);
if (last != uint.max) {
z[q[1]] = last - 1;
}
last = q[1];
}
i = j;
}
debug stderr.writeln ("z = ", z);
foreach_reverse (k; 0 .. n) {
z[k] = min (z[k+1], z[k]);
}
debug stderr.writeln ("z = ", z);
long res;
foreach (k; 0 .. n) {
z[k] = min (z[k], n);
if (z[k] > k) {
res += z[k] - k;
}
}
writeln (res);
}
| D |
import std.stdio, std.string, std.array, std.conv, std.algorithm.iteration, std.functional;
char[54][54] NS;
char[54][54] MS;
void main()
{
auto nm = readln.split.to!(int[]);
auto n = nm[0];
auto m = nm[1];
foreach (i; 0..n) {
auto line = readln;
foreach (j, c; line)
NS[i][j] = c;
}
foreach (i; 0..m) {
auto line = readln;
foreach (j, c; line)
MS[i][j] = c;
}
foreach (i; 0..n-m+1) {
foreach (j; 0..n-m+1) {
bool check() {
foreach (ii; 0..m) {
foreach (jj; 0..m) {
if (NS[i+ii][j+jj] != MS[ii][jj]) return false;
}
}
return true;
}
if (check()) {
writeln("Yes");
return;
}
}
}
writeln("No");
} | D |
import std.stdio, std.math, std.algorithm, std.array, std.string, std.conv, std.container, std.range;
T[] Reads(T)() { return readln.split.to!(T[]); }
alias reads = Reads!int;
void scan(Args...)(ref Args args) {
string[] ss = readln.split;
foreach (i, ref arg ; args) arg = ss[i].parse!int;
}
void main() {
int n,m; scan(n,m);
int[] a = reads();
long tot = a.sum();
auto cnt = a.filter!(i => i >= 1.0 * tot / 4 / m)
.array
.length;
writeln(cnt >= m ? "Yes" : "No");
}
| D |
import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.numeric, std.math, std.random;
import core.bitop;
string FMT_F = "%.10f";
static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }
long mod = 10^^9 + 7;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void main()
{
auto N = RD;
auto K = RD;
auto S = RD!string;
long[] cnts;
long cnt;
char last = S[0];
foreach (c; S)
{
if (c != last)
{
cnts ~= cnt;
cnt = 1;
last = c;
}
else
{
++cnt;
}
}
cnts ~= cnt;
long eo = S[0] == '0' ? 0 : 1;
long len = cnts.length / 2;
len += eo == 0 ? cnts.length % 2 : 0;
auto dp = new long[](max(1, len-K+1));
dp[0] = eo == 1 ? cnts[0] : 0;
foreach (i; 0..K)
{
auto j = i * 2 + eo;
if (j < cnts.length)
dp[0] += cnts[j];
if (j+1 < cnts.length)
dp[0] += cnts[j+1];
}
long ans = dp[0];
foreach (i; 1..dp.length)
{
dp[i] = dp[i-1];
auto j = (i-1) * 2 + eo;
dp[i] -= cnts[j];
if (j >= 1)
dp[i] -= cnts[j-1];
auto k = (i+K-1) * 2 + eo;
if (k < cnts.length)
dp[i] += cnts[k];
if (k+1 < cnts.length)
dp[i] += cnts[k+1];
ans = max(ans, dp[i]);
}
debug writeln(cnts);
debug writeln(dp);
writeln(ans);
stdout.flush();
debug readln();
} | D |
import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.numeric, std.math, std.random;
import core.bitop;
string FMT_F = "%.10f";
static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * y / gcd(x, y); }
long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void main()
{
auto N = RD!string;
long sn;
foreach (c; N)
{
sn += [c].to!long;
}
writeln(N.to!long % sn == 0 ? "Yes" : "No");
stdout.flush();
debug readln();
}
| D |
void main() {
auto N = ri;
auto S = rs;
ulong res = ulong.max;
auto A = new int[](N);
// i番目含め左から今までのWの個数
A[0] = S[0] == 'W';
foreach(i; 1..N) A[i] = S[i] == 'W' ? A[i-1]+1 : A[i-1];
// i番目含め左から今までのEの個数
// C[i] = (i+1) - A[i];
// 下二行はどちらも同じ結果をもつ
//auto C = iota(1, N+1).map!(a => a - A[a-1]).array;
// auto C = iota(N).map!(a => (a+1) - A[a]).array;
auto C = (int n) {
return n+1 - A[n];
};
foreach(i; 0..N) {
ulong tmp;
tmp += C(N-1) - C(i); // リーダーより右でEを向いている人の数
tmp += i < 1 ? 0 : A[i-1]; // リーダーより左でWを向いている人の数
res = min(res, tmp);
}
res.writeln;
}
// ===================================
import std.stdio;
import std.string;
import std.conv;
import std.algorithm;
import std.range;
import std.traits;
import std.math;
import std.container;
import std.bigint;
import std.numeric;
import std.conv;
import std.typecons;
import std.uni;
import std.ascii;
import std.bitmanip;
import core.bitop;
T readAs(T)() if (isBasicType!T) {
return readln.chomp.to!T;
}
T readAs(T)() if (isArray!T) {
return readln.split.to!T;
}
T[][] readMatrix(T)(uint height, uint width) if (!isSomeChar!T) {
auto res = new T[][](height, width);
foreach(i; 0..height) {
res[i] = readAs!(T[]);
}
return res;
}
T[][] readMatrix(T)(uint height, uint width) if (isSomeChar!T) {
auto res = new T[][](height, width);
foreach(i; 0..height) {
auto s = rs;
foreach(j; 0..width) res[i][j] = s[j].to!T;
}
return res;
}
int ri() {
return readAs!int;
}
double rd() {
return readAs!double;
}
string rs() {
return readln.chomp;
} | D |
import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;
string FMT_F = "%.10f";
static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen) return _RDA!T(_f, fix); else return _RDA!T(fix); }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }
void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { y.modpow(mod - 2); x.modm(y); }
long floor_sum(long n, long m, long a, long b)
{
long ans;
if (a >= m) ans += (n-1)*n*(a/m)/2; a %= m;
if (b >= m) ans += n*(b/m); b %= m;
long y_max = (a*n+b)/m, x_max = (y_max*m - b);
if (y_max == 0) return ans;
ans += (n-(x_max+a-1)/a)*y_max;
ans += floor_sum(y_max, a, m, (a - x_max%a)%a);
return ans;
}
void main()
{
auto T = RD;
foreach (i; 0..T)
{
auto N = RD;
auto M = RD;
auto A = RD;
auto B = RD;
writeln(floor_sum(N, M, A, B));
}
stdout.flush;
debug readln;
}
| D |
import std.stdio, std.conv, std.string, std.algorithm,
std.math, std.array, std.container, std.typecons;
void main() {
string s = readln.chomp;
foreach(c;s) write("x");
writeln();
}
| D |
import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;
class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }
bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }
int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }
void main() {
try {
for (; ; ) {
const S = readToken();
const L = cast(int)(S.length);
bool ans = (L % 2 == 0);
foreach (i; 0 .. L) {
ans = ans && (S[i] == "hi"[i % 2]);
}
writeln(ans ? "Yes" : "No");
}
} catch (EOFException e) {
}
}
| D |
void main() {
import std.stdio, std.string, std.conv;
auto rd = readln.split.to!(int[]);
int N = rd[0], Y = rd[1];
foreach (x ; 0 .. N + 1) {
foreach (y ; 0 .. N + 1 - x) {
int z = N - x - y;
if (10000*x + 5000*y + 1000*z == Y) {
writeln(x, ' ', y, ' ', z);
return;
}
}
}
writeln(-1, ' ', -1, ' ', -1);
} | D |
import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;
import std.regex : regex;
import std.container;
import std.bigint;
void main()
{
auto s = readln.chomp.array;
foreach (i;iota(0, s.length, 2)) write(s[i]);
writeln("");
}
| D |
import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;
void main()
{
auto N = readln.chomp.to!int;
auto js = new int[](N);
foreach (a; readln.split.to!(int[])) ++js[a-1];
foreach (j; js) writeln(j);
} | D |
void main() {
int n = readln.chomp.to!int;
bool ok;
foreach (i; 0 .. 26) {
foreach (j; 0 .. 15) {
if (4 * i + 7 * j == n) ok = true;
}
}
writeln(ok ? "Yes" : "No");
}
import std.stdio;
import std.string;
import std.array;
import std.conv;
import std.algorithm;
import std.range;
import std.math;
import std.container;
import std.typecons; | D |
import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;
void main()
{
auto N = readln.chomp.to!int;
auto S = readln.chomp.to!(wchar[]);
int cost;
foreach_reverse (c; S[1..$]) {
if (c == 'E') ++cost;
}
auto min_cost = cost;
for (int p = 1; p < N; ++p) {
if (S[p] == 'E') --cost;
if (S[p-1] == 'W') ++cost;
min_cost = min(cost, min_cost);
}
writeln(min_cost);
} | D |
import std.stdio, std.string, std.array, std.algorithm, std.conv, std.typecons, std.numeric, std.math;
void main()
{
for (;;) {
auto wh = readln.split.to!(int[]);
auto W = wh[0];
auto H = wh[1];
if (W == 0 && H == 0) return;
auto MAP = new char[][](2*H-1, 2*W-1);
foreach (i; 0..2*H-1) {
foreach (j, c; readln.chomp) {
MAP[i][j] = c;
}
}
auto MEMO = new bool[][](2*H-1, 2*W-1);
auto ss = [[0, 0, 0]];
MEMO[0][0] = true;
while (!ss.empty) {
auto s = ss[0];
ss = ss[1..$];
auto x = s[0];
auto y = s[1];
auto c = s[2];
foreach (d; [[1,0], [0,1], [-1,0], [0,-1]]) {
auto xx = x+d[0];
auto yy = y+d[1];
if (xx < 0 || xx >= 2*W-1 || yy < 0 || yy >= 2*H-1 || MAP[yy][xx] == '1') continue;
xx += d[0];
yy += d[1];
if (MEMO[yy][xx]) continue;
MEMO[yy][xx] = true;
if (xx == 2*W-2 && yy == 2*H-2) {
writeln(c+2);
goto ok;
}
ss ~= [xx, yy, c+1];
}
}
writeln(0);
ok:
}
}
| D |
import std;
alias sread = () => readln.chomp();
alias lread = () => readln.chomp.to!long();
alias aryread(T = long) = () => readln.split.to!(T[]);
//aryread!string();
//auto PS = new Tuple!(long,string)[](M);
//x[]=1;でlong[]全要素1に初期化
void main()
{
string a;
string b;
string c;
scan(a, b, c);
// writeln(a[$ - 1]);
if ((a[$ - 1] == b[0]) && (b[$ - 1] == c[0]))
{
writeln("YES");
return;
}
writeln("NO");
}
void scan(L...)(ref L A)
{
auto l = readln.split;
foreach (i, T; L)
{
A[i] = l[i].to!T;
}
}
void arywrite(T)(T a)
{
a.map!text.join(' ').writeln;
}
| D |
import std.stdio;
import std.string;
import std.conv;
void main()
{
auto a = to!long( split(readln())[0] ) ;
writeln(a/3);
} | D |
import std.stdio, std.string, std.conv;
import std.range, std.algorithm, std.array, std.typecons, std.container;
import std.math, std.numeric, core.bitop;
enum inf3 = 1_001_001_001;
enum inf6 = 1_001_001_001_001_001_001L;
enum mod = 1_000_000_007L;
void main() {
int n;
scan(n);
string a, b, c;
scan(a);
scan(b);
scan(c);
int ans;
foreach (i ; 0 .. n) {
if (a[i] == b[i] && b[i] == c[i]) {
}
else if (a[i] == b[i] || b[i] == c[i] || c[i] == a[i]) {
ans++;
}
else {
ans += 2;
}
}
writeln(ans);
}
void scan(T...)(ref T args) {
import std.stdio : readln;
import std.algorithm : splitter;
import std.conv : to;
import std.range.primitives;
auto line = readln().splitter();
foreach (ref arg; args) {
arg = line.front.to!(typeof(arg));
line.popFront();
}
assert(line.empty);
}
void fillAll(R, T)(ref R arr, T value) {
static if (is(typeof(arr[] = value))) {
arr[] = value;
}
else {
foreach (ref e; arr) {
fillAll(e, value);
}
}
}
| D |
import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.string;
void main() {
auto n = readln.chomp.to!int;
auto s = readln.chomp.split.map!(to!int).array;
auto q = readln.chomp.to!int;
auto t = readln.chomp.split.map!(to!int).array;
auto c = 0;
foreach (e_t; t) {
foreach (e_s; s) {
if (e_t == e_s) {
c++;
break;
}
}
}
c.writeln;
} | D |
import std.stdio, std.string, std.conv;
import std.range, std.algorithm, std.array, std.typecons, std.container;
import std.math, std.numeric, core.bitop;
enum inf = 1_001_001_001;
enum inf6 = 1_001_001_001_001_001_001L;
enum mod = 1_000_000_007L;
void main() {
int H, W;
scan(H, W);
auto b = new bool[][](H, W);
foreach (i ; 0 .. H) {
b[i] = readln.chomp.map!(c => c == '.').array;
}
debug {
writeln(b);
}
auto u = new int[][](H, W);
auto d = new int[][](H, W);
auto r = new int[][](H, W);
auto l = new int[][](H, W);
foreach (i ; 1 .. H) {
foreach (j ; 0 .. W) {
if (b[i - 1][j]) u[i][j] += u[i - 1][j] + 1;
}
}
foreach_reverse (i ; 0 .. H - 1) {
foreach (j ; 0 .. W) {
if (b[i + 1][j]) d[i][j] += d[i + 1][j] + 1;
}
}
foreach (j ; 1 .. W) {
foreach (i ; 0 .. H) {
if (b[i][j - 1]) l[i][j] += l[i][j - 1] + 1;
}
}
foreach_reverse (j ; 0 .. W - 1) {
foreach (i ; 0 .. H) {
if (b[i][j + 1]) r[i][j] += r[i][j + 1] + 1;
}
}
int ans;
foreach (i ; 0 .. H) {
foreach (j ; 0 .. W) {
if (!b[i][j]) continue;
chmax(ans, u[i][j] + d[i][j] + l[i][j] + r[i][j] + 1);
}
}
writeln(ans);
}
void scan(T...)(ref T args) {
import std.stdio : readln;
import std.algorithm : splitter;
import std.conv : to;
import std.range.primitives;
auto line = readln().splitter();
foreach (ref arg; args) {
arg = line.front.to!(typeof(arg));
line.popFront();
}
assert(line.empty);
}
void fillAll(R, T)(ref R arr, T value) {
static if (is(typeof(arr[] = value))) {
arr[] = value;
}
else {
foreach (ref e; arr) {
fillAll(e, value);
}
}
}
bool chmin(T, U...)(ref T x, U args) {
bool isChanged;
foreach (arg; args) {
if (x > arg) {
x = arg;
isChanged = true;
}
}
return isChanged;
}
bool chmax(T, U...)(ref T x, U args) {
bool isChanged;
foreach (arg; args) {
if (x < arg) {
x = arg;
isChanged = true;
}
}
return isChanged;
}
| D |
import std.stdio;
import std.string;
import std.conv;
import std.algorithm;
import std.math;
immutable limitList = 100000;
void main() {
int input;
bool[] listNumbers = new bool[](limitList);
int[] listPrimeNumbers; //List of prime numbers.
listNumbers.fill(true);
listNumbers[0..2] = false;
foreach (i; 2..limitList.to!double.sqrt.to!int) {
if (listNumbers[i]) {
for (int j = i*2; j < limitList; j += i) listNumbers[j] = false;
}
}
while ((input = readln.chomp.to!int) != 0) {
uint count = 0;
foreach (i; 0..(input/2)+1) {
if(listNumbers[i] && listNumbers[input-i]) count++;
}
writeln(count);
}
} | D |
import std.stdio, std.string, std.conv;
import std.range, std.algorithm, std.array, std.typecons, std.container;
import std.math, std.numeric, core.bitop;
enum inf3 = 1_001_001_001;
enum inf6 = 1_001_001_001_001_001_001L;
enum mod = 1_000_000_007L;
void main() {
long a, b, c, x, y;
scan(a, b, c, x, y);
long ans;
ans = min(x, y) * min(a + b, 2*c) + max(x - y, 0) * min(a, 2*c) + max(y - x, 0) * min(b, 2*c);
writeln(ans);
}
int[][] readGraph(int n, int m, bool isUndirected = true, bool is1indexed = true) {
auto adj = new int[][](n, 0);
foreach (i; 0 .. m) {
int u, v;
scan(u, v);
if (is1indexed) {
u--, v--;
}
adj[u] ~= v;
if (isUndirected) {
adj[v] ~= u;
}
}
return adj;
}
alias Edge = Tuple!(int, "to", int, "cost");
Edge[][] readWeightedGraph(int n, int m, bool isUndirected = true, bool is1indexed = true) {
auto adj = new Edge[][](n, 0);
foreach (i; 0 .. m) {
int u, v, c;
scan(u, v, c);
if (is1indexed) {
u--, v--;
}
adj[u] ~= Edge(v, c);
if (isUndirected) {
adj[v] ~= Edge(u, c);
}
}
return adj;
}
void yes(bool b) {
writeln(b ? "Yes" : "No");
}
void YES(bool b) {
writeln(b ? "YES" : "NO");
}
T[] readArr(T)() {
return readln.split.to!(T[]);
}
T[] readArrByLines(T)(int n) {
return iota(n).map!(i => readln.chomp.to!T).array;
}
void scan(T...)(ref T args) {
import std.stdio : readln;
import std.algorithm : splitter;
import std.conv : to;
import std.range.primitives;
auto line = readln().splitter();
foreach (ref arg; args) {
arg = line.front.to!(typeof(arg));
line.popFront();
}
assert(line.empty);
}
void fillAll(R, T)(ref R arr, T value) {
static if (is(typeof(arr[] = value))) {
arr[] = value;
}
else {
foreach (ref e; arr) {
fillAll(e, value);
}
}
}
bool chmin(T, U...)(ref T x, U args) {
bool isChanged;
foreach (arg; args) {
if (x > arg) {
x = arg;
isChanged = true;
}
}
return isChanged;
}
bool chmax(T, U...)(ref T x, U args) {
bool isChanged;
foreach (arg; args) {
if (x < arg) {
x = arg;
isChanged = true;
}
}
return isChanged;
}
| D |
void main() {
auto N = rs;
auto S = N.map!(a => a.to!int - '0').sum;
if(N.to!int%S==0) "Yes".writeln;
else "No".writeln;
}
// ===================================
import std.stdio;
import std.string;
import std.conv;
import std.algorithm;
import std.range;
import std.traits;
import std.math;
import std.container;
import std.bigint;
import std.numeric;
import std.conv;
import std.typecons;
import std.uni;
import std.ascii;
import std.bitmanip;
import core.bitop;
T readAs(T)() if (isBasicType!T) {
return readln.chomp.to!T;
}
T readAs(T)() if (isArray!T) {
return readln.split.to!T;
}
T[][] readMatrix(T)(uint height, uint width) if (!isSomeChar!T) {
auto res = new T[][](height, width);
foreach(i; 0..height) {
res[i] = readAs!(T[]);
}
return res;
}
T[][] readMatrix(T)(uint height, uint width) if (isSomeChar!T) {
auto res = new T[][](height, width);
foreach(i; 0..height) {
auto s = rs;
foreach(j; 0..width) res[i][j] = s[j].to!T;
}
return res;
}
int ri() {
return readAs!int;
}
double rd() {
return readAs!double;
}
string rs() {
return readln.chomp;
}
| D |
import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric, core.bitop;
void main()
{
auto N = readln.chomp.to!int;
uint[] ss;
foreach (_; 0..N) {
uint s;
foreach (i, f; readln.split) if (f == "1") s |= (1<<i);
ss ~= s;
}
long[][] ps;
foreach (_; 0..N) ps ~= readln.split.to!(long[]);
long r = long.min;
foreach (uint j; 1..(1<<10)) {
long rr;
foreach (i; 0..N) rr += ps[i][popcnt(j & ss[i])];
r = max(r, rr);
}
writeln(r);
} | D |
import std.stdio, std.conv, std.string, std.algorithm, std.range;
void main() {
auto input = readln.split.to!(int[]);
auto A = input[0];
auto B = input[1];
auto N = 1;
auto count=0;
while(N < B) {
N--;
N+=A;
count++;
}
count.writeln;
} | D |
import std.stdio, std.algorithm, std.conv, std.array, std.string;
void main()
{
auto s = readln.chomp;
auto cnt = 0;
char last = s[0];
foreach (c; s[1..$]) {
if (c != last) {
++cnt;
last = c;
}
}
writeln(cnt);
} | D |
import std.stdio, std.string, std.range, std.conv, std.array, std.algorithm, std.math, std.typecons, std.functional;
void main() {
struct Query { long p, q; }
auto tmp = readln.split.to!(long[]);
const N = tmp[0], M = tmp[1], Q = tmp[2];
auto count = new long[][](N+1,N+1);
foreach (i; 0..M) {
tmp = readln.split.to!(long[]);
const L = tmp[0], R = tmp[1];
count[L][R]++;
}
auto queryList = new Query[Q];
foreach (i; 0..Q) {
tmp = readln.split.to!(long[]);
const p = tmp[0], q = tmp[1];
queryList[i] = Query(p,q);
}
// p <= L && R <= qの数を求める
// ある電車の情報を(L,R)として二次元平面にプロットすると、
// (p,q)に対して右下にある電車の個数を数える問題になる
/*
(0,N) --- (p,N) --- (L,N) --- (N,N)
| | | |
(0,q) --- (p,q) --- (L,q) --- (N,q)
| | | |
(0,R) --- (p,R) --- (L,R) --- (N,R)
| | | |
(0,0) --- (p,0) --- (L,0) --- (N,0)
*/
// これは、原点から(x,y)までにある電車の個数をf(x,y)としたとき
// f(N,q) - f(p-1,q)で表される
foreach (i; 0..N+1) {
foreach (j; 0..N) {
count[i][j+1] += count[i][j];
}
}
foreach (i; 0..N) {
foreach (j; 0..N+1) {
count[i+1][j] += count[i][j];
}
}
foreach (query; queryList) {
with (query) {
writeln(count[N][q] - count[p-1][q]);
}
}
}
| D |
import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;
void main()
{
auto ab = readln.split.to!(int[]);
auto A = ab[0];
auto B = ab[1];
foreach (n; 1..20000) {
if ((n*0.08).to!int == A && (n*0.1).to!int == B) {
writeln(n);
return;
}
}
writeln(-1);
} | D |
import std.stdio;
import std.string;
import std.array; // split
import std.conv; // to
void main()
{
string n = chomp(readln());
string m = chomp(readln());
if(n[0] == m[2] && n[1] == m[1] && n[2] == m[0]){
writeln("YES");
} else {
writeln("NO");
}
} | D |
import std.stdio,
std.string,
std.conv,
std.algorithm;
void main() {
int[] buf = readln.chomp.split.to!(int[]);
int a = buf[0], b = buf[1], x = buf[2];
if (a == x || a < x && a + b >= x) {
writeln("YES");
}
else {
writeln("NO");
}
}
| D |
import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;
void main()
{
auto abq = readln.split.to!(int[]);
auto A = abq[0];
auto B = abq[1];
auto Q = abq[2];
long[] ss = [long.min/5], ts = [long.min/5];
foreach (_; 0..A) ss ~= readln.chomp.to!long;
foreach (_; 0..B) ts ~= readln.chomp.to!long;
ss ~= long.max/5;
ts ~= long.max/5;
foreach (_; 0..Q) {
auto x = readln.chomp.to!long;
int l, r = A+1;
while (l+1 < r) {
auto m = (l+r)/2;
if (ss[m] <= x) {
l = m;
} else {
r = m;
}
}
auto al = ss[l], ar = ss[r];
l = 0, r = B+1;
while (l+1 < r) {
auto m = (l+r)/2;
if (ts[m] <= x) {
l = m;
} else {
r = m;
}
}
auto bl = ts[l], br = ts[r];
writeln(min(
max(x - al, x - bl),
max(ar - x, br - x),
(x - al) * 2 + br - x,
(x - bl) * 2 + ar - x,
(ar - x) * 2 + x - bl,
(br - x) * 2 + x - al
));
}
} | D |
import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric, std.container, std.range;
void main()
{
auto nd = readln.split.to!(int[]);
auto N = nd[0];
long D = nd[1];
int c;
foreach (_; 0..N) {
auto xy = readln.split.to!(long[]);
if (xy[0]^^2 + xy[1]^^2 <= D^^2) ++c;
}
writeln(c);
} | D |
import std.stdio, std.algorithm, std.conv, std.array, std.string;
long P = 10^^9+7;
void main()
{
auto nm = readln.split.to!(long[]);
auto n = nm[0] > nm[1] ? nm[0] : nm[1];
auto m = n == nm[0] ? nm[1] : nm[0];
if (n == m || n == m+1) {
long x = 1;
foreach (i; 2..n+1) x = (x*i)%P;
foreach (i; 2..m+1) x = (x*i)%P;
if (n == m) x = (x*2)%P;
writeln(x);
} else {
writeln(0);
}
} | D |
import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, std.numeric, std.regex, std.typecons;
import core.bitop;
class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }
bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }
int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }
void main() {
try {
for (; ; ) {
const S = readToken();
const K = cast(int)(S.length);
const A = S.count('o');
const ans = (A + (15 - K) >= 8);
writeln(ans ? "YES" : "NO");
}
} catch (EOFException e) {
}
}
| D |
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
T read(T)() { return readln.chomp.to!T; }
T[] reads(T)() { return readln.split.to!(T[]); }
alias readint = read!int;
alias readints = reads!int;
/// double で計算しても AC はとれる
int calc(int[] a) {
double agv = 1.0 * a.sum / a.length;
double best = int.max;
int ans = 0;
for (int i = 0; i < a.length; i++) {
double d = abs(agv - a[i]);
if (d < best) {
best = d;
ans = i;
}
}
return ans;
}
/// 整数のみで答えを求める
int calc2(int[] a) {
int sum = a.sum;
int ans = 0;
int best = int.max;
int n = cast(int) a.length;
for (int i = 0; i < a.length; i++) {
int d = abs(sum - a[i] * n);
if (d < best) {
best = d;
ans = i;
}
}
return ans;
}
void main() {
readint;
auto a = readints;
// writeln(calc(a));
writeln(calc2(a));
}
| D |
import std.stdio, std.string, std.conv;
import std.range, std.algorithm, std.array, std.typecons, std.container;
import std.math, std.numeric, core.bitop;
void main() {
int n, k;
scan(n, k);
writeln(1 + (n - k + k - 2) / (k - 1));
}
void scan(T...)(ref T args) {
import std.stdio : readln;
import std.algorithm : splitter;
import std.conv : to;
import std.range.primitives;
auto line = readln().splitter();
foreach (ref arg; args) {
arg = line.front.to!(typeof(arg));
line.popFront();
}
assert(line.empty);
}
void fillAll(R, T)(ref R arr, T value) {
static if (is(typeof(arr[] = value))) {
arr[] = value;
}
else {
foreach (ref e; arr) {
fillAll(e, value);
}
}
}
| D |
import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math;
int[3][3] CS;
void main()
{
foreach (i; 0..3)
CS[i][] = readln.split.to!(int[])[];
foreach (a1; 0..201) {
if (a1 > CS[0][0] || a1 > CS[0][1] || a1 > CS[0][2]) continue;
auto b1 = CS[0][0] - a1;
if (b1 > CS[1][0] || b1 > CS[2][0]) continue;
auto a2 = CS[1][0] - b1;
auto a3 = CS[2][0] - b1;
auto b2 = CS[0][1] - a1;
if (a2 + b2 != CS[1][1] || a3 + b2 != CS[2][1]) continue;
auto b3 = CS[0][2] - a1;
if (a2 + b3 != CS[1][2] || a3 + b3 != CS[2][2]) continue;
writeln("Yes");
return;
}
writeln("No");
} | D |
// import chie template :) {{{
static if (__VERSION__ < 2090) {
import std.stdio, std.algorithm, std.array, std.string, std.math, std.conv,
std.range, std.container, std.bigint, std.ascii, std.typecons, std.format,
std.bitmanip, std.numeric;
} else {
import std;
}
// }}}
// nep.scanner {{{
class Scanner {
import std.stdio : File, stdin;
import std.conv : to;
import std.array : split;
import std.string;
import std.traits : isSomeString;
private File file;
private char[][] str;
private size_t idx;
this(File file = stdin) {
this.file = file;
this.idx = 0;
}
this(StrType)(StrType s, File file = stdin) if (isSomeString!(StrType)) {
this.file = file;
this.idx = 0;
fromString(s);
}
private char[] next() {
if (idx < str.length) {
return str[idx++];
}
char[] s;
while (s.length == 0) {
s = file.readln.strip.to!(char[]);
}
str = s.split;
idx = 0;
return str[idx++];
}
T next(T)() {
return next.to!(T);
}
T[] nextArray(T)(size_t len) {
T[] ret = new T[len];
foreach (ref c; ret) {
c = next!(T);
}
return ret;
}
void scan(T...)(ref T args) {
foreach (ref arg; args) {
arg = next!(typeof(arg));
}
}
void fromString(StrType)(StrType s) if (isSomeString!(StrType)) {
str ~= s.to!(char[]).strip.split;
}
}
// }}}
// ModInt {{{
struct ModInt(ulong modulus) {
import std.traits : isIntegral, isBoolean;
import std.exception : enforce;
private {
ulong val;
}
this(const ulong n) {
val = n % modulus;
}
this(const ModInt n) {
val = n.value;
}
@property {
ref inout(ulong) value() inout {
return val;
}
}
T opCast(T)() {
static if (isIntegral!T) {
return cast(T)(val);
} else if (isBoolean!T) {
return val != 0;
} else {
enforce(false, "cannot cast from " ~ this.stringof ~ " to " ~ T.stringof ~ ".");
}
}
ModInt opAssign(const ulong n) {
val = n % modulus;
return this;
}
ModInt opOpAssign(string op)(ModInt rhs) {
static if (op == "+") {
val += rhs.value;
if (val >= modulus) {
val -= modulus;
}
} else if (op == "-") {
if (val < rhs.value) {
val += modulus;
}
val -= rhs.value;
} else if (op == "*") {
val = val * rhs.value % modulus;
} else if (op == "/") {
this *= rhs.inv;
} else if (op == "^^") {
ModInt res = 1;
ModInt t = this;
while (rhs.value > 0) {
if (rhs.value % 2 != 0) {
res *= t;
}
t *= t;
rhs /= 2;
}
this = res;
} else {
enforce(false, op ~ "= is not implemented.");
}
return this;
}
ModInt opOpAssign(string op)(ulong rhs) {
static if (op == "+") {
val += rhs;
if (val >= modulus) {
val -= modulus;
}
} else if (op == "-") {
if (val < rhs) {
val += modulus;
}
val -= rhs;
} else if (op == "*") {
val = val * rhs % modulus;
} else if (op == "/") {
this *= ModInt(rhs).inv;
} else if (op == "^^") {
ModInt res = 1;
ModInt t = this;
while (rhs > 0) {
if (rhs % 2 != 0) {
res *= t;
}
t *= t;
rhs /= 2;
}
this = res;
} else {
enforce(false, op ~ "= is not implemented.");
}
return this;
}
ModInt opUnary(string op)() {
static if (op == "++") {
this += 1;
} else if (op == "--") {
this -= 1;
} else {
enforce(false, op ~ " is not implemented.");
}
return this;
}
ModInt opBinary(string op)(const ulong rhs) const {
mixin("return ModInt(this) " ~ op ~ "= rhs;");
}
ModInt opBinary(string op)(ref const ModInt rhs) const {
mixin("return ModInt(this) " ~ op ~ "= rhs;");
}
ModInt opBinary(string op)(const ModInt rhs) const {
mixin("return ModInt(this) " ~ op ~ "= rhs;");
}
ModInt opBinaryRight(string op)(const ulong lhs) const {
mixin("return ModInt(this) " ~ op ~ "= lhs;");
}
long opCmp(ref const ModInt rhs) const {
return cast(long)value - cast(long)rhs.value;
}
bool opEquals(const ulong rhs) const {
return value == ModInt(rhs).value;
}
ModInt inv() const {
ModInt ret = this;
ret ^^= modulus - 2;
return ret;
}
string toString() const {
import std.format : format;
return format("%s", val);
}
}
// }}}
// alias {{{
alias Heap(T, alias less = "a < b") = BinaryHeap!(Array!T, less);
alias MinHeap(T) = Heap!(T, "a > b");
// }}}
// memo {{{
/*
- ある値が見つかるかどうか
<https://dlang.org/phobos/std_algorithm_searching.html#canFind>
canFind(r, value); -> bool
- 条件に一致するやつだけ残す
<https://dlang.org/phobos/std_algorithm_iteration.html#filter>
// 2で割り切れるやつ
filter!"a % 2 == 0"(r); -> Range
- 合計
<https://dlang.org/phobos/std_algorithm_iteration.html#sum>
sum(r);
- 累積和
<https://dlang.org/phobos/std_algorithm_iteration.html#cumulativeFold>
// 今の要素に前の要素を足すタイプの一般的な累積和
// 累積和のrangeが帰ってくる(破壊的変更は行われない)
cumulativeFold!"a + b"(r, 0); -> Range
- rangeをarrayにしたいとき
array(r); -> Array
- 各要素に同じ処理をする
<https://dlang.org/phobos/std_algorithm_iteration.html#map>
// 各要素を2乗
map!"a * a"(r) -> Range
- ユニークなやつだけ残す
<https://dlang.org/phobos/std_algorithm_iteration.html#uniq>
uniq(r) -> Range
- 順列を列挙する
<https://dlang.org/phobos/std_algorithm_iteration.html#permutations>
permutation(r) -> Range
- ある値で埋める
<https://dlang.org/phobos/std_algorithm_mutation.html#fill>
fill(r, val); -> void
- バイナリヒープ
<https://dlang.org/phobos/std_container_binaryheap.html#.BinaryHeap>
// 昇順にするならこう(デフォは降順)
BinaryHeap!(Array!T, "a > b") heap;
heap.insert(val);
heap.front;
heap.removeFront();
- 浮動小数点の少数部の桁数設定
// 12桁
writefln("%.12f", val);
- 浮動小数点の誤差を考慮した比較
<https://dlang.org/phobos/std_math.html#.approxEqual>
approxEqual(1.0, 1.0099); -> true
- 小数点切り上げ
<https://dlang.org/phobos/std_math.html#.ceil>
ceil(123.4); -> 124
- 小数点切り捨て
<https://dlang.org/phobos/std_math.html#.floor>
floor(123.4) -> 123
- 小数点四捨五入
<https://dlang.org/phobos/std_math.html#.round>
round(4.5) -> 5
round(5.4) -> 5
*/
// }}}
void main() {
auto cin = new Scanner;
int h, w, k;
cin.scan(h, w, k);
string[] s = cin.nextArray!string(h);
int[][] imos = new int[][](h, w);
foreach (i; 0 .. h) {
foreach (j; 0 .. w) {
imos[i][j] = s[i][j] - '0';
}
}
foreach (i; 0 .. h) {
foreach (j; 1 .. w) {
imos[i][j] += imos[i][j - 1];
}
}
foreach (j; 0 .. w) {
foreach (i; 1 .. h) {
imos[i][j] += imos[i - 1][j];
}
}
int res = int.max;
foreach (bit; 0 .. 1 << (h - 1)) {
int[][] area = new int[][](0, w);
int cnt;
{
int prev = -1;
foreach (i; 0 .. h) {
if (((bit | (1 << (h - 1))) >> i) & 1) {
cnt++;
if (prev == -1) {
prev = i;
area ~= imos[i];
continue;
}
int[] t = new int[w];
foreach (j; 0 .. w) {
t[j] = imos[i][j] - imos[prev][j];
}
prev = i;
area ~= t;
}
}
}
cnt--;
int[] diff = new int[h];
bool can = true;
OUTER: foreach (j; 0 .. w) {
bool flg = false;
foreach (i; 0 .. area.length) {
if (area[i][j] - diff[i] > k) {
flg = true;
break;
}
}
if (flg) {
if (j == 0) {
can = false;
break OUTER;
}
foreach (i; 0 .. area.length) {
diff[i] += area[i][j - 1] - diff[i];
}
foreach (i; 0 .. area.length) {
if (area[i][j] - diff[i] > k) {
can = false;
break OUTER;
}
}
cnt++;
}
}
debug writefln("%010b cnt=%d", bit, cnt);
debug writeln(area);
if (can) res = min(res, cnt);
}
writeln(res);
}
| D |
import std.stdio, std.string, std.conv;
import std.algorithm, std.array;
immutable MOD = 1_000_000_007;
auto solve(string s_)
{
auto NC = s_.split.map!(to!int);
immutable N=NC[0], C=NC[1];
immutable A = readln.split.map!(to!long).array();
immutable B = readln.split.map!(to!long).array();
immutable u = B.reduce!max();
auto p = new long[][](u+1,C+1);
foreach(int v, ref a;p)
{
a[0]=1;
foreach(c;1..C+1) a[c]=a[c-1]*v%MOD;
}
foreach(c;0..C+1) foreach(v;1..u+1) p[v][c]=(p[v][c]+p[v-1][c])%MOD;
auto dp = new long[][](N+1,C+1);
dp[0][0]=1;
foreach(n;1..N+1)
{
auto a = p[A[n-1]-1];
auto b = p[B[n-1]];
foreach(c;0..C+1)
foreach(i;0..c+1)
dp[n][c]=(dp[n][c]+dp[n-1][c-i]*(b[i]-a[i]+MOD))%MOD;
}
return dp[N][C];
}
void main(){ for(string s; (s=readln.chomp()).length;) writeln(solve(s)); } | D |
import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
void solve(){
long n = read.to!long;
long best = 1_000_000_999;
long[] ms = [1, 10, 100, 1_000, 10_000, 100_000, 1_000_000];
foreach(i; 1 .. n){
long a = i;
long b = n - a;
long x;
while(a > 0 || b > 0){
x += a % 10, a /= 10;
x += b % 10, b /= 10;
}
best = min(best, x);
}
best.writeln;
}
| D |
import std.stdio;
import std.string;
import std.conv;
import std.algorithm;
import std.array;
void main(){
auto N = readln.chomp.to!int;
writeln(N*(N+1)/2);
} | D |
import std.stdio, std.string, std.conv;
import std.range, std.algorithm, std.array, std.typecons, std.container;
import std.math, std.numeric, core.bitop;
enum inf = 1_001_001_001;
enum infl = 1_001_001_001_001_001_001L;
enum mod = 1_000_000_007L;
void main() {
int n;
scan(n);
int a, b;
scan(a, b);
auto p = readln.split.to!(int[]);
auto c = new int[](3);
foreach (pi ; p) {
if (pi <= a) {
c[0]++;
}
else if (pi <= b) {
c[1]++;
}
else {
c[2]++;
}
}
int ans = c.reduce!min;
writeln(ans);
}
void scan(T...)(ref T args) {
import std.stdio : readln;
import std.algorithm : splitter;
import std.conv : to;
import std.range.primitives;
auto line = readln().splitter();
foreach (ref arg; args) {
arg = line.front.to!(typeof(arg));
line.popFront();
}
assert(line.empty);
}
void fillAll(R, T)(ref R arr, T value) {
static if (is(typeof(arr[] = value))) {
arr[] = value;
}
else {
foreach (ref e; arr) {
fillAll(e, value);
}
}
}
bool chmin(T, U...)(ref T x, U args) {
bool isChanged;
foreach (arg ; args) {
if (x > arg) {
x = arg;
isChanged = true;
}
}
return isChanged;
}
bool chmax(T, U...)(ref T x, U args) {
bool isChanged;
foreach (arg ; args) {
if (x < arg) {
x = arg;
isChanged = true;
}
}
return isChanged;
}
long powmod(long x, long y, long mod = 1_000_000_007L) {
long res = 1L;
while (y > 0) {
if (y & 1) {
(res *= x) %= mod;
}
(x *= x) %= mod;
y >>= 1;
}
return res;
} | D |
import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;
import std.regex : regex;
import std.container;
import std.bigint;
import std.ascii;
void main()
{
auto n = readln.chomp.to!int;
auto a = new long[](n);
auto b = new long[](n);
long res;
foreach (i; 0..n) {
auto x = readln.chomp.split.to!(long[]);
a[i] = x[0];
b[i] = x[1];
}
foreach_reverse(i; 0..n) {
auto s = (a[i] + res) % b[i];
if (s == 0) continue;
res += b[i] - s;
}
res.writeln;
}
| D |
import std.stdio, std.algorithm, std.conv, std.array, std.string;
void main()
{
auto abcd = readln.split.to!(int[]);
auto a = abcd[0];
auto b = abcd[1];
auto c = abcd[2];
auto d = abcd[3];
if (b <= c || d <= a) {
writeln(0);
} else if (a <= c) {
writeln(b < d ? b - c : d - c);
} else {
writeln(b < d ? b - a : d - a);
}
} | D |
import std.stdio, std.string, std.conv;
import std.range, std.algorithm, std.array, std.typecons, std.container;
import std.math, std.numeric, core.bitop;
enum inf = 1_001_001_001;
enum inf6 = 1_001_001_001_001_001_001L;
enum mod = 1_000_000_007L;
void main() {
long N;
scan(N);
auto ans = N^^3;
writeln(ans);
}
void scan(T...)(ref T args) {
import std.stdio : readln;
import std.algorithm : splitter;
import std.conv : to;
import std.range.primitives;
auto line = readln().splitter();
foreach (ref arg; args) {
arg = line.front.to!(typeof(arg));
line.popFront();
}
assert(line.empty);
}
void fillAll(R, T)(ref R arr, T value) {
static if (is(typeof(arr[] = value))) {
arr[] = value;
}
else {
foreach (ref e; arr) {
fillAll(e, value);
}
}
}
bool chmin(T, U...)(ref T x, U args) {
bool isChanged;
foreach (arg; args) {
if (x > arg) {
x = arg;
isChanged = true;
}
}
return isChanged;
}
bool chmax(T, U...)(ref T x, U args) {
bool isChanged;
foreach (arg; args) {
if (x < arg) {
x = arg;
isChanged = true;
}
}
return isChanged;
}
| D |
void main()
{
long[] tmp = readln.split.to!(long[]);
long n = tmp[0], m = tmp[1];
long scc = min(n, m/2);
scc += (m - 2 * scc) / 4;
scc.writeln;
}
import std.stdio;
import std.string;
import std.array;
import std.conv;
import std.algorithm;
import std.range;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import std.ascii;
import std.uni; | D |
import std.algorithm, std.container, std.conv, std.math, std.range, std.typecons, std.stdio, std.string;
auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void main()
{
int a, b, c; readV(a, b, c);
writeln(min(a+b, b+c, c+a));
}
| D |
import std.stdio;
import std.string;
import std.conv;
import std.algorithm;
import std.math;
import std.array;
import std.range;
import std.regex;
void main(){
auto a=readln.chomp.to!int;
if(a<1200)writeln("ABC");
else if(a>=1200&&a<2800)writeln("ARC");
else writeln("AGC");
} | D |
import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;
import std.regex : regex;
import std.container;
void main()
{
foreach (line; stdin.byLine) {
auto str = line.chomp;
if (str.length == 1) break;
auto aScore = str[1..str.length].count!(a => a == 'A');
auto bScore = str[1..str.length].count!(a => a == 'B');
if (aScore > bScore) aScore++;
else bScore++;
writeln(aScore, " ", bScore);
}
} | D |
import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;
import std.numeric;
import std.bigint;
import core.checkedint;
void main()
{
for (;;) {
int n = readln.chomp.to!int;
if (n == 0) {
break;
}
char[char] dic;
foreach (i; 0..n) {
auto raw = readln.chomp;
dic[raw[0]] = raw[2];
}
int m = readln.chomp.to!int;
foreach (i; 0..m) {
auto c = readln[0];
if (c in dic) {
dic[c].write;
} else {
c.write;
}
}
writeln;
}
}
void tie(R, Args...)(R arr, ref Args args)
if (isRandomAccessRange!R || isArray!R)
in
{
assert (arr.length == args.length);
}
body
{
foreach (i, ref v; args) {
alias T = typeof(v);
v = arr[i].to!T;
}
}
void verbose(Args...)(in Args args)
{
stderr.write("[");
foreach (i, ref v; args) {
if (i) stderr.write(", ");
stderr.write(v);
}
stderr.writeln("]");
}
| D |
import std.stdio;
import std.string;
import std.conv;
import std.algorithm.searching;
void main(){
auto str = readln.chomp;
if(str.canFind("a") && str.canFind("b") && str.canFind("c")){
"Yes".writeln;
}else{
"No".writeln;
}
}
| D |
void main() {
(48 - ri).writeln;
}
// ===================================
import std.stdio;
import std.string;
import std.conv;
import std.algorithm;
import std.range;
import std.traits;
import std.math;
import std.bigint;
import std.numeric;
import std.conv;
import std.typecons;
import std.uni;
import std.ascii;
import std.bitmanip;
import core.bitop;
T readAs(T)() if (isBasicType!T) {
return readln.chomp.to!T;
}
T readAs(T)() if (isArray!T) {
return readln.split.to!T;
}
T[][] readMatrix(T)(uint height, uint width) if (!isSomeChar!T) {
auto res = new T[][](height, width);
foreach(i; 0..height) {
res[i] = readAs!(T[]);
}
return res;
}
T[][] readMatrix(T)(uint height, uint width) if (isSomeChar!T) {
auto res = new T[][](height, width);
foreach(i; 0..height) {
auto s = rs;
foreach(j; 0..width) res[i][j] = s[j].to!T;
}
return res;
}
int ri() {
return readAs!int;
}
double rd() {
return readAs!double;
}
string rs() {
return readln.chomp;
}
| D |
'use strict';
var clear = require('es5-ext/array/#/clear')
, eIndexOf = require('es5-ext/array/#/e-index-of')
, setPrototypeOf = require('es5-ext/object/set-prototype-of')
, callable = require('es5-ext/object/valid-callable')
, d = require('d')
, ee = require('event-emitter')
, Symbol = require('es6-symbol')
, iterator = require('es6-iterator/valid-iterable')
, forOf = require('es6-iterator/for-of')
, Iterator = require('./lib/iterator')
, isNative = require('./is-native-implemented')
, call = Function.prototype.call, defineProperty = Object.defineProperty
, SetPoly, getValues;
module.exports = SetPoly = function (/*iterable*/) {
var iterable = arguments[0];
if (!(this instanceof SetPoly)) return new SetPoly(iterable);
if (this.__setData__ !== undefined) {
throw new TypeError(this + " cannot be reinitialized");
}
if (iterable != null) iterator(iterable);
defineProperty(this, '__setData__', d('c', []));
if (!iterable) return;
forOf(iterable, function (value) {
if (eIndexOf.call(this, value) !== -1) return;
this.push(value);
}, this.__setData__);
};
if (isNative) {
if (setPrototypeOf) setPrototypeOf(SetPoly, Set);
SetPoly.prototype = Object.create(Set.prototype, {
constructor: d(SetPoly)
});
}
ee(Object.defineProperties(SetPoly.prototype, {
add: d(function (value) {
if (this.has(value)) return this;
this.emit('_add', this.__setData__.push(value) - 1, value);
return this;
}),
clear: d(function () {
if (!this.__setData__.length) return;
clear.call(this.__setData__);
this.emit('_clear');
}),
delete: d(function (value) {
var index = eIndexOf.call(this.__setData__, value);
if (index === -1) return false;
this.__setData__.splice(index, 1);
this.emit('_delete', index, value);
return true;
}),
entries: d(function () { return new Iterator(this, 'key+value'); }),
forEach: d(function (cb/*, thisArg*/) {
var thisArg = arguments[1], iterator, result, value;
callable(cb);
iterator = this.values();
result = iterator._next();
while (result !== undefined) {
value = iterator._resolve(result);
call.call(cb, thisArg, value, value, this);
result = iterator._next();
}
}),
has: d(function (value) {
return (eIndexOf.call(this.__setData__, value) !== -1);
}),
keys: d(getValues = function () { return this.values(); }),
size: d.gs(function () { return this.__setData__.length; }),
values: d(function () { return new Iterator(this); }),
toString: d(function () { return '[object Set]'; })
}));
defineProperty(SetPoly.prototype, Symbol.iterator, d(getValues));
defineProperty(SetPoly.prototype, Symbol.toStringTag, d('c', 'Set'));
| Java |
'use strict';
const TYPE = Symbol.for('type');
class Data {
constructor(options) {
// File details
this.filepath = options.filepath;
// Type
this[TYPE] = 'data';
// Data
Object.assign(this, options.data);
}
}
module.exports = Data;
| Java |
package sodium
// #cgo pkg-config: libsodium
// #include <stdlib.h>
// #include <sodium.h>
import "C"
func RuntimeHasNeon() bool {
return C.sodium_runtime_has_neon() != 0
}
func RuntimeHasSse2() bool {
return C.sodium_runtime_has_sse2() != 0
}
func RuntimeHasSse3() bool {
return C.sodium_runtime_has_sse3() != 0
}
| Java |
function collectWithWildcard(test) {
test.expect(4);
var api_server = new Test_ApiServer(function handler(request, callback) {
var url = request.url;
switch (url) {
case '/accounts?username=chariz*':
let account = new Model_Account({
username: 'charizard'
});
return void callback(null, [
account.redact()
]);
default:
let error = new Error('Invalid url: ' + url);
return void callback(error);
}
});
var parameters = {
username: 'chariz*'
};
function handler(error, results) {
test.equals(error, null);
test.equals(results.length, 1);
var account = results[0];
test.equals(account.get('username'), 'charizard');
test.equals(account.get('type'), Enum_AccountTypes.MEMBER);
api_server.destroy();
test.done();
}
Resource_Accounts.collect(parameters, handler);
}
module.exports = {
collectWithWildcard
};
| Java |
<?php
interface Container {
/**
* Checks if a $x exists.
*
* @param unknown $x
*
* @return boolean
*/
function contains($x);
} | Java |
/*
* Read and write JSON.
*
* Copyright (c) 2014 Marko Kreen
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <usual/json.h>
#include <usual/cxextra.h>
#include <usual/cbtree.h>
#include <usual/misc.h>
#include <usual/utf8.h>
#include <usual/ctype.h>
#include <usual/bytemap.h>
#include <usual/string.h>
#include <math.h>
#define TYPE_BITS 3
#define TYPE_MASK ((1 << TYPE_BITS) - 1)
#define UNATTACHED ((struct JsonValue *)(1 << TYPE_BITS))
#define JSON_MAX_KEY (1024*1024)
#define NUMBER_BUF 100
#define JSON_MAXINT ((1LL << 53) - 1)
#define JSON_MININT (-(1LL << 53) + 1)
/*
* Common struct for all JSON values
*/
struct JsonValue {
/* actual value for simple types */
union {
double v_float; /* float */
int64_t v_int; /* int */
bool v_bool; /* bool */
size_t v_size; /* str/list/dict */
} u;
/* pointer to next elem and type in low bits */
uintptr_t v_next_and_type;
};
/*
* List container.
*/
struct ValueList {
struct JsonValue *first;
struct JsonValue *last;
struct JsonValue **array;
};
/*
* Extra data for list/dict.
*/
struct JsonContainer {
/* parent container */
struct JsonValue *c_parent;
/* main context for child alloc */
struct JsonContext *c_ctx;
/* child elements */
union {
struct CBTree *c_dict;
struct ValueList c_list;
} u;
};
#define DICT_EXTRA (offsetof(struct JsonContainer, u.c_dict) + sizeof(struct CBTree *))
#define LIST_EXTRA (sizeof(struct JsonContainer))
/*
* Allocation context.
*/
struct JsonContext {
CxMem *pool;
unsigned int options;
/* parse state */
struct JsonValue *parent;
struct JsonValue *cur_key;
struct JsonValue *top;
const char *lasterr;
char errbuf[128];
int64_t linenr;
};
struct RenderState {
struct MBuf *dst;
unsigned int options;
};
/*
* Parser states
*/
enum ParseState {
S_INITIAL_VALUE = 1,
S_LIST_VALUE,
S_LIST_VALUE_OR_CLOSE,
S_LIST_COMMA_OR_CLOSE,
S_DICT_KEY,
S_DICT_KEY_OR_CLOSE,
S_DICT_COLON,
S_DICT_VALUE,
S_DICT_COMMA_OR_CLOSE,
S_PARENT,
S_DONE,
MAX_STATES,
};
/*
* Tokens that change state.
*/
enum TokenTypes {
T_STRING,
T_OTHER,
T_COMMA,
T_COLON,
T_OPEN_DICT,
T_OPEN_LIST,
T_CLOSE_DICT,
T_CLOSE_LIST,
MAX_TOKENS
};
/*
* 4-byte ints for small string tokens.
*/
#define C_NULL FOURCC('n','u','l','l')
#define C_TRUE FOURCC('t','r','u','e')
#define C_ALSE FOURCC('a','l','s','e')
/*
* Signature for render functions.
*/
typedef bool (*render_func_t)(struct RenderState *rs, struct JsonValue *jv);
static bool render_any(struct RenderState *rs, struct JsonValue *jv);
/*
* Header manipulation
*/
static inline enum JsonValueType get_type(struct JsonValue *jv)
{
return jv->v_next_and_type & TYPE_MASK;
}
static inline bool has_type(struct JsonValue *jv, enum JsonValueType type)
{
if (!jv)
return false;
return get_type(jv) == type;
}
static inline struct JsonValue *get_next(struct JsonValue *jv)
{
return (struct JsonValue *)(jv->v_next_and_type & ~(uintptr_t)TYPE_MASK);
}
static inline void set_next(struct JsonValue *jv, struct JsonValue *next)
{
jv->v_next_and_type = (uintptr_t)next | get_type(jv);
}
static inline bool is_unattached(struct JsonValue *jv)
{
return get_next(jv) == UNATTACHED;
}
static inline void *get_extra(struct JsonValue *jv)
{
return (void *)(jv + 1);
}
static inline char *get_cstring(struct JsonValue *jv)
{
enum JsonValueType type = get_type(jv);
if (type != JSON_STRING)
return NULL;
return get_extra(jv);
}
/*
* Collection header manipulation.
*/
static inline struct JsonContainer *get_container(struct JsonValue *jv)
{
enum JsonValueType type = get_type(jv);
if (type != JSON_DICT && type != JSON_LIST)
return NULL;
return get_extra(jv);
}
static inline void set_parent(struct JsonValue *jv, struct JsonValue *parent)
{
struct JsonContainer *c = get_container(jv);
if (c)
c->c_parent = parent;
}
static inline struct JsonContext *get_context(struct JsonValue *jv)
{
struct JsonContainer *c = get_container(jv);
return c ? c->c_ctx : NULL;
}
static inline struct CBTree *get_dict_tree(struct JsonValue *jv)
{
struct JsonContainer *c;
if (has_type(jv, JSON_DICT)) {
c = get_container(jv);
return c->u.c_dict;
}
return NULL;
}
static inline struct ValueList *get_list_vlist(struct JsonValue *jv)
{
struct JsonContainer *c;
if (has_type(jv, JSON_LIST)) {
c = get_container(jv);
return &c->u.c_list;
}
return NULL;
}
/*
* Random helpers
*/
/* copy and return final pointer */
static inline char *plain_copy(char *dst, const char *src, const char *endptr)
{
if (src < endptr) {
memcpy(dst, src, endptr - src);
return dst + (endptr - src);
}
return dst;
}
/* error message on context */
_PRINTF(2,0)
static void format_err(struct JsonContext *ctx, const char *errmsg, va_list ap)
{
char buf[119];
if (ctx->lasterr)
return;
vsnprintf(buf, sizeof(buf), errmsg, ap);
snprintf(ctx->errbuf, sizeof(ctx->errbuf), "Line #%" PRIi64 ": %s", ctx->linenr, buf);
ctx->lasterr = ctx->errbuf;
}
/* set message and return false */
_PRINTF(2,3)
static bool err_false(struct JsonContext *ctx, const char *errmsg, ...)
{
va_list ap;
va_start(ap, errmsg);
format_err(ctx, errmsg, ap);
va_end(ap);
return false;
}
/* set message and return NULL */
_PRINTF(2,3)
static void *err_null(struct JsonContext *ctx, const char *errmsg, ...)
{
va_list ap;
va_start(ap, errmsg);
format_err(ctx, errmsg, ap);
va_end(ap);
return NULL;
}
/* callback for cbtree, returns key bytes */
static size_t get_key_data_cb(void *dictptr, void *keyptr, const void **dst_p)
{
struct JsonValue *key = keyptr;
*dst_p = get_cstring(key);
return key->u.v_size;
}
/* add elemnt to list */
static void real_list_append(struct JsonValue *list, struct JsonValue *elem)
{
struct ValueList *vlist;
vlist = get_list_vlist(list);
if (vlist->last) {
set_next(vlist->last, elem);
} else {
vlist->first = elem;
}
vlist->last = elem;
vlist->array = NULL;
list->u.v_size++;
}
/* add key to tree */
static bool real_dict_add_key(struct JsonContext *ctx, struct JsonValue *dict, struct JsonValue *key)
{
struct CBTree *tree;
tree = get_dict_tree(dict);
if (!tree)
return err_false(ctx, "Expect dict");
if (json_value_size(key) > JSON_MAX_KEY)
return err_false(ctx, "Too large key");
dict->u.v_size++;
if (!cbtree_insert(tree, key))
return err_false(ctx, "Key insertion failed");
return true;
}
/* create basic value struct, link to stuctures */
static struct JsonValue *mk_value(struct JsonContext *ctx, enum JsonValueType type, size_t extra, bool attach)
{
struct JsonValue *val;
struct JsonContainer *col = NULL;
if (!ctx)
return NULL;
val = cx_alloc(ctx->pool, sizeof(struct JsonValue) + extra);
if (!val)
return err_null(ctx, "No memory");
if ((uintptr_t)val & TYPE_MASK)
return err_null(ctx, "Unaligned pointer");
/* initial value */
val->v_next_and_type = type;
val->u.v_int = 0;
if (type == JSON_DICT || type == JSON_LIST) {
col = get_container(val);
col->c_ctx = ctx;
col->c_parent = NULL;
if (type == JSON_DICT) {
col->u.c_dict = cbtree_create(get_key_data_cb, NULL, val, ctx->pool);
if (!col->u.c_dict)
return err_null(ctx, "No memory");
} else {
memset(&col->u.c_list, 0, sizeof(col->u.c_list));
}
}
/* independent JsonValue? */
if (!attach) {
set_next(val, UNATTACHED);
return val;
}
/* attach to parent */
if (col)
col->c_parent = ctx->parent;
/* attach to previous value */
if (has_type(ctx->parent, JSON_DICT)) {
if (ctx->cur_key) {
set_next(ctx->cur_key, val);
ctx->cur_key = NULL;
} else {
ctx->cur_key = val;
}
} else if (has_type(ctx->parent, JSON_LIST)) {
real_list_append(ctx->parent, val);
} else if (!ctx->top) {
ctx->top = val;
} else {
return err_null(ctx, "Only one top element is allowed");
}
return val;
}
static void prepare_array(struct JsonValue *list)
{
struct JsonContainer *c;
struct JsonValue *val;
struct ValueList *vlist;
size_t i;
vlist = get_list_vlist(list);
if (vlist->array)
return;
c = get_container(list);
vlist->array = cx_alloc(c->c_ctx->pool, list->u.v_size * sizeof(struct JsonValue *));
if (!vlist->array)
return;
val = vlist->first;
for (i = 0; i < list->u.v_size && val; i++) {
vlist->array[i] = val;
val = get_next(val);
}
}
/*
* Parsing code starts
*/
/* create and change context */
static bool open_container(struct JsonContext *ctx, enum JsonValueType type, unsigned int extra)
{
struct JsonValue *jv;
jv = mk_value(ctx, type, extra, true);
if (!jv)
return false;
ctx->parent = jv;
ctx->cur_key = NULL;
return true;
}
/* close and change context */
static enum ParseState close_container(struct JsonContext *ctx, enum ParseState state)
{
struct JsonContainer *c;
if (state != S_PARENT)
return (int)err_false(ctx, "close_container bug");
c = get_container(ctx->parent);
if (!c)
return (int)err_false(ctx, "invalid parent");
ctx->parent = c->c_parent;
ctx->cur_key = NULL;
if (has_type(ctx->parent, JSON_DICT)) {
return S_DICT_COMMA_OR_CLOSE;
} else if (has_type(ctx->parent, JSON_LIST)) {
return S_LIST_COMMA_OR_CLOSE;
}
return S_DONE;
}
/* parse 4-char token */
static bool parse_char4(struct JsonContext *ctx, const char **src_p, const char *end,
uint32_t t_exp, enum JsonValueType type, bool val)
{
const char *src;
uint32_t t_got;
struct JsonValue *jv;
src = *src_p;
if (src + 4 > end)
return err_false(ctx, "Unexpected end of token");
memcpy(&t_got, src, 4);
if (t_exp != t_got)
return err_false(ctx, "Invalid token");
jv = mk_value(ctx, type, 0, true);
if (!jv)
return false;
jv->u.v_bool = val;
*src_p += 4;
return true;
}
/* parse int or float */
static bool parse_number(struct JsonContext *ctx, const char **src_p, const char *end)
{
const char *start, *src;
enum JsonValueType type = JSON_INT;
char *tokend = NULL;
char buf[NUMBER_BUF];
size_t len;
struct JsonValue *jv;
double v_float = 0;
int64_t v_int = 0;
/* scan & copy */
start = src = *src_p;
for (; src < end; src++) {
if (*src >= '0' && *src <= '9') {
} else if (*src == '+' || *src == '-') {
} else if (*src == '.' || *src == 'e' || *src == 'E') {
type = JSON_FLOAT;
} else {
break;
}
}
len = src - start;
if (len >= NUMBER_BUF)
goto failed;
memcpy(buf, start, len);
buf[len] = 0;
/* now parse */
errno = 0;
tokend = buf;
if (type == JSON_FLOAT) {
v_float = strtod_dot(buf, &tokend);
if (*tokend != 0 || errno || !isfinite(v_float))
goto failed;
} else if (len < 8) {
v_int = strtol(buf, &tokend, 10);
if (*tokend != 0 || errno)
goto failed;
} else {
v_int = strtoll(buf, &tokend, 10);
if (*tokend != 0 || errno || v_int < JSON_MININT || v_int > JSON_MAXINT)
goto failed;
}
/* create value struct */
jv = mk_value(ctx, type, 0, true);
if (!jv)
return false;
if (type == JSON_FLOAT) {
jv->u.v_float = v_float;
} else {
jv->u.v_int = v_int;
}
*src_p = src;
return true;
failed:
if (!errno)
errno = EINVAL;
return err_false(ctx, "Number parse failed");
}
/*
* String parsing
*/
static int parse_hex(const char *s, const char *end)
{
int v = 0, c, i, x;
if (s + 4 > end)
return -1;
for (i = 0; i < 4; i++) {
c = s[i];
if (c >= '0' && c <= '9') {
x = c - '0';
} else if (c >= 'a' && c <= 'f') {
x = c - 'a' + 10;
} else if (c >= 'A' && c <= 'F') {
x = c - 'A' + 10;
} else {
return -1;
}
v = (v << 4) | x;
}
return v;
}
/* process \uXXXX escapes, merge surrogates */
static bool parse_uescape(struct JsonContext *ctx, char **dst_p, char *dstend,
const char **src_p, const char *end)
{
int c, c2;
const char *src = *src_p;
c = parse_hex(src, end);
if (c <= 0)
return err_false(ctx, "Invalid hex escape");
src += 4;
if (c >= 0xD800 && c <= 0xDFFF) {
/* first surrogate */
if (c >= 0xDC00)
return err_false(ctx, "Invalid UTF16 escape");
if (src + 6 > end)
return err_false(ctx, "Invalid UTF16 escape");
/* second surrogate */
if (src[0] != '\\' || src[1] != 'u')
return err_false(ctx, "Invalid UTF16 escape");
c2 = parse_hex(src + 2, end);
if (c2 < 0xDC00 || c2 > 0xDFFF)
return err_false(ctx, "Invalid UTF16 escape");
c = 0x10000 + ((c & 0x3FF) << 10) + (c2 & 0x3FF);
src += 6;
}
/* now write char */
if (!utf8_put_char(c, dst_p, dstend))
return err_false(ctx, "Invalid UTF16 escape");
*src_p = src;
return true;
}
#define meta_string(c) (((c) == '"' || (c) == '\\' || (c) == '\0' || \
(c) == '\n' || ((c) & 0x80) != 0) ? 1 : 0)
static const uint8_t string_examine_chars[] = INTMAP256_CONST(meta_string);
/* look for string end, validate contents */
static bool scan_string(struct JsonContext *ctx, const char *src, const char *end,
const char **str_end_p, bool *hasesc_p, int64_t *nlines_p)
{
bool hasesc = false;
int64_t lines = 0;
unsigned int n;
bool check_utf8 = true;
if (ctx->options & JSON_PARSE_IGNORE_ENCODING)
check_utf8 = false;
while (src < end) {
if (!string_examine_chars[(uint8_t)*src]) {
src++;
} else if (*src == '"') {
/* string end */
*hasesc_p = hasesc;
*str_end_p = src;
*nlines_p = lines;
return true;
} else if (*src == '\\') {
hasesc = true;
src++;
if (src < end && (*src == '\\' || *src == '"'))
src++;
} else if (*src & 0x80) {
n = utf8_validate_seq(src, end);
if (n) {
src += n;
} else if (check_utf8) {
goto badutf;
} else {
src++;
}
} else if (*src == '\n') {
lines++;
src++;
} else {
goto badutf;
}
}
return err_false(ctx, "Unexpected end of string");
badutf:
return err_false(ctx, "Invalid UTF8 sequence");
}
/* string boundaries are known, copy and unescape */
static char *process_escapes(struct JsonContext *ctx,
const char *src, const char *end,
char *dst, char *dstend)
{
const char *esc;
/* process escapes */
while (src < end) {
esc = memchr(src, '\\', end - src);
if (!esc) {
dst = plain_copy(dst, src, end);
break;
}
dst = plain_copy(dst, src, esc);
src = esc + 1;
switch (*src++) {
case '"': *dst++ = '"'; break;
case '\\': *dst++ = '\\'; break;
case '/': *dst++ = '/'; break;
case 'b': *dst++ = '\b'; break;
case 'f': *dst++ = '\f'; break;
case 'n': *dst++ = '\n'; break;
case 'r': *dst++ = '\r'; break;
case 't': *dst++ = '\t'; break;
case 'u':
if (!parse_uescape(ctx, &dst, dstend, &src, end))
return NULL;
break;
default:
return err_null(ctx, "Invalid escape code");
}
}
return dst;
}
/* 2-phase string processing */
static bool parse_string(struct JsonContext *ctx, const char **src_p, const char *end)
{
const char *start, *strend = NULL;
bool hasesc = false;
char *dst, *dstend;
size_t len;
struct JsonValue *jv;
int64_t lines = 0;
/* find string boundaries, validate */
start = *src_p;
if (!scan_string(ctx, start, end, &strend, &hasesc, &lines))
return false;
/* create value struct */
len = strend - start;
jv = mk_value(ctx, JSON_STRING, len + 1, true);
if (!jv)
return false;
dst = get_cstring(jv);
dstend = dst + len;
/* copy & process escapes */
if (hasesc) {
dst = process_escapes(ctx, start, strend, dst, dstend);
if (!dst)
return false;
} else {
dst = plain_copy(dst, start, strend);
}
*dst = '\0';
jv->u.v_size = dst - get_cstring(jv);
ctx->linenr += lines;
*src_p = strend + 1;
return true;
}
/*
* Helpers for relaxed parsing
*/
static bool skip_comment(struct JsonContext *ctx, const char **src_p, const char *end)
{
const char *s, *start;
char c;
size_t lnr;
s = start = *src_p;
if (s >= end)
return false;
c = *s++;
if (c == '/') {
s = memchr(s, '\n', end - s);
if (s) {
ctx->linenr++;
*src_p = s + 1;
} else {
*src_p = end;
}
return true;
} else if (c == '*') {
for (lnr = 0; s + 2 <= end; s++) {
if (s[0] == '*' && s[1] == '/') {
ctx->linenr += lnr;
*src_p = s + 2;
return true;
} else if (s[0] == '\n') {
lnr++;
}
}
}
return false;
}
static bool skip_extra_comma(struct JsonContext *ctx, const char **src_p, const char *end, enum ParseState state)
{
bool skip = false;
const char *src = *src_p;
while (src < end && isspace(*src)) {
if (*src == '\n')
ctx->linenr++;
src++;
}
if (src < end) {
if (*src == '}') {
if (state == S_DICT_COMMA_OR_CLOSE || state == S_DICT_KEY_OR_CLOSE)
skip = true;
} else if (*src == ']') {
if (state == S_LIST_COMMA_OR_CLOSE || state == S_LIST_VALUE_OR_CLOSE)
skip = true;
}
}
*src_p = src;
return skip;
}
/*
* Main parser
*/
/* oldstate + token -> newstate */
static const unsigned char STATE_STEPS[MAX_STATES][MAX_TOKENS] = {
[S_INITIAL_VALUE] = {
[T_OPEN_LIST] = S_LIST_VALUE_OR_CLOSE,
[T_OPEN_DICT] = S_DICT_KEY_OR_CLOSE,
[T_STRING] = S_DONE,
[T_OTHER] = S_DONE },
[S_LIST_VALUE] = {
[T_OPEN_LIST] = S_LIST_VALUE_OR_CLOSE,
[T_OPEN_DICT] = S_DICT_KEY_OR_CLOSE,
[T_STRING] = S_LIST_COMMA_OR_CLOSE,
[T_OTHER] = S_LIST_COMMA_OR_CLOSE },
[S_LIST_VALUE_OR_CLOSE] = {
[T_OPEN_LIST] = S_LIST_VALUE_OR_CLOSE,
[T_OPEN_DICT] = S_DICT_KEY_OR_CLOSE,
[T_STRING] = S_LIST_COMMA_OR_CLOSE,
[T_OTHER] = S_LIST_COMMA_OR_CLOSE,
[T_CLOSE_LIST] = S_PARENT },
[S_LIST_COMMA_OR_CLOSE] = {
[T_COMMA] = S_LIST_VALUE,
[T_CLOSE_LIST] = S_PARENT },
[S_DICT_KEY] = {
[T_STRING] = S_DICT_COLON },
[S_DICT_KEY_OR_CLOSE] = {
[T_STRING] = S_DICT_COLON,
[T_CLOSE_DICT] = S_PARENT },
[S_DICT_COLON] = {
[T_COLON] = S_DICT_VALUE },
[S_DICT_VALUE] = {
[T_OPEN_LIST] = S_LIST_VALUE_OR_CLOSE,
[T_OPEN_DICT] = S_DICT_KEY_OR_CLOSE,
[T_STRING] = S_DICT_COMMA_OR_CLOSE,
[T_OTHER] = S_DICT_COMMA_OR_CLOSE },
[S_DICT_COMMA_OR_CLOSE] = {
[T_COMMA] = S_DICT_KEY,
[T_CLOSE_DICT] = S_PARENT },
};
#define MAPSTATE(state, tok) do { \
int newstate = STATE_STEPS[state][tok]; \
if (!newstate) \
return err_false(ctx, "Unexpected symbol: '%c'", c); \
state = newstate; \
} while (0)
/* actual parser */
static bool parse_tokens(struct JsonContext *ctx, const char *src, const char *end)
{
char c;
enum ParseState state = S_INITIAL_VALUE;
bool relaxed = ctx->options & JSON_PARSE_RELAXED;
while (src < end) {
c = *src++;
switch (c) {
case '\n':
ctx->linenr++;
case ' ': case '\t': case '\r': case '\f': case '\v':
/* common case - many spaces */
while (src < end && *src == ' ') src++;
break;
case '"':
MAPSTATE(state, T_STRING);
if (!parse_string(ctx, &src, end))
goto failed;
break;
case 'n':
MAPSTATE(state, T_OTHER);
src--;
if (!parse_char4(ctx, &src, end, C_NULL, JSON_NULL, 0))
goto failed;
continue;
case 't':
MAPSTATE(state, T_OTHER);
src--;
if (!parse_char4(ctx, &src, end, C_TRUE, JSON_BOOL, 1))
goto failed;
break;
case 'f':
MAPSTATE(state, T_OTHER);
if (!parse_char4(ctx, &src, end, C_ALSE, JSON_BOOL, 0))
goto failed;
break;
case '-':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
MAPSTATE(state, T_OTHER);
src--;
if (!parse_number(ctx, &src, end))
goto failed;
break;
case '[':
MAPSTATE(state, T_OPEN_LIST);
if (!open_container(ctx, JSON_LIST, LIST_EXTRA))
goto failed;
break;
case '{':
MAPSTATE(state, T_OPEN_DICT);
if (!open_container(ctx, JSON_DICT, DICT_EXTRA))
goto failed;
break;
case ']':
MAPSTATE(state, T_CLOSE_LIST);
state = close_container(ctx, state);
if (!state)
goto failed;
break;
case '}':
MAPSTATE(state, T_CLOSE_DICT);
state = close_container(ctx, state);
if (!state)
goto failed;
break;
case ':':
MAPSTATE(state, T_COLON);
if (!real_dict_add_key(ctx, ctx->parent, ctx->cur_key))
goto failed;
break;
case ',':
if (relaxed && skip_extra_comma(ctx, &src, end, state))
continue;
MAPSTATE(state, T_COMMA);
break;
case '/':
if (relaxed && skip_comment(ctx, &src, end))
continue;
/* fallthrough */
default:
return err_false(ctx, "Invalid symbol: '%c'", c);
}
}
if (state != S_DONE)
return err_false(ctx, "Container still open");
return true;
failed:
return false;
}
/* parser public api */
struct JsonValue *json_parse(struct JsonContext *ctx, const char *json, size_t len)
{
const char *end = json + len;
/* reset parser */
ctx->linenr = 1;
ctx->parent = NULL;
ctx->cur_key = NULL;
ctx->lasterr = NULL;
ctx->top = NULL;
if (!parse_tokens(ctx, json, end))
return NULL;
return ctx->top;
}
/*
* Render value as JSON string.
*/
static bool render_null(struct RenderState *rs, struct JsonValue *jv)
{
return mbuf_write(rs->dst, "null", 4);
}
static bool render_bool(struct RenderState *rs, struct JsonValue *jv)
{
if (jv->u.v_bool)
return mbuf_write(rs->dst, "true", 4);
return mbuf_write(rs->dst, "false", 5);
}
static bool render_int(struct RenderState *rs, struct JsonValue *jv)
{
char buf[NUMBER_BUF];
int len;
len = snprintf(buf, sizeof(buf), "%" PRIi64, jv->u.v_int);
if (len < 0 || len >= NUMBER_BUF)
return false;
return mbuf_write(rs->dst, buf, len);
}
static bool render_float(struct RenderState *rs, struct JsonValue *jv)
{
char buf[NUMBER_BUF + 2];
int len;
len = dtostr_dot(buf, NUMBER_BUF, jv->u.v_float);
if (len < 0 || len >= NUMBER_BUF)
return false;
if (!memchr(buf, '.', len) && !memchr(buf, 'e', len)) {
buf[len++] = '.';
buf[len++] = '0';
}
return mbuf_write(rs->dst, buf, len);
}
static bool escape_char(struct MBuf *dst, unsigned int c)
{
char ec;
char buf[10];
/* start escape */
if (!mbuf_write_byte(dst, '\\'))
return false;
/* escape same char */
if (c == '"' || c == '\\')
return mbuf_write_byte(dst, c);
/* low-ascii mess */
switch (c) {
case '\b': ec = 'b'; break;
case '\f': ec = 'f'; break;
case '\n': ec = 'n'; break;
case '\r': ec = 'r'; break;
case '\t': ec = 't'; break;
default:
snprintf(buf, sizeof(buf), "u%04x", c);
return mbuf_write(dst, buf, 5);
}
return mbuf_write_byte(dst, ec);
}
static bool render_string(struct RenderState *rs, struct JsonValue *jv)
{
const char *s, *last;
const char *val = get_cstring(jv);
size_t len = jv->u.v_size;
const char *end = val + len;
unsigned int c;
/* start quote */
if (!mbuf_write_byte(rs->dst, '"'))
return false;
for (s = last = val; s < end; s++) {
if (*s == '"' || *s == '\\' || (unsigned char)*s < 0x20 ||
/* Valid in JSON, but not in JS:
\u2028 - Line separator
\u2029 - Paragraph separator */
((unsigned char)s[0] == 0xE2 && (unsigned char)s[1] == 0x80 &&
((unsigned char)s[2] == 0xA8 || (unsigned char)s[2] == 0xA9)))
{
/* flush */
if (last < s) {
if (!mbuf_write(rs->dst, last, s - last))
return false;
}
if ((unsigned char)s[0] == 0xE2) {
c = 0x2028 + ((unsigned char)s[2] - 0xA8);
last = s + 3;
} else {
c = (unsigned char)*s;
last = s + 1;
}
/* output escaped char */
if (!escape_char(rs->dst, c))
return false;
}
}
/* flush */
if (last < s) {
if (!mbuf_write(rs->dst, last, s - last))
return false;
}
/* final quote */
if (!mbuf_write_byte(rs->dst, '"'))
return false;
return true;
}
/*
* Render complex values
*/
struct ElemWriterState {
struct RenderState *rs;
char sep;
};
static bool list_elem_writer(void *arg, struct JsonValue *elem)
{
struct ElemWriterState *state = arg;
if (state->sep && !mbuf_write_byte(state->rs->dst, state->sep))
return false;
state->sep = ',';
return render_any(state->rs, elem);
}
static bool render_list(struct RenderState *rs, struct JsonValue *list)
{
struct ElemWriterState state;
state.rs = rs;
state.sep = 0;
if (!mbuf_write_byte(rs->dst, '['))
return false;
if (!json_list_iter(list, list_elem_writer, &state))
return false;
if (!mbuf_write_byte(rs->dst, ']'))
return false;
return true;
}
static bool dict_elem_writer(void *ctx, struct JsonValue *key, struct JsonValue *val)
{
struct ElemWriterState *state = ctx;
if (state->sep && !mbuf_write_byte(state->rs->dst, state->sep))
return false;
state->sep = ',';
if (!render_any(state->rs, key))
return false;
if (!mbuf_write_byte(state->rs->dst, ':'))
return false;
return render_any(state->rs, val);
}
static bool render_dict(struct RenderState *rs, struct JsonValue *dict)
{
struct ElemWriterState state;
state.rs = rs;
state.sep = 0;
if (!mbuf_write_byte(rs->dst, '{'))
return false;
if (!json_dict_iter(dict, dict_elem_writer, &state))
return false;
if (!mbuf_write_byte(rs->dst, '}'))
return false;
return true;
}
static bool render_invalid(struct RenderState *rs, struct JsonValue *jv)
{
return false;
}
/*
* Public api
*/
static bool render_any(struct RenderState *rs, struct JsonValue *jv)
{
static const render_func_t rfunc_map[] = {
render_invalid, render_null, render_bool, render_int,
render_float, render_string, render_list, render_dict,
};
return rfunc_map[get_type(jv)](rs, jv);
}
bool json_render(struct MBuf *dst, struct JsonValue *jv)
{
struct RenderState rs;
rs.dst = dst;
rs.options = 0;
return render_any(&rs, jv);
}
/*
* Examine single value
*/
enum JsonValueType json_value_type(struct JsonValue *jv)
{
return get_type(jv);
}
size_t json_value_size(struct JsonValue *jv)
{
if (has_type(jv, JSON_STRING) ||
has_type(jv, JSON_LIST) ||
has_type(jv, JSON_DICT))
return jv->u.v_size;
return 0;
}
bool json_value_as_bool(struct JsonValue *jv, bool *dst_p)
{
if (!has_type(jv, JSON_BOOL))
return false;
*dst_p = jv->u.v_bool;
return true;
}
bool json_value_as_int(struct JsonValue *jv, int64_t *dst_p)
{
if (!has_type(jv, JSON_INT))
return false;
*dst_p = jv->u.v_int;
return true;
}
bool json_value_as_float(struct JsonValue *jv, double *dst_p)
{
if (!has_type(jv, JSON_FLOAT)) {
if (has_type(jv, JSON_INT)) {
*dst_p = jv->u.v_int;
return true;
}
return false;
}
*dst_p = jv->u.v_float;
return true;
}
bool json_value_as_string(struct JsonValue *jv, const char **dst_p, size_t *size_p)
{
if (!has_type(jv, JSON_STRING))
return false;
*dst_p = get_cstring(jv);
if (size_p)
*size_p = jv->u.v_size;
return true;
}
/*
* Load value from dict.
*/
static int dict_getter(struct JsonValue *dict,
const char *key, unsigned int klen,
struct JsonValue **val_p,
enum JsonValueType req_type, bool req_value)
{
struct JsonValue *val, *kjv;
struct CBTree *tree;
tree = get_dict_tree(dict);
if (!tree)
return false;
kjv = cbtree_lookup(tree, key, klen);
if (!kjv) {
if (req_value)
return false;
*val_p = NULL;
return true;
}
val = get_next(kjv);
if (!req_value && json_value_is_null(val)) {
*val_p = NULL;
return true;
}
if (!has_type(val, req_type))
return false;
*val_p = val;
return true;
}
bool json_dict_get_value(struct JsonValue *dict, const char *key, struct JsonValue **val_p)
{
struct CBTree *tree;
struct JsonValue *kjv;
size_t klen;
tree = get_dict_tree(dict);
if (!tree)
return false;
klen = strlen(key);
kjv = cbtree_lookup(tree, key, klen);
if (!kjv)
return false;
*val_p = get_next(kjv);
return true;
}
bool json_dict_is_null(struct JsonValue *dict, const char *key)
{
struct JsonValue *val;
if (!json_dict_get_value(dict, key, &val))
return true;
return has_type(val, JSON_NULL);
}
bool json_dict_get_bool(struct JsonValue *dict, const char *key, bool *dst_p)
{
struct JsonValue *val;
if (!dict_getter(dict, key, strlen(key), &val, JSON_BOOL, true))
return false;
return json_value_as_bool(val, dst_p);
}
bool json_dict_get_int(struct JsonValue *dict, const char *key, int64_t *dst_p)
{
struct JsonValue *val;
if (!dict_getter(dict, key, strlen(key), &val, JSON_INT, true))
return false;
return json_value_as_int(val, dst_p);
}
bool json_dict_get_float(struct JsonValue *dict, const char *key, double *dst_p)
{
struct JsonValue *val;
if (!dict_getter(dict, key, strlen(key), &val, JSON_FLOAT, true))
return false;
return json_value_as_float(val, dst_p);
}
bool json_dict_get_string(struct JsonValue *dict, const char *key, const char **dst_p, size_t *len_p)
{
struct JsonValue *val;
if (!dict_getter(dict, key, strlen(key), &val, JSON_STRING, true))
return false;
return json_value_as_string(val, dst_p, len_p);
}
bool json_dict_get_list(struct JsonValue *dict, const char *key, struct JsonValue **dst_p)
{
return dict_getter(dict, key, strlen(key), dst_p, JSON_LIST, true);
}
bool json_dict_get_dict(struct JsonValue *dict, const char *key, struct JsonValue **dst_p)
{
return dict_getter(dict, key, strlen(key), dst_p, JSON_DICT, true);
}
/*
* Load optional dict element.
*/
bool json_dict_get_opt_bool(struct JsonValue *dict, const char *key, bool *dst_p)
{
struct JsonValue *val;
if (!dict_getter(dict, key, strlen(key), &val, JSON_BOOL, false))
return false;
return !val || json_value_as_bool(val, dst_p);
}
bool json_dict_get_opt_int(struct JsonValue *dict, const char *key, int64_t *dst_p)
{
struct JsonValue *val;
if (!dict_getter(dict, key, strlen(key), &val, JSON_INT, false))
return false;
return !val || json_value_as_int(val, dst_p);
}
bool json_dict_get_opt_float(struct JsonValue *dict, const char *key, double *dst_p)
{
struct JsonValue *val;
if (!dict_getter(dict, key, strlen(key), &val, JSON_FLOAT, false))
return false;
return !val || json_value_as_float(val, dst_p);
}
bool json_dict_get_opt_string(struct JsonValue *dict, const char *key, const char **dst_p, size_t *len_p)
{
struct JsonValue *val;
if (!dict_getter(dict, key, strlen(key), &val, JSON_STRING, false))
return false;
return !val || json_value_as_string(val, dst_p, len_p);
}
bool json_dict_get_opt_list(struct JsonValue *dict, const char *key, struct JsonValue **dst_p)
{
struct JsonValue *val;
if (!dict_getter(dict, key, strlen(key), &val, JSON_LIST, false))
return false;
if (val)
*dst_p = val;
return true;
}
bool json_dict_get_opt_dict(struct JsonValue *dict, const char *key, struct JsonValue **dst_p)
{
struct JsonValue *val;
if (!dict_getter(dict, key, strlen(key), &val, JSON_DICT, false))
return false;
if (val)
*dst_p = val;
return true;
}
/*
* Load value from list.
*/
bool json_list_get_value(struct JsonValue *list, size_t index, struct JsonValue **val_p)
{
struct JsonValue *val;
struct ValueList *vlist;
size_t i;
vlist = get_list_vlist(list);
if (!vlist)
return false;
if (index >= list->u.v_size)
return false;
if (!vlist->array && list->u.v_size > 10)
prepare_array(list);
/* direct fetch */
if (vlist->array) {
*val_p = vlist->array[index];
return true;
}
/* walk */
val = vlist->first;
for (i = 0; val; i++) {
if (i == index) {
*val_p = val;
return true;
}
val = get_next(val);
}
return false;
}
bool json_list_is_null(struct JsonValue *list, size_t n)
{
struct JsonValue *jv;
if (!json_list_get_value(list, n, &jv))
return true;
return has_type(jv, JSON_NULL);
}
bool json_list_get_bool(struct JsonValue *list, size_t index, bool *val_p)
{
struct JsonValue *jv;
if (!json_list_get_value(list, index, &jv))
return false;
return json_value_as_bool(jv, val_p);
}
bool json_list_get_int(struct JsonValue *list, size_t index, int64_t *val_p)
{
struct JsonValue *jv;
if (!json_list_get_value(list, index, &jv))
return false;
return json_value_as_int(jv, val_p);
}
bool json_list_get_float(struct JsonValue *list, size_t index, double *val_p)
{
struct JsonValue *jv;
if (!json_list_get_value(list, index, &jv))
return false;
return json_value_as_float(jv, val_p);
}
bool json_list_get_string(struct JsonValue *list, size_t index, const char **val_p, size_t *len_p)
{
struct JsonValue *jv;
if (!json_list_get_value(list, index, &jv))
return false;
return json_value_as_string(jv, val_p, len_p);
}
bool json_list_get_list(struct JsonValue *list, size_t index, struct JsonValue **val_p)
{
struct JsonValue *jv;
if (!json_list_get_value(list, index, &jv))
return false;
if (!has_type(jv, JSON_LIST))
return false;
*val_p = jv;
return true;
}
bool json_list_get_dict(struct JsonValue *list, size_t index, struct JsonValue **val_p)
{
struct JsonValue *jv;
if (!json_list_get_value(list, index, &jv))
return false;
if (!has_type(jv, JSON_DICT))
return false;
*val_p = jv;
return true;
}
/*
* Iterate over list and dict values.
*/
struct DictIterState {
json_dict_iter_callback_f cb_func;
void *cb_arg;
};
static bool dict_iter_helper(void *arg, void *jv)
{
struct DictIterState *state = arg;
struct JsonValue *key = jv;
struct JsonValue *val = get_next(key);
return state->cb_func(state->cb_arg, key, val);
}
bool json_dict_iter(struct JsonValue *dict, json_dict_iter_callback_f cb_func, void *cb_arg)
{
struct DictIterState state;
struct CBTree *tree;
tree = get_dict_tree(dict);
if (!tree)
return false;
state.cb_func = cb_func;
state.cb_arg = cb_arg;
return cbtree_walk(tree, dict_iter_helper, &state);
}
bool json_list_iter(struct JsonValue *list, json_list_iter_callback_f cb_func, void *cb_arg)
{
struct JsonValue *elem;
struct ValueList *vlist;
vlist = get_list_vlist(list);
if (!vlist)
return false;
for (elem = vlist->first; elem; elem = get_next(elem)) {
if (!cb_func(cb_arg, elem))
return false;
}
return true;
}
/*
* Create new values.
*/
struct JsonValue *json_new_null(struct JsonContext *ctx)
{
return mk_value(ctx, JSON_NULL, 0, false);
}
struct JsonValue *json_new_bool(struct JsonContext *ctx, bool val)
{
struct JsonValue *jv;
jv = mk_value(ctx, JSON_BOOL, 0, false);
if (jv)
jv->u.v_bool = val;
return jv;
}
struct JsonValue *json_new_int(struct JsonContext *ctx, int64_t val)
{
struct JsonValue *jv;
if (val < JSON_MININT || val > JSON_MAXINT) {
errno = ERANGE;
return NULL;
}
jv = mk_value(ctx, JSON_INT, 0, false);
if (jv)
jv->u.v_int = val;
return jv;
}
struct JsonValue *json_new_float(struct JsonContext *ctx, double val)
{
struct JsonValue *jv;
/* check if value survives JSON roundtrip */
if (!isfinite(val))
return false;
jv = mk_value(ctx, JSON_FLOAT, 0, false);
if (jv)
jv->u.v_float = val;
return jv;
}
struct JsonValue *json_new_string(struct JsonContext *ctx, const char *val)
{
struct JsonValue *jv;
size_t len;
len = strlen(val);
if (!utf8_validate_string(val, val + len))
return NULL;
jv = mk_value(ctx, JSON_STRING, len + 1, false);
if (jv) {
memcpy(get_cstring(jv), val, len + 1);
jv->u.v_size = len;
}
return jv;
}
struct JsonValue *json_new_list(struct JsonContext *ctx)
{
return mk_value(ctx, JSON_LIST, LIST_EXTRA, false);
}
struct JsonValue *json_new_dict(struct JsonContext *ctx)
{
return mk_value(ctx, JSON_DICT, DICT_EXTRA, false);
}
/*
* Add to containers
*/
bool json_list_append(struct JsonValue *list, struct JsonValue *val)
{
if (!val)
return false;
if (!has_type(list, JSON_LIST))
return false;
if (!is_unattached(val))
return false;
set_parent(val, list);
set_next(val, NULL);
real_list_append(list, val);
return true;
}
bool json_list_append_null(struct JsonValue *list)
{
struct JsonValue *v;
v = json_new_null(get_context(list));
return json_list_append(list, v);
}
bool json_list_append_bool(struct JsonValue *list, bool val)
{
struct JsonValue *v;
v = json_new_bool(get_context(list), val);
return json_list_append(list, v);
}
bool json_list_append_int(struct JsonValue *list, int64_t val)
{
struct JsonValue *v;
v = json_new_int(get_context(list), val);
return json_list_append(list, v);
}
bool json_list_append_float(struct JsonValue *list, double val)
{
struct JsonValue *v;
v = json_new_float(get_context(list), val);
return json_list_append(list, v);
}
bool json_list_append_string(struct JsonValue *list, const char *val)
{
struct JsonValue *v;
v = json_new_string(get_context(list), val);
return json_list_append(list, v);
}
bool json_dict_put(struct JsonValue *dict, const char *key, struct JsonValue *val)
{
struct JsonValue *kjv;
struct JsonContainer *c;
if (!key || !val)
return false;
if (!has_type(dict, JSON_DICT))
return false;
if (!is_unattached(val))
return false;
c = get_container(dict);
kjv = json_new_string(c->c_ctx, key);
if (!kjv)
return false;
if (!real_dict_add_key(c->c_ctx, dict, kjv))
return false;
set_next(kjv, val);
set_next(val, NULL);
set_parent(val, dict);
return true;
}
bool json_dict_put_null(struct JsonValue *dict, const char *key)
{
struct JsonValue *v;
v = json_new_null(get_context(dict));
return json_dict_put(dict, key, v);
}
bool json_dict_put_bool(struct JsonValue *dict, const char *key, bool val)
{
struct JsonValue *v;
v = json_new_bool(get_context(dict), val);
return json_dict_put(dict, key, v);
}
bool json_dict_put_int(struct JsonValue *dict, const char *key, int64_t val)
{
struct JsonValue *v;
v = json_new_int(get_context(dict), val);
return json_dict_put(dict, key, v);
}
bool json_dict_put_float(struct JsonValue *dict, const char *key, double val)
{
struct JsonValue *v;
v = json_new_float(get_context(dict), val);
return json_dict_put(dict, key, v);
}
bool json_dict_put_string(struct JsonValue *dict, const char *key, const char *val)
{
struct JsonValue *v;
v = json_new_string(get_context(dict), val);
return json_dict_put(dict, key, v);
}
/*
* Main context management
*/
struct JsonContext *json_new_context(const void *cx, size_t initial_mem)
{
struct JsonContext *ctx;
CxMem *pool;
pool = cx_new_pool(cx, initial_mem, 8);
if (!pool)
return NULL;
ctx = cx_alloc0(pool, sizeof(*ctx));
if (!ctx) {
cx_destroy(pool);
return NULL;
}
ctx->pool = pool;
return ctx;
}
void json_free_context(struct JsonContext *ctx)
{
if (ctx) {
CxMem *pool = ctx->pool;
memset(ctx, 0, sizeof(*ctx));
cx_destroy(pool);
}
}
const char *json_strerror(struct JsonContext *ctx)
{
return ctx->lasterr;
}
void json_set_options(struct JsonContext *ctx, unsigned int options)
{
ctx->options = options;
}
| Java |
angular.module('appTesting').service("LoginLocalStorage", function () {
"use strict";
var STORE_NAME = "login";
var setUser = function setUser(user) {
localStorage.setItem(STORE_NAME, JSON.stringify(user));
}
var getUser = function getUser() {
var storedTasks = localStorage.getItem(STORE_NAME);
if (storedTasks) {
return JSON.parse(storedTasks);
}
return {};
}
return {
setUser: setUser,
getUser: getUser
}
}); | Java |
/* Copyright information is at end of file */
#include "xmlrpc_config.h"
#include <stddef.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "stdargx.h"
#include "xmlrpc-c/base.h"
#include "xmlrpc-c/base_int.h"
#include "xmlrpc-c/string_int.h"
static void
getString(xmlrpc_env *const envP,
const char **const formatP,
va_listx *const argsP,
xmlrpc_value **const valPP) {
const char *str;
size_t len;
str = (const char *) va_arg(argsP->v, char*);
if (*(*formatP) == '#') {
++(*formatP);
len = (size_t) va_arg(argsP->v, size_t);
} else
len = strlen(str);
*valPP = xmlrpc_string_new_lp(envP, len, str);
}
static void
getWideString(xmlrpc_env *const envP ATTR_UNUSED,
const char **const formatP ATTR_UNUSED,
va_listx *const argsP ATTR_UNUSED,
xmlrpc_value **const valPP ATTR_UNUSED) {
#if HAVE_UNICODE_WCHAR
wchar_t *wcs;
size_t len;
wcs = (wchar_t*) va_arg(argsP->v, wchar_t*);
if (**formatP == '#') {
(*formatP)++;
len = (size_t) va_arg(argsP->v, size_t);
} else
len = wcslen(wcs);
*valPP = xmlrpc_string_w_new_lp(envP, len, wcs);
#endif /* HAVE_UNICODE_WCHAR */
}
static void
getBase64(xmlrpc_env *const envP,
va_listx *const argsP,
xmlrpc_value **const valPP) {
unsigned char *value;
size_t length;
value = (unsigned char *) va_arg(argsP->v, unsigned char*);
length = (size_t) va_arg(argsP->v, size_t);
*valPP = xmlrpc_base64_new(envP, length, value);
}
static void
getValue(xmlrpc_env *const envP,
const char **const format,
va_listx *const argsP,
xmlrpc_value **const valPP);
static void
getArray(xmlrpc_env *const envP,
const char **const formatP,
char const delimiter,
va_listx *const argsP,
xmlrpc_value **const arrayPP) {
xmlrpc_value *arrayP;
arrayP = xmlrpc_array_new(envP);
/* Add items to the array until we hit our delimiter. */
while (**formatP != delimiter && !envP->fault_occurred) {
xmlrpc_value *itemP;
if (**formatP == '\0')
xmlrpc_env_set_fault(
envP, XMLRPC_INTERNAL_ERROR,
"format string ended before closing ')'.");
else {
getValue(envP, formatP, argsP, &itemP);
if (!envP->fault_occurred) {
xmlrpc_array_append_item(envP, arrayP, itemP);
xmlrpc_DECREF(itemP);
}
}
}
if (envP->fault_occurred)
xmlrpc_DECREF(arrayP);
*arrayPP = arrayP;
}
static void
getStructMember(xmlrpc_env *const envP,
const char **const formatP,
va_listx *const argsP,
xmlrpc_value **const keyPP,
xmlrpc_value **const valuePP) {
/* Get the key */
getValue(envP, formatP, argsP, keyPP);
if (!envP->fault_occurred) {
if (**formatP != ':')
xmlrpc_env_set_fault(
envP, XMLRPC_INTERNAL_ERROR,
"format string does not have ':' after a "
"structure member key.");
else {
/* Skip over colon that separates key from value */
(*formatP)++;
/* Get the value */
getValue(envP, formatP, argsP, valuePP);
}
if (envP->fault_occurred)
xmlrpc_DECREF(*keyPP);
}
}
static void
getStruct(xmlrpc_env *const envP,
const char **const formatP,
char const delimiter,
va_listx *const argsP,
xmlrpc_value **const structPP) {
xmlrpc_value *structP;
structP = xmlrpc_struct_new(envP);
if (!envP->fault_occurred) {
while (**formatP != delimiter && !envP->fault_occurred) {
xmlrpc_value *keyP;
xmlrpc_value *valueP;
getStructMember(envP, formatP, argsP, &keyP, &valueP);
if (!envP->fault_occurred) {
if (**formatP == ',')
(*formatP)++; /* Skip over the comma */
else if (**formatP == delimiter) {
/* End of the line */
} else
xmlrpc_env_set_fault(
envP, XMLRPC_INTERNAL_ERROR,
"format string does not have ',' or ')' after "
"a structure member");
if (!envP->fault_occurred)
/* Add the new member to the struct. */
xmlrpc_struct_set_value_v(envP, structP, keyP, valueP);
xmlrpc_DECREF(valueP);
xmlrpc_DECREF(keyP);
}
}
if (envP->fault_occurred)
xmlrpc_DECREF(structP);
}
*structPP = structP;
}
static void
mkArrayFromVal(xmlrpc_env *const envP,
xmlrpc_value *const value,
xmlrpc_value **const valPP) {
if (xmlrpc_value_type(value) != XMLRPC_TYPE_ARRAY)
xmlrpc_env_set_fault(envP, XMLRPC_INTERNAL_ERROR,
"Array format ('A'), non-array xmlrpc_value");
else
xmlrpc_INCREF(value);
*valPP = value;
}
static void
mkStructFromVal(xmlrpc_env *const envP,
xmlrpc_value *const value,
xmlrpc_value **const valPP) {
if (xmlrpc_value_type(value) != XMLRPC_TYPE_STRUCT)
xmlrpc_env_set_fault(envP, XMLRPC_INTERNAL_ERROR,
"Struct format ('S'), non-struct xmlrpc_value");
else
xmlrpc_INCREF(value);
*valPP = value;
}
static void
getValue(xmlrpc_env *const envP,
const char **const formatP,
va_listx *const argsP,
xmlrpc_value **const valPP) {
/*----------------------------------------------------------------------------
Get the next value from the list. *formatP points to the specifier
for the next value in the format string (i.e. to the type code
character) and we move *formatP past the whole specifier for the
next value. We read the required arguments from 'argsP'. We return
the value as *valPP with a reference to it.
For example, if *formatP points to the "i" in the string "sis",
we read one argument from 'argsP' and return as *valP an integer whose
value is the argument we read. We advance *formatP to point to the
last 's' and advance 'argsP' to point to the argument that belongs to
that 's'.
-----------------------------------------------------------------------------*/
char const formatChar = *(*formatP)++;
switch (formatChar) {
case 'i':
*valPP =
xmlrpc_int_new(envP, (xmlrpc_int32) va_arg(argsP->v,
xmlrpc_int32));
break;
case 'b':
*valPP =
xmlrpc_bool_new(envP, (xmlrpc_bool) va_arg(argsP->v,
xmlrpc_bool));
break;
case 'd':
*valPP =
xmlrpc_double_new(envP, (double) va_arg(argsP->v, double));
break;
case 's':
getString(envP, formatP, argsP, valPP);
break;
case 'w':
getWideString(envP, formatP, argsP, valPP);
break;
case 't':
*valPP = xmlrpc_datetime_new_sec(envP, va_arg(argsP->v, time_t));
break;
case '8':
*valPP = xmlrpc_datetime_new_str(envP, va_arg(argsP->v, char*));
break;
case '6':
getBase64(envP, argsP, valPP);
break;
case 'n':
*valPP =
xmlrpc_nil_new(envP);
break;
case 'I':
*valPP =
xmlrpc_i8_new(envP, (xmlrpc_int64) va_arg(argsP->v,
xmlrpc_int64));
break;
case 'p':
*valPP =
xmlrpc_cptr_new(envP, (void *) va_arg(argsP->v, void*));
break;
case 'A':
mkArrayFromVal(envP,
(xmlrpc_value *) va_arg(argsP->v, xmlrpc_value*),
valPP);
break;
case 'S':
mkStructFromVal(envP,
(xmlrpc_value *) va_arg(argsP->v, xmlrpc_value*),
valPP);
break;
case 'V':
*valPP = (xmlrpc_value *) va_arg(argsP->v, xmlrpc_value*);
xmlrpc_INCREF(*valPP);
break;
case '(':
getArray(envP, formatP, ')', argsP, valPP);
if (!envP->fault_occurred) {
XMLRPC_ASSERT(**formatP == ')');
(*formatP)++; /* Skip over closing parenthesis */
}
break;
case '{':
getStruct(envP, formatP, '}', argsP, valPP);
if (!envP->fault_occurred) {
XMLRPC_ASSERT(**formatP == '}');
(*formatP)++; /* Skip over closing brace */
}
break;
default: {
const char *const badCharacter = xmlrpc_makePrintableChar(
formatChar);
xmlrpc_env_set_fault_formatted(
envP, XMLRPC_INTERNAL_ERROR,
"Unexpected character '%s' in format string", badCharacter);
xmlrpc_strfree(badCharacter);
}
}
}
void
xmlrpc_build_value_va(xmlrpc_env *const envP,
const char *const format,
va_list const args,
xmlrpc_value **const valPP,
const char **const tailP) {
XMLRPC_ASSERT_ENV_OK(envP);
XMLRPC_ASSERT(format != NULL);
if (strlen(format) == 0)
xmlrpc_faultf(envP, "Format string is empty.");
else {
va_listx currentArgs;
const char *formatCursor;
init_va_listx(¤tArgs, args);
formatCursor = &format[0];
getValue(envP, &formatCursor, ¤tArgs, valPP);
if (!envP->fault_occurred)
XMLRPC_ASSERT_VALUE_OK(*valPP);
*tailP = formatCursor;
}
}
xmlrpc_value *
xmlrpc_build_value(xmlrpc_env *const envP,
const char *const format,
...) {
va_list args;
xmlrpc_value *retval;
const char *suffix;
va_start(args, format);
xmlrpc_build_value_va(envP, format, args, &retval, &suffix);
va_end(args);
if (!envP->fault_occurred) {
if (*suffix != '\0')
xmlrpc_faultf(envP, "Junk after the format specifier: '%s'. "
"The format string must describe exactly "
"one XML-RPC value "
"(but it might be a compound value "
"such as an array)",
suffix);
if (envP->fault_occurred)
xmlrpc_DECREF(retval);
}
return retval;
}
/* Copyright (C) 2001 by First Peer, Inc. All rights reserved.
** Copyright (C) 2001 by Eric Kidd. All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
** SUCH DAMAGE. */
| Java |
// flow-typed signature: d37503430b92ad584be6e2c6f8d1fc08
// flow-typed version: <<STUB>>/ua-parser-js_v1.0.2/flow_v0.171.0
/**
* This is an autogenerated libdef stub for:
*
* 'ua-parser-js'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'ua-parser-js' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'ua-parser-js/dist/ua-parser.min' {
declare module.exports: any;
}
declare module 'ua-parser-js/dist/ua-parser.pack' {
declare module.exports: any;
}
declare module 'ua-parser-js/package' {
declare module.exports: any;
}
declare module 'ua-parser-js/src/ua-parser' {
declare module.exports: any;
}
declare module 'ua-parser-js/test/test' {
declare module.exports: any;
}
// Filename aliases
declare module 'ua-parser-js/dist/ua-parser.min.js' {
declare module.exports: $Exports<'ua-parser-js/dist/ua-parser.min'>;
}
declare module 'ua-parser-js/dist/ua-parser.pack.js' {
declare module.exports: $Exports<'ua-parser-js/dist/ua-parser.pack'>;
}
declare module 'ua-parser-js/package.js' {
declare module.exports: $Exports<'ua-parser-js/package'>;
}
declare module 'ua-parser-js/src/ua-parser.js' {
declare module.exports: $Exports<'ua-parser-js/src/ua-parser'>;
}
declare module 'ua-parser-js/test/test.js' {
declare module.exports: $Exports<'ua-parser-js/test/test'>;
}
| Java |
/* ISC license. */
#include <bearssl.h>
#include <s6-networking/sbearssl.h>
int sbearssl_skey_to (sbearssl_skey const *l, br_skey *k, char *s)
{
switch (l->type)
{
case BR_KEYTYPE_RSA :
sbearssl_rsa_skey_to(&l->data.rsa, &k->data.rsa, s) ;
break ;
case BR_KEYTYPE_EC :
sbearssl_ec_skey_to(&l->data.ec, &k->data.ec, s) ;
break ;
default :
return 0 ;
}
k->type = l->type ;
return 1 ;
}
| Java |
/*
* The MIT License
* Copyright (c) 2012 Matias Meno <m@tias.me>
*/
@-webkit-keyframes passing-through {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px);
}
30%,
70% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px);
}
100% {
opacity: 0;
-webkit-transform: translateY(-40px);
-moz-transform: translateY(-40px);
-ms-transform: translateY(-40px);
-o-transform: translateY(-40px);
transform: translateY(-40px);
}
}
@-moz-keyframes passing-through {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px);
}
30%,
70% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px);
}
100% {
opacity: 0;
-webkit-transform: translateY(-40px);
-moz-transform: translateY(-40px);
-ms-transform: translateY(-40px);
-o-transform: translateY(-40px);
transform: translateY(-40px);
}
}
@keyframes passing-through {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px);
}
30%,
70% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px);
}
100% {
opacity: 0;
-webkit-transform: translateY(-40px);
-moz-transform: translateY(-40px);
-ms-transform: translateY(-40px);
-o-transform: translateY(-40px);
transform: translateY(-40px);
}
}
@-webkit-keyframes slide-in {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px);
}
30% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px);
}
}
@-moz-keyframes slide-in {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px);
}
30% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px);
}
}
@keyframes slide-in {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px);
}
30% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px);
}
}
@-webkit-keyframes pulse {
0% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
10% {
-webkit-transform: scale(1.1);
-moz-transform: scale(1.1);
-ms-transform: scale(1.1);
-o-transform: scale(1.1);
transform: scale(1.1);
}
20% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
}
@-moz-keyframes pulse {
0% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
10% {
-webkit-transform: scale(1.1);
-moz-transform: scale(1.1);
-ms-transform: scale(1.1);
-o-transform: scale(1.1);
transform: scale(1.1);
}
20% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
}
@keyframes pulse {
0% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
10% {
-webkit-transform: scale(1.1);
-moz-transform: scale(1.1);
-ms-transform: scale(1.1);
-o-transform: scale(1.1);
transform: scale(1.1);
}
20% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
}
.dropzone,
.dropzone * {
box-sizing: border-box;
}
.dropzone {
min-height: 150px;
height: 100%;
border: 2px dashed #0087F7;
border-radius: 5px;
background: white;
padding: 20px 20px;
}
.dropzone.dz-clickable {
cursor: pointer;
}
.dropzone.dz-clickable * {
cursor: default;
}
.dropzone.dz-clickable .dz-message,
.dropzone.dz-clickable .dz-message * {
cursor: pointer;
}
.dropzone.dz-started .dz-message {
display: none;
}
.dropzone.dz-drag-hover {
border-style: solid;
}
.dropzone.dz-drag-hover .dz-message {
opacity: 0.5;
}
.dropzone .dz-message {
text-align: center;
margin: 2em 0;
}
.dropzone .dz-preview {
position: relative;
display: inline-block;
vertical-align: top;
margin: 16px;
min-height: 100px;
}
.dropzone .dz-preview:hover {
z-index: 1000;
}
.dropzone .dz-preview:hover .dz-details {
opacity: 1;
}
.dropzone .dz-preview.dz-file-preview .dz-image {
border-radius: 20px;
background: #999;
background: linear-gradient(to bottom, #eee, #ddd);
}
.dropzone .dz-preview.dz-file-preview .dz-details {
opacity: 1;
}
.dropzone .dz-preview.dz-image-preview {
background: white;
}
.dropzone .dz-preview.dz-image-preview .dz-details {
-webkit-transition: opacity 0.2s linear;
-moz-transition: opacity 0.2s linear;
-ms-transition: opacity 0.2s linear;
-o-transition: opacity 0.2s linear;
transition: opacity 0.2s linear;
}
.dropzone .dz-preview .dz-remove {
font-size: 14px;
text-align: center;
display: block;
cursor: pointer;
border: none;
}
.dropzone .dz-preview .dz-remove:hover {
text-decoration: underline;
}
.dropzone .dz-preview:hover .dz-details {
opacity: 1;
}
.dropzone .dz-preview .dz-details {
z-index: 20;
position: absolute;
top: 0;
left: 0;
opacity: 0;
font-size: 13px;
min-width: 100%;
max-width: 100%;
padding: 2em 1em;
text-align: center;
color: rgba(0, 0, 0, 0.9);
line-height: 150%;
}
.dropzone .dz-preview .dz-details .dz-size {
margin-bottom: 1em;
font-size: 16px;
}
.dropzone .dz-preview .dz-details .dz-filename {
white-space: nowrap;
}
.dropzone .dz-preview .dz-details .dz-filename:hover span {
border: 1px solid rgba(200, 200, 200, 0.8);
background-color: rgba(255, 255, 255, 0.8);
}
.dropzone .dz-preview .dz-details .dz-filename:not(:hover) {
overflow: hidden;
text-overflow: ellipsis;
}
.dropzone .dz-preview .dz-details .dz-filename:not(:hover) span {
border: 1px solid transparent;
}
.dropzone .dz-preview .dz-details .dz-filename span,
.dropzone .dz-preview .dz-details .dz-size span {
background-color: rgba(255, 255, 255, 0.4);
padding: 0 0.4em;
border-radius: 3px;
}
.dropzone .dz-preview:hover .dz-image img {
-webkit-transform: scale(1.05, 1.05);
-moz-transform: scale(1.05, 1.05);
-ms-transform: scale(1.05, 1.05);
-o-transform: scale(1.05, 1.05);
transform: scale(1.05, 1.05);
-webkit-filter: blur(8px);
filter: blur(8px);
}
.dropzone .dz-preview .dz-image {
border-radius: 20px;
overflow: hidden;
width: 120px;
height: 120px;
position: relative;
display: block;
z-index: 10;
}
.dropzone .dz-preview .dz-image img {
display: block;
}
.dropzone .dz-preview.dz-success .dz-success-mark {
-webkit-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
-moz-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
-ms-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
-o-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
}
.dropzone .dz-preview.dz-error .dz-error-mark {
opacity: 1;
-webkit-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
-moz-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
-ms-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
-o-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
}
.dropzone .dz-preview .dz-success-mark,
.dropzone .dz-preview .dz-error-mark {
pointer-events: none;
opacity: 0;
z-index: 500;
position: absolute;
display: block;
top: 50%;
left: 50%;
margin-left: -27px;
margin-top: -27px;
}
.dropzone .dz-preview .dz-success-mark svg,
.dropzone .dz-preview .dz-error-mark svg {
display: block;
width: 54px;
height: 54px;
}
.dropzone .dz-preview.dz-processing .dz-progress {
opacity: 1;
-webkit-transition: all 0.2s linear;
-moz-transition: all 0.2s linear;
-ms-transition: all 0.2s linear;
-o-transition: all 0.2s linear;
transition: all 0.2s linear;
}
.dropzone .dz-preview.dz-complete .dz-progress {
opacity: 0;
-webkit-transition: opacity 0.4s ease-in;
-moz-transition: opacity 0.4s ease-in;
-ms-transition: opacity 0.4s ease-in;
-o-transition: opacity 0.4s ease-in;
transition: opacity 0.4s ease-in;
}
.dropzone .dz-preview:not(.dz-processing) .dz-progress {
-webkit-animation: pulse 6s ease infinite;
-moz-animation: pulse 6s ease infinite;
-ms-animation: pulse 6s ease infinite;
-o-animation: pulse 6s ease infinite;
animation: pulse 6s ease infinite;
}
.dropzone .dz-preview .dz-progress {
opacity: 1;
z-index: 1000;
pointer-events: none;
position: absolute;
height: 16px;
left: 50%;
top: 50%;
margin-top: -8px;
width: 80px;
margin-left: -40px;
background: rgba(255, 255, 255, 0.9);
-webkit-transform: scale(1);
border-radius: 8px;
overflow: hidden;
}
.dropzone .dz-preview .dz-progress .dz-upload {
background: #333;
background: linear-gradient(to bottom, #666, #444);
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 0;
-webkit-transition: width 300ms ease-in-out;
-moz-transition: width 300ms ease-in-out;
-ms-transition: width 300ms ease-in-out;
-o-transition: width 300ms ease-in-out;
transition: width 300ms ease-in-out;
}
.dropzone .dz-preview.dz-error .dz-error-message {
display: block;
}
.dropzone .dz-preview.dz-error:hover .dz-error-message {
opacity: 1;
pointer-events: auto;
}
.dropzone .dz-preview .dz-error-message {
pointer-events: none;
z-index: 1000;
position: absolute;
display: block;
display: none;
opacity: 0;
-webkit-transition: opacity 0.3s ease;
-moz-transition: opacity 0.3s ease;
-ms-transition: opacity 0.3s ease;
-o-transition: opacity 0.3s ease;
transition: opacity 0.3s ease;
border-radius: 8px;
font-size: 13px;
top: 130px;
left: -10px;
width: 140px;
background: #be2626;
background: linear-gradient(to bottom, #be2626, #a92222);
padding: 0.5em 1.2em;
color: white;
}
.dropzone .dz-preview .dz-error-message:after {
content: '';
position: absolute;
top: -6px;
left: 64px;
width: 0;
height: 0;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-bottom: 6px solid #be2626;
}
| Java |
/* eslint-disable no-console */
const buildData = require('./build_data');
const buildSrc = require('./build_src');
const buildCSS = require('./build_css');
let _currBuild = null;
// if called directly, do the thing.
buildAll();
function buildAll() {
if (_currBuild) return _currBuild;
return _currBuild =
Promise.resolve()
.then(() => buildCSS())
.then(() => buildData())
.then(() => buildSrc())
.then(() => _currBuild = null)
.catch((err) => {
console.error(err);
_currBuild = null;
process.exit(1);
});
}
module.exports = buildAll;
| Java |
//
// RCWorkspaceCache.h
//
// Created by Mark Lilback on 12/12/11.
// Copyright (c) 2011 . All rights reserved.
//
#import "_RCWorkspaceCache.h"
@interface RCWorkspaceCache : _RCWorkspaceCache
//if multiple values are to be set, it best to get properties, set them, and then call setProperties
//each call to setProperties serializes a plist
@property (nonatomic, strong) NSMutableDictionary *properties;
-(id)propertyForKey:(NSString*)key;
//removes property if value is nil
-(void)setProperty:(id)value forKey:(NSString*)key;
-(BOOL)boolPropertyForKey:(NSString*)key;
-(void)setBoolProperty:(BOOL)val forKey:(NSString*)key;
@end
| Java |
function LetterProps(o, sw, sc, fc, m, p) {
this.o = o;
this.sw = sw;
this.sc = sc;
this.fc = fc;
this.m = m;
this.p = p;
this._mdf = {
o: true,
sw: !!sw,
sc: !!sc,
fc: !!fc,
m: true,
p: true,
};
}
LetterProps.prototype.update = function (o, sw, sc, fc, m, p) {
this._mdf.o = false;
this._mdf.sw = false;
this._mdf.sc = false;
this._mdf.fc = false;
this._mdf.m = false;
this._mdf.p = false;
var updated = false;
if (this.o !== o) {
this.o = o;
this._mdf.o = true;
updated = true;
}
if (this.sw !== sw) {
this.sw = sw;
this._mdf.sw = true;
updated = true;
}
if (this.sc !== sc) {
this.sc = sc;
this._mdf.sc = true;
updated = true;
}
if (this.fc !== fc) {
this.fc = fc;
this._mdf.fc = true;
updated = true;
}
if (this.m !== m) {
this.m = m;
this._mdf.m = true;
updated = true;
}
if (p.length && (this.p[0] !== p[0] || this.p[1] !== p[1] || this.p[4] !== p[4] || this.p[5] !== p[5] || this.p[12] !== p[12] || this.p[13] !== p[13])) {
this.p = p;
this._mdf.p = true;
updated = true;
}
return updated;
};
| Java |
/*!
* DASSL solver library description
*/
#include "libinfo.h"
extern void _start()
{
_library_ident("DAE solver library");
_library_task("interfaces to generic IVP solver");
_library_task("operations on data for included solvers");
_library_task("DASSL solver backend");
_library_task("RADAU solver backend");
_library_task("MEBDFI solver backend");
_exit(0);
}
| Java |
/*
* WARNING: do not edit!
* Generated by util/mkbuildinf.pl
*
* Copyright 2014-2017 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#define PLATFORM "platform: linux-armv4"
#define DATE "built on: Fri Sep 13 15:59:17 2019 UTC"
/*
* Generate compiler_flags as an array of individual characters. This is a
* workaround for the situation where CFLAGS gets too long for a C90 string
* literal
*/
static const char compiler_flags[] = {
'c','o','m','p','i','l','e','r',':',' ','.','.','/','c','o','n',
'f','i','g','/','f','a','k','e','_','g','c','c','.','p','l',' ',
'-','f','P','I','C',' ','-','p','t','h','r','e','a','d',' ','-',
'W','a',',','-','-','n','o','e','x','e','c','s','t','a','c','k',
' ','-','W','a','l','l',' ','-','O','3',' ','-','D','O','P','E',
'N','S','S','L','_','U','S','E','_','N','O','D','E','L','E','T',
'E',' ','-','D','O','P','E','N','S','S','L','_','P','I','C',' ',
'-','D','O','P','E','N','S','S','L','_','C','P','U','I','D','_',
'O','B','J',' ','-','D','O','P','E','N','S','S','L','_','B','N',
'_','A','S','M','_','M','O','N','T',' ','-','D','O','P','E','N',
'S','S','L','_','B','N','_','A','S','M','_','G','F','2','m',' ',
'-','D','S','H','A','1','_','A','S','M',' ','-','D','S','H','A',
'2','5','6','_','A','S','M',' ','-','D','S','H','A','5','1','2',
'_','A','S','M',' ','-','D','K','E','C','C','A','K','1','6','0',
'0','_','A','S','M',' ','-','D','A','E','S','_','A','S','M',' ',
'-','D','B','S','A','E','S','_','A','S','M',' ','-','D','G','H',
'A','S','H','_','A','S','M',' ','-','D','E','C','P','_','N','I',
'S','T','Z','2','5','6','_','A','S','M',' ','-','D','P','O','L',
'Y','1','3','0','5','_','A','S','M',' ','-','D','N','D','E','B',
'U','G','\0'
};
| Java |
System.register(["angular2/test_lib", "angular2/src/test_lib/test_bed", "angular2/src/core/annotations_impl/annotations", "angular2/src/core/annotations_impl/view", "angular2/src/core/compiler/dynamic_component_loader", "angular2/src/core/compiler/element_ref", "angular2/src/directives/if", "angular2/src/render/dom/direct_dom_renderer", "angular2/src/dom/dom_adapter"], function($__export) {
"use strict";
var AsyncTestCompleter,
beforeEach,
ddescribe,
xdescribe,
describe,
el,
dispatchEvent,
expect,
iit,
inject,
beforeEachBindings,
it,
xit,
TestBed,
Component,
View,
DynamicComponentLoader,
ElementRef,
If,
DirectDomRenderer,
DOM,
ImperativeViewComponentUsingNgComponent,
ChildComp,
DynamicallyCreatedComponentService,
DynamicComp,
DynamicallyCreatedCmp,
DynamicallyLoaded,
DynamicallyLoaded2,
DynamicallyLoadedWithHostProps,
Location,
MyComp;
function main() {
describe('DynamicComponentLoader', function() {
describe("loading into existing location", (function() {
it('should work', inject([TestBed, AsyncTestCompleter], (function(tb, async) {
tb.overrideView(MyComp, new View({
template: '<dynamic-comp #dynamic></dynamic-comp>',
directives: [DynamicComp]
}));
tb.createView(MyComp).then((function(view) {
var dynamicComponent = view.rawView.locals.get("dynamic");
expect(dynamicComponent).toBeAnInstanceOf(DynamicComp);
dynamicComponent.done.then((function(_) {
view.detectChanges();
expect(view.rootNodes).toHaveText('hello');
async.done();
}));
}));
})));
it('should inject dependencies of the dynamically-loaded component', inject([TestBed, AsyncTestCompleter], (function(tb, async) {
tb.overrideView(MyComp, new View({
template: '<dynamic-comp #dynamic></dynamic-comp>',
directives: [DynamicComp]
}));
tb.createView(MyComp).then((function(view) {
var dynamicComponent = view.rawView.locals.get("dynamic");
dynamicComponent.done.then((function(ref) {
expect(ref.instance.dynamicallyCreatedComponentService).toBeAnInstanceOf(DynamicallyCreatedComponentService);
async.done();
}));
}));
})));
it('should allow to destroy and create them via viewcontainer directives', inject([TestBed, AsyncTestCompleter], (function(tb, async) {
tb.overrideView(MyComp, new View({
template: '<div><dynamic-comp #dynamic template="if: ctxBoolProp"></dynamic-comp></div>',
directives: [DynamicComp, If]
}));
tb.createView(MyComp).then((function(view) {
view.context.ctxBoolProp = true;
view.detectChanges();
var dynamicComponent = view.rawView.viewContainers[0].views[0].locals.get("dynamic");
dynamicComponent.done.then((function(_) {
view.detectChanges();
expect(view.rootNodes).toHaveText('hello');
view.context.ctxBoolProp = false;
view.detectChanges();
expect(view.rawView.viewContainers[0].views.length).toBe(0);
expect(view.rootNodes).toHaveText('');
view.context.ctxBoolProp = true;
view.detectChanges();
var dynamicComponent = view.rawView.viewContainers[0].views[0].locals.get("dynamic");
return dynamicComponent.done;
})).then((function(_) {
view.detectChanges();
expect(view.rootNodes).toHaveText('hello');
async.done();
}));
}));
})));
}));
describe("loading next to an existing location", (function() {
it('should work', inject([DynamicComponentLoader, TestBed, AsyncTestCompleter], (function(loader, tb, async) {
tb.overrideView(MyComp, new View({
template: '<div><location #loc></location></div>',
directives: [Location]
}));
tb.createView(MyComp).then((function(view) {
var location = view.rawView.locals.get("loc");
loader.loadNextToExistingLocation(DynamicallyLoaded, location.elementRef).then((function(ref) {
expect(view.rootNodes).toHaveText("Location;DynamicallyLoaded;");
async.done();
}));
}));
})));
it('should return a disposable component ref', inject([DynamicComponentLoader, TestBed, AsyncTestCompleter], (function(loader, tb, async) {
tb.overrideView(MyComp, new View({
template: '<div><location #loc></location></div>',
directives: [Location]
}));
tb.createView(MyComp).then((function(view) {
var location = view.rawView.locals.get("loc");
loader.loadNextToExistingLocation(DynamicallyLoaded, location.elementRef).then((function(ref) {
loader.loadNextToExistingLocation(DynamicallyLoaded2, location.elementRef).then((function(ref2) {
expect(view.rootNodes).toHaveText("Location;DynamicallyLoaded;DynamicallyLoaded2;");
ref2.dispose();
expect(view.rootNodes).toHaveText("Location;DynamicallyLoaded;");
async.done();
}));
}));
}));
})));
it('should update host properties', inject([DynamicComponentLoader, TestBed, AsyncTestCompleter], (function(loader, tb, async) {
tb.overrideView(MyComp, new View({
template: '<div><location #loc></location></div>',
directives: [Location]
}));
tb.createView(MyComp).then((function(view) {
var location = view.rawView.locals.get("loc");
loader.loadNextToExistingLocation(DynamicallyLoadedWithHostProps, location.elementRef).then((function(ref) {
ref.instance.id = "new value";
view.detectChanges();
var newlyInsertedElement = DOM.childNodesAsList(view.rootNodes[0])[1];
expect(newlyInsertedElement.id).toEqual("new value");
async.done();
}));
}));
})));
}));
describe('loading into a new location', (function() {
it('should allow to create, update and destroy components', inject([TestBed, AsyncTestCompleter], (function(tb, async) {
tb.overrideView(MyComp, new View({
template: '<imp-ng-cmp #impview></imp-ng-cmp>',
directives: [ImperativeViewComponentUsingNgComponent]
}));
tb.createView(MyComp).then((function(view) {
var userViewComponent = view.rawView.locals.get("impview");
userViewComponent.done.then((function(childComponentRef) {
view.detectChanges();
expect(view.rootNodes).toHaveText('hello');
childComponentRef.instance.ctxProp = 'new';
view.detectChanges();
expect(view.rootNodes).toHaveText('new');
childComponentRef.dispose();
expect(view.rootNodes).toHaveText('');
async.done();
}));
}));
})));
}));
});
}
$__export("main", main);
return {
setters: [function($__m) {
AsyncTestCompleter = $__m.AsyncTestCompleter;
beforeEach = $__m.beforeEach;
ddescribe = $__m.ddescribe;
xdescribe = $__m.xdescribe;
describe = $__m.describe;
el = $__m.el;
dispatchEvent = $__m.dispatchEvent;
expect = $__m.expect;
iit = $__m.iit;
inject = $__m.inject;
beforeEachBindings = $__m.beforeEachBindings;
it = $__m.it;
xit = $__m.xit;
}, function($__m) {
TestBed = $__m.TestBed;
}, function($__m) {
Component = $__m.Component;
}, function($__m) {
View = $__m.View;
}, function($__m) {
DynamicComponentLoader = $__m.DynamicComponentLoader;
}, function($__m) {
ElementRef = $__m.ElementRef;
}, function($__m) {
If = $__m.If;
}, function($__m) {
DirectDomRenderer = $__m.DirectDomRenderer;
}, function($__m) {
DOM = $__m.DOM;
}],
execute: function() {
ImperativeViewComponentUsingNgComponent = (function() {
var ImperativeViewComponentUsingNgComponent = function ImperativeViewComponentUsingNgComponent(self, dynamicComponentLoader, renderer) {
var div = el('<div></div>');
renderer.setImperativeComponentRootNodes(self.parentView.render, self.boundElementIndex, [div]);
this.done = dynamicComponentLoader.loadIntoNewLocation(ChildComp, self, div, null);
};
return ($traceurRuntime.createClass)(ImperativeViewComponentUsingNgComponent, {}, {});
}());
Object.defineProperty(ImperativeViewComponentUsingNgComponent, "annotations", {get: function() {
return [new Component({selector: 'imp-ng-cmp'}), new View({renderer: 'imp-ng-cmp-renderer'})];
}});
Object.defineProperty(ImperativeViewComponentUsingNgComponent, "parameters", {get: function() {
return [[ElementRef], [DynamicComponentLoader], [DirectDomRenderer]];
}});
ChildComp = (function() {
var ChildComp = function ChildComp() {
this.ctxProp = 'hello';
};
return ($traceurRuntime.createClass)(ChildComp, {}, {});
}());
Object.defineProperty(ChildComp, "annotations", {get: function() {
return [new Component({selector: 'child-cmp'}), new View({template: '{{ctxProp}}'})];
}});
DynamicallyCreatedComponentService = (function() {
var DynamicallyCreatedComponentService = function DynamicallyCreatedComponentService() {
;
};
return ($traceurRuntime.createClass)(DynamicallyCreatedComponentService, {}, {});
}());
DynamicComp = (function() {
var DynamicComp = function DynamicComp(loader, location) {
this.done = loader.loadIntoExistingLocation(DynamicallyCreatedCmp, location);
};
return ($traceurRuntime.createClass)(DynamicComp, {}, {});
}());
Object.defineProperty(DynamicComp, "annotations", {get: function() {
return [new Component({selector: 'dynamic-comp'})];
}});
Object.defineProperty(DynamicComp, "parameters", {get: function() {
return [[DynamicComponentLoader], [ElementRef]];
}});
DynamicallyCreatedCmp = (function() {
var DynamicallyCreatedCmp = function DynamicallyCreatedCmp(a) {
this.greeting = "hello";
this.dynamicallyCreatedComponentService = a;
};
return ($traceurRuntime.createClass)(DynamicallyCreatedCmp, {}, {});
}());
Object.defineProperty(DynamicallyCreatedCmp, "annotations", {get: function() {
return [new Component({
selector: 'hello-cmp',
injectables: [DynamicallyCreatedComponentService]
}), new View({template: "{{greeting}}"})];
}});
Object.defineProperty(DynamicallyCreatedCmp, "parameters", {get: function() {
return [[DynamicallyCreatedComponentService]];
}});
DynamicallyLoaded = (function() {
var DynamicallyLoaded = function DynamicallyLoaded() {
;
};
return ($traceurRuntime.createClass)(DynamicallyLoaded, {}, {});
}());
Object.defineProperty(DynamicallyLoaded, "annotations", {get: function() {
return [new Component({selector: 'dummy'}), new View({template: "DynamicallyLoaded;"})];
}});
DynamicallyLoaded2 = (function() {
var DynamicallyLoaded2 = function DynamicallyLoaded2() {
;
};
return ($traceurRuntime.createClass)(DynamicallyLoaded2, {}, {});
}());
Object.defineProperty(DynamicallyLoaded2, "annotations", {get: function() {
return [new Component({selector: 'dummy'}), new View({template: "DynamicallyLoaded2;"})];
}});
DynamicallyLoadedWithHostProps = (function() {
var DynamicallyLoadedWithHostProps = function DynamicallyLoadedWithHostProps() {
this.id = "default";
};
return ($traceurRuntime.createClass)(DynamicallyLoadedWithHostProps, {}, {});
}());
Object.defineProperty(DynamicallyLoadedWithHostProps, "annotations", {get: function() {
return [new Component({
selector: 'dummy',
hostProperties: {'id': 'id'}
}), new View({template: "DynamicallyLoadedWithHostProps;"})];
}});
Location = (function() {
var Location = function Location(elementRef) {
this.elementRef = elementRef;
};
return ($traceurRuntime.createClass)(Location, {}, {});
}());
Object.defineProperty(Location, "annotations", {get: function() {
return [new Component({selector: 'location'}), new View({template: "Location;"})];
}});
Object.defineProperty(Location, "parameters", {get: function() {
return [[ElementRef]];
}});
MyComp = (function() {
var MyComp = function MyComp() {
this.ctxBoolProp = false;
};
return ($traceurRuntime.createClass)(MyComp, {}, {});
}());
Object.defineProperty(MyComp, "annotations", {get: function() {
return [new Component({selector: 'my-comp'}), new View({directives: []})];
}});
}
};
});
//# sourceMappingURL=dynamic_component_loader_spec.es6.map
//# sourceMappingURL=./dynamic_component_loader_spec.js.map | Java |
---
name: Dreadnought
type: AV
speed: 15cm
armour: 3+
cc: 4+
ff: 4+
special_rules:
- walker
notes:
|
Armed with either a Missile Launcher and Twin Lascannon, or an Assault Cannon and Power Fist.
weapons:
-
id: missile-launcher
multiplier: 0–1
-
id: twin-lascannon
multiplier: 0–1
-
id: assault-cannon
multiplier: 0–1
-
id: power-fist
multiplier: 0–1
--- | Java |
/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "DistrhoPluginInternal.hpp"
#include "lv2/atom.h"
#include "lv2/buf-size.h"
#include "lv2/data-access.h"
#include "lv2/instance-access.h"
#include "lv2/midi.h"
#include "lv2/options.h"
#include "lv2/port-props.h"
#include "lv2/resize-port.h"
#include "lv2/state.h"
#include "lv2/time.h"
#include "lv2/ui.h"
#include "lv2/units.h"
#include "lv2/urid.h"
#include "lv2/worker.h"
#include "lv2/lv2_kxstudio_properties.h"
#include "lv2/lv2_programs.h"
#include <fstream>
#include <iostream>
#ifndef DISTRHO_PLUGIN_URI
# error DISTRHO_PLUGIN_URI undefined!
#endif
#ifndef DISTRHO_PLUGIN_MINIMUM_BUFFER_SIZE
# define DISTRHO_PLUGIN_MINIMUM_BUFFER_SIZE 2048
#endif
#define DISTRHO_LV2_USE_EVENTS_IN (DISTRHO_PLUGIN_HAS_MIDI_INPUT || DISTRHO_PLUGIN_WANT_TIMEPOS || (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI))
#define DISTRHO_LV2_USE_EVENTS_OUT (DISTRHO_PLUGIN_HAS_MIDI_OUTPUT || (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI))
// -----------------------------------------------------------------------
DISTRHO_PLUGIN_EXPORT
void lv2_generate_ttl(const char* const basename)
{
USE_NAMESPACE_DISTRHO
// Dummy plugin to get data from
d_lastBufferSize = 512;
d_lastSampleRate = 44100.0;
PluginExporter plugin;
d_lastBufferSize = 0;
d_lastSampleRate = 0.0;
d_string pluginDLL(basename);
d_string pluginTTL(pluginDLL + ".ttl");
// ---------------------------------------------
{
std::cout << "Writing manifest.ttl..."; std::cout.flush();
std::fstream manifestFile("manifest.ttl", std::ios::out);
d_string manifestString;
manifestString += "@prefix lv2: <" LV2_CORE_PREFIX "> .\n";
manifestString += "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n";
#if DISTRHO_PLUGIN_HAS_UI
manifestString += "@prefix ui: <" LV2_UI_PREFIX "> .\n";
#endif
manifestString += "\n";
manifestString += "<" DISTRHO_PLUGIN_URI ">\n";
manifestString += " a lv2:Plugin ;\n";
manifestString += " lv2:binary <" + pluginDLL + "." DISTRHO_DLL_EXTENSION "> ;\n";
manifestString += " rdfs:seeAlso <" + pluginTTL + "> .\n";
manifestString += "\n";
#if DISTRHO_PLUGIN_HAS_UI
manifestString += "<" DISTRHO_UI_URI ">\n";
# if DISTRHO_OS_HAIKU
manifestString += " a ui:BeUI ;\n";
# elif DISTRHO_OS_MAC
manifestString += " a ui:CocoaUI ;\n";
# elif DISTRHO_OS_WINDOWS
manifestString += " a ui:WindowsUI ;\n";
# else
manifestString += " a ui:X11UI ;\n";
# endif
# if ! DISTRHO_PLUGIN_WANT_DIRECT_ACCESS
d_string pluginUI(pluginDLL);
pluginUI.truncate(pluginDLL.rfind("_dsp"));
pluginUI += "_ui";
manifestString += " ui:binary <" + pluginUI + "." DISTRHO_DLL_EXTENSION "> ;\n";
# else
manifestString += " ui:binary <" + pluginDLL + "." DISTRHO_DLL_EXTENSION "> ;\n";
#endif
manifestString += " lv2:extensionData ui:idleInterface ,\n";
# if DISTRHO_PLUGIN_WANT_PROGRAMS
manifestString += " ui:showInterface ,\n";
manifestString += " <" LV2_PROGRAMS__Interface "> ;\n";
# else
manifestString += " ui:showInterface ;\n";
# endif
manifestString += " lv2:optionalFeature ui:noUserResize ,\n";
manifestString += " ui:resize ,\n";
manifestString += " ui:touch ;\n";
# if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS
manifestString += " lv2:requiredFeature <" LV2_DATA_ACCESS_URI "> ,\n";
manifestString += " <" LV2_INSTANCE_ACCESS_URI "> ,\n";
manifestString += " <" LV2_OPTIONS__options "> ,\n";
# else
manifestString += " lv2:requiredFeature <" LV2_OPTIONS__options "> ,\n";
# endif
manifestString += " <" LV2_URID__map "> .\n";
#endif
manifestFile << manifestString << std::endl;
manifestFile.close();
std::cout << " done!" << std::endl;
}
// ---------------------------------------------
{
std::cout << "Writing " << pluginTTL << "..."; std::cout.flush();
std::fstream pluginFile(pluginTTL, std::ios::out);
d_string pluginString;
// header
#if DISTRHO_LV2_USE_EVENTS_IN
pluginString += "@prefix atom: <" LV2_ATOM_PREFIX "> .\n";
#endif
pluginString += "@prefix doap: <http://usefulinc.com/ns/doap#> .\n";
pluginString += "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n";
pluginString += "@prefix lv2: <" LV2_CORE_PREFIX "> .\n";
pluginString += "@prefix rsz: <" LV2_RESIZE_PORT_PREFIX "> .\n";
#if DISTRHO_PLUGIN_HAS_UI
pluginString += "@prefix ui: <" LV2_UI_PREFIX "> .\n";
#endif
pluginString += "@prefix unit: <" LV2_UNITS_PREFIX "> .\n";
pluginString += "\n";
// plugin
pluginString += "<" DISTRHO_PLUGIN_URI ">\n";
#if DISTRHO_PLUGIN_IS_SYNTH
pluginString += " a lv2:InstrumentPlugin, lv2:Plugin ;\n";
#else
pluginString += " a lv2:Plugin ;\n";
#endif
pluginString += "\n";
// extensionData
pluginString += " lv2:extensionData <" LV2_STATE__interface "> ";
#if DISTRHO_PLUGIN_WANT_STATE
pluginString += ",\n <" LV2_OPTIONS__interface "> ";
pluginString += ",\n <" LV2_WORKER__interface "> ";
#endif
#if DISTRHO_PLUGIN_WANT_PROGRAMS
pluginString += ",\n <" LV2_PROGRAMS__Interface "> ";
#endif
pluginString += ";\n\n";
// optionalFeatures
#if DISTRHO_PLUGIN_IS_RT_SAFE
pluginString += " lv2:optionalFeature <" LV2_CORE__hardRTCapable "> ,\n";
pluginString += " <" LV2_BUF_SIZE__boundedBlockLength "> ;\n";
#else
pluginString += " lv2:optionalFeature <" LV2_BUF_SIZE__boundedBlockLength "> ;\n";
#endif
pluginString += "\n";
// requiredFeatures
pluginString += " lv2:requiredFeature <" LV2_OPTIONS__options "> ";
pluginString += ",\n <" LV2_URID__map "> ";
#if DISTRHO_PLUGIN_WANT_STATE
pluginString += ",\n <" LV2_WORKER__schedule "> ";
#endif
pluginString += ";\n\n";
// UI
#if DISTRHO_PLUGIN_HAS_UI
pluginString += " ui:ui <" DISTRHO_UI_URI "> ;\n";
pluginString += "\n";
#endif
{
uint32_t portIndex = 0;
#if DISTRHO_PLUGIN_NUM_INPUTS > 0
for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i, ++portIndex)
{
if (i == 0)
pluginString += " lv2:port [\n";
else
pluginString += " [\n";
pluginString += " a lv2:InputPort, lv2:AudioPort ;\n";
pluginString += " lv2:index " + d_string(portIndex) + " ;\n";
pluginString += " lv2:symbol \"lv2_audio_in_" + d_string(i+1) + "\" ;\n";
pluginString += " lv2:name \"Audio Input " + d_string(i+1) + "\" ;\n";
if (i+1 == DISTRHO_PLUGIN_NUM_INPUTS)
pluginString += " ] ;\n\n";
else
pluginString += " ] ,\n";
}
pluginString += "\n";
#endif
#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0
for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i, ++portIndex)
{
if (i == 0)
pluginString += " lv2:port [\n";
else
pluginString += " [\n";
pluginString += " a lv2:OutputPort, lv2:AudioPort ;\n";
pluginString += " lv2:index " + d_string(portIndex) + " ;\n";
pluginString += " lv2:symbol \"lv2_audio_out_" + d_string(i+1) + "\" ;\n";
pluginString += " lv2:name \"Audio Output " + d_string(i+1) + "\" ;\n";
if (i+1 == DISTRHO_PLUGIN_NUM_OUTPUTS)
pluginString += " ] ;\n\n";
else
pluginString += " ] ,\n";
}
pluginString += "\n";
#endif
#if DISTRHO_LV2_USE_EVENTS_IN
pluginString += " lv2:port [\n";
pluginString += " a lv2:InputPort, atom:AtomPort ;\n";
pluginString += " lv2:index " + d_string(portIndex) + " ;\n";
pluginString += " lv2:name \"Events Input\" ;\n";
pluginString += " lv2:symbol \"lv2_events_in\" ;\n";
pluginString += " rsz:minimumSize " + d_string(DISTRHO_PLUGIN_MINIMUM_BUFFER_SIZE) + " ;\n";
pluginString += " atom:bufferType atom:Sequence ;\n";
# if (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI)
pluginString += " atom:supports <" LV2_ATOM__String "> ;\n";
# endif
# if DISTRHO_PLUGIN_HAS_MIDI_INPUT
pluginString += " atom:supports <" LV2_MIDI__MidiEvent "> ;\n";
# endif
# if DISTRHO_PLUGIN_WANT_TIMEPOS
pluginString += " atom:supports <" LV2_TIME__Position "> ;\n";
# endif
pluginString += " ] ;\n\n";
++portIndex;
#endif
#if DISTRHO_LV2_USE_EVENTS_OUT
pluginString += " lv2:port [\n";
pluginString += " a lv2:OutputPort, atom:AtomPort ;\n";
pluginString += " lv2:index " + d_string(portIndex) + " ;\n";
pluginString += " lv2:name \"Events Output\" ;\n";
pluginString += " lv2:symbol \"lv2_events_out\" ;\n";
pluginString += " rsz:minimumSize " + d_string(DISTRHO_PLUGIN_MINIMUM_BUFFER_SIZE) + " ;\n";
pluginString += " atom:bufferType atom:Sequence ;\n";
# if (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI)
pluginString += " atom:supports <" LV2_ATOM__String "> ;\n";
# endif
# if DISTRHO_PLUGIN_HAS_MIDI_OUTPUT
pluginString += " atom:supports <" LV2_MIDI__MidiEvent "> ;\n";
# endif
pluginString += " ] ;\n\n";
++portIndex;
#endif
#if DISTRHO_PLUGIN_WANT_LATENCY
pluginString += " lv2:port [\n";
pluginString += " a lv2:OutputPort, lv2:ControlPort ;\n";
pluginString += " lv2:index " + d_string(portIndex) + " ;\n";
pluginString += " lv2:name \"Latency\" ;\n";
pluginString += " lv2:symbol \"lv2_latency\" ;\n";
pluginString += " lv2:designation lv2:latency ;\n";
pluginString += " lv2:portProperty lv2:reportsLatency, lv2:integer ;\n";
pluginString += " ] ;\n\n";
++portIndex;
#endif
for (uint32_t i=0, count=plugin.getParameterCount(); i < count; ++i, ++portIndex)
{
if (i == 0)
pluginString += " lv2:port [\n";
else
pluginString += " [\n";
if (plugin.isParameterOutput(i))
pluginString += " a lv2:OutputPort, lv2:ControlPort ;\n";
else
pluginString += " a lv2:InputPort, lv2:ControlPort ;\n";
pluginString += " lv2:index " + d_string(portIndex) + " ;\n";
pluginString += " lv2:name \"" + plugin.getParameterName(i) + "\" ;\n";
// symbol
{
d_string symbol(plugin.getParameterSymbol(i));
if (symbol.isEmpty())
symbol = "lv2_port_" + d_string(portIndex-1);
pluginString += " lv2:symbol \"" + symbol + "\" ;\n";
}
// ranges
{
const ParameterRanges& ranges(plugin.getParameterRanges(i));
if (plugin.getParameterHints(i) & kParameterIsInteger)
{
pluginString += " lv2:default " + d_string(int(plugin.getParameterValue(i))) + " ;\n";
pluginString += " lv2:minimum " + d_string(int(ranges.min)) + " ;\n";
pluginString += " lv2:maximum " + d_string(int(ranges.max)) + " ;\n";
}
else
{
pluginString += " lv2:default " + d_string(plugin.getParameterValue(i)) + " ;\n";
pluginString += " lv2:minimum " + d_string(ranges.min) + " ;\n";
pluginString += " lv2:maximum " + d_string(ranges.max) + " ;\n";
}
}
// unit
{
const d_string& unit(plugin.getParameterUnit(i));
if (! unit.isEmpty())
{
if (unit == "db" || unit == "dB")
{
pluginString += " unit:unit unit:db ;\n";
}
else if (unit == "hz" || unit == "Hz")
{
pluginString += " unit:unit unit:hz ;\n";
}
else if (unit == "khz" || unit == "kHz")
{
pluginString += " unit:unit unit:khz ;\n";
}
else if (unit == "mhz" || unit == "mHz")
{
pluginString += " unit:unit unit:mhz ;\n";
}
else if (unit == "%")
{
pluginString += " unit:unit unit:pc ;\n";
}
else
{
pluginString += " unit:unit [\n";
pluginString += " a unit:Unit ;\n";
pluginString += " unit:name \"" + unit + "\" ;\n";
pluginString += " unit:symbol \"" + unit + "\" ;\n";
pluginString += " unit:render \"%f " + unit + "\" ;\n";
pluginString += " ] ;\n";
}
}
}
// hints
{
const uint32_t hints(plugin.getParameterHints(i));
if (hints & kParameterIsBoolean)
pluginString += " lv2:portProperty lv2:toggled ;\n";
if (hints & kParameterIsInteger)
pluginString += " lv2:portProperty lv2:integer ;\n";
if (hints & kParameterIsLogarithmic)
pluginString += " lv2:portProperty <" LV2_PORT_PROPS__logarithmic "> ;\n";
if ((hints & kParameterIsAutomable) == 0 && ! plugin.isParameterOutput(i))
{
pluginString += " lv2:portProperty <" LV2_PORT_PROPS__expensive "> ,\n";
pluginString += " <" LV2_KXSTUDIO_PROPERTIES__NonAutomable "> ;\n";
}
}
if (i+1 == count)
pluginString += " ] ;\n\n";
else
pluginString += " ] ,\n";
}
}
pluginString += " doap:name \"" + d_string(plugin.getName()) + "\" ;\n";
pluginString += " doap:maintainer [ foaf:name \"" + d_string(plugin.getMaker()) + "\" ] .\n";
pluginFile << pluginString << std::endl;
pluginFile.close();
std::cout << " done!" << std::endl;
}
}
| Java |
// The following are instance methods and variables
var Note = Class.create({
initialize: function(id, is_new, raw_body) {
if (Note.debug) {
console.debug("Note#initialize (id=%d)", id)
}
this.id = id
this.is_new = is_new
this.document_observers = [];
// Cache the elements
this.elements = {
box: $('note-box-' + this.id),
corner: $('note-corner-' + this.id),
body: $('note-body-' + this.id),
image: $('image')
}
// Cache the dimensions
this.fullsize = {
left: this.elements.box.offsetLeft,
top: this.elements.box.offsetTop,
width: this.elements.box.clientWidth,
height: this.elements.box.clientHeight
}
// Store the original values (in case the user clicks Cancel)
this.old = {
raw_body: raw_body,
formatted_body: this.elements.body.innerHTML
}
for (p in this.fullsize) {
this.old[p] = this.fullsize[p]
}
// Make the note translucent
if (is_new) {
this.elements.box.setOpacity(0.2)
} else {
this.elements.box.setOpacity(0.5)
}
if (is_new && raw_body == '') {
this.bodyfit = true
this.elements.body.style.height = "100px"
}
// Attach the event listeners
this.elements.box.observe("mousedown", this.dragStart.bindAsEventListener(this))
this.elements.box.observe("mouseout", this.bodyHideTimer.bindAsEventListener(this))
this.elements.box.observe("mouseover", this.bodyShow.bindAsEventListener(this))
this.elements.corner.observe("mousedown", this.resizeStart.bindAsEventListener(this))
this.elements.body.observe("mouseover", this.bodyShow.bindAsEventListener(this))
this.elements.body.observe("mouseout", this.bodyHideTimer.bindAsEventListener(this))
this.elements.body.observe("click", this.showEditBox.bindAsEventListener(this))
this.adjustScale()
},
// Returns the raw text value of this note
textValue: function() {
if (Note.debug) {
console.debug("Note#textValue (id=%d)", this.id)
}
return this.old.raw_body.strip()
},
// Removes the edit box
hideEditBox: function(e) {
if (Note.debug) {
console.debug("Note#hideEditBox (id=%d)", this.id)
}
var editBox = $('edit-box')
if (editBox != null) {
var boxid = editBox.noteid
$("edit-box").stopObserving()
$("note-save-" + boxid).stopObserving()
$("note-cancel-" + boxid).stopObserving()
$("note-remove-" + boxid).stopObserving()
$("note-history-" + boxid).stopObserving()
$("edit-box").remove()
}
},
// Shows the edit box
showEditBox: function(e) {
if (Note.debug) {
console.debug("Note#showEditBox (id=%d)", this.id)
}
this.hideEditBox(e)
var insertionPosition = Note.getInsertionPosition()
var top = insertionPosition[0]
var left = insertionPosition[1]
var html = ""
html += '<div id="edit-box" style="top: '+top+'px; left: '+left+'px; position: absolute; visibility: visible; z-index: 100; background: white; border: 1px solid black; padding: 12px;">'
html += '<form onsubmit="return false;" style="padding: 0; margin: 0;">'
html += '<textarea rows="7" id="edit-box-text" style="width: 350px; margin: 2px 2px 12px 2px;">' + this.textValue() + '</textarea>'
html += '<input type="submit" value="Save" name="save" id="note-save-' + this.id + '">'
html += '<input type="submit" value="Cancel" name="cancel" id="note-cancel-' + this.id + '">'
html += '<input type="submit" value="Remove" name="remove" id="note-remove-' + this.id + '">'
html += '<input type="submit" value="History" name="history" id="note-history-' + this.id + '">'
html += '</form>'
html += '</div>'
$("note-container").insert({bottom: html})
$('edit-box').noteid = this.id
$("edit-box").observe("mousedown", this.editDragStart.bindAsEventListener(this))
$("note-save-" + this.id).observe("click", this.save.bindAsEventListener(this))
$("note-cancel-" + this.id).observe("click", this.cancel.bindAsEventListener(this))
$("note-remove-" + this.id).observe("click", this.remove.bindAsEventListener(this))
$("note-history-" + this.id).observe("click", this.history.bindAsEventListener(this))
$("edit-box-text").focus()
},
// Shows the body text for the note
bodyShow: function(e) {
if (Note.debug) {
console.debug("Note#bodyShow (id=%d)", this.id)
}
if (this.dragging) {
return
}
if (this.hideTimer) {
clearTimeout(this.hideTimer)
this.hideTimer = null
}
if (Note.noteShowingBody == this) {
return
}
if (Note.noteShowingBody) {
Note.noteShowingBody.bodyHide()
}
Note.noteShowingBody = this
if (Note.zindex >= 9) {
/* don't use more than 10 layers (+1 for the body, which will always be above all notes) */
Note.zindex = 0
for (var i=0; i< Note.all.length; ++i) {
Note.all[i].elements.box.style.zIndex = 0
}
}
this.elements.box.style.zIndex = ++Note.zindex
this.elements.body.style.zIndex = 10
this.elements.body.style.top = 0 + "px"
this.elements.body.style.left = 0 + "px"
var dw = document.documentElement.scrollWidth
this.elements.body.style.visibility = "hidden"
this.elements.body.style.display = "block"
if (!this.bodyfit) {
this.elements.body.style.height = "auto"
this.elements.body.style.minWidth = "140px"
var w = null, h = null, lo = null, hi = null, x = null, last = null
w = this.elements.body.offsetWidth
h = this.elements.body.offsetHeight
if (w/h < 1.6180339887) {
/* for tall notes (lots of text), find more pleasant proportions */
lo = 140, hi = 400
do {
last = w
x = (lo+hi)/2
this.elements.body.style.minWidth = x + "px"
w = this.elements.body.offsetWidth
h = this.elements.body.offsetHeight
if (w/h < 1.6180339887) lo = x
else hi = x
} while ((lo < hi) && (w > last))
} else if (this.elements.body.scrollWidth <= this.elements.body.clientWidth) {
/* for short notes (often a single line), make the box no wider than necessary */
// scroll test necessary for Firefox
lo = 20, hi = w
do {
x = (lo+hi)/2
this.elements.body.style.minWidth = x + "px"
if (this.elements.body.offsetHeight > h) lo = x
else hi = x
} while ((hi - lo) > 4)
if (this.elements.body.offsetHeight > h)
this.elements.body.style.minWidth = hi + "px"
}
if (Prototype.Browser.IE) {
// IE7 adds scrollbars if the box is too small, obscuring the text
if (this.elements.body.offsetHeight < 35) {
this.elements.body.style.minHeight = "35px"
}
if (this.elements.body.offsetWidth < 47) {
this.elements.body.style.minWidth = "47px"
}
}
this.bodyfit = true
}
this.elements.body.style.top = (this.elements.box.offsetTop + this.elements.box.clientHeight + 5) + "px"
// keep the box within the document's width
var l = 0, e = this.elements.box
do { l += e.offsetLeft } while (e = e.offsetParent)
l += this.elements.body.offsetWidth + 10 - dw
if (l > 0)
this.elements.body.style.left = this.elements.box.offsetLeft - l + "px"
else
this.elements.body.style.left = this.elements.box.offsetLeft + "px"
this.elements.body.style.visibility = "visible"
},
// Creates a timer that will hide the body text for the note
bodyHideTimer: function(e) {
if (Note.debug) {
console.debug("Note#bodyHideTimer (id=%d)", this.id)
}
this.hideTimer = setTimeout(this.bodyHide.bindAsEventListener(this), 250)
},
// Hides the body text for the note
bodyHide: function(e) {
if (Note.debug) {
console.debug("Note#bodyHide (id=%d)", this.id)
}
this.elements.body.hide()
if (Note.noteShowingBody == this) {
Note.noteShowingBody = null
}
},
addDocumentObserver: function(name, func)
{
document.observe(name, func);
this.document_observers.push([name, func]);
},
clearDocumentObservers: function(name, handler)
{
for(var i = 0; i < this.document_observers.length; ++i)
{
var observer = this.document_observers[i];
document.stopObserving(observer[0], observer[1]);
}
this.document_observers = [];
},
// Start dragging the note
dragStart: function(e) {
if (Note.debug) {
console.debug("Note#dragStart (id=%d)", this.id)
}
this.addDocumentObserver("mousemove", this.drag.bindAsEventListener(this))
this.addDocumentObserver("mouseup", this.dragStop.bindAsEventListener(this))
this.addDocumentObserver("selectstart", function() {return false})
this.cursorStartX = e.pointerX()
this.cursorStartY = e.pointerY()
this.boxStartX = this.elements.box.offsetLeft
this.boxStartY = this.elements.box.offsetTop
this.boundsX = new ClipRange(5, this.elements.image.clientWidth - this.elements.box.clientWidth - 5)
this.boundsY = new ClipRange(5, this.elements.image.clientHeight - this.elements.box.clientHeight - 5)
this.dragging = true
this.bodyHide()
},
// Stop dragging the note
dragStop: function(e) {
if (Note.debug) {
console.debug("Note#dragStop (id=%d)", this.id)
}
this.clearDocumentObservers()
this.cursorStartX = null
this.cursorStartY = null
this.boxStartX = null
this.boxStartY = null
this.boundsX = null
this.boundsY = null
this.dragging = false
this.bodyShow()
},
ratio: function() {
return this.elements.image.width / this.elements.image.getAttribute("large_width")
// var ratio = this.elements.image.width / this.elements.image.getAttribute("large_width")
// if (this.elements.image.scale_factor != null)
// ratio *= this.elements.image.scale_factor;
// return ratio
},
// Scale the notes for when the image gets resized
adjustScale: function() {
if (Note.debug) {
console.debug("Note#adjustScale (id=%d)", this.id)
}
var ratio = this.ratio()
for (p in this.fullsize) {
this.elements.box.style[p] = this.fullsize[p] * ratio + 'px'
}
},
// Update the note's position as it gets dragged
drag: function(e) {
var left = this.boxStartX + e.pointerX() - this.cursorStartX
var top = this.boxStartY + e.pointerY() - this.cursorStartY
left = this.boundsX.clip(left)
top = this.boundsY.clip(top)
this.elements.box.style.left = left + 'px'
this.elements.box.style.top = top + 'px'
var ratio = this.ratio()
this.fullsize.left = left / ratio
this.fullsize.top = top / ratio
e.stop()
},
// Start dragging the edit box
editDragStart: function(e) {
if (Note.debug) {
console.debug("Note#editDragStart (id=%d)", this.id)
}
var node = e.element().nodeName
if (node != 'FORM' && node != 'DIV') {
return
}
this.addDocumentObserver("mousemove", this.editDrag.bindAsEventListener(this))
this.addDocumentObserver("mouseup", this.editDragStop.bindAsEventListener(this))
this.addDocumentObserver("selectstart", function() {return false})
this.elements.editBox = $('edit-box');
this.cursorStartX = e.pointerX()
this.cursorStartY = e.pointerY()
this.editStartX = this.elements.editBox.offsetLeft
this.editStartY = this.elements.editBox.offsetTop
this.dragging = true
},
// Stop dragging the edit box
editDragStop: function(e) {
if (Note.debug) {
console.debug("Note#editDragStop (id=%d)", this.id)
}
this.clearDocumentObservers()
this.cursorStartX = null
this.cursorStartY = null
this.editStartX = null
this.editStartY = null
this.dragging = false
},
// Update the edit box's position as it gets dragged
editDrag: function(e) {
var left = this.editStartX + e.pointerX() - this.cursorStartX
var top = this.editStartY + e.pointerY() - this.cursorStartY
this.elements.editBox.style.left = left + 'px'
this.elements.editBox.style.top = top + 'px'
e.stop()
},
// Start resizing the note
resizeStart: function(e) {
if (Note.debug) {
console.debug("Note#resizeStart (id=%d)", this.id)
}
this.cursorStartX = e.pointerX()
this.cursorStartY = e.pointerY()
this.boxStartWidth = this.elements.box.clientWidth
this.boxStartHeight = this.elements.box.clientHeight
this.boxStartX = this.elements.box.offsetLeft
this.boxStartY = this.elements.box.offsetTop
this.boundsX = new ClipRange(10, this.elements.image.clientWidth - this.boxStartX - 5)
this.boundsY = new ClipRange(10, this.elements.image.clientHeight - this.boxStartY - 5)
this.dragging = true
this.clearDocumentObservers()
this.addDocumentObserver("mousemove", this.resize.bindAsEventListener(this))
this.addDocumentObserver("mouseup", this.resizeStop.bindAsEventListener(this))
e.stop()
this.bodyHide()
},
// Stop resizing teh note
resizeStop: function(e) {
if (Note.debug) {
console.debug("Note#resizeStop (id=%d)", this.id)
}
this.clearDocumentObservers()
this.boxCursorStartX = null
this.boxCursorStartY = null
this.boxStartWidth = null
this.boxStartHeight = null
this.boxStartX = null
this.boxStartY = null
this.boundsX = null
this.boundsY = null
this.dragging = false
e.stop()
},
// Update the note's dimensions as it gets resized
resize: function(e) {
var width = this.boxStartWidth + e.pointerX() - this.cursorStartX
var height = this.boxStartHeight + e.pointerY() - this.cursorStartY
width = this.boundsX.clip(width)
height = this.boundsY.clip(height)
this.elements.box.style.width = width + "px"
this.elements.box.style.height = height + "px"
var ratio = this.ratio()
this.fullsize.width = width / ratio
this.fullsize.height = height / ratio
e.stop()
},
// Save the note to the database
save: function(e) {
if (Note.debug) {
console.debug("Note#save (id=%d)", this.id)
}
var note = this
for (p in this.fullsize) {
this.old[p] = this.fullsize[p]
}
this.old.raw_body = $('edit-box-text').value
this.old.formatted_body = this.textValue()
// FIXME: this is not quite how the note will look (filtered elems, <tn>...). the user won't input a <script> that only damages him, but it might be nice to "preview" the <tn> here
this.elements.body.update(this.textValue())
this.hideEditBox(e)
this.bodyHide()
this.bodyfit = false
var params = {
"id": this.id,
"note[x]": this.old.left,
"note[y]": this.old.top,
"note[width]": this.old.width,
"note[height]": this.old.height,
"note[body]": this.old.raw_body
}
if (this.is_new) {
params["note[post_id]"] = Note.post_id
}
notice("Saving note...")
new Ajax.Request('/note/update.json', {
parameters: params,
onComplete: function(resp) {
var resp = resp.responseJSON
if (resp.success) {
notice("Note saved")
var note = Note.find(resp.old_id)
if (resp.old_id < 0) {
note.is_new = false
note.id = resp.new_id
note.elements.box.id = 'note-box-' + note.id
note.elements.body.id = 'note-body-' + note.id
note.elements.corner.id = 'note-corner-' + note.id
}
note.elements.body.innerHTML = resp.formatted_body
note.elements.box.setOpacity(0.5)
note.elements.box.removeClassName('unsaved')
} else {
notice("Error: " + resp.reason)
note.elements.box.addClassName('unsaved')
}
}
})
e.stop()
},
// Revert the note to the last saved state
cancel: function(e) {
if (Note.debug) {
console.debug("Note#cancel (id=%d)", this.id)
}
this.hideEditBox(e)
this.bodyHide()
var ratio = this.ratio()
for (p in this.fullsize) {
this.fullsize[p] = this.old[p]
this.elements.box.style[p] = this.fullsize[p] * ratio + 'px'
}
this.elements.body.innerHTML = this.old.formatted_body
e.stop()
},
// Remove all references to the note from the page
removeCleanup: function() {
if (Note.debug) {
console.debug("Note#removeCleanup (id=%d)", this.id)
}
this.elements.box.remove()
this.elements.body.remove()
var allTemp = []
for (i=0; i<Note.all.length; ++i) {
if (Note.all[i].id != this.id) {
allTemp.push(Note.all[i])
}
}
Note.all = allTemp
Note.updateNoteCount()
},
// Removes a note from the database
remove: function(e) {
if (Note.debug) {
console.debug("Note#remove (id=%d)", this.id)
}
this.hideEditBox(e)
this.bodyHide()
this_note = this
if (this.is_new) {
this.removeCleanup()
notice("Note removed")
} else {
notice("Removing note...")
new Ajax.Request('/note/update.json', {
parameters: {
"id": this.id,
"note[is_active]": "0"
},
onComplete: function(resp) {
var resp = resp.responseJSON
if (resp.success) {
notice("Note removed")
this_note.removeCleanup()
} else {
notice("Error: " + resp.reason)
}
}
})
}
e.stop()
},
// Redirect to the note's history
history: function(e) {
if (Note.debug) {
console.debug("Note#history (id=%d)", this.id)
}
this.hideEditBox(e)
if (this.is_new) {
notice("This note has no history")
} else {
location.href = '/history?search=notes:' + this.id
}
e.stop()
}
})
// The following are class methods and variables
Object.extend(Note, {
zindex: 0,
counter: -1,
all: [],
display: true,
debug: false,
// Show all notes
show: function() {
if (Note.debug) {
console.debug("Note.show")
}
$("note-container").show()
},
// Hide all notes
hide: function() {
if (Note.debug) {
console.debug("Note.hide")
}
$("note-container").hide()
},
// Find a note instance based on the id number
find: function(id) {
if (Note.debug) {
console.debug("Note.find")
}
for (var i=0; i<Note.all.size(); ++i) {
if (Note.all[i].id == id) {
return Note.all[i]
}
}
return null
},
// Toggle the display of all notes
toggle: function() {
if (Note.debug) {
console.debug("Note.toggle")
}
if (Note.display) {
Note.hide()
Note.display = false
} else {
Note.show()
Note.display = true
}
},
// Update the text displaying the number of notes a post has
updateNoteCount: function() {
if (Note.debug) {
console.debug("Note.updateNoteCount")
}
if (Note.all.length > 0) {
var label = ""
if (Note.all.length == 1)
label = "note"
else
label = "notes"
$('note-count').innerHTML = "This post has <a href=\"/note/history?post_id=" + Note.post_id + "\">" + Note.all.length + " " + label + "</a>"
} else {
$('note-count').innerHTML = ""
}
},
// Create a new note
create: function() {
if (Note.debug) {
console.debug("Note.create")
}
Note.show()
var insertion_position = Note.getInsertionPosition()
var top = insertion_position[0]
var left = insertion_position[1]
var html = ''
html += '<div class="note-box unsaved" style="width: 150px; height: 150px; '
html += 'top: ' + top + 'px; '
html += 'left: ' + left + 'px;" '
html += 'id="note-box-' + Note.counter + '">'
html += '<div class="note-corner" id="note-corner-' + Note.counter + '"></div>'
html += '</div>'
html += '<div class="note-body" title="Click to edit" id="note-body-' + Note.counter + '"></div>'
$("note-container").insert({bottom: html})
var note = new Note(Note.counter, true, "")
Note.all.push(note)
Note.counter -= 1
},
// Find a suitable position to insert new notes
getInsertionPosition: function() {
if (Note.debug) {
console.debug("Note.getInsertionPosition")
}
// We want to show the edit box somewhere on the screen, but not outside the image.
var scroll_x = $("image").cumulativeScrollOffset()[0]
var scroll_y = $("image").cumulativeScrollOffset()[1]
var image_left = $("image").positionedOffset()[0]
var image_top = $("image").positionedOffset()[1]
var image_right = image_left + $("image").width
var image_bottom = image_top + $("image").height
var left = 0
var top = 0
if (scroll_x > image_left) {
left = scroll_x
} else {
left = image_left
}
if (scroll_y > image_top) {
top = scroll_y
} else {
top = image_top + 20
}
if (top > image_bottom) {
top = image_top + 20
}
return [top, left]
}
})
| Java |
// Copyright (c) 2021 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package indexers
import (
"context"
"fmt"
"sync"
"sync/atomic"
"github.com/decred/dcrd/blockchain/v4/internal/progresslog"
"github.com/decred/dcrd/database/v3"
"github.com/decred/dcrd/dcrutil/v4"
)
// IndexNtfnType represents an index notification type.
type IndexNtfnType int
const (
// ConnectNtfn indicates the index notification signals a block
// connected to the main chain.
ConnectNtfn IndexNtfnType = iota
// DisconnectNtfn indicates the index notification signals a block
// disconnected from the main chain.
DisconnectNtfn
)
var (
// bufferSize represents the index notification buffer size.
bufferSize = 128
// noPrereqs indicates no index prerequisites.
noPrereqs = "none"
)
// IndexNtfn represents an index notification detailing a block connection
// or disconnection.
type IndexNtfn struct {
NtfnType IndexNtfnType
Block *dcrutil.Block
Parent *dcrutil.Block
PrevScripts PrevScripter
IsTreasuryEnabled bool
Done chan bool
}
// IndexSubscription represents a subscription for index updates.
type IndexSubscription struct {
id string
idx Indexer
subscriber *IndexSubscriber
mtx sync.Mutex
// prerequisite defines the notification processing hierarchy for this
// subscription. It is expected that the subscriber associated with the
// prerequisite provided processes notifications before they are
// delivered by this subscription to its subscriber. An empty string
// indicates the subscription has no prerequisite.
prerequisite string
// dependent defines the index subscription that requires the subscriber
// associated with this subscription to have processed incoming
// notifications before it does. A nil dependency indicates the subscription
// has no dependencies.
dependent *IndexSubscription
}
// newIndexSubscription initializes a new index subscription.
func newIndexSubscription(subber *IndexSubscriber, indexer Indexer, prereq string) *IndexSubscription {
return &IndexSubscription{
id: indexer.Name(),
idx: indexer,
prerequisite: prereq,
subscriber: subber,
}
}
// stop prevents any future index updates from being delivered and
// unsubscribes the associated subscription.
func (s *IndexSubscription) stop() error {
// If the subscription has a prerequisite, find it and remove the
// subscription as a dependency.
if s.prerequisite != noPrereqs {
s.mtx.Lock()
prereq, ok := s.subscriber.subscriptions[s.prerequisite]
s.mtx.Unlock()
if !ok {
return fmt.Errorf("no subscription found with id %s", s.prerequisite)
}
prereq.mtx.Lock()
prereq.dependent = nil
prereq.mtx.Unlock()
return nil
}
// If the subscription has a dependent, stop it as well.
if s.dependent != nil {
err := s.dependent.stop()
if err != nil {
return err
}
}
// If the subscription is independent, remove it from the
// index subscriber's subscriptions.
s.mtx.Lock()
delete(s.subscriber.subscriptions, s.id)
s.mtx.Unlock()
return nil
}
// IndexSubscriber subscribes clients for index updates.
type IndexSubscriber struct {
subscribers uint32 // update atomically.
c chan IndexNtfn
subscriptions map[string]*IndexSubscription
mtx sync.Mutex
ctx context.Context
cancel context.CancelFunc
quit chan struct{}
}
// NewIndexSubscriber creates a new index subscriber. It also starts the
// handler for incoming index update subscriptions.
func NewIndexSubscriber(sCtx context.Context) *IndexSubscriber {
ctx, cancel := context.WithCancel(sCtx)
s := &IndexSubscriber{
c: make(chan IndexNtfn, bufferSize),
subscriptions: make(map[string]*IndexSubscription),
ctx: ctx,
cancel: cancel,
quit: make(chan struct{}),
}
return s
}
// Subscribe subscribes an index for updates. The returned index subscription
// has functions to retrieve a channel that produces a stream of index updates
// and to stop the stream when the caller no longer wishes to receive updates.
func (s *IndexSubscriber) Subscribe(index Indexer, prerequisite string) (*IndexSubscription, error) {
sub := newIndexSubscription(s, index, prerequisite)
// If the subscription has a prequisite, find it and set the subscription
// as a dependency.
if prerequisite != noPrereqs {
s.mtx.Lock()
prereq, ok := s.subscriptions[prerequisite]
s.mtx.Unlock()
if !ok {
return nil, fmt.Errorf("no subscription found with id %s", prerequisite)
}
prereq.mtx.Lock()
defer prereq.mtx.Unlock()
if prereq.dependent != nil {
return nil, fmt.Errorf("%s already has a dependent set: %s",
prereq.id, prereq.dependent.id)
}
prereq.dependent = sub
atomic.AddUint32(&s.subscribers, 1)
return sub, nil
}
// If the subscription does not have a prerequisite, add it to the index
// subscriber's subscriptions.
s.mtx.Lock()
s.subscriptions[sub.id] = sub
s.mtx.Unlock()
atomic.AddUint32(&s.subscribers, 1)
return sub, nil
}
// Notify relays an index notification to subscribed indexes for processing.
func (s *IndexSubscriber) Notify(ntfn *IndexNtfn) {
subscribers := atomic.LoadUint32(&s.subscribers)
// Only relay notifications when there are subscribed indexes
// to be notified.
if subscribers > 0 {
select {
case <-s.quit:
case s.c <- *ntfn:
}
}
}
// findLowestIndexTipHeight determines the lowest index tip height among
// subscribed indexes and their dependencies.
func (s *IndexSubscriber) findLowestIndexTipHeight(queryer ChainQueryer) (int64, int64, error) {
// Find the lowest tip height to catch up among subscribed indexes.
bestHeight, _ := queryer.Best()
lowestHeight := bestHeight
for _, sub := range s.subscriptions {
tipHeight, tipHash, err := sub.idx.Tip()
if err != nil {
return 0, bestHeight, err
}
// Ensure the index tip is on the main chain.
if !queryer.MainChainHasBlock(tipHash) {
return 0, bestHeight, fmt.Errorf("%s: index tip (%s) is not on the "+
"main chain", sub.idx.Name(), tipHash)
}
if tipHeight < lowestHeight {
lowestHeight = tipHeight
}
// Update the lowest tip height if a dependent has a lower tip height.
dependent := sub.dependent
for dependent != nil {
tipHeight, _, err := sub.dependent.idx.Tip()
if err != nil {
return 0, bestHeight, err
}
if tipHeight < lowestHeight {
lowestHeight = tipHeight
}
dependent = dependent.dependent
}
}
return lowestHeight, bestHeight, nil
}
// CatchUp syncs all subscribed indexes to the the main chain by connecting
// blocks from after the lowest index tip to the current main chain tip.
//
// This should be called after all indexes have subscribed for updates.
func (s *IndexSubscriber) CatchUp(ctx context.Context, db database.DB, queryer ChainQueryer) error {
lowestHeight, bestHeight, err := s.findLowestIndexTipHeight(queryer)
if err != nil {
return err
}
// Nothing to do if all indexes are synced.
if bestHeight == lowestHeight {
return nil
}
// Create a progress logger for the indexing process below.
progressLogger := progresslog.NewBlockProgressLogger("Indexed", log)
// tip and need to be caught up, so log the details and loop through
// each block that needs to be indexed.
log.Infof("Catching up from height %d to %d", lowestHeight,
bestHeight)
var cachedParent *dcrutil.Block
for height := lowestHeight + 1; height <= bestHeight; height++ {
if interruptRequested(ctx) {
return indexerError(ErrInterruptRequested, interruptMsg)
}
hash, err := queryer.BlockHashByHeight(height)
if err != nil {
return err
}
// Ensure the next tip hash is on the main chain.
if !queryer.MainChainHasBlock(hash) {
msg := fmt.Sprintf("the next block being synced to (%s) "+
"at height %d is not on the main chain", hash, height)
return indexerError(ErrBlockNotOnMainChain, msg)
}
var parent *dcrutil.Block
if cachedParent == nil && height > 0 {
parentHash, err := queryer.BlockHashByHeight(height - 1)
if err != nil {
return err
}
parent, err = queryer.BlockByHash(parentHash)
if err != nil {
return err
}
} else {
parent = cachedParent
}
child, err := queryer.BlockByHash(hash)
if err != nil {
return err
}
// Construct and send the index notification.
var prevScripts PrevScripter
err = db.View(func(dbTx database.Tx) error {
if interruptRequested(ctx) {
return indexerError(ErrInterruptRequested, interruptMsg)
}
prevScripts, err = queryer.PrevScripts(dbTx, child)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
isTreasuryEnabled, err := queryer.IsTreasuryAgendaActive(parent.Hash())
if err != nil {
return err
}
ntfn := &IndexNtfn{
NtfnType: ConnectNtfn,
Block: child,
Parent: parent,
PrevScripts: prevScripts,
IsTreasuryEnabled: isTreasuryEnabled,
}
// Relay the index update to subscribed indexes.
for _, sub := range s.subscriptions {
err := updateIndex(ctx, sub.idx, ntfn)
if err != nil {
s.cancel()
return err
}
}
cachedParent = child
progressLogger.LogBlockHeight(child.MsgBlock(), parent.MsgBlock())
}
log.Infof("Caught up to height %d", bestHeight)
return nil
}
// Run relays index notifications to subscribed indexes.
//
// This should be run as a goroutine.
func (s *IndexSubscriber) Run(ctx context.Context) {
for {
select {
case ntfn := <-s.c:
// Relay the index update to subscribed indexes.
for _, sub := range s.subscriptions {
err := updateIndex(ctx, sub.idx, &ntfn)
if err != nil {
log.Error(err)
s.cancel()
break
}
}
if ntfn.Done != nil {
close(ntfn.Done)
}
case <-ctx.Done():
log.Infof("Index subscriber shutting down")
close(s.quit)
// Stop all updates to subscribed indexes and terminate their
// processes.
for _, sub := range s.subscriptions {
err := sub.stop()
if err != nil {
log.Error("unable to stop index subscription: %v", err)
}
}
s.cancel()
return
}
}
}
| Java |
@echo off
CLS
%header%
echo.
if not exist "Programme\HackMii Installer" mkdir "Programme\HackMii Installer"
echo Downloade den HackMii Installer...
start /min/wait Support\wget -c -l1 -r -nd --retr-symlinks -t10 -T30 --random-wait --reject "*.html" --reject "%2A" --reject "get.php@file=hackmii_installer_v1.0*" "http://bootmii.org/download/"
move get.php* hackmii-installer_v1.2.zip >NUL
start /min/wait Support\7za e -aoa hackmii-installer_v1.2.zip -o"Programme\HackMii Installer" *.elf -r
del hackmii*
:endedesmoduls | Java |
# Limit rozbieżności
**Ostrzeżenie! Ustawienie granicy rozbieżności nie powinno być zmieniane.** Zwiększenie granicy rozbieżności może spowodować znaczny spadek wydajności.
Limit rozbieżności określa ilość adresów, które portfel wygeneruje i przeprowadzi prognozy, aby określić wykorzystanie. Domyślnie, limit rozbieżności jest ustawiony na 20. Oznacza to 2 rzeczy.
1. Kiedy portfel ładuje się po raz pierwszy, skanuje w poszukiwaniu adresów w użycia i oczekuje, że największa przerwa między adresami będzie wynosić 20;
2. Kiedy użytkownik otrzymuje nowo wygenerowane adresy, ich liczba wynosi tylko 20, następnie portfel wykonuje tą operację ponownie co powoduje, że luki pomiędzy adresami nie są większe niż 20.
Tak naprawdę są tylko dwa przypadki w których należy zmienić tę wartość:
1. Jeśli twój portfel został stworzony i używany intensywnie przed v1.0, może mieć duże luki adresowe. Jeśli przywracasz portfel z seeda i zauważysz, że brakuje funduszy, możesz zwiększyć ustawienie do 100 (następnie 1000 jeśli problem wciąż występuje), a następnie ponownie uruchom Decrediton. Po przywróceniu funduszy możesz powrócić do 20.
2. Jeśli chcesz być w stanie wygenerować więcej niż 20 adresów na raz, bez kolejkowania.
| Java |
enum asmop {
ASNOP = 0,
ASSTB,
ASSTH,
ASSTW,
ASSTL,
ASSTM,
ASSTS,
ASSTD,
ASLDSB,
ASLDUB,
ASLDSH,
ASLDUH,
ASLDSW,
ASLDUW,
ASLDL,
ASLDS,
ASLDD,
ASADDW,
ASSUBW,
ASMULW,
ASMODW,
ASUMODW,
ASDIVW,
ASUDIVW,
ASSHLW,
ASSHRW,
ASUSHRW,
ASLTW,
ASULTW,
ASGTW,
ASUGTW,
ASLEW,
ASULEW,
ASGEW,
ASUGEW,
ASEQW,
ASNEW,
ASBANDW,
ASBORW,
ASBXORW,
ASADDL,
ASSUBL,
ASMULL,
ASMODL,
ASUMODL,
ASDIVL,
ASUDIVL,
ASSHLL,
ASSHRL,
ASUSHRL,
ASLTL,
ASULTL,
ASGTL,
ASUGTL,
ASLEL,
ASULEL,
ASGEL,
ASUGEL,
ASEQL,
ASNEL,
ASBANDL,
ASBORL,
ASBXORL,
ASADDS,
ASSUBS,
ASMULS,
ASDIVS,
ASLTS,
ASGTS,
ASLES,
ASGES,
ASEQS,
ASNES,
ASADDD,
ASSUBD,
ASMULD,
ASDIVD,
ASLTD,
ASGTD,
ASLED,
ASGED,
ASEQD,
ASNED,
ASEXTBW,
ASUEXTBW,
ASEXTBL,
ASUEXTBL,
ASEXTHW,
ASUEXTHW,
ASEXTHL,
ASUEXTHL,
ASEXTWL,
ASUEXTWL,
ASSTOL,
ASSTOW,
ASDTOL,
ASDTOW,
ASSWTOD,
ASSWTOS,
ASSLTOD,
ASSLTOS,
ASEXTS,
ASTRUNCD,
ASJMP,
ASBRANCH,
ASRET,
ASCALL,
ASCALLE,
ASCALLEX,
ASPAR,
ASPARE,
ASALLOC,
ASFORM,
ASCOPYB,
ASCOPYH,
ASCOPYW,
ASCOPYL,
ASCOPYS,
ASCOPYD,
ASVSTAR,
ASVARG,
};
| Java |
// Copyright (c) 2013-2015 The btcsuite developers
// Copyright (c) 2015 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wire_test
import (
"bytes"
"io"
"reflect"
"testing"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrutil"
)
// TestBlock tests the MsgBlock API.
func TestBlock(t *testing.T) {
pver := wire.ProtocolVersion
// Test block header.
bh := wire.NewBlockHeader(
int32(pver), // Version
&testBlock.Header.PrevBlock, // PrevHash
&testBlock.Header.MerkleRoot, // MerkleRoot
&testBlock.Header.StakeRoot, // StakeRoot
uint16(0x0000), // VoteBits
[6]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // FinalState
uint16(0x0000), // Voters
uint8(0x00), // FreshStake
uint8(0x00), // Revocations
uint32(0), // Poolsize
testBlock.Header.Bits, // Bits
int64(0x0000000000000000), // Sbits
uint32(1), // Height
uint32(1), // Size
testBlock.Header.Nonce, // Nonce
[36]byte{}, // ExtraData
)
// Ensure the command is expected value.
wantCmd := "block"
msg := wire.NewMsgBlock(bh)
if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgBlock: wrong command - got %v want %v",
cmd, wantCmd)
}
// Ensure max payload is expected value for latest protocol version.
// Num addresses (varInt) + max allowed addresses.
wantPayload := uint32(1000000)
maxPayload := msg.MaxPayloadLength(pver)
if maxPayload != wantPayload {
t.Errorf("MaxPayloadLength: wrong max payload length for "+
"protocol version %d - got %v, want %v", pver,
maxPayload, wantPayload)
}
// Ensure we get the same block header data back out.
if !reflect.DeepEqual(&msg.Header, bh) {
t.Errorf("NewMsgBlock: wrong block header - got %v, want %v",
spew.Sdump(&msg.Header), spew.Sdump(bh))
}
// Ensure transactions are added properly.
tx := testBlock.Transactions[0].Copy()
msg.AddTransaction(tx)
if !reflect.DeepEqual(msg.Transactions, testBlock.Transactions) {
t.Errorf("AddTransaction: wrong transactions - got %v, want %v",
spew.Sdump(msg.Transactions),
spew.Sdump(testBlock.Transactions))
}
// Ensure transactions are properly cleared.
msg.ClearTransactions()
if len(msg.Transactions) != 0 {
t.Errorf("ClearTransactions: wrong transactions - got %v, want %v",
len(msg.Transactions), 0)
}
// Ensure stake transactions are added properly.
stx := testBlock.STransactions[0].Copy()
msg.AddSTransaction(stx)
if !reflect.DeepEqual(msg.STransactions, testBlock.STransactions) {
t.Errorf("AddSTransaction: wrong transactions - got %v, want %v",
spew.Sdump(msg.STransactions),
spew.Sdump(testBlock.STransactions))
}
// Ensure transactions are properly cleared.
msg.ClearSTransactions()
if len(msg.STransactions) != 0 {
t.Errorf("ClearTransactions: wrong transactions - got %v, want %v",
len(msg.STransactions), 0)
}
return
}
// TestBlockTxShas tests the ability to generate a slice of all transaction
// hashes from a block accurately.
func TestBlockTxShas(t *testing.T) {
// Block 1, transaction 1 hash.
hashStr := "55a25248c04dd8b6599ca2a708413c00d79ae90ce075c54e8a967a647d7e4bea"
wantHash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
return
}
wantShas := []chainhash.Hash{*wantHash}
shas := testBlock.TxShas()
if !reflect.DeepEqual(shas, wantShas) {
t.Errorf("TxShas: wrong transaction hashes - got %v, want %v",
spew.Sdump(shas), spew.Sdump(wantShas))
}
}
// TestBlockSTxShas tests the ability to generate a slice of all stake transaction
// hashes from a block accurately.
func TestBlockSTxShas(t *testing.T) {
// Block 1, transaction 1 hash.
hashStr := "ae208a69f3ee088d0328126e3d9bef7652b108d1904f27b166c5999233a801d4"
wantHash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
return
}
wantShas := []chainhash.Hash{*wantHash}
shas := testBlock.STxShas()
if !reflect.DeepEqual(shas, wantShas) {
t.Errorf("STxShas: wrong transaction hashes - got %v, want %v",
spew.Sdump(shas), spew.Sdump(wantShas))
}
}
// TestBlockSha tests the ability to generate the hash of a block accurately.
func TestBlockSha(t *testing.T) {
// Block 1 hash.
hashStr := "152437dada95368c42b19febc1702939fa9c1ccdb6fd7284e5b7a19d8fe6df7a"
wantHash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
}
// Ensure the hash produced is expected.
blockHash := testBlock.BlockSha()
if !blockHash.IsEqual(wantHash) {
t.Errorf("BlockSha: wrong hash - got %v, want %v",
spew.Sprint(blockHash), spew.Sprint(wantHash))
}
}
// TestBlockWire tests the MsgBlock wire encode and decode for various numbers
// of transaction inputs and outputs and protocol versions.
func TestBlockWire(t *testing.T) {
tests := []struct {
in *wire.MsgBlock // Message to encode
out *wire.MsgBlock // Expected decoded message
buf []byte // Wire encoding
txLocs []wire.TxLoc // Expected transaction locations
sTxLocs []wire.TxLoc // Expected stake transaction locations
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version.
{
&testBlock,
&testBlock,
testBlockBytes,
testBlockTxLocs,
testBlockSTxLocs,
wire.ProtocolVersion,
},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode the message to wire format.
var buf bytes.Buffer
err := test.in.BtcEncode(&buf, test.pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
}
if !bytes.Equal(buf.Bytes(), test.buf) {
t.Errorf("BtcEncode #%d\n got: %s want: %s", i,
spew.Sdump(buf.Bytes()), spew.Sdump(test.buf))
continue
}
// Decode the message from wire format.
var msg wire.MsgBlock
rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue
}
if !reflect.DeepEqual(&msg, test.out) {
t.Errorf("BtcDecode #%d\n got: %s want: %s", i,
spew.Sdump(&msg), spew.Sdump(test.out))
continue
}
}
}
// TestBlockWireErrors performs negative tests against wire encode and decode
// of MsgBlock to confirm error paths work correctly.
func TestBlockWireErrors(t *testing.T) {
// Use protocol version 60002 specifically here instead of the latest
// because the test data is using bytes encoded with that protocol
// version.
pver := uint32(60002)
tests := []struct {
in *wire.MsgBlock // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{ // Force error in version.
{&testBlock, testBlockBytes, pver, 0, io.ErrShortWrite, io.EOF}, // 0
// Force error in prev block hash.
{&testBlock, testBlockBytes, pver, 4, io.ErrShortWrite, io.EOF}, // 1
// Force error in merkle root.
{&testBlock, testBlockBytes, pver, 36, io.ErrShortWrite, io.EOF}, // 2
// Force error in stake root.
{&testBlock, testBlockBytes, pver, 68, io.ErrShortWrite, io.EOF}, // 3
// Force error in vote bits.
{&testBlock, testBlockBytes, pver, 100, io.ErrShortWrite, io.EOF}, // 4
// Force error in finalState.
{&testBlock, testBlockBytes, pver, 102, io.ErrShortWrite, io.EOF}, // 5
// Force error in voters.
{&testBlock, testBlockBytes, pver, 108, io.ErrShortWrite, io.EOF}, // 6
// Force error in freshstake.
{&testBlock, testBlockBytes, pver, 110, io.ErrShortWrite, io.EOF}, // 7
// Force error in revocations.
{&testBlock, testBlockBytes, pver, 111, io.ErrShortWrite, io.EOF}, // 8
// Force error in poolsize.
{&testBlock, testBlockBytes, pver, 112, io.ErrShortWrite, io.EOF}, // 9
// Force error in difficulty bits.
{&testBlock, testBlockBytes, pver, 116, io.ErrShortWrite, io.EOF}, // 10
// Force error in stake difficulty bits.
{&testBlock, testBlockBytes, pver, 120, io.ErrShortWrite, io.EOF}, // 11
// Force error in height.
{&testBlock, testBlockBytes, pver, 128, io.ErrShortWrite, io.EOF}, // 12
// Force error in size.
{&testBlock, testBlockBytes, pver, 132, io.ErrShortWrite, io.EOF}, // 13
// Force error in timestamp.
{&testBlock, testBlockBytes, pver, 136, io.ErrShortWrite, io.EOF}, // 14
// Force error in nonce.
{&testBlock, testBlockBytes, pver, 140, io.ErrShortWrite, io.EOF}, // 15
// Force error in tx count.
{&testBlock, testBlockBytes, pver, 180, io.ErrShortWrite, io.EOF}, // 16
// Force error in tx.
{&testBlock, testBlockBytes, pver, 181, io.ErrShortWrite, io.EOF}, // 17
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver)
if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
continue
}
// Decode from wire format.
var msg wire.MsgBlock
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver)
if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)
continue
}
}
}
// TestBlockSerialize tests MsgBlock serialize and deserialize.
func TestBlockSerialize(t *testing.T) {
tests := []struct {
in *wire.MsgBlock // Message to encode
out *wire.MsgBlock // Expected decoded message
buf []byte // Serialized data
txLocs []wire.TxLoc // Expected transaction locations
sTxLocs []wire.TxLoc // Expected stake transaction locations
}{
{
&testBlock,
&testBlock,
testBlockBytes,
testBlockTxLocs,
testBlockSTxLocs,
},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Serialize the block.
var buf bytes.Buffer
err := test.in.Serialize(&buf)
if err != nil {
t.Errorf("Serialize #%d error %v", i, err)
continue
}
if !bytes.Equal(buf.Bytes(), test.buf) {
t.Errorf("Serialize #%d\n got: %s want: %s", i,
spew.Sdump(buf.Bytes()), spew.Sdump(test.buf))
continue
}
// Deserialize the block.
var block wire.MsgBlock
rbuf := bytes.NewReader(test.buf)
err = block.Deserialize(rbuf)
if err != nil {
t.Errorf("Deserialize #%d error %v", i, err)
continue
}
if !reflect.DeepEqual(&block, test.out) {
t.Errorf("Deserialize #%d\n got: %s want: %s", i,
spew.Sdump(&block), spew.Sdump(test.out))
continue
}
// Deserialize the block while gathering transaction location
// information.
var txLocBlock wire.MsgBlock
br := bytes.NewBuffer(test.buf)
txLocs, sTxLocs, err := txLocBlock.DeserializeTxLoc(br)
if err != nil {
t.Errorf("DeserializeTxLoc #%d error %v", i, err)
continue
}
if !reflect.DeepEqual(&txLocBlock, test.out) {
t.Errorf("DeserializeTxLoc #%d\n got: %s want: %s", i,
spew.Sdump(&txLocBlock), spew.Sdump(test.out))
continue
}
if !reflect.DeepEqual(txLocs, test.txLocs) {
t.Errorf("DeserializeTxLoc #%d\n got: %s want: %s", i,
spew.Sdump(txLocs), spew.Sdump(test.txLocs))
continue
}
if !reflect.DeepEqual(sTxLocs, test.sTxLocs) {
t.Errorf("DeserializeTxLoc, sTxLocs #%d\n got: %s want: %s", i,
spew.Sdump(sTxLocs), spew.Sdump(test.sTxLocs))
continue
}
}
}
// TestBlockSerializeErrors performs negative tests against wire encode and
// decode of MsgBlock to confirm error paths work correctly.
func TestBlockSerializeErrors(t *testing.T) {
tests := []struct {
in *wire.MsgBlock // Value to encode
buf []byte // Serialized data
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
{&testBlock, testBlockBytes, 0, io.ErrShortWrite, io.EOF}, // 0
// Force error in prev block hash.
{&testBlock, testBlockBytes, 4, io.ErrShortWrite, io.EOF}, // 1
// Force error in merkle root.
{&testBlock, testBlockBytes, 36, io.ErrShortWrite, io.EOF}, // 2
// Force error in stake root.
{&testBlock, testBlockBytes, 68, io.ErrShortWrite, io.EOF}, // 3
// Force error in vote bits.
{&testBlock, testBlockBytes, 100, io.ErrShortWrite, io.EOF}, // 4
// Force error in finalState.
{&testBlock, testBlockBytes, 102, io.ErrShortWrite, io.EOF}, // 5
// Force error in voters.
{&testBlock, testBlockBytes, 108, io.ErrShortWrite, io.EOF}, // 8
// Force error in freshstake.
{&testBlock, testBlockBytes, 110, io.ErrShortWrite, io.EOF}, // 9
// Force error in revocations.
{&testBlock, testBlockBytes, 111, io.ErrShortWrite, io.EOF}, // 10
// Force error in poolsize.
{&testBlock, testBlockBytes, 112, io.ErrShortWrite, io.EOF}, // 11
// Force error in difficulty bits.
{&testBlock, testBlockBytes, 116, io.ErrShortWrite, io.EOF}, // 12
// Force error in stake difficulty bits.
{&testBlock, testBlockBytes, 120, io.ErrShortWrite, io.EOF}, // 13
// Force error in height.
{&testBlock, testBlockBytes, 128, io.ErrShortWrite, io.EOF}, // 14
// Force error in size.
{&testBlock, testBlockBytes, 132, io.ErrShortWrite, io.EOF}, // 15
// Force error in timestamp.
{&testBlock, testBlockBytes, 136, io.ErrShortWrite, io.EOF}, // 16
// Force error in nonce.
{&testBlock, testBlockBytes, 140, io.ErrShortWrite, io.EOF}, // 17
// Force error in tx count.
{&testBlock, testBlockBytes, 180, io.ErrShortWrite, io.EOF}, // 18
// Force error in tx.
{&testBlock, testBlockBytes, 181, io.ErrShortWrite, io.EOF}, // 19
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Serialize the block.
w := newFixedWriter(test.max)
err := test.in.Serialize(w)
if err != test.writeErr {
t.Errorf("Serialize #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
continue
}
// Deserialize the block.
var block wire.MsgBlock
r := newFixedReader(test.max, test.buf)
err = block.Deserialize(r)
if err != test.readErr {
t.Errorf("Deserialize #%d wrong error got: %v, want: %v",
i, err, test.readErr)
continue
}
var txLocBlock wire.MsgBlock
br := bytes.NewBuffer(test.buf[0:test.max])
_, _, err = txLocBlock.DeserializeTxLoc(br)
if err != test.readErr {
t.Errorf("DeserializeTxLoc #%d wrong error got: %v, want: %v",
i, err, test.readErr)
continue
}
}
}
// TestBlockOverflowErrors performs tests to ensure deserializing blocks which
// are intentionally crafted to use large values for the number of transactions
// are handled properly. This could otherwise potentially be used as an attack
// vector.
func TestBlockOverflowErrors(t *testing.T) {
// Use protocol version 70001 specifically here instead of the latest
// protocol version because the test data is using bytes encoded with
// that version.
pver := uint32(1)
tests := []struct {
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
err error // Expected error
}{
// Block that claims to have ~uint64(0) transactions.
{
[]byte{
0x01, 0x00, 0x00, 0x00, // Version 1
0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f,
0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, // PrevBlock
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
0xcd, 0xb6, 0x06, 0xe8, 0x57, 0x23, 0x3e, 0x0e, // MerkleRoot
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
0xcd, 0xb6, 0x06, 0xe8, 0x57, 0x23, 0x3e, 0x0e, // StakeRoot
0x00, 0x00, // VoteBits
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // FinalState
0x00, 0x00, // Voters
0x00, // FreshStake
0x00, // Revocations
0x00, 0x00, 0x00, 0x00, // Poolsize
0xff, 0xff, 0x00, 0x1d, // Bits
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // SBits
0x01, 0x00, 0x00, 0x00, // Height
0x01, 0x00, 0x00, 0x00, // Size
0x61, 0xbc, 0x66, 0x49, // Timestamp
0x01, 0xe3, 0x62, 0x99, // Nonce
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ExtraData
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, // TxnCount
}, pver, &wire.MessageError{},
},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Decode from wire format.
var msg wire.MsgBlock
r := bytes.NewReader(test.buf)
err := msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, reflect.TypeOf(test.err))
continue
}
// Deserialize from wire format.
r = bytes.NewReader(test.buf)
err = msg.Deserialize(r)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
t.Errorf("Deserialize #%d wrong error got: %v, want: %v",
i, err, reflect.TypeOf(test.err))
continue
}
// Deserialize with transaction location info from wire format.
br := bytes.NewBuffer(test.buf)
_, _, err = msg.DeserializeTxLoc(br)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
t.Errorf("DeserializeTxLoc #%d wrong error got: %v, "+
"want: %v", i, err, reflect.TypeOf(test.err))
continue
}
}
}
// TestBlockSerializeSize performs tests to ensure the serialize size for
// various blocks is accurate.
func TestBlockSerializeSize(t *testing.T) {
// Block with no transactions.
noTxBlock := wire.NewMsgBlock(&testBlock.Header)
tests := []struct {
in *wire.MsgBlock // Block to encode
size int // Expected serialized size
}{
// Block with no transactions (header + 2x numtx)
{noTxBlock, 182},
// First block in the mainnet block chain.
{&testBlock, len(testBlockBytes)},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
serializedSize := test.in.SerializeSize()
if serializedSize != test.size {
t.Errorf("MsgBlock.SerializeSize: #%d got: %d, want: "+
"%d", i, serializedSize, test.size)
continue
}
}
}
// testBlock is a basic normative block that is used throughout tests.
var testBlock = wire.MsgBlock{
Header: wire.BlockHeader{
Version: 1,
PrevBlock: chainhash.Hash([chainhash.HashSize]byte{ // Make go vet happy.
0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f,
0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
}),
MerkleRoot: chainhash.Hash([chainhash.HashSize]byte{ // Make go vet happy.
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
0xcd, 0xb6, 0x06, 0xe8, 0x57, 0x23, 0x3e, 0x0e,
}),
StakeRoot: chainhash.Hash([chainhash.HashSize]byte{ // Make go vet happy.
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
0xcd, 0xb6, 0x06, 0xe8, 0x57, 0x23, 0x3e, 0x0e,
}),
VoteBits: uint16(0x0000),
FinalState: [6]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
Voters: uint16(0x0000),
FreshStake: uint8(0x00),
Revocations: uint8(0x00),
PoolSize: uint32(0x00000000), // Poolsize
Bits: 0x1d00ffff, // 486604799
SBits: int64(0x0000000000000000),
Height: uint32(1),
Size: uint32(1),
Timestamp: time.Unix(0x4966bc61, 0), // 2009-01-08 20:54:25 -0600 CST
Nonce: 0x9962e301, // 2573394689
ExtraData: [36]byte{},
},
Transactions: []*wire.MsgTx{
{
Version: 1,
TxIn: []*wire.TxIn{
{
PreviousOutPoint: wire.OutPoint{
Hash: chainhash.Hash{},
Index: 0xffffffff,
Tree: dcrutil.TxTreeRegular,
},
Sequence: 0xffffffff,
ValueIn: 0x1616161616161616,
BlockHeight: 0x17171717,
BlockIndex: 0x18181818,
SignatureScript: []byte{
0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf2,
},
},
},
TxOut: []*wire.TxOut{
{
Value: 0x3333333333333333,
Version: 0x9898,
PkScript: []byte{
0x41, // OP_DATA_65
0x04, 0x96, 0xb5, 0x38, 0xe8, 0x53, 0x51, 0x9c,
0x72, 0x6a, 0x2c, 0x91, 0xe6, 0x1e, 0xc1, 0x16,
0x00, 0xae, 0x13, 0x90, 0x81, 0x3a, 0x62, 0x7c,
0x66, 0xfb, 0x8b, 0xe7, 0x94, 0x7b, 0xe6, 0x3c,
0x52, 0xda, 0x75, 0x89, 0x37, 0x95, 0x15, 0xd4,
0xe0, 0xa6, 0x04, 0xf8, 0x14, 0x17, 0x81, 0xe6,
0x22, 0x94, 0x72, 0x11, 0x66, 0xbf, 0x62, 0x1e,
0x73, 0xa8, 0x2c, 0xbf, 0x23, 0x42, 0xc8, 0x58,
0xee, // 65-byte signature
0xac, // OP_CHECKSIG
},
},
},
LockTime: 0x11111111,
Expiry: 0x22222222,
},
},
STransactions: []*wire.MsgTx{
{
Version: 1,
TxIn: []*wire.TxIn{
{
PreviousOutPoint: wire.OutPoint{
Hash: chainhash.Hash{},
Index: 0xffffffff,
Tree: dcrutil.TxTreeStake,
},
Sequence: 0xffffffff,
ValueIn: 0x1313131313131313,
BlockHeight: 0x14141414,
BlockIndex: 0x15151515,
SignatureScript: []byte{
0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf2,
},
},
},
TxOut: []*wire.TxOut{
{
Value: 0x3333333333333333,
Version: 0x1212,
PkScript: []byte{
0x41, // OP_DATA_65
0x04, 0x96, 0xb5, 0x38, 0xe8, 0x53, 0x51, 0x9c,
0x72, 0x6a, 0x2c, 0x91, 0xe6, 0x1e, 0xc1, 0x16,
0x00, 0xae, 0x13, 0x90, 0x81, 0x3a, 0x62, 0x7c,
0x66, 0xfb, 0x8b, 0xe7, 0x94, 0x7b, 0xe6, 0x3c,
0x52, 0xda, 0x75, 0x89, 0x37, 0x95, 0x15, 0xd4,
0xe0, 0xa6, 0x04, 0xf8, 0x14, 0x17, 0x81, 0xe6,
0x22, 0x94, 0x72, 0x11, 0x66, 0xbf, 0x62, 0x1e,
0x73, 0xa8, 0x2c, 0xbf, 0x23, 0x42, 0xc8, 0x58,
0xee, // 65-byte signature
0xac, // OP_CHECKSIG
},
},
},
LockTime: 0x11111111,
Expiry: 0x22222222,
},
},
}
// testBlockBytes is the serialized bytes for the above test block (testBlock).
var testBlockBytes = []byte{
// Begin block header
0x01, 0x00, 0x00, 0x00, // Version 1 [0]
0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f,
0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, // PrevBlock [4]
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
0xcd, 0xb6, 0x06, 0xe8, 0x57, 0x23, 0x3e, 0x0e, // MerkleRoot [36]
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
0xcd, 0xb6, 0x06, 0xe8, 0x57, 0x23, 0x3e, 0x0e, // StakeRoot [68]
0x00, 0x00, // VoteBits [100]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // FinalState [102]
0x00, 0x00, // Voters [108]
0x00, // FreshStake [110]
0x00, // Revocations [111]
0x00, 0x00, 0x00, 0x00, // Poolsize [112]
0xff, 0xff, 0x00, 0x1d, // Bits [116]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // SBits [120]
0x01, 0x00, 0x00, 0x00, // Height [128]
0x01, 0x00, 0x00, 0x00, // Size [132]
0x61, 0xbc, 0x66, 0x49, // Timestamp [136]
0x01, 0xe3, 0x62, 0x99, // Nonce [140]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ExtraData [144]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
// Announce number of txs
0x01, // TxnCount [180]
// Begin bogus normal txs
0x01, 0x00, 0x00, 0x00, // Version [181]
0x01, // Varint for number of transaction inputs [185]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Previous output hash [186]
0xff, 0xff, 0xff, 0xff, // Prevous output index [218]
0x00, // Previous output tree [222]
0xff, 0xff, 0xff, 0xff, // Sequence [223]
0x01, // Varint for number of transaction outputs [227]
0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, // Transaction amount [228]
0x98, 0x98, // Script version
0x43, // Varint for length of pk script
0x41, // OP_DATA_65
0x04, 0x96, 0xb5, 0x38, 0xe8, 0x53, 0x51, 0x9c,
0x72, 0x6a, 0x2c, 0x91, 0xe6, 0x1e, 0xc1, 0x16,
0x00, 0xae, 0x13, 0x90, 0x81, 0x3a, 0x62, 0x7c,
0x66, 0xfb, 0x8b, 0xe7, 0x94, 0x7b, 0xe6, 0x3c,
0x52, 0xda, 0x75, 0x89, 0x37, 0x95, 0x15, 0xd4,
0xe0, 0xa6, 0x04, 0xf8, 0x14, 0x17, 0x81, 0xe6,
0x22, 0x94, 0x72, 0x11, 0x66, 0xbf, 0x62, 0x1e,
0x73, 0xa8, 0x2c, 0xbf, 0x23, 0x42, 0xc8, 0x58,
0xee, // 65-byte signature
0xac, // OP_CHECKSIG
0x11, 0x11, 0x11, 0x11, // Lock time
0x22, 0x22, 0x22, 0x22, // Expiry
0x01, // Varint for number of signatures
0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, // ValueIn
0x17, 0x17, 0x17, 0x17, // BlockHeight
0x18, 0x18, 0x18, 0x18, // BlockIndex
0x07, // SigScript length
0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf2, // Signature script (coinbase)
// Announce number of stake txs
0x01, // TxnCount for stake tx
// Begin bogus stake txs
0x01, 0x00, 0x00, 0x00, // Version
0x01, // Varint for number of transaction inputs
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Previous output hash
0xff, 0xff, 0xff, 0xff, // Prevous output index
0x01, // Previous output tree
0xff, 0xff, 0xff, 0xff, // Sequence
0x01, // Varint for number of transaction outputs
0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, // Transaction amount
0x12, 0x12, // Script version
0x43, // Varint for length of pk script
0x41, // OP_DATA_65
0x04, 0x96, 0xb5, 0x38, 0xe8, 0x53, 0x51, 0x9c,
0x72, 0x6a, 0x2c, 0x91, 0xe6, 0x1e, 0xc1, 0x16,
0x00, 0xae, 0x13, 0x90, 0x81, 0x3a, 0x62, 0x7c,
0x66, 0xfb, 0x8b, 0xe7, 0x94, 0x7b, 0xe6, 0x3c,
0x52, 0xda, 0x75, 0x89, 0x37, 0x95, 0x15, 0xd4,
0xe0, 0xa6, 0x04, 0xf8, 0x14, 0x17, 0x81, 0xe6,
0x22, 0x94, 0x72, 0x11, 0x66, 0xbf, 0x62, 0x1e,
0x73, 0xa8, 0x2c, 0xbf, 0x23, 0x42, 0xc8, 0x58,
0xee, // 65-byte signature
0xac, // OP_CHECKSIG
0x11, 0x11, 0x11, 0x11, // Lock time
0x22, 0x22, 0x22, 0x22, // Expiry
0x01, // Varint for number of signatures
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, // ValueIn
0x14, 0x14, 0x14, 0x14, // BlockHeight
0x15, 0x15, 0x15, 0x15, // BlockIndex
0x07, // SigScript length
0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf2, // Signature script (coinbase)
}
// Transaction location information for the test block transactions.
var testBlockTxLocs = []wire.TxLoc{
{TxStart: 181, TxLen: 158},
}
// Transaction location information for the test block stake transactions.
var testBlockSTxLocs = []wire.TxLoc{
{TxStart: 340, TxLen: 158},
}
| Java |
describe('dJSON', function () {
'use strict';
var chai = require('chai');
var expect = chai.expect;
var dJSON = require('../lib/dJSON');
var path = 'x.y["q.{r}"].z';
var obj;
beforeEach(function () {
obj = {
x: {
y: {
'q.{r}': {
z: 635
},
q: {
r: {
z: 1
}
}
}
},
'x-y': 5,
falsy: false
};
});
it('gets a value from an object with a path containing properties which contain a period', function () {
expect(dJSON.get(obj, path)).to.equal(635);
expect(dJSON.get(obj, 'x.y.q.r.z')).to.equal(1);
});
it('sets a value from an object with a path containing properties which contain a period', function () {
dJSON.set(obj, path, 17771);
expect(dJSON.get(obj, path)).to.equal(17771);
expect(dJSON.get(obj, 'x.y.q.r.z')).to.equal(1);
});
it('will return undefined when requesting a property with a dash directly', function () {
expect(dJSON.get(obj, 'x-y')).to.be.undefined;
});
it('will return the proper value when requesting a property with a dash by square bracket notation', function () {
expect(dJSON.get(obj, '["x-y"]')).to.equal(5);
});
it('returns a value that is falsy', function () {
expect(dJSON.get(obj, 'falsy')).to.equal(false);
});
it('sets a value that is falsy', function () {
dJSON.set(obj, 'new', false);
expect(dJSON.get(obj, 'new')).to.equal(false);
});
it('uses an empty object as default for the value in the set method', function () {
var newObj = {};
dJSON.set(newObj, 'foo.bar.lorem');
expect(newObj).to.deep.equal({
foo: {
bar: {
lorem: {}
}
}
});
});
it('does not create an object when a path exists as empty string', function () {
var newObj = {
nestedObject: {
anArray: [
'i have a value',
''
]
}
};
var newPath = 'nestedObject.anArray[1]';
dJSON.set(newObj, newPath, 17771);
expect(newObj).to.deep.equal({
nestedObject: {
anArray: [
'i have a value',
17771
]
}
});
});
it('creates an object from a path with a left curly brace', function () {
var newObj = {};
dJSON.set(newObj, path.replace('}', ''), 'foo');
expect(newObj).to.be.deep.equal({
x: {
y: {
'q.{r': {
z: 'foo'
}
}
}
});
});
it('creates an object from a path with a right curly brace', function () {
var newObj = {};
dJSON.set(newObj, path.replace('{', ''), 'foo');
expect(newObj).to.be.deep.equal({
x: {
y: {
'q.r}': {
z: 'foo'
}
}
}
});
});
it('creates an object from a path with curly braces', function () {
var newObj = {};
dJSON.set(newObj, path, 'foo');
expect(newObj).to.be.deep.equal({
x: {
y: {
'q.{r}': {
z: 'foo'
}
}
}
});
});
it('creates an object from a path without curly braces', function () {
var newObj = {};
dJSON.set(newObj, path.replace('{', '').replace('}', ''), 'foo');
expect(newObj).to.be.deep.equal({
x: {
y: {
'q.r': {
z: 'foo'
}
}
}
});
});
});
| Java |
/*
* 94 shifted lines of 72 ASCII characters.
*/
static const char *characters[] = {
"!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefgh",
"\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghi",
"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghij",
"$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijk",
"%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijkl",
"&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklm",
"'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmn",
"()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmno",
")*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnop",
"*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopq",
"+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqr",
",-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrs",
"-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrst",
"./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstu",
"/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuv",
"0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvw",
"123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwx",
"23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxy",
"3456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz",
"456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{",
"56789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|",
"6789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}",
"789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",
"89:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!",
"9:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"",
":;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#",
";<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$",
"<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%",
"=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&",
">?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'",
"?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'(",
"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*",
"BCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+",
"CDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,",
"DEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-",
"EFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-.",
"FGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./",
"GHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0",
"HIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./01",
"IJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./012",
"JKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123",
"KLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./01234",
"LMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./012345",
"MNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456",
"NOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./01234567",
"OPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./012345678",
"PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789",
"QRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:",
"RSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;",
"STUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<",
"TUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=",
"UVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>",
"VWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?",
"WXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@",
"XYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@A",
"YZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@AB",
"Z[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABC",
"[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCD",
"\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDE",
"]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEF",
"^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFG",
"_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGH",
"`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHI",
"abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJ",
"bcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJK",
"cdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKL",
"defghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLM",
"efghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMN",
"fghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO",
"ghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOP",
"hijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQ",
"ijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQR",
"jklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRS",
"klmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRST",
"lmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU",
"mnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUV",
"nopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVW",
"opqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWX",
"pqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXY",
"qrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"rstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[",
"stuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\",
"tuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]",
"uvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^",
"vwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_",
"wxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`",
"xyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`a",
"yz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`ab",
"z{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abc",
"{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcd",
"|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcde",
"}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdef",
"~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefg"
};
| Java |
#include <stdarg.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/endian.h>
#include <sysexits.h>
#include <mpg123.h>
#include "audio.h"
#include "mp3.h"
struct mp3 {
mpg123_handle *h;
int fd;
int first;
int rate;
int channels;
int endian;
int octets;
int sign;
};
struct mp3 *
mp3_open(const char *file) {
struct mp3 *m = NULL;
char magic[3];
long rate;
int chan;
int enc;
if ((m = malloc(sizeof(struct mp3))) == NULL)
goto err;
m->h = NULL;
if ((m->fd = open(file, O_RDONLY)) < 0)
goto err;
if (read(m->fd, magic, 3) != 3)
goto err;
if (strncmp(magic, "\xFF\xFB", 2) != 0 &&
strncmp(magic, "ID3", 3) != 0)
goto err;
if (lseek(m->fd, -3, SEEK_CUR) == -1)
goto err;
if (mpg123_init() != MPG123_OK)
return NULL;
if ((m->h = mpg123_new(NULL, NULL)) == NULL ||
mpg123_param(m->h, MPG123_ADD_FLAGS, MPG123_QUIET, 0)
!= MPG123_OK || mpg123_open_fd(m->h, m->fd) != MPG123_OK)
goto err;
if (mpg123_getformat(m->h, &rate, &chan, &enc)
!= MPG123_OK || rate > (int)(~0U >> 1)) {
mpg123_close(m->h);
goto err;
}
m->first = 1;
/* Does mpg123 always output in host byte-order? */
m->endian = BYTE_ORDER == LITTLE_ENDIAN;
m->rate = rate;
m->sign = !!(enc & MPG123_ENC_SIGNED);
if (chan & MPG123_STEREO)
m->channels = 2;
else /* MPG123_MONO */
m->channels = 1;
if (enc & MPG123_ENC_FLOAT) {
mpg123_close(m->h);
goto err;
}
if (enc & MPG123_ENC_32)
m->octets = 4;
else if (enc & MPG123_ENC_24)
m->octets = 3;
else if (enc & MPG123_ENC_16)
m->octets = 2;
else /* MPG123_ENC_8 */
m->octets = 1;
return m;
err:
if (m != NULL) {
if (m->h != NULL)
mpg123_delete(m->h);
if (m->fd >= 0)
close(m->fd);
free(m);
}
mpg123_exit();
return NULL;
}
int
mp3_copy(struct mp3 *m, void *buf, size_t size, struct audio *out) {
size_t r;
if (m == NULL || buf == NULL || size == 0 || out == NULL)
return EX_USAGE;
if (m->first) { /* setup audio output */
m->first = 0;
a_setrate(out, m->rate);
a_setchan(out, m->channels);
a_setend(out, m->endian);
a_setbits(out, m->octets << 3);
a_setsign(out, m->sign);
}
if (mpg123_read(m->h, buf, size, &r) != MPG123_OK)
return EX_SOFTWARE;
if (r == 0)
return 1;
if (a_write(out, buf, r) != r && errno != EINTR
&& errno != EAGAIN)
return EX_IOERR;
return EX_OK;
}
void
mp3_close(struct mp3 *m) {
if (m == NULL)
return;
if (m->fd >= 0)
close(m->fd);
if (m->h != NULL) {
mpg123_close(m->h);
mpg123_delete(m->h);
}
mpg123_exit();
free(m);
}
| Java |
package main
import (
"testing"
)
func TestParseHdbSignatureRow(t *testing.T) {
signature := new(signature)
sample := "e11c2aff804ca144a3e49c42d6ac5783:1006:Exploit.CVE_2012_0779"
sig := parseHdbSignatureRow(sample, signature)
if sig.Size != 1006 {
t.Fatal("Error parsing HDB or HSB signature length")
}
if signature.SigHash != "e11c2aff804ca144a3e49c42d6ac5783" {
t.Fatal("Error parsing HDB or HSB signature hash")
}
}
| Java |
/*
* Copyright 2005-2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/**
* The Whirlpool hashing function.
*
* See
* P.S.L.M. Barreto, V. Rijmen,
* ``The Whirlpool hashing function,''
* NESSIE submission, 2000 (tweaked version, 2001),
* <https://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/whirlpool.zip>
*
* Based on "@version 3.0 (2003.03.12)" by Paulo S.L.M. Barreto and
* Vincent Rijmen. Lookup "reference implementations" on
* <http://planeta.terra.com.br/informatica/paulobarreto/>
*
* =============================================================================
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "wp_locl.h"
#include <string.h>
typedef unsigned char u8;
#if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32)
typedef unsigned __int64 u64;
#elif defined(__arch64__)
typedef unsigned long u64;
#else
typedef unsigned long long u64;
#endif
#define ROUNDS 10
#define STRICT_ALIGNMENT
#if !defined(PEDANTIC) && (defined(__i386) || defined(__i386__) || \
defined(__x86_64) || defined(__x86_64__) || \
defined(_M_IX86) || defined(_M_AMD64) || \
defined(_M_X64))
/*
* Well, formally there're couple of other architectures, which permit
* unaligned loads, specifically those not crossing cache lines, IA-64 and
* PowerPC...
*/
# undef STRICT_ALIGNMENT
#endif
#undef SMALL_REGISTER_BANK
#if defined(__i386) || defined(__i386__) || defined(_M_IX86)
# define SMALL_REGISTER_BANK
# if defined(WHIRLPOOL_ASM)
# ifndef OPENSSL_SMALL_FOOTPRINT
/*
* it appears that for elder non-MMX
* CPUs this is actually faster!
*/
# define OPENSSL_SMALL_FOOTPRINT
# endif
# define GO_FOR_MMX(ctx,inp,num) do { \
extern unsigned long OPENSSL_ia32cap_P[]; \
void whirlpool_block_mmx(void *,const void *,size_t); \
if (!(OPENSSL_ia32cap_P[0] & (1<<23))) break; \
whirlpool_block_mmx(ctx->H.c,inp,num); return; \
} while (0)
# endif
#endif
#undef ROTATE
#ifndef PEDANTIC
# if defined(_MSC_VER)
# if defined(_WIN64) /* applies to both IA-64 and AMD64 */
# include <stdlib.h>
# pragma intrinsic(_rotl64)
# define ROTATE(a,n) _rotl64((a),n)
# endif
# elif defined(__GNUC__) && __GNUC__>=2
# if defined(__x86_64) || defined(__x86_64__)
# if defined(L_ENDIAN)
# define ROTATE(a,n) ({ u64 ret; asm ("rolq %1,%0" \
: "=r"(ret) : "J"(n),"0"(a) : "cc"); ret; })
# elif defined(B_ENDIAN)
/*
* Most will argue that x86_64 is always little-endian. Well, yes, but
* then we have stratus.com who has modified gcc to "emulate"
* big-endian on x86. Is there evidence that they [or somebody else]
* won't do same for x86_64? Naturally no. And this line is waiting
* ready for that brave soul:-)
*/
# define ROTATE(a,n) ({ u64 ret; asm ("rorq %1,%0" \
: "=r"(ret) : "J"(n),"0"(a) : "cc"); ret; })
# endif
# elif defined(__ia64) || defined(__ia64__)
# if defined(L_ENDIAN)
# define ROTATE(a,n) ({ u64 ret; asm ("shrp %0=%1,%1,%2" \
: "=r"(ret) : "r"(a),"M"(64-(n))); ret; })
# elif defined(B_ENDIAN)
# define ROTATE(a,n) ({ u64 ret; asm ("shrp %0=%1,%1,%2" \
: "=r"(ret) : "r"(a),"M"(n)); ret; })
# endif
# endif
# endif
#endif
#if defined(OPENSSL_SMALL_FOOTPRINT)
# if !defined(ROTATE)
# if defined(L_ENDIAN) /* little-endians have to rotate left */
# define ROTATE(i,n) ((i)<<(n) ^ (i)>>(64-n))
# elif defined(B_ENDIAN) /* big-endians have to rotate right */
# define ROTATE(i,n) ((i)>>(n) ^ (i)<<(64-n))
# endif
# endif
# if defined(ROTATE) && !defined(STRICT_ALIGNMENT)
# define STRICT_ALIGNMENT /* ensure smallest table size */
# endif
#endif
/*
* Table size depends on STRICT_ALIGNMENT and whether or not endian-
* specific ROTATE macro is defined. If STRICT_ALIGNMENT is not
* defined, which is normally the case on x86[_64] CPUs, the table is
* 4KB large unconditionally. Otherwise if ROTATE is defined, the
* table is 2KB large, and otherwise - 16KB. 2KB table requires a
* whole bunch of additional rotations, but I'm willing to "trade,"
* because 16KB table certainly trashes L1 cache. I wish all CPUs
* could handle unaligned load as 4KB table doesn't trash the cache,
* nor does it require additional rotations.
*/
/*
* Note that every Cn macro expands as two loads: one byte load and
* one quadword load. One can argue that that many single-byte loads
* is too excessive, as one could load a quadword and "milk" it for
* eight 8-bit values instead. Well, yes, but in order to do so *and*
* avoid excessive loads you have to accommodate a handful of 64-bit
* values in the register bank and issue a bunch of shifts and mask.
* It's a tradeoff: loads vs. shift and mask in big register bank[!].
* On most CPUs eight single-byte loads are faster and I let other
* ones to depend on smart compiler to fold byte loads if beneficial.
* Hand-coded assembler would be another alternative:-)
*/
#ifdef STRICT_ALIGNMENT
# if defined(ROTATE)
# define N 1
# define LL(c0,c1,c2,c3,c4,c5,c6,c7) c0,c1,c2,c3,c4,c5,c6,c7
# define C0(K,i) (Cx.q[K.c[(i)*8+0]])
# define C1(K,i) ROTATE(Cx.q[K.c[(i)*8+1]],8)
# define C2(K,i) ROTATE(Cx.q[K.c[(i)*8+2]],16)
# define C3(K,i) ROTATE(Cx.q[K.c[(i)*8+3]],24)
# define C4(K,i) ROTATE(Cx.q[K.c[(i)*8+4]],32)
# define C5(K,i) ROTATE(Cx.q[K.c[(i)*8+5]],40)
# define C6(K,i) ROTATE(Cx.q[K.c[(i)*8+6]],48)
# define C7(K,i) ROTATE(Cx.q[K.c[(i)*8+7]],56)
# else
# define N 8
# define LL(c0,c1,c2,c3,c4,c5,c6,c7) c0,c1,c2,c3,c4,c5,c6,c7, \
c7,c0,c1,c2,c3,c4,c5,c6, \
c6,c7,c0,c1,c2,c3,c4,c5, \
c5,c6,c7,c0,c1,c2,c3,c4, \
c4,c5,c6,c7,c0,c1,c2,c3, \
c3,c4,c5,c6,c7,c0,c1,c2, \
c2,c3,c4,c5,c6,c7,c0,c1, \
c1,c2,c3,c4,c5,c6,c7,c0
# define C0(K,i) (Cx.q[0+8*K.c[(i)*8+0]])
# define C1(K,i) (Cx.q[1+8*K.c[(i)*8+1]])
# define C2(K,i) (Cx.q[2+8*K.c[(i)*8+2]])
# define C3(K,i) (Cx.q[3+8*K.c[(i)*8+3]])
# define C4(K,i) (Cx.q[4+8*K.c[(i)*8+4]])
# define C5(K,i) (Cx.q[5+8*K.c[(i)*8+5]])
# define C6(K,i) (Cx.q[6+8*K.c[(i)*8+6]])
# define C7(K,i) (Cx.q[7+8*K.c[(i)*8+7]])
# endif
#else
# define N 2
# define LL(c0,c1,c2,c3,c4,c5,c6,c7) c0,c1,c2,c3,c4,c5,c6,c7, \
c0,c1,c2,c3,c4,c5,c6,c7
# define C0(K,i) (((u64*)(Cx.c+0))[2*K.c[(i)*8+0]])
# define C1(K,i) (((u64*)(Cx.c+7))[2*K.c[(i)*8+1]])
# define C2(K,i) (((u64*)(Cx.c+6))[2*K.c[(i)*8+2]])
# define C3(K,i) (((u64*)(Cx.c+5))[2*K.c[(i)*8+3]])
# define C4(K,i) (((u64*)(Cx.c+4))[2*K.c[(i)*8+4]])
# define C5(K,i) (((u64*)(Cx.c+3))[2*K.c[(i)*8+5]])
# define C6(K,i) (((u64*)(Cx.c+2))[2*K.c[(i)*8+6]])
# define C7(K,i) (((u64*)(Cx.c+1))[2*K.c[(i)*8+7]])
#endif
static const
union {
u8 c[(256 * N + ROUNDS) * sizeof(u64)];
u64 q[(256 * N + ROUNDS)];
} Cx = {
{
/* Note endian-neutral representation:-) */
LL(0x18, 0x18, 0x60, 0x18, 0xc0, 0x78, 0x30, 0xd8),
LL(0x23, 0x23, 0x8c, 0x23, 0x05, 0xaf, 0x46, 0x26),
LL(0xc6, 0xc6, 0x3f, 0xc6, 0x7e, 0xf9, 0x91, 0xb8),
LL(0xe8, 0xe8, 0x87, 0xe8, 0x13, 0x6f, 0xcd, 0xfb),
LL(0x87, 0x87, 0x26, 0x87, 0x4c, 0xa1, 0x13, 0xcb),
LL(0xb8, 0xb8, 0xda, 0xb8, 0xa9, 0x62, 0x6d, 0x11),
LL(0x01, 0x01, 0x04, 0x01, 0x08, 0x05, 0x02, 0x09),
LL(0x4f, 0x4f, 0x21, 0x4f, 0x42, 0x6e, 0x9e, 0x0d),
LL(0x36, 0x36, 0xd8, 0x36, 0xad, 0xee, 0x6c, 0x9b),
LL(0xa6, 0xa6, 0xa2, 0xa6, 0x59, 0x04, 0x51, 0xff),
LL(0xd2, 0xd2, 0x6f, 0xd2, 0xde, 0xbd, 0xb9, 0x0c),
LL(0xf5, 0xf5, 0xf3, 0xf5, 0xfb, 0x06, 0xf7, 0x0e),
LL(0x79, 0x79, 0xf9, 0x79, 0xef, 0x80, 0xf2, 0x96),
LL(0x6f, 0x6f, 0xa1, 0x6f, 0x5f, 0xce, 0xde, 0x30),
LL(0x91, 0x91, 0x7e, 0x91, 0xfc, 0xef, 0x3f, 0x6d),
LL(0x52, 0x52, 0x55, 0x52, 0xaa, 0x07, 0xa4, 0xf8),
LL(0x60, 0x60, 0x9d, 0x60, 0x27, 0xfd, 0xc0, 0x47),
LL(0xbc, 0xbc, 0xca, 0xbc, 0x89, 0x76, 0x65, 0x35),
LL(0x9b, 0x9b, 0x56, 0x9b, 0xac, 0xcd, 0x2b, 0x37),
LL(0x8e, 0x8e, 0x02, 0x8e, 0x04, 0x8c, 0x01, 0x8a),
LL(0xa3, 0xa3, 0xb6, 0xa3, 0x71, 0x15, 0x5b, 0xd2),
LL(0x0c, 0x0c, 0x30, 0x0c, 0x60, 0x3c, 0x18, 0x6c),
LL(0x7b, 0x7b, 0xf1, 0x7b, 0xff, 0x8a, 0xf6, 0x84),
LL(0x35, 0x35, 0xd4, 0x35, 0xb5, 0xe1, 0x6a, 0x80),
LL(0x1d, 0x1d, 0x74, 0x1d, 0xe8, 0x69, 0x3a, 0xf5),
LL(0xe0, 0xe0, 0xa7, 0xe0, 0x53, 0x47, 0xdd, 0xb3),
LL(0xd7, 0xd7, 0x7b, 0xd7, 0xf6, 0xac, 0xb3, 0x21),
LL(0xc2, 0xc2, 0x2f, 0xc2, 0x5e, 0xed, 0x99, 0x9c),
LL(0x2e, 0x2e, 0xb8, 0x2e, 0x6d, 0x96, 0x5c, 0x43),
LL(0x4b, 0x4b, 0x31, 0x4b, 0x62, 0x7a, 0x96, 0x29),
LL(0xfe, 0xfe, 0xdf, 0xfe, 0xa3, 0x21, 0xe1, 0x5d),
LL(0x57, 0x57, 0x41, 0x57, 0x82, 0x16, 0xae, 0xd5),
LL(0x15, 0x15, 0x54, 0x15, 0xa8, 0x41, 0x2a, 0xbd),
LL(0x77, 0x77, 0xc1, 0x77, 0x9f, 0xb6, 0xee, 0xe8),
LL(0x37, 0x37, 0xdc, 0x37, 0xa5, 0xeb, 0x6e, 0x92),
LL(0xe5, 0xe5, 0xb3, 0xe5, 0x7b, 0x56, 0xd7, 0x9e),
LL(0x9f, 0x9f, 0x46, 0x9f, 0x8c, 0xd9, 0x23, 0x13),
LL(0xf0, 0xf0, 0xe7, 0xf0, 0xd3, 0x17, 0xfd, 0x23),
LL(0x4a, 0x4a, 0x35, 0x4a, 0x6a, 0x7f, 0x94, 0x20),
LL(0xda, 0xda, 0x4f, 0xda, 0x9e, 0x95, 0xa9, 0x44),
LL(0x58, 0x58, 0x7d, 0x58, 0xfa, 0x25, 0xb0, 0xa2),
LL(0xc9, 0xc9, 0x03, 0xc9, 0x06, 0xca, 0x8f, 0xcf),
LL(0x29, 0x29, 0xa4, 0x29, 0x55, 0x8d, 0x52, 0x7c),
LL(0x0a, 0x0a, 0x28, 0x0a, 0x50, 0x22, 0x14, 0x5a),
LL(0xb1, 0xb1, 0xfe, 0xb1, 0xe1, 0x4f, 0x7f, 0x50),
LL(0xa0, 0xa0, 0xba, 0xa0, 0x69, 0x1a, 0x5d, 0xc9),
LL(0x6b, 0x6b, 0xb1, 0x6b, 0x7f, 0xda, 0xd6, 0x14),
LL(0x85, 0x85, 0x2e, 0x85, 0x5c, 0xab, 0x17, 0xd9),
LL(0xbd, 0xbd, 0xce, 0xbd, 0x81, 0x73, 0x67, 0x3c),
LL(0x5d, 0x5d, 0x69, 0x5d, 0xd2, 0x34, 0xba, 0x8f),
LL(0x10, 0x10, 0x40, 0x10, 0x80, 0x50, 0x20, 0x90),
LL(0xf4, 0xf4, 0xf7, 0xf4, 0xf3, 0x03, 0xf5, 0x07),
LL(0xcb, 0xcb, 0x0b, 0xcb, 0x16, 0xc0, 0x8b, 0xdd),
LL(0x3e, 0x3e, 0xf8, 0x3e, 0xed, 0xc6, 0x7c, 0xd3),
LL(0x05, 0x05, 0x14, 0x05, 0x28, 0x11, 0x0a, 0x2d),
LL(0x67, 0x67, 0x81, 0x67, 0x1f, 0xe6, 0xce, 0x78),
LL(0xe4, 0xe4, 0xb7, 0xe4, 0x73, 0x53, 0xd5, 0x97),
LL(0x27, 0x27, 0x9c, 0x27, 0x25, 0xbb, 0x4e, 0x02),
LL(0x41, 0x41, 0x19, 0x41, 0x32, 0x58, 0x82, 0x73),
LL(0x8b, 0x8b, 0x16, 0x8b, 0x2c, 0x9d, 0x0b, 0xa7),
LL(0xa7, 0xa7, 0xa6, 0xa7, 0x51, 0x01, 0x53, 0xf6),
LL(0x7d, 0x7d, 0xe9, 0x7d, 0xcf, 0x94, 0xfa, 0xb2),
LL(0x95, 0x95, 0x6e, 0x95, 0xdc, 0xfb, 0x37, 0x49),
LL(0xd8, 0xd8, 0x47, 0xd8, 0x8e, 0x9f, 0xad, 0x56),
LL(0xfb, 0xfb, 0xcb, 0xfb, 0x8b, 0x30, 0xeb, 0x70),
LL(0xee, 0xee, 0x9f, 0xee, 0x23, 0x71, 0xc1, 0xcd),
LL(0x7c, 0x7c, 0xed, 0x7c, 0xc7, 0x91, 0xf8, 0xbb),
LL(0x66, 0x66, 0x85, 0x66, 0x17, 0xe3, 0xcc, 0x71),
LL(0xdd, 0xdd, 0x53, 0xdd, 0xa6, 0x8e, 0xa7, 0x7b),
LL(0x17, 0x17, 0x5c, 0x17, 0xb8, 0x4b, 0x2e, 0xaf),
LL(0x47, 0x47, 0x01, 0x47, 0x02, 0x46, 0x8e, 0x45),
LL(0x9e, 0x9e, 0x42, 0x9e, 0x84, 0xdc, 0x21, 0x1a),
LL(0xca, 0xca, 0x0f, 0xca, 0x1e, 0xc5, 0x89, 0xd4),
LL(0x2d, 0x2d, 0xb4, 0x2d, 0x75, 0x99, 0x5a, 0x58),
LL(0xbf, 0xbf, 0xc6, 0xbf, 0x91, 0x79, 0x63, 0x2e),
LL(0x07, 0x07, 0x1c, 0x07, 0x38, 0x1b, 0x0e, 0x3f),
LL(0xad, 0xad, 0x8e, 0xad, 0x01, 0x23, 0x47, 0xac),
LL(0x5a, 0x5a, 0x75, 0x5a, 0xea, 0x2f, 0xb4, 0xb0),
LL(0x83, 0x83, 0x36, 0x83, 0x6c, 0xb5, 0x1b, 0xef),
LL(0x33, 0x33, 0xcc, 0x33, 0x85, 0xff, 0x66, 0xb6),
LL(0x63, 0x63, 0x91, 0x63, 0x3f, 0xf2, 0xc6, 0x5c),
LL(0x02, 0x02, 0x08, 0x02, 0x10, 0x0a, 0x04, 0x12),
LL(0xaa, 0xaa, 0x92, 0xaa, 0x39, 0x38, 0x49, 0x93),
LL(0x71, 0x71, 0xd9, 0x71, 0xaf, 0xa8, 0xe2, 0xde),
LL(0xc8, 0xc8, 0x07, 0xc8, 0x0e, 0xcf, 0x8d, 0xc6),
LL(0x19, 0x19, 0x64, 0x19, 0xc8, 0x7d, 0x32, 0xd1),
LL(0x49, 0x49, 0x39, 0x49, 0x72, 0x70, 0x92, 0x3b),
LL(0xd9, 0xd9, 0x43, 0xd9, 0x86, 0x9a, 0xaf, 0x5f),
LL(0xf2, 0xf2, 0xef, 0xf2, 0xc3, 0x1d, 0xf9, 0x31),
LL(0xe3, 0xe3, 0xab, 0xe3, 0x4b, 0x48, 0xdb, 0xa8),
LL(0x5b, 0x5b, 0x71, 0x5b, 0xe2, 0x2a, 0xb6, 0xb9),
LL(0x88, 0x88, 0x1a, 0x88, 0x34, 0x92, 0x0d, 0xbc),
LL(0x9a, 0x9a, 0x52, 0x9a, 0xa4, 0xc8, 0x29, 0x3e),
LL(0x26, 0x26, 0x98, 0x26, 0x2d, 0xbe, 0x4c, 0x0b),
LL(0x32, 0x32, 0xc8, 0x32, 0x8d, 0xfa, 0x64, 0xbf),
LL(0xb0, 0xb0, 0xfa, 0xb0, 0xe9, 0x4a, 0x7d, 0x59),
LL(0xe9, 0xe9, 0x83, 0xe9, 0x1b, 0x6a, 0xcf, 0xf2),
LL(0x0f, 0x0f, 0x3c, 0x0f, 0x78, 0x33, 0x1e, 0x77),
LL(0xd5, 0xd5, 0x73, 0xd5, 0xe6, 0xa6, 0xb7, 0x33),
LL(0x80, 0x80, 0x3a, 0x80, 0x74, 0xba, 0x1d, 0xf4),
LL(0xbe, 0xbe, 0xc2, 0xbe, 0x99, 0x7c, 0x61, 0x27),
LL(0xcd, 0xcd, 0x13, 0xcd, 0x26, 0xde, 0x87, 0xeb),
LL(0x34, 0x34, 0xd0, 0x34, 0xbd, 0xe4, 0x68, 0x89),
LL(0x48, 0x48, 0x3d, 0x48, 0x7a, 0x75, 0x90, 0x32),
LL(0xff, 0xff, 0xdb, 0xff, 0xab, 0x24, 0xe3, 0x54),
LL(0x7a, 0x7a, 0xf5, 0x7a, 0xf7, 0x8f, 0xf4, 0x8d),
LL(0x90, 0x90, 0x7a, 0x90, 0xf4, 0xea, 0x3d, 0x64),
LL(0x5f, 0x5f, 0x61, 0x5f, 0xc2, 0x3e, 0xbe, 0x9d),
LL(0x20, 0x20, 0x80, 0x20, 0x1d, 0xa0, 0x40, 0x3d),
LL(0x68, 0x68, 0xbd, 0x68, 0x67, 0xd5, 0xd0, 0x0f),
LL(0x1a, 0x1a, 0x68, 0x1a, 0xd0, 0x72, 0x34, 0xca),
LL(0xae, 0xae, 0x82, 0xae, 0x19, 0x2c, 0x41, 0xb7),
LL(0xb4, 0xb4, 0xea, 0xb4, 0xc9, 0x5e, 0x75, 0x7d),
LL(0x54, 0x54, 0x4d, 0x54, 0x9a, 0x19, 0xa8, 0xce),
LL(0x93, 0x93, 0x76, 0x93, 0xec, 0xe5, 0x3b, 0x7f),
LL(0x22, 0x22, 0x88, 0x22, 0x0d, 0xaa, 0x44, 0x2f),
LL(0x64, 0x64, 0x8d, 0x64, 0x07, 0xe9, 0xc8, 0x63),
LL(0xf1, 0xf1, 0xe3, 0xf1, 0xdb, 0x12, 0xff, 0x2a),
LL(0x73, 0x73, 0xd1, 0x73, 0xbf, 0xa2, 0xe6, 0xcc),
LL(0x12, 0x12, 0x48, 0x12, 0x90, 0x5a, 0x24, 0x82),
LL(0x40, 0x40, 0x1d, 0x40, 0x3a, 0x5d, 0x80, 0x7a),
LL(0x08, 0x08, 0x20, 0x08, 0x40, 0x28, 0x10, 0x48),
LL(0xc3, 0xc3, 0x2b, 0xc3, 0x56, 0xe8, 0x9b, 0x95),
LL(0xec, 0xec, 0x97, 0xec, 0x33, 0x7b, 0xc5, 0xdf),
LL(0xdb, 0xdb, 0x4b, 0xdb, 0x96, 0x90, 0xab, 0x4d),
LL(0xa1, 0xa1, 0xbe, 0xa1, 0x61, 0x1f, 0x5f, 0xc0),
LL(0x8d, 0x8d, 0x0e, 0x8d, 0x1c, 0x83, 0x07, 0x91),
LL(0x3d, 0x3d, 0xf4, 0x3d, 0xf5, 0xc9, 0x7a, 0xc8),
LL(0x97, 0x97, 0x66, 0x97, 0xcc, 0xf1, 0x33, 0x5b),
LL(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
LL(0xcf, 0xcf, 0x1b, 0xcf, 0x36, 0xd4, 0x83, 0xf9),
LL(0x2b, 0x2b, 0xac, 0x2b, 0x45, 0x87, 0x56, 0x6e),
LL(0x76, 0x76, 0xc5, 0x76, 0x97, 0xb3, 0xec, 0xe1),
LL(0x82, 0x82, 0x32, 0x82, 0x64, 0xb0, 0x19, 0xe6),
LL(0xd6, 0xd6, 0x7f, 0xd6, 0xfe, 0xa9, 0xb1, 0x28),
LL(0x1b, 0x1b, 0x6c, 0x1b, 0xd8, 0x77, 0x36, 0xc3),
LL(0xb5, 0xb5, 0xee, 0xb5, 0xc1, 0x5b, 0x77, 0x74),
LL(0xaf, 0xaf, 0x86, 0xaf, 0x11, 0x29, 0x43, 0xbe),
LL(0x6a, 0x6a, 0xb5, 0x6a, 0x77, 0xdf, 0xd4, 0x1d),
LL(0x50, 0x50, 0x5d, 0x50, 0xba, 0x0d, 0xa0, 0xea),
LL(0x45, 0x45, 0x09, 0x45, 0x12, 0x4c, 0x8a, 0x57),
LL(0xf3, 0xf3, 0xeb, 0xf3, 0xcb, 0x18, 0xfb, 0x38),
LL(0x30, 0x30, 0xc0, 0x30, 0x9d, 0xf0, 0x60, 0xad),
LL(0xef, 0xef, 0x9b, 0xef, 0x2b, 0x74, 0xc3, 0xc4),
LL(0x3f, 0x3f, 0xfc, 0x3f, 0xe5, 0xc3, 0x7e, 0xda),
LL(0x55, 0x55, 0x49, 0x55, 0x92, 0x1c, 0xaa, 0xc7),
LL(0xa2, 0xa2, 0xb2, 0xa2, 0x79, 0x10, 0x59, 0xdb),
LL(0xea, 0xea, 0x8f, 0xea, 0x03, 0x65, 0xc9, 0xe9),
LL(0x65, 0x65, 0x89, 0x65, 0x0f, 0xec, 0xca, 0x6a),
LL(0xba, 0xba, 0xd2, 0xba, 0xb9, 0x68, 0x69, 0x03),
LL(0x2f, 0x2f, 0xbc, 0x2f, 0x65, 0x93, 0x5e, 0x4a),
LL(0xc0, 0xc0, 0x27, 0xc0, 0x4e, 0xe7, 0x9d, 0x8e),
LL(0xde, 0xde, 0x5f, 0xde, 0xbe, 0x81, 0xa1, 0x60),
LL(0x1c, 0x1c, 0x70, 0x1c, 0xe0, 0x6c, 0x38, 0xfc),
LL(0xfd, 0xfd, 0xd3, 0xfd, 0xbb, 0x2e, 0xe7, 0x46),
LL(0x4d, 0x4d, 0x29, 0x4d, 0x52, 0x64, 0x9a, 0x1f),
LL(0x92, 0x92, 0x72, 0x92, 0xe4, 0xe0, 0x39, 0x76),
LL(0x75, 0x75, 0xc9, 0x75, 0x8f, 0xbc, 0xea, 0xfa),
LL(0x06, 0x06, 0x18, 0x06, 0x30, 0x1e, 0x0c, 0x36),
LL(0x8a, 0x8a, 0x12, 0x8a, 0x24, 0x98, 0x09, 0xae),
LL(0xb2, 0xb2, 0xf2, 0xb2, 0xf9, 0x40, 0x79, 0x4b),
LL(0xe6, 0xe6, 0xbf, 0xe6, 0x63, 0x59, 0xd1, 0x85),
LL(0x0e, 0x0e, 0x38, 0x0e, 0x70, 0x36, 0x1c, 0x7e),
LL(0x1f, 0x1f, 0x7c, 0x1f, 0xf8, 0x63, 0x3e, 0xe7),
LL(0x62, 0x62, 0x95, 0x62, 0x37, 0xf7, 0xc4, 0x55),
LL(0xd4, 0xd4, 0x77, 0xd4, 0xee, 0xa3, 0xb5, 0x3a),
LL(0xa8, 0xa8, 0x9a, 0xa8, 0x29, 0x32, 0x4d, 0x81),
LL(0x96, 0x96, 0x62, 0x96, 0xc4, 0xf4, 0x31, 0x52),
LL(0xf9, 0xf9, 0xc3, 0xf9, 0x9b, 0x3a, 0xef, 0x62),
LL(0xc5, 0xc5, 0x33, 0xc5, 0x66, 0xf6, 0x97, 0xa3),
LL(0x25, 0x25, 0x94, 0x25, 0x35, 0xb1, 0x4a, 0x10),
LL(0x59, 0x59, 0x79, 0x59, 0xf2, 0x20, 0xb2, 0xab),
LL(0x84, 0x84, 0x2a, 0x84, 0x54, 0xae, 0x15, 0xd0),
LL(0x72, 0x72, 0xd5, 0x72, 0xb7, 0xa7, 0xe4, 0xc5),
LL(0x39, 0x39, 0xe4, 0x39, 0xd5, 0xdd, 0x72, 0xec),
LL(0x4c, 0x4c, 0x2d, 0x4c, 0x5a, 0x61, 0x98, 0x16),
LL(0x5e, 0x5e, 0x65, 0x5e, 0xca, 0x3b, 0xbc, 0x94),
LL(0x78, 0x78, 0xfd, 0x78, 0xe7, 0x85, 0xf0, 0x9f),
LL(0x38, 0x38, 0xe0, 0x38, 0xdd, 0xd8, 0x70, 0xe5),
LL(0x8c, 0x8c, 0x0a, 0x8c, 0x14, 0x86, 0x05, 0x98),
LL(0xd1, 0xd1, 0x63, 0xd1, 0xc6, 0xb2, 0xbf, 0x17),
LL(0xa5, 0xa5, 0xae, 0xa5, 0x41, 0x0b, 0x57, 0xe4),
LL(0xe2, 0xe2, 0xaf, 0xe2, 0x43, 0x4d, 0xd9, 0xa1),
LL(0x61, 0x61, 0x99, 0x61, 0x2f, 0xf8, 0xc2, 0x4e),
LL(0xb3, 0xb3, 0xf6, 0xb3, 0xf1, 0x45, 0x7b, 0x42),
LL(0x21, 0x21, 0x84, 0x21, 0x15, 0xa5, 0x42, 0x34),
LL(0x9c, 0x9c, 0x4a, 0x9c, 0x94, 0xd6, 0x25, 0x08),
LL(0x1e, 0x1e, 0x78, 0x1e, 0xf0, 0x66, 0x3c, 0xee),
LL(0x43, 0x43, 0x11, 0x43, 0x22, 0x52, 0x86, 0x61),
LL(0xc7, 0xc7, 0x3b, 0xc7, 0x76, 0xfc, 0x93, 0xb1),
LL(0xfc, 0xfc, 0xd7, 0xfc, 0xb3, 0x2b, 0xe5, 0x4f),
LL(0x04, 0x04, 0x10, 0x04, 0x20, 0x14, 0x08, 0x24),
LL(0x51, 0x51, 0x59, 0x51, 0xb2, 0x08, 0xa2, 0xe3),
LL(0x99, 0x99, 0x5e, 0x99, 0xbc, 0xc7, 0x2f, 0x25),
LL(0x6d, 0x6d, 0xa9, 0x6d, 0x4f, 0xc4, 0xda, 0x22),
LL(0x0d, 0x0d, 0x34, 0x0d, 0x68, 0x39, 0x1a, 0x65),
LL(0xfa, 0xfa, 0xcf, 0xfa, 0x83, 0x35, 0xe9, 0x79),
LL(0xdf, 0xdf, 0x5b, 0xdf, 0xb6, 0x84, 0xa3, 0x69),
LL(0x7e, 0x7e, 0xe5, 0x7e, 0xd7, 0x9b, 0xfc, 0xa9),
LL(0x24, 0x24, 0x90, 0x24, 0x3d, 0xb4, 0x48, 0x19),
LL(0x3b, 0x3b, 0xec, 0x3b, 0xc5, 0xd7, 0x76, 0xfe),
LL(0xab, 0xab, 0x96, 0xab, 0x31, 0x3d, 0x4b, 0x9a),
LL(0xce, 0xce, 0x1f, 0xce, 0x3e, 0xd1, 0x81, 0xf0),
LL(0x11, 0x11, 0x44, 0x11, 0x88, 0x55, 0x22, 0x99),
LL(0x8f, 0x8f, 0x06, 0x8f, 0x0c, 0x89, 0x03, 0x83),
LL(0x4e, 0x4e, 0x25, 0x4e, 0x4a, 0x6b, 0x9c, 0x04),
LL(0xb7, 0xb7, 0xe6, 0xb7, 0xd1, 0x51, 0x73, 0x66),
LL(0xeb, 0xeb, 0x8b, 0xeb, 0x0b, 0x60, 0xcb, 0xe0),
LL(0x3c, 0x3c, 0xf0, 0x3c, 0xfd, 0xcc, 0x78, 0xc1),
LL(0x81, 0x81, 0x3e, 0x81, 0x7c, 0xbf, 0x1f, 0xfd),
LL(0x94, 0x94, 0x6a, 0x94, 0xd4, 0xfe, 0x35, 0x40),
LL(0xf7, 0xf7, 0xfb, 0xf7, 0xeb, 0x0c, 0xf3, 0x1c),
LL(0xb9, 0xb9, 0xde, 0xb9, 0xa1, 0x67, 0x6f, 0x18),
LL(0x13, 0x13, 0x4c, 0x13, 0x98, 0x5f, 0x26, 0x8b),
LL(0x2c, 0x2c, 0xb0, 0x2c, 0x7d, 0x9c, 0x58, 0x51),
LL(0xd3, 0xd3, 0x6b, 0xd3, 0xd6, 0xb8, 0xbb, 0x05),
LL(0xe7, 0xe7, 0xbb, 0xe7, 0x6b, 0x5c, 0xd3, 0x8c),
LL(0x6e, 0x6e, 0xa5, 0x6e, 0x57, 0xcb, 0xdc, 0x39),
LL(0xc4, 0xc4, 0x37, 0xc4, 0x6e, 0xf3, 0x95, 0xaa),
LL(0x03, 0x03, 0x0c, 0x03, 0x18, 0x0f, 0x06, 0x1b),
LL(0x56, 0x56, 0x45, 0x56, 0x8a, 0x13, 0xac, 0xdc),
LL(0x44, 0x44, 0x0d, 0x44, 0x1a, 0x49, 0x88, 0x5e),
LL(0x7f, 0x7f, 0xe1, 0x7f, 0xdf, 0x9e, 0xfe, 0xa0),
LL(0xa9, 0xa9, 0x9e, 0xa9, 0x21, 0x37, 0x4f, 0x88),
LL(0x2a, 0x2a, 0xa8, 0x2a, 0x4d, 0x82, 0x54, 0x67),
LL(0xbb, 0xbb, 0xd6, 0xbb, 0xb1, 0x6d, 0x6b, 0x0a),
LL(0xc1, 0xc1, 0x23, 0xc1, 0x46, 0xe2, 0x9f, 0x87),
LL(0x53, 0x53, 0x51, 0x53, 0xa2, 0x02, 0xa6, 0xf1),
LL(0xdc, 0xdc, 0x57, 0xdc, 0xae, 0x8b, 0xa5, 0x72),
LL(0x0b, 0x0b, 0x2c, 0x0b, 0x58, 0x27, 0x16, 0x53),
LL(0x9d, 0x9d, 0x4e, 0x9d, 0x9c, 0xd3, 0x27, 0x01),
LL(0x6c, 0x6c, 0xad, 0x6c, 0x47, 0xc1, 0xd8, 0x2b),
LL(0x31, 0x31, 0xc4, 0x31, 0x95, 0xf5, 0x62, 0xa4),
LL(0x74, 0x74, 0xcd, 0x74, 0x87, 0xb9, 0xe8, 0xf3),
LL(0xf6, 0xf6, 0xff, 0xf6, 0xe3, 0x09, 0xf1, 0x15),
LL(0x46, 0x46, 0x05, 0x46, 0x0a, 0x43, 0x8c, 0x4c),
LL(0xac, 0xac, 0x8a, 0xac, 0x09, 0x26, 0x45, 0xa5),
LL(0x89, 0x89, 0x1e, 0x89, 0x3c, 0x97, 0x0f, 0xb5),
LL(0x14, 0x14, 0x50, 0x14, 0xa0, 0x44, 0x28, 0xb4),
LL(0xe1, 0xe1, 0xa3, 0xe1, 0x5b, 0x42, 0xdf, 0xba),
LL(0x16, 0x16, 0x58, 0x16, 0xb0, 0x4e, 0x2c, 0xa6),
LL(0x3a, 0x3a, 0xe8, 0x3a, 0xcd, 0xd2, 0x74, 0xf7),
LL(0x69, 0x69, 0xb9, 0x69, 0x6f, 0xd0, 0xd2, 0x06),
LL(0x09, 0x09, 0x24, 0x09, 0x48, 0x2d, 0x12, 0x41),
LL(0x70, 0x70, 0xdd, 0x70, 0xa7, 0xad, 0xe0, 0xd7),
LL(0xb6, 0xb6, 0xe2, 0xb6, 0xd9, 0x54, 0x71, 0x6f),
LL(0xd0, 0xd0, 0x67, 0xd0, 0xce, 0xb7, 0xbd, 0x1e),
LL(0xed, 0xed, 0x93, 0xed, 0x3b, 0x7e, 0xc7, 0xd6),
LL(0xcc, 0xcc, 0x17, 0xcc, 0x2e, 0xdb, 0x85, 0xe2),
LL(0x42, 0x42, 0x15, 0x42, 0x2a, 0x57, 0x84, 0x68),
LL(0x98, 0x98, 0x5a, 0x98, 0xb4, 0xc2, 0x2d, 0x2c),
LL(0xa4, 0xa4, 0xaa, 0xa4, 0x49, 0x0e, 0x55, 0xed),
LL(0x28, 0x28, 0xa0, 0x28, 0x5d, 0x88, 0x50, 0x75),
LL(0x5c, 0x5c, 0x6d, 0x5c, 0xda, 0x31, 0xb8, 0x86),
LL(0xf8, 0xf8, 0xc7, 0xf8, 0x93, 0x3f, 0xed, 0x6b),
LL(0x86, 0x86, 0x22, 0x86, 0x44, 0xa4, 0x11, 0xc2),
#define RC (&(Cx.q[256*N]))
0x18, 0x23, 0xc6, 0xe8, 0x87, 0xb8, 0x01, 0x4f,
/* rc[ROUNDS] */
0x36, 0xa6, 0xd2, 0xf5, 0x79, 0x6f, 0x91, 0x52, 0x60, 0xbc, 0x9b,
0x8e, 0xa3, 0x0c, 0x7b, 0x35, 0x1d, 0xe0, 0xd7, 0xc2, 0x2e, 0x4b,
0xfe, 0x57, 0x15, 0x77, 0x37, 0xe5, 0x9f, 0xf0, 0x4a, 0xda, 0x58,
0xc9, 0x29, 0x0a, 0xb1, 0xa0, 0x6b, 0x85, 0xbd, 0x5d, 0x10, 0xf4,
0xcb, 0x3e, 0x05, 0x67, 0xe4, 0x27, 0x41, 0x8b, 0xa7, 0x7d, 0x95,
0xd8, 0xfb, 0xee, 0x7c, 0x66, 0xdd, 0x17, 0x47, 0x9e, 0xca, 0x2d,
0xbf, 0x07, 0xad, 0x5a, 0x83, 0x33
}
};
void whirlpool_block(WHIRLPOOL_CTX *ctx, const void *inp, size_t n)
{
int r;
const u8 *p = inp;
union {
u64 q[8];
u8 c[64];
} S, K, *H = (void *)ctx->H.q;
#ifdef GO_FOR_MMX
GO_FOR_MMX(ctx, inp, n);
#endif
do {
#ifdef OPENSSL_SMALL_FOOTPRINT
u64 L[8];
int i;
for (i = 0; i < 64; i++)
S.c[i] = (K.c[i] = H->c[i]) ^ p[i];
for (r = 0; r < ROUNDS; r++) {
for (i = 0; i < 8; i++) {
L[i] = i ? 0 : RC[r];
L[i] ^= C0(K, i) ^ C1(K, (i - 1) & 7) ^
C2(K, (i - 2) & 7) ^ C3(K, (i - 3) & 7) ^
C4(K, (i - 4) & 7) ^ C5(K, (i - 5) & 7) ^
C6(K, (i - 6) & 7) ^ C7(K, (i - 7) & 7);
}
memcpy(K.q, L, 64);
for (i = 0; i < 8; i++) {
L[i] ^= C0(S, i) ^ C1(S, (i - 1) & 7) ^
C2(S, (i - 2) & 7) ^ C3(S, (i - 3) & 7) ^
C4(S, (i - 4) & 7) ^ C5(S, (i - 5) & 7) ^
C6(S, (i - 6) & 7) ^ C7(S, (i - 7) & 7);
}
memcpy(S.q, L, 64);
}
for (i = 0; i < 64; i++)
H->c[i] ^= S.c[i] ^ p[i];
#else
u64 L0, L1, L2, L3, L4, L5, L6, L7;
# ifdef STRICT_ALIGNMENT
if ((size_t)p & 7) {
memcpy(S.c, p, 64);
S.q[0] ^= (K.q[0] = H->q[0]);
S.q[1] ^= (K.q[1] = H->q[1]);
S.q[2] ^= (K.q[2] = H->q[2]);
S.q[3] ^= (K.q[3] = H->q[3]);
S.q[4] ^= (K.q[4] = H->q[4]);
S.q[5] ^= (K.q[5] = H->q[5]);
S.q[6] ^= (K.q[6] = H->q[6]);
S.q[7] ^= (K.q[7] = H->q[7]);
} else
# endif
{
const u64 *pa = (const u64 *)p;
S.q[0] = (K.q[0] = H->q[0]) ^ pa[0];
S.q[1] = (K.q[1] = H->q[1]) ^ pa[1];
S.q[2] = (K.q[2] = H->q[2]) ^ pa[2];
S.q[3] = (K.q[3] = H->q[3]) ^ pa[3];
S.q[4] = (K.q[4] = H->q[4]) ^ pa[4];
S.q[5] = (K.q[5] = H->q[5]) ^ pa[5];
S.q[6] = (K.q[6] = H->q[6]) ^ pa[6];
S.q[7] = (K.q[7] = H->q[7]) ^ pa[7];
}
for (r = 0; r < ROUNDS; r++) {
# ifdef SMALL_REGISTER_BANK
L0 = C0(K, 0) ^ C1(K, 7) ^ C2(K, 6) ^ C3(K, 5) ^
C4(K, 4) ^ C5(K, 3) ^ C6(K, 2) ^ C7(K, 1) ^ RC[r];
L1 = C0(K, 1) ^ C1(K, 0) ^ C2(K, 7) ^ C3(K, 6) ^
C4(K, 5) ^ C5(K, 4) ^ C6(K, 3) ^ C7(K, 2);
L2 = C0(K, 2) ^ C1(K, 1) ^ C2(K, 0) ^ C3(K, 7) ^
C4(K, 6) ^ C5(K, 5) ^ C6(K, 4) ^ C7(K, 3);
L3 = C0(K, 3) ^ C1(K, 2) ^ C2(K, 1) ^ C3(K, 0) ^
C4(K, 7) ^ C5(K, 6) ^ C6(K, 5) ^ C7(K, 4);
L4 = C0(K, 4) ^ C1(K, 3) ^ C2(K, 2) ^ C3(K, 1) ^
C4(K, 0) ^ C5(K, 7) ^ C6(K, 6) ^ C7(K, 5);
L5 = C0(K, 5) ^ C1(K, 4) ^ C2(K, 3) ^ C3(K, 2) ^
C4(K, 1) ^ C5(K, 0) ^ C6(K, 7) ^ C7(K, 6);
L6 = C0(K, 6) ^ C1(K, 5) ^ C2(K, 4) ^ C3(K, 3) ^
C4(K, 2) ^ C5(K, 1) ^ C6(K, 0) ^ C7(K, 7);
L7 = C0(K, 7) ^ C1(K, 6) ^ C2(K, 5) ^ C3(K, 4) ^
C4(K, 3) ^ C5(K, 2) ^ C6(K, 1) ^ C7(K, 0);
K.q[0] = L0;
K.q[1] = L1;
K.q[2] = L2;
K.q[3] = L3;
K.q[4] = L4;
K.q[5] = L5;
K.q[6] = L6;
K.q[7] = L7;
L0 ^= C0(S, 0) ^ C1(S, 7) ^ C2(S, 6) ^ C3(S, 5) ^
C4(S, 4) ^ C5(S, 3) ^ C6(S, 2) ^ C7(S, 1);
L1 ^= C0(S, 1) ^ C1(S, 0) ^ C2(S, 7) ^ C3(S, 6) ^
C4(S, 5) ^ C5(S, 4) ^ C6(S, 3) ^ C7(S, 2);
L2 ^= C0(S, 2) ^ C1(S, 1) ^ C2(S, 0) ^ C3(S, 7) ^
C4(S, 6) ^ C5(S, 5) ^ C6(S, 4) ^ C7(S, 3);
L3 ^= C0(S, 3) ^ C1(S, 2) ^ C2(S, 1) ^ C3(S, 0) ^
C4(S, 7) ^ C5(S, 6) ^ C6(S, 5) ^ C7(S, 4);
L4 ^= C0(S, 4) ^ C1(S, 3) ^ C2(S, 2) ^ C3(S, 1) ^
C4(S, 0) ^ C5(S, 7) ^ C6(S, 6) ^ C7(S, 5);
L5 ^= C0(S, 5) ^ C1(S, 4) ^ C2(S, 3) ^ C3(S, 2) ^
C4(S, 1) ^ C5(S, 0) ^ C6(S, 7) ^ C7(S, 6);
L6 ^= C0(S, 6) ^ C1(S, 5) ^ C2(S, 4) ^ C3(S, 3) ^
C4(S, 2) ^ C5(S, 1) ^ C6(S, 0) ^ C7(S, 7);
L7 ^= C0(S, 7) ^ C1(S, 6) ^ C2(S, 5) ^ C3(S, 4) ^
C4(S, 3) ^ C5(S, 2) ^ C6(S, 1) ^ C7(S, 0);
S.q[0] = L0;
S.q[1] = L1;
S.q[2] = L2;
S.q[3] = L3;
S.q[4] = L4;
S.q[5] = L5;
S.q[6] = L6;
S.q[7] = L7;
# else
L0 = C0(K, 0);
L1 = C1(K, 0);
L2 = C2(K, 0);
L3 = C3(K, 0);
L4 = C4(K, 0);
L5 = C5(K, 0);
L6 = C6(K, 0);
L7 = C7(K, 0);
L0 ^= RC[r];
L1 ^= C0(K, 1);
L2 ^= C1(K, 1);
L3 ^= C2(K, 1);
L4 ^= C3(K, 1);
L5 ^= C4(K, 1);
L6 ^= C5(K, 1);
L7 ^= C6(K, 1);
L0 ^= C7(K, 1);
L2 ^= C0(K, 2);
L3 ^= C1(K, 2);
L4 ^= C2(K, 2);
L5 ^= C3(K, 2);
L6 ^= C4(K, 2);
L7 ^= C5(K, 2);
L0 ^= C6(K, 2);
L1 ^= C7(K, 2);
L3 ^= C0(K, 3);
L4 ^= C1(K, 3);
L5 ^= C2(K, 3);
L6 ^= C3(K, 3);
L7 ^= C4(K, 3);
L0 ^= C5(K, 3);
L1 ^= C6(K, 3);
L2 ^= C7(K, 3);
L4 ^= C0(K, 4);
L5 ^= C1(K, 4);
L6 ^= C2(K, 4);
L7 ^= C3(K, 4);
L0 ^= C4(K, 4);
L1 ^= C5(K, 4);
L2 ^= C6(K, 4);
L3 ^= C7(K, 4);
L5 ^= C0(K, 5);
L6 ^= C1(K, 5);
L7 ^= C2(K, 5);
L0 ^= C3(K, 5);
L1 ^= C4(K, 5);
L2 ^= C5(K, 5);
L3 ^= C6(K, 5);
L4 ^= C7(K, 5);
L6 ^= C0(K, 6);
L7 ^= C1(K, 6);
L0 ^= C2(K, 6);
L1 ^= C3(K, 6);
L2 ^= C4(K, 6);
L3 ^= C5(K, 6);
L4 ^= C6(K, 6);
L5 ^= C7(K, 6);
L7 ^= C0(K, 7);
L0 ^= C1(K, 7);
L1 ^= C2(K, 7);
L2 ^= C3(K, 7);
L3 ^= C4(K, 7);
L4 ^= C5(K, 7);
L5 ^= C6(K, 7);
L6 ^= C7(K, 7);
K.q[0] = L0;
K.q[1] = L1;
K.q[2] = L2;
K.q[3] = L3;
K.q[4] = L4;
K.q[5] = L5;
K.q[6] = L6;
K.q[7] = L7;
L0 ^= C0(S, 0);
L1 ^= C1(S, 0);
L2 ^= C2(S, 0);
L3 ^= C3(S, 0);
L4 ^= C4(S, 0);
L5 ^= C5(S, 0);
L6 ^= C6(S, 0);
L7 ^= C7(S, 0);
L1 ^= C0(S, 1);
L2 ^= C1(S, 1);
L3 ^= C2(S, 1);
L4 ^= C3(S, 1);
L5 ^= C4(S, 1);
L6 ^= C5(S, 1);
L7 ^= C6(S, 1);
L0 ^= C7(S, 1);
L2 ^= C0(S, 2);
L3 ^= C1(S, 2);
L4 ^= C2(S, 2);
L5 ^= C3(S, 2);
L6 ^= C4(S, 2);
L7 ^= C5(S, 2);
L0 ^= C6(S, 2);
L1 ^= C7(S, 2);
L3 ^= C0(S, 3);
L4 ^= C1(S, 3);
L5 ^= C2(S, 3);
L6 ^= C3(S, 3);
L7 ^= C4(S, 3);
L0 ^= C5(S, 3);
L1 ^= C6(S, 3);
L2 ^= C7(S, 3);
L4 ^= C0(S, 4);
L5 ^= C1(S, 4);
L6 ^= C2(S, 4);
L7 ^= C3(S, 4);
L0 ^= C4(S, 4);
L1 ^= C5(S, 4);
L2 ^= C6(S, 4);
L3 ^= C7(S, 4);
L5 ^= C0(S, 5);
L6 ^= C1(S, 5);
L7 ^= C2(S, 5);
L0 ^= C3(S, 5);
L1 ^= C4(S, 5);
L2 ^= C5(S, 5);
L3 ^= C6(S, 5);
L4 ^= C7(S, 5);
L6 ^= C0(S, 6);
L7 ^= C1(S, 6);
L0 ^= C2(S, 6);
L1 ^= C3(S, 6);
L2 ^= C4(S, 6);
L3 ^= C5(S, 6);
L4 ^= C6(S, 6);
L5 ^= C7(S, 6);
L7 ^= C0(S, 7);
L0 ^= C1(S, 7);
L1 ^= C2(S, 7);
L2 ^= C3(S, 7);
L3 ^= C4(S, 7);
L4 ^= C5(S, 7);
L5 ^= C6(S, 7);
L6 ^= C7(S, 7);
S.q[0] = L0;
S.q[1] = L1;
S.q[2] = L2;
S.q[3] = L3;
S.q[4] = L4;
S.q[5] = L5;
S.q[6] = L6;
S.q[7] = L7;
# endif
}
# ifdef STRICT_ALIGNMENT
if ((size_t)p & 7) {
int i;
for (i = 0; i < 64; i++)
H->c[i] ^= S.c[i] ^ p[i];
} else
# endif
{
const u64 *pa = (const u64 *)p;
H->q[0] ^= S.q[0] ^ pa[0];
H->q[1] ^= S.q[1] ^ pa[1];
H->q[2] ^= S.q[2] ^ pa[2];
H->q[3] ^= S.q[3] ^ pa[3];
H->q[4] ^= S.q[4] ^ pa[4];
H->q[5] ^= S.q[5] ^ pa[5];
H->q[6] ^= S.q[6] ^ pa[6];
H->q[7] ^= S.q[7] ^ pa[7];
}
#endif
p += 64;
} while (--n);
}
| Java |
/**
* The MIT License Copyright (c) 2015 Teal Cube Games
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package land.face.strife.managers;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import land.face.strife.StrifePlugin;
import land.face.strife.data.champion.Champion;
import land.face.strife.data.champion.LifeSkillType;
import org.bukkit.entity.Player;
public class CombatStatusManager {
private final StrifePlugin plugin;
private final Map<Player, Integer> tickMap = new ConcurrentHashMap<>();
private static final int SECONDS_TILL_EXPIRY = 8;
public CombatStatusManager(StrifePlugin plugin) {
this.plugin = plugin;
}
public boolean isInCombat(Player player) {
return tickMap.containsKey(player);
}
public void addPlayer(Player player) {
tickMap.put(player, SECONDS_TILL_EXPIRY);
}
public void tickCombat() {
for (Player player : tickMap.keySet()) {
if (!player.isOnline() || !player.isValid()) {
tickMap.remove(player);
continue;
}
int ticksLeft = tickMap.get(player);
if (ticksLeft < 1) {
doExitCombat(player);
tickMap.remove(player);
continue;
}
tickMap.put(player, ticksLeft - 1);
}
}
public void doExitCombat(Player player) {
if (!tickMap.containsKey(player)) {
return;
}
Champion champion = plugin.getChampionManager().getChampion(player);
if (champion.getDetailsContainer().getExpValues() == null) {
return;
}
for (LifeSkillType type : champion.getDetailsContainer().getExpValues().keySet()) {
plugin.getSkillExperienceManager().addExperience(player, type,
champion.getDetailsContainer().getExpValues().get(type), false, false);
}
champion.getDetailsContainer().clearAll();
}
}
| Java |
-- Section: Internal Functions
-- Group: Low-level event handling
\i functions/pgq.batch_event_sql.sql
\i functions/pgq.batch_event_tables.sql
\i functions/pgq.event_retry_raw.sql
\i functions/pgq.find_tick_helper.sql
-- \i functions/pgq.insert_event_raw.sql
\i lowlevel/pgq_lowlevel.sql
-- Group: Ticker
\i functions/pgq.ticker.sql
-- Group: Periodic maintenence
\i functions/pgq.maint_retry_events.sql
\i functions/pgq.maint_rotate_tables.sql
\i functions/pgq.maint_tables_to_vacuum.sql
\i functions/pgq.maint_operations.sql
-- Group: Random utility functions
\i functions/pgq.grant_perms.sql
\i functions/pgq.force_tick.sql
\i functions/pgq.seq_funcs.sql
| Java |
#AtaK
##The Atari 2600 Compiler Kit
AtaK, pronounced attack, is a collection of programs built to aid in the
development of Atari 2600 programs.
##Programs(Planned/Developing):
* AtaR(ah-tar), The **Ata**ri 2600 Assemble**r**
* AtaC(attack), The **Ata**ri 2600 **C** Compiler
##Universal Features:
* Programmed in C89
##Contributing:
Here are some ways to contribute:
* Come up with features
* Criticize source code and programming methods
* Put comments where you see fit
* Build/test the program on other machines
##Versioning Scheme:
[major release(roman)].[year of release(roman)], rev. [revision (arabic)]
Example:
AraR I.MMXVI, rev. 0
was the first release of AtaR(a development stub)
##Contributers:
Charles "Gip-Gip" Thompson - Author/Maintainer<br>
[ZackAttack](http://atariage.com/forums/user/40226-zackattack/) - General Critic
<br>
| Java |
/* Copyright (c) 2016, 2021 Dennis Wölfing
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* libc/src/stdio/printf.c
* Print format.
*/
#include <stdarg.h>
#include <stdio.h>
int printf(const char* restrict format, ...) {
va_list ap;
va_start(ap, format);
int result = vfprintf(stdout, format, ap);
va_end(ap);
return result;
}
| Java |
from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import validate_slug
from django.db import models
from django.utils import simplejson as json
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from philo.forms.fields import JSONFormField
from philo.utils.registry import RegistryIterator
from philo.validators import TemplateValidator, json_validator
#from philo.models.fields.entities import *
class TemplateField(models.TextField):
"""A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction."""
def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs):
super(TemplateField, self).__init__(*args, **kwargs)
self.validators.append(TemplateValidator(allow, disallow, secure))
class JSONDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, instance, owner):
if instance is None:
raise AttributeError # ?
if self.field.name not in instance.__dict__:
json_string = getattr(instance, self.field.attname)
instance.__dict__[self.field.name] = json.loads(json_string)
return instance.__dict__[self.field.name]
def __set__(self, instance, value):
instance.__dict__[self.field.name] = value
setattr(instance, self.field.attname, json.dumps(value))
def __delete__(self, instance):
del(instance.__dict__[self.field.name])
setattr(instance, self.field.attname, json.dumps(None))
class JSONField(models.TextField):
"""A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`."""
default_validators = [json_validator]
def get_attname(self):
return "%s_json" % self.name
def contribute_to_class(self, cls, name):
super(JSONField, self).contribute_to_class(cls, name)
setattr(cls, name, JSONDescriptor(self))
models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls)
def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs):
# Anything passed in as self.name is assumed to come from a serializer and
# will be treated as a json string.
if self.name in kwargs:
value = kwargs.pop(self.name)
# Hack to handle the xml serializer's handling of "null"
if value is None:
value = 'null'
kwargs[self.attname] = value
def formfield(self, *args, **kwargs):
kwargs["form_class"] = JSONFormField
return super(JSONField, self).formfield(*args, **kwargs)
class SlugMultipleChoiceField(models.Field):
"""Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices."""
__metaclass__ = models.SubfieldBase
description = _("Comma-separated slug field")
def get_internal_type(self):
return "TextField"
def to_python(self, value):
if not value:
return []
if isinstance(value, list):
return value
return value.split(',')
def get_prep_value(self, value):
return ','.join(value)
def formfield(self, **kwargs):
# This is necessary because django hard-codes TypedChoiceField for things with choices.
defaults = {
'widget': forms.CheckboxSelectMultiple,
'choices': self.get_choices(include_blank=False),
'label': capfirst(self.verbose_name),
'required': not self.blank,
'help_text': self.help_text
}
if self.has_default():
if callable(self.default):
defaults['initial'] = self.default
defaults['show_hidden_initial'] = True
else:
defaults['initial'] = self.get_default()
for k in kwargs.keys():
if k not in ('coerce', 'empty_value', 'choices', 'required',
'widget', 'label', 'initial', 'help_text',
'error_messages', 'show_hidden_initial'):
del kwargs[k]
defaults.update(kwargs)
form_class = forms.TypedMultipleChoiceField
return form_class(**defaults)
def validate(self, value, model_instance):
invalid_values = []
for val in value:
try:
validate_slug(val)
except ValidationError:
invalid_values.append(val)
if invalid_values:
# should really make a custom message.
raise ValidationError(self.error_messages['invalid_choice'] % invalid_values)
def _get_choices(self):
if isinstance(self._choices, RegistryIterator):
return self._choices.copy()
elif hasattr(self._choices, 'next'):
choices, self._choices = itertools.tee(self._choices)
return choices
else:
return self._choices
choices = property(_get_choices)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"])
add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"])
add_introspection_rules([], ["^philo\.models\.fields\.JSONField"]) | Java |
# gulp boilerplate
run
`npm start`
then open another termianl
run `gulp watch` ,change some files for browser-syn
## Gulp tasks
* gulp
* gulp prod
| Java |
/*-
* builtin.c
* This file is part of libmetha
*
* Copyright (c) 2008, Emil Romanus <emil.romanus@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* http://bithack.se/projects/methabot/
*/
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/stat.h>
#include "errors.h"
#include "ftpparse.h"
#include "worker.h"
#include "urlengine.h"
#include "io.h"
#include "builtin.h"
/**
* Builtin parsers except for the html parser which is in html.c
**/
struct {
const char *name;
int len;
} protocols[] = {
{"http", 4},
{"ftp", 3},
};
/**
* Default CSS parser
**/
M_CODE
lm_parser_css(worker_t *w, iobuf_t *buf, uehandle_t *ue_h,
url_t *url, attr_list_t *al)
{
return lm_extract_css_urls(ue_h, buf->ptr, buf->sz);
}
/**
* download the data to a local file instead of
* to memory
*
* the parser chain will receive the file name in
* this.data instead of the real buffer.
**/
M_CODE
lm_handler_writefile(worker_t *w, iohandle_t *h,
url_t *url)
{
int r;
char *name;
char *ext;
char *s;
int x;
int ext_offs;
int a_sz;
int sz;
struct stat st;
/**
* create a filename to download to
**/
if (url->ext_o) {
for (x = url->ext_o; *(url->str+x) && *(url->str+x) != '?'; x++)
;
if (!(ext = malloc(x-url->ext_o+1)))
return M_OUT_OF_MEM;
memcpy(ext, url->str+url->ext_o, x-url->ext_o);
ext[x-url->ext_o] = '\0';
ext_offs = url->ext_o-(url->file_o+1);
} else {
ext = strdup("");
for (x = url->file_o+1; *(url->str+x) && *(url->str+x) != '?'; x++)
;
ext_offs = x-(url->file_o+1);
}
if (url->file_o+1 == url->sz) {
if (!(name = malloc(a_sz = sizeof("index.html")+32)))
return M_OUT_OF_MEM;
memcpy(name, "index.html", sizeof("index.html"));
ext_offs = strlen("index");
ext = strdup(".html");
} else {
if (!(name = malloc(a_sz = ext_offs+strlen(ext)+1+32)))
return M_OUT_OF_MEM;
memcpy(name, url->str+url->file_o+1, ext_offs);
strcpy(name+ext_offs, ext);
}
x=0;
if (stat(name, &st) == 0) {
do {
x++;
sz = sprintf(name+ext_offs, "-%d%s", x, ext);
} while (stat(name, &st) == 0);
}
r = lm_io_save(h, url, name);
if (r == M_OK) {
/* set the I/O buffer to the name of the file */
free(h->buf.ptr);
h->buf.ptr = name;
h->buf.sz = strlen(name);
h->buf.cap = a_sz;
} else
free(name);
free(ext);
return M_OK;
}
/**
* Parse the given string as CSS and add the found URLs to
* the uehandle.
**/
M_CODE
lm_extract_css_urls(uehandle_t *ue_h, char *p, size_t sz)
{
char *e = p+sz;
char *t, *s;
while ((p = memmem(p, e-p, "url", 3))) {
p += 3;
while (isspace(*p)) p++;
if (*p == '(') {
do p++; while (isspace(*p));
t = (*p == '"' ? "\")"
: (*p == '\'' ? "')" : ")"));
if (*t != ')')
p++;
} else
t = (*p == '"' ? "\""
: (*p == '\'' ? "'" : ";"));
if (!(s = memmem(p, e-p, t, strlen(t))))
continue;
ue_add(ue_h, p, s-p);
p = s;
}
return M_OK;
}
/**
* Default plaintext parser
**/
M_CODE
lm_parser_text(worker_t *w, iobuf_t *buf,
uehandle_t *ue_h, url_t *url,
attr_list_t *al)
{
return lm_extract_text_urls(ue_h, buf->ptr, buf->sz);
}
M_CODE
lm_extract_text_urls(uehandle_t *ue_h, char *p, size_t sz)
{
int x;
char *s, *e = p+sz;
for (p = strstr(p, "://"); p && p<e; p = strstr(p+1, "://")) {
for (x=0;x<2;x++) {
if (p-e >= protocols[x].len
&& strncmp(p-protocols[x].len, protocols[x].name, protocols[x].len) == 0) {
for (s=p+3; s < e; s++) {
if (!isalnum(*s) && *s != '%' && *s != '?'
&& *s != '=' && *s != '&' && *s != '/'
&& *s != '.') {
ue_add(ue_h, p-protocols[x].len, (s-p)+protocols[x].len);
break;
}
}
p = s;
}
}
}
return M_OK;
}
/**
* Default FTP parser. Expects data returned from the default
* FTP handler.
**/
M_CODE
lm_parser_ftp(worker_t *w, iobuf_t *buf,
uehandle_t *ue_h, url_t *url,
attr_list_t *al)
{
char *p, *prev;
struct ftpparse info;
char name[128]; /* i'm pretty sure no filename will be longer than 127 chars... */
int len;
for (prev = p = buf->ptr; p<buf->ptr+buf->sz; p++) {
if (*p == '\n') {
if (p-prev) {
if (ftpparse(&info, prev, p-prev)) {
if (info.namelen >= 126) {
LM_WARNING(w->m, "file name too long");
continue;
}
if (info.flagtrycwd) {
memcpy(name, info.name, info.namelen);
name[info.namelen] = '/';
name[info.namelen+1] = '\0';
len = info.namelen+1;
} else {
strncpy(name, info.name, info.namelen);
len = info.namelen;
}
ue_add(ue_h, name, len);
}
prev = p+1;
} else
prev = p+1;
}
}
return M_OK;
}
| Java |
/* Copyright (c) 2019, 2022 Dennis Wölfing
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* libc/src/stdio/__file_write.c
* Write data to a file. (called from C89)
*/
#define write __write
#include <unistd.h>
#include "FILE.h"
size_t __file_write(FILE* file, const unsigned char* p, size_t size) {
size_t written = 0;
while (written < size) {
ssize_t result = write(file->fd, p, size - written);
if (result < 0) {
file->flags |= FILE_FLAG_ERROR;
return written;
}
written += result;
p += result;
}
return written;
}
| Java |
<?php
/**
* Time Controller
*
* @package Argentum
* @author Argentum Team
* @copyright (c) 2008 Argentum Team
* @license http://www.argentuminvoice.com/license.txt
*/
class Time_Controller extends Website_Controller {
/**
* Creates a new time block on a ticket
*/
public function add($ticket_id)
{
$time = new Time_Model();
$time->ticket_id = $ticket_id;
if ( ! $_POST) // Display the form
{
$this->template->body = new View('admin/time/add');
$this->template->body->errors = '';
$this->template->body->time = $time;
}
else
{
$time->set_fields($this->input->post());
$time->user_id = $_SESSION['auth_user']->id;
try
{
$time->save();
if ($this->input->post('ticket_complete'))
{
$ticket = new Ticket_Model($time->ticket_id);
$ticket->complete= TRUE;
$ticket->close_date = time();
$ticket->save();
Event::run('argentum.ticket_close', $ticket);
}
Event::run('argentum.ticket_time', $time);
url::redirect('ticket/'.($time->ticket->complete ? 'closed' : 'active').'/'.$time->ticket->project->id);
}
catch (Kohana_User_Exception $e)
{
$this->template->body = new View('admin/time/add');
$this->template->body->time = $time;
$this->template->body->errors = $e;
$this->template->body->set($this->input->post());
}
}
}
/**
* Deletes a time item for a ticket
*/
public function delete()
{
$time = new Time_Model($this->input->post('id'));
$time->delete();
url::redirect('ticket/view/'.$time->ticket->id);
}
} | Java |
var fusepm = require('./fusepm');
module.exports = fixunoproj;
function fixunoproj () {
var fn = fusepm.local_unoproj(".");
fusepm.read_unoproj(fn).then(function (obj) {
var inc = [];
if (obj.Includes) {
var re = /\//;
for (var i=0; i<obj.Includes.length;i++) {
if (obj.Includes[i] === '*') {
inc.push('./*.ux');
inc.push('./*.uno');
inc.push('./*.uxl');
}
else if (!obj.Includes[i].match(re)) {
inc.push('./' + obj.Includes[i]);
}
else {
inc.push(obj.Includes[i]);
}
}
}
else {
inc = ['./*.ux', './*.uno', './*.uxl'];
}
if (!obj.Version) {
obj.Version = "0.0.0";
}
obj.Includes = inc;
fusepm.save_unoproj(fn, obj);
}).catch(function (e) {
console.log(e);
});
} | Java |
import mod437 from './mod437';
var value=mod437+1;
export default value;
| Java |
<!DOCTYPE html>
<html>
<head>
<title>Hello World!</title>
<script src="lib/js/angular.min.js"></script>
<script src="lib/js/angular-route.min.js"></script>
<script src="lib/js/angular-animate.min.js"></script>
<script src="lib/js/angular-aria.min.js"></script>
<script src="lib/js/angular-touch.min.js"></script>
<script src="lib/js/angular-material.min.js"></script>
<script src="lib/js/angular-local-storage.min.js"></script>
<link rel="stylesheet" href="lib/css/angular-material.min.css">
<link rel="stylesheet" href="lib/css/font-awesome.min.css">
<link rel="stylesheet" href="lib/css/app.css">
<link rel="stylesheet" href="lib/css/animation.css">
<link rel="stylesheet" href="lib/css/material-custom.css">
</head>
<body ng-app="azure" md-theme="default">
<div ng-include="'app/layout/shell.html'" class="page-container"></div>
<script src="app/app.js"></script>
<script src="app/common/app-start.service.js"></script>
<script src="app/common/routes.constant.js"></script>
<script src="app/common/service.module.js"></script>
<script src="app/layout/shell.js"></script>
<script src="app/home/home.js"></script>
<script src="app/blob/blob.js"></script>
<script src="app/layout/account-storage.service.js"></script>
<!--We are using io.js <script>document.write(process.version)</script>-->
<!--and Electron <script>document.write(process.versions['electron'])</script>.-->
</body>
</html> | Java |
const defaults = {
base_css: true, // the base dark theme css
inline_youtube: true, // makes youtube videos play inline the chat
collapse_onebox: true, // can collapse
collapse_onebox_default: false, // default option for collapse
pause_youtube_on_collapse: true, // default option for pausing youtube on collapse
user_color_bars: true, // show colored bars above users message blocks
fish_spinner: true, // fish spinner is best spinner
inline_imgur: true, // inlines webm,gifv,mp4 content from imgur
visualize_hex: true, // underlines hex codes with their colour values
syntax_highlight_code: true, // guess at language and highlight the code blocks
emoji_translator: true, // emoji translator for INPUT area
code_mode_editor: true, // uses CodeMirror for your code inputs
better_image_uploads: true // use the drag & drop and paste api for image uploads
};
const fileLocations = {
inline_youtube: ['js/inline_youtube.js'],
collapse_onebox: ['js/collapse_onebox.js'],
user_color_bars: ['js/user_color_bars.js'],
fish_spinner: ['js/fish_spinner.js'],
inline_imgur: ['js/inline_imgur.js'],
visualize_hex: ['js/visualize_hex.js'],
better_image_uploads: ['js/better_image_uploads.js'],
syntax_highlight_code: ['js/highlight.js', 'js/syntax_highlight_code.js'],
emoji_translator: ['js/emojidata.js', 'js/emoji_translator.js'],
code_mode_editor: ['CodeMirror/js/codemirror.js',
'CodeMirror/mode/cmake/cmake.js',
'CodeMirror/mode/cobol/cobol.js',
'CodeMirror/mode/coffeescript/coffeescript.js',
'CodeMirror/mode/commonlisp/commonlisp.js',
'CodeMirror/mode/css/css.js',
'CodeMirror/mode/dart/dart.js',
'CodeMirror/mode/go/go.js',
'CodeMirror/mode/groovy/groovy.js',
'CodeMirror/mode/haml/haml.js',
'CodeMirror/mode/haskell/haskell.js',
'CodeMirror/mode/htmlembedded/htmlembedded.js',
'CodeMirror/mode/htmlmixed/htmlmixed.js',
'CodeMirror/mode/jade/jade.js',
'CodeMirror/mode/javascript/javascript.js',
'CodeMirror/mode/lua/lua.js',
'CodeMirror/mode/markdown/markdown.js',
'CodeMirror/mode/mathematica/mathematica.js',
'CodeMirror/mode/nginx/nginx.js',
'CodeMirror/mode/pascal/pascal.js',
'CodeMirror/mode/perl/perl.js',
'CodeMirror/mode/php/php.js',
'CodeMirror/mode/puppet/puppet.js',
'CodeMirror/mode/python/python.js',
'CodeMirror/mode/ruby/ruby.js',
'CodeMirror/mode/sass/sass.js',
'CodeMirror/mode/scheme/scheme.js',
'CodeMirror/mode/shell/shell.js' ,
'CodeMirror/mode/sql/sql.js',
'CodeMirror/mode/swift/swift.js',
'CodeMirror/mode/twig/twig.js',
'CodeMirror/mode/vb/vb.js',
'CodeMirror/mode/vbscript/vbscript.js',
'CodeMirror/mode/vhdl/vhdl.js',
'CodeMirror/mode/vue/vue.js',
'CodeMirror/mode/xml/xml.js',
'CodeMirror/mode/xquery/xquery.js',
'CodeMirror/mode/yaml/yaml.js',
'js/code_mode_editor.js']
};
// right now I assume order is correct because I'm a terrible person. make an order array or base it on File Locations and make that an array
// inject the observer and the utils always. then initialize the options.
injector([{type: 'js', location: 'js/observer.js'},{type: 'js', location: 'js/utils.js'}], _ => chrome.storage.sync.get(defaults, init));
function init(options) {
// inject the options for the plugins themselves.
const opts = document.createElement('script');
opts.textContent = `
const options = ${JSON.stringify(options)};
`;
document.body.appendChild(opts);
// now load the plugins.
const loading = [];
if( !options.base_css ) {
document.documentElement.classList.add('nocss');
}
delete options.base_css;
for( const key of Object.keys(options) ) {
if( !options[key] || !( key in fileLocations)) continue;
for( const location of fileLocations[key] ) {
const [,type] = location.split('.');
loading.push({location, type});
}
}
injector(loading, _ => {
const drai = document.createElement('script');
drai.textContent = `
if( document.readyState === 'complete' ) {
DOMObserver.drain();
} else {
window.onload = _ => DOMObserver.drain();
}
`;
document.body.appendChild(drai);
});
}
function injector([first, ...rest], cb) {
if( !first ) return cb();
if( first.type === 'js' ) {
injectJS(first.location, _ => injector(rest, cb));
} else {
injectCSS(first.location, _ => injector(rest, cb));
}
}
function injectCSS(file, cb) {
const elm = document.createElement('link');
elm.rel = 'stylesheet';
elm.type = 'text/css';
elm.href = chrome.extension.getURL(file);
elm.onload = cb;
document.head.appendChild(elm);
}
function injectJS(file, cb) {
const elm = document.createElement('script');
elm.type = 'text/javascript';
elm.src = chrome.extension.getURL(file);
elm.onload = cb;
document.body.appendChild(elm);
} | Java |
'use strict';
const expect = require('expect.js');
const http = require('http');
const express = require('express');
const linkCheck = require('../');
describe('link-check', function () {
this.timeout(2500);//increase timeout to enable 429 retry tests
let baseUrl;
let laterCustomRetryCounter;
before(function (done) {
const app = express();
app.head('/nohead', function (req, res) {
res.sendStatus(405); // method not allowed
});
app.get('/nohead', function (req, res) {
res.sendStatus(200);
});
app.get('/foo/redirect', function (req, res) {
res.redirect('/foo/bar');
});
app.get('/foo/bar', function (req, res) {
res.json({foo:'bar'});
});
app.get('/loop', function (req, res) {
res.redirect('/loop');
});
app.get('/hang', function (req, res) {
// no reply
});
app.get('/notfound', function (req, res) {
res.sendStatus(404);
});
app.get('/basic-auth', function (req, res) {
if (req.headers["authorization"] === "Basic Zm9vOmJhcg==") {
return res.sendStatus(200);
}
res.sendStatus(401);
});
// prevent first header try to be a hit
app.head('/later-custom-retry-count', function (req, res) {
res.sendStatus(405); // method not allowed
});
app.get('/later-custom-retry-count', function (req, res) {
laterCustomRetryCounter++;
if(laterCustomRetryCounter === parseInt(req.query.successNumber)) {
res.sendStatus(200);
}else{
res.setHeader('retry-after', 1);
res.sendStatus(429);
}
});
// prevent first header try to be a hit
app.head('/later-standard-header', function (req, res) {
res.sendStatus(405); // method not allowed
});
var stdRetried = false;
var stdFirstTry = 0;
app.get('/later', function (req, res) {
var isRetryDelayExpired = stdFirstTry + 1000 < Date.now();
if(!stdRetried || !isRetryDelayExpired){
stdFirstTry = Date.now();
stdRetried = true;
res.setHeader('retry-after', 1);
res.sendStatus(429);
}else{
res.sendStatus(200);
}
});
// prevent first header try to be a hit
app.head('/later-no-header', function (req, res) {
res.sendStatus(405); // method not allowed
});
var stdNoHeadRetried = false;
var stdNoHeadFirstTry = 0;
app.get('/later-no-header', function (req, res) {
var minTime = stdNoHeadFirstTry + 1000;
var maxTime = minTime + 100;
var now = Date.now();
var isRetryDelayExpired = minTime < now && now < maxTime;
if(!stdNoHeadRetried || !isRetryDelayExpired){
stdNoHeadFirstTry = Date.now();
stdNoHeadRetried = true;
res.sendStatus(429);
}else{
res.sendStatus(200);
}
});
// prevent first header try to be a hit
app.head('/later-non-standard-header', function (req, res) {
res.sendStatus(405); // method not allowed
});
var nonStdRetried = false;
var nonStdFirstTry = 0;
app.get('/later-non-standard-header', function (req, res) {
var isRetryDelayExpired = nonStdFirstTry + 1000 < Date.now();
if(!nonStdRetried || !isRetryDelayExpired){
nonStdFirstTry = Date.now();
nonStdRetried = true;
res.setHeader('retry-after', '1s');
res.sendStatus(429);
}else {
res.sendStatus(200);
}
});
app.get(encodeURI('/url_with_unicode–'), function (req, res) {
res.sendStatus(200);
});
app.get('/url_with_special_chars\\(\\)\\+', function (req, res) {
res.sendStatus(200);
});
const server = http.createServer(app);
server.listen(0 /* random open port */, 'localhost', function serverListen(err) {
if (err) {
done(err);
return;
}
baseUrl = 'http://' + server.address().address + ':' + server.address().port;
done();
});
});
it('should find that a valid link is alive', function (done) {
linkCheck(baseUrl + '/foo/bar', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/foo/bar');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
expect(result.err).to.be(null);
done();
});
});
it('should find that a valid external link with basic authentication is alive', function (done) {
linkCheck(baseUrl + '/basic-auth', {
headers: {
'Authorization': 'Basic Zm9vOmJhcg=='
},
}, function (err, result) {
expect(err).to.be(null);
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
expect(result.err).to.be(null);
done();
});
});
it('should find that a valid relative link is alive', function (done) {
linkCheck('/foo/bar', { baseUrl: baseUrl }, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('/foo/bar');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
expect(result.err).to.be(null);
done();
});
});
it('should find that an invalid link is dead', function (done) {
linkCheck(baseUrl + '/foo/dead', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/foo/dead');
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(404);
expect(result.err).to.be(null);
done();
});
});
it('should find that an invalid relative link is dead', function (done) {
linkCheck('/foo/dead', { baseUrl: baseUrl }, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('/foo/dead');
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(404);
expect(result.err).to.be(null);
done();
});
});
it('should report no DNS entry as a dead link (http)', function (done) {
linkCheck('http://example.example.example.com/', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('http://example.example.example.com/');
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(0);
expect(result.err.code).to.be('ENOTFOUND');
done();
});
});
it('should report no DNS entry as a dead link (https)', function (done) {
const badLink = 'https://githuuuub.com/tcort/link-check';
linkCheck(badLink, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(badLink);
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(0);
expect(result.err.code).to.contain('ENOTFOUND');
done();
});
});
it('should timeout if there is no response', function (done) {
linkCheck(baseUrl + '/hang', { timeout: '100ms' }, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/hang');
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(0);
expect(result.err.code).to.be('ECONNRESET');
done();
});
});
it('should try GET if HEAD fails', function (done) {
linkCheck(baseUrl + '/nohead', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/nohead');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
expect(result.err).to.be(null);
done();
});
});
it('should handle redirects', function (done) {
linkCheck(baseUrl + '/foo/redirect', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/foo/redirect');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
expect(result.err).to.be(null);
done();
});
});
it('should handle valid mailto', function (done) {
linkCheck('mailto:linuxgeek@gmail.com', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('mailto:linuxgeek@gmail.com');
expect(result.status).to.be('alive');
done();
});
});
it('should handle valid mailto with encoded characters in address', function (done) {
linkCheck('mailto:foo%20bar@example.org', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('mailto:foo%20bar@example.org');
expect(result.status).to.be('alive');
done();
});
});
it('should handle valid mailto containing hfields', function (done) {
linkCheck('mailto:linuxgeek@gmail.com?subject=caf%C3%A9', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('mailto:linuxgeek@gmail.com?subject=caf%C3%A9');
expect(result.status).to.be('alive');
done();
});
});
it('should handle invalid mailto', function (done) {
linkCheck('mailto:foo@@bar@@baz', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('mailto:foo@@bar@@baz');
expect(result.status).to.be('dead');
done();
});
});
it('should handle file protocol', function(done) {
linkCheck('fixtures/file.md', { baseUrl: 'file://' + __dirname }, function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
done()
});
});
it('should handle file protocol with fragment', function(done) {
linkCheck('fixtures/file.md#section-1', { baseUrl: 'file://' + __dirname }, function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
done()
});
});
it('should handle file protocol with query', function(done) {
linkCheck('fixtures/file.md?foo=bar', { baseUrl: 'file://' + __dirname }, function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
done()
});
});
it('should handle file path containing spaces', function(done) {
linkCheck('fixtures/s p a c e/A.md', { baseUrl: 'file://' + __dirname }, function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
done()
});
});
it('should handle baseUrl containing spaces', function(done) {
linkCheck('A.md', { baseUrl: 'file://' + __dirname + '/fixtures/s p a c e'}, function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
done()
});
});
it('should handle file protocol and invalid files', function(done) {
linkCheck('fixtures/missing.md', { baseUrl: 'file://' + __dirname }, function(err, result) {
expect(err).to.be(null);
expect(result.err.code).to.be('ENOENT');
expect(result.status).to.be('dead');
done()
});
});
it('should ignore file protocol on absolute links', function(done) {
linkCheck(baseUrl + '/foo/bar', { baseUrl: 'file://' }, function(err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/foo/bar');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
expect(result.err).to.be(null);
done()
});
});
it('should ignore file protocol on fragment links', function(done) {
linkCheck('#foobar', { baseUrl: 'file://' }, function(err, result) {
expect(err).to.be(null);
expect(result.link).to.be('#foobar');
done()
});
});
it('should callback with an error on unsupported protocol', function (done) {
linkCheck('gopher://gopher/0/v2/vstat', function (err, result) {
expect(result).to.be(null);
expect(err).to.be.an(Error);
done();
});
});
it('should handle redirect loops', function (done) {
linkCheck(baseUrl + '/loop', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/loop');
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(0);
expect(result.err.message).to.contain('Max redirects reached');
done();
});
});
it('should honour response codes in opts.aliveStatusCodes[]', function (done) {
linkCheck(baseUrl + '/notfound', { aliveStatusCodes: [ 404, 200 ] }, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/notfound');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(404);
done();
});
});
it('should honour regexps in opts.aliveStatusCodes[]', function (done) {
linkCheck(baseUrl + '/notfound', { aliveStatusCodes: [ 200, /^[45][0-9]{2}$/ ] }, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/notfound');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(404);
done();
});
});
it('should honour opts.aliveStatusCodes[]', function (done) {
linkCheck(baseUrl + '/notfound', { aliveStatusCodes: [ 200 ] }, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/notfound');
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(404);
done();
});
});
it('should retry after the provided delay on HTTP 429 with standard header', function (done) {
linkCheck(baseUrl + '/later', { retryOn429: true }, function (err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.link).to.be(baseUrl + '/later');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
done();
});
});
it('should retry after the provided delay on HTTP 429 with non standard header, and return a warning', function (done) {
linkCheck(baseUrl + '/later-non-standard-header', { retryOn429: true }, function (err, result) {
expect(err).to.be(null);
expect(result.err).not.to.be(null)
expect(result.err).to.contain("Server returned a non standard \'retry-after\' header.");
expect(result.link).to.be(baseUrl + '/later-non-standard-header');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
done();
});
});
it('should retry after 1s delay on HTTP 429 without header', function (done) {
linkCheck(baseUrl + '/later-no-header', { retryOn429: true, fallbackRetryDelay: '1s' }, function (err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.link).to.be(baseUrl + '/later-no-header');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
done();
});
});
// 2 is default retry so test with custom 3
it('should retry 3 times for 429 status codes', function(done) {
laterCustomRetryCounter = 0;
linkCheck(baseUrl + '/later-custom-retry-count?successNumber=3', { retryOn429: true, retryCount: 3 }, function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
done();
});
});
// See issue #23
it('should handle non URL encoded unicode chars in URLs', function(done) {
//last char is EN DASH
linkCheck(baseUrl + '/url_with_unicode–', function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
done();
});
});
// See issues #34 and #40
it('should not URL encode already encoded characters', function(done) {
linkCheck(baseUrl + '/url_with_special_chars%28%29%2B', function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
done();
});
});
});
| Java |
---
layout: post
title: More Office Interop in PowerShell
---
As part of our team's workflow we create various data files and then generate
tracking issues that we then import into our issue tracking system.
We have a semi-automated process to do this which works fairly well but for
some older issues we had imported I noticed that a vital piece of information
was missing.
When we ingest the issues into the system there is an identifier that we save
into the issue tracking system so we can find this information in our data
files later.
We also generate some reports from our data files one of which is an Excel
spreadsheet that contains the issue identifier and which also contains the
information that was missing from the issue tracking system.
Since there were hundreds of issue that needed updating I didn't want to update
all of the issues in the issue tracking system manually.
The issue tracking system allowed me to create a query and then download a CSV
of the issues that were missing the data. Then I found the spreadsheets that
had the data and wrote the following PowerShell script to generate a CSV file
with the missing data mapped to the issue identifiers:
```powershell
param(
[Parameter(Mandatory)][string]$issuesCsv,
[Parameter(Mandatory)][string]$excelReport
)
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
function Get-IssueData {
param(
[Parameter(Mandatory)]$workbook,
[Parameter(Mandatory)][PSCustomObject[]]$issues
)
$issueData = @()
foreach ($issue in $issues) {
if (-not $issue.IssueId) {
continue
}
foreach ($worksheet in $workbook.Worksheets) {
$target = $worksheet.UsedRange.Find($issueId)
if ($target) {
$csvIssue = [PSCustomObject]@{
IssueId = $issue.IssueId
MissingFieldData = $target.EntireRow.Value2[1, 5]
}
$issueData += $csvIssue
break
}
}
}
return $issueData
}
try {
$issues = Import-Csv -Path $path
} catch {
"Unable to import issues."
exit 1
}
$application = New-Object -ComObject Excel.Application
try {
$workbook = $application.Workbooks.Open($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($excelReport))
} catch {
"Unable to open workbook."
$application.Quit()
exit 1
}
Get-IssueData $workbook $issues | Export-Csv -Path export.csv -NoTypeInformation
$workbook.Close($false)
$application.Quit()
```
| Java |
/* Copyright (c) 2018 Dennis Wölfing
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* kernel/include/dennix/clock.h
* System clocks.
*/
#ifndef _DENNIX_CLOCK_H
#define _DENNIX_CLOCK_H
#define CLOCK_MONOTONIC 0
#define CLOCK_REALTIME 1
#define CLOCK_PROCESS_CPUTIME_ID 2
#define CLOCK_THREAD_CPUTIME_ID 3
#define TIMER_ABSTIME 1
#endif
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.