_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q7700
|
utilCallbackAfterPromise
|
train
|
function utilCallbackAfterPromise(self, func, args, cb) {
args = Array.prototype.slice.apply(args);
let lastarg = args.pop();
if(!cb) cb = lastarg;
func.apply(self, args).then(res => {
try {
cb(null, res);
} catch(e) {
process.nextTick(() => { throw e });
}
}).catch((err) => {
try {
cb(err);
} catch(e) {
process.nextTick(() => { throw e });
}
});
}
|
javascript
|
{
"resource": ""
}
|
q7701
|
removeClass
|
train
|
function removeClass(element, classname) {
// If classList supported, use that
if (element.classList)
element.classList.remove(classname);
// Otherwise, manually filter out classes with given name
else {
element.className = element.className.replace(/([^ ]+)[ ]*/g,
function removeMatchingClasses(match, testClassname) {
// If same class, remove
if (testClassname === classname)
return "";
// Otherwise, allow
return match;
}
);
}
}
|
javascript
|
{
"resource": ""
}
|
q7702
|
modifiersPressed
|
train
|
function modifiersPressed(names) {
// If any required modifiers are not pressed, return false
for (var i=0; i < names.length; i++) {
// Test whether current modifier is pressed
var name = names[i];
if (!(name in modifierKeysyms))
return false;
}
// Otherwise, all required modifiers are pressed
return true;
}
|
javascript
|
{
"resource": ""
}
|
q7703
|
press
|
train
|
function press(keyName, keyElement) {
// Press key if not yet pressed
if (!pressed[keyName]) {
addClass(keyElement, "guac-keyboard-pressed");
// Get current key based on modifier state
var key = getActiveKey(keyName);
// Update modifier state
if (key.modifier) {
// Construct classname for modifier
var modifierClass = "guac-keyboard-modifier-" + getCSSName(key.modifier);
// Retrieve originally-pressed keysym, if modifier was already pressed
var originalKeysym = modifierKeysyms[key.modifier];
// Activate modifier if not pressed
if (!originalKeysym) {
addClass(keyboard, modifierClass);
modifierKeysyms[key.modifier] = key.keysym;
// Send key event
if (osk.onkeydown)
osk.onkeydown(key.keysym);
}
// Deactivate if not pressed
else {
removeClass(keyboard, modifierClass);
delete modifierKeysyms[key.modifier];
// Send key event
if (osk.onkeyup)
osk.onkeyup(originalKeysym);
}
}
// If not modifier, send key event now
else if (osk.onkeydown)
osk.onkeydown(key.keysym);
// Mark key as pressed
pressed[keyName] = true;
}
}
|
javascript
|
{
"resource": ""
}
|
q7704
|
release
|
train
|
function release(keyName, keyElement) {
// Release key if currently pressed
if (pressed[keyName]) {
removeClass(keyElement, "guac-keyboard-pressed");
// Get current key based on modifier state
var key = getActiveKey(keyName);
// Send key event if not a modifier key
if (!key.modifier && osk.onkeyup)
osk.onkeyup(key.keysym);
// Mark key as released
pressed[keyName] = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q7705
|
getKeys
|
train
|
function getKeys(keys) {
var keyArrays = {};
// Coerce all keys into individual key arrays
for (var name in layout.keys) {
keyArrays[name] = asKeyArray(name, keys[name]);
}
return keyArrays;
}
|
javascript
|
{
"resource": ""
}
|
q7706
|
getCSSName
|
train
|
function getCSSName(name) {
// Convert name from possibly-CamelCase to hyphenated lowercase
var cssName = name
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/[^A-Za-z0-9]+/g, '-')
.toLowerCase();
return cssName;
}
|
javascript
|
{
"resource": ""
}
|
q7707
|
touchPress
|
train
|
function touchPress(e) {
e.preventDefault();
ignoreMouse = osk.touchMouseThreshold;
press(object, keyElement);
}
|
javascript
|
{
"resource": ""
}
|
q7708
|
touchRelease
|
train
|
function touchRelease(e) {
e.preventDefault();
ignoreMouse = osk.touchMouseThreshold;
release(object, keyElement);
}
|
javascript
|
{
"resource": ""
}
|
q7709
|
_makeJoiner
|
train
|
function _makeJoiner (type) {
return function (clause, options) {
if (isQueryizeObject(clause)) {
if (typeof options !== 'object') throw new Error('You must define join options when joining against a queryize subquery.');
options = Object.create(options);
options.table = clause;
clause = options;
} else if (typeof clause === 'object') {
if (isArray(clause)) throw new TypeError('Join clauses can only be strings or object definitions');
if (!clause.table) throw new Error('You must define a table to join against');
} else if (typeof options === 'object') {
options = Object.create(options);
options.table = clause;
clause = options;
}
if (typeof clause === 'object') {
clause.type = type;
} else {
clause = clause.search(joinTest) > -1 ? clause.replace(joinTest, type + ' JOIN ') : type + ' JOIN ' + clause;
}
this.join(clause);
return this;
};
}
|
javascript
|
{
"resource": ""
}
|
q7710
|
flatten
|
train
|
function flatten (input, includingObjects) {
var result = [];
function descend (level) {
if (isArray(level)) {
level.forEach(descend);
} else if (typeof level === 'object' && includingObjects) {
Object.keys(level).forEach(function (key) {
descend(level[key]);
});
} else {
result.push(level);
}
}
descend(input);
return result;
}
|
javascript
|
{
"resource": ""
}
|
q7711
|
mysqlDate
|
train
|
function mysqlDate (input) {
var date = new Date(input.getTime());
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
var y = date.getFullYear();
var m = ('0' + (date.getMonth() + 1)).substr(-2);
var d = ('0' + date.getDate()).substr(-2);
var h = ('0' + date.getHours()).substr(-2);
var i = ('0' + date.getMinutes()).substr(-2);
var s = ('0' + date.getSeconds()).substr(-2);
return y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s;
}
|
javascript
|
{
"resource": ""
}
|
q7712
|
arrayFromArguments
|
train
|
function arrayFromArguments () {
var len = arguments.length;
var args = new Array(len);
for (var i = 0; i < len; ++i) {
args[i] = arguments[i];
}
return args;
}
|
javascript
|
{
"resource": ""
}
|
q7713
|
train
|
function() {
var table = {}
// Invert 'alphabet'
for (var i = 0; i < alphabet.length; i++) {
table[alphabet[i]] = i
}
// Splice in 'alias'
for (var key in alias) {
if (!alias.hasOwnProperty(key)) continue
table[key] = table['' + alias[key]]
}
lookup = function() { return table }
return table
}
|
javascript
|
{
"resource": ""
}
|
|
q7714
|
Encoder
|
train
|
function Encoder() {
var skip = 0 // how many bits we will skip from the first byte
var bits = 0 // 5 high bits, carry from one byte to the next
this.output = ''
// Read one byte of input
// Should not really be used except by "update"
this.readByte = function(byte) {
// coerce the byte to an int
if (typeof byte == 'string') byte = byte.charCodeAt(0)
if (skip < 0) { // we have a carry from the previous byte
bits |= (byte >> (-skip))
} else { // no carry
bits = (byte << skip) & 248
}
if (skip > 3) {
// not enough data to produce a character, get us another one
skip -= 8
return 1
}
if (skip < 4) {
// produce a character
this.output += alphabet[bits >> 3]
skip += 5
}
return 0
}
// Flush any remaining bits left in the stream
this.finish = function(check) {
var output = this.output + (skip < 0 ? alphabet[bits >> 3] : '') + (check ? '$' : '')
this.output = ''
return output
}
}
|
javascript
|
{
"resource": ""
}
|
q7715
|
Decoder
|
train
|
function Decoder() {
var skip = 0 // how many bits we have from the previous character
var byte = 0 // current byte we're producing
this.output = ''
// Consume a character from the stream, store
// the output in this.output. As before, better
// to use update().
this.readChar = function(char) {
if (typeof char != 'string'){
if (typeof char == 'number') {
char = String.fromCharCode(char)
}
}
char = char.toLowerCase()
var val = lookup()[char]
if (typeof val == 'undefined') {
// character does not exist in our lookup table
return // skip silently. An alternative would be:
// throw Error('Could not find character "' + char + '" in lookup table.')
}
val <<= 3 // move to the high bits
byte |= val >>> skip
skip += 5
if (skip >= 8) {
// we have enough to preduce output
this.output += String.fromCharCode(byte)
skip -= 8
if (skip > 0) byte = (val << (5 - skip)) & 255
else byte = 0
}
}
this.finish = function(check) {
var output = this.output + (skip < 0 ? alphabet[bits >> 3] : '') + (check ? '$' : '')
this.output = ''
return output
}
}
|
javascript
|
{
"resource": ""
}
|
q7716
|
decode
|
train
|
function decode(input) {
var decoder = new Decoder()
var output = decoder.update(input, true)
return output
}
|
javascript
|
{
"resource": ""
}
|
q7717
|
amf3decUI29
|
train
|
function amf3decUI29(buf) {
var val = 0;
var len = 1;
var b;
do {
b = buf.readUInt8(len++);
val = (val << 7) + (b & 0x7F);
} while (len < 5 || b > 0x7F);
if (len == 5) val = val | b; // Preserve the major bit of the last byte
return { len: len, value: val }
}
|
javascript
|
{
"resource": ""
}
|
q7718
|
amf3encUI29
|
train
|
function amf3encUI29(num) {
var len = 0;
if (num < 0x80) len = 1;
if (num < 0x4000) len = 2;
if (num < 0x200000) len = 3;
if (num >= 0x200000) len = 4;
var buf = new Buffer(len);
switch (len) {
case 1:
buf.writeUInt8(num, 0);
break;
case 2:
buf.writeUInt8(num & 0x7F, 0);
buf.writeUInt8((num >> 7) | 0x80, 1);
break;
case 3:
buf.writeUInt8(num & 0x7F, 0);
buf.writeUInt8((num >> 7) & 0x7F, 1);
buf.writeUInt8((num >> 14) | 0x80, 2);
break;
case 4:
buf.writeUInt8(num & 0xFF, 0);
buf.writeUInt8((num >> 8) & 0x7F, 1);
buf.writeUInt8((num >> 15) | 0x7F, 2);
buf.writeUInt8((num >> 22) | 0x7F, 3);
break;
}
return buf;
}
|
javascript
|
{
"resource": ""
}
|
q7719
|
amf3decInteger
|
train
|
function amf3decInteger(buf) { // Invert the integer
var resp = amf3decUI29(buf);
if (resp.value > 0x0FFFFFFF) resp.value = (resp.value & 0x0FFFFFFF) - 0x10000000;
return resp;
}
|
javascript
|
{
"resource": ""
}
|
q7720
|
amf3encInteger
|
train
|
function amf3encInteger(num) {
var buf = new Buffer(1);
buf.writeUInt8(0x4, 0);
return Buffer.concat([buf, amf3encUI29(num & 0x3FFFFFFF)]); // This AND will auto convert the sign bit!
}
|
javascript
|
{
"resource": ""
}
|
q7721
|
amf3decXmlDoc
|
train
|
function amf3decXmlDoc(buf) {
var sLen = amf3decUI29(buf);
var s = sLen & 1;
sLen = sLen >> 1; // The real length without the lowest bit
if (s) return { len: sLen.value + 5, value: buf.slice(5, sLen.value + 5).toString('utf8') };
throw new Error("Error, we have a need to decode a String that is a Reference"); // TODO: Implement references!
}
|
javascript
|
{
"resource": ""
}
|
q7722
|
amf3encXmlDoc
|
train
|
function amf3encXmlDoc(str) {
var sLen = amf3encUI29(str.length << 1);
var buf = new Buffer(1);
buf.writeUInt8(0x7, 0);
return Buffer.concat([buf, sLen, new Buffer(str, 'utf8')]);
}
|
javascript
|
{
"resource": ""
}
|
q7723
|
amf3decByteArray
|
train
|
function amf3decByteArray(buf) {
var sLen = amf3decUI29(buf);
var s = sLen & 1; // TODO: Check if we follow the same rule!
sLen = sLen >> 1; // The real length without the lowest bit
if (s) return { len: sLen.value + 5, value: buf.slice(5, sLen.value + 5) };
throw new Error("Error, we have a need to decode a String that is a Reference"); // TODO: Implement references!
}
|
javascript
|
{
"resource": ""
}
|
q7724
|
amf3encDouble
|
train
|
function amf3encDouble(num) {
var buf = new Buffer(9);
buf.writeUInt8(0x05, 0);
buf.writeDoubleBE(num, 1);
return buf;
}
|
javascript
|
{
"resource": ""
}
|
q7725
|
amf3decDate
|
train
|
function amf3decDate(buf) { // The UI29 should be 1
var uTz = amf3decUI29(buf);
var ts = buf.readDoubleBE(uTz.len);
return { len: uTz.len + 8, value: ts }
}
|
javascript
|
{
"resource": ""
}
|
q7726
|
amf3encDate
|
train
|
function amf3encDate(ts) {
var buf = new Buffer(1);
buf.writeUInt8(0x8, 0);
var tsBuf = new Buffer(8);
tsBuf.writeDoubleBE(ts, 0);
return Buffer.concat([buf, amf3encUI29(1), tsBuf]); // We always do 1
}
|
javascript
|
{
"resource": ""
}
|
q7727
|
amf3decArray
|
train
|
function amf3decArray(buf) {
var count = amf3decUI29(buf.slice(1));
var obj = amf3decObject(buf.slice(count.len));
if (count.value % 2 == 1) throw new Error("This is a reference to another array, which currently we don't support!");
return { len: count.len + obj.len, value: obj.value }
}
|
javascript
|
{
"resource": ""
}
|
q7728
|
amf0encNumber
|
train
|
function amf0encNumber(num) {
var buf = new Buffer(9);
buf.writeUInt8(0x00, 0);
buf.writeDoubleBE(num, 1);
return buf;
}
|
javascript
|
{
"resource": ""
}
|
q7729
|
amf0encBool
|
train
|
function amf0encBool(num) {
var buf = new Buffer(2);
buf.writeUInt8(0x01, 0);
buf.writeUInt8((num ? 1 : 0), 1);
return buf;
}
|
javascript
|
{
"resource": ""
}
|
q7730
|
amf0encDate
|
train
|
function amf0encDate(ts) {
var buf = new Buffer(11);
buf.writeUInt8(0x0B, 0);
buf.writeInt16BE(0, 1);
buf.writeDoubleBE(ts, 3);
return buf;
}
|
javascript
|
{
"resource": ""
}
|
q7731
|
amf0decObject
|
train
|
function amf0decObject(buf) { // TODO: Implement references!
var obj = {};
var iBuf = buf.slice(1);
var len = 1;
// console.log('ODec',iBuf.readUInt8(0));
while (iBuf.readUInt8(0) != 0x09) {
// console.log('Field', iBuf.readUInt8(0), iBuf);
var prop = amf0decUString(iBuf);
// console.log('Got field for property', prop);
len += prop.len;
if (iBuf.slice(prop.len).readUInt8(0) == 0x09) {
len++;
// console.log('Found the end property');
break;
} // END Object as value, we shall leave
if (prop.value == '') break;
var val = amf0DecodeOne(iBuf.slice(prop.len));
// console.log('Got field for value', val);
obj[prop.value] = val.value;
len += val.len;
iBuf = iBuf.slice(prop.len + val.len);
}
return { len: len, value: obj }
}
|
javascript
|
{
"resource": ""
}
|
q7732
|
amf0encObject
|
train
|
function amf0encObject(o) {
if (typeof o !== 'object') return;
var data = new Buffer(1);
data.writeUInt8(0x03,0); // Type object
var k;
for (k in o) {
data = Buffer.concat([data,amf0encUString(k),amf0EncodeOne(o[k])]);
}
var termCode = new Buffer(1);
termCode.writeUInt8(0x09,0);
return Buffer.concat([data,amf0encUString(''),termCode]);
}
|
javascript
|
{
"resource": ""
}
|
q7733
|
amf0encRef
|
train
|
function amf0encRef(index) {
var buf = new Buffer(3);
buf.writeUInt8(0x07, 0);
buf.writeUInt16BE(index, 1);
return buf;
}
|
javascript
|
{
"resource": ""
}
|
q7734
|
amf0decString
|
train
|
function amf0decString(buf) {
var sLen = buf.readUInt16BE(1);
return { len: 3 + sLen, value: buf.toString('utf8', 3, 3 + sLen) }
}
|
javascript
|
{
"resource": ""
}
|
q7735
|
amf0encUString
|
train
|
function amf0encUString(s) {
var data = new Buffer(s,'utf8');
var sLen = new Buffer(2);
sLen.writeUInt16BE(data.length,0);
return Buffer.concat([sLen,data]);
}
|
javascript
|
{
"resource": ""
}
|
q7736
|
amf0encString
|
train
|
function amf0encString(str) {
var buf = new Buffer(3);
buf.writeUInt8(0x02, 0);
buf.writeUInt16BE(str.length, 1);
return Buffer.concat([buf, new Buffer(str, 'utf8')]);
}
|
javascript
|
{
"resource": ""
}
|
q7737
|
amf0decLongString
|
train
|
function amf0decLongString(buf) {
var sLen = buf.readUInt32BE(1);
return { len: 5 + sLen, value: buf.toString('utf8', 5, 5 + sLen) }
}
|
javascript
|
{
"resource": ""
}
|
q7738
|
amf0encLongString
|
train
|
function amf0encLongString(str) {
var buf = new Buffer(5);
buf.writeUInt8(0x0C, 0);
buf.writeUInt32BE(str.length, 1);
return Buffer.concat([buf, new Buffer(str, 'utf8')]);
}
|
javascript
|
{
"resource": ""
}
|
q7739
|
amf0decArray
|
train
|
function amf0decArray(buf) {
// var count = buf.readUInt32BE(1);
var obj = amf0decObject(buf.slice(4));
return { len: 5 + obj.len, value: obj.value }
}
|
javascript
|
{
"resource": ""
}
|
q7740
|
amf0encArray
|
train
|
function amf0encArray(a) {
var l = 0;
if (a instanceof Array) l = a.length; else l = Object.keys(a).length;
console.log('Array encode', l, a);
var buf = new Buffer(5);
buf.writeUInt8(8,0);
buf.writeUInt32BE(l,1);
var data = amf0encObject(a);
return Buffer.concat([buf,data.slice(1)]);
}
|
javascript
|
{
"resource": ""
}
|
q7741
|
amf0cnvArray2Object
|
train
|
function amf0cnvArray2Object(aData) {
var buf = new Buffer(1);
buf.writeUInt8(0x3,0); // Object id
return Buffer.concat([buf,aData.slice(5)]);
}
|
javascript
|
{
"resource": ""
}
|
q7742
|
amf0cnvObject2Array
|
train
|
function amf0cnvObject2Array(oData) {
var buf = new Buffer(5);
var o = amf0decObject(oData);
var l = Object.keys(o).length;
buf.writeUInt32BE(l,1);
return Buffer.concat([buf,oData.slice(1)]);
}
|
javascript
|
{
"resource": ""
}
|
q7743
|
amf0decXmlDoc
|
train
|
function amf0decXmlDoc(buf) {
var sLen = buf.readUInt16BE(1);
return { len: 3 + sLen, value: buf.toString('utf8', 3, 3 + sLen) }
}
|
javascript
|
{
"resource": ""
}
|
q7744
|
amf0encXmlDoc
|
train
|
function amf0encXmlDoc(str) { // Essentially it is the same as string
var buf = new Buffer(3);
buf.writeUInt8(0x0F, 0);
buf.writeUInt16BE(str.length, 1);
return Buffer.concat([buf, new Buffer(str, 'utf8')]);
}
|
javascript
|
{
"resource": ""
}
|
q7745
|
amf0decSArray
|
train
|
function amf0decSArray(buf) {
var a = [];
var len = 5;
var ret;
for (var count = buf.readUInt32BE(1); count; count--) {
ret = amf0DecodeOne(buf.slice(len));
a.push(ret.value);
len += ret.len;
}
return { len: len, value: amf0markSArray(a) }
}
|
javascript
|
{
"resource": ""
}
|
q7746
|
amf0encSArray
|
train
|
function amf0encSArray(a) {
console.log('Do strict array!');
var buf = new Buffer(5);
buf.writeUInt8(0x0A,0);
buf.writeUInt32BE(a.length,1);
var i;
for (i=0;i< a.length;i++) {
buf = Buffer.concat([buf,amf0EncodeOne(a[i])]);
}
return buf;
}
|
javascript
|
{
"resource": ""
}
|
q7747
|
amf0decTypedObj
|
train
|
function amf0decTypedObj(buf) {
var className = amf0decString(buf);
var obj = amf0decObject(buf.slice(className.len - 1));
obj.value.__className__ = className.value;
return { len: className.len + obj.len - 1, value: obj.value }
}
|
javascript
|
{
"resource": ""
}
|
q7748
|
amfXDecodeOne
|
train
|
function amfXDecodeOne(rules, buffer) {
if (!rules[buffer.readUInt8(0)]) {
console.log('Unknown field', buffer.readUInt8(0));
throw new Error("Error: Unknown field");
}
return rules[buffer.readUInt8(0)](buffer);
}
|
javascript
|
{
"resource": ""
}
|
q7749
|
amfXDecode
|
train
|
function amfXDecode(rules, buffer) {
// We shall receive clean buffer and will respond with an array of values
var resp = [];
var res;
for (var i = 0; i < buffer.length;) {
res = amfXDecodeOne(rules, buffer.slice(i));
i += res.len;
resp.push(res.value); // Add the response
}
return resp;
}
|
javascript
|
{
"resource": ""
}
|
q7750
|
amfXEncodeOne
|
train
|
function amfXEncodeOne(rules, o) {
// console.log('amfXEncodeOne type',o,amfType(o),rules[amfType(o)]);
var f = rules[amfType(o)];
if (f) return f(o);
throw new Error('Unsupported type for encoding!');
}
|
javascript
|
{
"resource": ""
}
|
q7751
|
decodeAMF0Cmd
|
train
|
function decodeAMF0Cmd(dbuf) {
var buffer = dbuf;
var resp = {};
var cmd = amf0DecodeOne(buffer);
resp.cmd = cmd.value;
buffer = buffer.slice(cmd.len);
if (rtmpCmdDecode[cmd.value]) {
rtmpCmdDecode[cmd.value].forEach(function (n) {
if (buffer.length > 0) {
var r = amf0DecodeOne(buffer);
buffer = buffer.slice(r.len);
resp[n] = r.value;
}
});
} else {
console.log('Unknown command', resp);
}
return resp
}
|
javascript
|
{
"resource": ""
}
|
q7752
|
encodeAMF3Cmd
|
train
|
function encodeAMF3Cmd(opt) {
var data = amf0EncodeOne(opt.cmd);
if (rtmpCmdDecode[opt.cmd]) {
rtmpCmdDecode[opt.cmd].forEach(function (n) {
if (opt.hasOwnProperty(n))
data = Buffer.concat([data, amf3EncodeOne(opt[n])]);
});
} else {
console.log('Unknown command', opt);
}
return data
}
|
javascript
|
{
"resource": ""
}
|
q7753
|
_isArrayIndex
|
train
|
function _isArrayIndex (target, key) {
var n = +key;
return Array.isArray(target) && n % 1 === 0 && !(n < 0 && _isEnumerable(target, key));
}
|
javascript
|
{
"resource": ""
}
|
q7754
|
flow
|
train
|
function flow(options) {
const result = spawnSync(bin, [
'check-contents',
'--json',
`--root=${options.root}`,
options.fileName
], {
input: options.source,
encoding: 'utf-8'
});
if (result.status !== 0) {
return [{
message: result.stderr,
loc: {
start: {
line: 1
},
end: {
line: 1
}
}
}];
}
const {errors} = JSON.parse(result.stdout);
return errors.map(error => {
const [leading, ...rest] = error.message;
const payload = rest.map(m => format(m, {
root: options.root
}));
return {
message: [leading.descr, ...payload].join(': '),
path: leading.path,
start: leading.loc.start.line,
end: leading.loc.end.line,
loc: leading.loc
};
});
}
|
javascript
|
{
"resource": ""
}
|
q7755
|
_getPathInfo
|
train
|
function _getPathInfo (obj, parts, walkNonEnumerables) {
if (isNil(obj)) {
throw _makeTypeErrorFor(obj, "object");
}
var target = obj;
var i = -1;
var len = parts.length;
var key;
while (++i < len) {
key = _getPathKey(target, parts[i], walkNonEnumerables);
if (isUndefined(key)) {
break;
}
target = target[key];
}
return i === len ? { isValid: true, target: target } : { isValid: false, target: void 0 };
}
|
javascript
|
{
"resource": ""
}
|
q7756
|
_flatten
|
train
|
function _flatten (array, isDeep, output, idx) {
for (var i = 0, len = array.length, value, j, vLen; i < len; i++) {
value = array[i];
if (!Array.isArray(value)) {
output[idx++] = value;
} else if (isDeep) {
_flatten(value, true, output, idx);
idx = output.length;
} else {
vLen = value.length;
output.length += vLen;
for (j = 0; j < vLen; j++) {
output[idx++] = value[j];
}
}
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
q7757
|
mapValues
|
train
|
function mapValues (object, map) {
return Object.keys(object).reduce((clone, key) =>
Object.assign(clone, { [key]: map(object[key], key) }), {})
}
|
javascript
|
{
"resource": ""
}
|
q7758
|
toBuffer
|
train
|
function toBuffer (object) {
if (Buffer.isBuffer(object)) return object
if (object.buffer) return object.buffer
throw new TypeError('Could not output buffer type.')
}
|
javascript
|
{
"resource": ""
}
|
q7759
|
generateQuery
|
train
|
function generateQuery (fields, options, not) {
let $and = []
const $or = []
const result = {}
for (const key in options)
switch (key) {
case 'and':
case 'or':
const query = {}
query[`$${key}`] = mapValues(options[key], value => {
return generateQuery(fields, value)
})
return query
case 'not':
return generateQuery(fields, options[key], true)
case 'range':
$and.push(generateRangeQuery(fields, options.range))
break
case 'match':
if ('or' in options.match)
for (const key in options.match.or) {
const q = {}
q[key] = options.match.or[key]
$or.push(q)
}
else $and.push(mapValues(options.match, value =>
Array.isArray(value) ? { $in: value } : value))
break
case 'exists':
$and.push(mapValues(options.exists, (value, key) => {
if (!(key in fields)) return void 0
if (fields[key].isArray)
return value ? { $ne: [] } : []
return value ? { $ne: null } : null
}))
break
default:
}
if (not)
$and = $and.map(applyNotOperator)
if ($and.length) result.$and = $and
if ($or.length) result.$or = $or
return result
}
|
javascript
|
{
"resource": ""
}
|
q7760
|
train
|
function(fileName) {
let file = assets[fileName] || {};
fileName = basePath + "/" + fileName.replace(/\\/g, '/');
let key = path.posix.join(uploadPath, fileName);
return new Promise((resolve, reject) => {
let begin = Date.now();
cos.putObject(
{
Bucket: bucket,
Region: region,
Key: key,
Body: fs.createReadStream(file.existsAt),
ContentLength: fs.statSync(file.existsAt).size
},
function(err, body) {
uploadedFiles++;
spinner.text = tip(uploadedFiles, totalFiles);
if (err) return reject(err);
body.duration = Date.now() - begin;
resolve(body);
}
);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q7761
|
train
|
function(err) {
if (err) {
// eslint-disable-next-line no-console
console.log("\n");
return Promise.reject(err);
}
// Get 20 files
let _files = filesNames.splice(0, batch);
if (_files.length) {
return Promise.all(_files.map(performUpload)).then(() => execStack(), execStack);
} else {
return Promise.resolve();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q7762
|
indent
|
train
|
function indent(level) {
var val = options.indent
_indent = ''
if (_lastch === null)
_lastch = _to // as-is, this is the first file
else if (_lastch !== _to) {
_lastch = _to
// istanbul ignore else
if (output)
output.emit('data', _to) // force eol after insert file
}
if (level > 0 && val && !/^0+\D?/.test(val)) {
// format is 2, 2t, 2s, etc. default is spaces
var match = /^(\d+)\s*(t?)/.exec(val),
count = level * (match[1] | 0)
_indent = Array(count + 1).join(match[2] ? '\t' : ' ')
}
}
|
javascript
|
{
"resource": ""
}
|
q7763
|
write
|
train
|
function write(buffer) {
// first, trim trailing whitespace for fast searching
buffer = buffer.replace(/[ \t]+$/gm, '')
// compact lines if emptyLines != -1
if (_elines >= 0)
buffer = trimBuffer(buffer)
if (!buffer) return
// finished the surrounding lines, now the inners
if (!_elines) {
// remove empty lines and change eols in one unique operation
buffer = buffer.replace(/\n{2,}/g, _to)
}
else {
// keep max n empty lines (n+1 sucesive eols), -1 keep all
if (_elines > 0)
buffer = buffer.replace(_re, '$1')
// change line terminator if not unix
if (_to !== '\n') buffer = buffer.replace(/\n/g, _to)
}
// apply indentation, regex `^.` with `/m` matches non-empty lines
if (_indent)
buffer = buffer.replace(/^./mg, _indent + '$&')
_lastch = buffer.slice(-1)
// istanbul ignore else
if (output)
output.emit('data', buffer)
}
|
javascript
|
{
"resource": ""
}
|
q7764
|
GherkinSpec
|
train
|
function GherkinSpec(runner) {
Base.call(this, runner);
let indents = 0;
let n = 0;
if (!Base.useColors) {
colors.enabled = false;
}
function indent() {
return Array(indents).join(' ');
}
runner.on('start', () => {
console.log();
});
runner.on('suite', (suite) => {
indents += 1;
let text = suite.title;
switch (suite.name) {
case 'Feature':
text = colors.underline.bold(suite.title);
suite.stories.forEach((story) => {
text += `\n${indent()} ${story}`;
});
break;
case 'Scenario':
text = colors.green(suite.title);
break;
default:
text = Base.color('suite', text);
}
console.log(indent() + text);
});
runner.on('suite end', () => {
indents -= 1;
if (indents === 1) {
console.log();
}
});
runner.on('pending', (test) => {
console.log(`${indent()} ${colors.cyan(`- ${test.title}`)}`);
});
runner.on('pass', (test) => {
let fmt = indent() + colors.green(` ${Base.symbols.ok} %s`);
if (test.speed === 'fast') {
cursor.CR();
console.log(fmt, test.title);
} else {
fmt += Base.color(test.speed, ' (%dms)');
cursor.CR();
console.log(fmt, test.title, test.duration);
}
});
runner.on('fail', (test) => {
cursor.CR();
n += 1;
console.log(`${indent()} ${colors.red('%d) %s')}`, n, test.title);
});
runner.on('end', this.epilogue.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q7765
|
entry
|
train
|
function entry() {
const patterns = Array.from( arguments );
const entry = {};
patterns.forEach( globPattern => {
// backwards compatibility:
const pattern = globPattern.replace( '[name]', '**' );
return glob.sync( pattern ).forEach( path => {
const baseName = path.replace( /\.[^.]+$/, '' );
entry[ baseName ] = path;
} );
} );
return entry;
}
|
javascript
|
{
"resource": ""
}
|
q7766
|
compileHtml
|
train
|
function compileHtml(src, dest) {
return gulp.src([src])
.pipe(plumber(config.plumberOptions))
.pipe(pug(pugOptions))
.pipe(prettify())
.pipe(gulp.dest(dest));
}
|
javascript
|
{
"resource": ""
}
|
q7767
|
addExtraHeaders
|
train
|
function addExtraHeaders(request, headers) {
for (var name in headers) {
request.setRequestHeader(name, headers[name]);
}
}
|
javascript
|
{
"resource": ""
}
|
q7768
|
reset_timeout
|
train
|
function reset_timeout() {
// Get rid of old timeout (if any)
window.clearTimeout(receive_timeout);
// Set new timeout
receive_timeout = window.setTimeout(function () {
close_tunnel(new Guacamole.Status(Guacamole.Status.Code.UPSTREAM_TIMEOUT, "Server timeout."));
}, tunnel.receiveTimeout);
}
|
javascript
|
{
"resource": ""
}
|
q7769
|
attach
|
train
|
function attach(tunnel) {
// Set own functions to tunnel's functions
chained_tunnel.disconnect = tunnel.disconnect;
chained_tunnel.sendMessage = tunnel.sendMessage;
/**
* Fails the currently-attached tunnel, attaching a new tunnel if
* possible.
*
* @private
* @param {Guacamole.Status} [status]
* An object representing the failure that occured in the
* currently-attached tunnel, if known.
*
* @return {Guacamole.Tunnel}
* The next tunnel, or null if there are no more tunnels to try or
* if no more tunnels should be tried.
*/
var failTunnel = function failTunnel(status) {
// Do not attempt to continue using next tunnel on server timeout
if (status && status.code === Guacamole.Status.Code.UPSTREAM_TIMEOUT) {
tunnels = [];
return null;
}
// Get next tunnel
var next_tunnel = tunnels.shift();
// If there IS a next tunnel, try using it.
if (next_tunnel) {
tunnel.onerror = null;
tunnel.oninstruction = null;
tunnel.onstatechange = null;
attach(next_tunnel);
}
return next_tunnel;
};
/**
* Use the current tunnel from this point forward. Do not try any more
* tunnels, even if the current tunnel fails.
*
* @private
*/
function commit_tunnel() {
tunnel.onstatechange = chained_tunnel.onstatechange;
tunnel.oninstruction = chained_tunnel.oninstruction;
tunnel.onerror = chained_tunnel.onerror;
chained_tunnel.uuid = tunnel.uuid;
committedTunnel = tunnel;
}
// Wrap own onstatechange within current tunnel
tunnel.onstatechange = function(state) {
switch (state) {
// If open, use this tunnel from this point forward.
case Guacamole.Tunnel.State.OPEN:
commit_tunnel();
if (chained_tunnel.onstatechange)
chained_tunnel.onstatechange(state);
break;
// If closed, mark failure, attempt next tunnel
case Guacamole.Tunnel.State.CLOSED:
if (!failTunnel() && chained_tunnel.onstatechange)
chained_tunnel.onstatechange(state);
break;
}
};
// Wrap own oninstruction within current tunnel
tunnel.oninstruction = function(opcode, elements) {
// Accept current tunnel
commit_tunnel();
// Invoke handler
if (chained_tunnel.oninstruction)
chained_tunnel.oninstruction(opcode, elements);
};
// Attach next tunnel on error
tunnel.onerror = function(status) {
// Mark failure, attempt next tunnel
if (!failTunnel(status) && chained_tunnel.onerror)
chained_tunnel.onerror(status);
};
// Attempt connection
tunnel.connect(connect_data);
}
|
javascript
|
{
"resource": ""
}
|
q7770
|
failTunnel
|
train
|
function failTunnel(status) {
// Do not attempt to continue using next tunnel on server timeout
if (status && status.code === Guacamole.Status.Code.UPSTREAM_TIMEOUT) {
tunnels = [];
return null;
}
// Get next tunnel
var next_tunnel = tunnels.shift();
// If there IS a next tunnel, try using it.
if (next_tunnel) {
tunnel.onerror = null;
tunnel.oninstruction = null;
tunnel.onstatechange = null;
attach(next_tunnel);
}
return next_tunnel;
}
|
javascript
|
{
"resource": ""
}
|
q7771
|
commit_tunnel
|
train
|
function commit_tunnel() {
tunnel.onstatechange = chained_tunnel.onstatechange;
tunnel.oninstruction = chained_tunnel.oninstruction;
tunnel.onerror = chained_tunnel.onerror;
chained_tunnel.uuid = tunnel.uuid;
committedTunnel = tunnel;
}
|
javascript
|
{
"resource": ""
}
|
q7772
|
getGuacamoleStatusCode
|
train
|
function getGuacamoleStatusCode(httpStatus) {
// Translate status codes with known equivalents
switch (httpStatus) {
// HTTP 400 - Bad request
case 400:
return Guacamole.Status.Code.CLIENT_BAD_REQUEST;
// HTTP 403 - Forbidden
case 403:
return Guacamole.Status.Code.CLIENT_FORBIDDEN;
// HTTP 404 - Resource not found
case 404:
return Guacamole.Status.Code.RESOURCE_NOT_FOUND;
// HTTP 429 - Too many requests
case 429:
return Guacamole.Status.Code.CLIENT_TOO_MANY;
// HTTP 503 - Server unavailable
case 503:
return Guacamole.Status.Code.SERVER_BUSY;
}
// Default all other codes to generic internal error
return Guacamole.Status.Code.SERVER_ERROR;
}
|
javascript
|
{
"resource": ""
}
|
q7773
|
validateAuthData
|
train
|
function validateAuthData(authData, config) {
var appSecretProof = crypto.createHmac('sha256', config.appSecret).update(authData.access_token).digest('hex');
return graphRequest('me/?access_token=' + authData.access_token + '&appsecret_proof=' + appSecretProof)
.then((data) => {
if (data && data.id == authData.id) {
return;
}
throw new Parse.Error(
Parse.Error.OBJECT_NOT_FOUND,
'AccountKit auth is invalid for this user.');
});
}
|
javascript
|
{
"resource": ""
}
|
q7774
|
getWrappedFunc
|
train
|
function getWrappedFunc(funcName, func, ...args) {
const funcDefaultArgs = defaultArgs[funcName] || defaultArgs['default'];
const allArgs = funcDefaultArgs.concat(args);
return function(...allArgs) {
const boomArgs = _.take(allArgs, funcDefaultArgs.length);
let result = func.call(null, ...boomArgs);
for (var i = 0; i < args.length; i++) {
let currArgVal = allArgs[i + funcDefaultArgs.length];
const argDef = args[i];
// Check if we need to use the defaults
if (currArgVal === undefined){
// Run the function from the args def
if (_.isFunction(argDef.default)) {
result.output.payload[argDef.name] = argDef.default();
// Add the default value to result
} else if (argDef.default) {
result.output.payload[argDef.name] = argDef.default;
}
// Add the passed value to result
} else {
result.output.payload[argDef.name] = currArgVal;
}
}
return result;
};
}
|
javascript
|
{
"resource": ""
}
|
q7775
|
__flush_frames
|
train
|
function __flush_frames() {
var rendered_frames = 0;
// Draw all pending frames, if ready
while (rendered_frames < frames.length) {
var frame = frames[rendered_frames];
if (!frame.isReady())
break;
frame.flush();
rendered_frames++;
}
// Remove rendered frames from array
frames.splice(0, rendered_frames);
}
|
javascript
|
{
"resource": ""
}
|
q7776
|
Task
|
train
|
function Task(taskHandler, blocked) {
var task = this;
/**
* Whether this Task is blocked.
*
* @type {boolean}
*/
this.blocked = blocked;
/**
* Unblocks this Task, allowing it to run.
*/
this.unblock = function() {
if (task.blocked) {
task.blocked = false;
__flush_frames();
}
};
/**
* Calls the handler associated with this task IMMEDIATELY. This
* function does not track whether this task is marked as blocked.
* Enforcing the blocked status of tasks is up to the caller.
*/
this.execute = function() {
if (taskHandler) taskHandler();
};
}
|
javascript
|
{
"resource": ""
}
|
q7777
|
get_children
|
train
|
function get_children(layer) {
// Build array of children
var children = [];
for (var index in layer.children)
children.push(layer.children[index]);
// Sort
children.sort(function children_comparator(a, b) {
// Compare based on Z order
var diff = a.z - b.z;
if (diff !== 0)
return diff;
// If Z order identical, use document order
var a_element = a.getElement();
var b_element = b.getElement();
var position = b_element.compareDocumentPosition(a_element);
if (position & Node.DOCUMENT_POSITION_PRECEDING) return -1;
if (position & Node.DOCUMENT_POSITION_FOLLOWING) return 1;
// Otherwise, assume same
return 0;
});
// Done
return children;
}
|
javascript
|
{
"resource": ""
}
|
q7778
|
draw_layer
|
train
|
function draw_layer(layer, x, y) {
// Draw layer
if (layer.width > 0 && layer.height > 0) {
// Save and update alpha
var initial_alpha = context.globalAlpha;
context.globalAlpha *= layer.alpha / 255.0;
// Copy data
context.drawImage(layer.getCanvas(), x, y);
// Draw all children
var children = get_children(layer);
for (var i=0; i<children.length; i++) {
var child = children[i];
draw_layer(child, x + child.x, y + child.y);
}
// Restore alpha
context.globalAlpha = initial_alpha;
}
}
|
javascript
|
{
"resource": ""
}
|
q7779
|
joinAudioPackets
|
train
|
function joinAudioPackets(packets) {
// Do not bother joining if one or fewer packets are in the queue
if (packets.length <= 1)
return packets[0];
// Determine total sample length of the entire queue
var totalLength = 0;
packets.forEach(function addPacketLengths(packet) {
totalLength += packet.length;
});
// Append each packet within queue
var offset = 0;
var joined = new SampleArray(totalLength);
packets.forEach(function appendPacket(packet) {
joined.set(packet, offset);
offset += packet.length;
});
return joined;
}
|
javascript
|
{
"resource": ""
}
|
q7780
|
splitAudioPacket
|
train
|
function splitAudioPacket(data) {
var minValue = Number.MAX_VALUE;
var optimalSplitLength = data.length;
// Calculate number of whole samples in the provided audio packet AND
// in the minimum possible split packet
var samples = Math.floor(data.length / format.channels);
var minSplitSamples = Math.floor(format.rate * MIN_SPLIT_SIZE);
// Calculate the beginning of the "end" of the audio packet
var start = Math.max(
format.channels * minSplitSamples,
format.channels * (samples - minSplitSamples)
);
// For all samples at the end of the given packet, find a point where
// the perceptible volume across all channels is lowest (and thus is
// the optimal point to split)
for (var offset = start; offset < data.length; offset += format.channels) {
// Calculate the sum of all values across all channels (the result
// will be proportional to the average volume of a sample)
var totalValue = 0;
for (var channel = 0; channel < format.channels; channel++) {
totalValue += Math.abs(data[offset + channel]);
}
// If this is the smallest average value thus far, set the split
// length such that the first packet ends with the current sample
if (totalValue <= minValue) {
optimalSplitLength = offset + format.channels;
minValue = totalValue;
}
}
// If packet is not split, return the supplied packet untouched
if (optimalSplitLength === data.length)
return [data];
// Otherwise, split the packet into two new packets according to the
// calculated optimal split length
return [
new SampleArray(data.buffer.slice(0, optimalSplitLength * format.bytesPerSample)),
new SampleArray(data.buffer.slice(optimalSplitLength * format.bytesPerSample))
];
}
|
javascript
|
{
"resource": ""
}
|
q7781
|
toAudioBuffer
|
train
|
function toAudioBuffer(data) {
// Calculate total number of samples
var samples = data.length / format.channels;
// Determine exactly when packet CAN play
var packetTime = context.currentTime;
if (nextPacketTime < packetTime)
nextPacketTime = packetTime;
// Get audio buffer for specified format
var audioBuffer = context.createBuffer(format.channels, samples, format.rate);
// Convert each channel
for (var channel = 0; channel < format.channels; channel++) {
var audioData = audioBuffer.getChannelData(channel);
// Fill audio buffer with data for channel
var offset = channel;
for (var i = 0; i < samples; i++) {
audioData[i] = data[offset] / maxSampleValue;
offset += format.channels;
}
}
return audioBuffer;
}
|
javascript
|
{
"resource": ""
}
|
q7782
|
enrichSchemaWithRelationships
|
train
|
function enrichSchemaWithRelationships(
schema,
relationships,
isIncludeParentRelationships,
fromModelClass
) {
const processedSchema = _.cloneDeep(schema);
_.forOwn(relationships, (value, key) => {
let relationshipValue;
if (value.relation.name === constants.HasOneRelation) {
//protect from endless recursion
const modelProperties =
value.modelClass !== fromModelClass
? _resolveModelProperties(
value.modelClass,
true,
isIncludeParentRelationships
)
: { type: "object" };
relationshipValue = {
...modelProperties
};
} else if (
isIncludeParentRelationships &&
value.relation.name === constants.BelongsToOneRelation
) {
//protect from endless recursion
const modelProperties =
value.modelClass !== fromModelClass
? _resolveModelProperties(
value.modelClass,
false,
isIncludeParentRelationships
)
: { type: "object" };
relationshipValue = {
...modelProperties
};
} else if (value.relation.name === constants.HasManyRelation) {
//protect from endless recursion
const modelProperties =
value.modelClass !== fromModelClass
? _resolveModelProperties(
value.modelClass,
true,
isIncludeParentRelationships
)
: { type: "object" };
relationshipValue = {
type: "array",
items: {
...modelProperties
}
};
} else if (
isIncludeParentRelationships &&
value.relation.name === constants.ManyToManyRelation
) {
//protect from endless recursion
const modelProperties =
value.modelClass !== fromModelClass
? _resolveModelProperties(
value.modelClass,
false,
isIncludeParentRelationships
)
: { type: "object" };
relationshipValue = {
type: "array",
items: {
...modelProperties
}
};
}
if (relationshipValue) {
processedSchema.properties[key] = relationshipValue;
}
});
return processedSchema;
}
|
javascript
|
{
"resource": ""
}
|
q7783
|
mktag
|
train
|
function mktag(name, html, css, attrs, js, pcex) {
var
c = ', ',
s = '}' + (pcex.length ? ', ' + q(pcex._bp[8]) : '') + ');'
// give more consistency to the output
if (js && js.slice(-1) !== '\n') s = '\n' + s
return 'riot.tag2(\'' + name + "'" + c + q(html) + c + q(css) + c + q(attrs) +
', function(opts) {\n' + js + s
}
|
javascript
|
{
"resource": ""
}
|
q7784
|
parseAttrs
|
train
|
function parseAttrs(str, pcex) {
var
list = [],
match,
k, v, t, e,
DQ = '"'
HTML_ATTR.lastIndex = 0
str = str.replace(/\s+/g, ' ')
while (match = HTML_ATTR.exec(str)) {
// all attribute names are converted to lower case
k = match[1].toLowerCase()
v = match[2]
if (!v) {
list.push(k) // boolean attribute without explicit value
}
else {
// attribute values must be enclosed in double quotes
if (v[0] !== DQ)
v = DQ + (v[0] === "'" ? v.slice(1, -1) : v) + DQ
if (k === 'type' && SPEC_TYPES.test(v)) {
t = v
}
else {
if (/\u0001\d/.test(v)) {
// renames special attributes with expressiones in their value.
if (k === 'value') e = 1
else if (BOOL_ATTRS.test(k)) k = '__' + k
else if (~RIOT_ATTRS.indexOf(k)) k = 'riot-' + k
}
// join the key-value pair, with no spaces between the parts
list.push(k + '=' + v)
}
}
}
// update() will evaluate `type` after the value, avoiding warnings
if (t) {
if (e) t = DQ + pcex._bp[0] + "'" + v.slice(1, -1) + "'" + pcex._bp[1] + DQ
list.push('type=' + t)
}
return list.join(' ') // returns the attribute list
}
|
javascript
|
{
"resource": ""
}
|
q7785
|
splitHtml
|
train
|
function splitHtml(html, opts, pcex) {
var _bp = pcex._bp
// `brackets.split` is a heavy function, so don't call it if not necessary
if (html && _bp[4].test(html)) {
var
jsfn = opts.expr && (opts.parser || opts.type) ? _compileJS : 0,
list = brackets.split(html, 0, _bp),
expr
for (var i = 1; i < list.length; i += 2) {
expr = list[i]
if (expr[0] === '^')
expr = expr.slice(1)
else if (jsfn) {
var israw = expr[0] === '='
expr = jsfn(israw ? expr.slice(1) : expr, opts).trim()
if (expr.slice(-1) === ';') expr = expr.slice(0, -1)
if (israw) expr = '=' + expr
}
list[i] = '\u0001' + (pcex.push(expr.replace(/[\r\n]+/g, ' ').trim()) - 1) + _bp[1]
}
html = list.join('')
}
return html
}
|
javascript
|
{
"resource": ""
}
|
q7786
|
restoreExpr
|
train
|
function restoreExpr(html, pcex) {
if (pcex.length) {
html = html
.replace(/\u0001(\d+)/g, function (_, d) {
var expr = pcex[d]
if (expr[0] === '=') {
expr = expr.replace(brackets.R_STRINGS, function (qs) {
return qs //.replace(/&/g, '&') // I don't know if this make sense
.replace(/</g, '<')
.replace(/>/g, '>')
})
}
return pcex._bp[0] + expr.replace(/"/g, '\u2057')
})
}
return html
}
|
javascript
|
{
"resource": ""
}
|
q7787
|
compileHTML
|
train
|
function compileHTML(html, opts, pcex) {
if (Array.isArray(opts)) {
pcex = opts
opts = {}
}
else {
if (!pcex) pcex = []
if (!opts) opts = {}
}
html = html.replace(/\r\n?/g, '\n').replace(HTML_COMMENT,
function (s) { return s[0] === '<' ? '' : s }).replace(TRIM_TRAIL, '')
// `_bp` is undefined when `compileHTML` is not called by compile
if (!pcex._bp) pcex._bp = brackets.array(opts.brackets)
return _compileHTML(html, opts, pcex)
}
|
javascript
|
{
"resource": ""
}
|
q7788
|
riotjs
|
train
|
function riotjs(js) {
var
match,
toes5,
parts = [], // parsed code
pos
// remove comments
js = js.replace(JS_RMCOMMS, function (m, q) { return q ? m : ' ' })
// $1: indentation,
// $2: method name,
// $3: parameters
while (match = js.match(JS_ES6SIGN)) {
// save remaining part now -- IE9 changes `rightContext` in `RegExp.test`
parts.push(RegExp.leftContext)
js = RegExp.rightContext
pos = skipBlock(js) // find the closing bracket
// convert ES6 method signature to ES5 function
toes5 = !/^(?:if|while|for|switch|catch|function)$/.test(match[2])
if (toes5)
match[0] = match[1] + 'this.' + match[2] + ' = function' + match[3]
parts.push(match[0], js.slice(0, pos))
js = js.slice(pos)
if (toes5 && !/^\s*.\s*bind\b/.test(js)) parts.push('.bind(this)')
}
return parts.length ? parts.join('') + js : js
// Inner helper - find the position following the closing bracket for the current block
function skipBlock(str) {
var
re = _regEx('([{}])|' + brackets.S_QBLOCKS, 'g'),
level = 1,
match
while (level && (match = re.exec(str))) {
if (match[1])
match[1] === '{' ? ++level : --level
}
return level ? str.length : re.lastIndex
}
}
|
javascript
|
{
"resource": ""
}
|
q7789
|
_groupWith
|
train
|
function _groupWith (makeValue) {
return function (arrayLike, iteratee) {
var result = {};
var len = arrayLike.length;
for (var i = 0, element, key; i < len; i++) {
element = arrayLike[i];
key = iteratee(element, i, arrayLike);
result[key] = makeValue(result[key], element);
}
return result;
};
}
|
javascript
|
{
"resource": ""
}
|
q7790
|
_curry3
|
train
|
function _curry3 (fn, isRightCurry) {
return function (a) {
return function (b) {
return function (c) {
return isRightCurry ? fn.call(this, c, b, a) : fn.call(this, a, b, c);
};
};
};
}
|
javascript
|
{
"resource": ""
}
|
q7791
|
getAudioContext
|
train
|
function getAudioContext() {
// Fallback to Webkit-specific AudioContext implementation
var AudioContext = window.AudioContext || window.webkitAudioContext;
// Get new AudioContext instance if Web Audio API is supported
if (AudioContext) {
try {
// Create new instance if none yet exists
if (!Guacamole.AudioContextFactory.singleton)
Guacamole.AudioContextFactory.singleton = new AudioContext();
// Return singleton instance
return Guacamole.AudioContextFactory.singleton;
}
catch (e) {
// Do not use Web Audio API if not allowed by browser
}
}
// Web Audio API not supported
return null;
}
|
javascript
|
{
"resource": ""
}
|
q7792
|
DOT3k
|
train
|
function DOT3k() {
if (!(this instanceof DOT3k)) {
return new DOT3k();
}
this.displayOTron = new DisplayOTron('3k');
this.lcd = new LCD(this.displayOTron);
this.backlight = new Backlight(this.displayOTron);
this.barGraph = new BarGraph(this.displayOTron);
this.joystick = new Joystick(this.displayOTron);
}
|
javascript
|
{
"resource": ""
}
|
q7793
|
_isEnumerable
|
train
|
function _isEnumerable (obj, key) {
return key in Object(obj) && (_isOwnEnumerable(obj, key) || ~_safeEnumerables(obj).indexOf(key));
}
|
javascript
|
{
"resource": ""
}
|
q7794
|
_compareWith
|
train
|
function _compareWith (criteria) {
return function (a, b) {
var len = criteria.length;
var criterion = criteria[0];
var result = criterion.compare(a.value, b.value);
for (var i = 1; result === 0 && i < len; i++) {
criterion = criteria[i];
result = criterion.compare(a.value, b.value);
}
if (result === 0) {
result = a.index - b.index;
}
return criterion.isDescending ? -result : result;
};
}
|
javascript
|
{
"resource": ""
}
|
q7795
|
_currier
|
train
|
function _currier (fn, arity, isRightCurry, isAutoCurry, argsHolder) {
return function () {
var holderLen = argsHolder.length;
var argsLen = arguments.length;
var newArgsLen = holderLen + (argsLen > 1 && isAutoCurry ? argsLen : 1);
var newArgs = Array(newArgsLen);
for (var i = 0; i < holderLen; i++) {
newArgs[i] = argsHolder[i];
}
for (; i < newArgsLen; i++) {
newArgs[i] = arguments[i - holderLen];
}
if (newArgsLen >= arity) {
return fn.apply(this, isRightCurry ? newArgs.reverse() : newArgs);
} else {
return _currier(fn, arity, isRightCurry, isAutoCurry, newArgs);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q7796
|
reset
|
train
|
function reset() {
$scope.count = ngAlertsMngr.get().length;
$scope.badge = ($attrs.badge);
if ($scope.count === 0 && $attrs.hideEmpty) {
$scope.count = '';
}
}
|
javascript
|
{
"resource": ""
}
|
q7797
|
remove
|
train
|
function remove(id) {
var i;
for (i = 0; i < $scope.alerts.length; i += 1) {
if ($scope.alerts[i].id === id) {
$scope.alerts.splice(i, 1);
return;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q7798
|
train
|
function (args) {
var params = angular.extend({
id: ngAlertsId.create(),
msg: '',
type: 'default',
time: Date.now()
}, args);
this.id = params.id;
this.msg = params.msg;
this.type = params.type;
this.time = params.time;
}
|
javascript
|
{
"resource": ""
}
|
|
q7799
|
fire
|
train
|
function fire(name, args) {
ngAlertsEvent.fire(name, args);
ngAlertsEvent.fire('change', args);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.