code
stringlengths
2
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
991
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
'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'));
Socratacom/socrata-europe
wp-content/themes/sage/node_modules/asset-builder/node_modules/main-bower-files/node_modules/vinyl-fs/node_modules/glob-stream/node_modules/unique-stream/node_modules/es6-set/polyfill.js
JavaScript
gpl-2.0
2,730
'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;
mshick/velvet
core/classes/data.js
JavaScript
isc
266
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 }
GoKillers/libsodium-go
sodium/runtime.go
GO
isc
322
<?php interface Container { /** * Checks if a $x exists. * * @param unknown $x * * @return boolean */ function contains($x); }
guide42/php-immutable
src/base.php
PHP
isc
165
/* * 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; }
markokr/libusual
usual/json.c
C
isc
38,477
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 } });
pikachumetal/cursoangular05
app/loginModule/services/localstorage.js
JavaScript
isc
515
/* 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(&currentArgs, args); formatCursor = &format[0]; getValue(envP, &formatCursor, &currentArgs, 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. */
arssivka/naomech
xmlrpc-c/src/xmlrpc_build.c
C
isc
12,744
/* 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 ; }
skarnet/s6-networking
src/sbearssl/sbearssl_skey_to.c
C
isc
438
/* * 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; }
sauban/angular-boilerplate
vendor/dropzone/dropzone.css
CSS
isc
12,777
/* 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;
kartta-labs/iD
build.js
JavaScript
isc
591
// // 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
wvuRc2/rc2client
source/rc2/model/RCWorkspaceCache.h
C
isc
639
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; };
damienmortini/dlib
node_modules/lottie-web/player/js/utils/text/LetterProps.js
JavaScript
isc
1,212
/*! * 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); }
becm/mpt-solver
modules/daesolv/libinfo.c
C
isc
379
/* * 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' };
ibc/MediaSoup
worker/deps/openssl/config/archs/linux-armv4/asm_avx2/crypto/buildinf.h
C
isc
2,032
--- 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 ---
dsusco/tp.net-armageddon.org
_site/_units/dreadnought.md
Markdown
isc
409
/* * 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; } }
DanielAeolusLaude/DPF-NTK
distrho/src/DistrhoPluginLV2export.cpp
C++
isc
16,790
// 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] } })
rhaphazard/moebooru
lib/assets/javascripts/moe-legacy/notes.js
JavaScript
isc
21,067
// 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 } } }
decred/dcrd
blockchain/indexers/indexsubscriber.go
GO
isc
10,267
@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
Brawl345/WiiDataDownloader-Module
HackMii Installer herunterladen.bat
Batchfile
isc
521
# 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.
decred/decrediton
app/i18n/docs/pl/InfoModals/GapLimit.md
Markdown
isc
1,305
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, };
k0gaMSX/scc
cc2/target/qbe/arch.h
C
isc
1,127
// 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}, }
Dirbaio/btcd
wire/msgblock_test.go
GO
isc
28,011
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' } } } }); }); });
bsander/dJSON
test/dJSON.spec.js
JavaScript
isc
3,391
/* * 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" };
ibara/chargend
chargend.h
C
isc
7,754
#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); }
kdhp/play
mp3.c
C
isc
2,590
/* * 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); }
ibc/MediaSoup
worker/deps/openssl/openssl/crypto/whrlpool/wp_block.c
C
isc
34,797
/** * 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(); } }
TealCube/strife
src/main/java/land/face/strife/managers/CombatStatusManager.java
Java
isc
2,828
-- 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
mpihlak/skytools-dev
sql/pgq/structure/func_internal.sql
SQL
isc
668
#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>
Gip-Gip/AtaC
README.md
Markdown
isc
871
/* 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; }
dennis95/dennix
libc/src/stdio/printf.c
C
isc
1,043
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"])
ithinksw/philo
philo/models/fields/__init__.py
Python
isc
4,971
# gulp boilerplate run `npm start` then open another termianl run `gulp watch` ,change some files for browser-syn ## Gulp tasks * gulp * gulp prod
nickleefly/gulp-boilerplate
README.md
Markdown
isc
152
/*- * 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; }
nicholaides/Methanol-Web-Crawler
src/libmetha/builtin.c
C
isc
6,361
/* 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; }
dennis95/dennix
libc/src/stdio/__file_write.c
C
isc
1,293
<?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); } }
la5942/argentum-invoice
application/controllers/admin/time.php
PHP
isc
1,554
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); }); }
bolav/fusepm
lib/fixunoproj.js
JavaScript
isc
752
import mod437 from './mod437'; var value=mod437+1; export default value;
MirekSz/webpack-es6-ts
app/mods/mod438.js
JavaScript
isc
73
<!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>
abdurrachman-habibi/azure-storage-studio
src/index.html
HTML
isc
1,608
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); }
rlemon/se-chat-dark-theme-plus
script.js
JavaScript
isc
4,901
'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(); }); }); });
tcort/link-check
test/link-check.test.js
JavaScript
isc
18,014
--- 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() ```
sethjackson/sethjackson.github.io
_posts/2017-11-27-more-office-interop-in-powershell.md
Markdown
isc
2,562
/* 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
dennis95/dennix
kernel/include/dennix/clock.h
C
isc
1,033
function daysLeftThisWeek (date) { return 6 - date.getDay() } module.exports = daysLeftThisWeek
akileez/toolz
src/date/daysLeftThisWeek.js
JavaScript
isc
99
#!/bin/bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" packer build -var-file="${DIR}/packer-vars.json" "${DIR}/packer.json"
datapipe/generator-bakery
generators/cm-puppet/templates/build.sh
Shell
isc
140
# Copyright (c) 2015, Max Fillinger <max@max-fillinger.net> # # 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. # The epub format specification is available at http://idpf.org/epub/201 '''Contains the EpubBuilder class to build epub2.0.1 files with the getebook module.''' import html import re import datetime import getebook import os.path import re import zipfile __all__ = ['EpubBuilder', 'EpubTOC', 'Author'] def _normalize(name): '''Transform "Firstname [Middlenames] Lastname" into "Lastname, Firstname [Middlenames]".''' split = name.split() if len(split) == 1: return name return split[-1] + ', ' + ' '.join(name[0:-1]) def _make_starttag(tag, attrs): 'Write a starttag.' out = '<' + tag for key in attrs: out += ' {}="{}"'.format(key, html.escape(attrs[key])) out += '>' return out def _make_xml_elem(tag, text, attr = []): 'Write a flat xml element.' out = ' <' + tag for (key, val) in attr: out += ' {}="{}"'.format(key, val) if text: out += '>{}</{}>\n'.format(text, tag) else: out += ' />\n' return out class EpubTOC(getebook.TOC): 'Table of contents.' _head = (( '<?xml version="1.0" encoding="UTF-8"?>\n' '<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en-US">\n' ' <head>\n' ' <meta name="dtb:uid" content="{}" />\n' ' <meta name="dtb:depth" content="{}" />\n' ' <meta name="dtb:totalPageCount" content="0" />\n' ' <meta name="dtb:maxPageNumber" content="0" />\n' ' </head>\n' ' <docTitle>\n' ' <text>{}</text>\n' ' </docTitle>\n' )) _doc_author = (( ' <docAuthor>\n' ' <text>{}</text>\n' ' </docAuthor>\n' )) _navp = (( '{0}<navPoint id="nav{1}">\n' '{0} <navLabel>\n' '{0} <text>{2}</text>\n' '{0} </navLabel>\n' '{0} <content src="{3}" />\n' )) def _navp_xml(self, entry, indent_lvl): 'Write xml for an entry and all its subentries.' xml = self._navp.format(' '*indent_lvl, str(entry.no), entry.text, entry.target) for sub in entry.entries: xml += self._navp_xml(sub, indent_lvl+1) xml += ' '*indent_lvl + '</navPoint>\n' return xml def write_xml(self, uid, title, authors): 'Write the xml code for the table of contents.' xml = self._head.format(uid, self.max_depth, title) for aut in authors: xml += self._doc_author.format(aut) xml += ' <navMap>\n' for entry in self.entries: xml += self._navp_xml(entry, 2) xml += ' </navMap>\n</ncx>' return xml class _Fileinfo: 'Information about a component file of an epub.' def __init__(self, name, in_spine = True, guide_title = None, guide_type = None): '''Initialize the object. If the file does not belong in the reading order, in_spine should be set to False. If it should appear in the guide, set guide_title and guide_type.''' self.name = name (self.ident, ext) = os.path.splitext(name) name_split = name.rsplit('.', 1) self.ident = name_split[0] self.in_spine = in_spine self.guide_title = guide_title self.guide_type = guide_type # Infer media-type from file extension ext = ext.lower() if ext in ('.htm', '.html', '.xhtml'): self.media_type = 'application/xhtml+xml' elif ext in ('.png', '.gif', '.jpeg'): self.media_type = 'image/' + ext elif ext == '.jpg': self.media_type = 'image/jpeg' elif ext == '.css': self.media_type = 'text/css' elif ext == '.ncx': self.media_type = 'application/x-dtbncx+xml' else: raise ValueError('Can\'t infer media-type from extension: %s' % ext) def manifest_entry(self): 'Write the XML element for the manifest.' return _make_xml_elem('item', '', [ ('href', self.name), ('id', self.ident), ('media-type', self.media_type) ]) def spine_entry(self): '''Write the XML element for the spine. (Empty string if in_spine is False.)''' if self.in_spine: return _make_xml_elem('itemref', '', [('idref', self.ident)]) else: return '' def guide_entry(self): '''Write the XML element for the guide. (Empty string if no guide title and type are given.)''' if self.guide_title and self.guide_type: return _make_xml_elem('reference', '', [ ('title', self.guide_title), ('type', self.guide_type), ('href', self.name) ]) else: return '' class _EpubMeta: 'Metadata entry for an epub file.' def __init__(self, tag, text, *args): '''The metadata entry is an XML element. *args is used for supplying the XML element's attributes as (key, value) pairs.''' self.tag = tag self.text = text self.attr = args def write_xml(self): 'Write the XML element.' return _make_xml_elem(self.tag, self.text, self.attr) def __repr__(self): 'Returns the text.' return self.text def __str__(self): 'Returns the text.' return self.text class _EpubDate(_EpubMeta): 'Metadata element for the publication date.' _date_re = re.compile('^([0-9]{4})(-[0-9]{2}(-[0-9]{2})?)?$') def __init__(self, date): '''date must be a string of the form "YYYY[-MM[-DD]]". If it is not of this form, or if the date is invalid, ValueError is raised.''' m = self._date_re.match(date) if not m: raise ValueError('invalid date format') year = int(m.group(1)) try: mon = int(m.group(2)[1:]) if mon < 0 or mon > 12: raise ValueError('month must be in 1..12') except IndexError: pass try: day = int(m.group(3)[1:]) datetime.date(year, mon, day) # raises ValueError if invalid except IndexError: pass self.tag = 'dc:date' self.text = date self.attr = () class _EpubLang(_EpubMeta): 'Metadata element for the language of the book.' _lang_re = re.compile('^[a-z]{2}(-[A-Z]{2})?$') def __init__(self, lang): '''lang must be a lower-case two-letter language code, optionally followed by a "-" and a upper-case two-letter country code. (e.g., "en", "en-US", "en-UK", "de", "de-DE", "de-AT")''' if self._lang_re.match(lang): self.tag = 'dc:language' self.text = lang self.attr = () else: raise ValueError('invalid language format') class Author(_EpubMeta): '''To control the file-as and role attribute for the authors, pass an Author object to the EpubBuilder instead of a string. The file-as attribute is a form of the name used for sorting. The role attribute describes how the person was involved in the work. You ONLY need this if an author's name is not of the form "Given-name Family-name", or if you want to specify a role other than author. Otherwise, you can just pass a string. The value of role should be a MARC relator, e.g., "aut" for author or "edt" for editor. See http://www.loc.gov/marc/relators/ for a full list.''' def __init__(self, name, fileas = None, role = 'aut'): '''Initialize the object. If the argument "fileas" is not given, "Last-name, First-name" is used for the file-as attribute. If the argument "role" is not given, "aut" is used for the role attribute.''' if not fileas: fileas = _normalize(name) self.tag = 'dc:creator' self.text = name self.attr = (('opf:file-as', fileas), ('opf:role', role)) class _OPFfile: '''Class for writing the OPF (Open Packaging Format) file for an epub file. The OPF file contains the metadata, a manifest of all component files in the epub, a "spine" which specifies the reading order and a guide which points to important components of the book such as the title page.''' _opf = ( '<?xml version="1.0" encoding="UTF-8"?>\n' '<package version="2.0" xmlns="http://www.idpf.org/2007/opf" unique_identifier="uid_id">\n' ' <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">\n' '{}' ' </metadata>\n' ' <manifest>\n' '{}' ' </manifest>\n' ' <spine toc="toc">\n' '{}' ' </spine>\n' ' <guide>\n' '{}' ' </guide>\n' '</package>\n' ) def __init__(self): 'Initialize.' self.meta = [] self.filelist = [] def write_xml(self): 'Write the XML code for the OPF file.' metadata = '' for elem in self.meta: metadata += elem.write_xml() manif = '' spine = '' guide = '' for finfo in self.filelist: manif += finfo.manifest_entry() spine += finfo.spine_entry() guide += finfo.guide_entry() return self._opf.format(metadata, manif, spine, guide) class EpubBuilder: '''Builds an epub2.0.1 file. Some of the attributes of this class (title, uid, lang) are marked as "mandatory" because they represent metadata that is required by the epub specification. If these attributes are left unset, default values will be used.''' _style_css = ( 'h1, h2, h3, h4, h5, h6 {\n' ' text-align: center;\n' '}\n' 'p {\n' ' text-align: justify;\n' ' margin-top: 0.125em;\n' ' margin-bottom: 0em;\n' ' text-indent: 1.0em;\n' '}\n' '.getebook-tp {\n' ' margin-top: 8em;\n' '}\n' '.getebook-tp-authors {\n' ' font-size: 2em;\n' ' text-align: center;\n' ' margin-bottom: 1em;\n' '}\n' '.getebook-tp-title {\n' ' font-weight: bold;\n' ' font-size: 3em;\n' ' text-align: center;\n' '}\n' '.getebook-tp-sub {\n' ' text-align: center;\n' ' font-weight: normal;\n' ' font-size: 0.8em;\n' ' margin-top: 1em;\n' '}\n' '.getebook-false-h {\n' ' font-weight: bold;\n' ' font-size: 1.5em;\n' '}\n' '.getebook-small-h {\n' ' font-style: normal;\n' ' font-weight: normal;\n' ' font-size: 0.8em;\n' '}\n' ) _container_xml = ( '<?xml version="1.0"?>\n' '<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">\n' ' <rootfiles>\n' ' <rootfile full-path="package.opf" media-type="application/oebps-package+xml"/>\n' ' </rootfiles>\n' '</container>\n' ) _html = ( '<?xml version="1.0" encoding="utf-8"?>\n' '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\n' '<html xmlns="http://www.w3.org/1999/xhtml">\n' ' <head>\n' ' <title>{}</title>\n' ' <meta http-equiv="content-type" content="application/xtml+xml; charset=utf-8" />\n' ' <link href="style.css" rel="stylesheet" type="text/css" />\n' ' </head>\n' ' <body>\n{}' ' </body>\n' '</html>\n' ) _finalized = False def __init__(self, epub_file): '''Initialize the EpubBuilder instance. "epub_file" is the filename of the epub to be created.''' self.epub_f = zipfile.ZipFile(epub_file, 'w', zipfile.ZIP_DEFLATED) self.epub_f.writestr('mimetype', 'application/epub+zip') self.epub_f.writestr('META-INF/container.xml', self._container_xml) self.toc = EpubTOC() self.opf = _OPFfile() self.opf.filelist.append(_Fileinfo('toc.ncx', False)) self.opf.filelist.append(_Fileinfo('style.css', False)) self._authors = [] self.opt_meta = {} # Optional metadata (other than authors) self.content = '' self.part_no = 0 self.cont_filename = 'part%03d.html' % self.part_no def __enter__(self): 'Return self for use in with ... as ... statement.' return self def __exit__(self, except_type, except_val, traceback): 'Call finalize() and close the file.' try: self.finalize() finally: # Close again in case an exception happened in finalize() self.epub_f.close() return False @property def uid(self): '''Unique identifier of the ebook. (mandatory) If this property is left unset, a pseudo-random string will be generated which is long enough for collisions with existing ebooks to be extremely unlikely.''' try: return self._uid except AttributeError: import random from string import (ascii_letters, digits) alnum = ascii_letters + digits self.uid = ''.join([random.choice(alnum) for i in range(15)]) return self._uid @uid.setter def uid(self, val): self._uid = _EpubMeta('dc:identifier', str(val), ('id', 'uid_id')) @property def title(self): '''Title of the ebook. (mandatory) If this property is left unset, it defaults to "Untitled".''' try: return self._title except AttributeError: self.title = 'Untitled' return self._title @title.setter def title(self, val): # If val is not a string, raise TypeError now rather than later. self._title = _EpubMeta('dc:title', '' + val) @property def lang(self): '''Language of the ebook. (mandatory) The language must be given as a lower-case two-letter code, optionally followed by a "-" and an upper-case two-letter country code. (e.g., "en", "en-US", "en-UK", "de", "de-DE", "de-AT") If this property is left unset, it defaults to "en".''' try: return self._lang except AttributeError: self.lang = 'en' return self._lang @lang.setter def lang(self, val): self._lang = _EpubLang(val) @property def author(self): '''Name of the author. (optional) If there are multiple authors, pass a list of strings. To control the file-as and role attribute, use author objects instead of strings; file-as is an alternate form of the name used for sorting. For a description of the role attribute, see the docstring of the author class.''' if len(self._authors) == 1: return self._authors[0] return tuple([aut for aut in self._authors]) @author.setter def author(self, val): if isinstance(val, Author) or isinstance(val, str): authors = [val] else: authors = val for aut in authors: try: self._authors.append(Author('' + aut)) except TypeError: # aut is not a string, so it should be an Author object self._authors.append(aut) @author.deleter def author(self): self._authors = [] @property def date(self): '''Publication date. (optional) Must be given in "YYYY[-MM[-DD]]" format.''' try: return self.opt_meta['date'] except KeyError: return None @date.setter def date(self, val): self.opt_meta['date'] = _EpubDate(val) @date.deleter def date(self): del self._date @property def rights(self): 'Copyright/licensing information. (optional)' try: return self.opt_meta['rights'] except KeyError: return None @rights.setter def rights(self, val): self.opt_meta['rights'] = _EpubMeta('dc:rights', '' + val) @rights.deleter def rights(self): del self._rights @property def publisher(self): 'Publisher name. (optional)' try: return self.opt_meta['publisher'] except KeyError: return None @publisher.setter def publisher(self, val): self.opt_meta['publisher'] = _EpubMeta('dc:publisher', '' + val) @publisher.deleter def publisher(self): del self._publisher @property def style_css(self): '''CSS stylesheet for the files that are generated by the EpubBuilder instance. Can be overwritten or extended, but not deleted.''' return self._style_css @style_css.setter def style_css(self, val): self._style_css = '' + val def titlepage(self, main_title = None, subtitle = None): '''Create a title page for the ebook. If no main_title is given, the title attribute of the EpubBuilder instance is used.''' tp = '<div class="getebook-tp">\n' if len(self._authors) >= 1: if len(self._authors) == 1: aut_str = str(self._authors[0]) else: aut_str = ', '.join(str(self._authors[0:-1])) + ', and ' \ + str(self._authors[-1]) tp += '<div class="getebook-tp-authors">%s</div>\n' % aut_str if not main_title: main_title = str(self.title) tp += '<div class="getebook-tp-title">%s' % main_title if subtitle: tp += '<div class="getebook-tp-sub">%s</div>' % subtitle tp += '</div>\n</div>\n' self.opf.filelist.insert(0, _Fileinfo('title.html', guide_title = 'Titlepage', guide_type = 'title-page')) self.epub_f.writestr('title.html', self._html.format(self.title, tp)) def headingpage(self, heading, subtitle = None, toc_text = None): '''Create a page containing only a (large) heading, optionally with a smaller subtitle. If toc_text is not given, it defaults to the heading.''' self.new_part() tag = 'h%d' % min(6, self.toc.depth) self.content += '<div class="getebook-tp">' self.content += '<{} class="getebook-tp-title">{}'.format(tag, heading) if subtitle: self.content += '<div class="getebook-tp-sub">%s</div>' % subtitle self.content += '</%s>\n' % tag if not toc_text: toc_text = heading self.toc.new_entry(toc_text, self.cont_filename) self.new_part() def insert_file(self, name, in_spine = False, guide_title = None, guide_type = None, arcname = None): '''Include an external file into the ebook. By default, it will be added to the archive under its basename; the argument "arcname" can be used to specify a different name.''' if not arcname: arcname = os.path.basename(name) self.opf.filelist.append(_Fileinfo(arcname, in_spine, guide_title, guide_type)) self.epub_f.write(name, arcname) def add_file(self, arcname, str_or_bytes, in_spine = False, guide_title = None, guide_type = None): '''Add the string or bytes instance str_or_bytes to the archive under the name arcname.''' self.opf.filelist.append(_Fileinfo(arcname, in_spine, guide_title, guide_type)) self.epub_f.writestr(arcname, str_or_bytes) def false_heading(self, elem): '''Handle a "false heading", i.e., text that appears in heading tags in the source even though it is not a chapter heading.''' elem.attrs['class'] = 'getebook-false-h' elem.tag = 'p' self.handle_elem(elem) def _heading(self, elem): '''Write a heading.''' # Handle paragraph heading if we have one waiting (see the # par_heading method). We don\'t use _handle_par_h here because # we merge it with the subsequent proper heading. try: par_h = self.par_h del self.par_h except AttributeError: toc_text = elem.text else: # There is a waiting paragraph heading, we merge it with the # new heading. toc_text = par_h.text + '. ' + elem.text par_h.tag = 'div' par_h.attrs['class'] = 'getebook-small-h' elem.children.insert(0, par_h) # Set the class attribute value. elem.attrs['class'] = 'getebook-chapter-h' self.toc.new_entry(toc_text, self.cont_filename) # Add heading to the epub. tag = 'h%d' % min(self.toc.depth, 6) self.content += _make_starttag(tag, elem.attrs) for elem in elem.children: self.handle_elem(elem) self.content += '</%s>\n' % tag def par_heading(self, elem): '''Handle a "paragraph heading", i.e., a chaper heading or part of a chapter heading inside paragraph tags. If it is immediately followed by a heading, they will be merged into one.''' self.par_h = elem def _handle_par_h(self): 'Check if there is a waiting paragraph heading and handle it.' try: self._heading(self.par_h) except AttributeError: pass def handle_elem(self, elem): 'Handle html element as supplied by getebook.EbookParser.' try: tag = elem.tag except AttributeError: # elem should be a string is_string = True tag = None else: is_string = False if tag in getebook._headings: self._heading(elem) else: # Handle waiting par_h if necessary (see par_heading) try: self._heading(self.par_h) except AttributeError: pass if is_string: self.content += elem elif tag == 'br': self.content += '<br />\n' elif tag == 'img': self.content += self._handle_image(elem.attrs) + '\n' elif tag == 'a' or tag == 'noscript': # Ignore tag, just write child elements for child in elem.children: self.handle_elem(child) else: self.content += _make_starttag(tag, elem.attrs) for child in elem.children: self.handle_elem(child) self.content += '</%s>' % tag if tag == 'p': self.content += '\n' def _handle_image(self, attrs): 'Returns the alt text of an image tag.' try: return attrs['alt'] except KeyError: return '' def new_part(self): '''Begin a new part of the epub. Write the current html document to the archive and begin a new one.''' # Handle waiting par_h (see par_heading) try: self._heading(self.par_h) except AttributeError: pass if self.content: html = self._html.format(self.title, self.content) self.epub_f.writestr(self.cont_filename, html) self.part_no += 1 self.content = '' self.cont_filename = 'part%03d.html' % self.part_no self.opf.filelist.append(_Fileinfo(self.cont_filename)) def finalize(self): 'Complete and close the epub file.' # Handle waiting par_h (see par_heading) if self._finalized: # Avoid finalizing twice. Otherwise, calling finalize inside # a with-block would lead to an exception when __exit__ # calls finalize again. return try: self._heading(self.par_h) except AttributeError: pass if self.content: html = self._html.format(self.title, self.content) self.epub_f.writestr(self.cont_filename, html) self.opf.meta = [self.uid, self.lang, self.title] + self._authors self.opf.meta += self.opt_meta.values() self.epub_f.writestr('package.opf', self.opf.write_xml()) self.epub_f.writestr('toc.ncx', self.toc.write_xml(self.uid, self.title, self._authors)) self.epub_f.writestr('style.css', self._style_css) self.epub_f.close() self._finalized = True
mfil/getebook
getebook/epub.py
Python
isc
25,314
CREATE TABLE <table-name>_nf ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `request_uri` VARCHAR(255) NOT NULL, `referrer` VARCHAR(255) DEFAULT '', `user_agent` VARCHAR(255) DEFAULT '', `created_at` TIMESTAMP, PRIMARY KEY (id) ) ENGINE = MyISAM DEFAULT CHARSET=utf8;
rockettpw/jumplinks
Blueprints/schema-update-v4.sql
SQL
isc
289
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. */ #include <sys/types.h> #include <ctype.h> #include <errno.h> #include <devid.h> #include <fcntl.h> #include <libintl.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <dlfcn.h> #include <unistd.h> #include <sys/efi_partition.h> #include <sys/vtoc.h> #include <sys/stat.h> #include <sys/zfs_ioctl.h> #include "zfs_namecheck.h" #include "zfs_prop.h" #include "libzfs_impl.h" #include "zfs_comutil.h" #include "format.h" #include <syslog.h> /*static int read_efi_label(nvlist_t *config, diskaddr_t *sb);*/ #if defined(__i386) || defined(__amd64) #define BOOTCMD "installgrub(1M)" #else #define BOOTCMD "installboot(1M)" #endif #define DISK_ROOT "/dev" #define RDISK_ROOT "/dev" #define BACKUP_SLICE "s2" /* * ==================================================================== * zpool property functions * ==================================================================== */ static int zpool_get_all_props(zpool_handle_t *zhp) { zfs_cmd_t zc = { 0 }; libzfs_handle_t *hdl = zhp->zpool_hdl; (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); if (zcmd_alloc_dst_nvlist(hdl, &zc, 0) != 0) return (-1); while (ioctl(hdl->libzfs_fd, ZFS_IOC_POOL_GET_PROPS, &zc) != 0) { if (errno == ENOMEM) { if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) { zcmd_free_nvlists(&zc); return (-1); } } else { zcmd_free_nvlists(&zc); return (-1); } } if (zcmd_read_dst_nvlist(hdl, &zc, &zhp->zpool_props) != 0) { zcmd_free_nvlists(&zc); return (-1); } zcmd_free_nvlists(&zc); return (0); } static int zpool_props_refresh(zpool_handle_t *zhp) { nvlist_t *old_props; old_props = zhp->zpool_props; if (zpool_get_all_props(zhp) != 0) return (-1); nvlist_free(old_props); return (0); } static char * zpool_get_prop_string(zpool_handle_t *zhp, zpool_prop_t prop, zprop_source_t *src) { nvlist_t *nv, *nvl; uint64_t ival; char *value; zprop_source_t source; nvl = zhp->zpool_props; if (nvlist_lookup_nvlist(nvl, zpool_prop_to_name(prop), &nv) == 0) { verify(nvlist_lookup_uint64(nv, ZPROP_SOURCE, &ival) == 0); source = ival; verify(nvlist_lookup_string(nv, ZPROP_VALUE, &value) == 0); } else { source = ZPROP_SRC_DEFAULT; if ((value = (char *)zpool_prop_default_string(prop)) == NULL) value = "-"; } if (src) *src = source; return (value); } uint64_t zpool_get_prop_int(zpool_handle_t *zhp, zpool_prop_t prop, zprop_source_t *src) { nvlist_t *nv, *nvl; uint64_t value; zprop_source_t source; if (zhp->zpool_props == NULL && zpool_get_all_props(zhp)) { /* * zpool_get_all_props() has most likely failed because * the pool is faulted, but if all we need is the top level * vdev's guid then get it from the zhp config nvlist. */ if ((prop == ZPOOL_PROP_GUID) && (nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE, &nv) == 0) && (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &value) == 0)) { return (value); } return (zpool_prop_default_numeric(prop)); } nvl = zhp->zpool_props; if (nvlist_lookup_nvlist(nvl, zpool_prop_to_name(prop), &nv) == 0) { verify(nvlist_lookup_uint64(nv, ZPROP_SOURCE, &value) == 0); source = value; verify(nvlist_lookup_uint64(nv, ZPROP_VALUE, &value) == 0); } else { source = ZPROP_SRC_DEFAULT; value = zpool_prop_default_numeric(prop); } if (src) *src = source; return (value); } /* * Map VDEV STATE to printed strings. */ char * zpool_state_to_name(vdev_state_t state, vdev_aux_t aux) { switch (state) { case VDEV_STATE_CLOSED: case VDEV_STATE_OFFLINE: return (gettext("OFFLINE")); case VDEV_STATE_REMOVED: return (gettext("REMOVED")); case VDEV_STATE_CANT_OPEN: if (aux == VDEV_AUX_CORRUPT_DATA || aux == VDEV_AUX_BAD_LOG) return (gettext("FAULTED")); else if (aux == VDEV_AUX_SPLIT_POOL) return (gettext("SPLIT")); else return (gettext("UNAVAIL")); case VDEV_STATE_FAULTED: return (gettext("FAULTED")); case VDEV_STATE_DEGRADED: return (gettext("DEGRADED")); case VDEV_STATE_HEALTHY: return (gettext("ONLINE")); } return (gettext("UNKNOWN")); } /* * Get a zpool property value for 'prop' and return the value in * a pre-allocated buffer. */ int zpool_get_prop(zpool_handle_t *zhp, zpool_prop_t prop, char *buf, size_t len, zprop_source_t *srctype) { uint64_t intval; const char *strval; zprop_source_t src = ZPROP_SRC_NONE; nvlist_t *nvroot; vdev_stat_t *vs; uint_t vsc; if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) { switch (prop) { case ZPOOL_PROP_NAME: (void) strlcpy(buf, zpool_get_name(zhp), len); break; case ZPOOL_PROP_HEALTH: (void) strlcpy(buf, "FAULTED", len); break; case ZPOOL_PROP_GUID: intval = zpool_get_prop_int(zhp, prop, &src); (void) snprintf(buf, len, "%llu", (long long unsigned int)intval); break; case ZPOOL_PROP_ALTROOT: case ZPOOL_PROP_CACHEFILE: if (zhp->zpool_props != NULL || zpool_get_all_props(zhp) == 0) { (void) strlcpy(buf, zpool_get_prop_string(zhp, prop, &src), len); if (srctype != NULL) *srctype = src; return (0); } /* FALLTHROUGH */ default: (void) strlcpy(buf, "-", len); break; } if (srctype != NULL) *srctype = src; return (0); } if (zhp->zpool_props == NULL && zpool_get_all_props(zhp) && prop != ZPOOL_PROP_NAME) return (-1); switch (zpool_prop_get_type(prop)) { case PROP_TYPE_STRING: (void) strlcpy(buf, zpool_get_prop_string(zhp, prop, &src), len); break; case PROP_TYPE_NUMBER: intval = zpool_get_prop_int(zhp, prop, &src); switch (prop) { case ZPOOL_PROP_SIZE: case ZPOOL_PROP_ALLOCATED: case ZPOOL_PROP_FREE: (void) zfs_nicenum(intval, buf, len); break; case ZPOOL_PROP_CAPACITY: (void) snprintf(buf, len, "%llu%%", (u_longlong_t)intval); break; case ZPOOL_PROP_DEDUPRATIO: (void) snprintf(buf, len, "%llu.%02llux", (u_longlong_t)(intval / 100), (u_longlong_t)(intval % 100)); break; case ZPOOL_PROP_HEALTH: verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL), ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0); verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc) == 0); (void) strlcpy(buf, zpool_state_to_name(intval, vs->vs_aux), len); break; default: (void) snprintf(buf, len, "%llu", (u_longlong_t) intval); } break; case PROP_TYPE_INDEX: intval = zpool_get_prop_int(zhp, prop, &src); if (zpool_prop_index_to_string(prop, intval, &strval) != 0) return (-1); (void) strlcpy(buf, strval, len); break; default: abort(); } if (srctype) *srctype = src; return (0); } /* * Check if the bootfs name has the same pool name as it is set to. * Assuming bootfs is a valid dataset name. */ static boolean_t bootfs_name_valid(const char *pool, char *bootfs) { int len = strlen(pool); if (!zfs_name_valid(bootfs, ZFS_TYPE_FILESYSTEM|ZFS_TYPE_SNAPSHOT)) return (B_FALSE); if (strncmp(pool, bootfs, len) == 0 && (bootfs[len] == '/' || bootfs[len] == '\0')) return (B_TRUE); return (B_FALSE); } /* * Inspect the configuration to determine if any of the devices contain * an EFI label. */ /* ZFSFUSE: disabled */ #if 0 static boolean_t pool_uses_efi(nvlist_t *config) { nvlist_t **child; uint_t c, children; if (nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_CHILDREN, &child, &children) != 0) return (read_efi_label(config, NULL) >= 0); for (c = 0; c < children; c++) { if (pool_uses_efi(child[c])) return (B_TRUE); } return (B_FALSE); } #endif static boolean_t pool_is_bootable(zpool_handle_t *zhp) { char bootfs[ZPOOL_MAXNAMELEN]; return (zpool_get_prop(zhp, ZPOOL_PROP_BOOTFS, bootfs, sizeof (bootfs), NULL) == 0 && strncmp(bootfs, "-", sizeof (bootfs)) != 0); } /* * Given an nvlist of zpool properties to be set, validate that they are * correct, and parse any numeric properties (index, boolean, etc) if they are * specified as strings. */ static nvlist_t * zpool_valid_proplist(libzfs_handle_t *hdl, const char *poolname, nvlist_t *props, uint64_t version, boolean_t create_or_import, char *errbuf) { nvpair_t *elem; nvlist_t *retprops; zpool_prop_t prop; char *strval; uint64_t intval; char *slash; struct stat64 statbuf; zpool_handle_t *zhp; nvlist_t *nvroot; if (nvlist_alloc(&retprops, NV_UNIQUE_NAME, 0) != 0) { (void) no_memory(hdl); return (NULL); } elem = NULL; while ((elem = nvlist_next_nvpair(props, elem)) != NULL) { const char *propname = nvpair_name(elem); /* * Make sure this property is valid and applies to this type. */ if ((prop = zpool_name_to_prop(propname)) == ZPROP_INVAL) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid property '%s'"), propname); (void) zfs_error(hdl, EZFS_BADPROP, errbuf); goto error; } if (zpool_prop_readonly(prop)) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' " "is readonly"), propname); (void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf); goto error; } if (zprop_parse_value(hdl, elem, prop, ZFS_TYPE_POOL, retprops, &strval, &intval, errbuf) != 0) goto error; /* * Perform additional checking for specific properties. */ switch (prop) { case ZPOOL_PROP_VERSION: if (intval < version || intval > SPA_VERSION) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "property '%s' number %d is invalid."), propname, intval); (void) zfs_error(hdl, EZFS_BADVERSION, errbuf); goto error; } break; case ZPOOL_PROP_BOOTFS: if (create_or_import) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "property '%s' cannot be set at creation " "or import time"), propname); (void) zfs_error(hdl, EZFS_BADPROP, errbuf); goto error; } if (version < SPA_VERSION_BOOTFS) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be upgraded to support " "'%s' property"), propname); (void) zfs_error(hdl, EZFS_BADVERSION, errbuf); goto error; } /* * bootfs property value has to be a dataset name and * the dataset has to be in the same pool as it sets to. */ if (strval[0] != '\0' && !bootfs_name_valid(poolname, strval)) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' " "is an invalid name"), strval); (void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf); goto error; } if ((zhp = zpool_open_canfail(hdl, poolname)) == NULL) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "could not open pool '%s'"), poolname); (void) zfs_error(hdl, EZFS_OPENFAILED, errbuf); goto error; } verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL), ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0); /* * bootfs property cannot be set on a disk which has * been EFI labeled. */ /* ZFSFUSE: disabled */ /*if (pool_uses_efi(nvroot)) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "property '%s' not supported on " "EFI labeled devices"), propname); (void) zfs_error(hdl, EZFS_POOL_NOTSUP, errbuf); zpool_close(zhp); goto error; }*/ zpool_close(zhp); break; case ZPOOL_PROP_ALTROOT: if (!create_or_import) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "property '%s' can only be set during pool " "creation or import"), propname); (void) zfs_error(hdl, EZFS_BADPROP, errbuf); goto error; } if (strval[0] != '/') { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "bad alternate root '%s'"), strval); (void) zfs_error(hdl, EZFS_BADPATH, errbuf); goto error; } break; case ZPOOL_PROP_CACHEFILE: if (strval[0] == '\0') break; if (strcmp(strval, "none") == 0) break; if (strval[0] != '/') { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "property '%s' must be empty, an " "absolute path, or 'none'"), propname); (void) zfs_error(hdl, EZFS_BADPATH, errbuf); goto error; } slash = strrchr(strval, '/'); if (slash[1] == '\0' || strcmp(slash, "/.") == 0 || strcmp(slash, "/..") == 0) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' is not a valid file"), strval); (void) zfs_error(hdl, EZFS_BADPATH, errbuf); goto error; } *slash = '\0'; if (strval[0] != '\0' && (stat64(strval, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' is not a valid directory"), strval); (void) zfs_error(hdl, EZFS_BADPATH, errbuf); goto error; } *slash = '/'; break; } } return (retprops); error: nvlist_free(retprops); return (NULL); } /* * Set zpool property : propname=propval. */ int zpool_set_prop(zpool_handle_t *zhp, const char *propname, const char *propval) { zfs_cmd_t zc = { 0 }; int ret = -1; char errbuf[1024]; nvlist_t *nvl = NULL; nvlist_t *realprops; uint64_t version; (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN, "cannot set property for '%s'"), zhp->zpool_name); if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) return (no_memory(zhp->zpool_hdl)); if (nvlist_add_string(nvl, propname, propval) != 0) { nvlist_free(nvl); return (no_memory(zhp->zpool_hdl)); } version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL); if ((realprops = zpool_valid_proplist(zhp->zpool_hdl, zhp->zpool_name, nvl, version, B_FALSE, errbuf)) == NULL) { nvlist_free(nvl); return (-1); } nvlist_free(nvl); nvl = realprops; /* * Execute the corresponding ioctl() to set this property. */ (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); if (zcmd_write_src_nvlist(zhp->zpool_hdl, &zc, nvl) != 0) { nvlist_free(nvl); return (-1); } ret = zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_SET_PROPS, &zc); zcmd_free_nvlists(&zc); nvlist_free(nvl); if (ret) (void) zpool_standard_error(zhp->zpool_hdl, errno, errbuf); else (void) zpool_props_refresh(zhp); return (ret); } int zpool_expand_proplist(zpool_handle_t *zhp, zprop_list_t **plp) { libzfs_handle_t *hdl = zhp->zpool_hdl; zprop_list_t *entry; char buf[ZFS_MAXPROPLEN]; if (zprop_expand_list(hdl, plp, ZFS_TYPE_POOL) != 0) return (-1); for (entry = *plp; entry != NULL; entry = entry->pl_next) { if (entry->pl_fixed) continue; if (entry->pl_prop != ZPROP_INVAL && zpool_get_prop(zhp, entry->pl_prop, buf, sizeof (buf), NULL) == 0) { if (strlen(buf) > entry->pl_width) entry->pl_width = strlen(buf); } } return (0); } /* * Don't start the slice at the default block of 34; many storage * devices will use a stripe width of 128k, so start there instead. */ #define NEW_START_BLOCK 256 /* * Validate the given pool name, optionally putting an extended error message in * 'buf'. */ boolean_t zpool_name_valid(libzfs_handle_t *hdl, boolean_t isopen, const char *pool) { namecheck_err_t why; char what; int ret; ret = pool_namecheck(pool, &why, &what); /* * The rules for reserved pool names were extended at a later point. * But we need to support users with existing pools that may now be * invalid. So we only check for this expanded set of names during a * create (or import), and only in userland. */ if (ret == 0 && !isopen && (strncmp(pool, "mirror", 6) == 0 || strncmp(pool, "raidz", 5) == 0 || strncmp(pool, "spare", 5) == 0 || strcmp(pool, "log") == 0)) { if (hdl != NULL) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "name is reserved")); return (B_FALSE); } if (ret != 0) { if (hdl != NULL) { switch (why) { case NAME_ERR_TOOLONG: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "name is too long")); break; case NAME_ERR_INVALCHAR: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid character " "'%c' in pool name"), what); break; case NAME_ERR_NOLETTER: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "name must begin with a letter")); break; case NAME_ERR_RESERVED: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "name is reserved")); break; case NAME_ERR_DISKLIKE: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool name is reserved")); break; case NAME_ERR_LEADING_SLASH: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "leading slash in name")); break; case NAME_ERR_EMPTY_COMPONENT: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "empty component in name")); break; case NAME_ERR_TRAILING_SLASH: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "trailing slash in name")); break; case NAME_ERR_MULTIPLE_AT: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "multiple '@' delimiters in name")); break; } } return (B_FALSE); } return (B_TRUE); } /* * Open a handle to the given pool, even if the pool is currently in the FAULTED * state. */ zpool_handle_t * zpool_open_canfail(libzfs_handle_t *hdl, const char *pool) { zpool_handle_t *zhp; boolean_t missing; /* * Make sure the pool name is valid. */ if (!zpool_name_valid(hdl, B_TRUE, pool)) { (void) zfs_error_fmt(hdl, EZFS_INVALIDNAME, dgettext(TEXT_DOMAIN, "cannot open '%s'"), pool); return (NULL); } if ((zhp = zfs_alloc(hdl, sizeof (zpool_handle_t))) == NULL) return (NULL); zhp->zpool_hdl = hdl; (void) strlcpy(zhp->zpool_name, pool, sizeof (zhp->zpool_name)); if (zpool_refresh_stats(zhp, &missing) != 0) { zpool_close(zhp); return (NULL); } if (missing) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "no such pool")); (void) zfs_error_fmt(hdl, EZFS_NOENT, dgettext(TEXT_DOMAIN, "cannot open '%s'"), pool); zpool_close(zhp); return (NULL); } return (zhp); } /* * Like the above, but silent on error. Used when iterating over pools (because * the configuration cache may be out of date). */ int zpool_open_silent(libzfs_handle_t *hdl, const char *pool, zpool_handle_t **ret) { zpool_handle_t *zhp; boolean_t missing; if ((zhp = zfs_alloc(hdl, sizeof (zpool_handle_t))) == NULL) return (-1); zhp->zpool_hdl = hdl; (void) strlcpy(zhp->zpool_name, pool, sizeof (zhp->zpool_name)); if (zpool_refresh_stats(zhp, &missing) != 0) { zpool_close(zhp); return (-1); } if (missing) { zpool_close(zhp); *ret = NULL; return (0); } *ret = zhp; return (0); } /* * Similar to zpool_open_canfail(), but refuses to open pools in the faulted * state. */ zpool_handle_t * zpool_open(libzfs_handle_t *hdl, const char *pool) { zpool_handle_t *zhp; if ((zhp = zpool_open_canfail(hdl, pool)) == NULL) return (NULL); if (zhp->zpool_state == POOL_STATE_UNAVAIL) { (void) zfs_error_fmt(hdl, EZFS_POOLUNAVAIL, dgettext(TEXT_DOMAIN, "cannot open '%s'"), zhp->zpool_name); zpool_close(zhp); return (NULL); } return (zhp); } /* * Close the handle. Simply frees the memory associated with the handle. */ void zpool_close(zpool_handle_t *zhp) { if (zhp->zpool_config) nvlist_free(zhp->zpool_config); if (zhp->zpool_old_config) nvlist_free(zhp->zpool_old_config); if (zhp->zpool_props) nvlist_free(zhp->zpool_props); free(zhp); } /* * Return the name of the pool. */ const char * zpool_get_name(zpool_handle_t *zhp) { return (zhp->zpool_name); } /* * Return the state of the pool (ACTIVE or UNAVAILABLE) */ int zpool_get_state(zpool_handle_t *zhp) { return (zhp->zpool_state); } /* * Create the named pool, using the provided vdev list. It is assumed * that the consumer has already validated the contents of the nvlist, so we * don't have to worry about error semantics. */ int zpool_create(libzfs_handle_t *hdl, const char *pool, nvlist_t *nvroot, nvlist_t *props, nvlist_t *fsprops) { zfs_cmd_t zc = { 0 }; nvlist_t *zc_fsprops = NULL; nvlist_t *zc_props = NULL; char msg[1024]; char *altroot; int ret = -1; (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot create '%s'"), pool); if (!zpool_name_valid(hdl, B_FALSE, pool)) return (zfs_error(hdl, EZFS_INVALIDNAME, msg)); if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0) return (-1); if (props) { if ((zc_props = zpool_valid_proplist(hdl, pool, props, SPA_VERSION_1, B_TRUE, msg)) == NULL) { goto create_failed; } } if (fsprops) { uint64_t zoned; char *zonestr; zoned = ((nvlist_lookup_string(fsprops, zfs_prop_to_name(ZFS_PROP_ZONED), &zonestr) == 0) && strcmp(zonestr, "on") == 0); if ((zc_fsprops = zfs_valid_proplist(hdl, ZFS_TYPE_FILESYSTEM, fsprops, zoned, NULL, msg)) == NULL) { goto create_failed; } if (!zc_props && (nvlist_alloc(&zc_props, NV_UNIQUE_NAME, 0) != 0)) { goto create_failed; } if (nvlist_add_nvlist(zc_props, ZPOOL_ROOTFS_PROPS, zc_fsprops) != 0) { goto create_failed; } } if (zc_props && zcmd_write_src_nvlist(hdl, &zc, zc_props) != 0) goto create_failed; (void) strlcpy(zc.zc_name, pool, sizeof (zc.zc_name)); if ((ret = zfs_ioctl(hdl, ZFS_IOC_POOL_CREATE, &zc)) != 0) { zcmd_free_nvlists(&zc); nvlist_free(zc_props); nvlist_free(zc_fsprops); switch (errno) { case EBUSY: /* * This can happen if the user has specified the same * device multiple times. We can't reliably detect this * until we try to add it and see we already have a * label. */ zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "one or more vdevs refer to the same device")); return (zfs_error(hdl, EZFS_BADDEV, msg)); case EOVERFLOW: /* * This occurs when one of the devices is below * SPA_MINDEVSIZE. Unfortunately, we can't detect which * device was the problem device since there's no * reliable way to determine device size from userland. */ { char buf[64]; zfs_nicenum(SPA_MINDEVSIZE, buf, sizeof (buf)); zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "one or more devices is less than the " "minimum size (%s)"), buf); } return (zfs_error(hdl, EZFS_BADDEV, msg)); case ENOSPC: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "one or more devices is out of space")); return (zfs_error(hdl, EZFS_BADDEV, msg)); case ENOTBLK: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cache device must be a disk or disk slice")); return (zfs_error(hdl, EZFS_BADDEV, msg)); default: return (zpool_standard_error(hdl, errno, msg)); } } /* * If this is an alternate root pool, then we automatically set the * mountpoint of the root dataset to be '/'. */ if (nvlist_lookup_string(props, zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot) == 0) { zfs_handle_t *zhp; verify((zhp = zfs_open(hdl, pool, ZFS_TYPE_DATASET)) != NULL); verify(zfs_prop_set(zhp, zfs_prop_to_name(ZFS_PROP_MOUNTPOINT), "/") == 0); zfs_close(zhp); } create_failed: zcmd_free_nvlists(&zc); nvlist_free(zc_props); nvlist_free(zc_fsprops); return (ret); } /* * Destroy the given pool. It is up to the caller to ensure that there are no * datasets left in the pool. */ int zpool_destroy(zpool_handle_t *zhp) { zfs_cmd_t zc = { 0 }; zfs_handle_t *zfp = NULL; libzfs_handle_t *hdl = zhp->zpool_hdl; char msg[1024]; if (zhp->zpool_state == POOL_STATE_ACTIVE && (zfp = zfs_open(zhp->zpool_hdl, zhp->zpool_name, ZFS_TYPE_FILESYSTEM)) == NULL) return (-1); (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_DESTROY, &zc) != 0) { (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot destroy '%s'"), zhp->zpool_name); if (errno == EROFS) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "one or more devices is read only")); (void) zfs_error(hdl, EZFS_BADDEV, msg); } else { (void) zpool_standard_error(hdl, errno, msg); } if (zfp) zfs_close(zfp); return (-1); } if (zfp) { remove_mountpoint(zfp); zfs_close(zfp); } return (0); } /* * Add the given vdevs to the pool. The caller must have already performed the * necessary verification to ensure that the vdev specification is well-formed. */ int zpool_add(zpool_handle_t *zhp, nvlist_t *nvroot) { zfs_cmd_t zc = { 0 }; int ret; libzfs_handle_t *hdl = zhp->zpool_hdl; char msg[1024]; nvlist_t **spares, **l2cache; uint_t nspares, nl2cache; (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot add to '%s'"), zhp->zpool_name); if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) < SPA_VERSION_SPARES && nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be " "upgraded to add hot spares")); return (zfs_error(hdl, EZFS_BADVERSION, msg)); } #if 0 if (pool_is_bootable(zhp) && nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0) { uint64_t s; for (s = 0; s < nspares; s++) { char *path; if (nvlist_lookup_string(spares[s], ZPOOL_CONFIG_PATH, &path) == 0 && pool_uses_efi(spares[s])) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "device '%s' contains an EFI label and " "cannot be used on root pools."), zpool_vdev_name(hdl, NULL, spares[s], B_FALSE)); return (zfs_error(hdl, EZFS_POOL_NOTSUP, msg)); } } } #endif if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) < SPA_VERSION_L2CACHE && nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be " "upgraded to add cache devices")); return (zfs_error(hdl, EZFS_BADVERSION, msg)); } if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0) return (-1); (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_VDEV_ADD, &zc) != 0) { switch (errno) { case EBUSY: /* * This can happen if the user has specified the same * device multiple times. We can't reliably detect this * until we try to add it and see we already have a * label. */ zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "one or more vdevs refer to the same device")); (void) zfs_error(hdl, EZFS_BADDEV, msg); break; case EOVERFLOW: /* * This occurrs when one of the devices is below * SPA_MINDEVSIZE. Unfortunately, we can't detect which * device was the problem device since there's no * reliable way to determine device size from userland. */ { char buf[64]; zfs_nicenum(SPA_MINDEVSIZE, buf, sizeof (buf)); zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "device is less than the minimum " "size (%s)"), buf); } (void) zfs_error(hdl, EZFS_BADDEV, msg); break; case ENOTSUP: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be upgraded to add these vdevs")); (void) zfs_error(hdl, EZFS_BADVERSION, msg); break; case EDOM: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "root pool can not have multiple vdevs" " or separate logs")); (void) zfs_error(hdl, EZFS_POOL_NOTSUP, msg); break; case ENOTBLK: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cache device must be a disk or disk slice")); (void) zfs_error(hdl, EZFS_BADDEV, msg); break; default: (void) zpool_standard_error(hdl, errno, msg); } ret = -1; } else { ret = 0; } zcmd_free_nvlists(&zc); return (ret); } /* * Exports the pool from the system. The caller must ensure that there are no * mounted datasets in the pool. */ int zpool_export_common(zpool_handle_t *zhp, boolean_t force, boolean_t hardforce) { zfs_cmd_t zc = { 0 }; char msg[1024]; (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot export '%s'"), zhp->zpool_name); (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); zc.zc_cookie = force; zc.zc_guid = hardforce; #define ZFSFUSE_BUSY_SLEEP_FACTOR 500000 // .5 seconds was chosen ater some tuning int retry = 0; int ret; while ((ret = zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_EXPORT, &zc)) == EBUSY && retry++ < 6) { struct timeval timeout; /* Something in the way zfs-fuse works keeps the datasets busy for * longer than expected. * If we try to export/destroy a pool containing a few fs like * pool/fs1/fs2, then it will try to export it much before the umounts * are really finished. * The sleep is a temporary workaround here. * The zfsfuse_destroy function is called after umount has already * returned, so the only solution is to allow a pause here in case the * export fails with EBUSY */ timeout.tv_sec=0; timeout.tv_usec=ZFSFUSE_BUSY_SLEEP_FACTOR; VERIFY(select(0,NULL,NULL,NULL,&timeout)==0); } if (retry>0) syslog(LOG_WARNING, "Pool '%s' was busy, export was tried for %0.1fs (%i attempts) resulting in %s", zhp->zpool_name, (retry*ZFSFUSE_BUSY_SLEEP_FACTOR)/100000.0, retry, strerror(errno)); if (ret != 0) { switch (errno) { case EXDEV: zfs_error_aux(zhp->zpool_hdl, dgettext(TEXT_DOMAIN, "use '-f' to override the following errors:\n" "'%s' has an active shared spare which could be" " used by other pools once '%s' is exported."), zhp->zpool_name, zhp->zpool_name); return (zfs_error(zhp->zpool_hdl, EZFS_ACTIVE_SPARE, msg)); default: return (zpool_standard_error_fmt(zhp->zpool_hdl, errno, msg)); } } return (0); } int zpool_export(zpool_handle_t *zhp, boolean_t force) { return (zpool_export_common(zhp, force, B_FALSE)); } int zpool_export_force(zpool_handle_t *zhp) { return (zpool_export_common(zhp, B_TRUE, B_TRUE)); } static void zpool_rewind_exclaim(libzfs_handle_t *hdl, const char *name, boolean_t dryrun, nvlist_t *rbi) { uint64_t rewindto; int64_t loss = -1; struct tm t; char timestr[128]; if (!hdl->libzfs_printerr || rbi == NULL) return; if (nvlist_lookup_uint64(rbi, ZPOOL_CONFIG_LOAD_TIME, &rewindto) != 0) return; (void) nvlist_lookup_int64(rbi, ZPOOL_CONFIG_REWIND_TIME, &loss); if (localtime_r((time_t *)&rewindto, &t) != NULL && strftime(timestr, 128, "%F", &t) != 0) { if (dryrun) { (void) printf(dgettext(TEXT_DOMAIN, "Would be able to return %s " "to its state as of %s.\n"), name, timestr); } else { (void) printf(dgettext(TEXT_DOMAIN, "Pool %s returned to its state as of %s.\n"), name, timestr); } if (loss > 120) { (void) printf(dgettext(TEXT_DOMAIN, "%s approximately " FI64 " "), dryrun ? "Would discard" : "Discarded", (loss + 30) / 60); (void) printf(dgettext(TEXT_DOMAIN, "minutes of transactions.\n")); } else if (loss > 0) { (void) printf(dgettext(TEXT_DOMAIN, "%s approximately " FI64 " "), dryrun ? "Would discard" : "Discarded", loss); (void) printf(dgettext(TEXT_DOMAIN, "seconds of transactions.\n")); } } } void zpool_explain_recover(libzfs_handle_t *hdl, const char *name, int reason, nvlist_t *config) { int64_t loss = -1; uint64_t edata = UINT64_MAX; uint64_t rewindto; struct tm t; char timestr[128]; if (!hdl->libzfs_printerr) return; if (reason >= 0) (void) printf(dgettext(TEXT_DOMAIN, "action: ")); else (void) printf(dgettext(TEXT_DOMAIN, "\t")); /* All attempted rewinds failed if ZPOOL_CONFIG_LOAD_TIME missing */ if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_LOAD_TIME, &rewindto) != 0) goto no_info; (void) nvlist_lookup_int64(config, ZPOOL_CONFIG_REWIND_TIME, &loss); (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_LOAD_DATA_ERRORS, &edata); (void) printf(dgettext(TEXT_DOMAIN, "Recovery is possible, but will result in some data loss.\n")); if (localtime_r((time_t *)&rewindto, &t) != NULL && strftime(timestr, 128, "%F", &t) != 0) { (void) printf(dgettext(TEXT_DOMAIN, "\tReturning the pool to its state as of %s\n" "\tshould correct the problem. "), timestr); } else { (void) printf(dgettext(TEXT_DOMAIN, "\tReverting the pool to an earlier state " "should correct the problem.\n\t")); } if (loss > 120) { (void) printf(dgettext(TEXT_DOMAIN, "Approximately " FI64 " minutes of data\n" "\tmust be discarded, irreversibly. "), (loss + 30) / 60); } else if (loss > 0) { (void) printf(dgettext(TEXT_DOMAIN, "Approximately " FI64 " seconds of data\n" "\tmust be discarded, irreversibly. "), loss); } if (edata != 0 && edata != UINT64_MAX) { if (edata == 1) { (void) printf(dgettext(TEXT_DOMAIN, "After rewind, at least\n" "\tone persistent user-data error will remain. ")); } else { (void) printf(dgettext(TEXT_DOMAIN, "After rewind, several\n" "\tpersistent user-data errors will remain. ")); } } (void) printf(dgettext(TEXT_DOMAIN, "Recovery can be attempted\n\tby executing 'zpool %s -F %s'. "), reason >= 0 ? "clear" : "import", name); (void) printf(dgettext(TEXT_DOMAIN, "A scrub of the pool\n" "\tis strongly recommended after recovery.\n")); return; no_info: (void) printf(dgettext(TEXT_DOMAIN, "Destroy and re-create the pool from\n\ta backup source.\n")); } /* * zpool_import() is a contracted interface. Should be kept the same * if possible. * * Applications should use zpool_import_props() to import a pool with * new properties value to be set. */ int zpool_import(libzfs_handle_t *hdl, nvlist_t *config, const char *newname, char *altroot) { nvlist_t *props = NULL; int ret; if (altroot != NULL) { if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) { return (zfs_error_fmt(hdl, EZFS_NOMEM, dgettext(TEXT_DOMAIN, "cannot import '%s'"), newname)); } if (nvlist_add_string(props, zpool_prop_to_name(ZPOOL_PROP_ALTROOT), altroot) != 0 || nvlist_add_string(props, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE), "none") != 0) { nvlist_free(props); return (zfs_error_fmt(hdl, EZFS_NOMEM, dgettext(TEXT_DOMAIN, "cannot import '%s'"), newname)); } } ret = zpool_import_props(hdl, config, newname, props, B_FALSE); if (props) nvlist_free(props); return (ret); } /* * Import the given pool using the known configuration and a list of * properties to be set. The configuration should have come from * zpool_find_import(). The 'newname' parameters control whether the pool * is imported with a different name. */ int zpool_import_props(libzfs_handle_t *hdl, nvlist_t *config, const char *newname, nvlist_t *props, boolean_t importfaulted) { zfs_cmd_t zc = { 0 }; zpool_rewind_policy_t policy; nvlist_t *nvi = NULL; char *thename; char *origname; uint64_t returned_size; int ret; char errbuf[1024]; verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME, &origname) == 0); (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN, "cannot import pool '%s'"), origname); if (newname != NULL) { if (!zpool_name_valid(hdl, B_FALSE, newname)) return (zfs_error_fmt(hdl, EZFS_INVALIDNAME, dgettext(TEXT_DOMAIN, "cannot import '%s'"), newname)); thename = (char *)newname; } else { thename = origname; } if (props) { uint64_t version; verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION, &version) == 0); if ((props = zpool_valid_proplist(hdl, origname, props, version, B_TRUE, errbuf)) == NULL) { return (-1); } else if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) { nvlist_free(props); return (-1); } } (void) strlcpy(zc.zc_name, thename, sizeof (zc.zc_name)); verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &zc.zc_guid) == 0); if (zcmd_write_conf_nvlist(hdl, &zc, config) != 0) { nvlist_free(props); return (-1); } returned_size = zc.zc_nvlist_conf_size + 512; if (zcmd_alloc_dst_nvlist(hdl, &zc, returned_size) != 0) { nvlist_free(props); return (-1); } zc.zc_cookie = (uint64_t)importfaulted; ret = 0; if (zfs_ioctl(hdl, ZFS_IOC_POOL_IMPORT, &zc) != 0) { char desc[1024]; (void) zcmd_read_dst_nvlist(hdl, &zc, &nvi); zpool_get_rewind_policy(config, &policy); /* * Dry-run failed, but we print out what success * looks like if we found a best txg */ if ((policy.zrp_request & ZPOOL_TRY_REWIND) && nvi) { zpool_rewind_exclaim(hdl, newname ? origname : thename, B_TRUE, nvi); nvlist_free(nvi); return (-1); } if (newname == NULL) (void) snprintf(desc, sizeof (desc), dgettext(TEXT_DOMAIN, "cannot import '%s'"), thename); else (void) snprintf(desc, sizeof (desc), dgettext(TEXT_DOMAIN, "cannot import '%s' as '%s'"), origname, thename); switch (errno) { case ENOTSUP: /* * Unsupported version. */ (void) zfs_error(hdl, EZFS_BADVERSION, desc); break; case EINVAL: (void) zfs_error(hdl, EZFS_INVALCONFIG, desc); break; case EROFS: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "one or more devices is read only")); (void) zfs_error(hdl, EZFS_BADDEV, desc); break; default: (void) zcmd_read_dst_nvlist(hdl, &zc, &nvi); (void) zpool_standard_error(hdl, errno, desc); zpool_explain_recover(hdl, newname ? origname : thename, -errno, nvi); nvlist_free(nvi); break; } ret = -1; } else { zpool_handle_t *zhp; /* * This should never fail, but play it safe anyway. */ if (zpool_open_silent(hdl, thename, &zhp) != 0) ret = -1; else if (zhp != NULL) zpool_close(zhp); (void) zcmd_read_dst_nvlist(hdl, &zc, &nvi); zpool_get_rewind_policy(config, &policy); if (policy.zrp_request & (ZPOOL_DO_REWIND | ZPOOL_TRY_REWIND)) { zpool_rewind_exclaim(hdl, newname ? origname : thename, ((policy.zrp_request & ZPOOL_TRY_REWIND) != 0), nvi); } nvlist_free(nvi); return (0); } zcmd_free_nvlists(&zc); nvlist_free(props); return (ret); } /* * Scan the pool. */ int zpool_scan(zpool_handle_t *zhp, pool_scan_func_t func) { zfs_cmd_t zc = { 0 }; char msg[1024]; libzfs_handle_t *hdl = zhp->zpool_hdl; (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); zc.zc_cookie = func; if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_SCAN, &zc) == 0 || (errno == ENOENT && func != POOL_SCAN_NONE)) return (0); if (func == POOL_SCAN_SCRUB) { (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot scrub %s"), zc.zc_name); } else if (func == POOL_SCAN_NONE) { (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot cancel scrubbing %s"), zc.zc_name); } else { assert(!"unexpected result"); } if (errno == EBUSY) { nvlist_t *nvroot; pool_scan_stat_t *ps = NULL; uint_t psc; verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0); (void) nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &psc); if (ps && ps->pss_func == POOL_SCAN_SCRUB) return (zfs_error(hdl, EZFS_SCRUBBING, msg)); else return (zfs_error(hdl, EZFS_RESILVERING, msg)); } else if (errno == ENOENT) { return (zfs_error(hdl, EZFS_NO_SCRUB, msg)); } else { return (zpool_standard_error(hdl, errno, msg)); } } /* * Find a vdev that matches the search criteria specified. We use the * the nvpair name to determine how we should look for the device. * 'avail_spare' is set to TRUE if the provided guid refers to an AVAIL * spare; but FALSE if its an INUSE spare. */ static nvlist_t * vdev_to_nvlist_iter(nvlist_t *nv, nvlist_t *search, boolean_t *avail_spare, boolean_t *l2cache, boolean_t *log) { uint_t c, children; nvlist_t **child; nvlist_t *ret; uint64_t is_log; char *srchkey; nvpair_t *pair = nvlist_next_nvpair(search, NULL); /* Nothing to look for */ if (search == NULL || pair == NULL) return (NULL); /* Obtain the key we will use to search */ srchkey = nvpair_name(pair); switch (nvpair_type(pair)) { case DATA_TYPE_UINT64: { uint64_t srchval, theguid, present; verify(nvpair_value_uint64(pair, &srchval) == 0); if (strcmp(srchkey, ZPOOL_CONFIG_GUID) == 0) { if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT, &present) == 0) { /* * If the device has never been present since * import, the only reliable way to match the * vdev is by GUID. */ verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &theguid) == 0); if (theguid == srchval) return (nv); } } break; } case DATA_TYPE_STRING: { char *srchval, *val; verify(nvpair_value_string(pair, &srchval) == 0); if (nvlist_lookup_string(nv, srchkey, &val) != 0) break; /* * Search for the requested value. We special case the search * for ZPOOL_CONFIG_PATH when it's a wholedisk and when * Looking for a top-level vdev name (i.e. ZPOOL_CONFIG_TYPE). * Otherwise, all other searches are simple string compares. */ if (strcmp(srchkey, ZPOOL_CONFIG_PATH) == 0 && val) { uint64_t wholedisk = 0; (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK, &wholedisk); if (wholedisk) { /* * For whole disks, the internal path has 's0', * but the path passed in by the user doesn't. */ if (strlen(srchval) == strlen(val) - 2 && strncmp(srchval, val, strlen(srchval)) == 0) return (nv); break; } } else if (strcmp(srchkey, ZPOOL_CONFIG_TYPE) == 0 && val) { char *type, *idx, *end, *p; uint64_t id, vdev_id; /* * Determine our vdev type, keeping in mind * that the srchval is composed of a type and * vdev id pair (i.e. mirror-4). */ if ((type = strdup(srchval)) == NULL) return (NULL); if ((p = strrchr(type, '-')) == NULL) { free(type); break; } idx = p + 1; *p = '\0'; /* * If the types don't match then keep looking. */ if (strncmp(val, type, strlen(val)) != 0) { free(type); break; } verify(strncmp(type, VDEV_TYPE_RAIDZ, strlen(VDEV_TYPE_RAIDZ)) == 0 || strncmp(type, VDEV_TYPE_MIRROR, strlen(VDEV_TYPE_MIRROR)) == 0); verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID, &id) == 0); errno = 0; vdev_id = strtoull(idx, &end, 10); free(type); if (errno != 0) return (NULL); /* * Now verify that we have the correct vdev id. */ if (vdev_id == id) return (nv); } /* * Common case */ if (strcmp(srchval, val) == 0) return (nv); break; } default: break; } if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child, &children) != 0) return (NULL); for (c = 0; c < children; c++) { if ((ret = vdev_to_nvlist_iter(child[c], search, avail_spare, l2cache, NULL)) != NULL) { /* * The 'is_log' value is only set for the toplevel * vdev, not the leaf vdevs. So we always lookup the * log device from the root of the vdev tree (where * 'log' is non-NULL). */ if (log != NULL && nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG, &is_log) == 0 && is_log) { *log = B_TRUE; } return (ret); } } if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES, &child, &children) == 0) { for (c = 0; c < children; c++) { if ((ret = vdev_to_nvlist_iter(child[c], search, avail_spare, l2cache, NULL)) != NULL) { *avail_spare = B_TRUE; return (ret); } } } if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE, &child, &children) == 0) { for (c = 0; c < children; c++) { if ((ret = vdev_to_nvlist_iter(child[c], search, avail_spare, l2cache, NULL)) != NULL) { *l2cache = B_TRUE; return (ret); } } } return (NULL); } /* * Given a physical path (minus the "/devices" prefix), find the * associated vdev. */ nvlist_t * zpool_find_vdev_by_physpath(zpool_handle_t *zhp, const char *ppath, boolean_t *avail_spare, boolean_t *l2cache, boolean_t *log) { nvlist_t *search, *nvroot, *ret; verify(nvlist_alloc(&search, NV_UNIQUE_NAME, KM_SLEEP) == 0); verify(nvlist_add_string(search, ZPOOL_CONFIG_PHYS_PATH, ppath) == 0); verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0); *avail_spare = B_FALSE; ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log); nvlist_free(search); return (ret); } /* * Determine if we have an "interior" top-level vdev (i.e mirror/raidz). */ boolean_t zpool_vdev_is_interior(const char *name) { if (strncmp(name, VDEV_TYPE_RAIDZ, strlen(VDEV_TYPE_RAIDZ)) == 0 || strncmp(name, VDEV_TYPE_MIRROR, strlen(VDEV_TYPE_MIRROR)) == 0) return (B_TRUE); return (B_FALSE); } nvlist_t * zpool_find_vdev(zpool_handle_t *zhp, const char *path, boolean_t *avail_spare, boolean_t *l2cache, boolean_t *log) { char buf[MAXPATHLEN]; char *end; nvlist_t *nvroot, *search, *ret; uint64_t guid; verify(nvlist_alloc(&search, NV_UNIQUE_NAME, KM_SLEEP) == 0); guid = strtoull(path, &end, 10); if (guid != 0 && *end == '\0') { verify(nvlist_add_uint64(search, ZPOOL_CONFIG_GUID, guid) == 0); } else if (zpool_vdev_is_interior(path)) { verify(nvlist_add_string(search, ZPOOL_CONFIG_TYPE, path) == 0); } else if (path[0] != '/') { (void) snprintf(buf, sizeof (buf), "%s%s", "/dev/dsk/", path); verify(nvlist_add_string(search, ZPOOL_CONFIG_PATH, buf) == 0); } else { verify(nvlist_add_string(search, ZPOOL_CONFIG_PATH, path) == 0); } verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0); *avail_spare = B_FALSE; *l2cache = B_FALSE; if (log != NULL) *log = B_FALSE; ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log); nvlist_free(search); return (ret); } static int vdev_online(nvlist_t *nv) { uint64_t ival; if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE, &ival) == 0 || nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED, &ival) == 0 || nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED, &ival) == 0) return (0); return (1); } /* * Helper function for zpool_get_physpaths(). */ static int vdev_get_one_physpath(nvlist_t *config, char *physpath, size_t physpath_size, size_t *bytes_written) { size_t bytes_left, pos, rsz; char *tmppath; const char *format; if (nvlist_lookup_string(config, ZPOOL_CONFIG_PHYS_PATH, &tmppath) != 0) return (EZFS_NODEVICE); pos = *bytes_written; bytes_left = physpath_size - pos; format = (pos == 0) ? "%s" : " %s"; rsz = snprintf(physpath + pos, bytes_left, format, tmppath); *bytes_written += rsz; if (rsz >= bytes_left) { /* if physpath was not copied properly, clear it */ if (bytes_left != 0) { physpath[pos] = 0; } return (EZFS_NOSPC); } return (0); } static int vdev_get_physpaths(nvlist_t *nv, char *physpath, size_t phypath_size, size_t *rsz, boolean_t is_spare) { char *type; int ret; if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0) return (EZFS_INVALCONFIG); if (strcmp(type, VDEV_TYPE_DISK) == 0) { /* * An active spare device has ZPOOL_CONFIG_IS_SPARE set. * For a spare vdev, we only want to boot from the active * spare device. */ if (is_spare) { uint64_t spare = 0; (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE, &spare); if (!spare) return (EZFS_INVALCONFIG); } if (vdev_online(nv)) { if ((ret = vdev_get_one_physpath(nv, physpath, phypath_size, rsz)) != 0) return (ret); } } else if (strcmp(type, VDEV_TYPE_MIRROR) == 0 || strcmp(type, VDEV_TYPE_REPLACING) == 0 || (is_spare = (strcmp(type, VDEV_TYPE_SPARE) == 0))) { nvlist_t **child; uint_t count; int i, ret; if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN, &child, &count) != 0) return (EZFS_INVALCONFIG); for (i = 0; i < count; i++) { ret = vdev_get_physpaths(child[i], physpath, phypath_size, rsz, is_spare); if (ret == EZFS_NOSPC) return (ret); } } return (EZFS_POOL_INVALARG); } /* * Get phys_path for a root pool config. * Return 0 on success; non-zero on failure. */ static int zpool_get_config_physpath(nvlist_t *config, char *physpath, size_t phypath_size) { size_t rsz; nvlist_t *vdev_root; nvlist_t **child; uint_t count; char *type; rsz = 0; if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &vdev_root) != 0) return (EZFS_INVALCONFIG); if (nvlist_lookup_string(vdev_root, ZPOOL_CONFIG_TYPE, &type) != 0 || nvlist_lookup_nvlist_array(vdev_root, ZPOOL_CONFIG_CHILDREN, &child, &count) != 0) return (EZFS_INVALCONFIG); /* * root pool can not have EFI labeled disks and can only have * a single top-level vdev. */ #if 0 if (strcmp(type, VDEV_TYPE_ROOT) != 0 || count != 1 || pool_uses_efi(vdev_root)) return (EZFS_POOL_INVALARG); #endif (void) vdev_get_physpaths(child[0], physpath, phypath_size, &rsz, B_FALSE); /* No online devices */ if (rsz == 0) return (EZFS_NODEVICE); return (0); } /* * Get phys_path for a root pool * Return 0 on success; non-zero on failure. */ int zpool_get_physpath(zpool_handle_t *zhp, char *physpath, size_t phypath_size) { return (zpool_get_config_physpath(zhp->zpool_config, physpath, phypath_size)); } /* * If the device has being dynamically expanded then we need to relabel * the disk to use the new unallocated space. */ static int zpool_relabel_disk(libzfs_handle_t *hdl, const char *name) { char path[MAXPATHLEN]; char errbuf[1024]; int fd, error; int (*_efi_use_whole_disk)(int); if ((_efi_use_whole_disk = (int (*)(int))dlsym(RTLD_DEFAULT, "efi_use_whole_disk")) == NULL) return (-1); (void) snprintf(path, sizeof (path), "%s/%s", RDISK_ROOT, name); if ((fd = open(path, O_RDWR | O_NDELAY)) < 0) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot " "relabel '%s': unable to open device"), name); return (zfs_error(hdl, EZFS_OPENFAILED, errbuf)); } /* * It's possible that we might encounter an error if the device * does not have any unallocated space left. If so, we simply * ignore that error and continue on. */ /* zfs-fuse : no efi function here, this should be fixed later if * possible... * error = _efi_use_whole_disk(fd); */ (void) close(fd); /* if (error && error != VT_ENOSPC) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot " "relabel '%s': unable to read disk capacity"), name); return (zfs_error(hdl, EZFS_NOCAP, errbuf)); } */ return (0); } /* * Bring the specified vdev online. The 'flags' parameter is a set of the * ZFS_ONLINE_* flags. */ int zpool_vdev_online(zpool_handle_t *zhp, const char *path, int flags, vdev_state_t *newstate) { zfs_cmd_t zc = { 0 }; char msg[1024]; nvlist_t *tgt; boolean_t avail_spare, l2cache, islog; libzfs_handle_t *hdl = zhp->zpool_hdl; if (flags & ZFS_ONLINE_EXPAND) { (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot expand %s"), path); } else { (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot online %s"), path); } (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache, &islog)) == NULL) return (zfs_error(hdl, EZFS_NODEVICE, msg)); verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0); if (avail_spare) return (zfs_error(hdl, EZFS_ISSPARE, msg)); if (flags & ZFS_ONLINE_EXPAND || zpool_get_prop_int(zhp, ZPOOL_PROP_AUTOEXPAND, NULL)) { char *pathname = NULL; uint64_t wholedisk = 0; (void) nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_WHOLE_DISK, &wholedisk); verify(nvlist_lookup_string(tgt, ZPOOL_CONFIG_PATH, &pathname) == 0); /* * XXX - L2ARC 1.0 devices can't support expansion. */ if (l2cache) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot expand cache devices")); return (zfs_error(hdl, EZFS_VDEVNOTSUP, msg)); } if (wholedisk) { pathname += strlen(DISK_ROOT) + 1; (void) zpool_relabel_disk(zhp->zpool_hdl, pathname); } } zc.zc_cookie = VDEV_STATE_ONLINE; zc.zc_obj = flags; if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_VDEV_SET_STATE, &zc) != 0) { if (errno == EINVAL) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "was split " "from this pool into a new one. Use '%s' " "instead"), "zpool detach"); return (zfs_error(hdl, EZFS_POSTSPLIT_ONLINE, msg)); } return (zpool_standard_error(hdl, errno, msg)); } *newstate = zc.zc_cookie; return (0); } /* * Take the specified vdev offline */ int zpool_vdev_offline(zpool_handle_t *zhp, const char *path, boolean_t istmp) { zfs_cmd_t zc = { 0 }; char msg[1024]; nvlist_t *tgt; boolean_t avail_spare, l2cache; libzfs_handle_t *hdl = zhp->zpool_hdl; (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot offline %s"), path); (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache, NULL)) == NULL) return (zfs_error(hdl, EZFS_NODEVICE, msg)); verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0); if (avail_spare) return (zfs_error(hdl, EZFS_ISSPARE, msg)); zc.zc_cookie = VDEV_STATE_OFFLINE; zc.zc_obj = istmp ? ZFS_OFFLINE_TEMPORARY : 0; if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_VDEV_SET_STATE, &zc) == 0) return (0); switch (errno) { case EBUSY: /* * There are no other replicas of this device. */ return (zfs_error(hdl, EZFS_NOREPLICAS, msg)); case EEXIST: /* * The log device has unplayed logs */ return (zfs_error(hdl, EZFS_UNPLAYED_LOGS, msg)); default: return (zpool_standard_error(hdl, errno, msg)); } } /* * Mark the given vdev faulted. */ int zpool_vdev_fault(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux) { zfs_cmd_t zc = { 0 }; char msg[1024]; libzfs_handle_t *hdl = zhp->zpool_hdl; (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot fault %llu"), (u_longlong_t) guid); (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); zc.zc_guid = guid; zc.zc_cookie = VDEV_STATE_FAULTED; zc.zc_obj = aux; if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0) return (0); switch (errno) { case EBUSY: /* * There are no other replicas of this device. */ return (zfs_error(hdl, EZFS_NOREPLICAS, msg)); default: return (zpool_standard_error(hdl, errno, msg)); } } /* * Mark the given vdev degraded. */ int zpool_vdev_degrade(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux) { zfs_cmd_t zc = { 0 }; char msg[1024]; libzfs_handle_t *hdl = zhp->zpool_hdl; (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot degrade %llu"), (u_longlong_t) guid); (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); zc.zc_guid = guid; zc.zc_cookie = VDEV_STATE_DEGRADED; zc.zc_obj = aux; if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0) return (0); return (zpool_standard_error(hdl, errno, msg)); } /* * Returns TRUE if the given nvlist is a vdev that was originally swapped in as * a hot spare. */ static boolean_t is_replacing_spare(nvlist_t *search, nvlist_t *tgt, int which) { nvlist_t **child; uint_t c, children; char *type; if (nvlist_lookup_nvlist_array(search, ZPOOL_CONFIG_CHILDREN, &child, &children) == 0) { verify(nvlist_lookup_string(search, ZPOOL_CONFIG_TYPE, &type) == 0); if (strcmp(type, VDEV_TYPE_SPARE) == 0 && children == 2 && child[which] == tgt) return (B_TRUE); for (c = 0; c < children; c++) if (is_replacing_spare(child[c], tgt, which)) return (B_TRUE); } return (B_FALSE); } /* * Attach new_disk (fully described by nvroot) to old_disk. * If 'replacing' is specified, the new disk will replace the old one. */ int zpool_vdev_attach(zpool_handle_t *zhp, const char *old_disk, const char *new_disk, nvlist_t *nvroot, int replacing) { zfs_cmd_t zc = { 0 }; char msg[1024]; int ret; nvlist_t *tgt; boolean_t avail_spare, l2cache, islog; uint64_t val; char *path, *newname; nvlist_t **child; uint_t children; nvlist_t *config_root; libzfs_handle_t *hdl = zhp->zpool_hdl; boolean_t rootpool = pool_is_bootable(zhp); if (replacing) (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot replace %s with %s"), old_disk, new_disk); else (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot attach %s to %s"), new_disk, old_disk); /* * If this is a root pool, make sure that we're not attaching an * EFI labeled device. */ #if 0 if (rootpool && pool_uses_efi(nvroot)) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "EFI labeled devices are not supported on root pools.")); return (zfs_error(hdl, EZFS_POOL_NOTSUP, msg)); } #endif (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); if ((tgt = zpool_find_vdev(zhp, old_disk, &avail_spare, &l2cache, &islog)) == 0) return (zfs_error(hdl, EZFS_NODEVICE, msg)); if (avail_spare) return (zfs_error(hdl, EZFS_ISSPARE, msg)); if (l2cache) return (zfs_error(hdl, EZFS_ISL2CACHE, msg)); verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0); zc.zc_cookie = replacing; if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN, &child, &children) != 0 || children != 1) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "new device must be a single disk")); return (zfs_error(hdl, EZFS_INVALCONFIG, msg)); } verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL), ZPOOL_CONFIG_VDEV_TREE, &config_root) == 0); if ((newname = zpool_vdev_name(NULL, NULL, child[0], B_FALSE)) == NULL) return (-1); /* * If the target is a hot spare that has been swapped in, we can only * replace it with another hot spare. */ if (replacing && nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_IS_SPARE, &val) == 0 && (zpool_find_vdev(zhp, newname, &avail_spare, &l2cache, NULL) == NULL || !avail_spare) && is_replacing_spare(config_root, tgt, 1)) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "can only be replaced by another hot spare")); free(newname); return (zfs_error(hdl, EZFS_BADTARGET, msg)); } /* * If we are attempting to replace a spare, it canot be applied to an * already spared device. */ if (replacing && nvlist_lookup_string(child[0], ZPOOL_CONFIG_PATH, &path) == 0 && zpool_find_vdev(zhp, newname, &avail_spare, &l2cache, NULL) != NULL && avail_spare && is_replacing_spare(config_root, tgt, 0)) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "device has already been replaced with a spare")); free(newname); return (zfs_error(hdl, EZFS_BADTARGET, msg)); } free(newname); if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0) return (-1); ret = zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_VDEV_ATTACH, &zc); zcmd_free_nvlists(&zc); if (ret == 0) { if (rootpool) { /* * XXX - This should be removed once we can * automatically install the bootblocks on the * newly attached disk. */ (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Please " "be sure to invoke %s to make '%s' bootable.\n"), BOOTCMD, new_disk); /* * XXX need a better way to prevent user from * booting up a half-baked vdev. */ (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Make " "sure to wait until resilver is done " "before rebooting.\n")); } return (0); } switch (errno) { case ENOTSUP: /* * Can't attach to or replace this type of vdev. */ if (replacing) { if (islog) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot replace a log with a spare")); else zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot replace a replacing device")); } else { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "can only attach to mirrors and top-level " "disks")); } (void) zfs_error(hdl, EZFS_BADTARGET, msg); break; case EINVAL: /* * The new device must be a single disk. */ zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "new device must be a single disk")); (void) zfs_error(hdl, EZFS_INVALCONFIG, msg); break; case EBUSY: zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "%s is busy"), new_disk); (void) zfs_error(hdl, EZFS_BADDEV, msg); break; case EOVERFLOW: /* * The new device is too small. */ zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "device is too small")); (void) zfs_error(hdl, EZFS_BADDEV, msg); break; case EDOM: /* * The new device has a different alignment requirement. */ zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "devices have different sector alignment")); (void) zfs_error(hdl, EZFS_BADDEV, msg); break; case ENAMETOOLONG: /* * The resulting top-level vdev spec won't fit in the label. */ (void) zfs_error(hdl, EZFS_DEVOVERFLOW, msg); break; default: (void) zpool_standard_error(hdl, errno, msg); } return (-1); } /* * Detach the specified device. */ int zpool_vdev_detach(zpool_handle_t *zhp, const char *path) { zfs_cmd_t zc = { 0 }; char msg[1024]; nvlist_t *tgt; boolean_t avail_spare, l2cache; libzfs_handle_t *hdl = zhp->zpool_hdl; (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot detach %s"), path); (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache, NULL)) == 0) return (zfs_error(hdl, EZFS_NODEVICE, msg)); if (avail_spare) return (zfs_error(hdl, EZFS_ISSPARE, msg)); if (l2cache) return (zfs_error(hdl, EZFS_ISL2CACHE, msg)); verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0); if (zfs_ioctl(hdl, ZFS_IOC_VDEV_DETACH, &zc) == 0) return (0); switch (errno) { case ENOTSUP: /* * Can't detach from this type of vdev. */ zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "only " "applicable to mirror and replacing vdevs")); (void) zfs_error(zhp->zpool_hdl, EZFS_BADTARGET, msg); break; case EBUSY: /* * There are no other replicas of this device. */ (void) zfs_error(hdl, EZFS_NOREPLICAS, msg); break; default: (void) zpool_standard_error(hdl, errno, msg); } return (-1); } /* * Find a mirror vdev in the source nvlist. * * The mchild array contains a list of disks in one of the top-level mirrors * of the source pool. The schild array contains a list of disks that the * user specified on the command line. We loop over the mchild array to * see if any entry in the schild array matches. * * If a disk in the mchild array is found in the schild array, we return * the index of that entry. Otherwise we return -1. */ static int find_vdev_entry(zpool_handle_t *zhp, nvlist_t **mchild, uint_t mchildren, nvlist_t **schild, uint_t schildren) { uint_t mc; for (mc = 0; mc < mchildren; mc++) { uint_t sc; char *mpath = zpool_vdev_name(zhp->zpool_hdl, zhp, mchild[mc], B_FALSE); for (sc = 0; sc < schildren; sc++) { char *spath = zpool_vdev_name(zhp->zpool_hdl, zhp, schild[sc], B_FALSE); boolean_t result = (strcmp(mpath, spath) == 0); free(spath); if (result) { free(mpath); return (mc); } } free(mpath); } return (-1); } /* * Split a mirror pool. If newroot points to null, then a new nvlist * is generated and it is the responsibility of the caller to free it. */ int zpool_vdev_split(zpool_handle_t *zhp, char *newname, nvlist_t **newroot, nvlist_t *props, splitflags_t flags) { zfs_cmd_t zc = { 0 }; char msg[1024]; nvlist_t *tree, *config, **child, **newchild, *newconfig = NULL; nvlist_t **varray = NULL, *zc_props = NULL; uint_t c, children, newchildren, lastlog = 0, vcount, found = 0; libzfs_handle_t *hdl = zhp->zpool_hdl; uint64_t vers; boolean_t freelist = B_FALSE, memory_err = B_TRUE; int retval = 0; (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "Unable to split %s"), zhp->zpool_name); if (!zpool_name_valid(hdl, B_FALSE, newname)) return (zfs_error(hdl, EZFS_INVALIDNAME, msg)); if ((config = zpool_get_config(zhp, NULL)) == NULL) { (void) fprintf(stderr, gettext("Internal error: unable to " "retrieve pool configuration\n")); return (-1); } verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &tree) == 0); verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION, &vers) == 0); if (props) { if ((zc_props = zpool_valid_proplist(hdl, zhp->zpool_name, props, vers, B_TRUE, msg)) == NULL) return (-1); } if (nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN, &child, &children) != 0) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Source pool is missing vdev tree")); if (zc_props) nvlist_free(zc_props); return (-1); } varray = zfs_alloc(hdl, children * sizeof (nvlist_t *)); vcount = 0; if (*newroot == NULL || nvlist_lookup_nvlist_array(*newroot, ZPOOL_CONFIG_CHILDREN, &newchild, &newchildren) != 0) newchildren = 0; for (c = 0; c < children; c++) { uint64_t is_log = B_FALSE, is_hole = B_FALSE; char *type; nvlist_t **mchild, *vdev; uint_t mchildren; int entry; /* * Unlike cache & spares, slogs are stored in the * ZPOOL_CONFIG_CHILDREN array. We filter them out here. */ (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG, &is_log); (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE, &is_hole); if (is_log || is_hole) { /* * Create a hole vdev and put it in the config. */ if (nvlist_alloc(&vdev, NV_UNIQUE_NAME, 0) != 0) goto out; if (nvlist_add_string(vdev, ZPOOL_CONFIG_TYPE, VDEV_TYPE_HOLE) != 0) goto out; if (nvlist_add_uint64(vdev, ZPOOL_CONFIG_IS_HOLE, 1) != 0) goto out; if (lastlog == 0) lastlog = vcount; varray[vcount++] = vdev; continue; } lastlog = 0; verify(nvlist_lookup_string(child[c], ZPOOL_CONFIG_TYPE, &type) == 0); if (strcmp(type, VDEV_TYPE_MIRROR) != 0) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Source pool must be composed only of mirrors\n")); retval = zfs_error(hdl, EZFS_INVALCONFIG, msg); goto out; } verify(nvlist_lookup_nvlist_array(child[c], ZPOOL_CONFIG_CHILDREN, &mchild, &mchildren) == 0); /* find or add an entry for this top-level vdev */ if (newchildren > 0 && (entry = find_vdev_entry(zhp, mchild, mchildren, newchild, newchildren)) >= 0) { /* We found a disk that the user specified. */ vdev = mchild[entry]; ++found; } else { /* User didn't specify a disk for this vdev. */ vdev = mchild[mchildren - 1]; } if (nvlist_dup(vdev, &varray[vcount++], 0) != 0) goto out; } /* did we find every disk the user specified? */ if (found != newchildren) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Device list must " "include at most one disk from each mirror")); retval = zfs_error(hdl, EZFS_INVALCONFIG, msg); goto out; } /* Prepare the nvlist for populating. */ if (*newroot == NULL) { if (nvlist_alloc(newroot, NV_UNIQUE_NAME, 0) != 0) goto out; freelist = B_TRUE; if (nvlist_add_string(*newroot, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT) != 0) goto out; } else { verify(nvlist_remove_all(*newroot, ZPOOL_CONFIG_CHILDREN) == 0); } /* Add all the children we found */ if (nvlist_add_nvlist_array(*newroot, ZPOOL_CONFIG_CHILDREN, varray, lastlog == 0 ? vcount : lastlog) != 0) goto out; /* * If we're just doing a dry run, exit now with success. */ if (flags.dryrun) { memory_err = B_FALSE; freelist = B_FALSE; goto out; } /* now build up the config list & call the ioctl */ if (nvlist_alloc(&newconfig, NV_UNIQUE_NAME, 0) != 0) goto out; if (nvlist_add_nvlist(newconfig, ZPOOL_CONFIG_VDEV_TREE, *newroot) != 0 || nvlist_add_string(newconfig, ZPOOL_CONFIG_POOL_NAME, newname) != 0 || nvlist_add_uint64(newconfig, ZPOOL_CONFIG_VERSION, vers) != 0) goto out; /* * The new pool is automatically part of the namespace unless we * explicitly export it. */ if (!flags.import) zc.zc_cookie = ZPOOL_EXPORT_AFTER_SPLIT; (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); (void) strlcpy(zc.zc_string, newname, sizeof (zc.zc_string)); if (zcmd_write_conf_nvlist(hdl, &zc, newconfig) != 0) goto out; if (zc_props != NULL && zcmd_write_src_nvlist(hdl, &zc, zc_props) != 0) goto out; if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SPLIT, &zc) != 0) { retval = zpool_standard_error(hdl, errno, msg); goto out; } freelist = B_FALSE; memory_err = B_FALSE; out: if (varray != NULL) { int v; for (v = 0; v < vcount; v++) nvlist_free(varray[v]); free(varray); } zcmd_free_nvlists(&zc); if (zc_props) nvlist_free(zc_props); if (newconfig) nvlist_free(newconfig); if (freelist) { nvlist_free(*newroot); *newroot = NULL; } if (retval != 0) return (retval); if (memory_err) return (no_memory(hdl)); return (0); } /* * Remove the given device. Currently, this is supported only for hot spares * and level 2 cache devices. */ int zpool_vdev_remove(zpool_handle_t *zhp, const char *path) { zfs_cmd_t zc = { 0 }; char msg[1024]; nvlist_t *tgt; boolean_t avail_spare, l2cache, islog; libzfs_handle_t *hdl = zhp->zpool_hdl; uint64_t version; (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot remove %s"), path); (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache, &islog)) == 0) return (zfs_error(hdl, EZFS_NODEVICE, msg)); /* * XXX - this should just go away. */ if (!avail_spare && !l2cache && !islog) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "only inactive hot spares, cache, top-level, " "or log devices can be removed")); return (zfs_error(hdl, EZFS_NODEVICE, msg)); } version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL); if (islog && version < SPA_VERSION_HOLES) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be upgrade to support log removal")); return (zfs_error(hdl, EZFS_BADVERSION, msg)); } verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0); if (zfs_ioctl(hdl, ZFS_IOC_VDEV_REMOVE, &zc) == 0) return (0); return (zpool_standard_error(hdl, errno, msg)); } /* * Clear the errors for the pool, or the particular device if specified. */ int zpool_clear(zpool_handle_t *zhp, const char *path, nvlist_t *rewindnvl) { zfs_cmd_t zc = { 0 }; char msg[1024]; nvlist_t *tgt; zpool_rewind_policy_t policy; boolean_t avail_spare, l2cache; libzfs_handle_t *hdl = zhp->zpool_hdl; nvlist_t *nvi = NULL; if (path) (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot clear errors for %s"), path); else (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot clear errors for %s"), zhp->zpool_name); (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); if (path) { if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache, NULL)) == 0) return (zfs_error(hdl, EZFS_NODEVICE, msg)); /* * Don't allow error clearing for hot spares. Do allow * error clearing for l2cache devices. */ if (avail_spare) return (zfs_error(hdl, EZFS_ISSPARE, msg)); verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0); } zpool_get_rewind_policy(rewindnvl, &policy); zc.zc_cookie = policy.zrp_request; if (zcmd_alloc_dst_nvlist(hdl, &zc, 8192) != 0) return (-1); if (zcmd_write_src_nvlist(zhp->zpool_hdl, &zc, rewindnvl) != 0) return (-1); if (zfs_ioctl(hdl, ZFS_IOC_CLEAR, &zc) == 0 || ((policy.zrp_request & ZPOOL_TRY_REWIND) && errno != EPERM && errno != EACCES)) { if (policy.zrp_request & (ZPOOL_DO_REWIND | ZPOOL_TRY_REWIND)) { (void) zcmd_read_dst_nvlist(hdl, &zc, &nvi); zpool_rewind_exclaim(hdl, zc.zc_name, ((policy.zrp_request & ZPOOL_TRY_REWIND) != 0), nvi); nvlist_free(nvi); } zcmd_free_nvlists(&zc); return (0); } zcmd_free_nvlists(&zc); return (zpool_standard_error(hdl, errno, msg)); } /* * Similar to zpool_clear(), but takes a GUID (used by fmd). */ int zpool_vdev_clear(zpool_handle_t *zhp, uint64_t guid) { zfs_cmd_t zc = { 0 }; char msg[1024]; libzfs_handle_t *hdl = zhp->zpool_hdl; (void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN, "cannot clear errors for %llx"), (longlong_t) guid); (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); zc.zc_guid = guid; if (ioctl(hdl->libzfs_fd, ZFS_IOC_CLEAR, &zc) == 0) return (0); return (zpool_standard_error(hdl, errno, msg)); } /* * Convert from a devid string to a path. */ static char * devid_to_path(char *devid_str) { ddi_devid_t devid; char *minor; char *path; devid_nmlist_t *list = NULL; int ret; if (devid_str_decode(devid_str, &devid, &minor) != 0) return (NULL); ret = devid_deviceid_to_nmlist("/dev", devid, minor, &list); devid_str_free(minor); devid_free(devid); if (ret != 0) return (NULL); if ((path = strdup(list[0].devname)) == NULL) return (NULL); devid_free_nmlist(list); return (path); } /* * Convert from a path to a devid string. */ static char * path_to_devid(const char *path) { int fd; ddi_devid_t devid; char *minor, *ret; if ((fd = open(path, O_RDONLY)) < 0) return (NULL); minor = NULL; ret = NULL; if (devid_get(fd, &devid) == 0) { if (devid_get_minor_name(fd, &minor) == 0) ret = devid_str_encode(devid, minor); if (minor != NULL) devid_str_free(minor); devid_free(devid); } (void) close(fd); return (ret); } /* * Issue the necessary ioctl() to update the stored path value for the vdev. We * ignore any failure here, since a common case is for an unprivileged user to * type 'zpool status', and we'll display the correct information anyway. */ static void set_path(zpool_handle_t *zhp, nvlist_t *nv, const char *path) { zfs_cmd_t zc = { 0 }; (void) strncpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); (void) strncpy(zc.zc_value, path, sizeof (zc.zc_value)); verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0); (void) ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_VDEV_SETPATH, &zc); } /* * Given a vdev, return the name to display in iostat. If the vdev has a path, * we use that, stripping off any leading "/dev/"; if not, we use the type. * We also check if this is a whole disk, in which case we strip off the * trailing 's0' slice name. * * This routine is also responsible for identifying when disks have been * reconfigured in a new location. The kernel will have opened the device by * devid, but the path will still refer to the old location. To catch this, we * first do a path -> devid translation (which is fast for the common case). If * the devid matches, we're done. If not, we do a reverse devid -> path * translation and issue the appropriate ioctl() to update the path of the vdev. * If 'zhp' is NULL, then this is an exported pool, and we don't need to do any * of these checks. */ /* * zfs-fuse FIXME: Handle this properly */ char * zpool_vdev_name(libzfs_handle_t *hdl, zpool_handle_t *zhp, nvlist_t *nv, boolean_t verbose) { char *path, *devid; uint64_t value; char buf[64]; vdev_stat_t *vs; uint_t vsc; if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT, &value) == 0) { verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &value) == 0); (void) snprintf(buf, sizeof (buf), "%llu", (u_longlong_t)value); path = buf; } else if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) { /* * If the device is dead (faulted, offline, etc) then don't * bother opening it. Otherwise we may be forcing the user to * open a misbehaving device, which can have undesirable * effects. */ if ((nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc) != 0 || vs->vs_state >= VDEV_STATE_DEGRADED) && zhp != NULL && nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &devid) == 0) { /* * Determine if the current path is correct. */ char *newdevid = path_to_devid(path); if (newdevid == NULL || strcmp(devid, newdevid) != 0) { char *newpath; if ((newpath = devid_to_path(devid)) != NULL) { /* * Update the path appropriately. */ set_path(zhp, nv, newpath); if (nvlist_add_string(nv, ZPOOL_CONFIG_PATH, newpath) == 0) verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0); free(newpath); } } if (newdevid) devid_str_free(newdevid); } if (strncmp(path, "/dev/", 5) == 0) path += 5; } else { verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &path) == 0); /* * If it's a raidz device, we need to stick in the parity level. */ if (strcmp(path, VDEV_TYPE_RAIDZ) == 0) { verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY, &value) == 0); (void) snprintf(buf, sizeof (buf), "%s%llu", path, (u_longlong_t)value); path = buf; } char str[64]; strcpy(str,path); /* * We identify each top-level vdev by using a <type-id> * naming convention. */ if (verbose) { uint64_t id; verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID, &id) == 0); (void) snprintf(buf, sizeof (buf), "%s-%llu", str, (u_longlong_t)id); path = buf; } } return (zfs_strdup(hdl, path)); } static int zbookmark_compare(const void *a, const void *b) { return (memcmp(a, b, sizeof (zbookmark_t))); } /* * Retrieve the persistent error log, uniquify the members, and return to the * caller. */ int zpool_get_errlog(zpool_handle_t *zhp, nvlist_t **nverrlistp) { zfs_cmd_t zc = { 0 }; uint64_t count; zbookmark_t *zb = NULL; int i; /* * Retrieve the raw error list from the kernel. If the number of errors * has increased, allocate more space and continue until we get the * entire list. */ verify(nvlist_lookup_uint64(zhp->zpool_config, ZPOOL_CONFIG_ERRCOUNT, &count) == 0); if (count == 0) return (0); if ((zc.zc_nvlist_dst = (uintptr_t)zfs_alloc(zhp->zpool_hdl, count * sizeof (zbookmark_t))) == (uintptr_t)NULL) return (-1); zc.zc_nvlist_dst_size = count; (void) strcpy(zc.zc_name, zhp->zpool_name); for (;;) { if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_ERROR_LOG, &zc) != 0) { free((void *)(uintptr_t)zc.zc_nvlist_dst); if (errno == ENOMEM) { count = zc.zc_nvlist_dst_size; if ((zc.zc_nvlist_dst = (uintptr_t) zfs_alloc(zhp->zpool_hdl, count * sizeof (zbookmark_t))) == (uintptr_t)NULL) return (-1); } else { return (-1); } } else { break; } } /* * Sort the resulting bookmarks. This is a little confusing due to the * implementation of ZFS_IOC_ERROR_LOG. The bookmarks are copied last * to first, and 'zc_nvlist_dst_size' indicates the number of boomarks * _not_ copied as part of the process. So we point the start of our * array appropriate and decrement the total number of elements. */ zb = ((zbookmark_t *)(uintptr_t)zc.zc_nvlist_dst) + zc.zc_nvlist_dst_size; count -= zc.zc_nvlist_dst_size; void *nvlist_dst = (void *)(uintptr_t) zc.zc_nvlist_dst; qsort(zb, count, sizeof (zbookmark_t), zbookmark_compare); verify(nvlist_alloc(nverrlistp, 0, KM_SLEEP) == 0); /* * Fill in the nverrlistp with nvlist's of dataset and object numbers. */ for (i = 0; i < count; i++) { nvlist_t *nv; /* ignoring zb_blkid and zb_level for now */ if (i > 0 && zb[i-1].zb_objset == zb[i].zb_objset && zb[i-1].zb_object == zb[i].zb_object) continue; if (nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) != 0) goto nomem; if (nvlist_add_uint64(nv, ZPOOL_ERR_DATASET, zb[i].zb_objset) != 0) { nvlist_free(nv); goto nomem; } if (nvlist_add_uint64(nv, ZPOOL_ERR_OBJECT, zb[i].zb_object) != 0) { nvlist_free(nv); goto nomem; } if (nvlist_add_nvlist(*nverrlistp, "ejk", nv) != 0) { nvlist_free(nv); goto nomem; } nvlist_free(nv); } free(nvlist_dst); return (0); nomem: free(nvlist_dst); free((void *)(uintptr_t)zc.zc_nvlist_dst); return (no_memory(zhp->zpool_hdl)); } /* * Upgrade a ZFS pool to the latest on-disk version. */ int zpool_upgrade(zpool_handle_t *zhp, uint64_t new_version) { zfs_cmd_t zc = { 0 }; libzfs_handle_t *hdl = zhp->zpool_hdl; (void) strcpy(zc.zc_name, zhp->zpool_name); zc.zc_cookie = new_version; if (zfs_ioctl(hdl, ZFS_IOC_POOL_UPGRADE, &zc) != 0) return (zpool_standard_error_fmt(hdl, errno, dgettext(TEXT_DOMAIN, "cannot upgrade '%s'"), zhp->zpool_name)); return (0); } void zpool_set_history_str(const char *subcommand, int argc, char **argv, char *history_str) { int i; (void) strlcpy(history_str, subcommand, HIS_MAX_RECORD_LEN); for (i = 1; i < argc; i++) { if (strlen(history_str) + 1 + strlen(argv[i]) > HIS_MAX_RECORD_LEN) break; (void) strlcat(history_str, " ", HIS_MAX_RECORD_LEN); (void) strlcat(history_str, argv[i], HIS_MAX_RECORD_LEN); } } /* * Stage command history for logging. */ int zpool_stage_history(libzfs_handle_t *hdl, const char *history_str) { if (history_str == NULL) return (EINVAL); if (strlen(history_str) > HIS_MAX_RECORD_LEN) return (EINVAL); if (hdl->libzfs_log_str != NULL) free(hdl->libzfs_log_str); if ((hdl->libzfs_log_str = strdup(history_str)) == NULL) return (no_memory(hdl)); return (0); } /* * Perform ioctl to get some command history of a pool. * * 'buf' is the buffer to fill up to 'len' bytes. 'off' is the * logical offset of the history buffer to start reading from. * * Upon return, 'off' is the next logical offset to read from and * 'len' is the actual amount of bytes read into 'buf'. */ static int get_history(zpool_handle_t *zhp, char *buf, uint64_t *off, uint64_t *len) { zfs_cmd_t zc = { 0 }; libzfs_handle_t *hdl = zhp->zpool_hdl; (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); zc.zc_history = (uint64_t)(uintptr_t)buf; zc.zc_history_len = *len; zc.zc_history_offset = *off; if (ioctl(hdl->libzfs_fd, ZFS_IOC_POOL_GET_HISTORY, &zc) != 0) { switch (errno) { case EPERM: return (zfs_error_fmt(hdl, EZFS_PERM, dgettext(TEXT_DOMAIN, "cannot show history for pool '%s'"), zhp->zpool_name)); case ENOENT: return (zfs_error_fmt(hdl, EZFS_NOHISTORY, dgettext(TEXT_DOMAIN, "cannot get history for pool " "'%s'"), zhp->zpool_name)); case ENOTSUP: return (zfs_error_fmt(hdl, EZFS_BADVERSION, dgettext(TEXT_DOMAIN, "cannot get history for pool " "'%s', pool must be upgraded"), zhp->zpool_name)); default: return (zpool_standard_error_fmt(hdl, errno, dgettext(TEXT_DOMAIN, "cannot get history for '%s'"), zhp->zpool_name)); } } *len = zc.zc_history_len; *off = zc.zc_history_offset; return (0); } /* * Process the buffer of nvlists, unpacking and storing each nvlist record * into 'records'. 'leftover' is set to the number of bytes that weren't * processed as there wasn't a complete record. */ int zpool_history_unpack(char *buf, uint64_t bytes_read, uint64_t *leftover, nvlist_t ***records, uint_t *numrecords) { uint64_t reclen; nvlist_t *nv; int i; while (bytes_read > sizeof (reclen)) { /* get length of packed record (stored as little endian) */ for (i = 0, reclen = 0; i < sizeof (reclen); i++) reclen += (uint64_t)(((uchar_t *)buf)[i]) << (8*i); if (bytes_read < sizeof (reclen) + reclen) break; /* unpack record */ if (nvlist_unpack(buf + sizeof (reclen), reclen, &nv, 0) != 0) return (ENOMEM); bytes_read -= sizeof (reclen) + reclen; buf += sizeof (reclen) + reclen; /* add record to nvlist array */ (*numrecords)++; if (ISP2(*numrecords + 1)) { *records = realloc(*records, *numrecords * 2 * sizeof (nvlist_t *)); } (*records)[*numrecords - 1] = nv; } *leftover = bytes_read; return (0); } #define HIS_BUF_LEN (128*1024) /* * Retrieve the command history of a pool. */ int zpool_get_history(zpool_handle_t *zhp, nvlist_t **nvhisp) { char buf[HIS_BUF_LEN]; uint64_t off = 0; nvlist_t **records = NULL; uint_t numrecords = 0; int err, i; do { uint64_t bytes_read = sizeof (buf); uint64_t leftover; if ((err = get_history(zhp, buf, &off, &bytes_read)) != 0) break; /* if nothing else was read in, we're at EOF, just return */ if (!bytes_read) break; if ((err = zpool_history_unpack(buf, bytes_read, &leftover, &records, &numrecords)) != 0) break; off -= leftover; /* CONSTCOND */ } while (1); if (!err) { verify(nvlist_alloc(nvhisp, NV_UNIQUE_NAME, 0) == 0); verify(nvlist_add_nvlist_array(*nvhisp, ZPOOL_HIST_RECORD, records, numrecords) == 0); } for (i = 0; i < numrecords; i++) nvlist_free(records[i]); free(records); return (err); } void zpool_obj_to_path(zpool_handle_t *zhp, uint64_t dsobj, uint64_t obj, char *pathname, size_t len) { zfs_cmd_t zc = { 0 }; boolean_t mounted = B_FALSE; char *mntpnt = NULL; char dsname[MAXNAMELEN]; if (dsobj == 0) { /* special case for the MOS */ (void) snprintf(pathname, len, "<metadata>:<0x%llx>", (u_longlong_t) obj); return; } /* get the dataset's name */ (void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name)); zc.zc_obj = dsobj; if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_DSOBJ_TO_DSNAME, &zc) != 0) { /* just write out a path of two object numbers */ (void) snprintf(pathname, len, "<0x%llx>:<0x%llx>", (u_longlong_t) dsobj, (u_longlong_t) obj); return; } (void) strlcpy(dsname, zc.zc_value, sizeof (dsname)); /* find out if the dataset is mounted */ mounted = is_mounted(zhp->zpool_hdl, dsname, &mntpnt); /* get the corrupted object's path */ (void) strlcpy(zc.zc_name, dsname, sizeof (zc.zc_name)); zc.zc_obj = obj; if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_OBJ_TO_PATH, &zc) == 0) { if (mounted) { (void) snprintf(pathname, len, "%s%s", mntpnt, zc.zc_value); } else { (void) snprintf(pathname, len, "%s:%s", dsname, zc.zc_value); } } else { (void) snprintf(pathname, len, "%s:<0x%llx>", dsname, (u_longlong_t) obj); } free(mntpnt); } /* * Read the EFI label from the config, if a label does not exist then * pass back the error to the caller. If the caller has passed a non-NULL * diskaddr argument then we set it to the starting address of the EFI * partition. */ /* ZFS-FUSE: not implemented */ #if 0 static int read_efi_label(nvlist_t *config, diskaddr_t *sb) { char *path; int fd; char diskname[MAXPATHLEN]; int err = -1; if (nvlist_lookup_string(config, ZPOOL_CONFIG_PATH, &path) != 0) return (err); (void) snprintf(diskname, sizeof (diskname), "%s%s", RDISK_ROOT, strrchr(path, '/')); if ((fd = open(diskname, O_RDONLY|O_NDELAY)) >= 0) { struct dk_gpt *vtoc; if ((err = efi_alloc_and_read(fd, &vtoc)) >= 0) { if (sb != NULL) *sb = vtoc->efi_parts[0].p_start; efi_free(vtoc); } (void) close(fd); } return (err); } /* * determine where a partition starts on a disk in the current * configuration */ static diskaddr_t find_start_block(nvlist_t *config) { nvlist_t **child; uint_t c, children; diskaddr_t sb = MAXOFFSET_T; uint64_t wholedisk; if (nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_CHILDREN, &child, &children) != 0) { if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_WHOLE_DISK, &wholedisk) != 0 || !wholedisk) { return (MAXOFFSET_T); } if (read_efi_label(config, &sb) < 0) sb = MAXOFFSET_T; return (sb); } for (c = 0; c < children; c++) { sb = find_start_block(child[c]); if (sb != MAXOFFSET_T) { return (sb); } } return (MAXOFFSET_T); } #endif /* * Label an individual disk. The name provided is the short name, * stripped of any leading /dev path. */ /* ZFS-FUSE: not implemented */ #if 0 int zpool_label_disk(libzfs_handle_t *hdl, zpool_handle_t *zhp, char *name) { char path[MAXPATHLEN]; struct dk_gpt *vtoc; int fd; size_t resv = EFI_MIN_RESV_SIZE; uint64_t slice_size; diskaddr_t start_block; char errbuf[1024]; /* prepare an error message just in case */ (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN, "cannot label '%s'"), name); if (zhp) { nvlist_t *nvroot; if (pool_is_bootable(zhp)) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "EFI labeled devices are not supported on root " "pools.")); return (zfs_error(hdl, EZFS_POOL_NOTSUP, errbuf)); } verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0); if (zhp->zpool_start_block == 0) start_block = find_start_block(nvroot); else start_block = zhp->zpool_start_block; zhp->zpool_start_block = start_block; } else { /* new pool */ start_block = NEW_START_BLOCK; } (void) snprintf(path, sizeof (path), "%s/%s%s", RDISK_ROOT, name, BACKUP_SLICE); if ((fd = open(path, O_RDWR | O_NDELAY)) < 0) { /* * This shouldn't happen. We've long since verified that this * is a valid device. */ zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "unable to open device")); return (zfs_error(hdl, EZFS_OPENFAILED, errbuf)); } if (efi_alloc_and_init(fd, EFI_NUMPAR, &vtoc) != 0) { /* * The only way this can fail is if we run out of memory, or we * were unable to read the disk's capacity */ if (errno == ENOMEM) (void) no_memory(hdl); (void) close(fd); zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "unable to read disk capacity"), name); return (zfs_error(hdl, EZFS_NOCAP, errbuf)); } slice_size = vtoc->efi_last_u_lba + 1; slice_size -= EFI_MIN_RESV_SIZE; if (start_block == MAXOFFSET_T) start_block = NEW_START_BLOCK; slice_size -= start_block; vtoc->efi_parts[0].p_start = start_block; vtoc->efi_parts[0].p_size = slice_size; /* * Why we use V_USR: V_BACKUP confuses users, and is considered * disposable by some EFI utilities (since EFI doesn't have a backup * slice). V_UNASSIGNED is supposed to be used only for zero size * partitions, and efi_write() will fail if we use it. V_ROOT, V_BOOT, * etc. were all pretty specific. V_USR is as close to reality as we * can get, in the absence of V_OTHER. */ vtoc->efi_parts[0].p_tag = V_USR; (void) strcpy(vtoc->efi_parts[0].p_name, "zfs"); vtoc->efi_parts[8].p_start = slice_size + start_block; vtoc->efi_parts[8].p_size = resv; vtoc->efi_parts[8].p_tag = V_RESERVED; if (efi_write(fd, vtoc) != 0) { /* * Some block drivers (like pcata) may not support EFI * GPT labels. Print out a helpful error message dir- * ecting the user to manually label the disk and give * a specific slice. */ (void) close(fd); efi_free(vtoc); zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "try using fdisk(1M) and then provide a specific slice")); return (zfs_error(hdl, EZFS_LABELFAILED, errbuf)); } (void) close(fd); efi_free(vtoc); return (0); } static boolean_t supported_dump_vdev_type(libzfs_handle_t *hdl, nvlist_t *config, char *errbuf) { char *type; nvlist_t **child; uint_t children, c; verify(nvlist_lookup_string(config, ZPOOL_CONFIG_TYPE, &type) == 0); if (strcmp(type, VDEV_TYPE_RAIDZ) == 0 || strcmp(type, VDEV_TYPE_FILE) == 0 || strcmp(type, VDEV_TYPE_LOG) == 0 || strcmp(type, VDEV_TYPE_HOLE) == 0 || strcmp(type, VDEV_TYPE_MISSING) == 0) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "vdev type '%s' is not supported"), type); (void) zfs_error(hdl, EZFS_VDEVNOTSUP, errbuf); return (B_FALSE); } if (nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_CHILDREN, &child, &children) == 0) { for (c = 0; c < children; c++) { if (!supported_dump_vdev_type(hdl, child[c], errbuf)) return (B_FALSE); } } return (B_TRUE); } /* * check if this zvol is allowable for use as a dump device; zero if * it is, > 0 if it isn't, < 0 if it isn't a zvol */ int zvol_check_dump_config(char *arg) { zpool_handle_t *zhp = NULL; nvlist_t *config, *nvroot; char *p, *volname; nvlist_t **top; uint_t toplevels; libzfs_handle_t *hdl; char errbuf[1024]; char poolname[ZPOOL_MAXNAMELEN]; int pathlen = strlen(ZVOL_FULL_DEV_DIR); int ret = 1; if (strncmp(arg, ZVOL_FULL_DEV_DIR, pathlen)) { return (-1); } (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN, "dump is not supported on device '%s'"), arg); if ((hdl = libzfs_init()) == NULL) return (1); libzfs_print_on_error(hdl, B_TRUE); volname = arg + pathlen; /* check the configuration of the pool */ if ((p = strchr(volname, '/')) == NULL) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "malformed dataset name")); (void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf); return (1); } else if (p - volname >= ZFS_MAXNAMELEN) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "dataset name is too long")); (void) zfs_error(hdl, EZFS_NAMETOOLONG, errbuf); return (1); } else { (void) strncpy(poolname, volname, p - volname); poolname[p - volname] = '\0'; } if ((zhp = zpool_open(hdl, poolname)) == NULL) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "could not open pool '%s'"), poolname); (void) zfs_error(hdl, EZFS_OPENFAILED, errbuf); goto out; } config = zpool_get_config(zhp, NULL); if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvroot) != 0) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "could not obtain vdev configuration for '%s'"), poolname); (void) zfs_error(hdl, EZFS_INVALCONFIG, errbuf); goto out; } verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN, &top, &toplevels) == 0); if (toplevels != 1) { zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' has multiple top level vdevs"), poolname); (void) zfs_error(hdl, EZFS_DEVOVERFLOW, errbuf); goto out; } if (!supported_dump_vdev_type(hdl, top[0], errbuf)) { goto out; } ret = 0; out: if (zhp) zpool_close(zhp); libzfs_fini(hdl); return (ret); } #endif
pscedu/slash2-stable
zfs-fuse/src/lib/libzfs/libzfs_pool.c
C
isc
94,615
<!DOCTYPE HTML> <html lang="de"> <head> <!-- Generated by javadoc (17) --> <title>Source code</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="source: package: com.restfb.types.send, class: ListViewElement"> <meta name="generator" content="javadoc/SourceToHTMLConverter"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body class="source-page"> <main role="main"> <div class="source-container"> <pre><span class="source-line-no">001</span><span id="line-1">// Generated by delombok at Mon Feb 14 17:40:58 CET 2022</span> <span class="source-line-no">002</span><span id="line-2">/*</span> <span class="source-line-no">003</span><span id="line-3"> * Copyright (c) 2010-2022 Mark Allen, Norbert Bartels.</span> <span class="source-line-no">004</span><span id="line-4"> *</span> <span class="source-line-no">005</span><span id="line-5"> * Permission is hereby granted, free of charge, to any person obtaining a copy</span> <span class="source-line-no">006</span><span id="line-6"> * of this software and associated documentation files (the "Software"), to deal</span> <span class="source-line-no">007</span><span id="line-7"> * in the Software without restriction, including without limitation the rights</span> <span class="source-line-no">008</span><span id="line-8"> * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell</span> <span class="source-line-no">009</span><span id="line-9"> * copies of the Software, and to permit persons to whom the Software is</span> <span class="source-line-no">010</span><span id="line-10"> * furnished to do so, subject to the following conditions:</span> <span class="source-line-no">011</span><span id="line-11"> *</span> <span class="source-line-no">012</span><span id="line-12"> * The above copyright notice and this permission notice shall be included in</span> <span class="source-line-no">013</span><span id="line-13"> * all copies or substantial portions of the Software.</span> <span class="source-line-no">014</span><span id="line-14"> *</span> <span class="source-line-no">015</span><span id="line-15"> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR</span> <span class="source-line-no">016</span><span id="line-16"> * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,</span> <span class="source-line-no">017</span><span id="line-17"> * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE</span> <span class="source-line-no">018</span><span id="line-18"> * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER</span> <span class="source-line-no">019</span><span id="line-19"> * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,</span> <span class="source-line-no">020</span><span id="line-20"> * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN</span> <span class="source-line-no">021</span><span id="line-21"> * THE SOFTWARE.</span> <span class="source-line-no">022</span><span id="line-22"> */</span> <span class="source-line-no">023</span><span id="line-23">package com.restfb.types.send;</span> <span class="source-line-no">024</span><span id="line-24"></span> <span class="source-line-no">025</span><span id="line-25">import java.util.ArrayList;</span> <span class="source-line-no">026</span><span id="line-26">import java.util.Collections;</span> <span class="source-line-no">027</span><span id="line-27">import java.util.List;</span> <span class="source-line-no">028</span><span id="line-28">import com.restfb.Facebook;</span> <span class="source-line-no">029</span><span id="line-29">import com.restfb.exception.FacebookPreconditionException;</span> <span class="source-line-no">030</span><span id="line-30">import com.restfb.types.AbstractFacebookType;</span> <span class="source-line-no">031</span><span id="line-31"></span> <span class="source-line-no">032</span><span id="line-32">public class ListViewElement extends AbstractFacebookType {</span> <span class="source-line-no">033</span><span id="line-33"> @Facebook</span> <span class="source-line-no">034</span><span id="line-34"> private String title;</span> <span class="source-line-no">035</span><span id="line-35"> @Facebook</span> <span class="source-line-no">036</span><span id="line-36"> private String subtitle;</span> <span class="source-line-no">037</span><span id="line-37"> @Facebook("image_url")</span> <span class="source-line-no">038</span><span id="line-38"> private String imageUrl;</span> <span class="source-line-no">039</span><span id="line-39"> @Facebook("default_action")</span> <span class="source-line-no">040</span><span id="line-40"> private DefaultAction defaultAction;</span> <span class="source-line-no">041</span><span id="line-41"> @Facebook</span> <span class="source-line-no">042</span><span id="line-42"> private List&lt;AbstractButton&gt; buttons;</span> <span class="source-line-no">043</span><span id="line-43"></span> <span class="source-line-no">044</span><span id="line-44"> public ListViewElement(String title) {</span> <span class="source-line-no">045</span><span id="line-45"> this.title = title;</span> <span class="source-line-no">046</span><span id="line-46"> }</span> <span class="source-line-no">047</span><span id="line-47"></span> <span class="source-line-no">048</span><span id="line-48"> public boolean addButton(AbstractButton button) {</span> <span class="source-line-no">049</span><span id="line-49"> if (buttons == null) {</span> <span class="source-line-no">050</span><span id="line-50"> buttons = new ArrayList&lt;&gt;();</span> <span class="source-line-no">051</span><span id="line-51"> }</span> <span class="source-line-no">052</span><span id="line-52"> if (buttons.size() == 1) {</span> <span class="source-line-no">053</span><span id="line-53"> throw new FacebookPreconditionException("maximum of associated buttons is 1");</span> <span class="source-line-no">054</span><span id="line-54"> }</span> <span class="source-line-no">055</span><span id="line-55"> return buttons.add(button);</span> <span class="source-line-no">056</span><span id="line-56"> }</span> <span class="source-line-no">057</span><span id="line-57"></span> <span class="source-line-no">058</span><span id="line-58"> public List&lt;AbstractButton&gt; getButtons() {</span> <span class="source-line-no">059</span><span id="line-59"> if (buttons == null) {</span> <span class="source-line-no">060</span><span id="line-60"> return Collections.emptyList();</span> <span class="source-line-no">061</span><span id="line-61"> }</span> <span class="source-line-no">062</span><span id="line-62"> return Collections.unmodifiableList(buttons);</span> <span class="source-line-no">063</span><span id="line-63"> }</span> <span class="source-line-no">064</span><span id="line-64"></span> <span class="source-line-no">065</span><span id="line-65"> @java.lang.SuppressWarnings("all")</span> <span class="source-line-no">066</span><span id="line-66"> public String getTitle() {</span> <span class="source-line-no">067</span><span id="line-67"> return this.title;</span> <span class="source-line-no">068</span><span id="line-68"> }</span> <span class="source-line-no">069</span><span id="line-69"></span> <span class="source-line-no">070</span><span id="line-70"> @java.lang.SuppressWarnings("all")</span> <span class="source-line-no">071</span><span id="line-71"> public String getSubtitle() {</span> <span class="source-line-no">072</span><span id="line-72"> return this.subtitle;</span> <span class="source-line-no">073</span><span id="line-73"> }</span> <span class="source-line-no">074</span><span id="line-74"></span> <span class="source-line-no">075</span><span id="line-75"> @java.lang.SuppressWarnings("all")</span> <span class="source-line-no">076</span><span id="line-76"> public void setSubtitle(final String subtitle) {</span> <span class="source-line-no">077</span><span id="line-77"> this.subtitle = subtitle;</span> <span class="source-line-no">078</span><span id="line-78"> }</span> <span class="source-line-no">079</span><span id="line-79"></span> <span class="source-line-no">080</span><span id="line-80"> @java.lang.SuppressWarnings("all")</span> <span class="source-line-no">081</span><span id="line-81"> public String getImageUrl() {</span> <span class="source-line-no">082</span><span id="line-82"> return this.imageUrl;</span> <span class="source-line-no">083</span><span id="line-83"> }</span> <span class="source-line-no">084</span><span id="line-84"></span> <span class="source-line-no">085</span><span id="line-85"> @java.lang.SuppressWarnings("all")</span> <span class="source-line-no">086</span><span id="line-86"> public void setImageUrl(final String imageUrl) {</span> <span class="source-line-no">087</span><span id="line-87"> this.imageUrl = imageUrl;</span> <span class="source-line-no">088</span><span id="line-88"> }</span> <span class="source-line-no">089</span><span id="line-89"></span> <span class="source-line-no">090</span><span id="line-90"> @java.lang.SuppressWarnings("all")</span> <span class="source-line-no">091</span><span id="line-91"> public DefaultAction getDefaultAction() {</span> <span class="source-line-no">092</span><span id="line-92"> return this.defaultAction;</span> <span class="source-line-no">093</span><span id="line-93"> }</span> <span class="source-line-no">094</span><span id="line-94"></span> <span class="source-line-no">095</span><span id="line-95"> @java.lang.SuppressWarnings("all")</span> <span class="source-line-no">096</span><span id="line-96"> public void setDefaultAction(final DefaultAction defaultAction) {</span> <span class="source-line-no">097</span><span id="line-97"> this.defaultAction = defaultAction;</span> <span class="source-line-no">098</span><span id="line-98"> }</span> <span class="source-line-no">099</span><span id="line-99">}</span> </pre> </div> </main> </body> </html>
restfb/restfb.github.io
javadoc/src-html/com/restfb/types/send/ListViewElement.html
HTML
mit
10,136
using System.Collections.Generic; namespace ConsoleDemo.Visitor.v0 { public class CommandsManager { readonly List<object> items = new List<object>(); // The client class has a structure (a list in this case) of items (commands). // The client knows how to iterate through the structure // The client would need to do different operations on the items from the structure when iterating it } }
iQuarc/Code-Design-Training
DesignPatterns/ConsoleDemo/Visitor/v0/CommandsManager.cs
C#
mit
440
--- layout: page_home title: Home headerline: Design Club at IIIT-Delhi headerlinelink: /about/ newslink: /news/ projectslink: /projects/ ---
ink-iiitd/ink-iiitd.github.io
index.html
HTML
mit
142
var contenedor = {}; var json = []; var json_active = []; var timeout; var result = {}; $(document).ready(function() { $('#buscador').keyup(function() {   if (timeout) {     clearTimeout(timeout);     timeout = null;   }    timeout = setTimeout(function() { search(); }, 100); }); $("body").on('change', '#result', function() { result = $("#result").val(); load_content(json); }); $("body").on('click', '.asc', function() { var name = $(this).parent().attr('rel'); console.log(name); $(this).removeClass("asc").addClass("desc"); order(name, true); }); $("body").on('click', '.desc', function() { var name = $(this).parent().attr('rel'); $(this).removeClass("desc").addClass("asc"); order(name, false); }); }); function update(id,parent,valor){ for (var i=0; i< json.length; i++) { if (json[i].id === id){ json[i][parent] = valor; return; } } } function load_content(json) { max = result; data = json.slice(0, max); json_active = json; $("#numRows").html(json.length); contenedor.html(''); 2 var list = table.find("th[rel]"); var html = ''; $.each(data, function(i, value) { html += '<tr id="' + value.id + '">'; $.each(list, function(index) { valor = $(this).attr('rel'); if (valor != 'acction') { if ($(this).hasClass("editable")) { html += '<td><span class="edition" rel="' + value.id + '">' + value[valor] .substring(0, 60) +'</span></td>'; } else if($(this).hasClass("view")){ if(value[valor].length > 1){ var class_1 = $(this).data('class'); html += '<td><a href="javascript:void(0)" class="'+class_1+'" rel="'+ value[valor] + '" data-id="' + value.id + '"></a></td>'; }else{ html += '<td></td>'; } }else{ html += '<td>' + value[valor] + '</td>'; } } else { html += '<td>'; $.each(acction, function(k, data) { html += '<a class="' + data.class + '" rel="' + value[data.rel] + '" href="' + data.link + value[data.parameter] + '" target="'+data.target+'" >' + data.button + '</a>'; }); html += "</td>"; } if (index >= list.length - 1) { html += '</tr>'; contenedor.append(html); html = ''; } }); }); } function selectedRow(json) { var num = result; var rows = json.length; var total = rows / num; var cant = Math.floor(total); $("#result").html(''); for (i = 0; i < cant; i++) { $("#result").append("<option value=\"" + parseInt(num) + "\">" + num + "</option>"); num = num + result; } $("#result").append("<option value=\"" + parseInt(rows) + "\">" + rows + "</option>"); } function order(prop, asc) { json = json.sort(function(a, b) { if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0); else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0); }); contenedor.html(''); load_content(json); } function search() { var list = table.find("th[rel]"); var data = []; var serch = $("#buscador").val(); json.forEach(function(element, index, array) { $.each(list, function(index) { valor = $(this).attr('rel'); if (element[valor]) { if (element[valor].like('%' + serch + '%')) { data.push(element); return false; } } }); }); contenedor.html(''); load_content(data); } String.prototype.like = function(search) { if (typeof search !== 'string' || this === null) { return false; } search = search.replace(new RegExp("([\\.\\\\\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:\\-])", "g"), "\\$1"); search = search.replace(/%/g, '.*').replace(/_/g, '.'); return RegExp('^' + search + '$', 'gi').test(this); } function export_csv(JSONData, ReportTitle, ShowLabel) { var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData; var CSV = ''; // CSV += ReportTitle + '\r\n\n'; if (ShowLabel) { var row = ""; for (var index in arrData[0]) { row += index + ';'; } row = row.slice(0, -1); CSV += row + '\r\n'; } for (var i = 0; i < arrData.length; i++) { var row = ""; for (var index in arrData[i]) { row += '"' + arrData[i][index] + '";'; } row.slice(0, row.length - 1); CSV += row + '\r\n'; } if (CSV == '') { alert("Invalid data"); return; } // var fileName = "Report_"; //fileName += ReportTitle.replace(/ /g,"_"); var uri = 'data:text/csv;charset=utf-8,' + escape(CSV); var link = document.createElement("a"); link.href = uri; link.style = "visibility:hidden"; link.download = ReportTitle + ".csv"; document.body.appendChild(link); link.click(); document.body.removeChild(link); }
mpandolfelli/papelera
js/function.js
JavaScript
mit
5,520
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage YouTube * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Username.php 24594 2012-01-05 21:27:01Z matthew $ */ /** * @see Zend_Gdata_Extension */ // require_once 'Zend/Gdata/Extension.php'; /** * Represents the yt:username element * * @category Zend * @package Zend_Gdata * @subpackage YouTube * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_YouTube_Extension_Username extends Zend_Gdata_Extension { protected $_rootElement = 'username'; protected $_rootNamespace = 'yt'; public function __construct($text = null) { $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces); parent::__construct(); $this->_text = $text; } }
levfurtado/scoops
vendor/bombayworks/zendframework1/library/Zend/Gdata/YouTube/Extension/Username.php
PHP
mit
1,488
# MondrianRedisSegmentCache Mondrian ships with an in memory segment cache that is great for standalone deployments of Mondrian, but doesn't scale out with multiple nodes. An interface is provided for extending Mondrian with a shared Segment Cache and examples of other implementations are in the links below. In order to use Mondrian with Redis (our preferred caching layer) and Ruby (our preferred language -- Jruby) we had to implement the SegmentCache interface from Mondrian and use the Redis notifications api. Mondrian's segment cache needs to be able to get/set/remove cache items and also get any updates from the caching server as other nodes are getting/setting/removing entries. This means that we need to use both the notifications and subscribe api's from Redis. http://stackoverflow.com/questions/17533594/implementing-a-mondrian-shared-segmentcache http://mondrian.pentaho.com/api/mondrian/spi/SegmentCache.html https://github.com/pentaho/mondrian/blob/master/src/main/mondrian/rolap/cache/MemorySegmentCache.java https://github.com/webdetails/cdc http://redis.io/topics/notifications ## Installation Add this line to your application's Gemfile: gem 'mondrian_redis_segment_cache' And then execute: $ bundle Or install it yourself as: $ gem install mondrian_redis_segment_cache ## Usage If using Rails you can put the configuration in an initializer ```ruby require 'redis' require 'mondrian_redis_segment_cache' # Setup a Redis connection MONDRIAN_REDIS_CONNECTION = Redis.new(:url => "redis://localhost:1234/2") MONDRIAN_SEGMENT_CACHE = ::MondrianRedisSegmentCache::Cache.new(MONDRIAN_REDIS_CONNECTION) # Register the segment cache with the Mondrian Injector ::Java::MondrianSpi::SegmentCache::SegmentCacheInjector::add_cache(MONDRIAN_SEGMENT_CACHE) ``` In Redis we use the notifications api, so you must turn it on! It is off by default because it is a new feature and can be CPU intensive. Redis does a ton, so there is a minimum of notifications that must be turned on for this gem to work. `notify-keyspace-events Egex$` This tells Redis to publish keyevent events (which means we can subscribe to things like set/del) and to publish the generic commands (like DEL, EXPIRE) and finally String commands (like SET) The SegmentCache uses these notifications to keep Mondrian in sync across your Mondrian instances. It also eager loads the current cached items into the listeners when they are added to the cache. This allows an existing cache to be reused between deploys. Cache expiry is handled by the options `:ttl` and `:expires_at` If you want a static ttl (time to live) then each key that is inserted will be set to expire after the ttl completes. This is not always optimal for an analytics cache and you may want all keys to expire at the same time (potentially on a daily basis). If you want all keys to expire at the same time you should use `:expires_at` in the options hash. This should be the hour that you want all keys to expire on. 1 being 1am, 2 being 2am, 15 being 3pm and so on. ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request
film42/mondrian_redis_segment_cache
README.md
Markdown
mit
3,298
module V1 class EventUserSchedulesController < ApplicationController before_action :set_event_session, only: [:create] # POST /event_user_schedules def create @event_user_schedule = current_user.add_session_to_my_schedule(@event_session) if @event_user_schedule.save render json: @event_user_schedule, serializer: EventUserScheduleShortSerializer, root: "event_user_schedule", status: :created else render json: @event_user_schedule.errors, status: :unprocessable_entity end end # DELETE /event_user_schedules/:id def destroy @event_user_schedule = EventUserSchedule.find(params[:id]) if @event_user_schedule.event_user.user == current_user @event_user_schedule.destroy head :no_content else head :forbidden end end private # Never trust parameters from the scary internet, only allow the white list through. def event_user_schedule_params params.require(:event_user_schedule).permit(:event_session_id) end def set_event_session @event_session = EventSession.find(event_user_schedule_params[:event_session_id]) end end end
danjohnson3141/rest_api
app/controllers/v1/event_user_schedules_controller.rb
Ruby
mit
1,200
package com.jeecg.qywx.core.service; import com.jeecg.qywx.base.entity.QywxReceivetext; /** * 文本处理接口 * @author 付明星 * */ public interface TextDealInterfaceService { /** * 文本消息处理接口 * @param receiveText 文本消息实体类 */ void dealTextMessage(QywxReceivetext receiveText); }
xiongmaoshouzha/test
jeecg-p3-biz-qywx/src/main/java/com/jeecg/qywx/core/service/TextDealInterfaceService.java
Java
mit
326
<?php namespace EugeneTolok\Telegram\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateEugenetolokTelegramDialogsSteps2 extends Migration { public function up() { Schema::table('eugenetolok_telegram_dialogs_steps', function($table) { $table->increments('id'); }); } public function down() { Schema::table('eugenetolok_telegram_dialogs_steps', function($table) { $table->dropColumn('id'); }); } }
eugenetolok/easy-telegram-bot
updates/builder_table_update_eugenetolok_telegram_dialogs_steps_2.php
PHP
mit
553
import React from 'react'; import ons from 'onsenui'; import { Page, Toolbar, BackButton, LazyList, ListItem } from 'react-onsenui'; class InfiniteScroll extends React.Component { renderRow(index) { return ( <ListItem key={index}> {'Item ' + (index + 1)} </ListItem> ); } renderToolbar() { return ( <Toolbar> <div className='left'> <BackButton>Back</BackButton> </div> <div className='center'> Infinite scroll </div> </Toolbar> ); } render() { return ( <Page renderToolbar={this.renderToolbar}> <LazyList length={10000} renderRow={this.renderRow} calculateItemHeight={() => ons.platform.isAndroid() ? 77 : 45} /> </Page> ); } } module.exports = InfiniteScroll;
gnetsys/OnsenUIv2-React-PhoneGap-Starter-Kit
www/components/InfiniteScroll.js
JavaScript
mit
854
# docker_runner Run docker containers on the fly with ansible roles # running program Must be run with sudo privlegies example "sudo ruby drun.rb" The program launches a docker container that self-provisions based on the ROLE The ROLE value in the ruby file is the Ansible role, which will be run on the container The docker container shares a common directory with all other docker containers, the host and a private host folder The common directory should contain the ansible code used to self-provision the docker container The host directory will be the same as the container name, which is randomly generated # things to do Have Ruby code ask for the role to be run Enable multiple roles to be run on a single container Create a UI for deployment Enable easy creation of custom docker containers (templates of roles to run) * example: a go container with vim, zsh etc * one click deploy from a UI
svartblomma/docker_runner
README.md
Markdown
mit
907
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.datafactory.v2018_06_01; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** * The location of Google Cloud Storage dataset. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = GoogleCloudStorageLocation.class) @JsonTypeName("GoogleCloudStorageLocation") public class GoogleCloudStorageLocation extends DatasetLocation { /** * Specify the bucketName of Google Cloud Storage. Type: string (or * Expression with resultType string). */ @JsonProperty(value = "bucketName") private Object bucketName; /** * Specify the version of Google Cloud Storage. Type: string (or Expression * with resultType string). */ @JsonProperty(value = "version") private Object version; /** * Get specify the bucketName of Google Cloud Storage. Type: string (or Expression with resultType string). * * @return the bucketName value */ public Object bucketName() { return this.bucketName; } /** * Set specify the bucketName of Google Cloud Storage. Type: string (or Expression with resultType string). * * @param bucketName the bucketName value to set * @return the GoogleCloudStorageLocation object itself. */ public GoogleCloudStorageLocation withBucketName(Object bucketName) { this.bucketName = bucketName; return this; } /** * Get specify the version of Google Cloud Storage. Type: string (or Expression with resultType string). * * @return the version value */ public Object version() { return this.version; } /** * Set specify the version of Google Cloud Storage. Type: string (or Expression with resultType string). * * @param version the version value to set * @return the GoogleCloudStorageLocation object itself. */ public GoogleCloudStorageLocation withVersion(Object version) { this.version = version; return this; } }
selvasingh/azure-sdk-for-java
sdk/datafactory/mgmt-v2018_06_01/src/main/java/com/microsoft/azure/management/datafactory/v2018_06_01/GoogleCloudStorageLocation.java
Java
mit
2,402
<a href="/article/{{post.pk}}"> <div class="search-result post {{post.primary_section}}"> <span class="primary">{{ post.title }}</span> <div class="metadata"> <span class="date">{{post.published | date:"F j, Y"}}</span> {% for author in post.creators %} {% if author.name %} <span class="author">{{ author.name }}</span> {% endif %} {% endfor %} </div> <span class="excerpt">{{ post.excerpt|truncatewords:50 }}</span> </div> </a>
BowdoinOrient/bongo
bongo/apps/search/templates/search/post.html
HTML
mit
557
$js.module({ prerequisite:[ '/{$jshome}/modules/splice.module.extensions.js' ], imports:[ { Inheritance : '/{$jshome}/modules/splice.inheritance.js' }, {'SpliceJS.UI':'../splice.ui.js'}, 'splice.controls.pageloader.html' ], definition:function(){ var scope = this; var imports = scope.imports ; var Class = imports.Inheritance.Class , UIControl = imports.SpliceJS.UI.UIControl ; var PageLoader = Class(function PageLoaderController(){ this.base(); }).extend(UIControl); scope.exports( PageLoader ); } })
jonahgroup/SpliceJS.Modules
src/ui.controls/splice.controls.pageloader.js
JavaScript
mit
545
RSpec.describe AuthorizeIf do let(:controller) { double(:dummy_controller, controller_name: "dummy", action_name: "index"). extend(AuthorizeIf) } describe "#authorize_if" do context "when object is given" do it "returns true if truthy object is given" do expect(controller.authorize_if(true)).to eq true expect(controller.authorize_if(Object.new)).to eq true end it "raises NotAuthorizedError if falsey object is given" do expect { controller.authorize_if(false) }.to raise_error(AuthorizeIf::NotAuthorizedError) expect { controller.authorize_if(nil) }.to raise_error(AuthorizeIf::NotAuthorizedError) end end context "when object and block are given" do it "allows exception customization through the block" do expect { controller.authorize_if(false) do |exception| exception.message = "Custom Message" exception.context[:request_ip] = "192.168.1.1" end }.to raise_error(AuthorizeIf::NotAuthorizedError, "Custom Message") do |exception| expect(exception.message).to eq("Custom Message") expect(exception.context[:request_ip]).to eq("192.168.1.1") end end end context "when no arguments are given" do it "raises ArgumentError" do expect { controller.authorize_if }.to raise_error(ArgumentError) end end end describe "#authorize" do context "when corresponding authorization rule exists" do context "when rule does not accept parameters" do it "returns true if rule returns true" do controller.define_singleton_method(:authorize_index?) { true } expect(controller.authorize).to eq true end end context "when rule accepts parameters" do it "calls rule with given parameters" do class << controller def authorize_index?(param_1, param_2:) param_1 || param_2 end end expect(controller.authorize(false, param_2: true)).to eq true end end context "when block is given" do it "passes block through to `authorize_if` method" do controller.define_singleton_method(:authorize_index?) { false } expect { controller.authorize do |exception| exception.message = "passed through" end }.to raise_error(AuthorizeIf::NotAuthorizedError, "passed through") do |exception| expect(exception.message).to eq("passed through") end end end end context "when corresponding authorization rule does not exist" do it "raises MissingAuthorizationRuleError" do expect { controller.authorize }.to raise_error( AuthorizeIf::MissingAuthorizationRuleError, "No authorization rule defined for action dummy#index. Please define method #authorize_index? for #{controller.class.name}" ) end end end end
vrybas/authorize_if
spec/authorize_if_spec.rb
Ruby
mit
3,092
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("34_FactorialSum")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("34_FactorialSum")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("880c59c2-814b-4c4c-91b0-a6f62aa7f1f2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
steliyan/ProjectEuler
34_FactorialSum/Properties/AssemblyInfo.cs
C#
mit
1,406
namespace MyColors { partial class SimpleToolTip { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Dock = System.Windows.Forms.DockStyle.Fill; this.label1.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(0, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(305, 51); this.label1.TabIndex = 0; this.label1.Text = "label1"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // SimpleToolTip // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(305, 51); this.ControlBox = false; this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SimpleToolTip"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Text = "SimpleToolTip"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label label1; } }
cborrow/MyColors
SimpleToolTip.Designer.cs
C#
mit
2,497
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Gama.Atenciones.Wpf.Views { /// <summary> /// Interaction logic for SearchBoxView.xaml /// </summary> public partial class SearchBoxView : UserControl { public SearchBoxView() { InitializeComponent(); } } }
PFC-acl-amg/GamaPFC
GamaPFC/Gama.Atenciones.Wpf/Views/SearchBoxView.xaml.cs
C#
mit
663
<?php namespace Terrific\Composition\Entity; use Doctrine\ORM\Mapping as ORM; use JMS\SerializerBundle\Annotation\ReadOnly; use JMS\SerializerBundle\Annotation\Type; use JMS\SerializerBundle\Annotation\Exclude; use JMS\SerializerBundle\Annotation\Groups; use JMS\SerializerBundle\Annotation\Accessor; /** * Terrific\Composition\Entity\Module * * @ORM\Table(name="module") * @ORM\Entity(repositoryClass="Terrific\Composition\Entity\ModuleRepository") */ class Module { /** * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * @Groups({"project_list", "project_details", "module_list", "module_details"}) * @ReadOnly */ private $id; /** * @ORM\Column(name="in_work", type="boolean") * @Type("boolean") * @Groups({"project_list", "project_details", "module_list", "module_details"}) */ private $inWork = false; /** * @ORM\Column(name="shared", type="boolean") * @Type("boolean") * @Groups({"project_list", "project_details", "module_list", "module_details"}) */ private $shared = false; /** * @ORM\Column(name="title", type="string", length=255) * @Type("string") * @Groups({"project_list", "project_details", "module_list", "module_details"}) */ private $title; /** * @ORM\Column(name="description", type="text") * @Type("string") * @Groups({"project_list", "project_details", "module_list", "module_details"}) */ private $description; /** * @ORM\ManyToOne(targetEntity="Project") * @Type("integer") * @Groups({"module_details"}) */ private $project; /** * @ORM\OneToOne(targetEntity="Snippet") * @Type("Terrific\Composition\Entity\Snippet") * @Groups({"module_details"}) */ private $markup; /** * @ORM\OneToOne(targetEntity="Snippet") * @Type("Terrific\Composition\Entity\Snippet") * @Groups({"module_details"}) */ private $style; /** * @ORM\OneToOne(targetEntity="Snippet") * @Type("Terrific\Composition\Entity\Snippet") * @Groups({"module_details"}) */ private $script; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set title * * @param string $title */ public function setTitle($title) { $this->title = $title; } /** * Get title * * @return string */ public function getTitle() { return $this->title; } /** * Set description * * @param text $description */ public function setDescription($description) { $this->description = $description; } /** * Get description * * @return text */ public function getDescription() { return $this->description; } /** * Set markup * * @param Terrific\Composition\Entity\Snippet $markup */ public function setMarkup(\Terrific\Composition\Entity\Snippet $markup) { $this->markup = $markup; } /** * Get markup * * @return Terrific\Composition\Entity\Snippet */ public function getMarkup() { return $this->markup; } /** * Set style * * @param Terrific\Composition\Entity\Snippet $style */ public function setStyle(\Terrific\Composition\Entity\Snippet $style) { $this->style = $style; } /** * Get style * * @return Terrific\Composition\Entity\Snippet */ public function getStyle() { return $this->style; } /** * Set script * * @param Terrific\Composition\Entity\Snippet $script */ public function setScript(\Terrific\Composition\Entity\Snippet $script) { $this->script = $script; } /** * Get script * * @return Terrific\Composition\Entity\Snippet */ public function getScript() { return $this->script; } /** * Set project * * @param Terrific\Composition\Entity\Project $project * @return Module */ public function setProject(\Terrific\Composition\Entity\Project $project = null) { $this->project = $project; return $this; } /** * Get project * * @return Terrific\Composition\Entity\Project */ public function getProject() { return $this->project; } /** * Set inWork * * @param boolean $inWork * @return Module */ public function setInWork($inWork) { $this->inWork = $inWork; return $this; } /** * Get inWork * * @return boolean */ public function getInWork() { return $this->inWork; } /** * Set shared * * @param boolean $shared * @return Module */ public function setShared($shared) { $this->shared = $shared; return $this; } /** * Get shared * * @return boolean */ public function getShared() { return $this->shared; } }
brunschgi/terrific-io-old
src/Terrific/Composition/Entity/Module.php
PHP
mit
5,480
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="blog,python,django,developer"> <meta name="author" content="Derek Stegelman"> <title>Derek.Stegelman.Com | Tags</title> <link rel="stylesheet" href='http://derek.stegelman.com/assets/bootstrap/css/bootstrap.min.css'> <link rel="stylesheet" href='http://derek.stegelman.com/assets/css/main.min.css'> <link href='https://fonts.googleapis.com/css?family=Raleway:200italic,200' rel='stylesheet' type='text/css'> <link rel="stylesheet" href='http://derek.stegelman.com/assets/font-awesome/css/font-awesome.min.css'> <link href='assets/css/prisim.min.css' rel='stylesheet' /> <link href="http://derek.stegelman.com/tags/index.xml" rel="alternate" type="application/rss+xml" title="Derek.Stegelman.Com" /> <link href="http://derek.stegelman.com/tags/index.xml" rel="feed" type="application/rss+xml" title="Derek.Stegelman.Com" /> <meta property="og:title" content="Tags" /> <meta property="og:description" content="" /> <meta property="og:type" content="website" /> <meta property="og:url" content="http://derek.stegelman.com/tags/" /> <meta itemprop="name" content="Tags"> <meta itemprop="description" content=""> <meta name="twitter:card" content="summary"/><meta name="twitter:title" content="Tags"/> <meta name="twitter:description" content=""/> </head> <body> <header class=""> <div class='color-overlay'> </div> <h1><a href="/">Derek Stegelman</a></h1> <nav> <ul> <li> <a href="/posts/">Writing</a> </li> <li> <a href="/tech/">Technical Writing</a> </li> <li> <a href="/thoughts/">Thoughts</a> </li> <li> <a href="/about/">About</a> </li> </ul> </nav> </header> <div class="container-fluid"> <article class="cf pa3 pa4-m pa4-l"> <div class="measure-wide-l center f4 lh-copy nested-copy-line-height nested-links nested-img mid-gray"> </div> </article> <div class="mw8 center"> <section class="ph4"> </section> </div> </div> <footer> <div class='container-fluid'> <div class='row'> <div class='col-md-8 col-md-offset-2'> <nav> <ul> <li> <a href="/colophon/">Colophon</a> </li> <li> <a href="/talks/">Talks</a> </li> <li> <a href="/hire/">Hire</a> </li> <li> <a href="/rocketry/">Rocketry</a> </li> <li> <a href="/essays/">Essays</a> </li> <li> <a href="mailto:email@stegelman.com">Contact</a> </li> </ul> </nav> <nav class='pull-right'> <ul> <li> <a href="https://github.com/dstegelman/" target="_blank"><i class="fa fa-github fa-inverse" aria-hidden="true"></i></a> </li> <li> <a href="https://twitter.com/dstegelman" target="_blank"><i class="fa fa-twitter fa-inverse" aria-hidden="true"></i></a> </li> <li> <a href="https://www.instagram.com/dstegelman/" target="_blank"><i class="fa fa-instagram fa-inverse" aria-hidden="true"></i></a> </li> <li> <a href="https://www.linkedin.com/in/derek-stegelman-22570813/" target="_blank"><i class="fa fa-linkedin fa-inverse" aria-hidden="true"></i></a> </li> <li> <a href="mailto:email@stegelman.com"><i class="fa fa-envelope fa-inverse" aria-hidden="true"></i></a> </li> <li> <a href="/atom.xml"><i class="fa fa-rss fa-inverse" aria-hidden="true"></i></a> </li> </ul> </nav> </div> </div> </div> </footer> <script src='http://derek.stegelman.com/assets/js/prisim.js'></script> <script src='http://derek.stegelman.com/assets/js/jquery.min.js'></script> <script src='http://derek.stegelman.com/assets/bootstrap/js/bootstrap.min.js'></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-4439935-7', 'auto'); ga('send', 'pageview'); </script> </body> </html>
dstegelman/derek.stegelman.com
public/tags/index.html
HTML
mit
5,880
using System; using System.Collections; using System.Linq; using Xunit; namespace Popsql.Tests { public class SqlValuesTests { [Fact] public void Add_WithNullValues_ThrowsArgumentNull() { var values = new SqlValues(); Assert.Throws<ArgumentNullException>(() => values.Add(null)); } [Fact] public void Count_ReturnsNumberOfItems() { var values = new SqlValues(); Assert.Equal(0, values.Count); values.Add(Enumerable.Range(0, 5).Cast<SqlValue>()); Assert.Equal(1, values.Count); values.Add(Enumerable.Range(5, 10).Cast<SqlValue>()); Assert.Equal(2, values.Count); } [Fact] public void ExpressionType_ReturnsValues() { Assert.Equal(SqlExpressionType.Values, new SqlValues().ExpressionType); } [Fact] public void GetEnumerator_ReturnsEnumerator() { var values = new SqlValues { Enumerable.Range(0, 5).Cast<SqlValue>(), Enumerable.Range(5, 10).Cast<SqlValue>() }; var enumerator = ((IEnumerable) values).GetEnumerator(); Assert.NotNull(enumerator); int count = 0; while (enumerator.MoveNext()) { count++; } Assert.Equal(2, count); } } }
WouterDemuynck/popsql
src/Popsql.Tests/SqlValuesTests.cs
C#
mit
1,149
package se.dsv.waora.deviceinternetinformation; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.TextView; /** * <code>ConnectionActivity</code> presents UI for showing if the device * is connected to internet. * * @author Dushant Singh */ public class ConnectionActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initiate view TextView connectivityStatus = (TextView) findViewById(R.id.textViewDeviceConnectivity); // Get connectivity service. ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // Get active network information NetworkInfo activeNetwork = manager.getActiveNetworkInfo(); // Check if active network is connected. boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); if (isConnected) { // Set status connected connectivityStatus.setText(getString(R.string.online)); connectivityStatus.setTextColor(getResources().getColor(R.color.color_on)); // Check if connected with wifi boolean isWifiOn = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; if (isWifiOn) { // Set wifi status on TextView wifiTextView = (TextView) findViewById(R.id.textViewWifi); wifiTextView.setText(getString(R.string.on)); wifiTextView.setTextColor(getResources().getColor(R.color.color_on)); } else { // Set mobile data status on. TextView mobileDataTextView = (TextView) findViewById(R.id.textViewMobileData); mobileDataTextView.setText(getString(R.string.on)); mobileDataTextView.setTextColor(getResources().getColor(R.color.color_on)); } } } }
dushantSW/ip-mobile
7.3.1/DeviceInternetInformation/app/src/main/java/se/dsv/waora/deviceinternetinformation/ConnectionActivity.java
Java
mit
2,212
// // Constants.h // // #define LANGUAGES_API @"https://api.unfoldingword.org/obs/txt/1/obs-catalog.json" #define SELECTION_BLUE_COLOR [UIColor colorWithRed:76.0/255.0 green:185.0/255.0 blue:224.0/255.0 alpha:1.0] #define TEXT_COLOR_NORMAL [UIColor colorWithRed:32.0/255.0 green:27.0/255.0 blue:22.0/255.0 alpha:1.0] #define BACKGROUND_GRAY [UIColor colorWithRed:42.0/255.0 green:34.0/255.0 blue:26.0/255.0 alpha:1.0] #define BACKGROUND_GREEN [UIColor colorWithRed:170.0/255.0 green:208.0/255.0 blue:0.0/255.0 alpha:1.0] #define TABBAR_COLOR_TRANSPARENT [UIColor colorWithRed:42.0/255.0 green:34.0/255.0 blue:26.0/255.0 alpha:0.7] #define FONT_LIGHT [UIFont fontWithName:@"HelveticaNeue-Light" size:17] #define FONT_NORMAL [UIFont fontWithName:@"HelveticaNeue" size:17] #define FONT_MEDIUM [UIFont fontWithName:@"HelveticaNeue-Medium" size:17] #define LEVEL_1_DESC NSLocalizedString(@"Level 1: internal — Translator (or team) affirms that translation is in line with Statement of Faith and Translation Guidelines.", nil) #define LEVEL_2_DESC NSLocalizedString(@"Level 2: external — Translation is independently checked and confirmed by at least two others not on the translation team.", nil) #define LEVEL_3_DESC NSLocalizedString(@"Level 3: authenticated — Translation is checked and confirmed by leadership of at least one Church network with native speakers of the language.", nil) #define LEVEL_1_IMAGE @"level1Cell" #define LEVEL_2_IMAGE @"level2Cell" #define LEVEL_3_IMAGE @"level3Cell" #define LEVEL_1_REVERSE @"level1" #define LEVEL_2_REVERSE @"level2" #define LEVEL_3_REVERSE @"level3" #define IMAGE_VERIFY_GOOD @"verifyGood" #define IMAGE_VERIFY_FAIL @"verifyFail.png" #define IMAGE_VERIFY_EXPIRE @"verifyExpired.png" // Allows us to track the verse for each part of an attributed string static NSString *const USFM_VERSE_NUMBER = @"USFMVerseNumber"; static NSString *const SignatureFileAppend = @".sig"; // Duplicated in UWConstants.swift static NSString *const FileExtensionUFW = @"ufw"; /// Duplicated in UWConstants.swift // Duplicated in UWConstants.swift static NSString *const BluetoothSend = @"BluetoothSend"; static NSString *const BluetoothReceive = @"BluetoothReceive"; static NSString *const MultiConnectSend = @"MultiConnectSend"; static NSString *const MultiConnectReceive = @"MultiConnectReceive"; static NSString *const iTunesSend = @"iTunesSend"; static NSString *const iTunesReceive = @"iTunesReceive"; static NSString *const IMAGE_DIGLOT = @"diglot";
unfoldingWord-dev/uw-ios
app/UnfoldingWord/UnfoldingWord/Constants.h
C
mit
2,540
# Les patrons de conception ## Bibliothèque d'exemples en Java Ce dossier est un aide mémoire. Il consiste à répertorier les patrons de conception en Java. ### [La liste des exemples](https://github.com/ewenb/Java_patterns) * COMPOSITE : Il dispose les objets dans des structures arborescentes ex1 : Un exemple basique * VISITEUR : Il permet de proposer plusieurs interprétations de la structure sans toucher au Composite ex1 : Un exemple basique.
ewenb/Java_patterns
VISITEUR/README.md
Markdown
mit
464
.highlight { background-color: black; } .highlight .hll { background-color: #404040 } .highlight .c { color: #999999; font-style: italic } /* Comment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .g { color: #d0d0d0 } /* Generic */ .highlight .k { color: #6ab825; font-weight: bold } /* Keyword */ .highlight .l { color: #d0d0d0 } /* Literal */ .highlight .n { color: #d0d0d0 } /* Name */ .highlight .o { color: #d0d0d0 } /* Operator */ .highlight .x { color: #d0d0d0 } /* Other */ .highlight .p { color: #d0d0d0 } /* Punctuation */ .highlight .cm { color: #999999; font-style: italic } /* Comment.Multiline */ .highlight .cp { color: #cd2828; font-weight: bold } /* Comment.Preproc */ .highlight .c1 { color: #999999; font-style: italic } /* Comment.Single */ .highlight .cs { color: #e50808; font-weight: bold; background-color: #520000 } /* Comment.Special */ .highlight .gd { color: #d22323 } /* Generic.Deleted */ .highlight .ge { color: #d0d0d0; font-style: italic } /* Generic.Emph */ .highlight .gr { color: #d22323 } /* Generic.Error */ .highlight .gh { color: #ffffff; font-weight: bold } /* Generic.Heading */ .highlight .gi { color: #589819 } /* Generic.Inserted */ .highlight .go { color: #cccccc } /* Generic.Output */ .highlight .gp { color: #aaaaaa } /* Generic.Prompt */ .highlight .gs { color: #d0d0d0; font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #ffffff; text-decoration: underline } /* Generic.Subheading */ .highlight .gt { color: #d22323 } /* Generic.Traceback */ .highlight .kc { color: #6ab825; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #6ab825; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #6ab825; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #6ab825 } /* Keyword.Pseudo */ .highlight .kr { color: #6ab825; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #6ab825; font-weight: bold } /* Keyword.Type */ .highlight .ld { color: #d0d0d0 } /* Literal.Date */ .highlight .m { color: #3677a9 } /* Literal.Number */ .highlight .s { color: #ed9d13 } /* Literal.String */ .highlight .na { color: #bbbbbb } /* Name.Attribute */ .highlight .nb { color: #24909d } /* Name.Builtin */ .highlight .nc { color: #447fcf; text-decoration: underline } /* Name.Class */ .highlight .no { color: #40ffff } /* Name.Constant */ .highlight .nd { color: #ffa500 } /* Name.Decorator */ .highlight .ni { color: #d0d0d0 } /* Name.Entity */ .highlight .ne { color: #bbbbbb } /* Name.Exception */ .highlight .nf { color: #447fcf } /* Name.Function */ .highlight .nl { color: #d0d0d0 } /* Name.Label */ .highlight .nn { color: #447fcf; text-decoration: underline } /* Name.Namespace */ .highlight .nx { color: #d0d0d0 } /* Name.Other */ .highlight .py { color: #d0d0d0 } /* Name.Property */ .highlight .nt { color: #6ab825; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #40ffff } /* Name.Variable */ .highlight .ow { color: #6ab825; font-weight: bold } /* Operator.Word */ .highlight .w { color: #666666 } /* Text.Whitespace */ .highlight .mf { color: #3677a9 } /* Literal.Number.Float */ .highlight .mh { color: #3677a9 } /* Literal.Number.Hex */ .highlight .mi { color: #3677a9 } /* Literal.Number.Integer */ .highlight .mo { color: #3677a9 } /* Literal.Number.Oct */ .highlight .sb { color: #ed9d13 } /* Literal.String.Backtick */ .highlight .sc { color: #ed9d13 } /* Literal.String.Char */ .highlight .sd { color: #ed9d13 } /* Literal.String.Doc */ .highlight .s2 { color: #ed9d13 } /* Literal.String.Double */ .highlight .se { color: #ed9d13 } /* Literal.String.Escape */ .highlight .sh { color: #ed9d13 } /* Literal.String.Heredoc */ .highlight .si { color: #ed9d13 } /* Literal.String.Interpol */ .highlight .sx { color: #ffa500 } /* Literal.String.Other */ .highlight .sr { color: #ed9d13 } /* Literal.String.Regex */ .highlight .s1 { color: #ed9d13 } /* Literal.String.Single */ .highlight .ss { color: #ed9d13 } /* Literal.String.Symbol */ .highlight .bp { color: #24909d } /* Name.Builtin.Pseudo */ .highlight .vc { color: #40ffff } /* Name.Variable.Class */ .highlight .vg { color: #40ffff } /* Name.Variable.Global */ .highlight .vi { color: #40ffff } /* Name.Variable.Instance */ .highlight .il { color: #3677a9 } /* Literal.Number.Integer.Long */
fdutey/formol
app/assets/stylesheets/pygments/native.css
CSS
mit
4,325
--- author: admin comments: true date: 2010-03-26 09:48:35+00:00 layout: post slug: what-to-do-when-ubuntu-device-mapper-seems-to-be-invincible title: 'What to do when Ubuntu Device-mapper seems to be invincible! ' categories: - Instructional tags: - 64-bit - hard drive - hardware - linux - lucid lynx - Ubuntu - workstation --- I've been trying a dozen different configurations of my 2x500GB SATA drives over the past few days involving switching between ACHI/IDE/RAID in my bios (This was after trying different things to solve [my problems with Ubuntu Lucid Lynx]({{ BASE_PATH }}/2010/03/my-experience-with-ubuntu-10-04-lucid-lynx/)) ; After each attempt I've reset the bios option, booted into a live CD, deleting partitions and rewriting partition tables left on the drives. Now, however, I've been sitting with a /dev/mapper/nvidia_XXXXXXX1 that seems to be impossible to kill! It's the only 'partition' that I see in the Ubuntu install (but I can see the others in parted) but it is only the size of one of the drives, and I know I did not set any RAID levels other than RAID0. Thanks to [wazoox](http://perlmonks.org/?node_id=292373) for eliminating a possibility involving LVM issues with lvremove and vgremove, but I found what works for me. After a bit of experimenting, I tried > > > <code>$dmraid -r > </code> > > so see what raid sets were set up, then did > > > <code>$dmraid -x > </code> > > but was presented with > ERROR: Raid set deletion is not supported in "nvidia" format Googled this and found [this forum post](http://ubuntuforums.org/showthread.php?p=8417410) that told me to do this; > > > <code>$dmraid -rE > </code> > > And that went through, rebooted, hoped, waited (well, while i was waiting, set the bios back to AHCI), and repartitioned, and all of (this particular issue) was well again. Hope this helps someone else down the line! (This is a duplicate of my [ServerFault query](http://serverfault.com/questions/125976/ubuntu-device-mapper-seems-to-be-invincible) on this that I answered myself)
andrewbolster/andrewbolster.github.io
_posts/2010-03-26-what-to-do-when-ubuntu-device-mapper-seems-to-be-invincible.markdown
Markdown
mit
2,095
/* MIT License (From https://choosealicense.com/ ) Copyright (c) 2017 Jonathan Burget support@solarfusionsoftware.com 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.*/ #include "TigerEngine.h" // Global variable so the objects are not lost static TIGValue *theNumberStack; static TIGValue *theStringStack; static int stackNumber; static char *stackString; // ************* For debugging Purposes ************* TIGValue *TIGStringNumberStack(void) { return theNumberStack; } TIGValue *TIGStringStringStack(void) { return theStringStack; } // ************* For debugging Purposes ************* void TIGStringStartStack(const char *startStackString) { // If there is another start stack called before the end stack free it if (stackString != NULL) { free(stackString); stackString = NULL; } if (startStackString == NULL) { stackNumber++; } else { stackString = (char *)malloc((strlen(startStackString) + 1) * sizeof(char)); if (startStackString != NULL) { strcpy(stackString, startStackString); } } } void TIGStringEndStack(const char *endStackString) { if (endStackString != NULL) { while (theStringStack != NULL) { TIGValue *theNextStack = theStringStack->nextStack; // 0 means both strings are the same if (strcmp(theStringStack->stackString, endStackString) == 0) { theStringStack = TIGStringDestroy(theStringStack); } theStringStack = theNextStack; } } else { while (theNumberStack != NULL) { TIGValue *theNextStack = theNumberStack->nextStack; if (theNumberStack->stackNumber == stackNumber) { theNumberStack = TIGStringDestroy(theNumberStack); } theNumberStack = theNextStack; } } // If there is another end or start stack string called before this end stack free it if (stackString != NULL) { free(stackString); stackString = NULL; } if (endStackString == NULL) { stackNumber--; } } TIGValue *TIGStringCreate(TIGValue *tigString, TIGBool useStack) { tigString = (TIGValue *)malloc(1 * sizeof(TIGValue)); if (tigString == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringCreate() Variable:tigString Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } if (useStack) { if (stackString != NULL) { if (theStringStack == NULL) { tigString->nextStack = NULL; } // Add the last added TIGString to the new tigString's ->nextStack else { tigString->nextStack = theStringStack; } tigString->stackNumber = -1; tigString->stackString = (char *)malloc((strlen(stackString) + 1) * sizeof(char)); if (tigString->stackString != NULL) { strcpy(tigString->stackString, stackString); } else { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringCreate() Variable:tigString->stackString Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif } // This adds the new tigString to the global TIGString stack theStringStack = tigString; } else { if (theNumberStack == NULL) { tigString->nextStack = NULL; } // Add the last added TIGString to the new tigString's ->nextStack else { tigString->nextStack = theNumberStack; } tigString->stackNumber = stackNumber; tigString->stackString = NULL; // This adds the tigString to the global TIGString stack theNumberStack = tigString; } } else { tigString->nextStack = NULL; tigString->stackString = NULL; tigString->stackNumber = -2; } tigString->nextLevel = NULL; tigString->thisLevel = NULL; tigString->number = 0.0; // Sets the TIGObject's string to an empty string tigString->string = NULL; // object type tigString->type = "String"; return tigString; } TIGValue *TIGStringDestroy(TIGValue *tigString) { // If the "tigString" pointer has already been used free it if (tigString != NULL) { if (strcmp(tigString->type, "String") != 0) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringDestroy() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return tigString; } if (tigString->string != NULL) { free(tigString->string); tigString->string = NULL; } if (tigString->stackString != NULL) { free(tigString->stackString); tigString->stackString = NULL; } tigString->number = 0.0; tigString->stackNumber = 0; tigString->type = NULL; tigString->nextStack = NULL; tigString->nextLevel = NULL; tigString->thisLevel = NULL; free(tigString); tigString = NULL; } return tigString; } TIGValue *TIGStr(const char *string) { return TIGStringInput(NULL, string); } TIGValue *TIGStringInput(TIGValue *tigString, const char *string) { return TIGStringStackInput(tigString, string, TIGYes); } TIGValue *TIGStringStackInput(TIGValue *tigString, const char *string, TIGBool useStack) { if (tigString == NULL) { tigString = TIGStringCreate(tigString, useStack); if (tigString == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringStackInput() Variable:tigString Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } } else if (strcmp(tigString->type, "String") != 0) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringStackInput() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } // If there is already a string free it if (tigString->string != NULL) { free(tigString->string); tigString->string = NULL; } tigString->string = (char *)malloc((strlen(string) + 1) * sizeof(char)); if (tigString->string == NULL || string == NULL) { #ifdef TIG_DEBUG if (string == NULL) { printf("ERROR Function:TIGStringStackInput() Variable:string Equals:NULL\n"); } if (tigString->string == NULL) { printf("ERROR Function:TIGStringStackInput() Variable:tigString->string Equals:NULL\n"); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } else { strcpy(tigString->string, string); } return tigString; } char *TIGStringOutput(TIGValue *tigString) { if (tigString == NULL || tigString->string == NULL || strcmp(tigString->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringOutput() Variable:tigString Equals:NULL\n"); } else { if (tigString->string == NULL) { printf("ERROR Function:TIGStringOutput() Variable:tigString->string Equals:NULL\n"); } if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringOutput() Variable:tigString->string Equals:%s Valid:\"String\"\n", tigString->type); } } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } else { return tigString->string; } } TIGInteger TIGStringLength(TIGValue *tigString) { if (tigString == NULL || tigString->string == NULL || strcmp(tigString->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringLength() Variable:tigString Equals:NULL\n"); } else { if (tigString->string == NULL) { printf("ERROR Function:TIGStringLength() Variable:tigString->string Equals:NULL\n"); } if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringLength() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); } } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return -1; } //if (tigString != NULL && tigString->string != NULL && strcmp(tigString->type, "String") == 0) else { return (int)strlen(tigString->string); } } TIGValue *TIGStringInsertStringAtIndex(TIGValue *tigString1, TIGValue *tigString2, int index) { if (tigString1 == NULL || tigString2 == NULL || strcmp(tigString1->type, "String") != 0 || strcmp(tigString2->type, "String") != 0 || index < 0 || index > TIGStringLength(tigString1)) { #ifdef TIG_DEBUG if (tigString1 == NULL) { printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:tigString1 Equals:NULL\n"); } else if (strcmp(tigString1->type, "String") != 0) { printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:tigNumber Equals:%s Valid:\"String\"\n", tigString1->type); } if (tigString2 == NULL) { printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:tigString2 Equals:NULL\n"); } else if (strcmp(tigString2->type, "String") != 0) { printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:tigNumber Equals:%s Valid:\"String\"\n", tigString2->type); } if (index < 0 || index > TIGStringLength(tigString1)) { printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:index Equals:%d Valid:0 to %d\n", index, TIGStringLength(tigString1)); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } char *newString = (char *)malloc(strlen(tigString1->string) + strlen(tigString2->string) + 1); if (index == strlen(tigString1->string)) { strcat(newString, tigString1->string); strcat(newString, tigString2->string); } else { char character[2]; int i; for (i = 0; i < strlen(tigString1->string); i++) { character[0] = tigString1->string[i]; character[1] = '\0'; if (index == i) { strcat(newString, tigString2->string); } strcat(newString, character); } } TIGValue *theString = TIGStringInput(NULL, newString); free(newString); newString = NULL; return theString; } TIGValue *TIGStringCharacterAtIndex(TIGValue *tigString, int index) { if (tigString == NULL || index < 0 || index >= TIGStringLength(tigString)) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringCharacterAtIndex() Variable:tigString Equals:NULL\n"); } if (index < 0 || index >= TIGStringLength(tigString)) { printf("ERROR Function:TIGStringCharacterAtIndex() Variable:index Equals:%d Valid:0 to %d\n", index, TIGStringLength(tigString) - 1); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } char *character = TIGStringOutput(tigString); return TIGStringWithFormat(NULL, "%c", character[index]); } void TIGStringRemoveCharacterAtIndex(TIGValue *tigString, int index) { if (tigString == NULL || index < 0 || index >= TIGStringLength(tigString)) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringRemoveCharacterAtIndex() Variable:tigString Equals:NULL\n"); } if (index < 0 || index >= TIGStringLength(tigString)) { printf("ERROR Function:TIGStringRemoveCharacterAtIndex() Variable:index Equals:%d Valid:0 to %d\n", index, TIGStringLength(tigString) - 1); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return; } int length = TIGStringLength(tigString); char *characters = TIGStringOutput(tigString); // Since a character is being removed don't add +1 to the malloc length char *newCharacters = (char *)malloc(length * sizeof(char)); int newIndex = 0; int i; for (i = 0; i < length; i++) { if (index != i) { newCharacters[newIndex] = characters[i]; newIndex++; } } TIGStringInput(tigString, newCharacters); free(newCharacters); newCharacters = NULL; } TIGValue *TIGStringFromNumber(TIGValue *tigNumber) { if (tigNumber == NULL || strcmp(tigNumber->type, "Number") != 0) { #ifdef TIG_DEBUG if (tigNumber == NULL) { printf("ERROR Function:TIGStringFromNumber() Variable:tigNumber Equals:NULL\n"); } else if (strcmp(tigNumber->type, "Number") != 0) { printf("ERROR Function:TIGStringFromNumber() Variable:tigNumber->type Equals:%s Valid:\"Number\"\n", tigNumber->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } else { int stringLength = snprintf( NULL, 0, "%f", tigNumber->number) + 1; char *stringBuffer = (char *)malloc(stringLength * sizeof(char)); if (stringBuffer == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringFromNumber() Variable:stringBuffer Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } snprintf(stringBuffer, stringLength, "%f", tigNumber->number); TIGValue *tigString = TIGStringInput(NULL, stringBuffer); free(stringBuffer); stringBuffer = NULL; return tigString; } } TIGBool TIGStringEqualsString(TIGValue *tigString1, TIGValue *tigString2) { if (tigString1 != NULL && strcmp(tigString1->type, "String") == 0 && tigString2 != NULL && strcmp(tigString2->type, "String") == 0 && strcmp(tigString1->string, tigString2->string) == 0) { return TIGYes; } return TIGNo; } TIGValue *TIGStringObjectType(TIGValue *tigObject) { if (tigObject == NULL || tigObject->type == NULL) { #ifdef TIG_DEBUG if (tigObject == NULL) { printf("ERROR Function:TIGStringObjectType() Variable:tigObject Equals:NULL\n"); } else if (tigObject->type == NULL) { printf("ERROR Function:TIGStringObjectType() Variable:tigObject->type Equals:NULL\n"); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } return TIGStringInput(NULL, tigObject->type); } TIGValue *TIGStringAddEscapeCharacters(TIGValue *tigString) { if (tigString == NULL || strcmp(tigString->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringAddEscapeCharacters() Variable:tigString Equals:NULL\n"); } else if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringAddEscapeCharacters() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } char *string = tigString->string; int extraCount = 0; int i; for (i = 0; i < strlen(string); i++) { switch (string[i]) { case '"': case '\\': case '/': case '\b': case '\f': case '\n': case '\r': case '\t': extraCount++; break; } } if (extraCount > 0) { char *newString = (char *)malloc((strlen(string) + extraCount + 1) * sizeof(char)); int index = 0; if (newString == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringAddEscapeCharacters() Variable:newString Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } for (i = 0; i < strlen(string); i++) { switch (string[i]) { case '\"': newString[index] = '\\'; newString[index + 1] = '"'; index += 2; break; case '\\': newString[index] = '\\'; newString[index + 1] = '\\'; index += 2; break; case '/': newString[index] = '\\'; newString[index + 1] = '/'; index += 2; break; case '\b': newString[index] = '\\'; newString[index + 1] = 'b'; index += 2; break; case '\f': newString[index] = '\\'; newString[index + 1] = 'f'; index += 2; break; case '\n': newString[index] = '\\'; newString[index + 1] = 'n'; index += 2; break; case '\r': newString[index] = '\\'; newString[index + 1] = 'r'; index += 2; break; case '\t': newString[index] = '\\'; newString[index + 1] = 't'; index += 2; break; default: newString[index] = string[i]; index++; break; } } TIGValue *theNewTIGString = TIGStringInput(NULL, newString); free(newString); newString = NULL; return theNewTIGString; } return tigString; } TIGValue *TIGStringRemoveEscapeCharacters(TIGValue *tigString) { if (tigString == NULL || strcmp(tigString->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringRemoveEscapeCharacters() Variable:tigString Equals:NULL\n"); } else if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringRemoveEscapeCharacters() Variable:tigObject->type Equals:%s Valid:\"String\"\n", tigString->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } char *string = tigString->string; int extraCount = 0; int i; for (i = 0; i < strlen(string); i++) { if (string[i] == '\\') { switch (string[i + 1]) { case '"': case '\\': case '/': case 'b': case 'f': case 'n': case 'r': case 't': extraCount++; // Below makes sure it is not read as something like \\t instead of \\ and \t i++; break; } } } //printf("extraCount %d\n", extraCount); if (extraCount > 0) { char *newString = (char *)malloc(((strlen(string) - extraCount) + 1) * sizeof(char)); int index = 0; if (newString == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringRemoveEscapeCharacters() Variable:newString Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } for (i = 0; i < strlen(string); i++) { if (string[i] == '\\') { switch (string[i + 1]) { case '\"': newString[index] = '"'; index++; i++; break; case '\\': newString[index] = '\\'; index++; i++; break; case '/': newString[index] = '/'; index++; i++; break; case 'b': newString[index] = '\b'; index++; i++; break; case 'f': newString[index] = '\f'; index++; i++; break; case 'n': newString[index] = '\n'; index++; i++; break; case 'r': newString[index] = '\r'; index++; i++; break; case 't': newString[index] = '\t'; index++; i++; break; } } else { newString[index] = string[i]; index++; } } newString[index] = '\0'; TIGValue *theNewTIGString = TIGStringInput(NULL, newString); if (newString != NULL) { free(newString); newString = NULL; } return theNewTIGString; } return tigString; } TIGValue *TIGStringWithFormat(TIGValue *tigString, const char *format, ...) { va_list arguments; // Find out how long the string is when the arguments are converted to text va_start(arguments, format); int stringLength = vsnprintf( NULL, 0, format, arguments) + 1; va_end(arguments); // Create the new buffer with the new string length char *stringBuffer = (char *)malloc(stringLength * sizeof(char)); if (stringBuffer == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringWithFormat() Variable:stringBuffer Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } else { // Use the new length of text and add the arguments to the new string buffer va_start(arguments, format); vsnprintf(stringBuffer, stringLength, format, arguments); va_end(arguments); if (stringBuffer != NULL) { if (tigString == NULL) { tigString = TIGStringInput(tigString, stringBuffer); } else if (tigString->string != NULL && strcmp(tigString->type, "String") == 0) { //printf("Length: %d\n", (int)(strlen(tigString->string) + stringLength)); // stringLength already has +1 added to it for the '\0' so adding another +1 below is not necessary tigString->string = (char *)realloc(tigString->string, (strlen(tigString->string) + stringLength) * sizeof(char)); strcat(tigString->string, stringBuffer); } } else { #ifdef TIG_DEBUG if (tigString->string == NULL) { printf("ERROR Function:TIGStringWithFormat() Variable:tigString->string Equals:NULL\n"); } if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringWithFormat() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } free(stringBuffer); stringBuffer = NULL; } return tigString; } TIGValue *TIGStringWithAddedString(TIGValue *oldTigString, TIGValue *newTigString) { if (oldTigString == NULL || newTigString == NULL || oldTigString->string == NULL) { #ifdef TIG_DEBUG if (oldTigString == NULL) { printf("ERROR Function:TIGStringWithAddedString() Variable:oldTigString Equals:NULL\n"); } else if (oldTigString->string == NULL) { printf("ERROR Function:TIGStringWithAddedString() Variable:oldTigString->string Equals:NULL\n"); } if (newTigString == NULL) { printf("ERROR Function:TIGStringWithAddedString() Variable:newTigString Equals:NULL\n"); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } oldTigString = TIGStringInsertStringAtIndex(oldTigString, newTigString, (int)strlen(oldTigString->string)); return oldTigString; } TIGValue *TIGStringFromObject(TIGValue *tigObject) { if (tigObject == NULL || strcmp(tigObject->type, "Object") != 0) { #ifdef TIG_DEBUG if (tigObject == NULL) { printf("ERROR Function:TIGStringFromObject() Variable:tigObject Equals:NULL\n"); } else if (strcmp(tigObject->type, "Object") != 0) { printf("ERROR Function:TIGStringFromObject() Variable:tigObject->type Equals:%s Valid:\"Object\"\n", tigObject->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } TIGObjectStartStack(NULL); TIGArrayStartStack(NULL); TIGNumberStartStack(NULL); TIGValue *theString = TIGStringFromObjectWithLevel(NULL, tigObject, 1, TIGYes); TIGNumberEndStack(NULL); TIGArrayEndStack(NULL); TIGObjectEndStack(NULL); return theString; } TIGValue *TIGStringFromObjectForNetwork(TIGValue *tigObject) { if (tigObject == NULL || strcmp(tigObject->type, "Object") != 0) { #ifdef TIG_DEBUG if (tigObject == NULL) { printf("ERROR Function:TIGStringFromObjectForNetwork() Variable:tigObject Equals:NULL\n"); } else if (strcmp(tigObject->type, "Object") != 0) { printf("ERROR Function:TIGStringFromObjectForNetwork() Variable:tigObject->type Equals:%s Valid:\"Object\"\n", tigObject->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } TIGObjectStartStack(NULL); TIGArrayStartStack(NULL); TIGNumberStartStack(NULL); TIGValue *theString = TIGStringFromObjectWithLevel(NULL, tigObject, 1, TIGNo); TIGNumberEndStack(NULL); TIGArrayEndStack(NULL); TIGObjectEndStack(NULL); return theString; } TIGValue *TIGStringFromArray(TIGValue *tigArray) { if (tigArray == NULL || strcmp(tigArray->type, "Array") != 0) { #ifdef TIG_DEBUG if (tigArray == NULL) { printf("ERROR Function:TIGStringFromArray() Variable:tigArray Equals:NULL\n"); } else if (strcmp(tigArray->type, "Array") != 0) { printf("ERROR Function:TIGStringFromArray() Variable:tigArray->type Equals:%s Valid:\"Array\"\n", tigArray->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } TIGObjectStartStack(NULL); TIGArrayStartStack(NULL); TIGNumberStartStack(NULL); TIGValue *theString = TIGStringFromObjectWithLevel(NULL, tigArray, 1, TIGYes); TIGNumberEndStack(NULL); TIGArrayEndStack(NULL); TIGObjectEndStack(NULL); return theString; } TIGValue *TIGStringFromArrayForNetwork(TIGValue *tigArray) { if (tigArray == NULL || strcmp(tigArray->type, "Array") != 0) { #ifdef TIG_DEBUG if (tigArray == NULL) { printf("ERROR Function:TIGStringFromArrayForNetwork() Variable:tigArray Equals:NULL\n"); } else if (strcmp(tigArray->type, "Array") != 0) { printf("ERROR Function:TIGStringFromArrayForNetwork() Variable:tigArray->type Equals:%s Valid:\"Array\"\n", tigArray->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } TIGObjectStartStack(NULL); TIGArrayStartStack(NULL); TIGNumberStartStack(NULL); TIGValue *theString = TIGStringFromObjectWithLevel(NULL, tigArray, 1, TIGNo); TIGNumberEndStack(NULL); TIGArrayEndStack(NULL); TIGObjectEndStack(NULL); return theString; } // The JSON string outputs a TIGString but the functions below have their own stack TIGValue *TIGStringFromObjectWithLevel(TIGValue *tigString, TIGValue *tigValue, int level, TIGBool useEscapeCharacters) { int i; if (strcmp(tigValue->type, "Array") == 0) { TIGValue *theTIGStringTabs = NULL; TIGValue *theTIGStringEndTab = NULL; if (useEscapeCharacters) { for (i = 0; i < level; i++) { theTIGStringTabs = TIGStringWithFormat(theTIGStringTabs, "\t"); if (i < level - 1) { theTIGStringEndTab = TIGStringWithFormat(theTIGStringEndTab, "\t"); } } tigString = TIGStringWithFormat(tigString, "[\n"); } else { tigString = TIGStringWithFormat(tigString, "["); } for (i = 0; i < TIGArrayCount(tigValue); i++) { TIGValue *theTIGValue = TIGArrayValueAtIndex(tigValue, i); if (useEscapeCharacters) { tigString = TIGStringWithAddedString(tigString, theTIGStringTabs); } tigString = TIGStringFromObjectWithLevel(tigString, theTIGValue, level + 1, useEscapeCharacters); if (useEscapeCharacters) { if (i < TIGArrayCount(tigValue) - 1) { tigString = TIGStringWithFormat(tigString, ",\n"); } else { tigString = TIGStringWithFormat(tigString, "\n"); } } else { if (i < TIGArrayCount(tigValue) - 1) { tigString = TIGStringWithFormat(tigString, ","); } } } if (level > 1 && useEscapeCharacters) { tigString = TIGStringWithAddedString(tigString, theTIGStringEndTab); } tigString = TIGStringWithFormat(tigString, "]"); } else if (strcmp(tigValue->type, "Number") == 0) { if (tigValue->string != NULL) { if (strcmp(tigValue->string, "false") == 0 || strcmp(tigValue->string, "true") == 0) { tigString = TIGStringWithAddedString(tigString, TIGStringInput(NULL, tigValue->string)); } } else { tigString = TIGStringWithAddedString(tigString, TIGStringFromNumber(tigValue)); } } else if (strcmp(tigValue->type, "Object") == 0) { TIGValue *theTIGArrayStrings = TIGArrayOfObjectStrings(tigValue); TIGValue *theTIGArrayValues = TIGArrayOfObjectValues(tigValue); TIGValue *theTIGStringTabs = NULL; TIGValue *theTIGStringEndTab = NULL; if (useEscapeCharacters) { for (i = 0; i < level; i++) { theTIGStringTabs = TIGStringWithFormat(theTIGStringTabs, "\t"); if (i < level - 1) { theTIGStringEndTab = TIGStringWithFormat(theTIGStringEndTab, "\t"); } } tigString = TIGStringWithFormat(tigString, "{\n"); } else { tigString = TIGStringWithFormat(tigString, "{"); } for (i = 0; i < TIGArrayCount(theTIGArrayStrings); i++) { TIGValue *theTIGString = TIGArrayValueAtIndex(theTIGArrayStrings, i); TIGValue *theTIGValue = TIGArrayValueAtIndex(theTIGArrayValues, i); if (useEscapeCharacters) { tigString = TIGStringWithAddedString(tigString, theTIGStringTabs); tigString = TIGStringWithFormat(tigString, "\"%s\": ", TIGStringOutput(TIGStringAddEscapeCharacters(theTIGString))); } else { tigString = TIGStringWithFormat(tigString, "\"%s\":", TIGStringOutput(TIGStringAddEscapeCharacters(theTIGString))); } tigString = TIGStringFromObjectWithLevel(tigString, theTIGValue, level + 1, useEscapeCharacters); if (useEscapeCharacters) { if (i < TIGArrayCount(theTIGArrayStrings) - 1) { tigString = TIGStringWithFormat(tigString, ",\n"); } else { tigString = TIGStringWithFormat(tigString, "\n"); } } else { if (i < TIGArrayCount(theTIGArrayStrings) - 1) { tigString = TIGStringWithFormat(tigString, ","); } } } if (level > 1 && useEscapeCharacters) { tigString = TIGStringWithAddedString(tigString, theTIGStringEndTab); } tigString = TIGStringWithFormat(tigString, "}"); } else if (strcmp(tigValue->type, "String") == 0) { tigString = TIGStringWithFormat(tigString, "\"%s\"", TIGStringOutput(TIGStringAddEscapeCharacters(tigValue))); } return tigString; } void TIGStringWriteWithFilename(TIGValue *tigString, TIGValue *filenameString) { if (tigString == NULL || filenameString == NULL || strcmp(tigString->type, "String") != 0 || strcmp(filenameString->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:tigString Equals:NULL\n"); } else if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); } if (filenameString == NULL) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:filenameString Equals:NULL\n"); } else if (strcmp(filenameString->type, "String") != 0) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:filenameString->type Equals:%s Valid:\"String\"\n", filenameString->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif } else { FILE *theFile = fopen(filenameString->string, "w"); if (theFile != NULL) { fprintf(theFile, "%s", tigString->string); } else { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringWriteWithFilename() Variable:theFile Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif } fclose(theFile); } } TIGValue *TIGStringReadFromFilename(TIGValue *filenameString) { if (filenameString == NULL || filenameString->string == NULL || strcmp(filenameString->type, "String") != 0) { if (filenameString == NULL) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:tigString Equals:NULL\n"); } else { if (strcmp(filenameString->type, "String") != 0) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:filenameString->type Equals:%s Valid:\"String\"\n", filenameString->type); } if (filenameString->string == NULL) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:filenameString->string Equals:NULL\n"); } } return NULL; } FILE *theFile = fopen(filenameString->string, "r"); int index = 0, block = 1, maxBlockLength = 100; char *newString = NULL; char *buffer = malloc(maxBlockLength * sizeof(char)); if (theFile == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringReadFromFilename() Variable:theFile Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif if (buffer != NULL) { free(buffer); buffer = NULL; } fclose(theFile); return NULL; } if (buffer == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringReadFromFilename() Variable:buffer Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif fclose(theFile); return NULL; } while (1) { buffer[index] = fgetc(theFile); if ((buffer[index] != EOF && index >= maxBlockLength - 2) || buffer[index] == EOF) { int stringLength; buffer[index + 1] = '\0'; if (newString == NULL) { stringLength = 0; } else { stringLength = (int)strlen(newString); } if (buffer[index] == EOF) { //printf("END Buffer: %d String Length: %d\n", (int)strlen(buffer), stringLength); // Since the "buffer" variable already has '\0' +1 is not needed newString = realloc(newString, (strlen(buffer) + stringLength) * sizeof(char)); } else { //printf("Buffer: %d String Length: %d\n", (int)strlen(buffer), stringLength); newString = realloc(newString, (strlen(buffer) + stringLength) * sizeof(char)); } if (newString == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringReadFromFilename() Variable:newString Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif free(buffer); buffer = NULL; fclose(theFile); return NULL; } strcat(newString, buffer); if (buffer[index] == EOF) { //printf("Total String Length: %d", (int)strlen(newString)); // Since the "buffer" always uses the same size block '\0' with -1 is needed for the last index number newString[strlen(newString) - 1] = '\0'; free(buffer); buffer = NULL; break; } else { free(buffer); buffer = NULL; buffer = malloc(maxBlockLength * sizeof(char)); index = -1; block++; } } index++; } fclose(theFile); TIGValue *theString = TIGStringInput(NULL, newString); free(newString); newString = NULL; return theString; } TIGBool TIGStringPrefix(TIGValue *tigString, TIGValue *tigStringPrefix) { if (tigString == NULL || strcmp(tigString->type, "String") != 0 || tigStringPrefix == NULL || strcmp(tigStringPrefix->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringPrefix() Variable:tigString Equals:NULL\n"); } else if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringPrefix() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); } if (tigStringPrefix == NULL) { printf("ERROR Function:TIGStringPrefix() Variable:tigStringPrefix Equals:NULL\n"); } else if (strcmp(tigStringPrefix->type, "String") != 0) { printf("ERROR Function:TIGStringPrefix() Variable:tigStringPrefix->type Equals:%s Valid:\"String\"\n", tigStringPrefix->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return TIGNo; } if (strlen(tigString->string) > 0 && strlen(tigStringPrefix->string) > 0) { int i; for (i = 0; i < strlen(tigString->string); i++) { if (tigString->string[i] == tigStringPrefix->string[i]) { // The prefix has been found if (i >= strlen(tigStringPrefix->string) - 1) { return TIGYes; } } else { return TIGNo; } } } return TIGNo; } TIGBool TIGStringSuffix(TIGValue *tigString, TIGValue *tigStringSuffix) { if (tigString == NULL || strcmp(tigString->type, "String") != 0 || tigStringSuffix == NULL || strcmp(tigStringSuffix->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringSuffix() Variable:tigString Equals:NULL\n"); } else if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringSuffix() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); } if (tigStringSuffix == NULL) { printf("ERROR Function:TIGStringSuffix() Variable:tigStringSuffix Equals:NULL\n"); } else if (strcmp(tigStringSuffix->type, "String") != 0) { printf("ERROR Function:TIGStringSuffix() Variable:tigStringSuffix->type Equals:%s Valid:\"String\"\n", tigStringSuffix->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return TIGNo; } if (strlen(tigString->string) > 0 && strlen(tigStringSuffix->string) > 0) { int suffixIndex = 0, suffixTotal = (int)strlen(tigStringSuffix->string), index = 0, total = (int)strlen(tigString->string); while (1) { if (tigString->string[total - index - 1] == tigStringSuffix->string[suffixTotal - suffixIndex - 1]) { // The suffix was found if (suffixIndex >= suffixTotal - 1) { return TIGYes; } suffixIndex++; index++; } else { return TIGNo; } } } return TIGNo; }
TigerFusion/TigerEngine
TIGString.c
C
mit
36,020
package com.github.kwoin.kgate.core.sequencer; import com.github.kwoin.kgate.core.message.Message; import com.github.kwoin.kgate.core.session.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.SocketException; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.CountDownLatch; /** * @author P. WILLEMET */ public abstract class AbstractSequencer<T extends Message> implements Iterator<T> { private final Logger logger = LoggerFactory.getLogger(AbstractSequencer.class); protected Session<T> session; protected boolean hasNext; protected final ByteArrayOutputStream baos = new ByteArrayOutputStream(); protected @Nullable CountDownLatch oppositeSessionSignal; public void setSession(Session<T> session) { this.session = session; hasNext = !session.getInput().isInputShutdown(); } @Override public boolean hasNext() { hasNext &= !session.getInput().isClosed(); return hasNext; } @Override @Nullable public T next() { if(!hasNext()) throw new NoSuchElementException(); baos.reset(); if(oppositeSessionSignal != null) { try { oppositeSessionSignal.await(); } catch (InterruptedException e) { logger.warn("Waiting for opposite session signal interrupted"); oppositeSessionSignal = null; } } try { return readNextMessage(); } catch (SocketException e) { logger.debug("Input read() interrupted because socket has been closed"); hasNext = false; return null; } catch (IOException e) { logger.error("Unexpected error while reading next message", e); return null; } finally { resetState(); } } protected abstract T readNextMessage() throws IOException; protected abstract void resetState(); protected void waitForOppositeSessionSignal() { if(oppositeSessionSignal == null) { logger.debug("Wait for opposite session..."); oppositeSessionSignal = new CountDownLatch(1); } } public void oppositeSessionSignal() { if(oppositeSessionSignal != null) { logger.debug("wait for opposite session RELEASED"); oppositeSessionSignal.countDown(); } } protected byte readByte() throws IOException { int read = session.getInput().getInputStream().read(); baos.write(read); return (byte) read; } protected byte[] readBytes(int n) throws IOException { byte[] bytes = new byte[n]; for (int i = 0; i < n; i++) bytes[i] = readByte(); return bytes; } protected byte[] readUntil(byte[] end, boolean withEnd) throws IOException { int read; int cursor = 0; ByteArrayOutputStream tmpBaos = new ByteArrayOutputStream(); while(cursor < end.length) { read = readByte(); cursor = read == end[cursor] ? cursor + 1 : 0; tmpBaos.write(read); } byte[] bytes = tmpBaos.toByteArray(); return withEnd ? bytes : Arrays.copyOf(bytes, bytes.length - end.length); } }
Kwoin/KGate
kgate-core/src/main/java/com/github/kwoin/kgate/core/sequencer/AbstractSequencer.java
Java
mit
3,496
/*! * jQuery JavaScript Library v1.8.3 -css,-effects,-offset,-dimensions * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Mon Nov 19 2012 11:58:00 GMT-0800 (PST) */ (function( window, undefined ) { var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, navigator = window.navigator, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Save a reference to some core methods core_push = Array.prototype.push, core_slice = Array.prototype.slice, core_indexOf = Array.prototype.indexOf, core_toString = Object.prototype.toString, core_hasOwn = Object.prototype.hasOwnProperty, core_trim = String.prototype.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, // Used for detecting and trimming whitespace core_rnotwhite = /\S/, core_rspace = /\s+/, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // The ready event handler and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context && context.nodeType ? context.ownerDocument || context : document ); // scripts is true for back-compat selector = jQuery.parseHTML( match[1], doc, true ); if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { this.attr.call( selector, context, true ); } return jQuery.merge( this, selector ); // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.8.3 -css,-effects,-offset,-dimensions", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ), "slice", core_slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ core_toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // scripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, scripts ) { var parsed; if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { scripts = context; context = 0; } context = context || document; // Single tag if ( (parsed = rsingleTag.exec( data )) ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); return jQuery.merge( [], (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && core_rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var name, i = 0, length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); if ( args ) { if ( isObj ) { for ( name in obj ) { if ( callback.apply( obj[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( obj[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in obj ) { if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var type, ret = results || []; if ( arr != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 type = jQuery.type( arr ); if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { core_push.call( ret, arr ); } else { jQuery.merge( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready, 1 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.split( core_rspace ), function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? function() { var returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } } : newDefer[ action ] ); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] = list.fire deferred[ tuple[0] ] = list.fire; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: ( document.compatMode === "CSS1Compat" ), // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", clickFn = function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent("onclick"); div.detachEvent( "onclick", clickFn ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; input.setAttribute( "checked", "checked" ); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Run tests that need a body at doc ready jQuery(function() { var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = document.createElement("div"); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; div.appendChild( marginDiv ); support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); container.style.zoom = 1; } // Null elements to avoid leaks in IE body.removeChild( container ); container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE fragment.removeChild( div ); all = a = select = opt = input = fragment = div = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // Remove at next major release (1.9/2.0) uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery.removeData( elem, type + "queue", true ); jQuery.removeData( elem, key, true ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, fixSpecified, rclass = /[\t\r\n]/g, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea|)$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var removes, className, elem, c, cl, i, l; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { removes = ( value || "" ).split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { className = (" " + elem.className + " ").replace( rclass, " " ); // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } elem.className = value ? jQuery.trim( className ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( core_rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 attrFn: {}, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.split( core_rspace ); for ( ; i < attrNames.length; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.value = value + "" ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, "events", true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event, namespaces = []; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; for ( old = elem; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old === (elem.ownerDocument || document) ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = core_slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) event.metaKey = !!event.metaKey; return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "_submit_attached" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "_submit_attached", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "_change_attached", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var cachedruns, dirruns, sortOrder, siblingCheck, assertGetIdNotName, document = window.document, docElem = document.documentElement, strundefined = "undefined", hasDuplicate = false, baseHasDuplicate = true, done = 0, slice = [].slice, push = [].push, expando = ( "sizcache" + Math.random() ).replace( ".", "" ), // Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)", pos = ":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)", combinators = whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*", groups = "(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|" + attributes + "|" + pseudos.replace( 2, 7 ) + "|[^\\\\(),])+", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcombinators = new RegExp( "^" + combinators ), // All simple (non-comma) selectors, excluding insignifant trailing whitespace rgroups = new RegExp( groups + "?(?=" + whitespace + "*,|$)", "g" ), // A selector, or everything after leading whitespace // Optionally followed in either case by a ")" for terminating sub-selectors rselector = new RegExp( "^(?:(?!,)(?:(?:^|,)" + whitespace + "*" + groups + ")*?|" + whitespace + "*(.*?))(\\)|$)" ), // All combinators and selector components (attribute test, tag, pseudo, etc.), the latter appearing together when consecutive rtokens = new RegExp( groups.slice( 19, -6 ) + "\\x20\\t\\r\\n\\f>+~])+|" + combinators, "g" ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, rheader = /h\d/i, rinputs = /input|select|textarea|button/i, rbackslash = /\\(?!\\)/g, matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "[-", "[-\\*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|nth|last|first)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "POS": new RegExp( pos, "ig" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, classCache = {}, cachedClasses = [], compilerCache = {}, cachedSelectors = [], // Mark a function for use in filtering markFunction = function( fn ) { fn.sizzleFilter = true; return fn; }, // Returns a function to use in pseudos for input types createInputFunction = function( type ) { return function( elem ) { // Check the input's nodeName and type return elem.nodeName.toLowerCase() === "input" && elem.type === type; }; }, // Returns a function to use in pseudos for buttons createButtonFunction = function( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; }, // Used for testing something on an element assert = function( fn ) { var pass = false, div = document.createElement("div"); try { pass = fn( div ); } catch (e) {} // release memory in IE div = null; return pass; }, // Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }), // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName( expando ).length === // buggy browsers will return more than the correct 0 2 + document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }), // Check if the browser returns only elements // when doing getElementsByTagName("*") assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return div.getElementsByTagName("*").length === 0; }), // Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }), // Check if getElementsByClassName can be trusted assertUsableClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return false; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; return div.getElementsByClassName("e").length !== 1; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( nodeType !== 1 && nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } xml = isXML( context ); if ( !xml && !seed ) { if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } } // All others return select( selector, context, results, seed, xml ); }; var Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, match: matchExpr, order: [ "ID", "TAG" ], attrHandle: {}, createPseudo: markFunction, find: { "ID": assertGetIdNotName ? function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } } : function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }, "TAG": assertTagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { var elem, tmp = [], i = 0; for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; } }, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( rbackslash, "" ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr.CHILD 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1] === "nth" ) { // nth-child requires argument if ( !match[2] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); // other types prohibit arguments } else if ( match[2] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var argument, unquoted = match[4]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Relinquish our claim on characters in `unquoted` from a closing parenthesis on if ( unquoted && (argument = rselector.exec( unquoted )) && argument.pop() ) { match[0] = match[0].slice( 0, argument[0].length - unquoted.length - 1 ); unquoted = argument[0].slice( 0, -1 ); } // Quoted or unquoted, we have the full argument // Return only captures needed by the pseudo filter method (type and argument) match.splice( 2, 3, unquoted || match[3] ); return match; } }, filter: { "ID": assertGetIdNotName ? function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { return elem.getAttribute("id") === id; }; } : function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className ]; if ( !pattern ) { pattern = classCache[ className ] = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ); cachedClasses.push( className ); // Avoid too large of a cache if ( cachedClasses.length > Expr.cacheLength ) { delete classCache[ cachedClasses.shift() ]; } } return function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }; }, "ATTR": function( name, operator, check ) { if ( !operator ) { return function( elem ) { return Sizzle.attr( elem, name ) != null; }; } return function( elem ) { var result = Sizzle.attr( elem, name ), value = result + ""; if ( result == null ) { return operator === "!="; } switch ( operator ) { case "=": return value === check; case "!=": return value !== check; case "^=": return check && value.indexOf( check ) === 0; case "*=": return check && value.indexOf( check ) > -1; case "$=": return check && value.substr( value.length - check.length ) === check; case "~=": return ( " " + value + " " ).indexOf( check ) > -1; case "|=": return value === check || value.substr( 0, check.length + 1 ) === check + "-"; } }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { var doneName = done++; return function( elem ) { var parent, diff, count = 0, node = elem; if ( first === 1 && last === 0 ) { return true; } parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.sizset) ) { for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.sizset = ++count; if ( node === elem ) { break; } } } parent[ expando ] = doneName; } diff = elem.sizset - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } }; } return function( elem ) { var node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; } }; }, "PSEUDO": function( pseudo, argument, context, xml ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters var fn = Expr.pseudos[ pseudo ] || Expr.pseudos[ pseudo.toLowerCase() ]; if ( !fn ) { Sizzle.error( "unsupported pseudo: " + pseudo ); } // The user may set fn.sizzleFilter to indicate // that arguments are needed to create the filter function // just as Sizzle does if ( !fn.sizzleFilter ) { return fn; } return fn( argument, context, xml ); } }, pseudos: { "not": markFunction(function( selector, context, xml ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var matcher = compile( selector.replace( rtrim, "$1" ), context, xml ); return function( elem ) { return !matcher( elem ); }; }), "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while ( elem ) { if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { return false; } elem = elem.nextSibling; } return true; }, "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "header": function( elem ) { return rheader.test( elem.nodeName ); }, "text": function( elem ) { var type, attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); }, // Input types "radio": createInputFunction("radio"), "checkbox": createInputFunction("checkbox"), "file": createInputFunction("file"), "password": createInputFunction("password"), "image": createInputFunction("image"), "submit": createButtonFunction("submit"), "reset": createButtonFunction("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "focus": function( elem ) { var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { "first": function( elements, argument, not ) { return not ? elements.slice( 1 ) : [ elements[0] ]; }, "last": function( elements, argument, not ) { var elem = elements.pop(); return not ? elements : [ elem ]; }, "even": function( elements, argument, not ) { var results = [], i = not ? 1 : 0, len = elements.length; for ( ; i < len; i = i + 2 ) { results.push( elements[i] ); } return results; }, "odd": function( elements, argument, not ) { var results = [], i = not ? 0 : 1, len = elements.length; for ( ; i < len; i = i + 2 ) { results.push( elements[i] ); } return results; }, "lt": function( elements, argument, not ) { return not ? elements.slice( +argument ) : elements.slice( 0, +argument ); }, "gt": function( elements, argument, not ) { return not ? elements.slice( 0, +argument + 1 ) : elements.slice( +argument + 1 ); }, "eq": function( elements, argument, not ) { var elem = elements.splice( +argument, 1 ); return not ? elements : elem; } } }; // Deprecated Expr.setFilters["nth"] = Expr.setFilters["eq"]; // Back-compat Expr.filters = Expr.pseudos; // IE6/7 return a modified href if ( !assertHrefNotNormalized ) { Expr.attrHandle = { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }; } // Add getElementsByName if usable if ( assertUsableName ) { Expr.order.push("NAME"); Expr.find["NAME"] = function( name, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }; } // Add getElementsByClassName if usable if ( assertUsableClassName ) { Expr.order.splice( 1, 0, "CLASS" ); Expr.find["CLASS"] = function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } }; } // If slice is not available, provide a backup try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } var isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Element contains another var contains = Sizzle.contains = docElem.compareDocumentPosition ? function( a, b ) { return !!( a.compareDocumentPosition( b ) & 16 ); } : docElem.contains ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ var getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes } else { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } return ret; }; Sizzle.attr = function( elem, name ) { var attr, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( Expr.attrHandle[ name ] ) { return Expr.attrHandle[ name ]( elem ); } if ( assertAttributes || xml ) { return elem.getAttribute( name ); } attr = elem.getAttributeNode( name ); return attr ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : attr.specified ? attr.value : null : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; // Check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { return (baseHasDuplicate = 0); }); if ( docElem.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, i = 1; if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; function multipleContexts( selector, contexts, results, seed ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results, seed ); } } function handlePOSGroup( selector, posfilter, argument, contexts, seed, not ) { var results, fn = Expr.setFilters[ posfilter.toLowerCase() ]; if ( !fn ) { Sizzle.error( posfilter ); } if ( selector || !(results = seed) ) { multipleContexts( selector || "*", contexts, (results = []), seed ); } return results.length > 0 ? fn( results, argument, not ) : []; } function handlePOS( selector, context, results, seed, groups ) { var match, not, anchor, ret, elements, currentContexts, part, lastIndex, i = 0, len = groups.length, rpos = matchExpr["POS"], // This is generated here in case matchExpr["POS"] is extended rposgroups = new RegExp( "^" + rpos.source + "(?!" + whitespace + ")", "i" ), // This is for making sure non-participating // matching groups are represented cross-browser (IE6-8) setUndefined = function() { var i = 1, len = arguments.length - 2; for ( ; i < len; i++ ) { if ( arguments[i] === undefined ) { match[i] = undefined; } } }; for ( ; i < len; i++ ) { // Reset regex index to 0 rpos.exec(""); selector = groups[i]; ret = []; anchor = 0; elements = seed; while ( (match = rpos.exec( selector )) ) { lastIndex = rpos.lastIndex = match.index + match[0].length; if ( lastIndex > anchor ) { part = selector.slice( anchor, match.index ); anchor = lastIndex; currentContexts = [ context ]; if ( rcombinators.test(part) ) { if ( elements ) { currentContexts = elements; } elements = seed; } if ( (not = rendsWithNot.test( part )) ) { part = part.slice( 0, -5 ).replace( rcombinators, "$&*" ); } if ( match.length > 1 ) { match[0].replace( rposgroups, setUndefined ); } elements = handlePOSGroup( part, match[1], match[2], currentContexts, elements, not ); } } if ( elements ) { ret = ret.concat( elements ); if ( (part = selector.slice( anchor )) && part !== ")" ) { if ( rcombinators.test(part) ) { multipleContexts( part, ret, results, seed ); } else { Sizzle( part, context, results, seed ? seed.concat(elements) : elements ); } } else { push.apply( results, ret ); } } else { Sizzle( selector, context, results, seed ); } } // Do not sort if this is a single filter return len === 1 ? results : Sizzle.uniqueSort( results ); } function tokenize( selector, context, xml ) { var tokens, soFar, type, groups = [], i = 0, // Catch obvious selector issues: terminal ")"; nonempty fallback match // rselector never fails to match *something* match = rselector.exec( selector ), matched = !match.pop() && !match.pop(), selectorGroups = matched && selector.match( rgroups ) || [""], preFilters = Expr.preFilter, filters = Expr.filter, checkContext = !xml && context !== document; for ( ; (soFar = selectorGroups[i]) != null && matched; i++ ) { groups.push( tokens = [] ); // Need to make sure we're within a narrower context if necessary // Adding a descendant combinator will generate what is needed if ( checkContext ) { soFar = " " + soFar; } while ( soFar ) { matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { soFar = soFar.slice( match[0].length ); // Cast descendant combinators to space matched = tokens.push({ part: match.pop().replace( rtrim, " " ), captures: match }); } // Filters for ( type in filters ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match, context, xml )) ) ) { soFar = soFar.slice( match.shift().length ); matched = tokens.push({ part: type, captures: match }); } } if ( !matched ) { break; } } } if ( !matched ) { Sizzle.error( selector ); } return groups; } function addCombinator( matcher, combinator, context ) { var dir = combinator.dir, doneName = done++; if ( !matcher ) { // If there is no matcher to check, check against the context matcher = function( elem ) { return elem === context; }; } return combinator.first ? function( elem, context ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 ) { return matcher( elem, context ) && elem; } } } : function( elem, context ) { var cache, dirkey = doneName + "." + dirruns, cachedkey = dirkey + "." + cachedruns; while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 ) { if ( (cache = elem[ expando ]) === cachedkey ) { return elem.sizset; } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { if ( elem.sizset ) { return elem; } } else { elem[ expando ] = cachedkey; if ( matcher( elem, context ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } }; } function addMatcher( higher, deeper ) { return higher ? function( elem, context ) { var result = deeper( elem, context ); return result && higher( result === true ? elem : result, context ); } : deeper; } // ["TAG", ">", "ID", " ", "CLASS"] function matcherFromTokens( tokens, context, xml ) { var token, matcher, i = 0; for ( ; (token = tokens[i]); i++ ) { if ( Expr.relative[ token.part ] ) { matcher = addCombinator( matcher, Expr.relative[ token.part ], context ); } else { token.captures.push( context, xml ); matcher = addMatcher( matcher, Expr.filter[ token.part ].apply( null, token.captures ) ); } } return matcher; } function matcherFromGroupMatchers( matchers ) { return function( elem, context ) { var matcher, j = 0; for ( ; (matcher = matchers[j]); j++ ) { if ( matcher(elem, context) ) { return true; } } return false; }; } var compile = Sizzle.compile = function( selector, context, xml ) { var tokens, group, i, cached = compilerCache[ selector ]; // Return a cached group function if already generated (context dependent) if ( cached && cached.context === context ) { return cached; } // Generate a function of recursive functions that can be used to check each element group = tokenize( selector, context, xml ); for ( i = 0; (tokens = group[i]); i++ ) { group[i] = matcherFromTokens( tokens, context, xml ); } // Cache the compiled function cached = compilerCache[ selector ] = matcherFromGroupMatchers( group ); cached.context = context; cached.runs = cached.dirruns = 0; cachedSelectors.push( selector ); // Ensure only the most recent are cached if ( cachedSelectors.length > Expr.cacheLength ) { delete compilerCache[ cachedSelectors.shift() ]; } return cached; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; var select = function( selector, context, results, seed, xml ) { // Remove excessive whitespace selector = selector.replace( rtrim, "$1" ); var elements, matcher, i, len, elem, token, type, findContext, notTokens, match = selector.match( rgroups ), tokens = selector.match( rtokens ), contextNodeType = context.nodeType; // POS handling if ( matchExpr["POS"].test(selector) ) { return handlePOS( selector, context, results, seed, match ); } if ( seed ) { elements = slice.call( seed, 0 ); // To maintain document order, only narrow the // set if there is one group } else if ( match && match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID if ( tokens.length > 1 && contextNodeType === 9 && !xml && (match = matchExpr["ID"].exec( tokens[0] )) ) { context = Expr.find["ID"]( match[1], context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } findContext = ( (match = rsibling.exec( tokens[0] )) && !match.index && context.parentNode ) || context; // Get the last token, excluding :not notTokens = tokens.pop(); token = notTokens.split(":not")[0]; for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = matchExpr[ type ].exec( token )) ) { elements = Expr.find[ type ]( (match[1] || "").replace( rbackslash, "" ), findContext, xml ); if ( elements == null ) { continue; } if ( token === notTokens ) { selector = selector.slice( 0, selector.length - notTokens.length ) + token.replace( matchExpr[ type ], "" ); if ( !selector ) { push.apply( results, slice.call(elements, 0) ); } } break; } } } // Only loop over the given elements once // If selector is empty, we're already done if ( selector ) { matcher = compile( selector, context, xml ); dirruns = matcher.dirruns++; if ( elements == null ) { elements = Expr.find["TAG"]( "*", (rsibling.test( selector ) && context.parentNode) || context ); } for ( i = 0; (elem = elements[i]); i++ ) { cachedruns = matcher.runs++; if ( matcher(elem, context) ) { results.push( elem ); } } } return results; }; if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, rbuggyQSA = [], // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [":active"], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { div.innerHTML = "<select><option selected></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here (do not put tests after this one) if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if ( div.querySelectorAll("[test^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'>"; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if ( !seed && !xml && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( context.nodeType === 9 ) { try { push.apply( results, slice.call(context.querySelectorAll( selector ), 0) ); return results; } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var old = context.getAttribute("id"), nid = old || expando, newContext = rsibling.test( selector ) && context.parentNode || context; if ( old ) { nid = nid.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } try { push.apply( results, slice.call( newContext.querySelectorAll( selector.replace( rgroups, "[id='" + nid + "'] $&" ) ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } return oldSelect( selector, context, results, seed, xml ); }; if ( matches ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); rbuggyMatches.push( Expr.match.PSEUDO ); } catch ( e ) {} }); // rbuggyMatches always contains :active, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && (!rbuggyQSA || !rbuggyQSA.test( expr )) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, null, null, [ elem ] ).length > 0; }; } })(); } // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, l, length, n, r, ret, self = this; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } ret = this.pushStack( "", "find", selector ); for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rcheckableType = /^(?:checkbox|radio)$/, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "X<div>", "</div>" ]; } jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); } }, after: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { if ( !isDisconnected( this[0] ) ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = [].concat.apply( [], args ); var results, first, fragment, iNoClone, i = 0, value = args[0], scripts = [], l = this.length; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call( this, i, table ? self.html() : undefined ); self.domManip( args, table, callback ); }); } if ( this[0] ) { results = jQuery.buildFragment( args, this, scripts ); fragment = results.fragment; first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). // Fragments from the fragment cache must always be cloned and never used in place. for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], i === iNoClone ? fragment : jQuery.clone( fragment, true, true ) ); } } // Fix #11809: Avoid leaking memory fragment = first = null; if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { if ( jQuery.ajax ) { jQuery.ajax({ url: elem.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.error("no ajax"); } } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); if ( nodeName === "object" ) { // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, context, scripts ) { var fragment, cacheable, cachehit, first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { // Mark cacheable and look for a hit cacheable = true; fragment = jQuery.fragments[ first ]; cachehit = fragment !== undefined; } if ( !fragment ) { fragment = context.createDocumentFragment(); jQuery.clean( args, context, fragment, scripts ); // Update the cache, but only store false // unless this is a second parsing of the same content if ( cacheable ) { jQuery.fragments[ first ] = cachehit && fragment; } } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), l = insert.length, parent = this.length === 1 && this[0].parentNode; if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( ; i < l; i++ ) { elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, clone; if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, safe = context === document && safeFragment, ret = []; // Ensure that context is a document if ( !context || typeof context.createDocumentFragment === "undefined" ) { context = document; } // Use the already-created safe fragment if context permits for ( i = 0; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); div = context.createElement("div"); safe.appendChild( div ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Go to html and back, then peel off extra wrappers tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; depth = wrap[0]; div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> hasBody = rtbody.test(elem); tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Take out of fragment container (we need a fresh div each time) div.parentNode.removeChild( div ); } } if ( elem.nodeType ) { ret.push( elem ); } else { jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { elem = div = safe = null; } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { for ( i = 0; (elem = ret[i]) != null; i++ ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } } // Append elements to a provided document fragment if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } jQuery.deletedIds.push( id ); } } } } } }); // Limit scope pollution from any deprecated API (function() { var matched, browser; // Use of jQuery.browser is frowned upon. // More details: http://api.jquery.com/jQuery.browser // jQuery.uaMatch maintained for back-compat jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }; })(); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rselectTextarea = /^(?:select|textarea)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), i = 0, length = dataTypes.length; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var selection, list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ); for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } // Don't do a request if no elements are being requested if ( !this.length ) { return this; } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // Request the remote document jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params, complete: function( jqXHR, status ) { if ( callback ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); } } }).done(function( responseText ) { // Save response for use in complete callback response = arguments; // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append( responseText.replace( rscript, "" ) ) // Locate the specified elements .find( selector ) : // If not, just inject the full result responseText ); }); return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // ifModified key ifModifiedKey, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || strAbort; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ ifModifiedKey ] = modified; } modified = jqXHR.getResponseHeader("Etag"); if ( modified ) { jQuery.etag[ ifModifiedKey ] = modified; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.always( tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv, conv2, current, tmp, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ], converters = {}, i = 0; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } var oldCallbacks = [], rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/, nonce = jQuery.now(); // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, data = s.data, url = s.url, hasCallback = s.jsonp !== false, replaceInUrl = hasCallback && rjsonp.test( url ), replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( data ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; overwritten = window[ callbackName ]; // Insert callback into url or form data if ( replaceInUrl ) { s.url = url.replace( rjsonp, "$1" + callbackName ); } else if ( replaceInData ) { s.data = data.replace( rjsonp, "$1" + callbackName ); } else if ( hasCallback ) { s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var xhrCallbacks, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( e ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback, 0 ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
alexoldenburg/subzero
node_modules/grunt-requirejs/node_modules/grunt-jquerybuilder/node_modules/jquery-builder/dist/1.8.3/jquery-css.js
JavaScript
mit
215,458
module Discordrb::Webhooks # An embed is a multipart-style attachment to a webhook message that can have a variety of different purposes and # appearances. class Embed def initialize(title: nil, description: nil, url: nil, timestamp: nil, colour: nil, color: nil, footer: nil, image: nil, thumbnail: nil, video: nil, provider: nil, author: nil, fields: []) @title = title @description = description @url = url @timestamp = timestamp @colour = colour || color @footer = footer @image = image @thumbnail = thumbnail @video = video @provider = provider @author = author @fields = fields end # The title of this embed that will be displayed above everything else. # @return [String] attr_accessor :title # The description for this embed. # @return [String] attr_accessor :description # The URL the title should point to. # @return [String] attr_accessor :url # The timestamp for this embed. Will be displayed just below the title. # @return [Time] attr_accessor :timestamp # @return [Integer] the colour of the bar to the side, in decimal form. attr_reader :colour alias_method :color, :colour # Sets the colour of the bar to the side of the embed to something new. # @param value [Integer, String, {Integer, Integer, Integer}] The colour in decimal, hexadecimal, or R/G/B decimal # form. def colour=(value) if value.is_a? Integer raise ArgumentError, 'Embed colour must be 24-bit!' if value >= 16_777_216 @colour = value elsif value.is_a? String self.colour = value.delete('#').to_i(16) elsif value.is_a? Array raise ArgumentError, 'Colour tuple must have three values!' if value.length != 3 self.colour = value[0] << 16 | value[1] << 8 | value[2] end end alias_method :color=, :colour= # The footer for this embed. # @example Add a footer to an embed # embed.footer = Discordrb::Webhooks::EmbedFooter.new(text: 'Hello', icon_url: 'https://i.imgur.com/j69wMDu.jpg') # @return [EmbedFooter] attr_accessor :footer # The image for this embed. # @see EmbedImage # @example Add a image to an embed # embed.image = Discordrb::Webhooks::EmbedImage.new(url: 'https://i.imgur.com/PcMltU7.jpg') # @return [EmbedImage] attr_accessor :image # The thumbnail for this embed. # @see EmbedThumbnail # @example Add a thumbnail to an embed # embed.thumbnail = Discordrb::Webhooks::EmbedThumbnail.new(url: 'https://i.imgur.com/xTG3a1I.jpg') # @return [EmbedThumbnail] attr_accessor :thumbnail # The author for this embed. # @see EmbedAuthor # @example Add a author to an embed # embed.author = Discordrb::Webhooks::EmbedAuthor.new(name: 'meew0', url: 'https://github.com/meew0', icon_url: 'https://avatars2.githubusercontent.com/u/3662915?v=3&s=466') # @return [EmbedAuthor] attr_accessor :author # Add a field object to this embed. # @param field [EmbedField] The field to add. def <<(field) @fields << field end # Convenience method to add a field to the embed without having to create one manually. # @see EmbedField # @example Add a field to an embed, conveniently # embed.add_field(name: 'A field', value: "The field's content") # @param name [String] The field's name # @param value [String] The field's value # @param inline [true, false] Whether the field should be inlined def add_field(name: nil, value: nil, inline: nil) self << EmbedField.new(name: name, value: value, inline: inline) end # @return [Array<EmbedField>] the fields attached to this embed. attr_reader :fields # @return [Hash] a hash representation of this embed, to be converted to JSON. def to_hash { title: @title, description: @description, url: @url, timestamp: @timestamp && @timestamp.utc.iso8601, color: @colour, footer: @footer && @footer.to_hash, image: @image && @image.to_hash, thumbnail: @thumbnail && @thumbnail.to_hash, video: @video && @video.to_hash, provider: @provider && @provider.to_hash, author: @author && @author.to_hash, fields: @fields.map(&:to_hash) } end end # An embed's footer will be displayed at the very bottom of an embed, together with the timestamp. An icon URL can be # set together with some text to be displayed. class EmbedFooter # Creates a new footer object. # @param text [String, nil] The text to be displayed in the footer. # @param icon_url [String, nil] The URL to an icon to be showed alongside the text. def initialize(text: nil, icon_url: nil) @text = text @icon_url = icon_url end # @return [Hash] a hash representation of this embed footer, to be converted to JSON. def to_hash { text: @text, icon_url: @icon_url } end end # An embed's image will be displayed at the bottom, in large format. It will replace a footer icon URL if one is set. class EmbedImage # Creates a new image object. # @param url [String, nil] The URL of the image. def initialize(url: nil) @url = url end # @return [Hash] a hash representation of this embed image, to be converted to JSON. def to_hash { url: @url } end end # An embed's thumbnail will be displayed at the right of the message, next to the description and fields. When clicked # it will point to the embed URL. class EmbedThumbnail # Creates a new thumbnail object. # @param url [String, nil] The URL of the thumbnail. def initialize(url: nil) @url = url end # @return [Hash] a hash representation of this embed thumbnail, to be converted to JSON. def to_hash { url: @url } end end # An embed's author will be shown at the top to indicate who "authored" the particular event the webhook was sent for. class EmbedAuthor # Creates a new author object. # @param name [String, nil] The name of the author. # @param url [String, nil] The URL the name should link to. # @param icon_url [String, nil] The URL of the icon to be displayed next to the author. def initialize(name: nil, url: nil, icon_url: nil) @name = name @url = url @icon_url = icon_url end # @return [Hash] a hash representation of this embed author, to be converted to JSON. def to_hash { name: @name, url: @url, icon_url: @icon_url } end end # A field is a small block of text with a header that can be relatively freely layouted with other fields. class EmbedField # Creates a new field object. # @param name [String, nil] The name of the field, displayed in bold at the top. # @param value [String, nil] The value of the field, displayed in normal text below the name. # @param inline [true, false] Whether the field should be displayed in-line with other fields. def initialize(name: nil, value: nil, inline: nil) @name = name @value = value @inline = inline end # @return [Hash] a hash representation of this embed field, to be converted to JSON. def to_hash { name: @name, value: @value, inline: @inline } end end end
Roughsketch/discordrb
lib/discordrb/webhooks/embeds.rb
Ruby
mit
7,499
var config = require('./config'); var express = require('express'); var superagent = require('superagent'); /** * Auth Token */ var authToken = null; var expires = 0; var expires_in = 20160; // 14 days in minutes /** * Urls */ var OAUTH = 'https://www.arcgis.com/sharing/oauth2/token'; var GEOCODE = 'http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer'; /** * ESRI Query Parameter Defaults */ var CATEGORY = 'Address'; var CENTER = config.geocode.center; var DISTANCE = 160 * 1000; // meters /** * Expose `router` */ var router = module.exports = express.Router(); /** * Expose `encode` & `reverse` */ module.exports.encode = encode; module.exports.reverse = reverse; module.exports.suggest = suggest; /** * Geocode */ router.get('/:address', function(req, res) { encode(req.params.address, function(err, addresses) { if (err) { console.error(err); res.status(400).send(err); } else { var ll = addresses[0].feature.geometry; res.status(200).send({ lng: ll.x, lat: ll.y }); } }); }); /** * Reverse */ router.get('/reverse/:coordinate', function(req, res) { reverse(req.params.coordinate, function(err, address) { if (err) { console.error(err); res.status(400).send(err); } else { res.status(200).send(address); } }); }); /** * Suggest */ router.get('/suggest/:text', function(req, res) { suggest(req.params.text, function(err, suggestions) { if (err) { console.error(err); res.status(400).send(err); } else { res.status(200).send(suggestions); } }); }); /** * Geocode */ function encode(address, callback) { var text = ''; if (address.address) { text = address.address + ', ' + address.city + ', ' + address.state + ' ' + address.zip; } else { text = address; } auth(callback, function(token) { superagent .get(GEOCODE + '/find') .query({ category: CATEGORY, f: 'json', text: text, token: token }) .end(function(err, res) { if (err) { callback(err, res); } else { var body = parseResponse(res, callback); if (!body || !body.locations || body.locations.length === 0) { callback(new Error('Location not found.')); } else { callback(null, body.locations); } } }); }); } /** * Reverse geocode */ function reverse(ll, callback) { var location = ll; if (ll.lng) { location = ll.lng + ',' + ll.lat; } else if (ll.x) { location = ll.x + ',' + ll.y; } else if (ll[0]) { location = ll[0] + ',' + ll[1]; } auth(callback, function(token) { superagent .get(GEOCODE + '/reverseGeocode') .query({ f: 'json', location: location, token: token }) .end(function(err, res) { if (err) { callback(err, res); } else { var body = parseResponse(res, callback); if (!body || !body.address) { callback(new Error('Location not found.')); } else { var addr = body.address; callback(null, { address: addr.Address, neighborhood: addr.Neighborhood, city: addr.City, county: addr.Subregion, state: addr.Region, zip: parseInt(addr.Postal, 10), country: addr.CountryCode }); } } }); }); } /** * Auto suggest */ function suggest(text, callback) { auth(callback, function(token) { superagent .get(GEOCODE + '/suggest') .query({ category: CATEGORY, distance: DISTANCE, f: 'json', location: CENTER, text: text, token: token }) .end(function(err, res) { if (err) { callback(err, res); } else { var body = parseResponse(res, callback); callback(null, body.suggestions); } }); }); } /** * Auth? */ function auth(callback, next) { generateAuthToken(function(err, token) { if (err) { callback(err); } else { next(token); } }); } /** * Parse */ function parseResponse(res, callback) { try { return JSON.parse(res.text); } catch (e) { callback(e); } } /** * Generate an auth token */ function generateAuthToken(callback) { // If we're within 7 days of auth token expiration, generate a new one if ((expires - expires_in / 2) < Date.now().valueOf()) { superagent .get(OAUTH) .query({ client_id: config.arcgis_id, client_secret: config.arcgis_secret, expiration: expires_in, grant_type: 'client_credentials' }) .end(function(err, res) { if (err || res.error || !res.ok) { callback(err || res.error || res.text); } else { authToken = res.body.access_token; // Set the expires time expires = new Date(); expires.setSeconds(expires.getSeconds() + res.body.expires_in); expires = expires.valueOf(); callback(null, authToken); } }); } else { callback(null, authToken); } }
Code4Maine/modeify
lib/geocode.js
JavaScript
mit
5,275
package billing // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // OperationsClient is the billing client provides access to billing resources for Azure subscriptions. type OperationsClient struct { BaseClient } // NewOperationsClient creates an instance of the OperationsClient client. func NewOperationsClient(subscriptionID string) OperationsClient { return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewOperationsClientWithBaseURI creates an instance of the OperationsClient client using a custom endpoint. Use this // when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} } // List lists the available billing REST API operations. func (client OperationsClient) List(ctx context.Context) (result OperationListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") defer func() { sc := -1 if result.olr.Response.Response != nil { sc = result.olr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "billing.OperationsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.olr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "billing.OperationsClient", "List", resp, "Failure sending request") return } result.olr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "billing.OperationsClient", "List", resp, "Failure responding to request") return } if result.olr.hasNextLink() && result.olr.IsEmpty() { err = result.NextWithContext(ctx) return } return } // ListPreparer prepares the List request. func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { const APIVersion = "2020-05-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPath("/providers/Microsoft.Billing/operations"), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client OperationsClient) listNextResults(ctx context.Context, lastResults OperationListResult) (result OperationListResult, err error) { req, err := lastResults.operationListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "billing.OperationsClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "billing.OperationsClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "billing.OperationsClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client OperationsClient) ListComplete(ctx context.Context) (result OperationListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx) return }
Azure/azure-sdk-for-go
services/preview/billing/mgmt/2020-05-01-preview/billing/operations.go
GO
mit
5,145
import Immutable from 'immutable'; import * as ActionType from '../../actions/auth/auth'; const defaultState = Immutable.fromJS({ loggedIn: false, }); function authReducer(state = defaultState, action) { const { loggedIn, } = action; switch (action.type) { case ActionType.VERIFIED_LOGIN: return state.merge(Immutable.fromJS({ loggedIn })); default: return state; } } export default authReducer;
phillydorn/CAProject2
app/reducers/auth/auth.js
JavaScript
mit
439
[See html formatted version](https://huasofoundries.github.io/google-maps-documentation/MapPanes.html) MapPanes interface ------------------ google.maps.MapPanes interface Properties [floatPane](#MapPanes.floatPane) **Type:**  Element This pane contains the info window. It is above all map overlays. (Pane 4). [mapPane](#MapPanes.mapPane) **Type:**  Element This pane is the lowest pane and is above the tiles. It may not receive DOM events. (Pane 0). [markerLayer](#MapPanes.markerLayer) **Type:**  Element This pane contains markers. It may not receive DOM events. (Pane 2). [overlayLayer](#MapPanes.overlayLayer) **Type:**  Element This pane contains polylines, polygons, ground overlays and tile layer overlays. It may not receive DOM events. (Pane 1). [overlayMouseTarget](#MapPanes.overlayMouseTarget) **Type:**  Element This pane contains elements that receive DOM events. (Pane 3).
amenadiel/google-maps-documentation
docs/MapPanes.md
Markdown
mit
914
package fr.pizzeria.admin.web; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils; @WebServlet("/login") public class LoginController extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login/login.jsp"); rd.forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String email = req.getParameter("email"); String password = req.getParameter("password"); if (StringUtils.isBlank(email) || StringUtils.isBlank(password)) { resp.sendError(400, "Non non non ! Zone interdite"); } else if ( StringUtils.equals(email, "admin@pizzeria.fr") && StringUtils.equals(password, "admin")) { HttpSession session = req.getSession(); session.setAttribute("email", email); resp.sendRedirect(req.getContextPath() + "/pizzas/list"); } else { resp.setStatus(403); req.setAttribute("msgerr", "Ooppps noooo"); RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login/login.jsp"); rd.forward(req, resp); } } }
kmokili/formation-dta
pizzeria-admin-app/src/main/java/fr/pizzeria/admin/web/LoginController.java
Java
mit
1,588
import { gql } from '@apollo/client' import avatarFragment from 'v2/components/AvatarUploader/fragments/avatar' export default gql` query AvatarCheck { me { ...Avatar } } ${avatarFragment} `
aredotna/ervell
src/v2/components/AvatarUploader/queries/avatar.ts
TypeScript
mit
213
<html> <head> </head> <body> <h2> But Honour Them As They Honour Men </h2> Thirdly, <span class="oldenglish"> for </span> <span class="oldenglish"> the </span> worship <span class="oldenglish"> which </span> naturally men exhibite <span class="oldenglish"> to </span> Powers invisible, <span class="oldenglish"> it </span> <span class="oldenglish"> can </span> <span class="oldenglish"> be </span> <span class="oldenglish"> no </span> other, <span class="oldenglish"> but </span> <span class="oldenglish"> such </span> <span class="french"> expressions </span> <span class="oldenglish"> of </span> <span class="oldnorse"> their </span> reverence, <span class="oldenglish"> as </span> <span class="oldnorse"> they </span> <span class="oldenglish"> would </span> <span class="oldfrench"> use </span> <span class="oldenglish"> towards </span> men; Gifts, Petitions, Thanks, <span class="oldfrench"> Submission </span> <span class="oldenglish"> of </span> Body, <span class="latin"> Considerate </span> Addresses, sober Behaviour, <span class="latin"> premeditated </span> Words, Swearing (that is, <span class="oldfrench"> assuring </span> <span class="oldenglish"> one </span> <span class="oldenglish"> another </span> <span class="oldenglish"> of </span> <span class="oldnorse"> their </span> promises,) <span class="oldenglish"> by </span> <span class="french"> invoking </span> them. <span class="oldenglish"> Beyond </span> <span class="oldenglish"> that </span> <span class="oldfrench"> reason </span> suggesteth nothing; <span class="oldenglish"> but </span> <span class="oldenglish"> leaves </span> <span class="oldnorse"> them </span> <span class="oldenglish"> either </span> <span class="oldenglish"> to </span> <span class="oldenglish"> rest </span> there; <span class="oldenglish"> or </span> <span class="oldenglish"> for </span> <span class="oldenglish"> further </span> ceremonies, <span class="oldenglish"> to </span> <span class="oldfrench"> rely </span> <span class="oldenglish"> on </span> <span class="oldenglish"> those </span> <span class="oldnorse"> they </span> <span class="oldenglish"> believe </span> <span class="oldenglish"> to </span> <span class="oldenglish"> be </span> <span class="oldenglish"> wiser </span> <span class="oldenglish"> than </span> themselves. </body> </html>
charlesreid1/wordswordswords
etymology/html/leviathan103.html
HTML
mit
2,705
var PassThrough = require('stream').PassThrough describe('Object Streams', function () { it('should be supported', function (done) { var app = koala() app.use(function* (next) { var body = this.body = new PassThrough({ objectMode: true }) body.write({ message: 'a' }) body.write({ message: 'b' }) body.end() }) request(app.listen()) .get('/') .expect(200) .expect([{ message: 'a' }, { message: 'b' }], done) }) })
francisbrito/koala
test/app/object-streams.js
JavaScript
mit
538
YUI.add("inputex-inplaceedit", function(Y){ var lang = Y.Lang;//, Event = YAHOO.util.Event, Dom = YAHOO.util.Dom, CSS_PREFIX = 'inputEx-InPlaceEdit-'; /** * Meta field providing in place editing (the editor appears when you click on the formatted value). * @class inputEx.InPlaceEdit * @extends inputEx.Field * @constructor * @param {Object} options Added options: * <ul> * <li>visu</li> * <li>editorField</li> * <li>animColors</li> * </ul> */ inputEx.InPlaceEdit = function(options) { inputEx.InPlaceEdit.superclass.constructor.call(this, options); this.publish('openEditor'); this.publish('closeEditor'); }; lang.extend(inputEx.InPlaceEdit, inputEx.Field, { /** * Set the default values of the options * @param {Object} options Options object as passed to the constructor */ setOptions: function(options) { inputEx.InPlaceEdit.superclass.setOptions.call(this, options); this.options.visu = options.visu; this.options.editorField = options.editorField; //this.options.buttonTypes = options.buttonTypes || {ok:"submit",cancel:"link"}; this.options.buttonConfigs = options.buttonConfigs || [{ type: "submit", value: inputEx.messages.okEditor, className: "inputEx-Button "+CSS_PREFIX+'OkButton', onClick: {fn: this.onOkEditor, scope:this} },{ type: "link", value: inputEx.messages.cancelEditor, className: "inputEx-Button "+CSS_PREFIX+'CancelLink', onClick: {fn: this.onCancelEditor, scope:this} }]; this.options.animColors = options.animColors || null; }, /** * Override renderComponent to create 2 divs: the visualization one, and the edit in place form */ renderComponent: function() { this.renderVisuDiv(); this.renderEditor(); }, /** * Render the editor */ renderEditor: function() { this.editorContainer = inputEx.cn('div', {className: CSS_PREFIX+'editor'}, {display: 'none'}); // Render the editor field this.editorField = inputEx(this.options.editorField,this); var editorFieldEl = this.editorField.getEl(); this.editorContainer.appendChild( editorFieldEl ); Y.one(editorFieldEl).addClass(CSS_PREFIX+'editorDiv'); this.buttons = []; for (var i = 0; i < this.options.buttonConfigs.length ; i++){ var config = this.options.buttonConfigs[i]; config.parentEl = this.editorContainer; this.buttons.push(new inputEx.widget.Button(config)); } // Line breaker () this.editorContainer.appendChild( inputEx.cn('div',null, {clear: 'both'}) ); this.fieldContainer.appendChild(this.editorContainer); }, /** * Set the color when hovering the field * @param {Event} e The original mouseover event */ onVisuMouseOver: function(e) { // to totally disable the visual effect on mouse enter, you should change css options inputEx-InPlaceEdit-visu:hover if(this.disabled) return; if(this.colorAnim) { this.colorAnim.stop(true); } inputEx.sn(this.formattedContainer, null, {backgroundColor: this.options.animColors.from }); }, /** * Start the color animation when hovering the field * @param {Event} e The original mouseout event */ onVisuMouseOut: function(e) { var optionsAnim; if(this.disabled) return; // Start animation if(this.colorAnim) { this.colorAnim.stop(true); } if(!this.options.animColors) return; optionsAnim = { node: Y.one(this.formattedContainer), } if(this.options.animColors.from){ optionsAnim.from = { backgroundColor : this.options.animColors.from } } if(this.options.animColors.from){ optionsAnim.to = { backgroundColor : this.options.animColors.to } } this.colorAnim = new Y.Anim(optionsAnim); this.colorAnim.on("end",function() { Y.one(this.formattedContainer).setStyle('background-color', ''); }); this.colorAnim.run(); }, /** * Create the div that will contain the visualization of the value */ renderVisuDiv: function() { this.formattedContainer = inputEx.cn('div', {className: 'inputEx-InPlaceEdit-visu'}); if( lang.isFunction(this.options.formatDom) ) { this.formattedContainer.appendChild( this.options.formatDom(this.options.value) ); } else if( lang.isFunction(this.options.formatValue) ) { this.formattedContainer.innerHTML = this.options.formatValue(this.options.value); } else { this.formattedContainer.innerHTML = lang.isUndefined(this.options.value) ? inputEx.messages.emptyInPlaceEdit: this.options.value; } this.fieldContainer.appendChild(this.formattedContainer); }, /** * Adds the events for the editor and color animations */ initEvents: function() { Y.one(this.formattedContainer).on("click", this.openEditor, this, true); // For color animation (if specified) if (this.options.animColors) { Y.one(this.formattedContainer).on('mouseover', this.onVisuMouseOver, this); Y.one(this.formattedContainer).on('mouseout', this.onVisuMouseOut, this); } if(this.editorField.el) { var that = this; // Register some listeners Y.on("key", function(){ that.onKeyUp },"#"+Y.one(this.editorField.el).get("id"),"up:"); Y.on("key", function(){ that.onKeyDown },"#"+Y.one(this.editorField.el).get("id"),"down:" ); } }, /** * Handle some keys events to close the editor * @param {Event} e The original keyup event */ onKeyUp: function(e) { // Enter if( e.keyCode == 13) { this.onOkEditor(e); } // Escape if( e.keyCode == 27) { this.onCancelEditor(e); } }, /** * Handle the tabulation key to close the editor * @param {Event} e The original keydown event */ onKeyDown: function(e) { // Tab if(e.keyCode == 9) { this.onOkEditor(e); } }, /** * Validate the editor (ok button, enter key or tabulation key) */ onOkEditor: function(e) { e.halt(); var newValue = this.editorField.getValue(); this.setValue(newValue); this.closeEditor(); var that = this; setTimeout(function() {that.fire("updated",newValue);}, 50); }, /** * Close the editor on cancel (cancel button, blur event or escape key) * @param {Event} e The original event (click, blur or keydown) */ onCancelEditor: function(e) { e.halt(); this.closeEditor(); }, /** * Close the editor on cancel (cancel button, blur event or escape key) * @param {Event} e The original event (click, blur or keydown) */ closeEditor: function() { this.editorContainer.style.display = 'none'; this.formattedContainer.style.display = ''; this.fire("closeEditor") }, /** * Override enable to Enable openEditor */ enable: function(){ this.disabled = false; inputEx.sn(this.formattedContainer, {className: 'inputEx-InPlaceEdit-visu'}); }, /** * Override disable to Disable openEditor */ disable: function(){ this.disabled = true; inputEx.sn(this.formattedContainer, {className: 'inputEx-InPlaceEdit-visu-disable'}); }, /** * Display the editor */ openEditor: function() { if(this.disabled) return; var value = this.getValue(); this.editorContainer.style.display = ''; this.formattedContainer.style.display = 'none'; if(!lang.isUndefined(value)) { this.editorField.setValue(value); } // Set focus in the element ! this.editorField.focus(); // Select the content if(this.editorField.el && lang.isFunction(this.editorField.el.setSelectionRange) && (!!value && !!value.length)) { this.editorField.el.setSelectionRange(0,value.length); } this.fire("openEditor"); }, /** * Returned the previously stored value * @return {Any} The value of the subfield */ getValue: function() { var editorOpened = (this.editorContainer.style.display == ''); return editorOpened ? this.editorField.getValue() : this.value; }, /** * Set the value and update the display * @param {Any} value The value to set * @param {boolean} [sendUpdatedEvt] (optional) Wether this setValue should fire the updatedEvt or not (default is true, pass false to NOT send the event) */ setValue: function(value, sendUpdatedEvt) { // Store the value this.value = value; if(lang.isUndefined(value) || value == "") { inputEx.renderVisu(this.options.visu, inputEx.messages.emptyInPlaceEdit, this.formattedContainer); } else { inputEx.renderVisu(this.options.visu, this.value, this.formattedContainer); } // If the editor is opened, update it if(this.editorContainer.style.display == '') { this.editorField.setValue(value); } inputEx.InPlaceEdit.superclass.setValue.call(this, value, sendUpdatedEvt); }, /** * Close the editor when calling the close function on this field */ close: function() { this.editorContainer.style.display = 'none'; this.formattedContainer.style.display = ''; this.fire("openEditor"); } }); inputEx.messages.emptyInPlaceEdit = "(click to edit)"; inputEx.messages.cancelEditor = "cancel"; inputEx.messages.okEditor = "Ok"; // Register this class as "inplaceedit" type inputEx.registerType("inplaceedit", inputEx.InPlaceEdit, [ { type:'type', label: 'Editor', name: 'editorField'} ]); }, '0.1.1', { requires:["anim","inputex-field","inputex-button"] })
piercus/inputex
js/fields/InPlaceEdit.js
JavaScript
mit
10,155
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class defines behaviors specific to a writing system. // A writing system is the collection of scripts and // orthographic rules required to represent a language as text. // // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { using System; using System.Runtime.Serialization; using System.Security.Permissions; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class StringInfo { [OptionalField(VersionAdded = 2)] private String m_str; // We allow this class to be serialized but there is no conceivable reason // for them to do so. Thus, we do not serialize the instance variables. [NonSerialized] private int[] m_indexes; // Legacy constructor public StringInfo() : this(""){} // Primary, useful constructor public StringInfo(String value) { this.String = value; } #region Serialization [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { m_str = String.Empty; } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { if (m_str.Length == 0) { m_indexes = null; } } #endregion Serialization [System.Runtime.InteropServices.ComVisible(false)] public override bool Equals(Object value) { StringInfo that = value as StringInfo; if (that != null) { return (this.m_str.Equals(that.m_str)); } return (false); } [System.Runtime.InteropServices.ComVisible(false)] public override int GetHashCode() { return this.m_str.GetHashCode(); } // Our zero-based array of index values into the string. Initialize if // our private array is not yet, in fact, initialized. private int[] Indexes { get { if((null == this.m_indexes) && (0 < this.String.Length)) { this.m_indexes = StringInfo.ParseCombiningCharacters(this.String); } return(this.m_indexes); } } public String String { get { return(this.m_str); } set { if (null == value) { throw new ArgumentNullException(nameof(String), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); this.m_str = value; this.m_indexes = null; } } public int LengthInTextElements { get { if(null == this.Indexes) { // Indexes not initialized, so assume length zero return(0); } return(this.Indexes.Length); } } public String SubstringByTextElements(int startingTextElement) { // If the string is empty, no sense going further. if(null == this.Indexes) { // Just decide which error to give depending on the param they gave us.... if(startingTextElement < 0) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } else { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } } return (this.SubstringByTextElements(startingTextElement, this.Indexes.Length - startingTextElement)); } public String SubstringByTextElements(int startingTextElement, int lengthInTextElements) { // // Parameter checking // if(startingTextElement < 0) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if(this.String.Length == 0 || startingTextElement >= this.Indexes.Length) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } if(lengthInTextElements < 0) { throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if(startingTextElement > this.Indexes.Length - lengthInTextElements) { throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } int start = this.Indexes[startingTextElement]; if(startingTextElement + lengthInTextElements == this.Indexes.Length) { // We are at the last text element in the string and because of that // must handle the call differently. return(this.String.Substring(start)); } else { return(this.String.Substring(start, (this.Indexes[lengthInTextElements + startingTextElement] - start))); } } public static String GetNextTextElement(String str) { return (GetNextTextElement(str, 0)); } //////////////////////////////////////////////////////////////////////// // // Get the code point count of the current text element. // // A combining class is defined as: // A character/surrogate that has the following Unicode category: // * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT) // * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA) // * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE) // // In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as: // // 1. If a character/surrogate is in the following category, it is a text element. // It can NOT further combine with characters in the combinging class to form a text element. // * one of the Unicode category in the combinging class // * UnicodeCategory.Format // * UnicodeCateogry.Control // * UnicodeCategory.OtherNotAssigned // 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element. // // Return: // The length of the current text element // // Parameters: // String str // index The starting index // len The total length of str (to define the upper boundary) // ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element. // currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element. // //////////////////////////////////////////////////////////////////////// internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount) { Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); if (index + currentCharCount == len) { // This is the last character/surrogate in the string. return (currentCharCount); } // Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not. int nextCharCount; UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount); if (CharUnicodeInfo.IsCombiningCategory(ucNext)) { // The next element is a combining class. // Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category, // not a format character, and not a control character). if (CharUnicodeInfo.IsCombiningCategory(ucCurrent) || (ucCurrent == UnicodeCategory.Format) || (ucCurrent == UnicodeCategory.Control) || (ucCurrent == UnicodeCategory.OtherNotAssigned) || (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate { // Will fall thru and return the currentCharCount } else { int startIndex = index; // Remember the current index. // We have a valid base characters, and we have a character (or surrogate) that is combining. // Check if there are more combining characters to follow. // Check if the next character is a nonspacing character. index += currentCharCount + nextCharCount; while (index < len) { ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount); if (!CharUnicodeInfo.IsCombiningCategory(ucNext)) { ucCurrent = ucNext; currentCharCount = nextCharCount; break; } index += nextCharCount; } return (index - startIndex); } } // The return value will be the currentCharCount. int ret = currentCharCount; ucCurrent = ucNext; // Update currentCharCount. currentCharCount = nextCharCount; return (ret); } // Returns the str containing the next text element in str starting at // index index. If index is not supplied, then it will start at the beginning // of str. It recognizes a base character plus one or more combining // characters or a properly formed surrogate pair as a text element. See also // the ParseCombiningCharacters() and the ParseSurrogates() methods. public static String GetNextTextElement(String str, int index) { // // Validate parameters. // if (str==null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; if (index < 0 || index >= len) { if (index == len) { return (String.Empty); } throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } int charLen; UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen); return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen))); } public static TextElementEnumerator GetTextElementEnumerator(String str) { return (GetTextElementEnumerator(str, 0)); } public static TextElementEnumerator GetTextElementEnumerator(String str, int index) { // // Validate parameters. // if (str==null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; if (index < 0 || (index > len)) { throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } return (new TextElementEnumerator(str, index, len)); } /* * Returns the indices of each base character or properly formed surrogate pair * within the str. It recognizes a base character plus one or more combining * characters or a properly formed surrogate pair as a text element and returns * the index of the base character or high surrogate. Each index is the * beginning of a text element within a str. The length of each element is * easily computed as the difference between successive indices. The length of * the array will always be less than or equal to the length of the str. For * example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would * return the indices: 0, 2, 4. */ public static int[] ParseCombiningCharacters(String str) { if (str == null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; int[] result = new int[len]; if (len == 0) { return (result); } int resultCount = 0; int i = 0; int currentCharLen; UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen); while (i < len) { result[resultCount++] = i; i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen); } if (resultCount < len) { int[] returnArray = new int[resultCount]; Array.Copy(result, returnArray, resultCount); return (returnArray); } return (result); } } }
Dmitry-Me/coreclr
src/mscorlib/src/System/Globalization/StringInfo.cs
C#
mit
14,973
package org.anodyneos.xp.tag.core; import javax.servlet.jsp.el.ELException; import org.anodyneos.xp.XpException; import org.anodyneos.xp.XpOutput; import org.anodyneos.xp.tagext.XpTagSupport; import org.xml.sax.SAXException; /** * @author jvas */ public class DebugTag extends XpTagSupport { public DebugTag() { super(); } /* (non-Javadoc) * @see org.anodyneos.xp.tagext.XpTag#doTag(org.anodyneos.xp.XpContentHandler) */ public void doTag(XpOutput out) throws XpException, ELException, SAXException { XpOutput newOut = new XpOutput(new DebugCH(System.err, out.getXpContentHandler())); getXpBody().invoke(newOut); } }
jvasileff/aos-xp
src.java/org/anodyneos/xp/tag/core/DebugTag.java
Java
mit
679
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>File: calculations.rb</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <link rel="stylesheet" href="../../../../../../../../../../../.././rdoc-style.css" type="text/css" media="screen" /> <script type="text/javascript"> // <![CDATA[ function popupCode( url ) { window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400") } function toggleCode( id ) { if ( document.getElementById ) elem = document.getElementById( id ); else if ( document.all ) elem = eval( "document.all." + id ); else return false; elemStyle = elem.style; if ( elemStyle.display != "block" ) { elemStyle.display = "block" } else { elemStyle.display = "none" } return true; } // Make codeblocks hidden by default document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" ) // ]]> </script> </head> <body> <div id="fileHeader"> <h1>calculations.rb</h1> <table class="header-table"> <tr class="top-aligned-row"> <td><strong>Path:</strong></td> <td>/usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/core_ext/time/calculations.rb </td> </tr> <tr class="top-aligned-row"> <td><strong>Last Update:</strong></td> <td>Sun Jun 20 17:19:12 -0600 2010</td> </tr> </table> </div> <!-- banner header --> <div id="bodyContent"> <div id="contextContent"> <div id="requires-list"> <h3 class="section-bar">Required files</h3> <div class="name-list"> active_support/duration&nbsp;&nbsp; active_support/core_ext/date/acts_like&nbsp;&nbsp; active_support/core_ext/date/calculations&nbsp;&nbsp; active_support/core_ext/date_time/conversions&nbsp;&nbsp; </div> </div> </div> </div> <!-- if includes --> <div id="section"> <!-- if method_list --> </div> <div id="validator-badges"> <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p> </div> </body> </html>
ecoulthard/summitsearch
doc/api/files/usr/lib/ruby/gems/1_8/gems/activesupport-3_0_0_beta4/lib/active_support/core_ext/time/calculations_rb.html
HTML
mit
2,478
class SessionsController < ApplicationController before_filter :authenticate_user, :only => [:home, :profile, :setting] before_filter :save_login_state, :only => [:login, :login_attempt] def login end def login_attempt authorized_user = User.authenticate(params[:username_or_email],params[:login_password]) if authorized_user session[:user_id] = authorized_user.id flash[:notice] = "Wow Welcome again, you logged in as #{authorized_user.username}" redirect_to(:action => 'home') else flash.keep[:notice] = "Invalid Username or Password" flash.keep[:color]= "invalid" redirect_to(:action => 'index',error_message: "Invalid Username or Password",:locals => {:errorMessage => "yes"}) end end def home end def profile @user = User.find(session[:user_id]) end def setting end def passreset end def contactus end def passreset_attempt if params[:submit_button] # render plain: "returned from the password reset form" render "home" else # render plain: "cancel pressed" render "home" end end def logout session[:user_id] = nil redirect_to :action => 'index' end end
app-man/LoginEasy
app/controllers/sessions_controller.rb
Ruby
mit
1,156
import numpy as np import pandas as pd from pandas import Series, DataFrame from scipy.spatial import distance import matplotlib.pyplot as plt from sklearn.cluster import DBSCAN from sklearn import metrics from sklearn.datasets.samples_generator import make_blobs from sklearn.preprocessing import StandardScaler from sklearn import decomposition # PCA from sklearn.metrics import confusion_matrix import json import ml.Features as ft from utils import Utils class Identifier(object): def __init__(self): columns = ['mean_height', 'min_height', 'max_height', 'mean_width', 'min_width', 'max_width', 'time', 'girth','id'] self.data = DataFrame(columns=columns) self.event = [] @staticmethod def subscribe(ch, method, properties, body): """ prints the body message. It's the default callback method :param ch: keep null :param method: keep null :param properties: keep null :param body: the message :return: """ #first we get the JSON from body #we check if it's part of the walking event #if walking event is completed, we if __name__ == '__main__': # we setup needed params MAX_HEIGHT = 203 MAX_WIDTH = 142 SPEED = 3 SAMPLING_RATE = 8 mq_host = '172.26.56.122' queue_name = 'door_data' # setting up MQTT subscriber Utils.sub(queue_name=queue_name,callback=subscribe,host=mq_host)
banacer/door-wiz
src/identification/Identifier.py
Python
mit
1,449
<?php /* TwigBundle:Exception:traces.html.twig */ class __TwigTemplate_034400bfb816a72b7b3da36dd2d8e07ee89621bac614688be25a4e8ff872b3ad extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<div class=\"block\"> "; // line 2 if (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) > 0)) { // line 3 echo " <h2> <span><small>["; // line 4 echo twig_escape_filter($this->env, (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) - (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position"))) + 1), "html", null, true); echo "/"; echo twig_escape_filter($this->env, ((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) + 1), "html", null, true); echo "]</small></span> "; // line 5 echo $this->env->getExtension('code')->abbrClass($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "class", array())); echo ": "; echo $this->env->getExtension('code')->formatFileFromText(nl2br(twig_escape_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "message", array()), "html", null, true))); echo "&nbsp; "; // line 6 ob_start(); // line 7 echo " <a href=\"#\" onclick=\"toggle('traces-"; echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "', 'traces'); switchIcons('icon-traces-"; echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "-open', 'icon-traces-"; echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "-close'); return false;\"> <img class=\"toggle\" id=\"icon-traces-"; // line 8 echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: "; echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("inline") : ("none")); echo "\" /> <img class=\"toggle\" id=\"icon-traces-"; // line 9 echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: "; echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("none") : ("inline")); echo "\" /> </a> "; echo trim(preg_replace('/>\s+</', '><', ob_get_clean())); // line 12 echo " </h2> "; } else { // line 14 echo " <h2>Stack Trace</h2> "; } // line 16 echo " <a id=\"traces-link-"; // line 17 echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "\"></a> <ol class=\"traces list-exception\" id=\"traces-"; // line 18 echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "\" style=\"display: "; echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("block") : ("none")); echo "\"> "; // line 19 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array())); foreach ($context['_seq'] as $context["i"] => $context["trace"]) { // line 20 echo " <li> "; // line 21 $this->loadTemplate("TwigBundle:Exception:trace.html.twig", "TwigBundle:Exception:traces.html.twig", 21)->display(array("prefix" => (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "i" => $context["i"], "trace" => $context["trace"])); // line 22 echo " </li> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['i'], $context['trace'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 24 echo " </ol> </div> "; } public function getTemplateName() { return "TwigBundle:Exception:traces.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 101 => 24, 94 => 22, 92 => 21, 89 => 20, 85 => 19, 79 => 18, 75 => 17, 72 => 16, 68 => 14, 64 => 12, 56 => 9, 50 => 8, 41 => 7, 39 => 6, 33 => 5, 27 => 4, 24 => 3, 22 => 2, 19 => 1,); } } /* <div class="block">*/ /* {% if count > 0 %}*/ /* <h2>*/ /* <span><small>[{{ count - position + 1 }}/{{ count + 1 }}]</small></span>*/ /* {{ exception.class|abbr_class }}: {{ exception.message|nl2br|format_file_from_text }}&nbsp;*/ /* {% spaceless %}*/ /* <a href="#" onclick="toggle('traces-{{ position }}', 'traces'); switchIcons('icon-traces-{{ position }}-open', 'icon-traces-{{ position }}-close'); return false;">*/ /* <img class="toggle" id="icon-traces-{{ position }}-close" alt="-" src="data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=" style="display: {{ 0 == count ? 'inline' : 'none' }}" />*/ /* <img class="toggle" id="icon-traces-{{ position }}-open" alt="+" src="data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7" style="display: {{ 0 == count ? 'none' : 'inline' }}" />*/ /* </a>*/ /* {% endspaceless %}*/ /* </h2>*/ /* {% else %}*/ /* <h2>Stack Trace</h2>*/ /* {% endif %}*/ /* */ /* <a id="traces-link-{{ position }}"></a>*/ /* <ol class="traces list-exception" id="traces-{{ position }}" style="display: {{ 0 == count ? 'block' : 'none' }}">*/ /* {% for i, trace in exception.trace %}*/ /* <li>*/ /* {% include 'TwigBundle:Exception:trace.html.twig' with { 'prefix': position, 'i': i, 'trace': trace } only %}*/ /* </li>*/ /* {% endfor %}*/ /* </ol>*/ /* </div>*/ /* */
JoseGMaestre/Cupon_check
app/cache/dev/twig/9e/9e7ec4c116a05cf87d6dedc6906bdf1b530cafcee29ed870fee22e6360fa5e44.php
PHP
mit
8,589
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require("@angular/core"); var RemainingTimePipe = (function () { function RemainingTimePipe() { } RemainingTimePipe.prototype.transform = function (date) { var DaysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; var Months = "JanFebMarAprMayJunJulAugSepOctNovDec"; var padding = "in "; //Input pattern example: 2017-01-02T09:23:00.000Z var input = date + ""; var splitted = input.split('T'); var today = new Date(); var year = +splitted[0].split('-')[0]; var month = +splitted[0].split('-')[1]; var day = +splitted[0].split('-')[2]; var splittedTime = splitted[1].split(':'); var hour = +splittedTime[0]; var minute = +splittedTime[1]; var second = +splittedTime[2].split('.')[0]; //Years var currentYear = today.getFullYear(); var remaining = year - currentYear; if (remaining < 0) { return 'Started'; } if (remaining > 0) { if (remaining == 1) { return padding + '1 year'; } return padding + remaining + ' years'; } //Months var currentMonth = today.getMonth() + 1; remaining = month - currentMonth; if (remaining > 0) { if (remaining == 1) { //TODO Leap year var currentDate = today.getDate(); var daysInPreviousMonth = (month != 0 ? DaysInMonths[month - 1] : DaysInMonths[11]); var daysRemaining = (daysInPreviousMonth + day) - currentDate; if (daysRemaining < 7) { if (daysRemaining == 1) { return padding + '1 day'; } return padding + daysRemaining + ' days'; } var weeksPassed = daysRemaining / 7; weeksPassed = Math.round(weeksPassed); if (weeksPassed == 1) { return padding + '1 week'; } return padding + weeksPassed + ' weeks'; } return padding + remaining + ' months'; } //Days var currentDay = today.getDate(); var daysPassed = day - currentDay; if (daysPassed > 0) { if (daysPassed < 7) { if (daysPassed == 1) { return padding + '1 day'; } return padding + daysPassed + ' days'; } var weeksPassed = daysPassed / 7; weeksPassed = Math.round(weeksPassed); if (weeksPassed == 1) { return padding + '1 week'; } return padding + weeksPassed + ' weeks'; } //Hours var currentHour = today.getHours(); remaining = hour - currentHour; if (remaining > 1) { if (remaining == 2) { return padding + '1 hour'; } return padding + remaining + ' hours'; } //Minutes var currentMinute = today.getMinutes(); if (remaining == 1) { remaining = 60 + minute - currentMinute; } else { remaining = minute - currentMinute; } if (remaining > 0) { if (remaining == 1) { return padding + 'a minute'; } return padding + remaining + ' minutes'; } //Seconds var currentSecond = today.getSeconds(); remaining = second - currentSecond; if (remaining > 0) { return padding + 'less than a minute'; } return 'Started'; }; return RemainingTimePipe; }()); RemainingTimePipe = __decorate([ core_1.Pipe({ name: 'remainingTimePipe' }), __metadata("design:paramtypes", []) ], RemainingTimePipe); exports.RemainingTimePipe = RemainingTimePipe; //# sourceMappingURL=remainingTimePipe.js.map
ng2-slavs/Sportsemblr
public/app/pipes/remainingTimePipe.js
JavaScript
mit
4,775
/* eslint-disable import/no-extraneous-dependencies,import/no-unresolved */ import React, { useState } from 'react'; import { Form } from 'react-bootstrap'; import { Typeahead } from 'react-bootstrap-typeahead'; /* example-start */ const options = [ 'Warsaw', 'Kraków', 'Łódź', 'Wrocław', 'Poznań', 'Gdańsk', 'Szczecin', 'Bydgoszcz', 'Lublin', 'Katowice', 'Białystok', 'Gdynia', 'Częstochowa', 'Radom', 'Sosnowiec', 'Toruń', 'Kielce', 'Gliwice', 'Zabrze', 'Bytom', 'Olsztyn', 'Bielsko-Biała', 'Rzeszów', 'Ruda Śląska', 'Rybnik', ]; const FilteringExample = () => { const [caseSensitive, setCaseSensitive] = useState(false); const [ignoreDiacritics, setIgnoreDiacritics] = useState(true); return ( <> <Typeahead caseSensitive={caseSensitive} id="filtering-example" ignoreDiacritics={ignoreDiacritics} options={options} placeholder="Cities in Poland..." /> <Form.Group> <Form.Check checked={caseSensitive} id="case-sensitive-filtering" label="Case-sensitive filtering" onChange={(e) => setCaseSensitive(e.target.checked)} type="checkbox" /> <Form.Check checked={!ignoreDiacritics} id="diacritical-marks" label="Account for diacritical marks" onChange={(e) => setIgnoreDiacritics(!e.target.checked)} type="checkbox" /> </Form.Group> </> ); }; /* example-end */ export default FilteringExample;
ericgio/react-bootstrap-typeahead
example/src/examples/FilteringExample.js
JavaScript
mit
1,572
{% extends "base.html" %} {% block content %} <div class="container"> <form action="" method="POST" enctype="multipart/form-data"> {{ form.hidden_tag() }} <p> Descriptive Name: {{ form.descriptive_name(size = 50) }} {% for error in form.descriptive_name.errors %} <span style="color: red;">[{{error}}]</span> {% endfor %} </p> <p> Table Name: {{ form.table_name(size = 30) }} {% for error in form.table_name.errors %} <span style="color: red;">[{{error}}]</span> {% endfor %} </p> <p> <input type="submit" value="Create Table"> | <input type="reset" value="Clear"> | <a href="{{ url_for('admin') }}"> <input type="button" value="Cancel" /></a> </p> </form> </div> {% endblock %}
okyere/excel-data-collection
app/templates/add_tableinfo.html
HTML
mit
820
@extends('layouts.app') @section('content') <div class="container-fluid"> <div class="row"> <div class="panel panel-default"> <div class="panel-heading" style="padding-bottom: 40px;">PREVIEW <div class="col-xs-3 pull-right"> <a href="/ssearch"><input type="button" value="Search another Record" class=" btn btn-lg btn-success"></a> </div> </div> <div class="panel-body" style="padding-top: 20px;padding-bottom: 100px;"> @foreach($find as $files) <div class="alert alert-success text-center"> <a href="/storage/{{$files->filename}}"><li>CLICK TO DOWNLOAD THE FILE FOR THIS RECORD</li></a> </div> @endforeach <h3> Record result for <b>{{$id}}</b>. </h3> <div class="col-xs-12" style="padding-top: 100px;padding-bottom: 100px;"> <div class="col-xs-12" style="border-bottom: 1px solid #ccc;"> <div class="col-xs-2" style="border-right:1px solid #ccc;"> NAME OF SUSPECT </div> <div class="col-xs-1" style="border-right:1px solid #ccc;"> NUMBERS OF SUSPECT </div> <div class="col-xs-3" style="border-right:1px solid #ccc;"> COMMODITY NAME </div> <div class="col-xs-3" style="border-right:1px solid #ccc;"> QUANTITY </div> <div class="col-xs-1" style="border-right:1px solid #ccc;"> DATE RECORDED BY SYSTEM </div> <div class="col-xs-1" style="border-right:1px solid #ccc;"> DATESET BY ADMIN </div> <div class="col-xs-1" style="border-right:1px solid #ccc;"> A/C </div> </div> @foreach($preview as $a) <div class="col-xs-12" style="border-bottom: 1px solid #ccc;"> <div class="col-xs-2"> {{$a->suspectname}} </div> <div class="col-xs-1"> {{$a->suspectno}} </div> <div class="col-xs-3"> {{$a->commodityname}} </div> <div class="col-xs-3"> {{$a->quantity}} </div> <div class="col-xs-1"> {{$a->created_at}} </div> <div class="col-xs-1"> {{$a->dateinput}} </div> <div class="col-xs-1"> {{$a->areacommand}} </div> </div> @endforeach </div> </div> </div> </div> </div> </div> @endsection
ayoshoks/ncs
resources/views/search/specific_result.blade.php
PHP
mit
3,877
export default { hello : "hello" };
hasangilak/react-multilingual
example/locales/en.js
JavaScript
mit
37
using System.Collections.Generic; using UnityEngine; using System; namespace AI { public class GreedyAIController : PlayerController { enum NextState { Wait, Draw, Play } private NextState nextState; Dictionary<DominoController, List<DominoController>> placesToPlay = null; private void Update() { switch (nextState) { case NextState.Wait: return; case NextState.Draw: if (history.horizontalDominoes.Count > 0) { placesToPlay = PlacesToPlay(); if (placesToPlay.Count == 0) { base.DrawDomino(); placesToPlay = PlacesToPlay(); if (placesToPlay.Count == 0) { nextState = NextState.Wait; gameController.PlayerIsBlocked(this); return; } } } nextState = NextState.Play; break; case NextState.Play: List<ChosenWayToPlay> waysToPlay = new List<ChosenWayToPlay>(); if (history.horizontalDominoes.Count == 0) { foreach (DominoController domino in dominoControllers) { waysToPlay.Add(new ChosenWayToPlay(domino, null)); } } else { foreach (KeyValuePair<DominoController, List<DominoController>> entry in placesToPlay) { List<DominoController> list = entry.Value; foreach (DominoController chosenPlace in list) { ChosenWayToPlay chosenWayToPlay = new ChosenWayToPlay(entry.Key, chosenPlace); waysToPlay.Add(chosenWayToPlay); } } } // From small to large waysToPlay.Sort(delegate (ChosenWayToPlay x, ChosenWayToPlay y) { int xScore = GetScoreOfChosenWay(x); int yScore = GetScoreOfChosenWay(y); return xScore - yScore; }); ChosenWayToPlay bestWayToPlay = waysToPlay[waysToPlay.Count - 1]; PlaceDomino(bestWayToPlay.chosenDomino, bestWayToPlay.chosenPlace, history); dominoControllers.Remove(bestWayToPlay.chosenDomino); // Debug Debug.Log("Chosen Domino: " + bestWayToPlay.chosenDomino.leftValue + ", " + bestWayToPlay.chosenDomino.rightValue + ", " + bestWayToPlay.chosenDomino.upperValue + ", " + bestWayToPlay.chosenDomino.lowerValue); if (bestWayToPlay.chosenPlace != null) { Debug.Log("Chosen Place: " + bestWayToPlay.chosenPlace.leftValue + ", " + bestWayToPlay.chosenPlace.rightValue + ", " + bestWayToPlay.chosenPlace.upperValue + ", " + bestWayToPlay.chosenPlace.lowerValue); } Debug.Log(Environment.StackTrace); nextState = NextState.Wait; gameController.PlayerPlayDomino(this, bestWayToPlay.chosenDomino, bestWayToPlay.chosenPlace); break; } } public override void PlayDomino() { nextState = NextState.Draw; } private Dictionary<DominoController, List<DominoController>> PlacesToPlay() { Dictionary<DominoController, List<DominoController>> placesToPlay = new Dictionary<DominoController, List<DominoController>>(dominoControllers.Count * 4); foreach (DominoController domino in dominoControllers) { // Add places can be played for each domino List<DominoController> places = base.ListOfValidPlaces(domino); if (places == null) { continue; } placesToPlay.Add(domino, places); } return placesToPlay; } private int GetScoreOfChosenWay(ChosenWayToPlay wayToPlay) { int score = 0; // If history has no domino if (history.horizontalDominoes.Count == 0) { if (wayToPlay.chosenDomino.direction == DominoController.Direction.Horizontal) { int value = wayToPlay.chosenDomino.leftValue + wayToPlay.chosenDomino.rightValue; score = (value % 5 == 0) ? value : 0; } else { int value = wayToPlay.chosenDomino.upperValue + wayToPlay.chosenDomino.lowerValue; score = (value % 5 == 0) ? value : 0; } return score; } // Else that history has at least 1 domino DominoController copiedDomino = Instantiate<DominoController>(wayToPlay.chosenDomino); HistoryController copiedHistory = Instantiate<HistoryController>(history); // Simulate to place a domino and then calculate the sum PlaceDomino(copiedDomino, wayToPlay.chosenPlace, copiedHistory); copiedHistory.Add(copiedDomino, wayToPlay.chosenPlace); score = Utility.GetSumOfHistoryDominoes(copiedHistory.horizontalDominoes, copiedHistory.verticalDominoes, copiedHistory.spinner); score = score % 5 == 0 ? score : 0; Destroy(copiedDomino.gameObject); Destroy(copiedHistory.gameObject); return score; } private void PlaceDomino(DominoController chosenDomino, DominoController chosenPlace, HistoryController history) { DominoController clickedDomino = chosenPlace; int horizontalLen = history.horizontalDominoes.Count; int verticalLen = history.verticalDominoes.Count; if (chosenDomino != null) { if (chosenPlace != null) { if (chosenPlace == history.horizontalDominoes[0]) { if (clickedDomino.leftValue == -1) { if (chosenDomino.upperValue == clickedDomino.upperValue || chosenDomino.lowerValue == clickedDomino.upperValue) { chosenPlace = clickedDomino; if (chosenDomino.upperValue == clickedDomino.upperValue) chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue); else chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); return; } } else { if (chosenDomino.upperValue == clickedDomino.leftValue && chosenDomino.upperValue == chosenDomino.lowerValue) { chosenPlace = clickedDomino; return; } else if (chosenDomino.upperValue == clickedDomino.leftValue || chosenDomino.lowerValue == clickedDomino.leftValue) { chosenPlace = clickedDomino; if (chosenDomino.upperValue == clickedDomino.leftValue) chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue); else chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); return; } } } if (clickedDomino == history.horizontalDominoes[horizontalLen - 1]) { if (clickedDomino.leftValue == -1) { if (chosenDomino.upperValue == clickedDomino.upperValue || chosenDomino.lowerValue == clickedDomino.upperValue) { chosenPlace = clickedDomino; if (chosenDomino.upperValue == clickedDomino.upperValue) chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); else chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue); return; } } else { if (chosenDomino.upperValue == clickedDomino.rightValue && chosenDomino.upperValue == chosenDomino.lowerValue) { chosenPlace = clickedDomino; return; } else if (chosenDomino.upperValue == clickedDomino.rightValue || chosenDomino.lowerValue == clickedDomino.rightValue) { chosenPlace = clickedDomino; if (chosenDomino.upperValue == clickedDomino.rightValue) chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); else chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue); return; } } } if (verticalLen > 0 && clickedDomino == history.verticalDominoes[0]) { if (clickedDomino.leftValue == -1) { if (chosenDomino.upperValue == clickedDomino.upperValue && chosenDomino.upperValue == chosenDomino.lowerValue) { chosenPlace = clickedDomino; chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); return; } else if (chosenDomino.upperValue == clickedDomino.upperValue || chosenDomino.lowerValue == clickedDomino.upperValue) { chosenPlace = clickedDomino; if (chosenDomino.upperValue == clickedDomino.upperValue) chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue); return; } } else { if (chosenDomino.upperValue == clickedDomino.leftValue || chosenDomino.lowerValue == clickedDomino.leftValue) { chosenPlace = clickedDomino; if (chosenDomino.upperValue == clickedDomino.leftValue) chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue); return; } } } if (verticalLen > 0 && clickedDomino == history.verticalDominoes[verticalLen - 1]) { if (clickedDomino.leftValue == -1) { if (chosenDomino.upperValue == clickedDomino.lowerValue && chosenDomino.upperValue == chosenDomino.lowerValue) { chosenPlace = clickedDomino; chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); return; } else if (chosenDomino.upperValue == clickedDomino.lowerValue || chosenDomino.lowerValue == clickedDomino.lowerValue) { chosenPlace = clickedDomino; if (chosenDomino.lowerValue == clickedDomino.lowerValue) chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue); return; } } else { if (chosenDomino.upperValue == clickedDomino.leftValue || chosenDomino.lowerValue == clickedDomino.leftValue) { chosenPlace = clickedDomino; if (chosenDomino.lowerValue == clickedDomino.leftValue) chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue); return; } } } } else { if (chosenDomino.upperValue != chosenDomino.lowerValue) chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); } } } } }
hahamty/Dominoes
Game/Assets/Scripts/AI/GreedyAIController.cs
C#
mit
14,285
package com.codenotfound.endpoint; import java.math.BigInteger; import org.example.ticketagent.ObjectFactory; import org.example.ticketagent.TFlightsResponse; import org.example.ticketagent.TListFlights; import org.example.ticketagent_wsdl11.TicketAgent; public class TicketAgentImpl implements TicketAgent { @Override public TFlightsResponse listFlights(TListFlights body) { ObjectFactory factory = new ObjectFactory(); TFlightsResponse response = factory.createTFlightsResponse(); response.getFlightNumber().add(BigInteger.valueOf(101)); return response; } }
code-not-found/jaxws-cxf
jaxws-cxf-digital-signature/src/main/java/com/codenotfound/endpoint/TicketAgentImpl.java
Java
mit
588
/* The MIT License (MIT) Copyright (c) 2014 Mehmetali Shaqiri (mehmetalishaqiri@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using openvpn.api.common.domain; using openvpn.api.core.controllers; using openvpn.api.shared; using Raven.Client; using openvpn.api.core.auth; namespace openvpn.api.Controllers { public class UsersController : RavenDbApiController { /// <summary> /// Get requested user by email /// </summary> [Route("api/users/{email}")] public async Task<User> Get(string email) { return await Session.Query<User>().SingleOrDefaultAsync(u => u.Email == email); } /// <summary> /// Get all users /// </summary> [Route("api/users/all")] public async Task<IEnumerable<User>> Get() { var query = Session.Query<User>().OrderBy(u => u.Firstname).ToListAsync(); return await query; } [HttpPost] public async Task<ApiStatusCode> Post([FromBody]User userModel) { var user = await Session.Query<User>().SingleOrDefaultAsync(u => u.Email == userModel.Email); if (ModelState.IsValid) { if (user != null) return ApiStatusCode.Exists; await Session.StoreAsync(userModel); return ApiStatusCode.Saved; } return ApiStatusCode.Error; } [HttpDelete] [Route("api/users/{email}")] public async Task<ApiStatusCode> Delete(string email) { var user = await Session.Query<User>().SingleOrDefaultAsync(u => u.Email == email); if (user == null) return ApiStatusCode.Error; Session.Delete<User>(user); return ApiStatusCode.Deleted; } [HttpPut] public async Task<ApiStatusCode> Put(User userModel) { var user = await Session.Query<User>().SingleOrDefaultAsync(u => u.Email == userModel.Email); if (user != null) { user.Firstname = userModel.Firstname; user.Lastname = userModel.Lastname; user.Certificates = userModel.Certificates; await Session.SaveChangesAsync(); return ApiStatusCode.Saved; } return ApiStatusCode.Error; } } }
spartanbeg/OpenVPN-Event-Viewer
openvpn.api/openvpn.api/Controllers/UsersController.cs
C#
mit
3,668