_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q28000 | defineNativeMethodsOnChainable | train | function defineNativeMethodsOnChainable() {
var nativeTokens = {
'Function': 'apply,call',
'RegExp': 'compile,exec,test',
'Number': 'toExponential,toFixed,toLocaleString,toPrecision',
'Object': 'hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString',
'Array': 'concat,join,pop,push,reverse,shift,slice,sort,splice,toLocaleString,unshift',
'Date': 'getTime,getTimezoneOffset,setTime,toDateString,toGMTString,toLocaleDateString,toLocaleString,toLocaleTimeString,toTimeString,toUTCString',
'String': 'anchor,big,blink,bold,charAt,charCodeAt,concat,fixed,fontcolor,fontsize,indexOf,italics,lastIndexOf,link,localeCompare,match,replace,search,slice,small,split,strike,sub,substr,substring,sup,toLocaleLowerCase,toLocaleUpperCase,toLowerCase,toUpperCase'
};
var dateTokens = 'FullYear,Month,Date,Hours,Minutes,Seconds,Milliseconds'.split(',');
function addDateTokens(prefix, arr) {
for (var i = 0; i < dateTokens.length; i++) {
arr.push(prefix + dateTokens[i]);
}
}
forEachProperty(nativeTokens, function(str, name) {
var tokens = str.split(',');
if (name === 'Date') {
addDateTokens('get', tokens);
addDateTokens('set', tokens);
addDateTokens('getUTC', tokens);
addDateTokens('setUTC', tokens);
}
tokens.push('toString');
mapNativeToChainable(name, tokens);
});
} | javascript | {
"resource": ""
} |
q28001 | showHelp | train | function showHelp(specifiedScripts) {
if (parsedArgv.help) {
// if --help was specified, then yargs will show the default help
log.info(help(psConfig))
return true
}
const helpStyle = String(psConfig.options['help-style'])
const hasDefaultScript = Boolean(psConfig.scripts.default)
const noScriptSpecifiedAndNoDefault =
!specifiedScripts.length && !hasDefaultScript
const hasHelpScript = Boolean(psConfig.scripts.help)
const commandIsHelp =
isEqual(specifiedScripts[0], 'help') && !hasHelpScript
const shouldShowSpecificScriptHelp =
commandIsHelp && specifiedScripts.length > 1
if (shouldShowSpecificScriptHelp) {
log.info(specificHelpScript(psConfig, specifiedScripts[1]))
return true
} else if (commandIsHelp || noScriptSpecifiedAndNoDefault) {
// Can't achieve 100% branch coverage without refactoring this showHelp()
// function into ./index.js and re-working existing tests and such. Branch
// options aren't relevant here either, so telling Istanbul to ignore.
/* istanbul ignore next */
if (helpStyle === 'all') {
parser.showHelp('log')
}
log.info(help(psConfig))
return true
}
return false
} | javascript | {
"resource": ""
} |
q28002 | stringifyObject | train | function stringifyObject(object, indent) {
return Object.keys(object).reduce((string, key, index) => {
const script = object[key]
let value
if (isPlainObject(script)) {
value = `{${stringifyObject(script, `${indent} `)}\n${indent}}`
} else {
value = `'${escapeSingleQuote(script)}'`
}
const comma = getComma(isLast(object, index))
return `${string}\n${indent}${key}: ${value}${comma}`
}, '')
} | javascript | {
"resource": ""
} |
q28003 | loadConfig | train | function loadConfig(configPath, input) {
let config
if (configPath.endsWith('.yml') || configPath.endsWith('.yaml')) {
config = loadYAMLConfig(configPath)
} else {
config = loadJSConfig(configPath)
}
if (isUndefined(config)) {
// let the caller deal with this
return config
}
let typeMessage = `Your config data type was`
if (isFunction(config)) {
config = config(input)
typeMessage = `${typeMessage} a function which returned`
}
const emptyConfig = isEmpty(config)
const plainObjectConfig = isPlainObject(config)
if (plainObjectConfig && emptyConfig) {
typeMessage = `${typeMessage} an object, but it was empty`
} else {
typeMessage = `${typeMessage} a data type of "${typeOf(config)}"`
}
if (!plainObjectConfig || emptyConfig) {
log.error({
message: chalk.red(
oneLine`
The package-scripts configuration
("${configPath.replace(/\\/g, '/')}") must be a non-empty object
or a function that returns a non-empty object.
`,
),
ref: 'config-must-be-an-object',
})
throw new Error(typeMessage)
}
const defaultConfig = {
options: {
'help-style': 'all',
},
}
return {...defaultConfig, ...config}
} | javascript | {
"resource": ""
} |
q28004 | addData | train | function addData (db, mime, source) {
Object.keys(mime).forEach(function (key) {
var data = mime[key]
var type = key.toLowerCase()
var obj = db[type] = db[type] || createTypeEntry(source)
// add missing data
setValue(obj, 'charset', data.charset)
setValue(obj, 'compressible', data.compressible)
// append new extensions
appendExtensions(obj, data.extensions)
})
} | javascript | {
"resource": ""
} |
q28005 | appendExtension | train | function appendExtension (obj, extension) {
if (!obj.extensions) {
obj.extensions = []
}
if (obj.extensions.indexOf(extension) === -1) {
obj.extensions.push(extension)
}
} | javascript | {
"resource": ""
} |
q28006 | appendExtensions | train | function appendExtensions (obj, extensions) {
if (!extensions) {
return
}
for (var i = 0; i < extensions.length; i++) {
var extension = extensions[i]
// add extension to the type entry
appendExtension(obj, extension)
}
} | javascript | {
"resource": ""
} |
q28007 | setValue | train | function setValue (obj, prop, value) {
if (value !== undefined && obj[prop] === undefined) {
obj[prop] = value
}
} | javascript | {
"resource": ""
} |
q28008 | get | train | function get (url, callback) {
https.get(url, function onResponse (res) {
if (res.statusCode !== 200) {
callback(new Error('got status code ' + res.statusCode + ' from ' + URL))
} else {
getBody(res, true, callback)
}
})
} | javascript | {
"resource": ""
} |
q28009 | parseScope | train | function parseScope( path, obj ) {
return path.split('.').reduce( function( prev, curr ) {
return prev[curr];
}, obj || this );
} | javascript | {
"resource": ""
} |
q28010 | train | function(el) {
(el.length > 0) && (el = el[0]);
var orgAttributes = {};
for (var i=0; i<el.attributes.length; i++) {
var attr = el.attributes[i];
orgAttributes[attr.name] = attr.value;
}
return orgAttributes;
} | javascript | {
"resource": ""
} | |
q28011 | train | function(scope, attrs) {
var events = {};
var toLowercaseFunc = function($1){
return "_"+$1.toLowerCase();
};
var EventFunc = function(attrValue) {
// funcName(argsStr)
var matches = attrValue.match(/([^\(]+)\(([^\)]*)\)/);
var funcName = matches[1];
var argsStr = matches[2].replace(/event[ ,]*/,''); //remove string 'event'
var argsExpr = $parse("["+argsStr+"]"); //for perf when triggering event
return function(event) {
var args = argsExpr(scope); //get args here to pass updated model values
function index(obj,i) {return obj[i];}
var f = funcName.split('.').reduce(index, scope);
f && f.apply(this, [event].concat(args));
$timeout( function() {
scope.$apply();
});
};
};
for(var key in attrs) {
if (attrs[key]) {
if (!key.match(/^on[A-Z]/)) { //skip if not events
continue;
}
//get event name as underscored. i.e. zoom_changed
var eventName = key.replace(/^on/,'');
eventName = eventName.charAt(0).toLowerCase() + eventName.slice(1);
eventName = eventName.replace(/([A-Z])/g, toLowercaseFunc);
var attrValue = attrs[key];
events[eventName] = new EventFunc(attrValue);
}
}
return events;
} | javascript | {
"resource": ""
} | |
q28012 | train | function(filtered) {
var controlOptions = {};
if (typeof filtered != 'object') {
return false;
}
for (var attr in filtered) {
if (filtered[attr]) {
if (!attr.match(/(.*)ControlOptions$/)) {
continue; // if not controlOptions, skip it
}
//change invalid json to valid one, i.e. {foo:1} to {"foo": 1}
var orgValue = filtered[attr];
var newValue = orgValue.replace(/'/g, '"');
newValue = newValue.replace(/([^"]+)|("[^"]+")/g, function($0, $1, $2) {
if ($1) {
return $1.replace(/([a-zA-Z0-9]+?):/g, '"$1":');
} else {
return $2;
}
});
try {
var options = JSON.parse(newValue);
for (var key in options) { //assign the right values
if (options[key]) {
var value = options[key];
if (typeof value === 'string') {
value = value.toUpperCase();
} else if (key === "mapTypeIds") {
value = value.map( function(str) {
if (str.match(/^[A-Z]+$/)) { // if constant
return google.maps.MapTypeId[str.toUpperCase()];
} else { // else, custom map-type
return str;
}
});
}
if (key === "style") {
var str = attr.charAt(0).toUpperCase() + attr.slice(1);
var objName = str.replace(/Options$/,'')+"Style";
options[key] = google.maps[objName][value];
} else if (key === "position") {
options[key] = google.maps.ControlPosition[value];
} else {
options[key] = value;
}
}
}
controlOptions[attr] = options;
} catch (e) {
console.error('invald option for', attr, newValue, e, e.stack);
}
}
} // for
return controlOptions;
} | javascript | {
"resource": ""
} | |
q28013 | train | function(map, panoId) {
var svp = new google.maps.StreetViewPanorama(
map.getDiv(), {enableCloseButton: true}
);
svp.setPano(panoId);
} | javascript | {
"resource": ""
} | |
q28014 | pages | train | function pages() {
return gulp.src(['src/pages/**/*.html', '!src/pages/archive/**/*.html'])
.pipe(panini({
root: 'src/pages',
layouts: 'src/layouts',
partials: 'src/partials',
helpers: 'src/helpers'
}))
.pipe(inky())
.pipe(gulp.dest('dist'));
} | javascript | {
"resource": ""
} |
q28015 | sass | train | function sass() {
return gulp.src('src/assets/scss/app.scss')
.pipe($.if(!PRODUCTION, $.sourcemaps.init()))
.pipe($.sass({
includePaths: ['node_modules/foundation-emails/scss']
}).on('error', $.sass.logError))
.pipe($.if(PRODUCTION, $.uncss(
{
html: ['dist/**/*.html']
})))
.pipe($.if(!PRODUCTION, $.sourcemaps.write()))
.pipe(gulp.dest('dist/css'));
} | javascript | {
"resource": ""
} |
q28016 | watch | train | function watch() {
gulp.watch('src/pages/**/*.html').on('all', gulp.series(pages, inline, browser.reload));
gulp.watch(['src/layouts/**/*', 'src/partials/**/*']).on('all', gulp.series(resetPages, pages, inline, browser.reload));
gulp.watch(['../scss/**/*.scss', 'src/assets/scss/**/*.scss']).on('all', gulp.series(resetPages, sass, pages, inline, browser.reload));
gulp.watch('src/assets/img/**/*').on('all', gulp.series(images, browser.reload));
} | javascript | {
"resource": ""
} |
q28017 | creds | train | function creds(done) {
var configPath = './config.json';
try { CONFIG = JSON.parse(fs.readFileSync(configPath)); }
catch(e) {
beep();
console.log('[AWS]'.bold.red + ' Sorry, there was an issue locating your config.json. Please see README.md');
process.exit();
}
done();
} | javascript | {
"resource": ""
} |
q28018 | aws | train | function aws() {
var publisher = !!CONFIG.aws ? $.awspublish.create(CONFIG.aws) : $.awspublish.create();
var headers = {
'Cache-Control': 'max-age=315360000, no-transform, public'
};
return gulp.src('./dist/assets/img/*')
// publisher will add Content-Length, Content-Type and headers specified above
// If not specified it will set x-amz-acl to public-read by default
.pipe(publisher.publish(headers))
// create a cache file to speed up consecutive uploads
//.pipe(publisher.cache())
// print upload updates to console
.pipe($.awspublish.reporter());
} | javascript | {
"resource": ""
} |
q28019 | litmus | train | function litmus() {
var awsURL = !!CONFIG && !!CONFIG.aws && !!CONFIG.aws.url ? CONFIG.aws.url : false;
return gulp.src('dist/**/*.html')
.pipe($.if(!!awsURL, $.replace(/=('|")(\/?assets\/img)/g, "=$1"+ awsURL)))
.pipe($.litmus(CONFIG.litmus))
.pipe(gulp.dest('dist'));
} | javascript | {
"resource": ""
} |
q28020 | mail | train | function mail() {
var awsURL = !!CONFIG && !!CONFIG.aws && !!CONFIG.aws.url ? CONFIG.aws.url : false;
if (EMAIL) {
CONFIG.mail.to = [EMAIL];
}
return gulp.src('dist/**/*.html')
.pipe($.if(!!awsURL, $.replace(/=('|")(\/?assets\/img)/g, "=$1"+ awsURL)))
.pipe($.mail(CONFIG.mail))
.pipe(gulp.dest('dist'));
} | javascript | {
"resource": ""
} |
q28021 | zip | train | function zip() {
var dist = 'dist';
var ext = '.html';
function getHtmlFiles(dir) {
return fs.readdirSync(dir)
.filter(function(file) {
var fileExt = path.join(dir, file);
var isHtml = path.extname(fileExt) == ext;
return fs.statSync(fileExt).isFile() && isHtml;
});
}
var htmlFiles = getHtmlFiles(dist);
var moveTasks = htmlFiles.map(function(file){
var sourcePath = path.join(dist, file);
var fileName = path.basename(sourcePath, ext);
var moveHTML = gulp.src(sourcePath)
.pipe($.rename(function (path) {
path.dirname = fileName;
return path;
}));
var moveImages = gulp.src(sourcePath)
.pipe($.htmlSrc({ selector: 'img'}))
.pipe($.rename(function (path) {
path.dirname = fileName + path.dirname.replace('dist', '');
return path;
}));
return merge(moveHTML, moveImages)
.pipe($.zip(fileName+ '.zip'))
.pipe(gulp.dest('dist'));
});
return merge(moveTasks);
} | javascript | {
"resource": ""
} |
q28022 | train | function() {
if (this.$element[0] instanceof document.constructor && !this.options.selector) {
throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!');
}
if (this.getTrigger() !== 'manual') {
//init the event handlers
if (isMobile) {
this.$element.off('touchend', this.options.selector).on('touchend', this.options.selector, $.proxy(this.toggle, this));
} else if (this.getTrigger() === 'click') {
this.$element.off('click', this.options.selector).on('click', this.options.selector, $.proxy(this.toggle, this));
} else if (this.getTrigger() === 'hover') {
this.$element
.off('mouseenter mouseleave click', this.options.selector)
.on('mouseenter', this.options.selector, $.proxy(this.mouseenterHandler, this))
.on('mouseleave', this.options.selector, $.proxy(this.mouseleaveHandler, this));
}
}
this._poped = false;
this._inited = true;
this._opened = false;
this._idSeed = _globalIdSeed;
this.id = pluginName + this._idSeed;
// normalize container
this.options.container = $(this.options.container || document.body).first();
if (this.options.backdrop) {
backdrop.appendTo(this.options.container).hide();
}
_globalIdSeed++;
if (this.getTrigger() === 'sticky') {
this.show();
}
if (this.options.selector) {
this._options = $.extend({}, this.options, {
selector: ''
});
}
} | javascript | {
"resource": ""
} | |
q28023 | some | train | function some(array, member) {
if(isUndefined(member)) {
return false;
}
return array.some(function(el) {
return equals(el, member);
});
} | javascript | {
"resource": ""
} |
q28024 | indexOf | train | function indexOf(word, p, c) {
var j = 0;
while ((p + j) <= word.length) {
if (word.charAt(p + j) == c) return j;
j++;
}
return -1;
} | javascript | {
"resource": ""
} |
q28025 | hasSimilarSelectors | train | function hasSimilarSelectors(selectors1, selectors2) {
var cursor1 = selectors1.head;
while (cursor1 !== null) {
var cursor2 = selectors2.head;
while (cursor2 !== null) {
if (cursor1.data.compareMarker === cursor2.data.compareMarker) {
return true;
}
cursor2 = cursor2.next;
}
cursor1 = cursor1.next;
}
return false;
} | javascript | {
"resource": ""
} |
q28026 | unsafeToSkipNode | train | function unsafeToSkipNode(node) {
switch (node.type) {
case 'Rule':
// unsafe skip ruleset with selector similarities
return hasSimilarSelectors(node.prelude.children, this);
case 'Atrule':
// can skip at-rules with blocks
if (node.block) {
// unsafe skip at-rule if block contains something unsafe to skip
return node.block.children.some(unsafeToSkipNode, this);
}
break;
case 'Declaration':
return false;
}
// unsafe by default
return true;
} | javascript | {
"resource": ""
} |
q28027 | throttled | train | function throttled (fn, delay) {
let lastCall = 0
return function (...args) {
const now = new Date().getTime()
if (now - lastCall < delay) {
return
}
lastCall = now
return fn(...args)
}
} | javascript | {
"resource": ""
} |
q28028 | train | function(path, options) {
var self = this;
// options
if (typeof(options) === "undefined") options = {};
// disable auto open, as we handle the open
options.autoOpen = false;
// internal buffer
this._buffer = Buffer.alloc(0);
this._id = 0;
this._cmd = 0;
this._length = 0;
// create the SerialPort
this._client = new SerialPort(path, options);
// register the port data event
this._client.on("data", function onData(data) {
// add data to buffer
self._buffer = Buffer.concat([self._buffer, data]);
// check if buffer include a complete modbus answer
var expectedLength = self._length;
var bufferLength = self._buffer.length;
modbusSerialDebug({ action: "receive serial rtu buffered port", data: data, buffer: self._buffer });
// check data length
if (expectedLength < MIN_DATA_LENGTH || bufferLength < EXCEPTION_LENGTH) return;
// check buffer size for MAX_BUFFER_SIZE
if (bufferLength > MAX_BUFFER_LENGTH) {
self._buffer = self._buffer.slice(-MAX_BUFFER_LENGTH);
bufferLength = MAX_BUFFER_LENGTH;
}
// loop and check length-sized buffer chunks
var maxOffset = bufferLength - EXCEPTION_LENGTH;
for (var i = 0; i <= maxOffset; i++) {
var unitId = self._buffer[i];
var functionCode = self._buffer[i + 1];
if (unitId !== self._id) continue;
if (functionCode === self._cmd && i + expectedLength <= bufferLength) {
self._emitData(i, expectedLength);
return;
}
if (functionCode === (0x80 | self._cmd) && i + EXCEPTION_LENGTH <= bufferLength) {
self._emitData(i, EXCEPTION_LENGTH);
return;
}
// frame header matches, but still missing bytes pending
if (functionCode === (0x7f & self._cmd)) break;
}
});
/**
* Check if port is open.
*
* @returns {boolean}
*/
Object.defineProperty(this, "isOpen", {
enumerable: true,
get: function() {
return this._client.isOpen;
}
});
EventEmitter.call(this);
} | javascript | {
"resource": ""
} | |
q28029 | checkError | train | function checkError(e) {
if(e.errno && networkErrors.includes(e.errno)) {
console.log("we have to reconnect");
// close port
client.close();
// re open client
client = new ModbusRTU();
timeoutConnectRef = setTimeout(connect, 1000);
}
} | javascript | {
"resource": ""
} |
q28030 | connect | train | function connect() {
// clear pending timeouts
clearTimeout(timeoutConnectRef);
// if client already open, just run
if (client.isOpen) {
run();
}
// if client closed, open a new connection
client.connectTCP("127.0.0.1", { port: 8502 })
.then(setClient)
.then(function() {
console.log("Connected"); })
.catch(function(e) {
checkError(e);
console.log(e.message); });
} | javascript | {
"resource": ""
} |
q28031 | _asciiEncodeRequestBuffer | train | function _asciiEncodeRequestBuffer(buf) {
// replace the 2 byte crc16 with a single byte lrc
buf.writeUInt8(calculateLrc(buf.slice(0, -2)), buf.length - 2);
// create a new buffer of the correct size
var bufAscii = Buffer.alloc(buf.length * 2 + 1); // 1 byte start delimit + x2 data as ascii encoded + 2 lrc + 2 end delimit
// create the ascii payload
// start with the single start delimiter
bufAscii.write(":", 0);
// encode the data, with the new single byte lrc
bufAscii.write(buf.toString("hex", 0, buf.length - 1).toUpperCase(), 1);
// end with the two end delimiters
bufAscii.write("\r", bufAscii.length - 2);
bufAscii.write("\n", bufAscii.length - 1);
return bufAscii;
} | javascript | {
"resource": ""
} |
q28032 | _asciiDecodeResponseBuffer | train | function _asciiDecodeResponseBuffer(bufAscii) {
// create a new buffer of the correct size (based on ascii encoded buffer length)
var bufDecoded = Buffer.alloc((bufAscii.length - 1) / 2);
// decode into new buffer (removing delimiters at start and end)
for (var i = 0; i < (bufAscii.length - 3) / 2; i++) {
bufDecoded.write(String.fromCharCode(bufAscii.readUInt8(i * 2 + 1), bufAscii.readUInt8(i * 2 + 2)), i, 1, "hex");
}
// check the lrc is true
var lrcIn = bufDecoded.readUInt8(bufDecoded.length - 2);
if(calculateLrc(bufDecoded.slice(0, -2)) !== lrcIn) {
// return null if lrc error
var calcLrc = calculateLrc(bufDecoded.slice(0, -2));
modbusSerialDebug({ action: "LRC error", LRC: lrcIn.toString(16), calcLRC: calcLrc.toString(16) });
return null;
}
// replace the 1 byte lrc with a two byte crc16
bufDecoded.writeUInt16LE(crc16(bufDecoded.slice(0, -2)), bufDecoded.length - 2);
return bufDecoded;
} | javascript | {
"resource": ""
} |
q28033 | _checkData | train | function _checkData(modbus, buf) {
// check buffer size
if (buf.length !== modbus._length && buf.length !== 5) {
modbusSerialDebug({ action: "length error", recive: buf.length, expected: modbus._length });
return false;
}
// check buffer unit-id and command
return (buf[0] === modbus._id &&
(0x7f & buf[1]) === modbus._cmd);
} | javascript | {
"resource": ""
} |
q28034 | train | function(path, options) {
var modbus = this;
// options
options = options || {};
// disable auto open, as we handle the open
options.autoOpen = false;
// internal buffer
this._buffer = Buffer.from("");
this._id = 0;
this._cmd = 0;
this._length = 0;
// create the SerialPort
this._client = new SerialPort(path, options);
// register the port data event
this._client.on("data", function(data) {
// add new data to buffer
modbus._buffer = Buffer.concat([modbus._buffer, data]);
modbusSerialDebug({ action: "receive serial ascii port", data: data, buffer: modbus._buffer });
modbusSerialDebug(JSON.stringify({ action: "receive serial ascii port strings", data: data, buffer: modbus._buffer }));
// check buffer for start delimiter
var sdIndex = modbus._buffer.indexOf(0x3A); // ascii for ':'
if(sdIndex === -1) {
// if not there, reset the buffer and return
modbus._buffer = Buffer.from("");
return;
}
// if there is data before the start delimiter, remove it
if(sdIndex > 0) {
modbus._buffer = modbus._buffer.slice(sdIndex);
}
// do we have the complete message (i.e. are the end delimiters there)
if(modbus._buffer.includes("\r\n", 1, "ascii") === true) {
// check there is no excess data after end delimiters
var edIndex = modbus._buffer.indexOf(0x0A); // ascii for '\n'
if(edIndex !== modbus._buffer.length - 1) {
// if there is, remove it
modbus._buffer = modbus._buffer.slice(0, edIndex + 1);
}
// we have what looks like a complete ascii encoded response message, so decode
var _data = _asciiDecodeResponseBuffer(modbus._buffer);
modbusSerialDebug({ action: "got EOM", data: _data, buffer: modbus._buffer });
if(_data !== null) {
// check if this is the data we are waiting for
if (_checkData(modbus, _data)) {
modbusSerialDebug({ action: "emit data serial ascii port", data: data, buffer: modbus._buffer });
modbusSerialDebug(JSON.stringify({ action: "emit data serial ascii port strings", data: data, buffer: modbus._buffer }));
// emit a data signal
modbus.emit("data", _data);
}
}
// reset the buffer now its been used
modbus._buffer = Buffer.from("");
} else {
// otherwise just wait for more data to arrive
}
});
/**
* Check if port is open.
*
* @returns {boolean}
*/
Object.defineProperty(this, "isOpen", {
enumerable: true,
get: function() {
return this._client.isOpen;
}
});
EventEmitter.call(this);
} | javascript | {
"resource": ""
} | |
q28035 | _startTimeout | train | function _startTimeout(duration, transaction) {
if (!duration) {
return undefined;
}
return setTimeout(function() {
transaction._timeoutFired = true;
if (transaction.next) {
transaction.next(new TransactionTimedOutError());
}
}, duration);
} | javascript | {
"resource": ""
} |
q28036 | _handlePromiseOrValue | train | function _handlePromiseOrValue(promiseOrValue, cb) {
if (promiseOrValue && promiseOrValue.then && typeof promiseOrValue.then === "function") {
promiseOrValue
.then(function(value) {
cb(null, value);
})
.catch(function(err) {
cb(err);
});
} else {
cb(null, promiseOrValue);
}
} | javascript | {
"resource": ""
} |
q28037 | _handleReadCoilsOrInputDiscretes | train | function _handleReadCoilsOrInputDiscretes(requestBuffer, vector, unitID, callback, fc) {
var address = requestBuffer.readUInt16BE(2);
var length = requestBuffer.readUInt16BE(4);
if (_errorRequestBufferLength(requestBuffer)) {
return;
}
// build answer
var dataBytes = parseInt((length - 1) / 8 + 1);
var responseBuffer = Buffer.alloc(3 + dataBytes + 2);
try {
responseBuffer.writeUInt8(dataBytes, 2);
}
catch (err) {
callback(err);
return;
}
var vectorCB;
if(fc === 1)
vectorCB = vector.getCoil;
else if (fc === 2)
vectorCB = vector.getDiscreteInput;
// read coils
if (vectorCB) {
var callbackInvoked = false;
var cbCount = 0;
var buildCb = function(i) {
return function(err, value) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
cbCount = cbCount + 1;
responseBuffer.writeBit(value, i % 8, 3 + parseInt(i / 8));
if (cbCount === length && !callbackInvoked) {
modbusSerialDebug({ action: "FC" + fc + " response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
};
if (length === 0)
callback({
modbusErrorCode: 0x02, // Illegal address
msg: "Invalid length"
});
for (var i = 0; i < length; i++) {
var cb = buildCb(i);
try {
if (vectorCB.length === 3) {
vectorCB(address + i, unitID, cb);
}
else {
var promiseOrValue = vectorCB(address + i, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
}
catch(err) {
cb(err);
}
}
}
} | javascript | {
"resource": ""
} |
q28038 | _handleWriteCoil | train | function _handleWriteCoil(requestBuffer, vector, unitID, callback) {
var address = requestBuffer.readUInt16BE(2);
var state = requestBuffer.readUInt16BE(4);
if (_errorRequestBufferLength(requestBuffer)) {
return;
}
// build answer
var responseBuffer = Buffer.alloc(8);
responseBuffer.writeUInt16BE(address, 2);
responseBuffer.writeUInt16BE(state, 4);
if (vector.setCoil) {
var callbackInvoked = false;
var cb = function(err) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
if (!callbackInvoked) {
modbusSerialDebug({ action: "FC5 response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
try {
if (vector.setCoil.length === 4) {
vector.setCoil(address, state === 0xff00, unitID, cb);
}
else {
var promiseOrValue = vector.setCoil(address, state === 0xff00, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
}
catch(err) {
cb(err);
}
}
} | javascript | {
"resource": ""
} |
q28039 | _handleWriteSingleRegister | train | function _handleWriteSingleRegister(requestBuffer, vector, unitID, callback) {
var address = requestBuffer.readUInt16BE(2);
var value = requestBuffer.readUInt16BE(4);
if (_errorRequestBufferLength(requestBuffer)) {
return;
}
// build answer
var responseBuffer = Buffer.alloc(8);
responseBuffer.writeUInt16BE(address, 2);
responseBuffer.writeUInt16BE(value, 4);
if (vector.setRegister) {
var callbackInvoked = false;
var cb = function(err) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
if (!callbackInvoked) {
modbusSerialDebug({ action: "FC6 response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
try {
if (vector.setRegister.length === 4) {
vector.setRegister(address, value, unitID, cb);
}
else {
var promiseOrValue = vector.setRegister(address, value, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
} catch(err) {
cb(err);
}
}
} | javascript | {
"resource": ""
} |
q28040 | _handleForceMultipleCoils | train | function _handleForceMultipleCoils(requestBuffer, vector, unitID, callback) {
var address = requestBuffer.readUInt16BE(2);
var length = requestBuffer.readUInt16BE(4);
// if length is bad, ignore message
if (requestBuffer.length !== 7 + Math.ceil(length / 8) + 2) {
return;
}
// build answer
var responseBuffer = Buffer.alloc(8);
responseBuffer.writeUInt16BE(address, 2);
responseBuffer.writeUInt16BE(length, 4);
var callbackInvoked = false;
var cbCount = 0;
var buildCb = function(/* i - not used at the moment */) {
return function(err) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
cbCount = cbCount + 1;
if (cbCount === length && !callbackInvoked) {
modbusSerialDebug({ action: "FC15 response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
};
if (length === 0)
callback({
modbusErrorCode: 0x02, // Illegal address
msg: "Invalid length"
});
if (vector.setCoil) {
var state;
for (var i = 0; i < length; i++) {
var cb = buildCb(i);
state = requestBuffer.readBit(i, 7);
try {
if (vector.setCoil.length === 4) {
vector.setCoil(address + i, state !== false, unitID, cb);
}
else {
var promiseOrValue = vector.setCoil(address + i, state !== false, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
}
catch(err) {
cb(err);
}
}
} else if (vector.setCoilArray) {
state = [];
for (i = 0; i < length; i++) {
cb = buildCb(i);
state.push(requestBuffer.readBit(i, 7));
_handlePromiseOrValue(promiseOrValue, cb);
}
try {
if (vector.setCoilArray.length === 4) {
vector.setCoilArray(address, state, unitID, cb);
}
else {
vector.setCoilArray(address, state, unitID);
}
}
catch(err) {
cb(err);
}
}
} | javascript | {
"resource": ""
} |
q28041 | _handleWriteMultipleRegisters | train | function _handleWriteMultipleRegisters(requestBuffer, vector, unitID, callback) {
var address = requestBuffer.readUInt16BE(2);
var length = requestBuffer.readUInt16BE(4);
// if length is bad, ignore message
if (requestBuffer.length !== (7 + length * 2 + 2)) {
return;
}
// build answer
var responseBuffer = Buffer.alloc(8);
responseBuffer.writeUInt16BE(address, 2);
responseBuffer.writeUInt16BE(length, 4);
// write registers
var callbackInvoked = false;
var cbCount = 0;
var buildCb = function(/* i - not used at the moment */) {
return function(err) {
if (err) {
if (!callbackInvoked) {
callbackInvoked = true;
callback(err);
}
return;
}
cbCount = cbCount + 1;
if (cbCount === length && !callbackInvoked) {
modbusSerialDebug({ action: "FC16 response", responseBuffer: responseBuffer });
callbackInvoked = true;
callback(null, responseBuffer);
}
};
};
if (length === 0)
callback({
modbusErrorCode: 0x02, // Illegal address
msg: "Invalid length"
});
if (vector.setRegister) {
var value;
for (var i = 0; i < length; i++) {
var cb = buildCb(i);
value = requestBuffer.readUInt16BE(7 + i * 2);
try {
if (vector.setRegister.length === 4) {
vector.setRegister(address + i, value, unitID, cb);
}
else {
var promiseOrValue = vector.setRegister(address + i, value, unitID);
_handlePromiseOrValue(promiseOrValue, cb);
}
}
catch(err) {
cb(err);
}
}
} else if (vector.setRegisterArray) {
value = [];
for (i = 0; i < length; i++) {
cb = buildCb(i);
value.push(requestBuffer.readUInt16BE(7 + i * 2));
_handlePromiseOrValue(value, cb);
}
try {
if (vector.setRegisterArray.length === 6) {
vector.setRegisterArray(address, value, unitID, cb);
}
else {
vector.setRegisterArray(address, value, unitID);
}
}
catch (err) {
cb(err);
}
}
} | javascript | {
"resource": ""
} |
q28042 | _handleMEI | train | function _handleMEI(requestBuffer, vector, unitID, callback) {
var MEIType = requestBuffer[2];
switch(parseInt(MEIType)) {
case 14:
_handleReadDeviceIdentification(requestBuffer, vector, unitID, callback);
break;
default:
callback({ modbusErrorCode: 0x01 }); // illegal MEI type
}
} | javascript | {
"resource": ""
} |
q28043 | _serverDebug | train | function _serverDebug(text, unitID, functionCode, responseBuffer) {
// If no responseBuffer, then assume this is an error
// o/w assume an action
if (typeof responseBuffer === "undefined") {
modbusSerialDebug({
error: text,
unitID: unitID,
functionCode: functionCode
});
} else {
modbusSerialDebug({
action: text,
unitID: unitID,
functionCode: functionCode,
responseBuffer: responseBuffer.toString("hex")
});
}
} | javascript | {
"resource": ""
} |
q28044 | _callbackFactory | train | function _callbackFactory(unitID, functionCode, sockWriter) {
return function cb(err, responseBuffer) {
var crc;
// If we have an error.
if (err) {
var errorCode = 0x04; // slave device failure
if (!isNaN(err.modbusErrorCode)) {
errorCode = err.modbusErrorCode;
}
// Set an error response
functionCode = parseInt(functionCode) | 0x80;
responseBuffer = Buffer.alloc(3 + 2);
responseBuffer.writeUInt8(errorCode, 2);
_serverDebug("error processing response", unitID, functionCode);
}
// If we do not have a responseBuffer
if (!responseBuffer) {
_serverDebug("no response buffer", unitID, functionCode);
return sockWriter(null, responseBuffer);
}
// add unit number and function code
responseBuffer.writeUInt8(unitID, 0);
responseBuffer.writeUInt8(functionCode, 1);
// Add crc
crc = crc16(responseBuffer.slice(0, -2));
responseBuffer.writeUInt16LE(crc, responseBuffer.length - 2);
// Call callback function
_serverDebug("server response", unitID, functionCode, responseBuffer);
return sockWriter(null, responseBuffer);
};
} | javascript | {
"resource": ""
} |
q28045 | _parseModbusBuffer | train | function _parseModbusBuffer(requestBuffer, vector, serverUnitID, sockWriter) {
var cb;
// Check requestBuffer length
if (!requestBuffer || requestBuffer.length < MBAP_LEN) {
modbusSerialDebug("wrong size of request Buffer " + requestBuffer.length);
return;
}
var unitID = requestBuffer[0];
var functionCode = requestBuffer[1];
var crc = requestBuffer[requestBuffer.length - 2] + requestBuffer[requestBuffer.length - 1] * 0x100;
// if crc is bad, ignore message
if (crc !== crc16(requestBuffer.slice(0, -2))) {
modbusSerialDebug("wrong CRC of request Buffer");
return;
}
// if crc is bad, ignore message
if (serverUnitID !== 255 && serverUnitID !== unitID) {
modbusSerialDebug("wrong unitID");
return;
}
modbusSerialDebug("request for function code " + functionCode);
cb = _callbackFactory(unitID, functionCode, sockWriter);
switch (parseInt(functionCode)) {
case 1:
case 2:
handlers.readCoilsOrInputDiscretes(requestBuffer, vector, unitID, cb, functionCode);
break;
case 3:
handlers.readMultipleRegisters(requestBuffer, vector, unitID, cb);
break;
case 4:
handlers.readInputRegisters(requestBuffer, vector, unitID, cb);
break;
case 5:
handlers.writeCoil(requestBuffer, vector, unitID, cb);
break;
case 6:
handlers.writeSingleRegister(requestBuffer, vector, unitID, cb);
break;
case 15:
handlers.forceMultipleCoils(requestBuffer, vector, unitID, cb);
break;
case 16:
handlers.writeMultipleRegisters(requestBuffer, vector, unitID, cb);
break;
case 43:
handlers.handleMEI(requestBuffer, vector, unitID, cb);
break;
default:
var errorCode = 0x01; // illegal function
// set an error response
functionCode = parseInt(functionCode) | 0x80;
var responseBuffer = Buffer.alloc(3 + 2);
responseBuffer.writeUInt8(errorCode, 2);
modbusSerialDebug({
error: "Illegal function",
functionCode: functionCode
});
cb({ modbusErrorCode: errorCode }, responseBuffer);
}
} | javascript | {
"resource": ""
} |
q28046 | _checkData | train | function _checkData(modbus, buf) {
// check buffer size
if (buf.length !== modbus._length && buf.length !== 5) return false;
// calculate crc16
var crcIn = buf.readUInt16LE(buf.length - 2);
// check buffer unit-id, command and crc
return (buf[0] === modbus._id &&
(0x7f & buf[1]) === modbus._cmd &&
crcIn === crc16(buf.slice(0, -2)));
} | javascript | {
"resource": ""
} |
q28047 | train | function(ip, options) {
var modbus = this;
this.ip = ip;
this.openFlag = false;
// options
if (typeof(options) === "undefined") options = {};
this.port = options.port || C701_PORT; // C701 port
// create a socket
this._client = dgram.createSocket("udp4");
// wait for answer
this._client.on("message", function(data) {
var buffer = null;
// check expected length
if (modbus.length < 6) return;
// check message length
if (data.length < (116 + 5)) return;
// check the C701 packet magic
if (data.readUInt16LE(2) !== 602) return;
// check for modbus valid answer
// get the serial data from the C701 packet
buffer = data.slice(data.length - modbus._length);
modbusSerialDebug({ action: "receive c701 upd port", data: data, buffer: buffer });
modbusSerialDebug(JSON.stringify({ action: "receive c701 upd port strings", data: data, buffer: buffer }));
// check the serial data
if (_checkData(modbus, buffer)) {
modbusSerialDebug({ action: "emit data serial rtu buffered port", buffer: buffer });
modbusSerialDebug(JSON.stringify({ action: "emit data serial rtu buffered port strings", buffer: buffer }));
modbus.emit("data", buffer);
} else {
// check for modbus exception
// get the serial data from the C701 packet
buffer = data.slice(data.length - 5);
// check the serial data
if (_checkData(modbus, buffer)) {
modbusSerialDebug({ action: "emit data serial rtu buffered port", buffer: buffer });
modbusSerialDebug(JSON.stringify({
action: "emit data serial rtu buffered port strings",
buffer: buffer
}));
modbus.emit("data", buffer);
}
}
});
this._client.on("listening", function() {
modbus.openFlag = true;
});
this._client.on("close", function() {
modbus.openFlag = false;
});
/**
* Check if port is open.
*
* @returns {boolean}
*/
Object.defineProperty(this, "isOpen", {
enumerable: true,
get: function() {
return this.openFlag;
}
});
EventEmitter.call(this);
} | javascript | {
"resource": ""
} | |
q28048 | checkGraphvizInstalled | train | function checkGraphvizInstalled(config) {
if (config.graphVizPath) {
const cmd = path.join(config.graphVizPath, 'gvpr -V');
return exec(cmd)
.catch(() => {
throw new Error('Could not execute ' + cmd);
});
}
return exec('gvpr -V')
.catch((error) => {
throw new Error('Graphviz could not be found. Ensure that "gvpr" is in your $PATH.\n' + error);
});
} | javascript | {
"resource": ""
} |
q28049 | createGraphvizOptions | train | function createGraphvizOptions(config) {
const graphVizOptions = config.graphVizOptions || {};
return {
G: Object.assign({
overlap: false,
pad: 0.3,
rankdir: config.rankdir,
layout: config.layout,
bgcolor: config.backgroundColor
}, graphVizOptions.G),
E: Object.assign({
color: config.edgeColor
}, graphVizOptions.E),
N: Object.assign({
fontname: config.fontName,
fontsize: config.fontSize,
color: config.nodeColor,
shape: config.nodeShape,
style: config.nodeStyle,
height: 0,
fontcolor: config.nodeColor
}, graphVizOptions.N)
};
} | javascript | {
"resource": ""
} |
q28050 | createGraph | train | function createGraph(modules, circular, config, options) {
const g = graphviz.digraph('G');
const nodes = {};
const cyclicModules = circular.reduce((a, b) => a.concat(b), []);
if (config.graphVizPath) {
g.setGraphVizPath(config.graphVizPath);
}
Object.keys(modules).forEach((id) => {
nodes[id] = nodes[id] || g.addNode(id);
if (!modules[id].length) {
setNodeColor(nodes[id], config.noDependencyColor);
} else if (cyclicModules.indexOf(id) >= 0) {
setNodeColor(nodes[id], config.cyclicNodeColor);
}
modules[id].forEach((depId) => {
nodes[depId] = nodes[depId] || g.addNode(depId);
if (!modules[depId]) {
setNodeColor(nodes[depId], config.noDependencyColor);
}
g.addEdge(nodes[id], nodes[depId]);
});
});
return new Promise((resolve, reject) => {
g.output(options, resolve, (code, out, err) => {
reject(new Error(err));
});
});
} | javascript | {
"resource": ""
} |
q28051 | getPath | train | function getPath(parent, unresolved) {
let parentVisited = false;
return Object.keys(unresolved).filter((module) => {
if (module === parent) {
parentVisited = true;
}
return parentVisited && unresolved[module];
});
} | javascript | {
"resource": ""
} |
q28052 | resolver | train | function resolver(id, modules, circular, resolved, unresolved) {
unresolved[id] = true;
if (modules[id]) {
modules[id].forEach((dependency) => {
if (!resolved[dependency]) {
if (unresolved[dependency]) {
circular.push(getPath(dependency, unresolved));
return;
}
resolver(dependency, modules, circular, resolved, unresolved);
}
});
}
resolved[id] = true;
unresolved[id] = false;
} | javascript | {
"resource": ""
} |
q28053 | tryInitOrHookIntoEvents | train | function tryInitOrHookIntoEvents(options, $that) {
var success = tryInit(options, $that);
if (!success) {
console.log('TSS: Body width smaller than options.minWidth. Init is delayed.');
$(document).on('scroll.' + options.namespace, function (options, $that) {
return function (evt) {
var success = tryInit(options, $that);
if (success) {
$(this).unbind(evt);
}
};
}(options, $that));
$(window).on('resize.' + options.namespace, function (options, $that) {
return function (evt) {
var success = tryInit(options, $that);
if (success) {
$(this).unbind(evt);
}
};
}(options, $that))
}
} | javascript | {
"resource": ""
} |
q28054 | tryInit | train | function tryInit(options, $that) {
if (options.initialized === true) {
return true;
}
if ($('body').width() < options.minWidth) {
return false;
}
init(options, $that);
return true;
} | javascript | {
"resource": ""
} |
q28055 | getClearedHeight | train | function getClearedHeight(e) {
var height = e.height();
e.children().each(function () {
height = Math.max(height, $(this).height());
});
return height;
} | javascript | {
"resource": ""
} |
q28056 | isSameValue | train | function isSameValue(a, b) {
const [propA, propB] = [a, b].map(value => (
isArray(value) ? [...value].sort() : value
));
return isEqual(propA, propB);
} | javascript | {
"resource": ""
} |
q28057 | upgrade | train | function upgrade(template) {
const type = OWNER_SVG_ELEMENT in this ? 'svg' : 'html';
const tagger = new Tagger(type);
bewitched.set(this, {tagger, template: template});
this.textContent = '';
this.appendChild(tagger.apply(null, arguments));
} | javascript | {
"resource": ""
} |
q28058 | hyper | train | function hyper(HTML) {
return arguments.length < 2 ?
(HTML == null ?
content('html') :
(typeof HTML === 'string' ?
hyper.wire(null, HTML) :
('raw' in HTML ?
content('html')(HTML) :
('nodeType' in HTML ?
hyper.bind(HTML) :
weakly(HTML, 'html')
)
)
)) :
('raw' in HTML ?
content('html') : hyper.wire
).apply(null, arguments);
} | javascript | {
"resource": ""
} |
q28059 | train | function (options) {
google.maps.Marker.prototype.setMap.apply(this, [options]);
(this.MarkerLabel) && this.MarkerLabel.setMap.apply(this.MarkerLabel, [options]);
} | javascript | {
"resource": ""
} | |
q28060 | train | function () {
this.div.parentNode.removeChild(this.div);
for (var i = 0, I = this.listeners.length; i < I; ++i) {
google.maps.event.removeListener(this.listeners[i]);
}
} | javascript | {
"resource": ""
} | |
q28061 | basicAuth | train | function basicAuth(checker, realm) {
realm = realm || 'Authorization Required';
function unauthorized(res) {
res.writeHead(401, {
'WWW-Authenticate': 'Basic realm="' + realm + '"',
'Content-Length': 13
});
res.end("Unauthorized\n");
}
function badRequest(res) {
res.writeHead(400, {
"Content-Length": 12
});
res.end('Bad Request\n');
}
return function(req, res, next) {
var authorization = req.headers.authorization;
if (!authorization) return unauthorized(res);
var parts = authorization.split(' ');
var scheme = parts[0];
var credentials = new Buffer(parts[1], 'base64').toString().split(':');
if ('Basic' != scheme) return badRequest(res);
checker(req, credentials[0], credentials[1], function (user) {
if (!user) return unauthorized(res);
req.remoteUser = user;
next();
});
}
} | javascript | {
"resource": ""
} |
q28062 | getReactProps | train | function getReactProps(node, parent) {
if (node.openingElement.attributes.length === 0 ||
htmlElements.indexOf(node.openingElement.name.name) > 0) return {};
const result = node.openingElement.attributes
.map(attribute => {
const name = attribute.name.name;
let valueName;
if (attribute.value === null) valueName = undefined;
else if (attribute.value.type === 'Literal') valueName = attribute.value.value;
else if (attribute.value.expression.type === 'Literal') {
valueName = attribute.value.expression.value;
} else if (attribute.value.expression.type === 'Identifier') {
valueName = attribute.value.expression.name;
} else if (attribute.value.expression.type === 'CallExpression') {
valueName = attribute.value.expression.callee.object.property.name;
} else if (attribute.value.expression.type === 'BinaryExpression') {
valueName = attribute.value.expression.left.name
+ attribute.value.expression.operator
+ (attribute.value.expression.right.name
|| attribute.value.expression.right.value);
} else if (attribute.value.expression.type === 'MemberExpression') {
let current = attribute.value.expression;
while (current && current.property) {
// && !current.property.name.match(/(state|props)/)
valueName = `.${current.property.name}${valueName || ''}`;
current = current.object;
if (current.type === 'Identifier') {
valueName = `.${current.name}${valueName || ''}`;
break;
}
}
valueName = valueName.replace('.', '');
} else if (attribute.value.expression.type === 'LogicalExpression') {
valueName = attribute.value.expression.left.property.name;
// valueType = attribute.value.expression.left.object.name;
} else if (attribute.value.expression.type === 'JSXElement') {
const nodez = attribute.value.expression;
const output = {
name: nodez.openingElement.name.name,
children: getChildJSXElements(nodez, parent),
props: getReactProps(nodez, parent),
state: {},
methods: [],
};
valueName = output;
} else valueName = escodegen.generate(attribute.value);
return {
name,
value: valueName,
parent,
};
});
return result;
} | javascript | {
"resource": ""
} |
q28063 | getChildJSXElements | train | function getChildJSXElements(node, parent) {
if (node.children.length === 0) return [];
const childJsxComponentsArr = node
.children
.filter(jsx => jsx.type === 'JSXElement'
&& htmlElements.indexOf(jsx.openingElement.name.name) < 0);
return childJsxComponentsArr
.map(child => {
return {
name: child.openingElement.name.name,
children: getChildJSXElements(child, parent),
props: getReactProps(child, parent),
state: {},
methods: [],
};
});
} | javascript | {
"resource": ""
} |
q28064 | isES6ReactComponent | train | function isES6ReactComponent(node) {
return (node.superClass.property && node.superClass.property.name === 'Component')
|| node.superClass.name === 'Component';
} | javascript | {
"resource": ""
} |
q28065 | jsToAst | train | function jsToAst(js) {
const ast = acorn.parse(js, {
plugins: { jsx: true },
});
if (ast.body.length === 0) throw new Error('Empty AST input');
return ast;
} | javascript | {
"resource": ""
} |
q28066 | d3DataBuilder | train | function d3DataBuilder(obj) {
if (!obj.ENTRY) throw new Error('Entry component not found');
const formatted = {};
// parsing AST into formatted objects based on ES5/ES6 syntax
Object.entries(obj).forEach(entry => {
if (entry[0] === 'ENTRY') return;
const componentChecker = reactParser.componentChecker(entry[1]);
switch (componentChecker) {
case 'ES6':
formatted[entry[0]] = reactParser.getES6ReactComponents(entry[1]);
break;
case 'ES5':
formatted[entry[0]] = reactParser.getES5ReactComponents(entry[1]);
break;
default:
formatted[entry[0]] = reactParser.getStatelessFunctionalComponents(entry[1], entry[0]);
break;
}
});
Object.values(formatted).forEach(node => {
node.children.forEach(ele => {
if (Array.isArray(ele.props)) {
ele.props.forEach((propped, i) => {
if (typeof propped.value === 'object' && propped.value.name && propped.value.children) {
formatted[propped.parent].children.push(propped.value);
ele.props.splice(i, 1);
}
});
}
});
});
formatted.monocleENTRY = obj.ENTRY;
fs.writeFileSync('data.js', JSON.stringify(formatted, null, 2));
return formatted;
} | javascript | {
"resource": ""
} |
q28067 | assignFiberPropertiesInDEV | train | function assignFiberPropertiesInDEV(target, source) {
if (target === null) {
// This Fiber's initial properties will always be overwritten.
// We only use a Fiber to ensure the same hidden class so DEV isn't slow.
target = createFiber(IndeterminateComponent, null, null, NoContext);
}
// This is intentionally written as a list of all properties.
// We tried to use Object.assign() instead but this is called in
// the hottest path, and Object.assign() was too slow:
// https://github.com/facebook/react/issues/12502
// This code is DEV-only so size is not a concern.
target.tag = source.tag;
target.key = source.key;
target.elementType = source.elementType;
target.type = source.type;
target.stateNode = source.stateNode;
target.return = source.return;
target.child = source.child;
target.sibling = source.sibling;
target.index = source.index;
target.ref = source.ref;
target.pendingProps = source.pendingProps;
target.memoizedProps = source.memoizedProps;
target.updateQueue = source.updateQueue;
target.memoizedState = source.memoizedState;
target.contextDependencies = source.contextDependencies;
target.mode = source.mode;
target.effectTag = source.effectTag;
target.nextEffect = source.nextEffect;
target.firstEffect = source.firstEffect;
target.lastEffect = source.lastEffect;
target.expirationTime = source.expirationTime;
target.childExpirationTime = source.childExpirationTime;
target.alternate = source.alternate;
if (enableProfilerTimer) {
target.actualDuration = source.actualDuration;
target.actualStartTime = source.actualStartTime;
target.selfBaseDuration = source.selfBaseDuration;
target.treeBaseDuration = source.treeBaseDuration;
}
target._debugID = source._debugID;
target._debugSource = source._debugSource;
target._debugOwner = source._debugOwner;
target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
target._debugHookTypes = source._debugHookTypes;
return target;
} | javascript | {
"resource": ""
} |
q28068 | processor | train | function processor() {
var destination = unified()
var length = attachers.length
var index = -1
while (++index < length) {
destination.use.apply(null, attachers[index])
}
destination.data(extend(true, {}, namespace))
return destination
} | javascript | {
"resource": ""
} |
q28069 | toByteArray | train | function toByteArray(obj) {
var uint = new Uint8Array(obj.length);
for (var i = 0, l = obj.length; i < l; i++){
uint[i] = obj.charCodeAt(i);
}
return new Uint8Array(uint);
} | javascript | {
"resource": ""
} |
q28070 | Vehicle | train | function Vehicle(id, token, unitSystem) {
if (!(this instanceof Vehicle)) {
// eslint-disable-next-line max-len
throw new TypeError("Class constructor Vehicle cannot be invoked without 'new'");
}
this.id = id;
this.token = token;
this.request = util.request.defaults({
baseUrl: util.getUrl(this.id),
auth: {
bearer: this.token,
},
});
this.setUnitSystem(unitSystem || 'metric');
} | javascript | {
"resource": ""
} |
q28071 | relativePath | train | function relativePath(file1, file2) {
var file1Dirname = path.dirname(file1);
var file2Dirname = path.dirname(file2);
if (file1Dirname !== file2Dirname) {
return path.relative(file1Dirname, file2Dirname);
}
return '';
} | javascript | {
"resource": ""
} |
q28072 | curry | train | function curry( func ) {
var args = aps.call( arguments, 1 );
return function() {
return func.apply( this, args.concat( aps.call( arguments ) ) );
};
} | javascript | {
"resource": ""
} |
q28073 | train | function(d) {
return function(t) {
var c = d.sets.map(function(set) {
var start = previous[set], end = circles[set];
if (!start) {
start = {x : width/2, y : height/2, radius : 1};
}
if (!end) {
end = {x : width/2, y : height/2, radius : 1};
}
return {'x' : start.x * (1 - t) + end.x * t,
'y' : start.y * (1 - t) + end.y * t,
'radius' : start.radius * (1 - t) + end.radius * t};
});
return intersectionAreaPath(c);
};
} | javascript | {
"resource": ""
} | |
q28074 | shouldExclude | train | function shouldExclude(sets) {
for (var i = 0; i < sets.length; ++i) {
if (!(sets[i] in exclude)) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q28075 | containedInCircles | train | function containedInCircles(point, circles) {
for (var i = 0; i < circles.length; ++i) {
if (distance(point, circles[i]) > circles[i].radius + SMALL) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q28076 | getIntersectionPoints | train | function getIntersectionPoints(circles) {
var ret = [];
for (var i = 0; i < circles.length; ++i) {
for (var j = i + 1; j < circles.length; ++j) {
var intersect = circleCircleIntersection(circles[i],
circles[j]);
for (var k = 0; k < intersect.length; ++k) {
var p = intersect[k];
p.parentIndex = [i,j];
ret.push(p);
}
}
}
return ret;
} | javascript | {
"resource": ""
} |
q28077 | distance | train | function distance(p1, p2) {
return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) +
(p1.y - p2.y) * (p1.y - p2.y));
} | javascript | {
"resource": ""
} |
q28078 | circleOverlap | train | function circleOverlap(r1, r2, d) {
// no overlap
if (d >= r1 + r2) {
return 0;
}
// completely overlapped
if (d <= Math.abs(r1 - r2)) {
return Math.PI * Math.min(r1, r2) * Math.min(r1, r2);
}
var w1 = r1 - (d * d - r2 * r2 + r1 * r1) / (2 * d),
w2 = r2 - (d * d - r1 * r1 + r2 * r2) / (2 * d);
return circleArea(r1, w1) + circleArea(r2, w2);
} | javascript | {
"resource": ""
} |
q28079 | getCenter | train | function getCenter(points) {
var center = {x: 0, y: 0};
for (var i =0; i < points.length; ++i ) {
center.x += points[i].x;
center.y += points[i].y;
}
center.x /= points.length;
center.y /= points.length;
return center;
} | javascript | {
"resource": ""
} |
q28080 | bisect | train | function bisect(f, a, b, parameters) {
parameters = parameters || {};
var maxIterations = parameters.maxIterations || 100,
tolerance = parameters.tolerance || 1e-10,
fA = f(a),
fB = f(b),
delta = b - a;
if (fA * fB > 0) {
throw "Initial bisect points must have opposite signs";
}
if (fA === 0) return a;
if (fB === 0) return b;
for (var i = 0; i < maxIterations; ++i) {
delta /= 2;
var mid = a + delta,
fMid = f(mid);
if (fMid * fA >= 0) {
a = mid;
}
if ((Math.abs(delta) < tolerance) || (fMid === 0)) {
return mid;
}
}
return a + delta;
} | javascript | {
"resource": ""
} |
q28081 | distanceFromIntersectArea | train | function distanceFromIntersectArea(r1, r2, overlap) {
// handle complete overlapped circles
if (Math.min(r1, r2) * Math.min(r1,r2) * Math.PI <= overlap + SMALL$1) {
return Math.abs(r1 - r2);
}
return bisect(function(distance$$1) {
return circleOverlap(r1, r2, distance$$1) - overlap;
}, 0, r1 + r2);
} | javascript | {
"resource": ""
} |
q28082 | train | function(value, context, scope) {
return this.isInstance(value, context, scope) || (Jsonix.Util.Type.isObject(value) && !Jsonix.Util.Type.isArray(value));
} | javascript | {
"resource": ""
} | |
q28083 | train | function(value){
value = Function.from(value)();
value = (typeof value == 'string') ? value.split(' ') : Array.from(value);
return value.map(function(val){
val = String(val);
var found = false;
Object.each(Fx.CSS.Parsers, function(parser, key){
if (found) return;
var parsed = parser.parse(val);
if (parsed || parsed === 0) found = {value: parsed, parser: parser};
});
found = found || {value: val, parser: Fx.CSS.Parsers.String};
return found;
});
} | javascript | {
"resource": ""
} | |
q28084 | train | function(from, to, delta){
var computed = [];
(Math.min(from.length, to.length)).times(function(i){
computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser});
});
computed.$family = Function.from('fx:css:value');
return computed;
} | javascript | {
"resource": ""
} | |
q28085 | train | function(value, unit){
if (typeOf(value) != 'fx:css:value') value = this.parse(value);
var returned = [];
value.each(function(bit){
returned = returned.concat(bit.parser.serve(bit.value, unit));
});
return returned;
} | javascript | {
"resource": ""
} | |
q28086 | train | function(element, property, value, unit){
element.setStyle(property, this.serve(value, unit));
} | javascript | {
"resource": ""
} | |
q28087 | isScriptLoaded | train | function isScriptLoaded(elem,scriptentry) {
if ((elem[sREADYSTATE] && elem[sREADYSTATE]!==sCOMPLETE && elem[sREADYSTATE]!=="loaded") || scriptentry[sDONE]) { return bFALSE; }
elem[sONLOAD] = elem[sONREADYSTATECHANGE] = nNULL; // prevent memory leak
return bTRUE;
} | javascript | {
"resource": ""
} |
q28088 | resetScroll | train | function resetScroll() {
// Set the element to it original positioning.
target.trigger('preUnfixed.ScrollToFixed');
setUnfixed();
target.trigger('unfixed.ScrollToFixed');
// Reset the last offset used to determine if the page has moved
// horizontally.
lastOffsetLeft = -1;
// Capture the offset top of the target element.
offsetTop = target.offset().top;
// Capture the offset left of the target element.
offsetLeft = target.offset().left;
// If the offsets option is on, alter the left offset.
if (base.options.offsets) {
offsetLeft += (target.offset().left - target.position().left);
}
if (originalOffsetLeft == -1) {
originalOffsetLeft = offsetLeft;
}
position = target.css('position');
// Set that this has been called at least once.
isReset = true;
if (base.options.bottom != -1) {
target.trigger('preFixed.ScrollToFixed');
setFixed();
target.trigger('fixed.ScrollToFixed');
}
} | javascript | {
"resource": ""
} |
q28089 | setFixed | train | function setFixed() {
// Only fix the target element and the spacer if we need to.
if (!isFixed()) {
//get REAL dimensions (decimal fix)
//Ref. http://stackoverflow.com/questions/3603065/how-to-make-jquery-to-not-round-value-returned-by-width
var dimensions = target[0].getBoundingClientRect();
// Set the spacer to fill the height and width of the target
// element, then display it.
spacer.css({
'display' : target.css('display'),
'width' : dimensions.width,
'height' : dimensions.height,
'float' : target.css('float')
});
// Set the target element to fixed and set its width so it does
// not fill the rest of the page horizontally. Also, set its top
// to the margin top specified in the options.
cssOptions={
'z-index' : base.options.zIndex,
'position' : 'fixed',
'top' : base.options.bottom == -1?getMarginTop():'',
'bottom' : base.options.bottom == -1?'':base.options.bottom,
'margin-left' : '0px'
}
if (!base.options.dontSetWidth){ cssOptions['width']=target.css('width'); };
target.css(cssOptions);
target.addClass(base.options.baseClassName);
if (base.options.className) {
target.addClass(base.options.className);
}
position = 'fixed';
}
} | javascript | {
"resource": ""
} |
q28090 | setUnfixed | train | function setUnfixed() {
// Only unfix the target element and the spacer if we need to.
if (!isUnfixed()) {
lastOffsetLeft = -1;
// Hide the spacer now that the target element will fill the
// space.
spacer.css('display', 'none');
// Remove the style attributes that were added to the target.
// This will reverse the target back to the its original style.
target.css({
'z-index' : originalZIndex,
'width' : '',
'position' : originalPosition,
'left' : '',
'top' : originalOffsetTop,
'margin-left' : ''
});
target.removeClass('scroll-to-fixed-fixed');
if (base.options.className) {
target.removeClass(base.options.className);
}
position = null;
}
} | javascript | {
"resource": ""
} |
q28091 | setLeft | train | function setLeft(x) {
// Only if the scroll is not what it was last time we did this.
if (x != lastOffsetLeft) {
// Move the target element horizontally relative to its original
// horizontal position.
target.css('left', offsetLeft - x);
// Hold the last horizontal position set.
lastOffsetLeft = x;
}
} | javascript | {
"resource": ""
} |
q28092 | rstr2binb | train | function rstr2binb(input) {
var i, l = input.length * 8,
output = Array(input.length >> 2),
lo = output.length;
for (i = 0; i < lo; i += 1) {
output[i] = 0;
}
for (i = 0; i < l; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32);
}
return output;
} | javascript | {
"resource": ""
} |
q28093 | train | function(str) {
var crc = 0,
x = 0,
y = 0,
table, i, iTop;
str = utf8Encode(str);
table = [
'00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 ',
'79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 ',
'84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F ',
'63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD ',
'A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC ',
'51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 ',
'B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 ',
'06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 ',
'E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 ',
'12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 ',
'D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 ',
'33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 ',
'CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 ',
'9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E ',
'7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D ',
'806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 ',
'60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA ',
'AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 ',
'5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 ',
'B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 ',
'05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 ',
'F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA ',
'11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 ',
'D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F ',
'30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E ',
'C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D'
].join('');
crc = crc ^ (-1);
for (i = 0, iTop = str.length; i < iTop; i += 1) {
y = (crc ^ str.charCodeAt(i)) & 0xFF;
x = '0x' + table.substr(y * 9, 8);
crc = (crc >>> 8) ^ x;
}
// always return a positive number (that's what >>> 0 does)
return (crc ^ (-1)) >>> 0;
} | javascript | {
"resource": ""
} | |
q28094 | rstr | train | function rstr(s) {
s = (utf8) ? utf8Encode(s) : s;
return binl2rstr(binl(rstr2binl(s), s.length * 8));
} | javascript | {
"resource": ""
} |
q28095 | rstr | train | function rstr(s, utf8) {
s = (utf8) ? utf8Encode(s) : s;
return binb2rstr(binb(rstr2binb(s), s.length * 8));
} | javascript | {
"resource": ""
} |
q28096 | int64copy | train | function int64copy(dst, src) {
dst.h = src.h;
dst.l = src.l;
} | javascript | {
"resource": ""
} |
q28097 | int64revrrot | train | function int64revrrot(dst, x, shift) {
dst.l = (x.h >>> shift) | (x.l << (32 - shift));
dst.h = (x.l >>> shift) | (x.h << (32 - shift));
} | javascript | {
"resource": ""
} |
q28098 | int64shr | train | function int64shr(dst, x, shift) {
dst.l = (x.l >>> shift) | (x.h << (32 - shift));
dst.h = (x.h >>> shift);
} | javascript | {
"resource": ""
} |
q28099 | int64add | train | function int64add(dst, x, y) {
var w0 = (x.l & 0xffff) + (y.l & 0xffff);
var w1 = (x.l >>> 16) + (y.l >>> 16) + (w0 >>> 16);
var w2 = (x.h & 0xffff) + (y.h & 0xffff) + (w1 >>> 16);
var w3 = (x.h >>> 16) + (y.h >>> 16) + (w2 >>> 16);
dst.l = (w0 & 0xffff) | (w1 << 16);
dst.h = (w2 & 0xffff) | (w3 << 16);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.