repo_name
stringlengths 5
89
| path
stringlengths 4
310
| size
stringlengths 1
7
| content
stringlengths 4
1.04M
| license
stringclasses 15
values |
---|---|---|---|---|
fredyw/leetcode | src/main/java/leetcode/Problem804.java | 799 | package leetcode;
import java.util.HashSet;
import java.util.Set;
/**
* https://leetcode.com/problems/unique-morse-code-words/
*/
public class Problem804 {
public int uniqueMorseRepresentations(String[] words) {
String[] morse = new String[]{
".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..",
"--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-",
"-.--", "--.."};
Set<String> set = new HashSet<>();
for (String word : words) {
StringBuilder sb = new StringBuilder();
for (char c : word.toCharArray()) {
sb.append(morse[c - 'a']);
}
set.add(sb.toString());
}
return set.size();
}
}
| mit |
nagadomi/animeface-2009 | nvxs/CLAPACK/TESTING/LIN/srqt02.c | 6800 | #include "f2c.h"
#include "blaswrap.h"
/* Common Block Declarations */
struct {
char srnamt[6];
} srnamc_;
#define srnamc_1 srnamc_
/* Table of constant values */
static real c_b4 = -1e10f;
static real c_b10 = 0.f;
static real c_b15 = -1.f;
static real c_b16 = 1.f;
/* Subroutine */ int srqt02_(integer *m, integer *n, integer *k, real *a,
real *af, real *q, real *r__, integer *lda, real *tau, real *work,
integer *lwork, real *rwork, real *result)
{
/* System generated locals */
integer a_dim1, a_offset, af_dim1, af_offset, q_dim1, q_offset, r_dim1,
r_offset, i__1, i__2;
/* Builtin functions */
/* Subroutine */ int s_copy(char *, char *, ftnlen, ftnlen);
/* Local variables */
real eps;
integer info;
real resid;
extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *,
integer *, real *, real *, integer *, real *, integer *, real *,
real *, integer *);
real anorm;
extern /* Subroutine */ int ssyrk_(char *, char *, integer *, integer *,
real *, real *, integer *, real *, real *, integer *);
extern doublereal slamch_(char *), slange_(char *, integer *,
integer *, real *, integer *, real *);
extern /* Subroutine */ int slacpy_(char *, integer *, integer *, real *,
integer *, real *, integer *), slaset_(char *, integer *,
integer *, real *, real *, real *, integer *);
extern doublereal slansy_(char *, char *, integer *, real *, integer *,
real *);
extern /* Subroutine */ int sorgrq_(integer *, integer *, integer *, real
*, integer *, real *, real *, integer *, integer *);
/* -- LAPACK test routine (version 3.1) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* SRQT02 tests SORGRQ, which generates an m-by-n matrix Q with */
/* orthonornmal rows that is defined as the product of k elementary */
/* reflectors. */
/* Given the RQ factorization of an m-by-n matrix A, SRQT02 generates */
/* the orthogonal matrix Q defined by the factorization of the last k */
/* rows of A; it compares R(m-k+1:m,n-m+1:n) with */
/* A(m-k+1:m,1:n)*Q(n-m+1:n,1:n)', and checks that the rows of Q are */
/* orthonormal. */
/* Arguments */
/* ========= */
/* M (input) INTEGER */
/* The number of rows of the matrix Q to be generated. M >= 0. */
/* N (input) INTEGER */
/* The number of columns of the matrix Q to be generated. */
/* N >= M >= 0. */
/* K (input) INTEGER */
/* The number of elementary reflectors whose product defines the */
/* matrix Q. M >= K >= 0. */
/* A (input) REAL array, dimension (LDA,N) */
/* The m-by-n matrix A which was factorized by SRQT01. */
/* AF (input) REAL array, dimension (LDA,N) */
/* Details of the RQ factorization of A, as returned by SGERQF. */
/* See SGERQF for further details. */
/* Q (workspace) REAL array, dimension (LDA,N) */
/* R (workspace) REAL array, dimension (LDA,M) */
/* LDA (input) INTEGER */
/* The leading dimension of the arrays A, AF, Q and L. LDA >= N. */
/* TAU (input) REAL array, dimension (M) */
/* The scalar factors of the elementary reflectors corresponding */
/* to the RQ factorization in AF. */
/* WORK (workspace) REAL array, dimension (LWORK) */
/* LWORK (input) INTEGER */
/* The dimension of the array WORK. */
/* RWORK (workspace) REAL array, dimension (M) */
/* RESULT (output) REAL array, dimension (2) */
/* The test ratios: */
/* RESULT(1) = norm( R - A*Q' ) / ( N * norm(A) * EPS ) */
/* RESULT(2) = norm( I - Q*Q' ) / ( N * EPS ) */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Scalars in Common .. */
/* .. */
/* .. Common blocks .. */
/* .. */
/* .. Executable Statements .. */
/* Quick return if possible */
/* Parameter adjustments */
r_dim1 = *lda;
r_offset = 1 + r_dim1;
r__ -= r_offset;
q_dim1 = *lda;
q_offset = 1 + q_dim1;
q -= q_offset;
af_dim1 = *lda;
af_offset = 1 + af_dim1;
af -= af_offset;
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
--tau;
--work;
--rwork;
--result;
/* Function Body */
if (*m == 0 || *n == 0 || *k == 0) {
result[1] = 0.f;
result[2] = 0.f;
return 0;
}
eps = slamch_("Epsilon");
/* Copy the last k rows of the factorization to the array Q */
slaset_("Full", m, n, &c_b4, &c_b4, &q[q_offset], lda);
if (*k < *n) {
i__1 = *n - *k;
slacpy_("Full", k, &i__1, &af[*m - *k + 1 + af_dim1], lda, &q[*m - *k
+ 1 + q_dim1], lda);
}
if (*k > 1) {
i__1 = *k - 1;
i__2 = *k - 1;
slacpy_("Lower", &i__1, &i__2, &af[*m - *k + 2 + (*n - *k + 1) *
af_dim1], lda, &q[*m - *k + 2 + (*n - *k + 1) * q_dim1], lda);
}
/* Generate the last n rows of the matrix Q */
s_copy(srnamc_1.srnamt, "SORGRQ", (ftnlen)6, (ftnlen)6);
sorgrq_(m, n, k, &q[q_offset], lda, &tau[*m - *k + 1], &work[1], lwork, &
info);
/* Copy R(m-k+1:m,n-m+1:n) */
slaset_("Full", k, m, &c_b10, &c_b10, &r__[*m - *k + 1 + (*n - *m + 1) *
r_dim1], lda);
slacpy_("Upper", k, k, &af[*m - *k + 1 + (*n - *k + 1) * af_dim1], lda, &
r__[*m - *k + 1 + (*n - *k + 1) * r_dim1], lda);
/* Compute R(m-k+1:m,n-m+1:n) - A(m-k+1:m,1:n) * Q(n-m+1:n,1:n)' */
sgemm_("No transpose", "Transpose", k, m, n, &c_b15, &a[*m - *k + 1 +
a_dim1], lda, &q[q_offset], lda, &c_b16, &r__[*m - *k + 1 + (*n -
*m + 1) * r_dim1], lda);
/* Compute norm( R - A*Q' ) / ( N * norm(A) * EPS ) . */
anorm = slange_("1", k, n, &a[*m - *k + 1 + a_dim1], lda, &rwork[1]);
resid = slange_("1", k, m, &r__[*m - *k + 1 + (*n - *m + 1) * r_dim1],
lda, &rwork[1]);
if (anorm > 0.f) {
result[1] = resid / (real) max(1,*n) / anorm / eps;
} else {
result[1] = 0.f;
}
/* Compute I - Q*Q' */
slaset_("Full", m, m, &c_b10, &c_b16, &r__[r_offset], lda);
ssyrk_("Upper", "No transpose", m, n, &c_b15, &q[q_offset], lda, &c_b16, &
r__[r_offset], lda);
/* Compute norm( I - Q*Q' ) / ( N * EPS ) . */
resid = slansy_("1", "Upper", m, &r__[r_offset], lda, &rwork[1]);
result[2] = resid / (real) max(1,*n) / eps;
return 0;
/* End of SRQT02 */
} /* srqt02_ */
| mit |
xdien/Sua-anh | README.md | 10 | # Sua-anh
| mit |
fuzzbomb/accessibility-demos | ms-high-contrast-media-query.html | 1848 | <!DOCTYPE html>
<html lang="en">
<head>
<title>MS High Contrast Media Query Test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
@media all and (-ms-high-contrast) {
.mshc:after {
content: ' MATCHED';
}
}
@media all and (-ms-high-contrast: none) {
.mshc-none:after {
content: ' MATCHED';
}
}
@media all and (-ms-high-contrast: active) {
.mshc-active:after {
content: ' MATCHED';
}
}
@media all and (-ms-high-contrast: white-on-black) {
.mshc-white-on-black:after {
content: ' MATCHED';
}
}
@media all and (-ms-high-contrast: black-on-white) {
.mshc-black-on-white:after {
content: ' MATCHED';
}
}
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.mshc-none-or-active:after {
content: ' MATCHED';
}
}
</style>
</head>
<body>
<main role="main">
<h1>MS High Contrast Media Query Test</h1>
<p>A test page for various ways to use the <code>-ms-high-contrast</code> media query.</p>
<p class="mshc"><code>@media all and (-ms-high-contrast)</code></p>
<p class="mshc-none"><code>@media all and (-ms-high-contrast: none)</code></p>
<p class="mshc-active"><code>@media all and (-ms-high-contrast: active)</code></p>
<p class="mshc-white-on-black"><code>@media all and (-ms-high-contrast: white-on-black)</code></p>
<p class="mshc-black-on-white"><code>@media all and (-ms-high-contrast: black-on-white)</code></p>
<p class="mshc-none-or-active"><code>@media all and (-ms-high-contrast: none), (-ms-high-contrast: active)</code></p>
</main>
</body>
</html>
| mit |
hongjianqiang/Reading-Notes | 深入浅出NodeJS/demo/EventProxy实现前端模块加载/js/eventproxy.js | 18203 | /*global define*/
!(function (name, definition) {
// Check define
var hasDefine = typeof define === 'function',
// Check exports
hasExports = typeof module !== 'undefined' && module.exports;
if (hasDefine) {
// AMD Module or CMD Module
define('eventproxy_debug', function () {return function () {};});
define(['eventproxy_debug'], definition);
} else if (hasExports) {
// Node.js Module
module.exports = definition(require('debug')('eventproxy'));
} else {
// Assign to common namespaces or simply the global object (window)
this[name] = definition();
}
})('EventProxy', function (debug) {
debug = debug || function () {};
/*!
* refs
*/
var SLICE = Array.prototype.slice;
var CONCAT = Array.prototype.concat;
var ALL_EVENT = '__all__';
/**
* EventProxy. An implementation of task/event based asynchronous pattern.
* A module that can be mixed in to *any object* in order to provide it with custom events.
* You may `bind` or `unbind` a callback function to an event;
* `trigger`-ing an event fires all callbacks in succession.
* Examples:
* ```js
* var render = function (template, resources) {};
* var proxy = new EventProxy();
* proxy.assign("template", "l10n", render);
* proxy.trigger("template", template);
* proxy.trigger("l10n", resources);
* ```
*/
var EventProxy = function () {
if (!(this instanceof EventProxy)) {
return new EventProxy();
}
this._callbacks = {};
this._fired = {};
this._events = {};
};
/**
* Bind an event, specified by a string name, `ev`, to a `callback` function.
* Passing __ALL_EVENT__ will bind the callback to all events fired.
* Examples:
* ```js
* var proxy = new EventProxy();
* proxy.addListener("template", function (event) {
* // TODO
* });
* ```
* @param {String} eventname Event name.
* @param {Function} callback Callback.
*/
EventProxy.prototype.addListener = function (ev, callback) {
debug('Add listener for %s', ev);
this._callbacks[ev] = this._callbacks[ev] || [];
this._callbacks[ev].push(callback);
return this;
};
/**
* `addListener` alias, `bind`
*/
EventProxy.prototype.bind = EventProxy.prototype.addListener;
/**
* `addListener` alias, `on`
*/
EventProxy.prototype.on = EventProxy.prototype.addListener;
/**
* `addListener` alias, `subscribe`
*/
EventProxy.prototype.subscribe = EventProxy.prototype.addListener;
/**
* Bind an event, but put the callback into head of all callbacks.
* @param {String} eventname Event name.
* @param {Function} callback Callback.
*/
EventProxy.prototype.headbind = function (ev, callback) {
debug('Add listener for %s', ev);
this._callbacks[ev] = this._callbacks[ev] || [];
this._callbacks[ev].unshift(callback);
return this;
};
/**
* Remove one or many callbacks.
*
* - If `callback` is null, removes all callbacks for the event.
* - If `eventname` is null, removes all bound callbacks for all events.
* @param {String} eventname Event name.
* @param {Function} callback Callback.
*/
EventProxy.prototype.removeListener = function (eventname, callback) {
var calls = this._callbacks;
if (!eventname) {
debug('Remove all listeners');
this._callbacks = {};
} else {
if (!callback) {
debug('Remove all listeners of %s', eventname);
calls[eventname] = [];
} else {
var list = calls[eventname];
if (list) {
var l = list.length;
for (var i = 0; i < l; i++) {
if (callback === list[i]) {
debug('Remove a listener of %s', eventname);
list[i] = null;
}
}
}
}
}
return this;
};
/**
* `removeListener` alias, unbind
*/
EventProxy.prototype.unbind = EventProxy.prototype.removeListener;
/**
* Remove all listeners. It equals unbind()
* Just add this API for as same as Event.Emitter.
* @param {String} event Event name.
*/
EventProxy.prototype.removeAllListeners = function (event) {
return this.unbind(event);
};
/**
* Bind the ALL_EVENT event
*/
EventProxy.prototype.bindForAll = function (callback) {
this.bind(ALL_EVENT, callback);
};
/**
* Unbind the ALL_EVENT event
*/
EventProxy.prototype.unbindForAll = function (callback) {
this.unbind(ALL_EVENT, callback);
};
/**
* Trigger an event, firing all bound callbacks. Callbacks are passed the
* same arguments as `trigger` is, apart from the event name.
* Listening for `"all"` passes the true event name as the first argument.
* @param {String} eventname Event name
* @param {Mix} data Pass in data
*/
EventProxy.prototype.trigger = function (eventname, data) {
var list, ev, callback, i, l;
var both = 2;
var calls = this._callbacks;
debug('Emit event %s with data %j', eventname, data);
while (both--) {
ev = both ? eventname : ALL_EVENT;
list = calls[ev];
if (list) {
for (i = 0, l = list.length; i < l; i++) {
if (!(callback = list[i])) {
list.splice(i, 1);
i--;
l--;
} else {
var args = [];
var start = both ? 1 : 0;
for (var j = start; j < arguments.length; j++) {
args.push(arguments[j]);
}
callback.apply(this, args);
}
}
}
}
return this;
};
/**
* `trigger` alias
*/
EventProxy.prototype.emit = function(eventname, data) {
this._events[eventname] = data;
this.trigger.apply(this, [eventname, data]);
};
/**
* `trigger` alias
*/
EventProxy.prototype.fire = EventProxy.prototype.trigger;
/**
* Bind an event like the bind method, but will remove the listener after it was fired.
* @param {String} ev Event name
* @param {Function} callback Callback
*/
EventProxy.prototype.once = function (ev, callback) {
var self = this;
var wrapper = function () {
callback.apply(self, arguments);
self.unbind(ev, wrapper);
};
this.bind(ev, wrapper);
return this;
};
var later = (typeof setImmediate !== 'undefined' && setImmediate) ||
(typeof process !== 'undefined' && process.nextTick) || function (fn) {
setTimeout(fn, 0);
};
/**
* emitLater
* make emit async
*/
EventProxy.prototype.emitLater = function () {
var self = this;
var args = arguments;
later(function () {
self.trigger.apply(self, args);
});
};
/**
* Bind an event, and trigger it immediately.
* @param {String} ev Event name.
* @param {Function} callback Callback.
* @param {Mix} data The data that will be passed to calback as arguments.
*/
EventProxy.prototype.immediate = function (ev, callback, data) {
this.bind(ev, callback);
this.trigger(ev, data);
return this;
};
/**
* `immediate` alias
*/
EventProxy.prototype.asap = EventProxy.prototype.immediate;
var _assign = function (eventname1, eventname2, cb, once) {
var proxy = this;
var argsLength = arguments.length;
var times = 0;
var flag = {};
// Check the arguments length.
if (argsLength < 3) {
return this;
}
var events = SLICE.call(arguments, 0, -2);
var callback = arguments[argsLength - 2];
var isOnce = arguments[argsLength - 1];
// Check the callback type.
if (typeof callback !== "function") {
return this;
}
debug('Assign listener for events %j, once is %s', events, !!isOnce);
var bind = function (key) {
var method = isOnce ? "once" : "bind";
proxy[method](key, function (data) {
proxy._fired[key] = proxy._fired[key] || {};
proxy._fired[key].data = data;
if (!flag[key]) {
flag[key] = true;
times++;
}
});
};
var length = events.length;
for (var index = 0; index < length; index++) {
bind(events[index]);
}
var _all = function (event) {
if (times < length) {
return;
}
if (!flag[event]) {
return;
}
var data = [];
for (var index = 0; index < length; index++) {
data.push(proxy._fired[events[index]].data);
}
if (isOnce) {
proxy.unbindForAll(_all);
}
debug('Events %j all emited with data %j', events, data);
callback.apply(null, data);
};
proxy.bindForAll(_all);
};
/**
* Assign some events, after all events were fired, the callback will be executed once.
*
* Examples:
* ```js
* proxy.all(ev1, ev2, callback);
* proxy.all([ev1, ev2], callback);
* proxy.all(ev1, [ev2, ev3], callback);
* ```
* @param {String} eventname1 First event name.
* @param {String} eventname2 Second event name.
* @param {Function} callback Callback, that will be called after predefined events were fired.
*/
EventProxy.prototype.all = function (eventname1, eventname2, callback) {
var args = CONCAT.apply([], arguments);
args.push(true);
_assign.apply(this, args);
for (var k in this._events) {
this.emit.apply(this, [k, this._events[k]]);
}
return this;
};
/**
* `all` alias
*/
EventProxy.prototype.assign = EventProxy.prototype.all;
/**
* Assign the only one 'error' event handler.
* @param {Function(err)} callback
*/
EventProxy.prototype.fail = function (callback) {
var that = this;
that.once('error', function () {
that.unbind();
// put all arguments to the error handler
// fail(function(err, args1, args2, ...){})
callback.apply(null, arguments);
});
return this;
};
/**
* A shortcut of ep#emit('error', err)
*/
EventProxy.prototype.throw = function () {
var that = this;
that.emit.apply(that, ['error'].concat(SLICE.call(arguments)));
};
/**
* Assign some events, after all events were fired, the callback will be executed first time.
* Then any event that predefined be fired again, the callback will executed with the newest data.
* Examples:
* ```js
* proxy.tail(ev1, ev2, callback);
* proxy.tail([ev1, ev2], callback);
* proxy.tail(ev1, [ev2, ev3], callback);
* ```
* @param {String} eventname1 First event name.
* @param {String} eventname2 Second event name.
* @param {Function} callback Callback, that will be called after predefined events were fired.
*/
EventProxy.prototype.tail = function () {
var args = CONCAT.apply([], arguments);
args.push(false);
_assign.apply(this, args);
return this;
};
/**
* `tail` alias, assignAll
*/
EventProxy.prototype.assignAll = EventProxy.prototype.tail;
/**
* `tail` alias, assignAlways
*/
EventProxy.prototype.assignAlways = EventProxy.prototype.tail;
/**
* The callback will be executed after the event be fired N times.
* @param {String} eventname Event name.
* @param {Number} times N times.
* @param {Function} callback Callback, that will be called after event was fired N times.
*/
EventProxy.prototype.after = function (eventname, times, callback) {
if (times === 0) {
callback.call(null, []);
return this;
}
var proxy = this,
firedData = [];
this._after = this._after || {};
var group = eventname + '_group';
this._after[group] = {
index: 0,
results: []
};
debug('After emit %s times, event %s\'s listenner will execute', times, eventname);
var all = function (name, data) {
if (name === eventname) {
times--;
firedData.push(data);
if (times < 1) {
debug('Event %s was emit %s, and execute the listenner', eventname, times);
proxy.unbindForAll(all);
callback.apply(null, [firedData]);
}
}
if (name === group) {
times--;
proxy._after[group].results[data.index] = data.result;
if (times < 1) {
debug('Event %s was emit %s, and execute the listenner', eventname, times);
proxy.unbindForAll(all);
callback.call(null, proxy._after[group].results);
}
}
};
proxy.bindForAll(all);
return this;
};
/**
* The `after` method's helper. Use it will return ordered results.
* If you need manipulate result, you need callback
* Examples:
* ```js
* var ep = new EventProxy();
* ep.after('file', files.length, function (list) {
* // Ordered results
* });
* for (var i = 0; i < files.length; i++) {
* fs.readFile(files[i], 'utf-8', ep.group('file'));
* }
* ```
* @param {String} eventname Event name, shoule keep consistent with `after`.
* @param {Function} callback Callback function, should return the final result.
*/
EventProxy.prototype.group = function (eventname, callback) {
var that = this;
var group = eventname + '_group';
var index = that._after[group].index;
that._after[group].index++;
return function (err, data) {
if (err) {
// put all arguments to the error handler
return that.emit.apply(that, ['error'].concat(SLICE.call(arguments)));
}
that.emit(group, {
index: index,
// callback(err, args1, args2, ...)
result: callback ? callback.apply(null, SLICE.call(arguments, 1)) : data
});
};
};
/**
* The callback will be executed after any registered event was fired. It only executed once.
* @param {String} eventname1 Event name.
* @param {String} eventname2 Event name.
* @param {Function} callback The callback will get a map that has data and eventname attributes.
*/
EventProxy.prototype.any = function () {
var proxy = this,
callback = arguments[arguments.length - 1],
events = SLICE.call(arguments, 0, -1),
_eventname = events.join("_");
debug('Add listenner for Any of events %j emit', events);
proxy.once(_eventname, callback);
var _bind = function (key) {
proxy.bind(key, function (data) {
debug('One of events %j emited, execute the listenner');
proxy.trigger(_eventname, {"data": data, eventName: key});
});
};
for (var index = 0; index < events.length; index++) {
_bind(events[index]);
}
};
/**
* The callback will be executed when the event name not equals with assigned event.
* @param {String} eventname Event name.
* @param {Function} callback Callback.
*/
EventProxy.prototype.not = function (eventname, callback) {
var proxy = this;
debug('Add listenner for not event %s', eventname);
proxy.bindForAll(function (name, data) {
if (name !== eventname) {
debug('listenner execute of event %s emit, but not event %s.', name, eventname);
callback(data);
}
});
};
/**
* Success callback wrapper, will handler err for you.
*
* ```js
* fs.readFile('foo.txt', ep.done('content'));
*
* // equal to =>
*
* fs.readFile('foo.txt', function (err, content) {
* if (err) {
* return ep.emit('error', err);
* }
* ep.emit('content', content);
* });
* ```
*
* ```js
* fs.readFile('foo.txt', ep.done('content', function (content) {
* return content.trim();
* }));
*
* // equal to =>
*
* fs.readFile('foo.txt', function (err, content) {
* if (err) {
* return ep.emit('error', err);
* }
* ep.emit('content', content.trim());
* });
* ```
* @param {Function|String} handler, success callback or event name will be emit after callback.
* @return {Function}
*/
EventProxy.prototype.done = function (handler, callback) {
var that = this;
return function (err, data) {
if (err) {
// put all arguments to the error handler
return that.emit.apply(that, ['error'].concat(SLICE.call(arguments)));
}
// callback(err, args1, args2, ...)
var args = SLICE.call(arguments, 1);
if (typeof handler === 'string') {
// getAsync(query, ep.done('query'));
// or
// getAsync(query, ep.done('query', function (data) {
// return data.trim();
// }));
if (callback) {
// only replace the args when it really return a result
return that.emit(handler, callback.apply(null, args));
} else {
// put all arguments to the done handler
//ep.done('some');
//ep.on('some', function(args1, args2, ...){});
return that.emit.apply(that, [handler].concat(args));
}
}
// speed improve for mostly case: `callback(err, data)`
if (arguments.length <= 2) {
return handler(data);
}
// callback(err, args1, args2, ...)
handler.apply(null, args);
};
};
/**
* make done async
* @return {Function} delay done
*/
EventProxy.prototype.doneLater = function (handler, callback) {
var _doneHandler = this.done(handler, callback);
return function (err, data) {
var args = arguments;
later(function () {
_doneHandler.apply(null, args);
});
};
};
/**
* Create a new EventProxy
* Examples:
* ```js
* var ep = EventProxy.create();
* ep.assign('user', 'articles', function(user, articles) {
* // do something...
* });
* // or one line ways: Create EventProxy and Assign
* var ep = EventProxy.create('user', 'articles', function(user, articles) {
* // do something...
* });
* ```
* @return {EventProxy} EventProxy instance
*/
EventProxy.create = function () {
var ep = new EventProxy();
var args = CONCAT.apply([], arguments);
if (args.length) {
var errorHandler = args[args.length - 1];
var callback = args[args.length - 2];
if (typeof errorHandler === 'function' && typeof callback === 'function') {
args.pop();
ep.fail(errorHandler);
}
ep.assign.apply(ep, args);
}
return ep;
};
// Backwards compatibility
EventProxy.EventProxy = EventProxy;
return EventProxy;
});
var eventProxy = new EventProxy(); | mit |
Warframe-Community-Developers/warframe-worldstate-parser | .github/ISSUE_TEMPLATE/Bug_report.md | 163 | ---
name: Bug report
about: Create a report to help us improve
---
**Summary (short):**
---
**Description:**
---
**If issue, Reproduction:**
---
**Evidence:**
| mit |
ntrampe/FanFactory | fan/ntt/ntt_core/CCChangeScaleWithoutPositionChangeCenter.h | 1404 | /*
* Copyright (c) 2013 Nicholas Trampe
*
* 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.
*
*/
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface CCChangeScaleWithoutPositionChangeCenter : CCActionInstant <NSCopying>
{
CGPoint newScale;
}
+(id) actionWithScale: (CGPoint) scale;
-(id) initWithScale:(CGPoint) scale;
-(void) startWithTarget:(id)aTarget;
@end
| mit |
jsperts/workshop_unterlagen | angularjs/examples/14-Routing_2/app/main.component.js | 1710 | class Main {
constructor($scope, $route, $window) {
this.current = $route.current;
$scope.$on('$locationChangeStart', (event, newUrl, oldUrl) => {
this.locationStatus = 'Location change start';
this.oldUrl = oldUrl;
this.newUrl = newUrl;
});
$scope.$on('$routeChangeStart', (event, next, current) => {
this.current = current;
this.next = next;
this.status = 'Route change start';
});
$scope.$on('$locationChangeSuccess', (event, newUrl, oldUrl) => {
this.locationStatus = 'Location change success';
this.oldUrl = oldUrl;
this.newUrl = newUrl;
});
$scope.$on('$routeChangeSuccess', (event, current, previous) => {
this.current = current;
this.previous = previous;
this.status = 'Route change success';
});
$scope.$on('$routeChangeError', (event, current, previous, rejection) => {
this.current = current;
this.previous = previous;
this.status = `Route change failed: ${rejection}`;
});
}
}
Main.$inject = ['$scope', '$route', '$window'];
const component = {
template: `
<a href="#!/comp1?name=comp1">Component 1</a> <a href="#!/comp2?name=comp2">Component 2</a>
<div>Route status: {{$ctrl.status}}</div>
<div>
<pre>Previous: {{$ctrl.previous.params.name}}</pre>
<pre>Current: {{$ctrl.current.params.name}}</pre>
<pre>Next: {{$ctrl.next.params.name}}</pre>
</div>
<div>Location status: {{$ctrl.locationStatus}}</div>
<div>
<pre>Old Url: {{$ctrl.oldUrl}}</pre>
<pre>New Url: {{$ctrl.newUrl}}</pre>
</div>
<ng-view></ng-view>
`,
controller: Main
};
export default component;
export const name = 'myApp';
| mit |
ICJIA/icjia-tvpp | statamic/core/Extend/Management/ModifierLoader.php | 1357 | <?php
namespace Statamic\Extend\Management;
use Statamic\API\Str;
use Statamic\Exceptions\ResourceNotFoundException;
class ModifierLoader
{
public function load($modifier)
{
// An addon may contain multiple modifiers. You may specify a "secondary" modifier by delimiting with a dot.
// For example, "{{ var | bacon.bits }}" would reference the "BitsModifier" in the "Bacon" addon.
if (Str::contains($modifier, '.')) {
list($addon, $name) = explode('.', $modifier);
} else {
$addon = $name = $modifier;
}
$name = Str::studly($name);
$addon = Str::studly($addon);
$root = "Statamic\\Addons\\$addon";
// Modifiers may be stored in the root of the addon directory, named using YourAddonModifier.php or
// secondary ones may be named SecondaryModifier.php. Classes in the root will take precedence.
if (class_exists($rootClass = "{$root}\\{$name}Modifier")) {
return app($rootClass);
}
// Alternatively, modifiers may be placed in a "Modifiers" namespace.
if (class_exists($namespacedClass = "{$root}\\Modifiers\\{$name}Modifier")) {
return app($namespacedClass);
}
throw new ResourceNotFoundException("Could not find files to load the `{$modifier}` modifier.");
}
}
| mit |
Nazi-Nigger/Ms-CRM-2016-Controls | Ms-CRM-2016-Controls/Ms-CRM-2016-Controls Resources/Javascript/Intellisense Files/Lead Form - Information.js | 41290 | /// <reference path="Xrm.js" />
var EntityLogicalName = "lead";
var Form_9886ead0_4fcc_4747_9a18_08e7a9a6de71_Properties = {
address1_city: "address1_city",
address1_country: "address1_country",
address1_line1: "address1_line1",
address1_line2: "address1_line2",
address1_line3: "address1_line3",
address1_postalcode: "address1_postalcode",
address1_stateorprovince: "address1_stateorprovince",
campaignid: "campaignid",
companyname: "companyname",
description: "description",
donotbulkemail: "donotbulkemail",
donotemail: "donotemail",
donotfax: "donotfax",
donotphone: "donotphone",
donotpostalmail: "donotpostalmail",
donotsendmm: "donotsendmm",
emailaddress1: "emailaddress1",
fax: "fax",
firstname: "firstname",
industrycode: "industrycode",
jobtitle: "jobtitle",
lastname: "lastname",
lastusedincampaign: "lastusedincampaign",
leadqualitycode: "leadqualitycode",
leadsourcecode: "leadsourcecode",
mobilephone: "mobilephone",
numberofemployees: "numberofemployees",
ownerid: "ownerid",
pager: "pager",
preferredcontactmethodcode: "preferredcontactmethodcode",
revenue: "revenue",
salutation: "salutation",
sic: "sic",
statuscode: "statuscode",
subject: "subject",
telephone1: "telephone1",
telephone2: "telephone2",
telephone3: "telephone3",
transactioncurrencyid: "transactioncurrencyid",
websiteurl: "websiteurl"
};
var Form_9886ead0_4fcc_4747_9a18_08e7a9a6de71_Controls = {
address1_city: "address1_city",
address1_country: "address1_country",
address1_line1: "address1_line1",
address1_line2: "address1_line2",
address1_line3: "address1_line3",
address1_postalcode: "address1_postalcode",
address1_stateorprovince: "address1_stateorprovince",
campaignid: "campaignid",
companyname: "companyname",
description: "description",
donotbulkemail: "donotbulkemail",
donotemail: "donotemail",
donotfax: "donotfax",
donotphone: "donotphone",
donotpostalmail: "donotpostalmail",
donotsendmm: "donotsendmm",
emailaddress1: "emailaddress1",
fax: "fax",
firstname: "firstname",
header_leadqualitycode: "header_leadqualitycode",
header_leadsourcecode: "header_leadsourcecode",
header_ownerid: "header_ownerid",
industrycode: "industrycode",
jobtitle: "jobtitle",
lastname: "lastname",
lastusedincampaign: "lastusedincampaign",
leadactivitiesgrid: "leadactivitiesgrid",
leadqualitycode: "leadqualitycode",
leadsourcecode: "leadsourcecode",
mobilephone: "mobilephone",
notescontrol: "notescontrol",
numberofemployees: "numberofemployees",
ownerid: "ownerid",
pager: "pager",
preferredcontactmethodcode: "preferredcontactmethodcode",
revenue: "revenue",
salutation: "salutation",
sic: "sic",
statuscode: "statuscode",
subject: "subject",
telephone1: "telephone1",
telephone2: "telephone2",
telephone3: "telephone3",
transactioncurrencyid: "transactioncurrencyid",
WebResource_RecordWall: "WebResource_RecordWall",
websiteurl: "websiteurl"
};
var pageData = {
"Event": "none",
"SaveMode": 1,
"EventSource": null,
"AuthenticationHeader": "",
"CurrentTheme": "Default",
"OrgLcid": 1033,
"OrgUniqueName": "",
"QueryStringParameters": {
"_gridType": "4",
"etc": "4",
"id": "",
"pagemode": "iframe",
"preloadcache": "1344548892170",
"rskey": "141637534"
},
"ServerUrl": "",
"UserId": "",
"UserLcid": 1033,
"UserRoles": [""],
"isOutlookClient": false,
"isOutlookOnline": true,
"DataXml": "",
"EntityName": "lead",
"Id": "",
"IsDirty": false,
"CurrentControl": "",
"CurrentForm": null,
"Forms": [],
"FormType": 2,
"ViewPortHeight": 558,
"ViewPortWidth": 1231,
"Attributes": [{
"Name": "address1_city",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 80,
"Controls": [{
"Name": "address1_city"
}]
},
{
"Name": "address1_country",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 80,
"Controls": [{
"Name": "address1_country"
}]
},
{
"Name": "address1_line1",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 250,
"Controls": [{
"Name": "address1_line1"
}]
},
{
"Name": "address1_line2",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 250,
"Controls": [{
"Name": "address1_line2"
}]
},
{
"Name": "address1_line3",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 250,
"Controls": [{
"Name": "address1_line3"
}]
},
{
"Name": "address1_postalcode",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 20,
"Controls": [{
"Name": "address1_postalcode"
}]
},
{
"Name": "address1_stateorprovince",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 50,
"Controls": [{
"Name": "address1_stateorprovince"
}]
},
{
"Name": "campaignid",
"Value": [{
"entityType": "Unknown",
"id": "{27ACAE0A-5D79-E111-BBD3-2657AEB3167B}",
"name": "Temp"
}],
"Type": "lookup",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"Controls": [{
"Name": "campaignid"
}]
},
{
"Name": "companyname",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 100,
"Controls": [{
"Name": "companyname"
}]
},
{
"Name": "description",
"Value": "",
"Type": "memo",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 2000,
"Controls": [{
"Name": "description"
}]
},
{
"Name": "donotbulkemail",
"Value": null,
"Type": "boolean",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"InitialValue": null,
"Controls": [{
"Name": "donotbulkemail"
}]
},
{
"Name": "donotemail",
"Value": null,
"Type": "boolean",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"InitialValue": null,
"Controls": [{
"Name": "donotemail"
}]
},
{
"Name": "donotfax",
"Value": null,
"Type": "boolean",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"InitialValue": null,
"Controls": [{
"Name": "donotfax"
}]
},
{
"Name": "donotphone",
"Value": null,
"Type": "boolean",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"InitialValue": null,
"Controls": [{
"Name": "donotphone"
}]
},
{
"Name": "donotpostalmail",
"Value": null,
"Type": "boolean",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"InitialValue": null,
"Controls": [{
"Name": "donotpostalmail"
}]
},
{
"Name": "donotsendmm",
"Value": null,
"Type": "boolean",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"InitialValue": null,
"Controls": [{
"Name": "donotsendmm"
}]
},
{
"Name": "emailaddress1",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 100,
"Controls": [{
"Name": "emailaddress1"
}]
},
{
"Name": "fax",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 50,
"Controls": [{
"Name": "fax"
}]
},
{
"Name": "firstname",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 50,
"Controls": [{
"Name": "firstname"
}]
},
{
"Name": "industrycode",
"Value": null,
"Type": "optionset",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"InitialValue": 930650000,
"Options": [{
"text": "Accounting",
"value": 1
},
{
"text": "Agriculture and Non-petrol Natural Resource Extraction",
"value": 2
},
{
"text": "Broadcasting Printing and Publishing",
"value": 3
},
{
"text": "Brokers",
"value": 4
},
{
"text": "Building Supply Retail",
"value": 5
},
{
"text": "Business Services",
"value": 6
},
{
"text": "Consulting",
"value": 7
},
{
"text": "Consumer Services",
"value": 8
},
{
"text": "Design, Direction and Creative Management",
"value": 9
},
{
"text": "Distributors, Dispatchers and Processors",
"value": 10
},
{
"text": "Doctor's Offices and Clinics",
"value": 11
},
{
"text": "Durable Manufacturing",
"value": 12
},
{
"text": "Eating and Drinking Places",
"value": 13
},
{
"text": "Entertainment Retail",
"value": 14
},
{
"text": "Equipment Rental and Leasing",
"value": 15
},
{
"text": "Financial",
"value": 16
},
{
"text": "Food and Tobacco Processing",
"value": 17
},
{
"text": "Inbound Capital Intensive Processing",
"value": 18
},
{
"text": "Inbound Repair and Services",
"value": 19
},
{
"text": "Insurance",
"value": 20
},
{
"text": "Legal Services",
"value": 21
},
{
"text": "Non-Durable Merchandise Retail",
"value": 22
},
{
"text": "Outbound Consumer Service",
"value": 23
},
{
"text": "Petrochemical Extraction and Distribution",
"value": 24
},
{
"text": "Service Retail",
"value": 25
},
{
"text": "SIG Affiliations",
"value": 26
},
{
"text": "Social Services",
"value": 27
},
{
"text": "Special Outbound Trade Contractors",
"value": 28
},
{
"text": "Specialty Realty",
"value": 29
},
{
"text": "Transportation",
"value": 30
},
{
"text": "Utility Creation and Distribution",
"value": 31
},
{
"text": "Vehicle Retail",
"value": 32
},
{
"text": "Wholesale",
"value": 33
}],
"SelectedOption": {
"option": "Accounting",
"value": 1
},
"Text": "Accounting",
"Controls": [{
"Name": "industrycode"
}]
},
{
"Name": "jobtitle",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 100,
"Controls": [{
"Name": "jobtitle"
}]
},
{
"Name": "lastname",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 50,
"Controls": [{
"Name": "lastname"
}]
},
{
"Name": "lastusedincampaign",
"Value": null,
"Type": "datetime",
"Format": "date",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": false
},
"Controls": [{
"Name": "lastusedincampaign"
}]
},
{
"Name": "leadqualitycode",
"Value": null,
"Type": "optionset",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"InitialValue": 930650000,
"Options": [{
"text": "Hot",
"value": 1
},
{
"text": "Warm",
"value": 2
},
{
"text": "Cold",
"value": 3
}],
"SelectedOption": {
"option": "Hot",
"value": 1
},
"Text": "Hot",
"Controls": [{
"Name": "header_leadqualitycode"
},
{
"Name": "leadqualitycode"
}]
},
{
"Name": "leadsourcecode",
"Value": null,
"Type": "optionset",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"InitialValue": 930650000,
"Options": [{
"text": "Advertisement",
"value": 1
},
{
"text": "Employee Referral",
"value": 2
},
{
"text": "External Referral",
"value": 3
},
{
"text": "Partner",
"value": 4
},
{
"text": "Public Relations",
"value": 5
},
{
"text": "Seminar",
"value": 6
},
{
"text": "Trade Show",
"value": 7
},
{
"text": "Web",
"value": 8
},
{
"text": "Word of Mouth",
"value": 9
},
{
"text": "Other",
"value": 10
}],
"SelectedOption": {
"option": "Advertisement",
"value": 1
},
"Text": "Advertisement",
"Controls": [{
"Name": "header_leadsourcecode"
},
{
"Name": "leadsourcecode"
}]
},
{
"Name": "mobilephone",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 20,
"Controls": [{
"Name": "mobilephone"
}]
},
{
"Name": "numberofemployees",
"Value": null,
"Type": "integer",
"Format": "none",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"Max": 1000000,
"Min": 0,
"Precision": 0,
"Controls": [{
"Name": "numberofemployees"
}]
},
{
"Name": "ownerid",
"Value": [{
"entityType": "Unknown",
"id": "{27ACAE0A-5D79-E111-BBD3-2657AEB3167B}",
"name": "Temp"
}],
"Type": "lookup",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"Controls": [{
"Name": "header_ownerid"
},
{
"Name": "ownerid"
}]
},
{
"Name": "pager",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 20,
"Controls": [{
"Name": "pager"
}]
},
{
"Name": "preferredcontactmethodcode",
"Value": null,
"Type": "optionset",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"InitialValue": 930650000,
"Options": [{
"text": "Any",
"value": 1
},
{
"text": "Email",
"value": 2
},
{
"text": "Phone",
"value": 3
},
{
"text": "Fax",
"value": 4
},
{
"text": "Mail",
"value": 5
}],
"SelectedOption": {
"option": "Any",
"value": 1
},
"Text": "Any",
"Controls": [{
"Name": "preferredcontactmethodcode"
}]
},
{
"Name": "revenue",
"Value": null,
"Type": "double",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"Max": 100000000000000,
"Min": 0,
"Precision": 2,
"Controls": [{
"Name": "revenue"
}]
},
{
"Name": "salutation",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 100,
"Controls": [{
"Name": "salutation"
}]
},
{
"Name": "sic",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 20,
"Controls": [{
"Name": "sic"
}]
},
{
"Name": "statuscode",
"Value": null,
"Type": "optionset",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"InitialValue": 930650000,
"Options": [{
"text": "New",
"value": 1
},
{
"text": "Contacted",
"value": 2
},
{
"text": "Qualified",
"value": 3
},
{
"text": "Lost",
"value": 4
},
{
"text": "Cannot Contact",
"value": 5
},
{
"text": "No Longer Interested",
"value": 6
},
{
"text": "Canceled",
"value": 7
}],
"SelectedOption": {
"option": "New",
"value": 1
},
"Text": "New",
"Controls": [{
"Name": "statuscode"
}]
},
{
"Name": "subject",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 300,
"Controls": [{
"Name": "subject"
}]
},
{
"Name": "telephone1",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 50,
"Controls": [{
"Name": "telephone1"
}]
},
{
"Name": "telephone2",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 50,
"Controls": [{
"Name": "telephone2"
}]
},
{
"Name": "telephone3",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 50,
"Controls": [{
"Name": "telephone3"
}]
},
{
"Name": "transactioncurrencyid",
"Value": [{
"entityType": "Unknown",
"id": "{27ACAE0A-5D79-E111-BBD3-2657AEB3167B}",
"name": "Temp"
}],
"Type": "lookup",
"Format": null,
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"Controls": [{
"Name": "transactioncurrencyid"
}]
},
{
"Name": "websiteurl",
"Value": "",
"Type": "string",
"Format": "text",
"IsDirty": false,
"RequiredLevel": "none",
"SubmitMode": "dirty",
"UserPrivilege": {
"canRead": true,
"canUpdate": true,
"canCreate": true
},
"MaxLength": 200,
"Controls": [{
"Name": "websiteurl"
}]
}],
"AttributesLength": 40,
"Controls": [{
"Name": "address1_city",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "City",
"Attribute": "address1_city"
},
{
"Name": "address1_country",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Country/Region",
"Attribute": "address1_country"
},
{
"Name": "address1_line1",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Street 1",
"Attribute": "address1_line1"
},
{
"Name": "address1_line2",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Street 2",
"Attribute": "address1_line2"
},
{
"Name": "address1_line3",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Street 3",
"Attribute": "address1_line3"
},
{
"Name": "address1_postalcode",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "ZIP/Postal Code",
"Attribute": "address1_postalcode"
},
{
"Name": "address1_stateorprovince",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "State/Province",
"Attribute": "address1_stateorprovince"
},
{
"Name": "campaignid",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Source Campaign",
"Attribute": "campaignid"
},
{
"Name": "companyname",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Company Name",
"Attribute": "companyname"
},
{
"Name": "description",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Description",
"Attribute": "description"
},
{
"Name": "donotbulkemail",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Bulk Email",
"Attribute": "donotbulkemail"
},
{
"Name": "donotemail",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Email",
"Attribute": "donotemail"
},
{
"Name": "donotfax",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Fax",
"Attribute": "donotfax"
},
{
"Name": "donotphone",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Phone",
"Attribute": "donotphone"
},
{
"Name": "donotpostalmail",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Mail",
"Attribute": "donotpostalmail"
},
{
"Name": "donotsendmm",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Marketing Material",
"Attribute": "donotsendmm"
},
{
"Name": "emailaddress1",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Email",
"Attribute": "emailaddress1"
},
{
"Name": "fax",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Fax",
"Attribute": "fax"
},
{
"Name": "firstname",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "First Name",
"Attribute": "firstname"
},
{
"Name": "header_leadqualitycode",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Rating",
"Attribute": "leadqualitycode"
},
{
"Name": "header_leadsourcecode",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Lead Source",
"Attribute": "leadsourcecode"
},
{
"Name": "header_ownerid",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Owner",
"Attribute": "ownerid"
},
{
"Name": "industrycode",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Industry",
"Attribute": "industrycode"
},
{
"Name": "jobtitle",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Job Title",
"Attribute": "jobtitle"
},
{
"Name": "lastname",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Last Name",
"Attribute": "lastname"
},
{
"Name": "lastusedincampaign",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Last Campaign Date",
"Attribute": "lastusedincampaign"
},
{
"Name": "leadqualitycode",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Rating",
"Attribute": "leadqualitycode"
},
{
"Name": "leadsourcecode",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Lead Source",
"Attribute": "leadsourcecode"
},
{
"Name": "mobilephone",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Mobile Phone",
"Attribute": "mobilephone"
},
{
"Name": "numberofemployees",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "No. of Employees",
"Attribute": "numberofemployees"
},
{
"Name": "ownerid",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Owner",
"Attribute": "ownerid"
},
{
"Name": "pager",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Pager",
"Attribute": "pager"
},
{
"Name": "preferredcontactmethodcode",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Preferred",
"Attribute": "preferredcontactmethodcode"
},
{
"Name": "revenue",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Annual Revenue",
"Attribute": "revenue"
},
{
"Name": "salutation",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Salutation",
"Attribute": "salutation"
},
{
"Name": "sic",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "SIC Code",
"Attribute": "sic"
},
{
"Name": "statuscode",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Status Reason",
"Attribute": "statuscode"
},
{
"Name": "subject",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Topic",
"Attribute": "subject"
},
{
"Name": "telephone1",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Business Phone",
"Attribute": "telephone1"
},
{
"Name": "telephone2",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Home Phone",
"Attribute": "telephone2"
},
{
"Name": "telephone3",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Other Phone",
"Attribute": "telephone3"
},
{
"Name": "transactioncurrencyid",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Currency",
"Attribute": "transactioncurrencyid"
},
{
"Name": "websiteurl",
"Type": "standard",
"Disabled": false,
"Visible": true,
"Label": "Website",
"Attribute": "websiteurl"
}],
"ControlsLength": 43,
"Navigation": [{
"Id": "navActivities",
"Key": "navActivities",
"Label": "",
"Visible": true
},
{
"Id": "navActivityHistory",
"Key": "navActivityHistory",
"Label": "",
"Visible": true
}],
"Tabs": [{
"Label": "What's New",
"Name": "tab_recordwall",
"DisplayState": "expanded",
"Visible": true,
"Sections": [{
"Label": "Section",
"Name": "tab_recordwall_section_1",
"Visible": true,
"Controls": [{
"Name": "WebResource_RecordWall"
}]
}]
},
{
"Label": "General",
"Name": "general",
"DisplayState": "expanded",
"Visible": true,
"Sections": [{
"Label": "Name",
"Name": "name",
"Visible": true,
"Controls": [{
"Name": "subject"
},
{
"Name": "salutation"
},
{
"Name": "telephone1"
},
{
"Name": "firstname"
},
{
"Name": "telephone2"
},
{
"Name": "lastname"
},
{
"Name": "mobilephone"
},
{
"Name": "jobtitle"
},
{
"Name": "fax"
},
{
"Name": "companyname"
},
{
"Name": "telephone3"
},
{
"Name": "websiteurl"
},
{
"Name": "pager"
},
{
"Name": "emailaddress1"
}]
},
{
"Label": "Address",
"Name": "address",
"Visible": true,
"Controls": [{
"Name": "address1_line1"
},
{
"Name": "address1_stateorprovince"
},
{
"Name": "address1_line2"
},
{
"Name": "address1_postalcode"
},
{
"Name": "address1_line3"
},
{
"Name": "address1_country"
},
{
"Name": "address1_city"
}]
},
{
"Label": "Description",
"Name": "description",
"Visible": true,
"Controls": [{
"Name": "description"
}]
}]
},
{
"Label": "Details",
"Name": "details",
"DisplayState": "expanded",
"Visible": true,
"Sections": [{
"Label": "Lead Information",
"Name": "lead information",
"Visible": true,
"Controls": [{
"Name": "leadsourcecode"
},
{
"Name": "leadqualitycode"
}]
},
{
"Label": "Company Information",
"Name": "company information",
"Visible": true,
"Controls": [{
"Name": "industrycode"
},
{
"Name": "transactioncurrencyid"
},
{
"Name": "sic"
},
{
"Name": "revenue"
},
{
"Name": "numberofemployees"
}]
}]
},
{
"Label": "Notes & Activities",
"Name": "notes and activities",
"DisplayState": "expanded",
"Visible": true,
"Sections": [{
"Label": "Activities",
"Name": "activities",
"Visible": true,
"Controls": [{
"Name": "leadactivitiesgrid"
}]
},
{
"Label": "Notes",
"Name": "notes",
"Visible": true,
"Controls": [{
"Name": "notescontrol"
}]
}]
},
{
"Label": "Preferences",
"Name": "administration",
"DisplayState": "expanded",
"Visible": true,
"Sections": [{
"Label": "Internal Information",
"Name": "internal information",
"Visible": true,
"Controls": [{
"Name": "ownerid"
},
{
"Name": "statuscode"
}]
},
{
"Label": "Contact Methods",
"Name": "contact methods",
"Visible": true,
"Controls": [{
"Name": "preferredcontactmethodcode"
},
{
"Name": "donotemail"
},
{
"Name": "donotbulkemail"
},
{
"Name": "donotphone"
},
{
"Name": "donotfax"
},
{
"Name": "donotpostalmail"
}]
},
{
"Label": "Marketing Information",
"Name": "marketing information",
"Visible": true,
"Controls": [{
"Name": "campaignid"
},
{
"Name": "lastusedincampaign"
},
{
"Name": "donotsendmm"
}]
}]
}]
};
var Xrm = new _xrm(pageData); | mit |
darling0825/CustomControl | CustomControl/CustomView/BCCollectionView/BCCollectionView.h | 2944 | // Created by Pieter Omvlee on 24/11/2010.
// Copyright 2010 Bohemian Coding. All rights reserved.
#import <Cocoa/Cocoa.h>
#import "BCCollectionViewDelegate.h"
#ifndef BCArray
#define BCArray(args...) [NSArray arrayWithObjects:args, nil]
#endif
@class BCCollectionViewLayoutManager;
@interface BCCollectionView : NSView
{
IBOutlet id<BCCollectionViewDelegate> delegate;
BCCollectionViewLayoutManager *layoutManager;
NSArray *contentArray;
NSArray *groups;
NSMutableArray *reusableViewControllers;
NSMutableDictionary *visibleViewControllers;
NSMutableIndexSet *selectionIndexes;
NSMutableDictionary *visibleGroupViewControllers;
NSColor *backgroundColor;
NSUInteger numberOfPreRenderedRows;
@private
NSPoint mouseDownLocation;
NSPoint mouseDraggedLocation;
NSRect previousFrameBounds;
NSUInteger lastSelectionIndex;
NSIndexSet *originalSelectionIndexes;
NSInteger dragHoverIndex;
BOOL isDragging;
BOOL firstDrag;
BOOL selectionChangedDisabled;
NSString *zoomValueObserverKey;
CGFloat lastPinchMagnification;
NSString *accumulatedKeyStrokes;
}
@property (nonatomic, assign) id<BCCollectionViewDelegate> delegate;
@property (nonatomic, retain) NSColor *backgroundColor;
@property (nonatomic) NSUInteger numberOfPreRenderedRows;
//private
@property (nonatomic, copy) NSIndexSet *originalSelectionIndexes;
@property (nonatomic, copy) NSArray *contentArray, *groups;
@property (nonatomic, copy) NSString *zoomValueObserverKey, *accumulatedKeyStrokes;
@property (readonly) NSArray *visibleViewControllerArray;
@property (readonly) BCCollectionViewLayoutManager *layoutManager;
//designated way to load BCCollectionView
- (void)reloadDataWithItems:(NSArray *)newContent emptyCaches:(BOOL)shouldEmptyCaches;
- (void)reloadDataWithItems:(NSArray *)newContent groups:(NSArray *)newGroups emptyCaches:(BOOL)shouldEmptyCaches;
- (void)reloadDataWithItems:(NSArray *)newContent groups:(NSArray *)newGroups emptyCaches:(BOOL)shouldEmptyCaches completionBlock:(dispatch_block_t)completionBlock;
//Managing Selections
- (void)selectItemAtIndex:(NSUInteger)index;
- (void)selectItemAtIndex:(NSUInteger)index inBulk:(BOOL)bulk;
- (void)selectItemsAtIndexes:(NSIndexSet *)indexes;
- (void)deselectItemAtIndex:(NSUInteger)index;
- (void)deselectItemsAtIndexes:(NSIndexSet *)indexes;
- (void)deselectAllItems;
- (NSIndexSet *)selectionIndexes;
//Basic Cell Information
- (NSSize)cellSize;
- (NSUInteger)groupHeaderHeight;
- (NSRange)rangeOfVisibleItems;
- (NSRange)rangeOfVisibleItemsWithOverflow;
- (NSIndexSet *)indexesOfItemsInRect:(NSRect)aRect;
- (NSIndexSet *)indexesOfItemContentRectsInRect:(NSRect)aRect;
//Querying ViewControllers
- (NSIndexSet *)indexesOfViewControllers;
- (NSIndexSet *)indexesOfInvisibleViewControllers;
- (NSViewController *)viewControllerForItemAtIndex:(NSUInteger)index;
- (void)softReloadDataWithCompletionBlock:(dispatch_block_t)block;
@end
| mit |
PiotrDabkowski/pyjsparser | tests/pass/756e3fe0ef87b136.js | 104 | function a() {
b();
c();
return d();
}
function e() {
b();
c();
throw new f();
} | mit |
ekarulf/pymp | src/pymp/dispatcher.py | 11009 | import functools
import time
import traceback
from multiprocessing.util import Finalize
from threading import Event, RLock, Thread, current_thread
from pymp import logger, trace_function
from pymp.messages import DispatcherState, Request, Response, ProxyHandle, generate_id
from collections import deque
class State(object):
INIT, STARTUP, RUNNING, SHUTDOWN, TERMINATED = range(5)
class Dispatcher(object):
PREFIX = '#'
EXPOSED = '_dispatch_'
SPIN_TIME = 0.01
_dispatch_ = ['del_proxy', 'new_proxy']
@trace_function
def __init__(self, conn):
self._state = State.INIT
self._lock = RLock() # protects internal methods
self._queue = deque()
self._pending = dict() # id => Event or Response
self._provided_classes = dict() # string => (Class, callable)
self._consumed_classes = dict() # Class => Class
self._objects = dict()
self._thread = Thread(target=self._run, args=(conn,))
self._thread.daemon = True
self._thread.start()
# We register with multiprocessing to prevent bugs related to the
# order of execution of atexit functions & multiprocessing's join's
Finalize(self, self._atexit, exitpriority=100)
def get_state(self):
return self._state
def set_state(self, state):
with self._lock:
if state > self.state:
self._state = state
self._queue.append(DispatcherState(state)) # head of line
logger.info("Changing state to %d" % state)
elif state == self.state:
pass
else:
raise ValueError('Invalid state progression')
state = property(get_state, set_state)
@trace_function
def _atexit(self):
self.shutdown()
@trace_function
def __del__(self):
if self.alive():
self.shutdown()
self._thread.join()
self._objects.clear()
@trace_function
def provide(self, proxy_class, generator=None, name=None):
"""
Registers a class that will be provided by this dispatcher
If present, a generator will be used in lieu of using a the provided
class's default constructor.
"""
if not name:
name = proxy_class.__name__
with self._lock:
if name in self._provided_classes:
raise NameError("The name '%s' is already in use" % name)
self._provided_classes[name] = (proxy_class, generator)
@trace_function
def consume(self, name, proxy_client=None):
if hasattr(name, '__name__'):
name = name.__name__
with self._lock:
if hasattr(self, name):
raise NameError("The name '%s' is already in use" % name)
self._consumed_classes[name] = proxy_client or Proxy
def create_instance(*args, **kwargs):
new_proxy_args = (name, args, kwargs)
return self.call('#new_proxy', new_proxy_args)
setattr(self, name, create_instance)
def alive(self):
return self.state in (State.STARTUP, State.RUNNING, State.SHUTDOWN)
@trace_function
def call(self, function, args=[], kwargs={}, proxy_id=None, wait=True):
# Step 1: Send Request
request = Request(generate_id(), proxy_id, function, args, kwargs)
if wait:
event = Event()
with self._lock:
self._pending[request.id] = event
self._queue.appendleft(request)
# Step 2: Wait for Response
if wait:
event.wait()
else:
return
# Step 3: Process Response
with self._lock:
response = self._pending.pop(request.id, None)
if not isinstance(response, Response):
raise RuntimeError('Dispatcher stored invalid response')
elif response.exception:
raise response.exception
elif isinstance(response.return_value, ProxyHandle):
proxy_handle = response.return_value
try:
proxy_class = self._consumed_classes[proxy_handle.obj_type]
except KeyError:
logger.info("Recieved proxy_class for unexpected type %s" % proxy_handle.obj_type)
else:
return proxy_class(self, proxy_handle.id, proxy_handle.exposed)
else:
return response.return_value
@trace_function
def start(self):
if self.state is State.INIT:
self.state = State.STARTUP
if self.state is State.STARTUP:
while self.state is State.STARTUP:
time.sleep(self.SPIN_TIME)
@trace_function
def shutdown(self):
if self.state in (State.INIT, State.STARTUP, State.RUNNING):
self.state = State.SHUTDOWN
@trace_function
def _run(self, conn):
while self.state is State.INIT:
time.sleep(self.SPIN_TIME) # wait for the constructor to catch up
while self.state in (State.STARTUP, State.RUNNING):
self._write_once(conn)
self._read_once(conn, timeout=self.SPIN_TIME)
while len(self._queue) > 0:
self._write_once(conn) # send shutdown message if needed
self.state = State.TERMINATED
conn.close()
@trace_function
def join(self):
self._thread.join()
@trace_function
def new_proxy(self, name, args, kwargs):
with self._lock:
if name not in self._provided_classes:
raise NameError("%s does not name a provided class" % name)
source_class, generator = self._provided_classes[name]
if not generator:
generator = source_class
obj = generator(*args, **kwargs)
obj_id = id(obj)
obj_store, refcount = self._objects.get(obj_id, (obj, 0))
assert obj is obj_store, "Different objects returned for the same key"
self._objects[obj_id] = (obj, refcount + 1)
exposed = self._exposed_functions(obj)
return ProxyHandle(obj_id, name, exposed)
@trace_function
def del_proxy(self, proxy_id):
"""
Called by clients to signify when they no longer need a proxy
See: DefaultProxy.__del__
"""
with self._lock:
obj, refcount = self._objects.get(proxy_id, (None, 0))
if refcount <= 0:
logger.warn("Error destructing object %s, not found" % str(proxy_id))
elif refcount == 1:
del self._objects[proxy_id]
else:
self._objects[proxy_id] = (obj, refcount - 1)
def _write_once(self, conn):
if not self.alive():
return
try:
msg = self._queue.pop()
except IndexError:
return
try:
if isinstance(msg, DispatcherState) or self.state is State.RUNNING:
conn.send(msg)
else:
logger.info("Skipping outgoing message %s" % repr(msg))
except IOError:
self.state = State.TERMINATED
except Exception as exception:
# Most likely a PicklingError
if hasattr(msg, 'id'):
response = Response(msg.id, exception, None)
self._process_response(response)
def _read_once(self, conn, timeout=0):
if not self.alive() or not conn.poll(timeout):
return
try:
msg = conn.recv()
except EOFError:
self.state = State.TERMINATED
if isinstance(msg, Request) and self.state is State.RUNNING:
response = self._process_request(msg)
if response:
self._queue.appendleft(response)
elif isinstance(msg, Response) and self.state is State.RUNNING:
self._process_response(msg)
elif isinstance(msg, DispatcherState):
if self.state is State.STARTUP and msg.state is State.STARTUP:
self.state = State.RUNNING
elif msg.state is State.SHUTDOWN:
self.state = msg.state
else:
logger.info("Skipping incoming message %s" % repr(msg))
return True
@trace_function
def _exposed_functions(self, obj):
exposed = getattr(obj, self.EXPOSED, None)
if exposed is None:
exposed = []
for name in dir(obj): # TODO: Not use dir
attribute = getattr(obj, name)
if callable(attribute) and not name.startswith('_'):
exposed.append(name)
setattr(obj, self.EXPOSED, exposed)
return exposed
@trace_function
def _callmethod(self, obj, fname, args, kwargs):
if fname in self._exposed_functions(obj):
function = getattr(obj, fname)
return function(*args, **kwargs)
else:
raise AttributeError("%s does not have an exposed method %s" % (repr(obj), fname))
@trace_function
def _process_request(self, request):
exception = None
fname = request.function
if fname.startswith(self.PREFIX):
obj = self # invoke methods on dispatcher
fname = fname[1:] # strip prefix
else:
with self._lock:
try:
obj, refcount = self._objects[request.proxy_id]
except KeyError:
exception = RuntimeError("No object found")
return Response(request.id, exception, None)
try:
value = self._callmethod(obj, fname, request.args, request.kwargs)
except Exception as exception:
logger.error("Exception thrown while processing response\nRemote " + traceback.format_exc())
return Response(request.id, exception, None)
else:
return Response(request.id, None, value)
@trace_function
def _process_response(self, response):
with self._lock:
event = self._pending.pop(response.id, None)
if hasattr(event, 'set'):
self._pending[response.id] = response
event.set()
class Proxy(object):
@trace_function
def __init__(self, dispatcher, proxy_id, exposed):
self._dispatcher = dispatcher
self._proxy_id = proxy_id
self._exposed = exposed
for name in exposed:
func = functools.partial(self._callmethod, name)
func.__name__ = name
setattr(self, name, func)
@trace_function
def _callmethod(self, name, *args, **kwargs):
return self._dispatcher.call(name, args, kwargs, proxy_id=self._proxy_id)
@trace_function
def __del__(self):
self._dispatcher.call('#del_proxy', (self._proxy_id,), wait=False)
| mit |
nusedutech/coursemology.org | app/assets/javascripts/textext/textext.core.js | 44768 | /**
* jQuery TextExt Plugin
* http://textextjs.com
*
* @version 1.3.1
* @copyright Copyright (C) 2011 Alex Gorbatchev. All rights reserved.
* @license MIT License
*/
(function($, undefined)
{
/**
* TextExt is the main core class which by itself doesn't provide any functionality
* that is user facing, however it has the underlying mechanics to bring all the
* plugins together under one roof and make them work with each other or on their
* own.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt
*/
function TextExt() {};
/**
* ItemManager is used to seamlessly convert between string that come from the user input to whatever
* the format the item data is being passed around in. It's used by all plugins that in one way or
* another operate with items, such as Tags, Filter, Autocomplete and Suggestions. Default implementation
* works with `String` type.
*
* Each instance of `TextExt` creates a new instance of default implementation of `ItemManager`
* unless `itemManager` option was set to another implementation.
*
* To satisfy requirements of managing items of type other than a `String`, different implementation
* if `ItemManager` should be supplied.
*
* If you wish to bring your own implementation, you need to create a new class and implement all the
* methods that `ItemManager` has. After, you need to supply your pass via the `itemManager` option during
* initialization like so:
*
* $('#input').textext({
* itemManager : CustomItemManager
* })
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager
*/
function ItemManager() {};
/**
* TextExtPlugin is a base class for all plugins. It provides common methods which are reused
* by majority of plugins.
*
* All plugins must register themselves by calling the `$.fn.textext.addPlugin(name, constructor)`
* function while providing plugin name and constructor. The plugin name is the same name that user
* will identify the plugin in the `plugins` option when initializing TextExt component and constructor
* function will create a new instance of the plugin. *Without registering, the core won't
* be able to see the plugin.*
*
* <span class="new label version">new in 1.2.0</span> You can get instance of each plugin from the core
* via associated function with the same name as the plugin. For example:
*
* $('#input').textext()[0].tags()
* $('#input').textext()[0].autocomplete()
* ...
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin
*/
function TextExtPlugin() {};
var stringify = (JSON || {}).stringify,
slice = Array.prototype.slice,
p,
UNDEFINED = 'undefined',
/**
* TextExt provides a way to pass in the options to configure the core as well as
* each plugin that is being currently used. The jQuery exposed plugin `$().textext()`
* function takes a hash object with key/value set of options. For example:
*
* $('textarea').textext({
* enabled: true
* })
*
* There are multiple ways of passing in the options:
*
* 1. Options could be nested multiple levels deep and accessed using all lowercased, dot
* separated style, eg `foo.bar.world`. The manual is using this style for clarity and
* consistency. For example:
*
* {
* item: {
* manager: ...
* },
*
* html: {
* wrap: ...
* },
*
* autocomplete: {
* enabled: ...,
* dropdown: {
* position: ...
* }
* }
* }
*
* 2. Options could be specified using camel cased names in a flat key/value fashion like so:
*
* {
* itemManager: ...,
* htmlWrap: ...,
* autocompleteEnabled: ...,
* autocompleteDropdownPosition: ...
* }
*
* 3. Finally, options could be specified in mixed style. It's important to understand that
* for each dot separated name, its alternative in camel case is also checked for, eg for
* `foo.bar.world` it's alternatives could be `fooBarWorld`, `foo.barWorld` or `fooBar.world`,
* which translates to `{ foo: { bar: { world: ... } } }`, `{ fooBarWorld: ... }`,
* `{ foo : { barWorld : ... } }` or `{ fooBar: { world: ... } }` respectively. For example:
*
* {
* itemManager : ...,
* htmlWrap: ...,
* autocomplete: {
* enabled: ...,
* dropdownPosition: ...
* }
* }
*
* Mixed case is used through out the code, wherever it seems appropriate. However in the code, all option
* names are specified in the dot notation because it works both ways where as camel case is not
* being converted to its alternative dot notation.
*
* @author agorbatchev
* @date 2011/08/17
* @id TextExt.options
*/
/**
* Default instance of `ItemManager` which takes `String` type as default for tags.
*
* @name item.manager
* @default ItemManager
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.options.item.manager
*/
OPT_ITEM_MANAGER = 'item.manager',
/**
* List of plugins that should be used with the current instance of TextExt. The list could be
* specified as array of strings or as comma or space separated string.
*
* @name plugins
* @default []
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.options.plugins
*/
OPT_PLUGINS = 'plugins',
/**
* TextExt allows for overriding of virtually any method that the core or any of its plugins
* use. This could be accomplished through the use of the `ext` option.
*
* It's possible to specifically target the core or any plugin, as well as overwrite all the
* desired methods everywhere.
*
* 1. Targeting the core:
*
* ext: {
* core: {
* trigger: function()
* {
* console.log('TextExt.trigger', arguments);
* $.fn.textext.TextExt.prototype.trigger.apply(this, arguments);
* }
* }
* }
*
* 2. Targeting individual plugins:
*
* ext: {
* tags: {
* addTags: function(tags)
* {
* console.log('TextExtTags.addTags', tags);
* $.fn.textext.TextExtTags.prototype.addTags.apply(this, arguments);
* }
* }
* }
*
* 3. Targeting `ItemManager` instance:
*
* ext: {
* itemManager: {
* stringToItem: function(str)
* {
* console.log('ItemManager.stringToItem', str);
* return $.fn.textext.ItemManager.prototype.stringToItem.apply(this, arguments);
* }
* }
* }
*
* 4. And finally, in edge cases you can extend everything at once:
*
* ext: {
* '*': {
* fooBar: function() {}
* }
* }
*
* @name ext
* @default {}
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.options.ext
*/
OPT_EXT = 'ext',
/**
* HTML source that is used to generate elements necessary for the core and all other
* plugins to function.
*
* @name html.wrap
* @default '<div class="text-core"><div class="text-wrap"/></div>'
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.options.html.wrap
*/
OPT_HTML_WRAP = 'html.wrap',
/**
* HTML source that is used to generate hidden input value of which will be submitted
* with the HTML form.
*
* @name html.hidden
* @default '<input type="hidden" />'
* @author agorbatchev
* @date 2011/08/20
* @id TextExt.options.html.hidden
*/
OPT_HTML_HIDDEN = 'html.hidden',
/**
* Hash table of key codes and key names for which special events will be created
* by the core. For each entry a `[name]KeyDown`, `[name]KeyUp` and `[name]KeyPress` events
* will be triggered along side with `anyKeyUp` and `anyKeyDown` events for every
* key stroke.
*
* Here's a list of default keys:
*
* {
* 8 : 'backspace',
* 9 : 'tab',
* 13 : 'enter!',
* 27 : 'escape!',
* 37 : 'left',
* 38 : 'up!',
* 39 : 'right',
* 40 : 'down!',
* 46 : 'delete',
* 108 : 'numpadEnter'
* }
*
* Please note the `!` at the end of some keys. This tells the core that by default
* this keypress will be trapped and not passed on to the text input.
*
* @name keys
* @default { ... }
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.options.keys
*/
OPT_KEYS = 'keys',
/**
* The core triggers or reacts to the following events.
*
* @author agorbatchev
* @date 2011/08/17
* @id TextExt.events
*/
/**
* Core triggers `preInvalidate` event before the dimensions of padding on the text input
* are set.
*
* @name preInvalidate
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.preInvalidate
*/
EVENT_PRE_INVALIDATE = 'preInvalidate',
/**
* Core triggers `postInvalidate` event after the dimensions of padding on the text input
* are set.
*
* @name postInvalidate
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.postInvalidate
*/
EVENT_POST_INVALIDATE = 'postInvalidate',
/**
* Core triggers `getFormData` on every key press to collect data that will be populated
* into the hidden input that will be submitted with the HTML form and data that will
* be displayed in the input field that user is currently interacting with.
*
* All plugins that wish to affect how the data is presented or sent must react to
* `getFormData` and populate the data in the following format:
*
* {
* input : {String},
* form : {Object}
* }
*
* The data key must be a numeric weight which will be used to determine which data
* ends up being used. Data with the highest numerical weight gets the priority. This
* allows plugins to set the final data regardless of their initialization order, which
* otherwise would be impossible.
*
* For example, the Tags and Autocomplete plugins have to work side by side and Tags
* plugin must get priority on setting the data. Therefore the Tags plugin sets data
* with the weight 200 where as the Autocomplete plugin sets data with the weight 100.
*
* Here's an example of a typical `getFormData` handler:
*
* TextExtPlugin.prototype.onGetFormData = function(e, data, keyCode)
* {
* data[100] = self.formDataObject('input value', 'form value');
* };
*
* Core also reacts to the `getFormData` and updates hidden input with data which will be
* submitted with the HTML form.
*
* @name getFormData
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.getFormData
*/
EVENT_GET_FORM_DATA = 'getFormData',
/**
* Core triggers and reacts to the `setFormData` event to update the actual value in the
* hidden input that will be submitted with the HTML form. Second argument can be value
* of any type and by default it will be JSON serialized with `TextExt.serializeData()`
* function.
*
* @name setFormData
* @author agorbatchev
* @date 2011/08/22
* @id TextExt.events.setFormData
*/
EVENT_SET_FORM_DATA = 'setFormData',
/**
* Core triggers and reacts to the `setInputData` event to update the actual value in the
* text input that user is interacting with. Second argument must be of a `String` type
* the value of which will be set into the text input.
*
* @name setInputData
* @author agorbatchev
* @date 2011/08/22
* @id TextExt.events.setInputData
*/
EVENT_SET_INPUT_DATA = 'setInputData',
/**
* Core triggers `postInit` event to let plugins run code after all plugins have been
* created and initialized. This is a good place to set some kind of global values before
* somebody gets to use them. This is not the right place to expect all plugins to finish
* their initialization.
*
* @name postInit
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.postInit
*/
EVENT_POST_INIT = 'postInit',
/**
* Core triggers `ready` event after all global configuration and prepearation has been
* done and the TextExt component is ready for use. Event handlers should expect all
* values to be set and the plugins to be in the final state.
*
* @name ready
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.ready
*/
EVENT_READY = 'ready',
/**
* Core triggers `anyKeyUp` event for every key up event triggered within the component.
*
* @name anyKeyUp
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.anyKeyUp
*/
/**
* Core triggers `anyKeyDown` event for every key down event triggered within the component.
*
* @name anyKeyDown
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.anyKeyDown
*/
/**
* Core triggers `[name]KeyUp` event for every key specifid in the `keys` option that is
* triggered within the component.
*
* @name [name]KeyUp
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.[name]KeyUp
*/
/**
* Core triggers `[name]KeyDown` event for every key specified in the `keys` option that is
* triggered within the component.
*
* @name [name]KeyDown
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.[name]KeyDown
*/
/**
* Core triggers `[name]KeyPress` event for every key specified in the `keys` option that is
* triggered within the component.
*
* @name [name]KeyPress
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.events.[name]KeyPress
*/
DEFAULT_OPTS = {
itemManager : ItemManager,
plugins : [],
ext : {},
html : {
wrap : '<div class="text-core"><div class="text-wrap"/></div>',
hidden : '<input type="hidden" />'
},
keys : {
8 : 'backspace',
9 : 'tab',
13 : 'enter!',
27 : 'escape!',
37 : 'left',
38 : 'up!',
39 : 'right',
40 : 'down!',
46 : 'delete',
108 : 'numpadEnter'
}
}
;
// Freak out if there's no JSON.stringify function found
if(!stringify)
throw new Error('JSON.stringify() not found');
/**
* Returns object property by name where name is dot-separated and object is multiple levels deep.
* @param target Object Source object.
* @param name String Dot separated property name, ie `foo.bar.world`
* @id core.getProperty
*/
function getProperty(source, name)
{
if(typeof(name) === 'string')
name = name.split('.');
var fullCamelCaseName = name.join('.').replace(/\.(\w)/g, function(match, letter) { return letter.toUpperCase() }),
nestedName = name.shift(),
result
;
if(typeof(result = source[fullCamelCaseName]) != UNDEFINED)
result = result;
else if(typeof(result = source[nestedName]) != UNDEFINED && name.length > 0)
result = getProperty(result, name);
// name.length here should be zero
return result;
};
/**
* Hooks up specified events in the scope of the current object.
* @author agorbatchev
* @date 2011/08/09
*/
function hookupEvents()
{
var args = slice.apply(arguments),
self = this,
target = args.length === 1 ? self : args.shift(),
event
;
args = args[0] || {};
function bind(event, handler)
{
target.bind(event, function()
{
// apply handler to our PLUGIN object, not the target
return handler.apply(self, arguments);
});
}
for(event in args)
bind(event, args[event]);
};
function formDataObject(input, form)
{
return { 'input' : input, 'form' : form };
};
//--------------------------------------------------------------------------------
// ItemManager core component
p = ItemManager.prototype;
/**
* Initialization method called by the core during instantiation.
*
* @signature ItemManager.init(core)
*
* @param core {TextExt} Instance of the TextExt core class.
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager.init
*/
p.init = function(core)
{
};
/**
* Filters out items from the list that don't match the query and returns remaining items. Default
* implementation checks if the item starts with the query.
*
* @signature ItemManager.filter(list, query)
*
* @param list {Array} List of items. Default implementation works with strings.
* @param query {String} Query string.
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager.filter
*/
p.filter = function(list, query)
{
var result = [],
i, item
;
for(i = 0; i < list.length; i++)
{
item = list[i];
if(this.itemContains(item, query))
result.push(item);
}
return result;
};
/**
* Returns `true` if specified item contains another string, `false` otherwise. In the default implementation
* `String.indexOf()` is used to check if item string begins with the needle string.
*
* @signature ItemManager.itemContains(item, needle)
*
* @param item {Object} Item to check. Default implementation works with strings.
* @param needle {String} Search string to be found within the item.
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager.itemContains
*/
p.itemContains = function(item, needle)
{
return this.itemToString(item).toLowerCase().indexOf(needle.toLowerCase()) == 0;
};
/**
* Converts specified string to item. Because default implemenation works with string, input string
* is simply returned back. To use custom objects, different implementation of this method could
* return something like `{ name : {String} }`.
*
* @signature ItemManager.stringToItem(str)
*
* @param str {String} Input string.
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager.stringToItem
*/
p.stringToItem = function(str)
{
return str;
};
/**
* Converts specified item to string. Because default implemenation works with string, input string
* is simply returned back. To use custom objects, different implementation of this method could
* for example return `name` field of `{ name : {String} }`.
*
* @signature ItemManager.itemToString(item)
*
* @param item {Object} Input item to be converted to string.
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager.itemToString
*/
p.itemToString = function(item)
{
return item;
};
/**
* Returns `true` if both items are equal, `false` otherwise. Because default implemenation works with
* string, input items are compared as strings. To use custom objects, different implementation of this
* method could for example compare `name` fields of `{ name : {String} }` type object.
*
* @signature ItemManager.compareItems(item1, item2)
*
* @param item1 {Object} First item.
* @param item2 {Object} Second item.
*
* @author agorbatchev
* @date 2011/08/19
* @id ItemManager.compareItems
*/
p.compareItems = function(item1, item2)
{
return item1 == item2;
};
//--------------------------------------------------------------------------------
// TextExt core component
p = TextExt.prototype;
/**
* Initializes current component instance with work with the supplied text input and options.
*
* @signature TextExt.init(input, opts)
*
* @param input {HTMLElement} Text input.
* @param opts {Object} Options.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.init
*/
p.init = function(input, opts)
{
var self = this,
hiddenInput,
itemManager,
container
;
self._defaults = $.extend({}, DEFAULT_OPTS);
self._opts = opts || {};
self._plugins = {};
self._itemManager = itemManager = new (self.opts(OPT_ITEM_MANAGER))();
input = $(input);
container = $(self.opts(OPT_HTML_WRAP));
hiddenInput = $(self.opts(OPT_HTML_HIDDEN));
input
.wrap(container)
.keydown(function(e) { return self.onKeyDown(e) })
.keyup(function(e) { return self.onKeyUp(e) })
.data('textext', self)
;
// keep references to html elements using jQuery.data() to avoid circular references
$(self).data({
'hiddenInput' : hiddenInput,
'wrapElement' : input.parents('.text-wrap').first(),
'input' : input
});
// set the name of the hidden input to the text input's name
hiddenInput.attr('name', input.attr('name'));
// remove name attribute from the text input
input.attr('name', null);
// add hidden input to the DOM
hiddenInput.insertAfter(input);
$.extend(true, itemManager, self.opts(OPT_EXT + '.item.manager'));
$.extend(true, self, self.opts(OPT_EXT + '.*'), self.opts(OPT_EXT + '.core'));
self.originalWidth = input.outerWidth();
self.invalidateBounds();
itemManager.init(self);
self.initPatches();
self.initPlugins(self.opts(OPT_PLUGINS), $.fn.textext.plugins);
self.on({
setFormData : self.onSetFormData,
getFormData : self.onGetFormData,
setInputData : self.onSetInputData,
anyKeyUp : self.onAnyKeyUp
});
self.trigger(EVENT_POST_INIT);
self.trigger(EVENT_READY);
self.getFormData(0);
};
/**
* Initialized all installed patches against current instance. The patches are initialized based on their
* initialization priority which is returned by each patch's `initPriority()` method. Priority
* is a `Number` where patches with higher value gets their `init()` method called before patches
* with lower priority value.
*
* This facilitates initializing of patches in certain order to insure proper dependencies
* regardless of which order they are loaded.
*
* By default all patches have the same priority - zero, which means they will be initialized
* in rorder they are loaded, that is unless `initPriority()` is overriden.
*
* @signature TextExt.initPatches()
*
* @author agorbatchev
* @date 2011/10/11
* @id TextExt.initPatches
*/
p.initPatches = function()
{
var list = [],
source = $.fn.textext.patches,
name
;
for(name in source)
list.push(name);
this.initPlugins(list, source);
};
/**
* Creates and initializes all specified plugins. The plugins are initialized based on their
* initialization priority which is returned by each plugin's `initPriority()` method. Priority
* is a `Number` where plugins with higher value gets their `init()` method called before plugins
* with lower priority value.
*
* This facilitates initializing of plugins in certain order to insure proper dependencies
* regardless of which order user enters them in the `plugins` option field.
*
* By default all plugins have the same priority - zero, which means they will be initialized
* in the same order as entered by the user.
*
* @signature TextExt.initPlugins(plugins)
*
* @param plugins {Array} List of plugin names to initialize.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.initPlugins
*/
p.initPlugins = function(plugins, source)
{
var self = this,
ext, name, plugin, initList = [], i
;
if(typeof(plugins) == 'string')
plugins = plugins.split(/\s*,\s*|\s+/g);
for(i = 0; i < plugins.length; i++)
{
name = plugins[i];
plugin = source[name];
if(plugin)
{
self._plugins[name] = plugin = new plugin();
self[name] = (function(plugin) {
return function(){ return plugin; }
})(plugin);
initList.push(plugin);
$.extend(true, plugin, self.opts(OPT_EXT + '.*'), self.opts(OPT_EXT + '.' + name));
}
}
// sort plugins based on their priority values
initList.sort(function(p1, p2)
{
p1 = p1.initPriority();
p2 = p2.initPriority();
return p1 === p2
? 0
: p1 < p2 ? 1 : -1
;
});
for(i = 0; i < initList.length; i++)
initList[i].init(self);
};
/**
* Returns true if specified plugin is was instantiated for the current instance of core.
*
* @signature TextExt.hasPlugin(name)
*
* @param name {String} Name of the plugin to check.
*
* @author agorbatchev
* @date 2011/12/28
* @id TextExt.hasPlugin
* @version 1.1
*/
p.hasPlugin = function(name)
{
return !!this._plugins[name];
};
/**
* Allows to add multiple event handlers which will be execued in the scope of the current object.
*
* @signature TextExt.on([target], handlers)
*
* @param target {Object} **Optional**. Target object which has traditional `bind(event, handler)` method.
* Handler function will still be executed in the current object's scope.
* @param handlers {Object} Key/value pairs of event names and handlers, eg `{ event: handler }`.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.on
*/
p.on = hookupEvents;
/**
* Binds an event handler to the input box that user interacts with.
*
* @signature TextExt.bind(event, handler)
*
* @param event {String} Event name.
* @param handler {Function} Event handler.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.bind
*/
p.bind = function(event, handler)
{
this.input().bind(event, handler);
};
/**
* Triggers an event on the input box that user interacts with. All core events are originated here.
*
* @signature TextExt.trigger(event, ...args)
*
* @param event {String} Name of the event to trigger.
* @param ...args All remaining arguments will be passed to the event handler.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.trigger
*/
p.trigger = function()
{
var args = arguments;
this.input().trigger(args[0], slice.call(args, 1));
};
/**
* Returns instance of `itemManager` that is used by the component.
*
* @signature TextExt.itemManager()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.itemManager
*/
p.itemManager = function()
{
return this._itemManager;
};
/**
* Returns jQuery input element with which user is interacting with.
*
* @signature TextExt.input()
*
* @author agorbatchev
* @date 2011/08/10
* @id TextExt.input
*/
p.input = function()
{
return $(this).data('input');
};
/**
* Returns option value for the specified option by name. If the value isn't found in the user
* provided options, it will try looking for default value.
*
* @signature TextExt.opts(name)
*
* @param name {String} Option name as described in the options.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.opts
*/
p.opts = function(name)
{
var result = getProperty(this._opts, name);
return typeof(result) == 'undefined' ? getProperty(this._defaults, name) : result;
};
/**
* Returns HTML element that was created from the `html.wrap` option. This is the top level HTML
* container for the text input with which user is interacting with.
*
* @signature TextExt.wrapElement()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.wrapElement
*/
p.wrapElement = function()
{
return $(this).data('wrapElement');
};
/**
* Updates container to match dimensions of the text input. Triggers `preInvalidate` and `postInvalidate`
* events.
*
* @signature TextExt.invalidateBounds()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.invalidateBounds
*/
p.invalidateBounds = function()
{
var self = this,
input = self.input(),
wrap = self.wrapElement(),
container = wrap.parent(),
width = '100%',
height = '30px'
;
self.trigger(EVENT_PRE_INVALIDATE);
height = '30px';
// using css() method instead of width() and height() here because they don't seem to do the right thing in jQuery 1.8.x
// https://github.com/alexgorbatchev/jquery-textext/issues/74
input.css({ 'width' : width });
wrap.css({ 'width' : width, 'height' : height });
container.css({ 'height' : height });
self.trigger(EVENT_POST_INVALIDATE);
};
/**
* Focuses user input on the text box.
*
* @signature TextExt.focusInput()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.focusInput
*/
p.focusInput = function()
{
this.input()[0].focus();
};
/**
* Serializes data for to be set into the hidden input field and which will be submitted
* with the HTML form.
*
* By default simple JSON serialization is used. It's expected that `JSON.stringify`
* method would be available either through built in class in most modern browsers
* or through JSON2 library.
*
* @signature TextExt.serializeData(data)
*
* @param data {Object} Data to serialize.
*
* @author agorbatchev
* @date 2011/08/09
* @id TextExt.serializeData
*/
p.serializeData = stringify;
/**
* Returns the hidden input HTML element which will be submitted with the HTML form.
*
* @signature TextExt.hiddenInput()
*
* @author agorbatchev
* @date 2011/08/09
* @id TextExt.hiddenInput
*/
p.hiddenInput = function(value)
{
return $(this).data('hiddenInput');
};
/**
* Abstracted functionality to trigger an event and get the data with maximum weight set by all
* the event handlers. This functionality is used for the `getFormData` event.
*
* @signature TextExt.getWeightedEventResponse(event, args)
*
* @param event {String} Event name.
* @param args {Object} Argument to be passed with the event.
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExt.getWeightedEventResponse
*/
p.getWeightedEventResponse = function(event, args)
{
var self = this,
data = {},
maxWeight = 0
;
self.trigger(event, data, args);
for(var weight in data)
maxWeight = Math.max(maxWeight, weight);
return data[maxWeight];
};
/**
* Triggers the `getFormData` event to get all the plugins to return their data.
*
* After the data is returned, triggers `setFormData` and `setInputData` to update appopriate values.
*
* @signature TextExt.getFormData(keyCode)
*
* @param keyCode {Number} Key code number which has triggered this update. It's impotant to pass
* this value to the plugins because they might return different values based on the key that was
* pressed. For example, the Tags plugin returns an empty string for the `input` value if the enter
* key was pressed, otherwise it returns whatever is currently in the text input.
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExt.getFormData
*/
p.getFormData = function(keyCode)
{
var self = this,
data = self.getWeightedEventResponse(EVENT_GET_FORM_DATA, keyCode || 0)
;
self.trigger(EVENT_SET_FORM_DATA , data['form']);
self.trigger(EVENT_SET_INPUT_DATA , data['input']);
};
//--------------------------------------------------------------------------------
// Event handlers
/**
* Reacts to the `anyKeyUp` event and triggers the `getFormData` to change data that will be submitted
* with the form. Default behaviour is that everything that is typed in will be JSON serialized, so
* the end result will be a JSON string.
*
* @signature TextExt.onAnyKeyUp(e)
*
* @param e {Object} jQuery event.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.onAnyKeyUp
*/
p.onAnyKeyUp = function(e, keyCode)
{
this.getFormData(keyCode);
};
/**
* Reacts to the `setInputData` event and populates the input text field that user is currently
* interacting with.
*
* @signature TextExt.onSetInputData(e, data)
*
* @param e {Event} jQuery event.
* @param data {String} Value to be set.
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExt.onSetInputData
*/
p.onSetInputData = function(e, data)
{
this.input().val(data);
};
/**
* Reacts to the `setFormData` event and populates the hidden input with will be submitted with
* the HTML form. The value will be serialized with `serializeData()` method.
*
* @signature TextExt.onSetFormData(e, data)
*
* @param e {Event} jQuery event.
* @param data {Object} Data that will be set.
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExt.onSetFormData
*/
p.onSetFormData = function(e, data)
{
var self = this;
self.hiddenInput().val(self.serializeData(data));
};
/**
* Reacts to `getFormData` event triggered by the core. At the bare minimum the core will tell
* itself to use the current value in the text input as the data to be submitted with the HTML
* form.
*
* @signature TextExt.onGetFormData(e, data)
*
* @param e {Event} jQuery event.
*
* @author agorbatchev
* @date 2011/08/09
* @id TextExt.onGetFormData
*/
p.onGetFormData = function(e, data)
{
var val = this.input().val();
data[0] = formDataObject(val, val);
};
//--------------------------------------------------------------------------------
// User mouse/keyboard input
/**
* Triggers `[name]KeyUp` and `[name]KeyPress` for every keystroke as described in the events.
*
* @signature TextExt.onKeyUp(e)
*
* @param e {Object} jQuery event.
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.onKeyUp
*/
/**
* Triggers `[name]KeyDown` for every keystroke as described in the events.
*
* @signature TextExt.onKeyDown(e)
*
* @param e {Object} jQuery event.
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.onKeyDown
*/
$(['Down', 'Up']).each(function()
{
var type = this.toString();
p['onKey' + type] = function(e)
{
var self = this,
keyName = self.opts(OPT_KEYS)[e.keyCode],
defaultResult = true
;
if(keyName)
{
defaultResult = keyName.substr(-1) != '!';
keyName = keyName.replace('!', '');
self.trigger(keyName + 'Key' + type);
// manual *KeyPress event fimplementation for the function keys like Enter, Backspace, etc.
if(type == 'Up' && self._lastKeyDown == e.keyCode)
{
self._lastKeyDown = null;
self.trigger(keyName + 'KeyPress');
}
if(type == 'Down')
self._lastKeyDown = e.keyCode;
}
self.trigger('anyKey' + type, e.keyCode);
return defaultResult;
};
});
//--------------------------------------------------------------------------------
// Plugin Base
p = TextExtPlugin.prototype;
/**
* Allows to add multiple event handlers which will be execued in the scope of the current object.
*
* @signature TextExt.on([target], handlers)
*
* @param target {Object} **Optional**. Target object which has traditional `bind(event, handler)` method.
* Handler function will still be executed in the current object's scope.
* @param handlers {Object} Key/value pairs of event names and handlers, eg `{ event: handler }`.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.on
*/
p.on = hookupEvents;
/**
* Returns the hash object that `getFormData` triggered by the core expects.
*
* @signature TextExtPlugin.formDataObject(input, form)
*
* @param input {String} Value that will go into the text input that user is interacting with.
* @param form {Object} Value that will be serialized and put into the hidden that will be submitted
* with the HTML form.
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExtPlugin.formDataObject
*/
p.formDataObject = formDataObject;
/**
* Initialization method called by the core during plugin instantiation. This method must be implemented
* by each plugin individually.
*
* @signature TextExtPlugin.init(core)
*
* @param core {TextExt} Instance of the TextExt core class.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.init
*/
p.init = function(core) { throw new Error('Not implemented') };
/**
* Initialization method wich should be called by the plugin during the `init()` call.
*
* @signature TextExtPlugin.baseInit(core, defaults)
*
* @param core {TextExt} Instance of the TextExt core class.
* @param defaults {Object} Default plugin options. These will be checked if desired value wasn't
* found in the options supplied by the user.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.baseInit
*/
p.baseInit = function(core, defaults)
{
var self = this;
core._defaults = $.extend(true, core._defaults, defaults);
self._core = core;
self._timers = {};
};
/**
* Allows starting of multiple timeout calls. Each time this method is called with the same
* timer name, the timer is reset. This functionality is useful in cases where an action needs
* to occur only after a certain period of inactivity. For example, making an AJAX call after
* user stoped typing for 1 second.
*
* @signature TextExtPlugin.startTimer(name, delay, callback)
*
* @param name {String} Timer name.
* @param delay {Number} Delay in seconds.
* @param callback {Function} Callback function.
*
* @author agorbatchev
* @date 2011/08/25
* @id TextExtPlugin.startTimer
*/
p.startTimer = function(name, delay, callback)
{
var self = this;
self.stopTimer(name);
self._timers[name] = setTimeout(
function()
{
delete self._timers[name];
callback.apply(self);
},
delay * 1000
);
};
/**
* Stops the timer by name without resetting it.
*
* @signature TextExtPlugin.stopTimer(name)
*
* @param name {String} Timer name.
*
* @author agorbatchev
* @date 2011/08/25
* @id TextExtPlugin.stopTimer
*/
p.stopTimer = function(name)
{
clearTimeout(this._timers[name]);
};
/**
* Returns instance of the `TextExt` to which current instance of the plugin is attached to.
*
* @signature TextExtPlugin.core()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.core
*/
p.core = function()
{
return this._core;
};
/**
* Shortcut to the core's `opts()` method. Returns option value.
*
* @signature TextExtPlugin.opts(name)
*
* @param name {String} Option name as described in the options.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.opts
*/
p.opts = function(name)
{
return this.core().opts(name);
};
/**
* Shortcut to the core's `itemManager()` method. Returns instance of the `ItemManger` that is
* currently in use.
*
* @signature TextExtPlugin.itemManager()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.itemManager
*/
p.itemManager = function()
{
return this.core().itemManager();
};
/**
* Shortcut to the core's `input()` method. Returns instance of the HTML element that represents
* current text input.
*
* @signature TextExtPlugin.input()
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.input
*/
p.input = function()
{
return this.core().input();
};
/**
* Shortcut to the commonly used `this.input().val()` call to get or set value of the text input.
*
* @signature TextExtPlugin.val(value)
*
* @param value {String} Optional value. If specified, the value will be set, otherwise it will be
* returned.
*
* @author agorbatchev
* @date 2011/08/20
* @id TextExtPlugin.val
*/
p.val = function(value)
{
var input = this.input();
if(typeof(value) === UNDEFINED)
return input.val();
else
input.val(value);
};
/**
* Shortcut to the core's `trigger()` method. Triggers specified event with arguments on the
* component core.
*
* @signature TextExtPlugin.trigger(event, ...args)
*
* @param event {String} Name of the event to trigger.
* @param ...args All remaining arguments will be passed to the event handler.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExtPlugin.trigger
*/
p.trigger = function()
{
var core = this.core();
core.trigger.apply(core, arguments);
};
/**
* Shortcut to the core's `bind()` method. Binds specified handler to the event.
*
* @signature TextExtPlugin.bind(event, handler)
*
* @param event {String} Event name.
* @param handler {Function} Event handler.
*
* @author agorbatchev
* @date 2011/08/20
* @id TextExtPlugin.bind
*/
p.bind = function(event, handler)
{
this.core().bind(event, handler);
};
/**
* Returns initialization priority for this plugin. If current plugin depends upon some other plugin
* to be initialized before or after, priority needs to be adjusted accordingly. Plugins with higher
* priority initialize before plugins with lower priority.
*
* Default initialization priority is `0`.
*
* @signature TextExtPlugin.initPriority()
*
* @author agorbatchev
* @date 2011/08/22
* @id TextExtPlugin.initPriority
*/
p.initPriority = function()
{
return 0;
};
//--------------------------------------------------------------------------------
// jQuery Integration
/**
* TextExt integrates as a jQuery plugin available through the `$(selector).textext(opts)` call. If
* `opts` argument is passed, then a new instance of `TextExt` will be created for all the inputs
* that match the `selector`. If `opts` wasn't passed and TextExt was already intantiated for
* inputs that match the `selector`, array of `TextExt` instances will be returned instead.
*
* // will create a new instance of `TextExt` for all elements that match `.sample`
* $('.sample').textext({ ... });
*
* // will return array of all `TextExt` instances
* var list = $('.sample').textext();
*
* The following properties are also exposed through the jQuery `$.fn.textext`:
*
* * `TextExt` -- `TextExt` class.
* * `TextExtPlugin` -- `TextExtPlugin` class.
* * `ItemManager` -- `ItemManager` class.
* * `plugins` -- Key/value table of all registered plugins.
* * `addPlugin(name, constructor)` -- All plugins should register themselves using this function.
*
* @author agorbatchev
* @date 2011/08/19
* @id TextExt.jquery
*/
var cssInjected = false;
var textext = $.fn.textext = function(opts)
{
var css;
if(!cssInjected && (css = $.fn.textext.css) != null)
{
$('head').append('<style>' + css + '</style>');
cssInjected = true;
}
return this.map(function()
{
var self = $(this);
if(opts == null)
return self.data('textext');
var instance = new TextExt();
instance.init(self, opts);
self.data('textext', instance);
return instance.input()[0];
});
};
/**
* This static function registers a new plugin which makes it available through the `plugins` option
* to the end user. The name specified here is the name the end user would put in the `plugins` option
* to add this plugin to a new instance of TextExt.
*
* @signature $.fn.textext.addPlugin(name, constructor)
*
* @param name {String} Name of the plugin.
* @param constructor {Function} Plugin constructor.
*
* @author agorbatchev
* @date 2011/10/11
* @id TextExt.addPlugin
*/
textext.addPlugin = function(name, constructor)
{
textext.plugins[name] = constructor;
constructor.prototype = new textext.TextExtPlugin();
};
/**
* This static function registers a new patch which is added to each instance of TextExt. If you are
* adding a new patch, make sure to call this method.
*
* @signature $.fn.textext.addPatch(name, constructor)
*
* @param name {String} Name of the patch.
* @param constructor {Function} Patch constructor.
*
* @author agorbatchev
* @date 2011/10/11
* @id TextExt.addPatch
*/
textext.addPatch = function(name, constructor)
{
textext.patches[name] = constructor;
constructor.prototype = new textext.TextExtPlugin();
};
textext.TextExt = TextExt;
textext.TextExtPlugin = TextExtPlugin;
textext.ItemManager = ItemManager;
textext.plugins = {};
textext.patches = {};
})(jQuery);
(function($)
{
function TextExtIE9Patches() {};
$.fn.textext.TextExtIE9Patches = TextExtIE9Patches;
$.fn.textext.addPatch('ie9',TextExtIE9Patches);
var p = TextExtIE9Patches.prototype;
p.init = function(core)
{
if(navigator.userAgent.indexOf('MSIE 9') == -1)
return;
var self = this;
core.on({ postInvalidate : self.onPostInvalidate });
};
p.onPostInvalidate = function()
{
var self = this,
input = self.input(),
val = input.val()
;
// agorbatchev :: IE9 doesn't seem to update the padding if box-sizing is on until the
// text box value changes, so forcing this change seems to do the trick of updating
// IE's padding visually.
input.val(Math.random());
input.val(val);
};
})(jQuery);
| mit |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
New: Create and edit this dataset card directly on the website!
Contribute a Dataset Card- Downloads last month
- 0