_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q6300
|
provide
|
train
|
function provide(nucleus, key, provider) {
provider(preventMultiCall(function (result) {
set(nucleus, key, result);
}));
}
|
javascript
|
{
"resource": ""
}
|
q6301
|
doNext
|
train
|
function doNext() {
if (q) {
q.pending = q.next = (!q.next && q.length) ?
q.shift() : q.next;
q.args = slice.call(arguments, 0);
if (q.pending) {
q.next = 0;
q.pending.apply({}, [preventMultiCall(doNext)].concat(q.args));
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6302
|
train
|
function () {
if (q) {
for (var i = 0, len = arguments.length; i < len; i++) {
q.push(arguments[i]);
if (!q.pending) {
doNext.apply({}, q.args || []);
}
}
}
return me;
}
|
javascript
|
{
"resource": ""
}
|
|
q6303
|
train
|
function () {
delete nucleus.props;
delete nucleus.needs;
delete nucleus.providers;
delete nucleus.listeners;
while (q.length) {
q.pop();
}
nucleus = props = needs = providers = listeners =
q = q.pending = q.next = q.args = 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q6304
|
train
|
function (keyOrList, func) {
var keys = toArray(keyOrList), i = -1, len = keys.length, key;
while (++i < len) {
key = keys[i];
func(key, me.get(key));
}
return me;
}
|
javascript
|
{
"resource": ""
}
|
|
q6305
|
train
|
function (keyOrList, func) {
var result = get(nucleus, keyOrList, func);
return func ? result : typeof keyOrList === 'string' ?
result.values[0] : result.values;
}
|
javascript
|
{
"resource": ""
}
|
|
q6306
|
train
|
function () {
var keys = [];
for (var key in props) {
if (hasOwn.call(props, key)) {
keys.push(key);
}
}
return keys;
}
|
javascript
|
{
"resource": ""
}
|
|
q6307
|
train
|
function (obj) {
for (var p in obj) {
if (hasOwn.call(obj, p)) {
me[p] = obj[p];
}
}
return me;
}
|
javascript
|
{
"resource": ""
}
|
|
q6308
|
train
|
function (keyOrList, func) { // alias: `bind`
listeners.unshift({ keys: toArray(keyOrList), cb: func,
calls: Infinity });
return me;
}
|
javascript
|
{
"resource": ""
}
|
|
q6309
|
train
|
function (keyOrList, func) {
var keys = toArray(keyOrList),
results = get(nucleus, keys),
values = results.values,
missing = results.missing;
if (!missing) {
func.apply({}, values);
} else {
listeners.unshift(
{ keys: keys, cb: func, missing: missing, calls: 1 });
}
return me;
}
|
javascript
|
{
"resource": ""
}
|
|
q6310
|
train
|
function (key, func) {
if (needs[key]) {
provide(nucleus, key, func);
} else if (!providers[key]) {
providers[key] = func;
}
return me;
}
|
javascript
|
{
"resource": ""
}
|
|
q6311
|
train
|
function (keyOrMap, value) {
if (typeof keyOrMap === typeObj) {
for (var key in keyOrMap) {
if (hasOwn.call(keyOrMap, key)) {
set(nucleus, key, keyOrMap[key]);
}
}
} else {
set(nucleus, keyOrMap, value);
}
return me;
}
|
javascript
|
{
"resource": ""
}
|
|
q6312
|
join
|
train
|
function join(separator, itemList) {
var result = "";
for (var i = 0; i < itemList.length; i++) {
if (i > 0) {
result += separator;
}
result += itemList[i];
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q6313
|
similarity
|
train
|
function similarity(left, right, ignoreCase, trim) {
if (left === right) {
return 1;
}
if (TypeUtils.isNullOrUndefined(left) ||
TypeUtils.isNullOrUndefined(right)) {
return 0;
}
if (arguments.length < 4) {
if (arguments.length < 3) {
ignoreCase = false;
}
trim = false;
}
if (ignoreCase) {
left = left.toLowerCase();
right = right.toLowerCase();
}
if (trim) {
left = left.trim();
right = right.trim();
}
var distance = 0;
if (left !== right) {
var matrix = new Array(left.length + 1);
for (var i = 0; i < matrix.length; i++) {
matrix[i] = new Array(right.length + 1);
for (var ii = 0; ii < matrix[i].length; ii++) {
matrix[i][ii] = 0;
}
}
for (var i = 0; i <= left.length; i++) {
// delete
matrix[i][0] = i;
}
for (var j = 0; j <= right.length; j++) {
// insert
matrix[0][j] = j;
}
for (var i = 0; i < left.length; i++) {
for (var j = 0; j < right.length; j++) {
if (left[i] === right[j]) {
matrix[i + 1][j + 1] = matrix[i][j];
}
else {
// delete or insert
matrix[i + 1][j + 1] = Math.min(matrix[i][j + 1] + 1, matrix[i + 1][j] + 1);
// substitution
matrix[i + 1][j + 1] = Math.min(matrix[i + 1][j + 1], matrix[i][j] + 1);
}
}
distance = matrix[left.length][right.length];
}
}
return 1.0 - distance / Math.max(left.length, right.length);
}
|
javascript
|
{
"resource": ""
}
|
q6314
|
train
|
function (filename, callbackFn) {
var self = this;
request.post(this.options.hostAndPort + '/phantom/functions/injectJs', {form:{args:JSON.stringify(arguments)}},
function (error, response, body) {
if (response.statusCode === 200) {
callbackFn && callbackFn.call(self, body);
}
else {
console.error(body);
throw new Error(body);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6315
|
db_import
|
train
|
function db_import(config, src) {
var cmd;
// 1) Create cmd string from Lo-Dash template
var tpl_mysql = grunt.template.process(tpls.mysql, {
data: {
host: config.host,
user: config.user,
pass: config.pass,
database: config.database,
path: src
}
});
// 2) Test whether target MYSQL DB is local or whether requires remote access via SSH
if (typeof config.ssh_host === "undefined") { // it's a local connection
grunt.log.writeln("Importing into local database");
cmd = tpl_mysql + " < " + src;
} else { // it's a remote connection
var tpl_ssh = grunt.template.process(tpls.ssh, {
data: {
host: config.ssh_host
}
});
grunt.log.writeln("Importing DUMP into remote database");
cmd = tpl_ssh + " '" + tpl_mysql + "' < " + src;
}
// Execute cmd
shell.exec(cmd);
grunt.log.oklns("Database imported succesfully");
}
|
javascript
|
{
"resource": ""
}
|
q6316
|
db_dump
|
train
|
function db_dump(config, output_paths) {
var cmd;
grunt.file.mkdir(output_paths.dir);
// 2) Compile MYSQL cmd via Lo-Dash template string
var tpl_mysqldump = grunt.template.process(tpls.mysqldump, {
data: {
user: config.user,
pass: config.pass,
database: config.database,
host: config.host
}
});
// 3) Test whether MYSQL DB is local or whether requires remote access via SSH
if (typeof config.ssh_host === "undefined") { // it's a local connection
grunt.log.writeln("Creating DUMP of local database");
cmd = tpl_mysqldump;
} else { // it's a remote connection
var tpl_ssh = grunt.template.process(tpls.ssh, {
data: {
host: config.ssh_host
}
});
grunt.log.writeln("Creating DUMP of remote database");
cmd = tpl_ssh + " \\ " + tpl_mysqldump;
}
// Capture output...
var output = shell.exec(cmd, {silent: true}).output;
// Write output to file using native Grunt methods
grunt.file.write( output_paths.file, output );
grunt.log.oklns("Database DUMP succesfully exported to: " + output_paths.file);
}
|
javascript
|
{
"resource": ""
}
|
q6317
|
train
|
function (callbackFn) {
var self = this;
request.post(this.options.hostAndPort + '/phantom/functions/exit', {
form:{
}
},
function (error, response, body) {
if (response && response.statusCode === 200) { //server up
self.server.close();
callbackFn && callbackFn.call(self, true);
}
else { //server down
callbackFn.call(self, false);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6318
|
train
|
function (options, callbackFn) {
var self = this;
//compensate for optional options parm
if (typeof options === 'function') {
callbackFn = options;
options = {};
}
//assign default port
options.port = options.port || 1061;
options.host = options.host || 'localhost';
options.hostAndPort = 'http://' + options.host + ':' + options.port;
options.eventStreamPath = require('path').normalize(__dirname + '/../temp/events.txt');
options.phantomjsPath = options.phantomjsPath || 'phantomjs';
options.debug && console.log('creating proxy to %s', options.hostAndPort);
this.options = options;
//try starting server
createServer.call(self, options, function (proxy) {
callbackFn.call(self, proxy);
});
return this;//return this to chain end
}
|
javascript
|
{
"resource": ""
}
|
|
q6319
|
train
|
function (cert, cb) {
var infoObject = {},
subjectElements = [],
err;
var openssl = spawn('openssl', ['req', '-noout', '-subject', '-nameopt', 'RFC2253']);
// Catch stderr
openssl.stderr.on('data', function (out) {
err = new Error(out);
// Callback and return array
return cb(err, infoObject);
});
openssl.stdout.on('data', function (out) {
var data = out.toString();
// Put each line into an array
var lineArray = data.split('\n');
// Filter out empty ones
lineArray = lineArray.filter(function(n){ return n !== undefined && n !== '' });
/* Construct infoObject */
// Certificate
infoObject.certificate = cert;
// Subject
infoObject.subject = {};
// Split by "/" prefix
subjectElements = lineArray[0].replace('subject=', '').split(',');
// For each elements
for (var iS = 0; iS < subjectElements.length; iS++) {
// Split keys and values by "=" separator
var subjectKeyValue = subjectElements[iS].split('=');
infoObject.subject[subjectKeyValue[0]] = subjectKeyValue[1];
}
// Callback and return array
return cb(err, infoObject);
});
openssl.stdin.write(cert);
openssl.stdin.end();
}
|
javascript
|
{
"resource": ""
}
|
|
q6320
|
toBunyan
|
train
|
function toBunyan (obj) {
if (obj.msg && !obj.message) {
obj.message = obj.msg
delete obj.msg
}
if (typeof obj.level === 'number') {
if (obj.level === 20) obj.level = 'debug'
if (obj.level === 30) obj.level = 'info'
if (obj.level === 40) obj.level = 'warn'
if (obj.level === 50) obj.level = 'error'
}
}
|
javascript
|
{
"resource": ""
}
|
q6321
|
mock
|
train
|
function mock (_, mockArgs, fieldArgs, currentValue) {
if (currentValue !== undefined) {
return currentValue;
}
if (mockArgs && mockArgs.with) {
if (fieldArgs) {
try {
return Mustache.render(mockArgs.with, fieldArgs);
} catch (e) {
logger.error(new AntError(
'Coould not renderize field template',
e
));
}
} else {
return mockArgs.with;
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q6322
|
train
|
function(derives, xStart, yStart, h) {
this.derives = derives
this.x = xStart
this.y = yStart || []
this.dimension = this.y.length
this.h = h || 0.01
// cache the k1, k2, k3, k4 of each step
this._k1
this._k2
this._k3
this._k4
}
|
javascript
|
{
"resource": ""
}
|
|
q6323
|
train
|
function() {
var derives = this.derives,
x = this.x,
dimension = this.dimension,
h = this.h
var i, _y = []
// Alias: f() <=> this.derives()
// Xn <=> this.x
// Yn <=> this.y
// H <=> this.h
// K1 <=> this._k1
// calculate _k1: K1 = f(Xn, Yn)
this._k1 = derives(x, this.y)
// calculate _k2: K2 = f(Xn + 0.5 * H, Yn + 0.5 * H * K1)
for (i = 0; i < dimension; i++) {
_y[i] = this.y[i] + h * 0.5 * this._k1[i]
}
this._k2 = derives(x + h * 0.5, _y)
// calculate _k3: K3 = f(Xn + 0.5 * H, Yn + 0.5 * H * K2)
for (i = 0; i < dimension; i++) {
_y[i] = this.y[i] + h * 0.5 * this._k2[i]
}
this._k3 = derives(x + h * 0.5, _y)
// calculate _k4: K4 = f(Xn + H, Yn + H * K3)
for (i = 0; i < dimension; i++) {
_y[i] = this.y[i] + h * this._k3[i]
}
this._k4 = derives(x + h, _y)
// calculate yNext: Y(n + 1) = Yn + H / 6 * (K1 + 2 * K2 + 2 * K3 + K4)
for (i = 0; i < dimension; i++) {
this.y[i] += h / 6 * (this._k1[i] + 2 * this._k2[i] + 2 * this._k3[i] + this._k4[i])
}
// calculate xNext: X(n + 1) = Xn + H
this.x += h
return this.y
}
|
javascript
|
{
"resource": ""
}
|
|
q6324
|
reducer
|
train
|
function reducer() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments[1];
// add initial state
if (action.type === (0, _.generateType)(_.types.add, (0, _get2.default)(action, 'payload.name'))) {
return _extends({}, state, _defineProperty({}, action.payload.name, action.payload.state));
}
// delete state
if (action.type === (0, _.generateType)(_.types.delete, (0, _get2.default)(action, 'payload.name'))) {
var tempState = _extends({}, state);
delete tempState[action.payload.name];
return tempState;
}
// reset to initial state
if (action.type === (0, _.generateType)(_.types.reset, (0, _get2.default)(action, 'payload.name'))) {
return _extends({}, state, _defineProperty({}, action.payload.name, action.payload.state));
}
// shallow merge for state updates
if (action.type === (0, _.generateType)(_.types.set, (0, _get2.default)(action, 'payload.name'))) {
return (0, _immutabilityHelper2.default)(state,
// if store not created with combinedReducers, assume state is top-level
state[action.payload.name] ? _defineProperty({}, action.payload.name, { $merge: action.payload.state }) : { $merge: action.payload.state });
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
q6325
|
suite
|
train
|
function suite() {
process.env.NODESASS_COV = 1;
var coveralls = spawn(bin('coveralls'));
var args = [bin('_mocha')].concat(['--reporter', 'mocha-lcov-reporter']);
var mocha = spawn(process.sass.runtime.execPath, args, {
env: process.env
});
mocha.on('error', function(err) {
console.error(err);
process.exit(1);
});
mocha.stderr.setEncoding('utf8');
mocha.stderr.on('data', function(err) {
console.error(err);
process.exit(1);
});
mocha.stdout.pipe(coveralls.stdin);
}
|
javascript
|
{
"resource": ""
}
|
q6326
|
coverage
|
train
|
function coverage() {
var jscoverage = spawn(bin('jscoverage'), ['lib', 'lib-cov']);
jscoverage.on('error', function(err) {
console.error(err);
process.exit(1);
});
jscoverage.stderr.setEncoding('utf8');
jscoverage.stderr.on('data', function(err) {
console.error(err);
process.exit(1);
});
jscoverage.on('close', suite);
}
|
javascript
|
{
"resource": ""
}
|
q6327
|
destructureMessage
|
train
|
function destructureMessage (msg) {
const keys = Object.keys(msg)
var res = ''
for (var i = 0; i < keys.length; i++) {
var key = keys[i]
var val = msg[key]
if (i !== 0) res += '\n'
res += chalk.blue(' "' + key + '"')
res += ': '
res += chalk.green('"' + val + '"')
}
return res
}
|
javascript
|
{
"resource": ""
}
|
q6328
|
train
|
function(ast) {
if (ast) {
try {
var doc = reader.parse(ast.lines);
} catch(e) {
console.error(e.stack);
console.log('Source : \n* ' + ast.lines.join('\n* '));
return;
}
this.summary = doc.summary;
this.tags = {};
this.annotations = [];
for(var i = 0; i < doc.body.length; i++) {
var child = doc.body[i];
if (child.kind === 'annotation') {
this.annotations.push(child);
} else {
var name = child.kind.toLowerCase();
if (typeof child.name === 'string') {
name = child.name.toLowerCase();
}
if (!this.tags.hasOwnProperty(name)) {
this.tags[name] = [];
}
this.tags[name].push(child);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6329
|
train
|
function(e) {
delete self._pending[filename];
self.emit('error', {
name: filename,
error: e
});
return reject(e);
}
|
javascript
|
{
"resource": ""
}
|
|
q6330
|
_expectUsageInstructions
|
train
|
async function _expectUsageInstructions(args) {
const { stdout, stderr } = await exec(getAntCommand(args));
expect(stdout).not.toBeNull();
expect(stdout.split('\n')[0]).toEqual(
'Usage: ant.js [--help] [--version] [--config <path>] [--verbose] <command>'
);
expect(stdout).toContain(
`Usage: ant.js [--help] [--version] [--config <path>] [--verbose] <command>
[<args>] [<options>]`
);
expect(stdout).toContain(`Commands:
ant.js create <service> [--template Create a new service
<template>]`);
expect(stdout).toContain(
'--help, -h Show help [boolean]'
);
expect(stdout).toContain(
'--version Show version number [boolean]'
);
expect(stdout).toContain(
'--config, -c Path to YAML config file'
);
expect(stdout).toContain(
'--verbose, -v Show execution logs and error stacks [boolean] [default: false]'
);
expect(stdout).toContain(`Plugins:
Core`);
expect(stdout).toContain(
'For more information, visit https://github.com/back4app/antframework'
);
expect(stderr).toEqual('');
}
|
javascript
|
{
"resource": ""
}
|
q6331
|
_expectErrorMessage
|
train
|
async function _expectErrorMessage(args, ...errorMessages) {
expect.hasAssertions();
try {
await exec(getAntCommand(args));
throw new Error('It is expected to throw some error');
} catch (e) {
const { code, stdout, stderr } = e;
expect(code).toEqual(1);
expect(stdout).toEqual('');
for(const errorMessage of errorMessages) {
expect(stderr).toContain(errorMessage);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6332
|
_expectSuccessMessage
|
train
|
async function _expectSuccessMessage(args, ...successMessages) {
const { stdout, stderr } = await exec(getAntCommand(args));
for (const successMessage of successMessages) {
expect(stdout).toContain(successMessage);
}
expect(stderr).toEqual('');
}
|
javascript
|
{
"resource": ""
}
|
q6333
|
_expectPackageVersion
|
train
|
async function _expectPackageVersion(args) {
const packageVersion = require(
path.resolve(__dirname, '../../package.json')
).version;
await _expectSuccessMessage(args, `${packageVersion}\n`);
}
|
javascript
|
{
"resource": ""
}
|
q6334
|
train
|
function(node) {
if (node) {
this.start = {
line: node.start.line,
column: node.start.column
};
this.end = {
line: node.end.line,
column: node.end.column
};
this.offset = {
start: node.start.offset,
end: node.end.offset
};
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6335
|
Amperize
|
train
|
function Amperize(options) {
this.config = _.merge({}, DEFAULTS, options || {});
this.emits = emits;
this.htmlParser = new html.Parser(
new html.DomHandler(this.emits('read'))
);
}
|
javascript
|
{
"resource": ""
}
|
q6336
|
resolve
|
train
|
async function resolve (ant, resolveArgs, fieldArgs, currentValue, model) {
let field = null;
if (model) {
field = model.field;
}
if (ant && resolveArgs && resolveArgs.to) {
const antFunction = ant.functionController.getFunction(resolveArgs.to);
if (!antFunction) {
logger.error(new AntError(
`Could not find "${resolveArgs.to}" function`
));
return null;
}
try {
currentValue = antFunction.run(
currentValue !== undefined ? currentValue : fieldArgs
);
if (currentValue instanceof Observable) {
if (
field &&
field.astNode &&
field.astNode.type &&
field.astNode.type.kind === 'ListType'
) {
return await currentValue.pipe(
flatMap(data => data instanceof Array ? data : [ data ]),
toArray()
).toPromise();
} else {
return await currentValue.toPromise();
}
} else {
return currentValue;
}
} catch (e) {
logger.error(new AntError(
`Could not run "${resolveArgs.to}" function`,
e
));
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q6337
|
dispatchToProps
|
train
|
function dispatchToProps(dispatch) {
return {
add: function add() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var name = arguments[1];
return dispatch({
type: generateType(types.add, name),
payload: {
name: name,
state: state
}
});
},
delete: function _delete(name) {
return dispatch({
type: generateType(types.delete, name),
payload: {
name: name
}
});
},
reset: function reset() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var name = arguments[1];
return dispatch({
type: generateType(types.reset, name),
payload: {
name: name,
state: state
}
});
},
set: function set() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var name = arguments[1];
return dispatch({
type: generateType(types.set, name),
payload: {
name: name,
state: state
}
});
}
};
}
|
javascript
|
{
"resource": ""
}
|
q6338
|
train
|
function (type) {
if (this.has(type)) {
var messages = req.session[_session_key][type];
delete req.session[_session_key][type];
}
return messages||[];
}
|
javascript
|
{
"resource": ""
}
|
|
q6339
|
train
|
function (host, port, cb) {
var err,
data = {};
var openssl = spawn('openssl', ['s_client', '-connect', host + ':' + port, '-servername', host]);
// Clear timeout when execution was successful
openssl.on('exit', function(){
clearTimeout(timeoutTimer);
});
// Catch stderr and search for possible errors
openssl.stderr.on('data', function (out) {
// Search for possible errors in stderr
var errorRegexp = /(Connection refused)|(Can't assign requested address)|(gethostbyname failure)|(getaddrinfo: nodename)/;
var regexTester = errorRegexp.test(out);
// If match, raise error
if (regexTester) {
err = new Error(out.toString().replace(/^\s+|\s+$/g, ''));
// Callback and return array
return cb(err, data);
}
});
openssl.stdout.on('data', function (out) {
var data = out.toString();
// Search for certificate in stdout
var matches = data.match(/-----BEGIN CERTIFICATE-----([\s\S.]*)-----END CERTIFICATE-----/);
try {
data = matches[0];
} catch (e) {
// ... otherwise raise error
err = new Error('Couldn\'t extract certificate for ' + host + ':' + port);
}
// ... callback and return certificate
return cb(err, data);
});
// End stdin (otherwise it'll run indefinitely)
openssl.stdin.end();
// Timeout function to kill in case of errors
var timeoutTimer = setTimeout(function(){
openssl.kill();
// ... otherwise throw error
err = new Error('Time out while trying to extract certificate for ' + host + ':' + port);
// and return
return cb(err, data);
}, 5000);
}
|
javascript
|
{
"resource": ""
}
|
|
q6340
|
applyProxy
|
train
|
function applyProxy(options, cb) {
npmconf.load({}, function (er, conf) {
var proxyUrl;
if (!er) {
proxyUrl = conf.get('https-proxy') ||
conf.get('proxy') ||
conf.get('http-proxy');
}
var env = process.env;
options.proxy = proxyUrl ||
env.HTTPS_PROXY ||
env.https_proxy ||
env.HTTP_PROXY ||
env.http_proxy;
cb(options);
});
}
|
javascript
|
{
"resource": ""
}
|
q6341
|
generateSourceMap
|
train
|
function generateSourceMap ( definition, options ) {
if ( options === void 0 ) { options = {}; }
if ( 'padding' in options ) {
options.offset = options.padding;
if ( !alreadyWarned ) {
console.warn( 'rcu: options.padding is deprecated, use options.offset instead' ); // eslint-disable-line no-console
alreadyWarned = true;
}
}
var mappings = '';
if ( definition.scriptStart ) {
// The generated code probably includes a load of module gubbins - we don't bother
// mapping that to anything, instead we just have a bunch of empty lines
var offset = new Array( ( options.offset || 0 ) + 1 ).join( ';' );
var lines = definition.script.split( '\n' );
var encoded;
if ( options.hires !== false ) {
var previousLineEnd = -definition.scriptStart.column;
encoded = lines.map( function ( line, i ) {
var lineOffset = i === 0 ? definition.scriptStart.line : 1;
var encoded = encode([ 0, 0, lineOffset, -previousLineEnd ]);
var lineEnd = line.length;
for ( var j = 1; j < lineEnd; j += 1 ) {
encoded += ',CAAC';
}
previousLineEnd = i === 0 ?
lineEnd + definition.scriptStart.column :
Math.max( 0, lineEnd - 1 );
return encoded;
});
} else {
encoded = lines.map( function ( line, i ) {
if ( i === 0 ) {
// first mapping points to code immediately following opening <script> tag
return encode([ 0, 0, definition.scriptStart.line, definition.scriptStart.column ]);
}
if ( i === 1 ) {
return encode([ 0, 0, 1, -definition.scriptStart.column ]);
}
return 'AACA'; // equates to [ 0, 0, 1, 0 ];
});
}
mappings = offset + encoded.join( ';' );
}
return new SourceMap({
file: options.file || null,
sources: [ options.source || null ],
sourcesContent: [ definition.source ],
names: [],
mappings: mappings
});
}
|
javascript
|
{
"resource": ""
}
|
q6342
|
handleErrorMessage
|
train
|
function handleErrorMessage (msg, err, command, exitProcess) {
setErrorHandled();
console.error(`Fatal => ${msg}`);
if (err) {
console.error();
if (isVerboseMode()) {
console.error('Error stack:');
console.error(err.stack);
} else {
console.error('For getting the error stack, use --verbose option');
}
}
console.error();
console.error('For getting help:');
console.error(
`${getCliFileName()} --help ${command ? command : '[command]'}`
);
if (!err && msg) {
err = new Error(msg);
}
if (!exitProcess) {
return Analytics.trackError(err).then(() => process.exit(1));
}
process.exit(1);
}
|
javascript
|
{
"resource": ""
}
|
q6343
|
attachFailHandler
|
train
|
function attachFailHandler (yargs, handler) {
yargs.fail((msg, err, usage) => {
// If failure was handled previously, does nothing.
if (errorHandled) {
return;
}
handler(msg, err, usage);
if (errorHandled) {
// Workaround to avoid yargs from running the command.
// Since yargs has no mechanisms to any error handler
// alert the command execution needs to be stopped, and we can't
// exit the process right away due to possible asynchronous
// error handlers, we need a way to prevent the command to be
// ran, since we are handling the error asynchronously.
// Setting this inner flag will prevent yargs to run the command.
yargs._setHasOutput();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q6344
|
executeCommand
|
train
|
async function executeCommand(command, asyncFn) {
try {
await asyncFn();
process.exit(0);
} catch (e) {
handleErrorMessage(e.message, e, command);
}
}
|
javascript
|
{
"resource": ""
}
|
q6345
|
subscribe
|
train
|
async function subscribe (ant, field, directiveArgs, fieldArgs) {
if (ant && field && directiveArgs && directiveArgs.to) {
const antFunction = ant.functionController.getFunction(directiveArgs.to);
if (!antFunction) {
logger.error(new AntError(
`Could not find "${directiveArgs.to}" function`
));
return null;
}
try {
const currentValue = antFunction.run(fieldArgs);
if (currentValue instanceof Observable) {
return new AsyncIterableObserver(field.fieldName, currentValue);
}
return currentValue;
} catch (e) {
logger.error(new AntError(
`Could not run "${directiveArgs.to}" function`,
e
));
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q6346
|
train
|
function(inEvent) {
var eventCopy = Object.create(null);
var p;
for (var i = 0; i < CLONE_PROPS.length; i++) {
p = CLONE_PROPS[i];
eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i];
// Work around SVGInstanceElement shadow tree
// Return the <use> element that is represented by the instance for Safari, Chrome, IE.
// This is the behavior implemented by Firefox.
if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) {
if (eventCopy[p] instanceof SVGElementInstance) {
eventCopy[p] = eventCopy[p].correspondingUseElement;
}
}
}
// keep the semantics of preventDefault
if (inEvent.preventDefault) {
eventCopy.preventDefault = function() {
inEvent.preventDefault();
};
}
return eventCopy;
}
|
javascript
|
{
"resource": ""
}
|
|
q6347
|
train
|
function(inEvent) {
var lts = mouse.lastTouches;
var t = inEvent.changedTouches[0];
// only the primary finger will synth mouse events
if (this.isPrimaryTouch(t)) {
// remember x/y of last touch
var lt = { x: t.clientX, y: t.clientY };
lts.push(lt);
var fn = (function(lts, lt) {
var i = lts.indexOf(lt);
if (i > -1) {
lts.splice(i, 1);
}
}).bind(null, lts, lt);
setTimeout(fn, DEDUP_TIMEOUT);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6348
|
train
|
function(name, bool, node) {
node = node || this;
if (arguments.length == 1) {
bool = !node.hasAttribute(name) || node.getAttribute(name) == 'false';
}
bool ? node.setAttribute(name, 'true') : node.setAttribute(name, 'false');
}
|
javascript
|
{
"resource": ""
}
|
|
q6349
|
generateSchema
|
train
|
function generateSchema(ant, graphQL, _model) {
let model = [];
if (graphQL) {
for (const directive of graphQL.directiveController.directives) {
const directiveDefinition = graphQL.directiveController
.getDirectiveDefinition(directive);
if (directiveDefinition) {
model.push(directiveDefinition);
}
}
}
if (_model === undefined && graphQL) {
_model = graphQL.getModel();
}
if (_model) {
model.push(_model);
}
model = model.join('\n');
if (model.length) {
const astDocument = parse(model);
const schema = buildASTSchema(astDocument);
// This code will be better componentized and improved. Essentially it
// visits a GraphQL schema and look for each of its types, then each of
// the fields of the types that were found before and finally each of the
// directives of the fields that were found before. If it is a "mock"
// directive, a resolve function is attached to the field.
for (const typeName in schema._typeMap) {
const type = schema._typeMap[typeName];
for (const fieldName in type._fields) {
const field = type._fields[fieldName];
if (field.astNode && field.astNode.directives) {
for (const directive of field.astNode.directives) {
const directiveName = directive.name.value;
let directiveResolved = false;
if (graphQL) {
const antDirective = graphQL.directiveController
.getDirective(directiveName);
if (antDirective) {
directiveResolved = true;
const directiveArgs = {};
for (const arg of directive.arguments) {
directiveArgs[arg.name.value] = arg.value.value;
}
if (directiveName === 'subscribe') {
field.subscribe = (source, fieldArgs, context, info) => antDirective.resolver.run(
ant,
info,
directiveArgs,
fieldArgs
);
continue;
}
const currentResolver = field.resolve;
const directiveResolver = antDirective.resolver;
field.resolve = (_, fieldArgs) => {
// We can't provide Ant to any kind of AntFunction, due to
// serialization issues, so the class check is needed here
const resolvedValue = directiveResolver.run(
directiveResolver.constructor.name === AntFunction.name ? ant : undefined,
directiveArgs,
fieldArgs,
currentResolver ? currentResolver(_, fieldArgs) : undefined,
{ type, field, directive }
);
// The resolver should garantee the content resolved is compatible
// with the type specified in the GraphQL model.
// If the GraphQL model requires an Array and the resolver returns an
// Observable, for instance, the resolver needs to pipe its Observable
// into toArray before returning it; since there is no way
// to predict what the resolver implementation returns and treat it somehow.
if (resolvedValue instanceof Observable) {
return resolvedValue.toPromise();
}
return resolvedValue;
};
}
}
if (!directiveResolved) {
logger.error(`Could not find "${directiveName}" directive`);
}
}
}
}
}
const errors = validateSchema(schema);
if (errors && errors.length) {
logger.error(
'There were some errors when validating the GraphQL schema:'
);
errors.forEach(error => logger.error(error.toString()));
}
return schema;
} else {
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
q6350
|
train
|
function(url, callback) {
url = getBaseUrl() + url;
http.get(url, function(response) {
var output = "";
response.on('data', function (chunk) {
output += chunk;
});
response.on('end', function() {
output = JSON.parse(output);
if (debug) {console.log(output);}
if (output == undefined) {
output = {
LL: {
Code: 500,
value: undefined,
message: 'Unable to get response from Loxone Miniserver'
}
}
}
// return our current value
callback(output);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
callback({
LL: {
Code: 500,
value: undefined,
message: e.message
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6351
|
facetAO
|
train
|
function facetAO(a00, a01, a02,
a10, a12,
a20, a21, a22) {
var s00 = (a00&OPAQUE_BIT) ? 1 : 0
, s01 = (a01&OPAQUE_BIT) ? 1 : 0
, s02 = (a02&OPAQUE_BIT) ? 1 : 0
, s10 = (a10&OPAQUE_BIT) ? 1 : 0
, s12 = (a12&OPAQUE_BIT) ? 1 : 0
, s20 = (a20&OPAQUE_BIT) ? 1 : 0
, s21 = (a21&OPAQUE_BIT) ? 1 : 0
, s22 = (a22&OPAQUE_BIT) ? 1 : 0
return (vertexAO(s10, s01, s00)<< AO_SHIFT) +
(vertexAO(s01, s12, s02)<<(AO_SHIFT+AO_BITS)) +
(vertexAO(s12, s21, s22)<<(AO_SHIFT+2*AO_BITS)) +
(vertexAO(s21, s10, s20)<<(AO_SHIFT+3*AO_BITS))
}
|
javascript
|
{
"resource": ""
}
|
q6352
|
generateSurfaceVoxel
|
train
|
function generateSurfaceVoxel(
v000, v001, v002,
v010, v011, v012,
v020, v021, v022,
v100, v101, v102,
v110, v111, v112,
v120, v121, v122) {
var t0 = !(v011 & OPAQUE_BIT)
, t1 = !(v111 & OPAQUE_BIT)
if(v111 && (!v011 || (t0 && !t1))) {
return v111 | FLIP_BIT | facetAO(v000, v001, v002,
v010, v012,
v020, v021, v022)
} else if(v011 && (!v111 || (t1 && !t0)) ) {
return v011 | facetAO(v100, v101, v102,
v110, v112,
v120, v121, v122)
}
}
|
javascript
|
{
"resource": ""
}
|
q6353
|
ForecastIoAPIError
|
train
|
function ForecastIoAPIError(url, statusCode, body) {
this.response = {
statusCode: statusCode,
body: body
};
this.message = this._formatErrorMessage(body);
this.name = "ForecastIoAPIError";
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.request = "GET " + url;
}
|
javascript
|
{
"resource": ""
}
|
q6354
|
getRuntimeInfo
|
train
|
function getRuntimeInfo() {
var execPath = fs.realpathSync(process.execPath); // resolve symbolic link
var runtime = execPath
.split(/[\\/]+/).pop()
.split('.').shift();
runtime = runtime === 'nodejs' ? 'node' : runtime;
return {
name: runtime,
execPath: execPath
};
}
|
javascript
|
{
"resource": ""
}
|
q6355
|
getBinaryUrl
|
train
|
function getBinaryUrl() {
var site = flags['--sass-binary-site'] ||
process.env.SASS_BINARY_SITE ||
pkg.nodeSassConfig.binarySite;
return [site, 'v' + pkg.version, sass.binaryName].join('/');
}
|
javascript
|
{
"resource": ""
}
|
q6356
|
train
|
function (where) {
if (where !== undefined) {
if (where.gene !== undefined) {
get_gene(where);
return;
} else {
if (where.species === undefined) {
where.species = genome_browser.species();
} else {
genome_browser.species(where.species);
}
if (where.chr === undefined) {
where.chr = genome_browser.chr();
} else {
genome_browser.chr(where.chr);
}
if (where.from === undefined) {
where.from = genome_browser.from();
} else {
genome_browser.from(where.from);
}
if (where.to === undefined) {
where.to = genome_browser.to();
} else {
genome_browser.to(where.to);
}
}
} else { // "where" is undef so look for gene or loc
if (genome_browser.gene() !== undefined) {
get_gene({ species : genome_browser.species(),
gene : genome_browser.gene()
});
return;
} else {
where = {};
where.species = genome_browser.species();
where.chr = genome_browser.chr();
where.from = genome_browser.from();
where.to = genome_browser.to();
}
}
// Min is 0 by default or use the provided promise
conf.min_coord
.then (function (min) {
genome_browser.min(min);
if (!conf.max_coord) {
var url = ensembl_rest.url()
.endpoint("info/assembly/:species/:region_name")
.parameters({
species: where.species,
region_name: where.chr
});
conf.max_coord = ensembl_rest.call (url)
.then (function (resp) {
return resp.body.length;
});
}
return conf.max_coord;
})
.then (function (max) {
genome_browser.max(max);
genome_browser._start();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6357
|
train
|
function (node, type, callback) {
if (node.addEventListener) {
node.addEventListener(type, function (e) {
callback(e, e.target)
}, false)
} else if (node.attachEvent) {
node.attachEvent('on' + type, function (e) {
callback(e, e.srcElement)
})
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6358
|
train
|
function (node, callback) {
GOVUK.details.addEvent(node, 'keypress', function (e, target) {
// When the key gets pressed - check if it is enter or space
if (GOVUK.details.charCode(e) === GOVUK.details.KEY_ENTER || GOVUK.details.charCode(e) === GOVUK.details.KEY_SPACE) {
if (target.nodeName.toLowerCase() === 'summary') {
// Prevent space from scrolling the page
// and enter from submitting a form
GOVUK.details.preventDefault(e)
// Click to let the click event do all the necessary action
if (target.click) {
target.click()
} else {
// except Safari 5.1 and under don't support .click() here
callback(e, target)
}
}
}
})
// Prevent keyup to prevent clicking twice in Firefox when using space key
GOVUK.details.addEvent(node, 'keyup', function (e, target) {
if (GOVUK.details.charCode(e) === GOVUK.details.KEY_SPACE) {
if (target.nodeName === 'SUMMARY') {
GOVUK.details.preventDefault(e)
}
}
})
GOVUK.details.addEvent(node, 'click', function (e, target) {
callback(e, target)
})
}
|
javascript
|
{
"resource": ""
}
|
|
q6359
|
train
|
function (node, match) {
do {
if (!node || node.nodeName.toLowerCase() === match) {
break
}
node = node.parentNode
} while (node)
return node
}
|
javascript
|
{
"resource": ""
}
|
|
q6360
|
train
|
function (summary) {
var expanded = summary.__details.__summary.getAttribute('aria-expanded') === 'true'
var hidden = summary.__details.__content.getAttribute('aria-hidden') === 'true'
summary.__details.__summary.setAttribute('aria-expanded', (expanded ? 'false' : 'true'))
summary.__details.__content.setAttribute('aria-hidden', (hidden ? 'false' : 'true'))
if (!GOVUK.details.NATIVE_DETAILS) {
summary.__details.__content.style.display = (expanded ? 'none' : '')
var hasOpenAttr = summary.__details.getAttribute('open') !== null
if (!hasOpenAttr) {
summary.__details.setAttribute('open', 'open')
} else {
summary.__details.removeAttribute('open')
}
}
if (summary.__twisty) {
summary.__twisty.firstChild.nodeValue = (expanded ? '\u25ba' : '\u25bc')
summary.__twisty.setAttribute('class', (expanded ? 'arrow arrow-closed' : 'arrow arrow-open'))
}
return true
}
|
javascript
|
{
"resource": ""
}
|
|
q6361
|
train
|
function ($container) {
GOVUK.details.addEvent(document, 'DOMContentLoaded', GOVUK.details.addDetailsPolyfill)
GOVUK.details.addEvent(window, 'load', GOVUK.details.addDetailsPolyfill)
}
|
javascript
|
{
"resource": ""
}
|
|
q6362
|
undef
|
train
|
function undef(w, i, depth, probs) {
if (depth <= 1) return typeof probs[w[i]] === "undefined";
if (typeof probs[w[i]] === "undefined") return true;
return undef(w, i + 1, depth - 1, probs[w[i]]);
}
|
javascript
|
{
"resource": ""
}
|
q6363
|
trainTuples
|
train
|
function trainTuples(words) {
var probs = {};
var count = 0;
words.forEach(function(w) {
w = clean(w);
for (var i = 0; i < w.length - 1; i++) {
if (!probs[w[i]]) probs[w[i]] = {};
if (!probs[w[i]][w[i + 1]]) probs[w[i]][w[i + 1]] = 1;
else probs[w[i]][w[i + 1]]++;
count++;
}
});
Object.keys(probs).forEach(function(first) {
Object.keys(probs[first]).forEach(function(second) {
probs[first][second] = percent(probs[first][second], count);
});
});
return probs;
}
|
javascript
|
{
"resource": ""
}
|
q6364
|
trainTriples
|
train
|
function trainTriples(words) {
var probs = {};
var count = 0;
words.forEach(function(w) {
w = clean(w);
for (var i = 0; i < w.length - 2; i++) {
if (!probs[w[i]]) probs[w[i]] = {};
if (!probs[w[i]][w[i + 1]]) probs[w[i]][w[i + 1]] = {};
if (!probs[w[i]][w[i + 1]][w[i + 2]]) probs[w[i]][w[i + 1]][w[i + 2]] = 1;
else probs[w[i]][w[i + 1]][w[i + 2]]++;
count++;
}
});
Object.keys(probs).forEach(function(first) {
Object.keys(probs[first]).forEach(function(second) {
Object.keys(probs[first][second]).forEach(function(third) {
probs[first][second][third] = percent(
probs[first][second][third],
count
);
});
});
});
return probs;
}
|
javascript
|
{
"resource": ""
}
|
q6365
|
train
|
function(apiKey, contactId, creditCardId,
payPlanId, productIds, subscriptionPlanIds, processSpecials,
promoCodes, _leadAffiliatedId, _affiliatedId) {}
|
javascript
|
{
"resource": ""
}
|
|
q6366
|
equals
|
train
|
function equals(first, second){
//If are the same instance, true
if (first === second)
return true;
//If values are equals, return true
if (first == second)
return true;
//If different type, false
if (typeof first != typeof second)
return false;
//If are not objects, check value
if (typeof first != "object")
return first == second;
//For each property on first
for (var current in first){
//Get property value from each element
var firstValue = first[current];
var secondValue = second[current];
//If current is object, invoke "Equals" on each
//member of the object; otherwise just check values
var isEqual = (typeof firstValue === 'object') ? equals(firstValue, secondValue) : firstValue == secondValue;
//If not equals, exit
if (!isEqual)
return false;
}
//Confirm
return true;
}
|
javascript
|
{
"resource": ""
}
|
q6367
|
train
|
function(a, b){
//Get value for "a" and "b" element
var aValue = expression(a);
var bValue = expression(b);
//Check if one element is greater then the second one
if(aValue < bValue) return -1;
if(aValue > bValue) return 1;
return 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q6368
|
subtract
|
train
|
function subtract(otherData, compareExpression) {
//If other data is invalid, return empty array
if (!otherData)
return new jslinq([]);
//Data for output
var outData = [];
//Check every element of "items"
for (var n = 0; n < this.items.length; n++) {
//Current element on items
var currentOnItems = this.items[n];
//Set flag of "found match" as false
var aMatchWasFound = false;
//Check every element on "otherData"
for (var i = 0; i < otherData.length; i++) {
//If a match was already found, skip
if (aMatchWasFound)
continue;
//Current element on "otherData"
var currentOnOtherData = otherData[i];
//Fails by default matching of elements
var doesMatch = false;
//If compare expression was not set
if (!compareExpression){
//Compare on same instance
//doesMatch = currentOnItems == currentOnOtherData;
doesMatch = equals(currentOnItems, currentOnOtherData);
}
else{
//Calculate comparison value for each element
var comparisonForItems = compareExpression(currentOnItems);
var comparisonForOtherData = compareExpression(currentOnOtherData);
//Compare result of compare expressions
//doesMatch = comparisonForItems == comparisonForOtherData;
doesMatch = equals(comparisonForItems, comparisonForOtherData);
}
//If there's a match, set the flag
if (doesMatch){
aMatchWasFound = true;
}
}
//If no match was found, append element to output
if (!aMatchWasFound){
outData.push(currentOnItems);
}
}
//Return for chaining
return new jslinq(outData);
}
|
javascript
|
{
"resource": ""
}
|
q6369
|
transformer
|
train
|
function transformer(tree, file) {
search(tree, phrases, searcher)
function searcher(match, index, parent, phrase) {
var type = weasel
var message
if (weasels.indexOf(phrase) === -1) {
type = fillers.indexOf(phrase) === -1 ? hedge : filler
}
message = file.warn(
'Don’t use ' + quote(toString(match), '“', '”') + ', ' + messages[type],
{
start: position.start(match[0]),
end: position.end(match[match.length - 1])
}
)
message.ruleId = type
message.source = 'retext-intensify'
}
}
|
javascript
|
{
"resource": ""
}
|
q6370
|
buildHTML
|
train
|
function buildHTML(navigation, first, sParentLink) {
return '<ul class="nav' + (first ? ' sidenav' : '') + '">' + navigation.map(function(loc) {
if (!loc || !loc.link) return '';
loc.link = (opts.parentLink && sParentLink ? sParentLink + '-' : '') + loc.link;
loc.$ele.attr('id', loc.link);
return '<li><a href="#' + loc.link + '">' + escape(loc.text) + '</a>' + (loc.children ? buildHTML(loc.children, false, loc.link) : '') + '</li>';
}).join('\n') + '</ul>';
}
|
javascript
|
{
"resource": ""
}
|
q6371
|
train
|
function(arrayOfSearchResultsArrays) {
let ids = {};
let dedupedResults = [];
_.each(arrayOfSearchResultsArrays, (searchResults) => {
_.each(searchResults, (item) => {
if (! ids.hasOwnProperty(item._id)) {
ids[item._id] = true;
dedupedResults.push(item);
}
});
});
return dedupedResults;
}
|
javascript
|
{
"resource": ""
}
|
|
q6372
|
logOrThrow
|
train
|
function logOrThrow(error, result) {
if (result) {
self.log('connect-azuretables created table ' + self.table);
}
if (error) {
throw ('failed to create table: ' + error);
}
}
|
javascript
|
{
"resource": ""
}
|
q6373
|
errorOrResult
|
train
|
function errorOrResult(error, result, fn) {
return error ? fn(error) : fn(null, result);
}
|
javascript
|
{
"resource": ""
}
|
q6374
|
getExpiryDate
|
train
|
function getExpiryDate(store, data) {
var offset;
if (data.cookie.originalMaxAge) {
offset = data.cookie.originalMaxAge;
} else {
offset = store.sessionTimeOut * 60000;
}
return offset ? new Date(Date.now() + offset) : null;
}
|
javascript
|
{
"resource": ""
}
|
q6375
|
startListening
|
train
|
function startListening () {
if (isBuilt === false) {
app.listen(
parseInt(port),
host,
() => {
isBuilt = true
console.log(chalk.green(`[React Emoji Component SSR] ${host}:${port}`))
}
)
}
}
|
javascript
|
{
"resource": ""
}
|
q6376
|
magnify
|
train
|
function magnify( rect, scale ) {
var scrollOffset = getScrollOffset();
// Ensure a width/height is set
rect.width = rect.width || 1;
rect.height = rect.height || 1;
// Center the rect within the zoomed viewport
rect.x -= ( window.innerWidth - ( rect.width * scale ) ) / 2;
rect.y -= ( window.innerHeight - ( rect.height * scale ) ) / 2;
if( supportsTransforms ) {
// Reset
if( scale === 1 ) {
document.body.style.transform = '';
document.body.style.OTransform = '';
document.body.style.msTransform = '';
document.body.style.MozTransform = '';
document.body.style.WebkitTransform = '';
}
// Scale
else {
var origin = scrollOffset.x +'px '+ scrollOffset.y +'px',
transform = 'translate('+ -rect.x +'px,'+ -rect.y +'px) scale('+ scale +')';
document.body.style.transformOrigin = origin;
document.body.style.OTransformOrigin = origin;
document.body.style.msTransformOrigin = origin;
document.body.style.MozTransformOrigin = origin;
document.body.style.WebkitTransformOrigin = origin;
document.body.style.transform = transform;
document.body.style.OTransform = transform;
document.body.style.msTransform = transform;
document.body.style.MozTransform = transform;
document.body.style.WebkitTransform = transform;
}
}
else {
// Reset
if( scale === 1 ) {
document.body.style.position = '';
document.body.style.left = '';
document.body.style.top = '';
document.body.style.width = '';
document.body.style.height = '';
document.body.style.zoom = '';
}
// Scale
else {
document.body.style.position = 'relative';
document.body.style.left = ( - ( scrollOffset.x + rect.x ) / scale ) + 'px';
document.body.style.top = ( - ( scrollOffset.y + rect.y ) / scale ) + 'px';
document.body.style.width = ( scale * 100 ) + '%';
document.body.style.height = ( scale * 100 ) + '%';
document.body.style.zoom = scale;
}
}
level = scale;
if( document.documentElement.classList ) {
if( level !== 1 ) {
document.documentElement.classList.add( 'zoomed' );
}
else {
document.documentElement.classList.remove( 'zoomed' );
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6377
|
train
|
function(T)
{
var ret = [];
_(typedef.signature(T)).each(function(info, key) {
if (info.decorations.FIELD)
ret.push(key);
});
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q6378
|
train
|
function(o)
{
var q = this.clone();
q._orderBy = o;
q._ascending = true;
return q;
}
|
javascript
|
{
"resource": ""
}
|
|
q6379
|
train
|
function(f)
{
var q = this.clone();
if (arguments.length > 1)
q._fields = _(arguments).toArray();
else if (f)
q._fields = _(f).isArray() ? f : [f];
else
q._fields = Queryable.getFields(this._T);
return q;
}
|
javascript
|
{
"resource": ""
}
|
|
q6380
|
train
|
function()
{
if (this._executePromise)
return this._executePromise;
var q = this.clone();
var table = q._T.__name__;
var page = q._page;
var fields = q._fields;
// Create the query from our stuff
var query = {};
_(q._where.concat(q._like)).each(function (q) {
query[q.key] = q.value;
});
var doneLoading = Q.defer();
this._executePromise = doneLoading.promise;
var left = q._take;
// A single iteration of fetching via the API. Called repeatedly in
// the case of large / unbounded TAKES
var loop = function() {
// always take 1000 unless we're almost done
var take = left < 1000 ? left : 1000;
// Hit the API and incremement the page
q._fetch(table, take, page++, query, fields).then(function(res) {
// publish progress
doneLoading.notify(q._results.length);
if (left !== undefined) left -= res.length;
// Either resolve the the promise with the results if we're
// done or call the loop again
if (q._doneLoading || left <= 0)
doneLoading.resolve(q._getResults());
else
process.nextTick(loop);
}).catch(function(err) {
doneLoading.reject(err);
});
};
// do tha damn thing
loop();
return doneLoading.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q6381
|
train
|
function(table, limit, page, query, fields)
{
if (this._doneLoading)
return;
var _this = this;
// Execute -- add orderBy and ascending?
var args = [table, limit, page, query, fields];
if (this._orderBy) {
args.push(this._orderBy);
args.push(this._ascending);
}
var p = this.dataService.query.apply(this.dataService.query, args)
// Pack results back into <T> and add it to our _results array
.then(function(results) {
results.forEach(function(r) {
var obj = new _this._T();
_(r).each(function(value, key) {
obj[key] = value;
});
_this._results.push(obj);
});
// If we hit the last page
if (results.length !== limit)
_this._doneLoading = true;
return _this._results;
});
return p;
}
|
javascript
|
{
"resource": ""
}
|
|
q6382
|
train
|
function(apiKey, pieceTitle, categories,
fromAddress, toAddress, ccAddress, bccAddress, subject, textBody,
htmlBody, contentType, mergeContext) {}
|
javascript
|
{
"resource": ""
}
|
|
q6383
|
train
|
function(apiKey, contactId, fromName,
fromAddress, toAddress, ccAddresses, bccAddresses, contentType,
subject, htmlBody, textBody, header, receivedDate, sentDate,
emailSentType) {}
|
javascript
|
{
"resource": ""
}
|
|
q6384
|
train
|
function(apiKey, contactList, fromAddress,
toAddress, ccAddresses, bccAddresses, contentType, subject, htmlBody,
textBody, _templateId) {}
|
javascript
|
{
"resource": ""
}
|
|
q6385
|
train
|
function(apiKey, templateId, pieceTitle,
category, fromAddress, toAddress, ccAddress, bccAddresses, subject,
textBody, htmlBody, contentType, mergeContext) {}
|
javascript
|
{
"resource": ""
}
|
|
q6386
|
parentIsAllowedAtRule
|
train
|
function parentIsAllowedAtRule(rule) {
return (
rule.parent &&
rule.parent.type === 'atrule' &&
!/(?:media|supports|for)$/.test(rule.parent.name)
)
}
|
javascript
|
{
"resource": ""
}
|
q6387
|
hasParentRule
|
train
|
function hasParentRule(rule) {
if (!rule.parent) {
return false
}
if (rule.parent.type === 'rule') {
return true
}
return hasParentRule(rule.parent)
}
|
javascript
|
{
"resource": ""
}
|
q6388
|
regexpToGlobalRegexp
|
train
|
function regexpToGlobalRegexp(regexp) {
let source = regexp instanceof RegExp ? regexp.source : regexp
return new RegExp(source, 'g')
}
|
javascript
|
{
"resource": ""
}
|
q6389
|
init
|
train
|
function init ($container, elementSelector, eventSelectors, handler) {
$container = $container || $(document.body)
// Handle control clicks
function deferred () {
var $control = $(this)
handler($control, getToggledContent($control))
}
// Prepare ARIA attributes
var $controls = $(elementSelector)
$controls.each(initToggledContent)
// Handle events
$.each(eventSelectors, function (idx, eventSelector) {
$container.on('click.' + selectors.namespace, eventSelector, deferred)
})
// Any already :checked on init?
if ($controls.is(':checked')) {
$controls.filter(':checked').each(deferred)
}
}
|
javascript
|
{
"resource": ""
}
|
q6390
|
getEventSelectorsForRadioGroups
|
train
|
function getEventSelectorsForRadioGroups () {
var radioGroups = []
// Build an array of radio group selectors
return $(selectors.radio).map(function () {
var groupName = $(this).attr('name')
if ($.inArray(groupName, radioGroups) === -1) {
radioGroups.push(groupName)
return 'input[type="radio"][name="' + $(this).attr('name') + '"]'
}
return null
})
}
|
javascript
|
{
"resource": ""
}
|
q6391
|
getIndex
|
train
|
function getIndex(objects, obj) {
var i;
for (i = 0; i < objects.length; i++) {
if (objects[i] === obj) {
return i;
}
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
q6392
|
train
|
function()
{
var _this = this;
_(api.services).each(function(service, key) {
_this._addService(service);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6393
|
train
|
function(T)
{
var tName = inflection.pluralize(T.__name__);
this[tName] = new Queryable(T, this.DataService);
}
|
javascript
|
{
"resource": ""
}
|
|
q6394
|
train
|
function(iface)
{
var hash = {};
var collection = iface.__name__.substring(1);
var dataContext = this;
_(typedef.signature(iface)).each(function (info, key) {
// create the function that calls method call and returns a promise
hash[key] = function() {
var args = [dataContext.apiKey].concat(_(arguments).toArray());
//http://community.infusionsoft.com/showthread.php/2140-API-vs-Web-Form?p=8853&viewfull=1#post8853
//There is an issue in the sendTemplate function, it needs to be sendEmail
if (key == 'sendTemplate') {
key = 'sendEmail';
}
var methodName = collection + '.' + key;
var d = Q.defer();
dataContext.client.methodCall(methodName, args, d.makeNodeResolver());
return d.promise;
};
});
// instantiate a version of this class
this[collection] = new (typedef.class(collection).define(hash))();
}
|
javascript
|
{
"resource": ""
}
|
|
q6395
|
Dialog
|
train
|
function Dialog(options) {
ui.Emitter.call(this);
options = options || {};
this.template = html;
this.el = $(this.template);
this.render(options);
if (active && !active.hiding) active.hide();
if (Dialog.effect) this.effect(Dialog.effect);
active = this;
}
|
javascript
|
{
"resource": ""
}
|
q6396
|
ColorPicker
|
train
|
function ColorPicker() {
ui.Emitter.call(this);
this._colorPos = {};
this.el = $(html);
this.main = this.el.find('.main').get(0);
this.spectrum = this.el.find('.spectrum').get(0);
$(this.main).bind('selectstart', function(e){ e.preventDefault() });
$(this.spectrum).bind('selectstart', function(e){ e.preventDefault() });
this.hue(rgb(255, 0, 0));
this.spectrumEvents();
this.mainEvents();
this.w = 180;
this.h = 180;
this.render();
}
|
javascript
|
{
"resource": ""
}
|
q6397
|
type
|
train
|
function type(type) {
return function(title, msg){
return exports.notify.apply(this, arguments)
.type(type);
}
}
|
javascript
|
{
"resource": ""
}
|
q6398
|
Notification
|
train
|
function Notification(options) {
ui.Emitter.call(this);
options = options || {};
this.template = html;
this.el = $(this.template);
this.render(options);
if (Notification.effect) this.effect(Notification.effect);
}
|
javascript
|
{
"resource": ""
}
|
q6399
|
SplitButton
|
train
|
function SplitButton(label) {
ui.Emitter.call(this);
this.el = $(html);
this.events();
this.render({ label: label });
this.state = 'hidden';
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.