_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q23000
|
mixin
|
train
|
function mixin() {
var args = arguments;
if (Object$assign) {
return Object$assign.apply(null, args);
}
var target = {};
each(args, function (it) {
each(it, function (v, k) {
target[k] = v;
});
});
return args[0] = target;
}
|
javascript
|
{
"resource": ""
}
|
q23001
|
dataset
|
train
|
function dataset(elem) {
if (elem.dataset) {
return JSON.parse(JSON.stringify(elem.dataset));
}
var target = {};
if (elem.hasAttributes()) {
each(elem.attributes, function (attr) {
var name = attr.name;
if (name.indexOf('data-') !== 0) {
return true;
}
name = name.replace(/^data-/i, '')
.replace(/-(\w)/g, function (all, letter) {
return letter.toUpperCase();
});
target[name] = attr.value;
});
return target;
}
return {};
}
|
javascript
|
{
"resource": ""
}
|
q23002
|
inArray
|
train
|
function inArray(elem, arr, i) {
var len;
if (arr) {
if (Array$indexOf) {
return Array$indexOf.call(arr, elem, i);
}
len = arr.length;
i = i ? i < 0 ? Math.max(0, len + i) : i : 0;
for (; i < len; i++) {
// Skip accessing in sparse arrays
if (i in arr && arr[i] === elem) {
return i;
}
}
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
q23003
|
each
|
train
|
function each(obj, callback) {
var length = obj.length;
if (length === undefined) {
for (var name in obj) {
if (obj.hasOwnProperty(name)) {
if (callback.call(obj[name], obj[name], name) === false) {
break;
}
}
}
} else {
for (var i = 0; i < length; i++) {
if (callback.call(obj[i], obj[i], i) === false) {
break;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q23004
|
alReady
|
train
|
function alReady ( fn ) {
var add = 'addEventListener';
var pre = document[ add ] ? '' : 'on';
~document.readyState.indexOf( 'm' ) ? fn() :
'load DOMContentLoaded readystatechange'.replace( /\w+/g, function( type, i ) {
( i ? document : window )
[ pre ? 'attachEvent' : add ]
(
pre + type,
function(){ if ( fn ) if ( i < 6 || ~document.readyState.indexOf( 'm' ) ) fn(), fn = 0 },
!1
)
})
}
|
javascript
|
{
"resource": ""
}
|
q23005
|
_getAndroid
|
train
|
function _getAndroid() {
var android = false;
var sAgent = navigator.userAgent;
if (/android/i.test(sAgent)) { // android
android = true;
var aMat = sAgent.toString().match(/android ([0-9]\.[0-9])/i);
if (aMat && aMat[1]) {
android = parseFloat(aMat[1]);
}
}
return android;
}
|
javascript
|
{
"resource": ""
}
|
q23006
|
_safeSetDataURI
|
train
|
function _safeSetDataURI(fSuccess, fFail) {
var self = this;
self._fFail = fFail;
self._fSuccess = fSuccess;
// Check it just once
if (self._bSupportDataURI === null) {
var el = document.createElement("img");
var fOnError = function() {
self._bSupportDataURI = false;
if (self._fFail) {
self._fFail.call(self);
}
};
var fOnSuccess = function() {
self._bSupportDataURI = true;
if (self._fSuccess) {
self._fSuccess.call(self);
}
};
el.onabort = fOnError;
el.onerror = fOnError;
el.onload = fOnSuccess;
el.src = "data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; // the Image contains 1px data.
return;
} else if (self._bSupportDataURI === true && self._fSuccess) {
self._fSuccess.call(self);
} else if (self._bSupportDataURI === false && self._fFail) {
self._fFail.call(self);
}
}
|
javascript
|
{
"resource": ""
}
|
q23007
|
train
|
function (el, htOption) {
this._bIsPainted = false;
this._android = _getAndroid();
this._htOption = htOption;
this._elCanvas = document.createElement("canvas");
this._elCanvas.width = htOption.width;
this._elCanvas.height = htOption.height;
el.appendChild(this._elCanvas);
this._el = el;
this._oContext = this._elCanvas.getContext("2d");
this._bIsPainted = false;
this._elImage = document.createElement("img");
this._elImage.alt = "Scan me!";
this._elImage.style.display = "none";
this._el.appendChild(this._elImage);
this._bSupportDataURI = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q23008
|
_getTypeNumber
|
train
|
function _getTypeNumber(sText, nCorrectLevel) {
var nType = 1;
var length = _getUTF8Length(sText);
for (var i = 0, len = QRCodeLimitLength.length; i <= len; i++) {
var nLimit = 0;
switch (nCorrectLevel) {
case QRErrorCorrectLevel.L :
nLimit = QRCodeLimitLength[i][0];
break;
case QRErrorCorrectLevel.M :
nLimit = QRCodeLimitLength[i][1];
break;
case QRErrorCorrectLevel.Q :
nLimit = QRCodeLimitLength[i][2];
break;
case QRErrorCorrectLevel.H :
nLimit = QRCodeLimitLength[i][3];
break;
}
if (length <= nLimit) {
break;
} else {
nType++;
}
}
if (nType > QRCodeLimitLength.length) {
throw new Error("Too long data");
}
return nType;
}
|
javascript
|
{
"resource": ""
}
|
q23009
|
getCurrentActiveType
|
train
|
function getCurrentActiveType (version) {
let typelist = TypeList
for (let i = 0; i < typelist.length; i++) {
if (semver[typelist[i]](version)) {
return typelist[i]
}
}
}
|
javascript
|
{
"resource": ""
}
|
q23010
|
consumeBody
|
train
|
function consumeBody() {
if (this[INTERNALS].disturbed) {
return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
}
this[INTERNALS].disturbed = true;
if (this[INTERNALS].error) {
return Body.Promise.reject(this[INTERNALS].error);
}
let body = this.body;
// body is null
if (body === null) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is blob
if (isBlob(body)) {
body = body.stream();
}
// body is buffer
if (Buffer.isBuffer(body)) {
return Body.Promise.resolve(body);
}
// istanbul ignore if: should never happen
if (!(body instanceof Stream)) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is stream
// get ready to actually consume the body
let accum = [];
let accumBytes = 0;
let abort = false;
return new Body.Promise((resolve, reject) => {
let resTimeout;
// allow timeout on slow response body
if (this.timeout) {
resTimeout = setTimeout(() => {
abort = true;
reject(new FetchError(`Response timeout while trying to fetch ${this.url} (over ${this.timeout}ms)`, 'body-timeout'));
}, this.timeout);
}
// handle stream errors
body.on('error', err => {
if (err.name === 'AbortError') {
// if the request was aborted, reject with this Error
abort = true;
reject(err);
} else {
// other errors, such as incorrect content-encoding
reject(new FetchError(`Invalid response body while trying to fetch ${this.url}: ${err.message}`, 'system', err));
}
});
body.on('data', chunk => {
if (abort || chunk === null) {
return;
}
if (this.size && accumBytes + chunk.length > this.size) {
abort = true;
reject(new FetchError(`content size at ${this.url} over limit: ${this.size}`, 'max-size'));
return;
}
accumBytes += chunk.length;
accum.push(chunk);
});
body.on('end', () => {
if (abort) {
return;
}
clearTimeout(resTimeout);
try {
resolve(Buffer.concat(accum, accumBytes));
} catch (err) {
// handle streams that have accumulated too much data (issue #414)
reject(new FetchError(`Could not create Buffer from response body for ${this.url}: ${err.message}`, 'system', err));
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q23011
|
find
|
train
|
function find(map, name) {
name = name.toLowerCase();
for (const key in map) {
if (key.toLowerCase() === name) {
return key;
}
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q23012
|
logMessage
|
train
|
function logMessage(messageType, message) {
if (Object.values(messageTypes).includes(messageType)) {
console[messageType](message)
} else {
console.info(message)
}
}
|
javascript
|
{
"resource": ""
}
|
q23013
|
train
|
function(fns, done) {
done = done || function() {};
this.map(fns, function(fn, callback) {
fn(callback);
}, done);
}
|
javascript
|
{
"resource": ""
}
|
|
q23014
|
train
|
function(items, iterator, done) {
done = done || function() {};
var results = [];
var failure = false;
var expected = items.length;
var actual = 0;
var createIntermediary = function(index) {
return function(err, result) {
// Return if we found a failure anywhere.
// We can't stop execution of functions since they've already
// been fired off; but we can prevent excessive handling of callbacks.
if (failure != false) {
return;
}
if (err != null) {
failure = true;
done(err, result);
return;
}
actual += 1;
if (actual == expected) {
done(null, results);
}
};
};
for (var i = 0; i < items.length; i++) {
var item = items[i];
iterator(item, createIntermediary(i));
}
if (items.length == 0) {
done(null, []);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23015
|
train
|
function(items, iterator, done) {
done = done || function() {};
var results = [];
var failure = false;
var expected = items.length;
var current = -1;
function callback(err, result) {
if (err) return done(err);
results.push(result);
if (current == expected) {
return done(null, results);
} else {
next();
}
}
function next() {
current += 1;
var item = items[current];
iterator(item, callback);
}
next()
}
|
javascript
|
{
"resource": ""
}
|
|
q23016
|
cloneTxParams
|
train
|
function cloneTxParams(txParams){
return {
from: txParams.from,
to: txParams.to,
value: txParams.value,
data: txParams.data,
gas: txParams.gas,
gasPrice: txParams.gasPrice,
nonce: txParams.nonce,
}
}
|
javascript
|
{
"resource": ""
}
|
q23017
|
resemblesData
|
train
|
function resemblesData (string) {
const fixed = ethUtil.addHexPrefix(string)
const isValidAddress = ethUtil.isValidAddress(fixed)
return !isValidAddress && isValidHex(string)
}
|
javascript
|
{
"resource": ""
}
|
q23018
|
train
|
function(data) {
if (data.row.index === 5) {
data.cell.styles.fillColor = [40, 170, 100];
}
if ((data.row.section === 'head' || data.row.section === 'foot') && data.column.dataKey === "expenses") {
data.cell.text = '' // Use an icon in didDrawCell instead
}
if (data.row.index === 0 && data.row.section === 'body' && data.column.dataKey === 'city') {
data.cell.text = 'とうきょう'
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23019
|
train
|
function(data) {
if (data.row.section === 'body' && data.column.dataKey === "expenses") {
if (data.cell.raw > 750) {
doc.setTextColor(231, 76, 60); // Red
doc.setFontStyle('bold');
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23020
|
train
|
function(data) {
if ((data.row.section === 'head' || data.row.section === 'foot') && data.column.dataKey === "expenses" && coinBase64Img) {
doc.addImage(coinBase64Img, 'PNG', data.cell.x + 5, data.cell.y + 2, 5, 5);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23021
|
train
|
function(data) {
doc.setFontSize(18);
doc.text("Custom styling with hooks", data.settings.margin.left, 22);
doc.setFontSize(12);
doc.text("Conditional styling of cells, rows and columns, cell and table borders, custom font, image in cell", data.settings.margin.left, 30)
}
|
javascript
|
{
"resource": ""
}
|
|
q23022
|
findAll
|
train
|
function findAll (el, node) {
return [].slice.call(node ? el.querySelectorAll(node) : $.querySelectorAll(el))
}
|
javascript
|
{
"resource": ""
}
|
q23023
|
corner
|
train
|
function corner (data) {
if (!data) { return '' }
if (!/\/\//.test(data)) { data = 'https://github.com/' + data; }
data = data.replace(/^git\+/, '');
return (
"<a href=\"" + data + "\" class=\"github-corner\" aria-label=\"View source on Github\">" +
'<svg viewBox="0 0 250 250" aria-hidden="true">' +
'<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>' +
'<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>' +
'<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path>' +
'</svg>' +
'</a>')
}
|
javascript
|
{
"resource": ""
}
|
q23024
|
main
|
train
|
function main (config) {
var aside = (
'<button class="sidebar-toggle">' +
'<div class="sidebar-toggle-button">' +
'<span></span><span></span><span></span>' +
'</div>' +
'</button>' +
'<aside class="sidebar">' +
(config.name
? ("<h1><a class=\"app-name-link\" data-nosearch>" + (config.name) + "</a></h1>")
: '') +
'<div class="sidebar-nav"><!--sidebar--></div>' +
'</aside>');
return (isMobile ? (aside + "<main>") : ("<main>" + aside)) +
'<section class="content">' +
'<article class="markdown-section" id="main"><!--main--></article>' +
'</section>' +
'</main>'
}
|
javascript
|
{
"resource": ""
}
|
q23025
|
init
|
train
|
function init () {
var div = create('div');
div.classList.add('progress');
appendTo(body, div);
barEl = div;
}
|
javascript
|
{
"resource": ""
}
|
q23026
|
train
|
function (ref) {
var loaded = ref.loaded;
var total = ref.total;
var step = ref.step;
var num;
!barEl && init();
if (step) {
num = parseInt(barEl.style.width || 0, 10) + step;
num = num > 80 ? 80 : num;
} else {
num = Math.floor(loaded / total * 100);
}
barEl.style.opacity = 1;
barEl.style.width = num >= 95 ? '100%' : num + '%';
if (num >= 95) {
clearTimeout(timeId);
timeId = setTimeout(function (_) {
barEl.style.opacity = 0;
barEl.style.width = '0%';
}, 200);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23027
|
genTree
|
train
|
function genTree (toc, maxLevel) {
var headlines = [];
var last = {};
toc.forEach(function (headline) {
var level = headline.level || 1;
var len = level - 1;
if (level > maxLevel) { return }
if (last[len]) {
last[len].children = (last[len].children || []).concat(headline);
} else {
headlines.push(headline);
}
last[level] = headline;
});
return headlines
}
|
javascript
|
{
"resource": ""
}
|
q23028
|
getAndActive
|
train
|
function getAndActive (router, el, isParent, autoTitle) {
el = getNode(el);
var links = findAll(el, 'a');
var hash = router.toURL(router.getCurrentPath());
var target;
links
.sort(function (a, b) { return b.href.length - a.href.length; })
.forEach(function (a) {
var href = a.getAttribute('href');
var node = isParent ? a.parentNode : a;
if (hash.indexOf(href) === 0 && !target) {
target = a;
toggleClass(node, 'add', 'active');
} else {
toggleClass(node, 'remove', 'active');
}
});
if (autoTitle) {
$.title = target ? ((target.innerText) + " - " + title) : title;
}
return target
}
|
javascript
|
{
"resource": ""
}
|
q23029
|
train
|
function () {
var self = this;
delete $.noty.store[self.options.id]; // deleting noty from store
if (self.options.theme.callback && self.options.theme.callback.onClose) {
self.options.theme.callback.onClose.apply(self);
}
if (!self.options.dismissQueue) {
// Queue render
$.noty.ontap = true;
$.notyRenderer.render();
}
if (self.options.maxVisible > 0 && self.options.dismissQueue) {
$.notyRenderer.render();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23030
|
listen
|
train
|
function listen(name, callback) {
if (!showdown.helper.isString(name)) {
throw Error('Invalid argument in converter.listen() method: name must be a string, but ' + typeof name + ' given');
}
if (typeof callback !== 'function') {
throw Error('Invalid argument in converter.listen() method: callback must be a function, but ' + typeof callback + ' given');
}
if (!listeners.hasOwnProperty(name)) {
listeners[name] = [];
}
listeners[name].push(callback);
}
|
javascript
|
{
"resource": ""
}
|
q23031
|
train
|
function(req, res, next) {
var parsed = require("url").parse(req.url);
if (parsed.pathname.match(/\.less$/)) {
return less(parsed.pathname).then(function(o) {
res.setHeader("Content-Type", "text/css");
res.end(o.css);
});
}
next();
}
|
javascript
|
{
"resource": ""
}
|
|
q23032
|
iteratorToArray
|
train
|
function iteratorToArray(iterator) {
var data,
result = [];
while (!(data = iterator.next()).done) {
result.push(data.value);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q23033
|
getIteratee
|
train
|
function getIteratee() {
var result = lodash.iteratee || iteratee;
result = result === iteratee ? baseIteratee : result;
return arguments.length ? result(arguments[0], arguments[1]) : result;
}
|
javascript
|
{
"resource": ""
}
|
q23034
|
memoizeCapped
|
train
|
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
|
javascript
|
{
"resource": ""
}
|
q23035
|
toInteger
|
train
|
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result
? remainder ? result - remainder : result
: 0;
}
|
javascript
|
{
"resource": ""
}
|
q23036
|
requirePlugin
|
train
|
function requirePlugin(item) {
/**
* if the "module" property already exists and
* is not a string, then we bail and don't bother looking
* for the file
*/
if (item.get("module") && typeof item.get("module") !== "string") {
return item;
}
try {
/**
* Try a raw node require() call - this will be how
* regular "npm installed" plugins wil work
*/
var maybe = require.resolve(item.get("name"));
return item.set("module", require(maybe));
} catch (e) {
/**
* If require threw an MODULE_NOT_FOUND error, try again
* by resolving from cwd. This is needed since cli
* users will not add ./ to the front of a path (which
* node requires to resolve from cwd)
*/
if (e.code === "MODULE_NOT_FOUND") {
var maybe = path.resolve(process.cwd(), item.get("name"));
if (fs.existsSync(maybe)) {
return item.set("module", require(maybe));
} else {
/**
* Finally return a plugin that contains the error
* this will be picked up later and discarded
*/
return item.update("errors", function(errors) {
return errors.concat(e);
});
}
}
throw e;
}
}
|
javascript
|
{
"resource": ""
}
|
q23037
|
train
|
function(bs, data) {
if (canLogFileChange(bs, data)) {
if (data.path[0] === "*") {
return logger.info(
"{cyan:Reloading files that match: {magenta:%s",
data.path
);
}
logger.info(
"{cyan:File event [" + data.event + "] : {magenta:%s",
data.path
);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23038
|
train
|
function(bs, data) {
var uaString = utils.getUaString(data.ua);
var msg = "{cyan:Browser Connected: {magenta:%s, version: %s}";
var method = "info";
if (!bs.options.get("logConnections")) {
method = "debug";
}
logger.log(method, msg, uaString.name, uaString.version);
}
|
javascript
|
{
"resource": ""
}
|
|
q23039
|
train
|
function(bs, data) {
const type = data.type;
if (bs.options.get('json')) {
return console.log(JSON.stringify({
"service:running": {
"options": bs.options.toJS()
}
}));
}
if (type === "server") {
var baseDir = bs.options.getIn(["server", "baseDir"]);
logUrls(bs.options.get("urls").toJS());
if (baseDir) {
if (utils.isList(baseDir)) {
baseDir.forEach(serveFiles);
} else {
serveFiles(baseDir);
}
}
}
if (type === "proxy") {
logger.info(
"Proxying: {cyan:%s}",
bs.options.getIn(["proxy", "target"])
);
logUrls(bs.options.get("urls").toJS());
}
if (type === "snippet") {
if (bs.options.get("logSnippet")) {
logger.info(
"{bold:Copy the following snippet into your website, " +
"just before the closing {cyan:</body>} tag"
);
logger.unprefixed("info", messages.scriptTags(bs.options));
}
logUrls(
bs.options
.get("urls")
.filter(function(value, key) {
return key.slice(0, 2) === "ui";
})
.toJS()
);
}
function serveFiles(base) {
logger.info("Serving files from: {magenta:%s}", base);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23040
|
getKeyName
|
train
|
function getKeyName(key) {
if (key.indexOf("ui") > -1) {
if (key === "ui") {
return "UI";
}
if (key === "ui-external") {
return "UI External";
}
}
return key.substr(0, 1).toUpperCase() + key.substring(1);
}
|
javascript
|
{
"resource": ""
}
|
q23041
|
canLogFileChange
|
train
|
function canLogFileChange(bs, data) {
if (data && data.log === false) {
return false;
}
return bs.options.get("logFileChanges");
}
|
javascript
|
{
"resource": ""
}
|
q23042
|
createServer
|
train
|
function createServer(bs) {
var proxy = bs.options.get("proxy");
var server = bs.options.get("server");
if (!proxy && !server) {
return require("./snippet-server")(bs);
}
if (proxy) {
return require("./proxy-server")(bs);
}
if (server) {
return require("./static-server")(bs);
}
}
|
javascript
|
{
"resource": ""
}
|
q23043
|
icons
|
train
|
function icons (opts, ctx, done) {
return vfs.src(opts.input)
.pipe(easysvg.stream({js: false}))
.on('error', done)
.pipe(vfs.dest(opts.output))
}
|
javascript
|
{
"resource": ""
}
|
q23044
|
train
|
function ($section) {
angular.forEach(pagesConfig, function (item) {
item.active = false;
});
$section.active = true;
return pagesConfig;
}
|
javascript
|
{
"resource": ""
}
|
|
q23045
|
train
|
function () {
if ($location.path() === "/") {
return pagesConfig["overview"];
}
var match;
angular.forEach(pagesConfig, function (item) {
if (item.path === $location.path()) {
match = item;
}
});
return match;
}
|
javascript
|
{
"resource": ""
}
|
|
q23046
|
train
|
function (ui, done) {
Object.keys(ui.defaultPlugins).forEach(function (key) {
ui.pluginManager.get(key)(ui, ui.bs);
});
done();
}
|
javascript
|
{
"resource": ""
}
|
|
q23047
|
train
|
function (ui, done) {
var bs = ui.bs;
ui.clients.on("connection", function (client) {
client.emit("ui:connection", ui.options.toJS());
ui.options.get("clientFiles").map(function (item) {
if (item.get("active")) {
ui.addElement(client, item.toJS());
}
});
});
ui.socket.on("connection", function (client) {
client.emit("connection", bs.getOptions().toJS());
client.emit("ui:connection", ui.options.toJS());
client.on("ui:get:options", function () {
client.emit("ui:receive:options", {
bs: bs.getOptions().toJS(),
ui: ui.options.toJS()
});
});
// proxy client events
client.on("ui:client:proxy", function (evt) {
ui.clients.emit(evt.event, evt.data);
});
client.on("ui", function (data) {
ui.delegateEvent(data);
});
});
done();
}
|
javascript
|
{
"resource": ""
}
|
|
q23048
|
train
|
function(event, path) {
emitter.emit("file:changed", {
event: event,
path: path,
namespace: namespace
});
}
|
javascript
|
{
"resource": ""
}
|
|
q23049
|
noop
|
train
|
function noop(name) {
return function() {
var args = Array.prototype.slice.call(arguments);
if (singleton) {
return singleton[name].apply(singleton, args);
} else {
if (publicUtils.isStreamArg(name, args)) {
return new PassThrough({ objectMode: true });
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q23050
|
getSingle
|
train
|
function getSingle(name) {
if (instances.length) {
var match = instances.filter(function(item) {
return item.name === name;
});
if (match.length) {
return match[0];
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q23051
|
getUrls
|
train
|
function getUrls (opts) {
var list = [];
var bsLocal = require("url").parse(opts.urls.local);
list.push([bsLocal.protocol + "//", bsLocal.hostname, ":", opts.port].join(""));
if (opts.urls.external) {
var external = require("url").parse(opts.urls.external);
list.push([bsLocal.protocol + "//", external.hostname, ":", opts.port].join(""));
}
return Immutable.List(list);
}
|
javascript
|
{
"resource": ""
}
|
q23052
|
train
|
function (current, temp) {
if (!Immutable.is(current, temp)) {
validUrls = temp;
methods.sendUpdatedUrls(validUrls);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23053
|
train
|
function (data) {
var temp = addPath(validUrls, url.parse(data.href), bs.options.get("mode"));
methods.sendUpdatedIfChanged(validUrls, temp, ui.socket);
}
|
javascript
|
{
"resource": ""
}
|
|
q23054
|
train
|
function (data) {
var temp = removePath(validUrls, data.path);
methods.sendUpdatedIfChanged(validUrls, temp, ui.socket);
}
|
javascript
|
{
"resource": ""
}
|
|
q23055
|
rewriteCookies
|
train
|
function rewriteCookies(rawCookie) {
var objCookie = (function() {
// simple parse function (does not remove quotes)
var obj = {};
var pairs = rawCookie.split(/; */);
pairs.forEach(function(pair) {
var eqIndex = pair.indexOf("=");
// skip things that don't look like key=value
if (eqIndex < 0) {
return;
}
var key = pair.substr(0, eqIndex).trim();
obj[key] = pair.substr(eqIndex + 1, pair.length).trim();
});
return obj;
})();
var pairs = Object.keys(objCookie)
.filter(function(item) {
return item.toLowerCase() !== "domain";
})
.map(function(key) {
return key + "=" + objCookie[key];
});
if (rawCookie.match(/httponly/i)) {
pairs.push("HttpOnly");
}
return pairs.join("; ");
}
|
javascript
|
{
"resource": ""
}
|
q23056
|
applyFns
|
train
|
function applyFns(name, fns) {
if (!List.isList(fns)) fns = [fns];
proxy.on(name, function() {
var args = arguments;
fns.forEach(function(fn) {
if (typeof fn === "function") {
fn.apply(null, args);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q23057
|
handleConnection
|
train
|
function handleConnection(client) {
// set ghostmode callbacks
if (bs.options.get("ghostMode")) {
addGhostMode(client);
}
client.emit("connection", bs.options.toJS()); //todo - trim the amount of options sent to clients
emitter.emit("client:connected", {
ua: client.handshake.headers["user-agent"]
});
}
|
javascript
|
{
"resource": ""
}
|
q23058
|
train
|
function (hooks, ui) {
var config = hooks
.map(transformConfig)
.reduce(createConfigItem, {});
return {
/**
* pagesConfig - This is the angular configuration such as routes
*/
pagesConfig: configTmpl
.replace("%when%", hooks.reduce(
createAngularRoutes,
""
))
.replace("%pages%", JSON.stringify(
config,
null,
4
)),
/**
* pagesConfig in object form
*/
pagesObj: config,
pageMarkup: function () {
return preAngular(ui.pluginManager.plugins, config, ui);
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q23059
|
train
|
function (hooks) {
var obj = {};
hooks.forEach(function (elements) {
elements.forEach(function (item) {
if (!obj[item.name]) {
obj[item.name] = item;
}
});
});
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q23060
|
train
|
function(app, options) {
return {
server: (function() {
var httpModule = serverUtils.getHttpModule(options);
if (
options.get("scheme") === "https" ||
options.get("httpModule") === "http2"
) {
var opts = serverUtils.getHttpsOptions(options);
return httpModule.createServer(opts.toJS(), app);
}
return httpModule.createServer(app);
})(),
app: app
};
}
|
javascript
|
{
"resource": ""
}
|
|
q23061
|
train
|
function(name, args) {
if (name === "stream") {
return true;
}
if (name !== "reload") {
return false;
}
var firstArg = args[0];
/**
* If here, it's reload with args
*/
if (_.isObject(firstArg)) {
if (!Array.isArray(firstArg) && Object.keys(firstArg).length) {
return firstArg.stream === true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q23062
|
train
|
function(bs, done) {
utils.getPorts(bs.options, function(err, port) {
if (err) {
return utils.fail(true, err, bs.cb);
}
bs.debug("Found a free port: {magenta:%s", port);
done(null, {
options: {
port: port
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q23063
|
train
|
function(bs, done) {
/**
* An extra port is not needed in snippet/server mode
*/
if (bs.options.get("mode") !== "proxy") {
return done();
}
/**
* Web socket support is disabled by default
*/
if (!bs.options.getIn(["proxy", "ws"])) {
return done();
}
/**
* Use 1 higher than server port by default...
*/
var socketPort = bs.options.get("port") + 1;
/**
* Or use the user-defined socket.port option instead
*/
if (bs.options.hasIn(["socket", "port"])) {
socketPort = bs.options.getIn(["socket", "port"]);
}
utils.getPort(bs.options.get("listen", "localhost"), socketPort, null, function(err, port) {
if (err) {
return utils.fail(true, err, bs.cb);
}
done(null, {
optionsIn: [
{
path: ["socket", "port"],
value: port
}
]
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q23064
|
train
|
function(bs, done) {
var plugins = bs.options
.get("plugins")
.map(pluginUtils.resolvePlugin)
.map(pluginUtils.requirePlugin);
plugins.forEach(function(plugin) {
if (plugin.get("errors").size) {
return logPluginError(plugin);
}
var jsPlugin = plugin.toJS();
jsPlugin.options = jsPlugin.options || {};
jsPlugin.options.moduleName = jsPlugin.moduleName;
bs.registerPlugin(jsPlugin.module, jsPlugin.options);
});
function logPluginError(plugin) {
utils.fail(true, plugin.getIn(["errors", 0]), bs.cb);
}
done();
}
|
javascript
|
{
"resource": ""
}
|
|
q23065
|
train
|
function(data) {
var mode = bs.options.get("mode");
var open = bs.options.get("open");
if (
mode === "proxy" ||
mode === "server" ||
open === "ui" ||
open === "ui-external"
) {
utils.openBrowser(data.url, bs.options, bs);
}
// log about any file watching
if (bs.watchers) {
bs.events.emit("file:watching", bs.watchers);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23066
|
train
|
function(data) {
if (data.active) {
bs.pluginManager.enablePlugin(data.name);
} else {
bs.pluginManager.disablePlugin(data.name);
}
bs.setOption("userPlugins", bs.getUserPlugins());
}
|
javascript
|
{
"resource": ""
}
|
|
q23067
|
setHeaders
|
train
|
function setHeaders(res, body) {
res.setHeader("Cache-Control", "public, max-age=0");
res.setHeader("Content-Type", "text/javascript");
res.setHeader("ETag", etag(body));
}
|
javascript
|
{
"resource": ""
}
|
q23068
|
init
|
train
|
function init(options, requestBody, type) {
/**
* If the user asked for a file, simply return the string.
*/
if (type && type === "file") {
return processItems(requestBody);
}
/**
* Otherwise return a function to be used a middleware
*/
return function(req, res) {
/**
* default to using the uncompressed string
* @type {String}
*/
var output = processItems(requestBody);
/**
* Set the appropriate headers for caching
*/
setHeaders(res, output);
if (isConditionalGet(req) && fresh(req.headers, res._headers)) {
return notModified(res);
}
/**
* If gzip is supported, compress the string once
* and save for future requests
*/
if (supportsGzip(req)) {
res.setHeader("Content-Encoding", "gzip");
var buf = new Buffer(output, "utf-8");
zlib.gzip(buf, function(_, result) {
res.end(result);
});
} else {
res.end(output);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q23069
|
setOptions
|
train
|
function setOptions(bs, options) {
/**
* If multiple options were set, act on the immutable map
* in an efficient way
*/
if (Object.keys(options).length > 1) {
bs.setMany(function(item) {
Object.keys(options).forEach(function(key) {
item.set(key, options[key]);
return item;
});
});
} else {
Object.keys(options).forEach(function(key) {
bs.setOption(key, options[key]);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q23070
|
tasksComplete
|
train
|
function tasksComplete(bs) {
return function(err) {
if (err) {
bs.logger.setOnce("useLevelPrefixes", true).error(err.message);
}
/**
* Set active flag
*/
bs.active = true;
/**
* @deprecated
*/
bs.events.emit("init", bs);
/**
* This is no-longer needed as the Callback now only resolves
* when everything (including slow things, like the tunnel) is ready.
* It's here purely for backwards compatibility.
* @deprecated
*/
bs.events.emit("service:running", {
options: bs.options,
baseDir: bs.options.getIn(["server", "baseDir"]),
type: bs.options.get("mode"),
port: bs.options.get("port"),
url: bs.options.getIn(["urls", "local"]),
urls: bs.options.get("urls").toJS(),
tunnel: bs.options.getIn(["urls", "tunnel"])
});
/**
* Call any option-provided callbacks
*/
bs.callback("ready", null, bs);
/**
* Finally, call the user-provided callback given as last arg
*/
bs.cb(null, bs);
};
}
|
javascript
|
{
"resource": ""
}
|
q23071
|
taskRunner
|
train
|
function taskRunner (ui) {
return function (item, cb) {
ui.logger.debug("Starting Step: " + item.step);
/**
* Give each step access to the UI Instance
*/
item.fn(ui, function (err, out) {
if (err) {
return cb(err);
}
if (out) {
handleOut(ui, out);
}
ui.logger.debug("{green:Step Complete: " + item.step);
cb();
});
};
}
|
javascript
|
{
"resource": ""
}
|
q23072
|
handleOut
|
train
|
function handleOut (ui, out) {
if (out.options) {
Object.keys(out.options).forEach(function (key) {
ui.options = ui.options.set(key, out.options[key]);
});
}
if (out.optionsIn) {
out.optionsIn.forEach(function (item) {
ui.options = ui.options.setIn(item.path, item.value);
});
}
if (out.instance) {
Object.keys(out.instance).forEach(function (key) {
ui[key] = out.instance[key];
});
}
}
|
javascript
|
{
"resource": ""
}
|
q23073
|
tasksComplete
|
train
|
function tasksComplete (ui) {
return function (err) {
/**
* Log any error according to BrowserSync's Logging level
*/
if (err) {
ui.logger.setOnce("useLevelPrefixes", true).error(err.message || err);
}
/**
* Running event
*/
ui.events.emit("ui:running", {instance: ui, options: ui.options});
/**
* Finally call the user-provided callback
*/
ui.cb(null, ui);
};
}
|
javascript
|
{
"resource": ""
}
|
q23074
|
decorateClients
|
train
|
function decorateClients(clients, clientsInfo) {
return clients.map(function (item) {
clientsInfo.forEach(function (client) {
if (client.id === item.id) {
item.data = client.data;
return false;
}
});
return item;
});
}
|
javascript
|
{
"resource": ""
}
|
q23075
|
resolvePluginFiles
|
train
|
function resolvePluginFiles (collection, relPath) {
return Immutable.fromJS(collection.reduce(function (all, item) {
var full = path.join(relPath, item);
if (fs.existsSync(full)) {
all[full] = fs.readFileSync(full, "utf8");
}
return all;
}, {}));
}
|
javascript
|
{
"resource": ""
}
|
q23076
|
formatKey
|
train
|
function formatKey(key) {
key = key.toLowerCase()
// Don't capitalize -ms- prefix
if (/^-ms-/.test(key)) key = key.substr(1)
return t.identifier(hyphenToCamelCase(key))
}
|
javascript
|
{
"resource": ""
}
|
q23077
|
formatValue
|
train
|
function formatValue(value) {
if (isNumeric(value)) return t.numericLiteral(Number(value))
if (isConvertiblePixelValue(value))
return t.numericLiteral(Number(trimEnd(value, 'px')))
return t.stringLiteral(value)
}
|
javascript
|
{
"resource": ""
}
|
q23078
|
stringToObjectStyle
|
train
|
function stringToObjectStyle(rawStyle) {
const entries = rawStyle.split(';')
const properties = []
let index = -1
while (++index < entries.length) {
const entry = entries[index]
const style = entry.trim()
const firstColon = style.indexOf(':')
const value = style.substr(firstColon + 1).trim()
const key = style.substr(0, firstColon)
if (key !== '') {
const property = t.objectProperty(formatKey(key), formatValue(value))
properties.push(property)
}
}
return t.objectExpression(properties)
}
|
javascript
|
{
"resource": ""
}
|
q23079
|
train
|
function (table, key, obj, clientIdentity) {
// Create table if it doesnt exist:
db.tables[table] = db.tables[table] || {};
// Put the obj into to table
db.tables[table][key] = obj;
// Register the change:
db.changes.push({
rev: ++db.revision,
source: clientIdentity,
type: CREATE,
table: table,
key: key,
obj: obj
});
db.trigger();
}
|
javascript
|
{
"resource": ""
}
|
|
q23080
|
sendAnyChanges
|
train
|
function sendAnyChanges() {
// Get all changes after syncedRevision that was not performed by the client we're talkin' to.
var changes = db.changes.filter(function (change) { return change.rev > syncedRevision && change.source !== conn.clientIdentity; });
// Compact changes so that multiple changes on same object is merged into a single change.
var reducedSet = reduceChanges(changes, conn.clientIdentity);
// Convert the reduced set into an array again.
var reducedArray = Object.keys(reducedSet).map(function (key) { return reducedSet[key]; });
// Notice the current revision of the database. We want to send it to client so it knows what to ask for next time.
var currentRevision = db.revision;
conn.sendText(JSON.stringify({
type: "changes",
changes: reducedArray,
currentRevision: currentRevision,
partial: false // Tell client that these are the only changes we are aware of. Since our mem DB is syncronous, we got all changes in one chunk.
}));
syncedRevision = currentRevision; // Make sure we only send revisions coming after this revision next time and not resend the above changes over and over.
}
|
javascript
|
{
"resource": ""
}
|
q23081
|
train
|
function (callback, args) {
microtickQueue.push([callback, args]);
if (needsNewPhysicalTick) {
schedulePhysicalTick();
needsNewPhysicalTick = false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23082
|
EmulatedWebSocketServerFactory
|
train
|
function EmulatedWebSocketServerFactory() {
this.createServer = function (connectCallback) {
var server = {
_connect: function (socket) {
var conn = {
_client: socket,
_listeners: { "text": [], "close": [] },
on: function (type, listener) {
conn._listeners[type].push(listener);
},
_fire: function (type, args) {
conn._listeners[type].forEach(function (listener) {
listener.apply(null, args);
});
},
_text: function (msg) {
conn._fire("text", [msg]);
},
sendText: function (msg) {
setTimeout(function () {
conn._client._text(msg);
}, 0);
},
close: function (code, reason) {
setTimeout(function () {
conn._client._disconnect(code, reason);
}, 0);
},
_disconnect: function (code, reason) {
conn._fire("close", [code, reason]);
}
};
connectCallback(conn);
return conn;
},
listen: function (port) {
EmulatedWebSocketServerFactory.listeners[port] = this;
return this;
}
}
return server;
}
}
|
javascript
|
{
"resource": ""
}
|
q23083
|
getCharset
|
train
|
function getCharset(str){
var charset = (str && str.match(/charset=['"]?([\w.-]+)/i) || [0, null])[1];
return charset && charset.replace(/:\d{4}$|[^0-9a-z]/g, '') == 'gb2312' ? 'gbk' : charset;
}
|
javascript
|
{
"resource": ""
}
|
q23084
|
extend
|
train
|
function extend(dest, src, merge) {
for(var key in src) {
if(dest[key] !== undefined && merge) {
continue;
}
dest[key] = src[key];
}
return dest;
}
|
javascript
|
{
"resource": ""
}
|
q23085
|
getVelocity
|
train
|
function getVelocity(delta_time, delta_x, delta_y) {
return {
x: Math.abs(delta_x / delta_time) || 0,
y: Math.abs(delta_y / delta_time) || 0
};
}
|
javascript
|
{
"resource": ""
}
|
q23086
|
toggleDefaultBehavior
|
train
|
function toggleDefaultBehavior(element, css_props, toggle) {
if(!css_props || !element || !element.style) {
return;
}
// with css properties for modern browsers
Utils.each(['webkit', 'moz', 'Moz', 'ms', 'o', ''], function setStyle(vendor) {
Utils.each(css_props, function(value, prop) {
// vender prefix at the property
if(vendor) {
prop = vendor + prop.substring(0, 1).toUpperCase() + prop.substring(1);
}
// set the style
if(prop in element.style) {
element.style[prop] = !toggle && value;
}
});
});
var false_fn = function(){ return false; };
// also the disable onselectstart
if(css_props.userSelect == 'none') {
element.onselectstart = !toggle && false_fn;
}
// and disable ondragstart
if(css_props.userDrag == 'none') {
element.ondragstart = !toggle && false_fn;
}
}
|
javascript
|
{
"resource": ""
}
|
q23087
|
dispose
|
train
|
function dispose() {
var i, eh;
// undo all changes made by stop_browser_behavior
if(this.options.stop_browser_behavior) {
Utils.toggleDefaultBehavior(this.element, this.options.stop_browser_behavior, true);
}
// unbind all custom event handlers
for(i=-1; (eh=this.eventHandlers[++i]);) {
this.element.removeEventListener(eh.gesture, eh.handler, false);
}
this.eventHandlers = [];
// unbind the start event listener
Event.unbindDom(this.element, Hammer.EVENT_TYPES[EVENT_START], this.eventStartHandler);
return null;
}
|
javascript
|
{
"resource": ""
}
|
q23088
|
collectEventData
|
train
|
function collectEventData(element, eventType, touches, ev) {
// find out pointerType
var pointerType = POINTER_TOUCH;
if(Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) {
pointerType = POINTER_MOUSE;
}
return {
center : Utils.getCenter(touches),
timeStamp : new Date().getTime(),
target : ev.target,
touches : touches,
eventType : eventType,
pointerType: pointerType,
srcEvent : ev,
/**
* prevent the browser default actions
* mostly used to disable scrolling of the browser
*/
preventDefault: function() {
var srcEvent = this.srcEvent;
srcEvent.preventManipulation && srcEvent.preventManipulation();
srcEvent.preventDefault && srcEvent.preventDefault();
},
/**
* stop bubbling the event up to its parents
*/
stopPropagation: function() {
this.srcEvent.stopPropagation();
},
/**
* immediately stop gesture detection
* might be useful after a swipe was detected
* @return {*}
*/
stopDetect: function() {
return Detection.stopDetect();
}
};
}
|
javascript
|
{
"resource": ""
}
|
q23089
|
getInterimData
|
train
|
function getInterimData(ev) {
var lastEvent = this.current.lastEvent
, angle
, direction;
// end events (e.g. dragend) don't have useful values for interimDirection & interimAngle
// because the previous event has exactly the same coordinates
// so for end events, take the previous values of interimDirection & interimAngle
// instead of recalculating them and getting a spurious '0'
if(ev.eventType == EVENT_END) {
angle = lastEvent && lastEvent.interimAngle;
direction = lastEvent && lastEvent.interimDirection;
}
else {
angle = lastEvent && Utils.getAngle(lastEvent.center, ev.center);
direction = lastEvent && Utils.getDirection(lastEvent.center, ev.center);
}
ev.interimAngle = angle;
ev.interimDirection = direction;
}
|
javascript
|
{
"resource": ""
}
|
q23090
|
round
|
train
|
function round(float, digits) {
if(digits == null) {
return Math.round(float);
}
var round = 10 * digits;
return Math.round(float * round) / round;
}
|
javascript
|
{
"resource": ""
}
|
q23091
|
logHammerEvent
|
train
|
function logHammerEvent(ev) {
if(!ev.gesture) {
return;
}
// store last event, that should might match the gremlin
if(ev.gesture.eventType == 'end') {
testLogger.lastEvent = ev;
}
// highlight gesture
var event_el = getLogElement('gesture', ev.type);
event_el.className = 'active';
for(var i = 0, len = hammerProps.length; i < len; i++) {
var prop = hammerProps[i];
var value = ev.gesture[prop];
switch(prop) {
case 'center':
value = value.pageX + 'x' + value.pageY;
break;
case 'gesture':
value = ev.type;
break;
case 'target':
value = ev.gesture.target.tagName;
break;
case 'touches':
value = ev.gesture.touches.length;
break;
}
getLogElement('prop', prop).innerHTML = value;
}
}
|
javascript
|
{
"resource": ""
}
|
q23092
|
train
|
function(attrs, options) {
if (!options.validate || !this.validate) return true;
attrs = _.extend({}, this.attributes, attrs);
var error = this.validationError = this.validate(attrs, options) || null;
if (!error) return true;
this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q23093
|
train
|
function(models, options) {
return this.set(models, _.extend({merge: false}, options, addOptions));
}
|
javascript
|
{
"resource": ""
}
|
|
q23094
|
incrementNbErrors
|
train
|
function incrementNbErrors() {
nbErrors++;
if (nbErrors == config.maxErrors) {
horde.stop();
if (!config.logger) return;
window.setTimeout(function() {
// display the mogwai error after the caught error
config.logger.warn('mogwai ', 'gizmo ', 'stopped test execution after ', config.maxErrors, 'errors');
}, 4);
}
}
|
javascript
|
{
"resource": ""
}
|
q23095
|
executeInSeries
|
train
|
function executeInSeries(callbacks, args, context, done) {
var nbArguments = args.length;
callbacks = callbacks.slice(0); // clone the array to avoid modifying the original
var iterator = function(callbacks, args) {
if (!callbacks.length) {
return typeof done === 'function' ? done() : true;
}
var callback = callbacks.shift();
callback.apply(context, args);
// Is the callback synchronous ?
if (callback.length === nbArguments) {
iterator(callbacks, args, done);
}
};
args.push(function(){
iterator(callbacks, args, done);
});
iterator(callbacks, args, done);
}
|
javascript
|
{
"resource": ""
}
|
q23096
|
train
|
function(callbacks, args) {
if (!callbacks.length) {
return typeof done === 'function' ? done() : true;
}
var callback = callbacks.shift();
callback.apply(context, args);
// Is the callback synchronous ?
if (callback.length === nbArguments) {
iterator(callbacks, args, done);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23097
|
initOptions
|
train
|
function initOptions(options, defaults) {
options || (options = {});
if (!defaults) {
return options;
}
for (var i in defaults) {
if (typeof options[i] === 'undefined') {
options[i] = defaults[i];
}
}
return options;
}
|
javascript
|
{
"resource": ""
}
|
q23098
|
triggerTouch
|
train
|
function triggerTouch(touches, element, type) {
var touchlist = [],
event = document.createEvent('Event');
event.initEvent('touch' + type, true, true);
touchlist.identifiedTouch = touchlist.item = function(index) {
return this[index] || {};
};
touches.forEach(function(touch, i) {
var x = Math.round(touch.x),
y = Math.round(touch.y);
touchlist.push({
pageX: x,
pageY: y,
clientX: x,
clientY: y,
screenX: x,
screenY: y,
target: element,
identifier: i
});
});
event.touches = (type == 'end') ? [] : touchlist;
event.targetTouches = (type == 'end') ? [] : touchlist;
event.changedTouches = touchlist;
element.dispatchEvent(event);
config.showAction(touches);
}
|
javascript
|
{
"resource": ""
}
|
q23099
|
tap
|
train
|
function tap(position, element, done) {
var touches = getTouches(position, 1);
var gesture = {
duration: config.randomizer.integer({ min: 20, max: 700 })
};
triggerTouch(touches, element, 'start');
setTimeout(function() {
triggerTouch(touches, element, 'end');
done(touches, gesture);
}, gesture.duration);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.