_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q56500
|
setupTimer
|
train
|
function setupTimer(opts) {
var name, timer;
name = opts.name || node.game.timer.name;
timer = node.timer.getTimer(name);
if (!timer) {
node.warn('setup("timer"): timer not found: ' + name);
return false;
}
if (opts.options) timer.init(opts.options);
switch (opts.action) {
case 'start':
timer.start();
break;
case 'stop':
timer.stop();
break;
case 'restart':
timer.restart();
break;
case 'pause':
timer.pause();
break;
case 'resume':
timer.resume();
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q56501
|
completed
|
train
|
function completed(event) {
var iframeDoc;
// IE < 10 (also 11?) gives 'Permission Denied' if trying to access
// the iframeDoc from the context of the function above.
// We need to re-get it from the DOM.
iframeDoc = J.getIFrameDocument(iframe);
// readyState === "complete" works also in oldIE.
if (event.type === 'load' ||
iframeDoc.readyState === 'complete') {
// Detaching the function to avoid double execution.
iframe.detachEvent('onreadystatechange', completed );
iframeWin.detachEvent('onload', completed );
if (cb) {
// Some browsers fire onLoad too early.
// A small timeout is enough.
setTimeout(function() { cb(); }, 120);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q56502
|
train
|
function(w, data) {
return (w.senderToNameMap[data.id] || data.id) + ' ' +
(data.collapsed ? 'mini' : 'maxi') + 'mized the chat';
}
|
javascript
|
{
"resource": ""
}
|
|
q56503
|
FacePainter
|
train
|
function FacePainter(canvas, settings) {
this.canvas = new W.Canvas(canvas);
this.scaleX = canvas.width / ChernoffFaces.defaults.canvas.width;
this.scaleY = canvas.height / ChernoffFaces.defaults.canvas.heigth;
}
|
javascript
|
{
"resource": ""
}
|
q56504
|
objToLK
|
train
|
function objToLK(obj) {
var p, objLow;
objLow = {};
for (p in obj) {
if (obj.hasOwnProperty(p)) {
objLow[p.toLowerCase()] = obj[p];
}
}
return objLow;
}
|
javascript
|
{
"resource": ""
}
|
q56505
|
invalidRange
|
train
|
function invalidRange(res) {
var body = 'Requested Range Not Satisfiable';
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Length', body.length);
res.statusCode = 416;
res.end(body);
}
|
javascript
|
{
"resource": ""
}
|
q56506
|
train
|
function( page, desiredHeight ) {
var pageParent = page.parent(),
toolbarsAffectingHeight = [],
// We use this function to filter fixed toolbars with option updatePagePadding set to
// true (which is the default) from our height subtraction, because fixed toolbars with
// option updatePagePadding set to true compensate for their presence by adding padding
// to the active page. We want to avoid double-counting by also subtracting their
// height from the desired page height.
noPadders = function() {
var theElement = $( this ),
widgetOptions = $.mobile.toolbar && theElement.data( "mobile-toolbar" ) ?
theElement.toolbar( "option" ) : {
position: theElement.attr( "data-" + $.mobile.ns + "position" ),
updatePagePadding: ( theElement.attr( "data-" + $.mobile.ns +
"update-page-padding" ) !== false )
};
return !( widgetOptions.position === "fixed" &&
widgetOptions.updatePagePadding === true );
},
externalHeaders = pageParent.children( ":jqmData(role='header')" ).filter( noPadders ),
internalHeaders = page.children( ":jqmData(role='header')" ),
externalFooters = pageParent.children( ":jqmData(role='footer')" ).filter( noPadders ),
internalFooters = page.children( ":jqmData(role='footer')" );
// If we have no internal headers, but we do have external headers, then their height
// reduces the page height
if ( internalHeaders.length === 0 && externalHeaders.length > 0 ) {
toolbarsAffectingHeight = toolbarsAffectingHeight.concat( externalHeaders.toArray() );
}
// If we have no internal footers, but we do have external footers, then their height
// reduces the page height
if ( internalFooters.length === 0 && externalFooters.length > 0 ) {
toolbarsAffectingHeight = toolbarsAffectingHeight.concat( externalFooters.toArray() );
}
$.each( toolbarsAffectingHeight, function( index, value ) {
desiredHeight -= $( value ).outerHeight();
});
// Height must be at least zero
return Math.max( 0, desiredHeight );
}
|
javascript
|
{
"resource": ""
}
|
|
q56507
|
train
|
function( height ) {
var page = $( "." + $.mobile.activePageClass ),
pageHeight = page.height(),
pageOuterHeight = page.outerHeight( true );
height = compensateToolbars( page,
( typeof height === "number" ) ? height : $.mobile.getScreenHeight() );
// Remove any previous min-height setting
page.css( "min-height", "" );
// Set the minimum height only if the height as determined by CSS is insufficient
if ( page.height() < height ) {
page.css( "min-height", height - ( pageOuterHeight - pageHeight ) );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56508
|
train
|
function() {
var offset = this.element.offset(),
scrollTop = this.window.scrollTop(),
screenHeight = $.mobile.getScreenHeight();
if ( offset.top < scrollTop || ( offset.top - scrollTop ) > screenHeight ) {
this.element.addClass( "ui-loader-fakefix" );
this.fakeFixLoader();
this.window
.unbind( "scroll", this.checkLoaderPosition )
.bind( "scroll", $.proxy( this.fakeFixLoader, this ) );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56509
|
train
|
function( url, data ) {
data = data || {};
//if there's forward history, wipe it
if ( this.getNext() ) {
this.clearForward();
}
// if the hash is included in the data make sure the shape
// is consistent for comparison
if ( data.hash && data.hash.indexOf( "#" ) === -1) {
data.hash = "#" + data.hash;
}
data.url = url;
this.stack.push( data );
this.activeIndex = this.stack.length - 1;
}
|
javascript
|
{
"resource": ""
}
|
|
q56510
|
train
|
function( historyEntry, direction ) {
// make sure to create a new object to pass down as the navigate event data
event.hashchangeState = $.extend({}, historyEntry);
event.hashchangeState.direction = direction;
}
|
javascript
|
{
"resource": ""
}
|
|
q56511
|
train
|
function( href ) {
// we should do nothing if the user wants to manage their url base
// manually
if ( !$.mobile.dynamicBaseEnabled ) {
return;
}
// we should use the base tag if we can manipulate it dynamically
if ( $.support.dynamicBaseTag ) {
base.element.attr( "href",
$.mobile.path.makeUrlAbsolute( href, $.mobile.path.documentBase ) );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56512
|
train
|
function() {
var options = this.options,
keepNative = $.trim( options.keepNative || "" ),
globalValue = $.trim( $.mobile.keepNative ),
optionValue = $.trim( options.keepNativeDefault ),
// Check if $.mobile.keepNative has changed from the factory default
newDefault = ( keepNativeFactoryDefault === globalValue ?
"" : globalValue ),
// If $.mobile.keepNative has not changed, use options.keepNativeDefault
oldDefault = ( newDefault === "" ? optionValue : "" );
// Concatenate keepNative selectors from all sources where the value has
// changed or, if nothing has changed, return the default
return ( ( keepNative ? [ keepNative ] : [] )
.concat( newDefault ? [ newDefault ] : [] )
.concat( oldDefault ? [ oldDefault ] : [] )
.join( ", " ) );
}
|
javascript
|
{
"resource": ""
}
|
|
q56513
|
train
|
function() {
var hist = $.mobile.navigate.history;
if ( this._isCloseable ) {
this._isCloseable = false;
// If the hash listening is enabled and there is at least one preceding history
// entry it's ok to go back. Initial pages with the dialog hash state are an example
// where the stack check is necessary
if ( $.mobile.hashListeningEnabled && hist.activeIndex > 0 ) {
$.mobile.back();
} else {
$.mobile.pageContainer.pagecontainer( "back" );
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56514
|
train
|
function( options ) {
var key,
accordion = this._ui.accordion,
accordionWidget = this._ui.accordionWidget;
// Copy options
options = $.extend( {}, options );
if ( accordion.length && !accordionWidget ) {
this._ui.accordionWidget =
accordionWidget = accordion.data( "mobile-collapsibleset" );
}
for ( key in options ) {
// Retrieve the option value first from the options object passed in and, if
// null, from the parent accordion or, if that's null too, or if there's no
// parent accordion, then from the defaults.
options[ key ] =
( options[ key ] != null ) ? options[ key ] :
( accordionWidget ) ? accordionWidget.options[ key ] :
accordion.length ? $.mobile.getAttribute( accordion[ 0 ],
key.replace( rInitialLetter, "-$1" ).toLowerCase() ):
null;
if ( null == options[ key ] ) {
options[ key ] = $.mobile.collapsible.defaults[ key ];
}
}
return options;
}
|
javascript
|
{
"resource": ""
}
|
|
q56515
|
train
|
function() {
var dstOffset = this.handle.offset();
this._popup.offset( {
left: dstOffset.left + ( this.handle.width() - this._popup.width() ) / 2,
top: dstOffset.top - this._popup.outerHeight() - 5
});
}
|
javascript
|
{
"resource": ""
}
|
|
q56516
|
train
|
function() {
var screen = this._ui.screen,
popupHeight = this._ui.container.outerHeight( true ),
screenHeight = screen.removeAttr( "style" ).height(),
// Subtracting 1 here is necessary for an obscure Andrdoid 4.0 bug where
// the browser hangs if the screen covers the entire document :/
documentHeight = this.document.height() - 1;
if ( screenHeight < documentHeight ) {
screen.height( documentHeight );
} else if ( popupHeight > screenHeight ) {
screen.height( popupHeight );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56517
|
train
|
function( theEvent ) {
var target,
targetElement = theEvent.target,
ui = this._ui;
if ( !this._isOpen ) {
return;
}
if ( targetElement !== ui.container[ 0 ] ) {
target = $( targetElement );
if ( !$.contains( ui.container[ 0 ], targetElement ) ) {
$( this.document[ 0 ].activeElement ).one( "focus", $.proxy( function() {
this._safelyBlur( targetElement );
}, this ) );
ui.focusElement.focus();
theEvent.preventDefault();
theEvent.stopImmediatePropagation();
return false;
} else if ( ui.focusElement[ 0 ] === ui.container[ 0 ] ) {
ui.focusElement = target;
}
}
this._ignoreResizeEvents();
}
|
javascript
|
{
"resource": ""
}
|
|
q56518
|
train
|
function() {
var ua = navigator.userAgent,
platform = navigator.platform,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
os = null,
self = this;
//set the os we are working in if it dosent match one with workarounds return
if ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) {
os = "ios";
} else if ( ua.indexOf( "Android" ) > -1 ) {
os = "android";
} else {
return;
}
//check os version if it dosent match one with workarounds return
if ( os === "ios" ) {
//iOS workarounds
self._bindScrollWorkaround();
} else if ( os === "android" && wkversion && wkversion < 534 ) {
//Android 2.3 run all Android 2.3 workaround
self._bindScrollWorkaround();
self._bindListThumbWorkaround();
} else {
return;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56519
|
train
|
function() {
var $el = this.element,
header = $el.hasClass( "ui-header" ),
offset = Math.abs( $el.offset().top - this.window.scrollTop() );
if ( !header ) {
offset = Math.round( offset - this.window.height() + $el.outerHeight() ) - 60;
}
return offset;
}
|
javascript
|
{
"resource": ""
}
|
|
q56520
|
train
|
function( p, dir, desired, s, best ) {
var result, r, diff, desiredForArrow = {}, tip = {};
// If the arrow has no wiggle room along the edge of the popup, it cannot
// be displayed along the requested edge without it sticking out.
if ( s.arFull[ p.dimKey ] > s.guideDims[ p.dimKey ] ) {
return best;
}
desiredForArrow[ p.fst ] = desired[ p.fst ] +
( s.arHalf[ p.oDimKey ] + s.menuHalf[ p.oDimKey ] ) * p.offsetFactor -
s.contentBox[ p.fst ] + ( s.clampInfo.menuSize[ p.oDimKey ] - s.contentBox[ p.oDimKey ] ) * p.arrowOffsetFactor;
desiredForArrow[ p.snd ] = desired[ p.snd ];
result = s.result || this._calculateFinalLocation( desiredForArrow, s.clampInfo );
r = { x: result.left, y: result.top };
tip[ p.fst ] = r[ p.fst ] + s.contentBox[ p.fst ] + p.tipOffset;
tip[ p.snd ] = Math.max( result[ p.prop ] + s.guideOffset[ p.prop ] + s.arHalf[ p.dimKey ],
Math.min( result[ p.prop ] + s.guideOffset[ p.prop ] + s.guideDims[ p.dimKey ] - s.arHalf[ p.dimKey ],
desired[ p.snd ] ) );
diff = Math.abs( desired.x - tip.x ) + Math.abs( desired.y - tip.y );
if ( !best || diff < best.diff ) {
// Convert tip offset to coordinates inside the popup
tip[ p.snd ] -= s.arHalf[ p.dimKey ] + result[ p.prop ] + s.contentBox[ p.snd ];
best = { dir: dir, diff: diff, result: result, posProp: p.prop, posVal: tip[ p.snd ] };
}
return best;
}
|
javascript
|
{
"resource": ""
}
|
|
q56521
|
train
|
function (event) {
var target = event.target;
var e = event;
var ev;
// [CDP modified]: set target.clientX.
if (null == target.clientX || null == target.clientY) {
if (null != e.pageX && null != e.pageY) {
target.clientX = e.pageX;
target.clientY = e.pageY;
}
else if (e.changedTouches && e.changedTouches[0]) {
target.clientX = e.changedTouches[0].pageX;
target.clientY = e.changedTouches[0].pageY;
}
}
if (!(/(SELECT|INPUT|TEXTAREA)/i).test(target.tagName)) {
ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, true, e.view, 1, target.screenX, target.screenY, target.clientX, target.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, 0, null);
ev._constructed = true;
target.dispatchEvent(ev);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56522
|
setupByCopy
|
train
|
function setupByCopy() {
let task_dir;
let required_tasks;
try {
const config = require(path.join(process.cwd(), 'project.config'));
required_tasks = config.required_tasks;
if (!required_tasks) {
throw Error('no task required.');
}
task_dir = config.dir.task;
if (!task_dir) {
throw Error('task directory not defined.');
}
} catch (error) {
console.warn(error);
process.exit(0);
}
const dstTaskDir = path.join(process.cwd(), task_dir);
if (!fs.existsSync(dstTaskDir)) {
// create tasks dir
fs.mkdirSync(dstTaskDir);
}
required_tasks.forEach((task) => {
const src = path.join(__dirname, 'tasks', task);
const dst = path.join(dstTaskDir, task);
if (fs.existsSync(src)) {
if (fs.existsSync(dst)) {
fs.unlinkSync(dst);
}
fs.writeFileSync(dst, fs.readFileSync(src).toString());
} else {
console.error('task not found: ' + task);
process.exit(1);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q56523
|
train
|
function () {
var encTable = this._tables[0], decTable = this._tables[1],
sbox = encTable[4], sboxInv = decTable[4],
i, x, xInv, d=[], th=[], x2, x4, x8, s, tEnc, tDec;
// Compute double and third tables
for (i = 0; i < 256; i++) {
th[( d[i] = i<<1 ^ (i>>7)*283 )^i]=i;
}
for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
// Compute sbox
s = xInv ^ xInv<<1 ^ xInv<<2 ^ xInv<<3 ^ xInv<<4;
s = s>>8 ^ s&255 ^ 99;
sbox[x] = s;
sboxInv[s] = x;
// Compute MixColumns
x8 = d[x4 = d[x2 = d[x]]];
tDec = x8*0x1010101 ^ x4*0x10001 ^ x2*0x101 ^ x*0x1010100;
tEnc = d[s]*0x101 ^ s*0x1010100;
for (i = 0; i < 4; i++) {
encTable[i][x] = tEnc = tEnc<<24 ^ tEnc>>>8;
decTable[i][s] = tDec = tDec<<24 ^ tDec>>>8;
}
}
// Compactify. Considerable speedup on Firefox.
for (i = 0; i < 5; i++) {
encTable[i] = encTable[i].slice(0);
decTable[i] = decTable[i].slice(0);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56524
|
train
|
function (input, dir) {
if (input.length !== 4) {
throw new sjcl.exception.invalid("invalid aes block size");
}
var key = this._key[dir],
// state variables a,b,c,d are loaded with pre-whitened data
a = input[0] ^ key[0],
b = input[dir ? 3 : 1] ^ key[1],
c = input[2] ^ key[2],
d = input[dir ? 1 : 3] ^ key[3],
a2, b2, c2,
nInnerRounds = key.length/4 - 2,
i,
kIndex = 4,
out = [0,0,0,0],
table = this._tables[dir],
// load up the tables
t0 = table[0],
t1 = table[1],
t2 = table[2],
t3 = table[3],
sbox = table[4];
// Inner rounds. Cribbed from OpenSSL.
for (i = 0; i < nInnerRounds; i++) {
a2 = t0[a>>>24] ^ t1[b>>16 & 255] ^ t2[c>>8 & 255] ^ t3[d & 255] ^ key[kIndex];
b2 = t0[b>>>24] ^ t1[c>>16 & 255] ^ t2[d>>8 & 255] ^ t3[a & 255] ^ key[kIndex + 1];
c2 = t0[c>>>24] ^ t1[d>>16 & 255] ^ t2[a>>8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];
d = t0[d>>>24] ^ t1[a>>16 & 255] ^ t2[b>>8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];
kIndex += 4;
a=a2; b=b2; c=c2;
}
// Last round.
for (i = 0; i < 4; i++) {
out[dir ? 3&-i : i] =
sbox[a>>>24 ]<<24 ^
sbox[b>>16 & 255]<<16 ^
sbox[c>>8 & 255]<<8 ^
sbox[d & 255] ^
key[kIndex++];
a2=a; a=b; b=c; c=d; d=a2;
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
|
q56525
|
train
|
function (a, bstart, bend) {
a = sjcl.bitArray._shiftRight(a.slice(bstart/32), 32 - (bstart & 31)).slice(1);
return (bend === undefined) ? a : sjcl.bitArray.clamp(a, bend-bstart);
}
|
javascript
|
{
"resource": ""
}
|
|
q56526
|
train
|
function(a, bstart, blength) {
// FIXME: this Math.floor is not necessary at all, but for some reason
// seems to suppress a bug in the Chromium JIT.
var x, sh = Math.floor((-bstart-blength) & 31);
if ((bstart + blength - 1 ^ bstart) & -32) {
// it crosses a boundary
x = (a[bstart/32|0] << (32 - sh)) ^ (a[bstart/32+1|0] >>> sh);
} else {
// within a single word
x = a[bstart/32|0] >>> sh;
}
return x & ((1<<blength) - 1);
}
|
javascript
|
{
"resource": ""
}
|
|
q56527
|
train
|
function (a1, a2) {
if (a1.length === 0 || a2.length === 0) {
return a1.concat(a2);
}
var last = a1[a1.length-1], shift = sjcl.bitArray.getPartial(last);
if (shift === 32) {
return a1.concat(a2);
} else {
return sjcl.bitArray._shiftRight(a2, shift, last|0, a1.slice(0,a1.length-1));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56528
|
train
|
function (a) {
var l = a.length, x;
if (l === 0) { return 0; }
x = a[l - 1];
return (l-1) * 32 + sjcl.bitArray.getPartial(x);
}
|
javascript
|
{
"resource": ""
}
|
|
q56529
|
train
|
function (a, len) {
if (a.length * 32 < len) { return a; }
a = a.slice(0, Math.ceil(len / 32));
var l = a.length;
len = len & 31;
if (l > 0 && len) {
a[l-1] = sjcl.bitArray.partial(len, a[l-1] & 0x80000000 >> (len-1), 1);
}
return a;
}
|
javascript
|
{
"resource": ""
}
|
|
q56530
|
train
|
function (a, b) {
if (sjcl.bitArray.bitLength(a) !== sjcl.bitArray.bitLength(b)) {
return false;
}
var x = 0, i;
for (i=0; i<a.length; i++) {
x |= a[i]^b[i];
}
return (x === 0);
}
|
javascript
|
{
"resource": ""
}
|
|
q56531
|
train
|
function (a, shift, carry, out) {
var i, last2=0, shift2;
if (out === undefined) { out = []; }
for (; shift >= 32; shift -= 32) {
out.push(carry);
carry = 0;
}
if (shift === 0) {
return out.concat(a);
}
for (i=0; i<a.length; i++) {
out.push(carry | a[i]>>>shift);
carry = a[i] << (32-shift);
}
last2 = a.length ? a[a.length-1] : 0;
shift2 = sjcl.bitArray.getPartial(last2);
out.push(sjcl.bitArray.partial(shift+shift2 & 31, (shift + shift2 > 32) ? carry : out.pop(),1));
return out;
}
|
javascript
|
{
"resource": ""
}
|
|
q56532
|
train
|
function (arr) {
var out = "", bl = sjcl.bitArray.bitLength(arr), i, tmp;
for (i=0; i<bl/8; i++) {
if ((i&3) === 0) {
tmp = arr[i/4];
}
out += String.fromCharCode(tmp >>> 24);
tmp <<= 8;
}
return decodeURIComponent(escape(out));
}
|
javascript
|
{
"resource": ""
}
|
|
q56533
|
train
|
function (str) {
str = unescape(encodeURIComponent(str));
var out = [], i, tmp=0;
for (i=0; i<str.length; i++) {
tmp = tmp << 8 | str.charCodeAt(i);
if ((i&3) === 3) {
out.push(tmp);
tmp = 0;
}
}
if (i&3) {
out.push(sjcl.bitArray.partial(8*(i&3), tmp));
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
|
q56534
|
train
|
function (arr) {
var out = "", i;
for (i=0; i<arr.length; i++) {
out += ((arr[i]|0)+0xF00000000000).toString(16).substr(4);
}
return out.substr(0, sjcl.bitArray.bitLength(arr)/4);//.replace(/(.{8})/g, "$1 ");
}
|
javascript
|
{
"resource": ""
}
|
|
q56535
|
train
|
function (str) {
var i, out=[], len;
str = str.replace(/\s|0x/g, "");
len = str.length;
str = str + "00000000";
for (i=0; i<str.length; i+=8) {
out.push(parseInt(str.substr(i,8),16)^0);
}
return sjcl.bitArray.clamp(out, len*4);
}
|
javascript
|
{
"resource": ""
}
|
|
q56536
|
train
|
function (arr, _noEquals, _url) {
var out = "", i, bits=0, c = sjcl.codec.base64._chars, ta=0, bl = sjcl.bitArray.bitLength(arr);
if (_url) {
c = c.substr(0,62) + '-_';
}
for (i=0; out.length * 6 < bl; ) {
out += c.charAt((ta ^ arr[i]>>>bits) >>> 26);
if (bits < 6) {
ta = arr[i] << (6-bits);
bits += 26;
i++;
} else {
ta <<= 6;
bits -= 6;
}
}
while ((out.length & 3) && !_noEquals) { out += "="; }
return out;
}
|
javascript
|
{
"resource": ""
}
|
|
q56537
|
train
|
function(str, _url) {
str = str.replace(/\s|=/g,'');
var out = [], i, bits=0, c = sjcl.codec.base64._chars, ta=0, x;
if (_url) {
c = c.substr(0,62) + '-_';
}
for (i=0; i<str.length; i++) {
x = c.indexOf(str.charAt(i));
if (x < 0) {
throw new sjcl.exception.invalid("this isn't base64!");
}
if (bits > 26) {
bits -= 26;
out.push(ta ^ x>>>bits);
ta = x << (32-bits);
} else {
bits += 6;
ta ^= x << (32-bits);
}
}
if (bits&56) {
out.push(sjcl.bitArray.partial(bits&56, ta, 1));
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
|
q56538
|
train
|
function (data) {
if (typeof data === "string") {
data = sjcl.codec.utf8String.toBits(data);
}
var i, b = this._buffer = sjcl.bitArray.concat(this._buffer, data),
ol = this._length,
nl = this._length = ol + sjcl.bitArray.bitLength(data);
for (i = 512+ol & -512; i <= nl; i+= 512) {
this._block(b.splice(0,16));
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q56539
|
train
|
function (words) {
var i, tmp, a, b,
w = words.slice(0),
h = this._h,
k = this._key,
h0 = h[0], h1 = h[1], h2 = h[2], h3 = h[3],
h4 = h[4], h5 = h[5], h6 = h[6], h7 = h[7];
/* Rationale for placement of |0 :
* If a value can overflow is original 32 bits by a factor of more than a few
* million (2^23 ish), there is a possibility that it might overflow the
* 53-bit mantissa and lose precision.
*
* To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that
* propagates around the loop, and on the hash state h[]. I don't believe
* that the clamps on h4 and on h0 are strictly necessary, but it's close
* (for h4 anyway), and better safe than sorry.
*
* The clamps on h[] are necessary for the output to be correct even in the
* common case and for short inputs.
*/
for (i=0; i<64; i++) {
// load up the input word for this round
if (i<16) {
tmp = w[i];
} else {
a = w[(i+1 ) & 15];
b = w[(i+14) & 15];
tmp = w[i&15] = ((a>>>7 ^ a>>>18 ^ a>>>3 ^ a<<25 ^ a<<14) +
(b>>>17 ^ b>>>19 ^ b>>>10 ^ b<<15 ^ b<<13) +
w[i&15] + w[(i+9) & 15]) | 0;
}
tmp = (tmp + h7 + (h4>>>6 ^ h4>>>11 ^ h4>>>25 ^ h4<<26 ^ h4<<21 ^ h4<<7) + (h6 ^ h4&(h5^h6)) + k[i]); // | 0;
// shift register
h7 = h6; h6 = h5; h5 = h4;
h4 = h3 + tmp | 0;
h3 = h2; h2 = h1; h1 = h0;
h0 = (tmp + ((h1&h2) ^ (h3&(h1^h2))) + (h1>>>2 ^ h1>>>13 ^ h1>>>22 ^ h1<<30 ^ h1<<19 ^ h1<<10)) | 0;
}
h[0] = h[0]+h0 | 0;
h[1] = h[1]+h1 | 0;
h[2] = h[2]+h2 | 0;
h[3] = h[3]+h3 | 0;
h[4] = h[4]+h4 | 0;
h[5] = h[5]+h5 | 0;
h[6] = h[6]+h6 | 0;
h[7] = h[7]+h7 | 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q56540
|
train
|
function(prf, plaintext, iv, adata, tlen) {
var L, out = plaintext.slice(0), tag, w=sjcl.bitArray, ivl = w.bitLength(iv) / 8, ol = w.bitLength(out) / 8;
tlen = tlen || 64;
adata = adata || [];
if (ivl < 7) {
throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");
}
// compute the length of the length
for (L=2; L<4 && ol >>> 8*L; L++) {}
if (L < 15 - ivl) { L = 15-ivl; }
iv = w.clamp(iv,8*(15-L));
// compute the tag
tag = sjcl.mode.ccm._computeTag(prf, plaintext, iv, adata, tlen, L);
// encrypt
out = sjcl.mode.ccm._ctrMode(prf, out, iv, tag, tlen, L);
return w.concat(out.data, out.tag);
}
|
javascript
|
{
"resource": ""
}
|
|
q56541
|
train
|
function(prf, ciphertext, iv, adata, tlen) {
tlen = tlen || 64;
adata = adata || [];
var L,
w=sjcl.bitArray,
ivl = w.bitLength(iv) / 8,
ol = w.bitLength(ciphertext),
out = w.clamp(ciphertext, ol - tlen),
tag = w.bitSlice(ciphertext, ol - tlen), tag2;
ol = (ol - tlen) / 8;
if (ivl < 7) {
throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");
}
// compute the length of the length
for (L=2; L<4 && ol >>> 8*L; L++) {}
if (L < 15 - ivl) { L = 15-ivl; }
iv = w.clamp(iv,8*(15-L));
// decrypt
out = sjcl.mode.ccm._ctrMode(prf, out, iv, tag, tlen, L);
// check the tag
tag2 = sjcl.mode.ccm._computeTag(prf, out.data, iv, adata, tlen, L);
if (!w.equal(out.tag, tag2)) {
throw new sjcl.exception.corrupt("ccm: tag doesn't match");
}
return out.data;
}
|
javascript
|
{
"resource": ""
}
|
|
q56542
|
train
|
function(prf, data, iv, tag, tlen, L) {
var enc, i, w=sjcl.bitArray, xor = w._xor4, ctr, l = data.length, bl=w.bitLength(data);
// start the ctr
ctr = w.concat([w.partial(8,L-1)],iv).concat([0,0,0]).slice(0,4);
// en/decrypt the tag
tag = w.bitSlice(xor(tag,prf.encrypt(ctr)), 0, tlen);
// en/decrypt the data
if (!l) { return {tag:tag, data:[]}; }
for (i=0; i<l; i+=4) {
ctr[3]++;
enc = prf.encrypt(ctr);
data[i] ^= enc[0];
data[i+1] ^= enc[1];
data[i+2] ^= enc[2];
data[i+3] ^= enc[3];
}
return { tag:tag, data:w.clamp(data,bl) };
}
|
javascript
|
{
"resource": ""
}
|
|
q56543
|
train
|
function(prp, plaintext, iv, adata, tlen, premac) {
if (sjcl.bitArray.bitLength(iv) !== 128) {
throw new sjcl.exception.invalid("ocb iv must be 128 bits");
}
var i,
times2 = sjcl.mode.ocb2._times2,
w = sjcl.bitArray,
xor = w._xor4,
checksum = [0,0,0,0],
delta = times2(prp.encrypt(iv)),
bi, bl,
output = [],
pad;
adata = adata || [];
tlen = tlen || 64;
for (i=0; i+4 < plaintext.length; i+=4) {
/* Encrypt a non-final block */
bi = plaintext.slice(i,i+4);
checksum = xor(checksum, bi);
output = output.concat(xor(delta,prp.encrypt(xor(delta, bi))));
delta = times2(delta);
}
/* Chop out the final block */
bi = plaintext.slice(i);
bl = w.bitLength(bi);
pad = prp.encrypt(xor(delta,[0,0,0,bl]));
bi = w.clamp(xor(bi.concat([0,0,0]),pad), bl);
/* Checksum the final block, and finalize the checksum */
checksum = xor(checksum,xor(bi.concat([0,0,0]),pad));
checksum = prp.encrypt(xor(checksum,xor(delta,times2(delta))));
/* MAC the header */
if (adata.length) {
checksum = xor(checksum, premac ? adata : sjcl.mode.ocb2.pmac(prp, adata));
}
return output.concat(w.concat(bi, w.clamp(checksum, tlen)));
}
|
javascript
|
{
"resource": ""
}
|
|
q56544
|
train
|
function(prp, adata) {
var i,
times2 = sjcl.mode.ocb2._times2,
w = sjcl.bitArray,
xor = w._xor4,
checksum = [0,0,0,0],
delta = prp.encrypt([0,0,0,0]),
bi;
delta = xor(delta,times2(times2(delta)));
for (i=0; i+4<adata.length; i+=4) {
delta = times2(delta);
checksum = xor(checksum, prp.encrypt(xor(delta, adata.slice(i,i+4))));
}
bi = adata.slice(i);
if (w.bitLength(bi) < 128) {
delta = xor(delta,times2(delta));
bi = w.concat(bi,[0x80000000|0,0,0,0]);
}
checksum = xor(checksum, bi);
return prp.encrypt(xor(times2(xor(delta,times2(delta))), checksum));
}
|
javascript
|
{
"resource": ""
}
|
|
q56545
|
train
|
function (prf, plaintext, iv, adata, tlen) {
var out, data = plaintext.slice(0), w=sjcl.bitArray;
tlen = tlen || 128;
adata = adata || [];
// encrypt and tag
out = sjcl.mode.gcm._ctrMode(true, prf, data, adata, iv, tlen);
return w.concat(out.data, out.tag);
}
|
javascript
|
{
"resource": ""
}
|
|
q56546
|
train
|
function (prf, ciphertext, iv, adata, tlen) {
var out, data = ciphertext.slice(0), tag, w=sjcl.bitArray, l=w.bitLength(data);
tlen = tlen || 128;
adata = adata || [];
// Slice tag out of data
if (tlen <= l) {
tag = w.bitSlice(data, l-tlen);
data = w.bitSlice(data, 0, l-tlen);
} else {
tag = data;
data = [];
}
// decrypt and tag
out = sjcl.mode.gcm._ctrMode(false, prf, data, adata, iv, tlen);
if (!w.equal(out.tag, tag)) {
throw new sjcl.exception.corrupt("gcm: tag doesn't match");
}
return out.data;
}
|
javascript
|
{
"resource": ""
}
|
|
q56547
|
train
|
function(encrypt, prf, data, adata, iv, tlen) {
var H, J0, S0, enc, i, ctr, tag, last, l, bl, abl, ivbl, w=sjcl.bitArray;
// Calculate data lengths
l = data.length;
bl = w.bitLength(data);
abl = w.bitLength(adata);
ivbl = w.bitLength(iv);
// Calculate the parameters
H = prf.encrypt([0,0,0,0]);
if (ivbl === 96) {
J0 = iv.slice(0);
J0 = w.concat(J0, [1]);
} else {
J0 = sjcl.mode.gcm._ghash(H, [0,0,0,0], iv);
J0 = sjcl.mode.gcm._ghash(H, J0, [0,0,Math.floor(ivbl/0x100000000),ivbl&0xffffffff]);
}
S0 = sjcl.mode.gcm._ghash(H, [0,0,0,0], adata);
// Initialize ctr and tag
ctr = J0.slice(0);
tag = S0.slice(0);
// If decrypting, calculate hash
if (!encrypt) {
tag = sjcl.mode.gcm._ghash(H, S0, data);
}
// Encrypt all the data
for (i=0; i<l; i+=4) {
ctr[3]++;
enc = prf.encrypt(ctr);
data[i] ^= enc[0];
data[i+1] ^= enc[1];
data[i+2] ^= enc[2];
data[i+3] ^= enc[3];
}
data = w.clamp(data, bl);
// If encrypting, calculate hash
if (encrypt) {
tag = sjcl.mode.gcm._ghash(H, S0, data);
}
// Calculate last block from bit lengths, ugly because bitwise operations are 32-bit
last = [
Math.floor(abl/0x100000000), abl&0xffffffff,
Math.floor(bl/0x100000000), bl&0xffffffff
];
// Calculate the final tag block
tag = sjcl.mode.gcm._ghash(H, tag, last);
enc = prf.encrypt(J0);
tag[0] ^= enc[0];
tag[1] ^= enc[1];
tag[2] ^= enc[2];
tag[3] ^= enc[3];
return { tag:w.bitSlice(tag, 0, tlen), data:data };
}
|
javascript
|
{
"resource": ""
}
|
|
q56548
|
train
|
function (paranoia) {
var entropyRequired = this._PARANOIA_LEVELS[ (paranoia !== undefined) ? paranoia : this._defaultParanoia ];
if (this._strength && this._strength >= entropyRequired) {
return (this._poolEntropy[0] > this._BITS_PER_RESEED && (new Date()).valueOf() > this._nextReseed) ?
this._REQUIRES_RESEED | this._READY :
this._READY;
} else {
return (this._poolStrength >= entropyRequired) ?
this._REQUIRES_RESEED | this._NOT_READY :
this._NOT_READY;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56549
|
train
|
function (paranoia) {
var entropyRequired = this._PARANOIA_LEVELS[ paranoia ? paranoia : this._defaultParanoia ];
if (this._strength >= entropyRequired) {
return 1.0;
} else {
return (this._poolStrength > entropyRequired) ?
1.0 :
this._poolStrength / entropyRequired;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56550
|
train
|
function () {
if (this._collectorsStarted) { return; }
this._eventListener = {
loadTimeCollector: this._bind(this._loadTimeCollector),
mouseCollector: this._bind(this._mouseCollector),
keyboardCollector: this._bind(this._keyboardCollector),
accelerometerCollector: this._bind(this._accelerometerCollector),
touchCollector: this._bind(this._touchCollector)
};
if (window.addEventListener) {
window.addEventListener("load", this._eventListener.loadTimeCollector, false);
window.addEventListener("mousemove", this._eventListener.mouseCollector, false);
window.addEventListener("keypress", this._eventListener.keyboardCollector, false);
window.addEventListener("devicemotion", this._eventListener.accelerometerCollector, false);
window.addEventListener("touchmove", this._eventListener.touchCollector, false);
} else if (document.attachEvent) {
document.attachEvent("onload", this._eventListener.loadTimeCollector);
document.attachEvent("onmousemove", this._eventListener.mouseCollector);
document.attachEvent("keypress", this._eventListener.keyboardCollector);
} else {
throw new sjcl.exception.bug("can't attach event");
}
this._collectorsStarted = true;
}
|
javascript
|
{
"resource": ""
}
|
|
q56551
|
train
|
function () {
if (!this._collectorsStarted) { return; }
if (window.removeEventListener) {
window.removeEventListener("load", this._eventListener.loadTimeCollector, false);
window.removeEventListener("mousemove", this._eventListener.mouseCollector, false);
window.removeEventListener("keypress", this._eventListener.keyboardCollector, false);
window.removeEventListener("devicemotion", this._eventListener.accelerometerCollector, false);
window.removeEventListener("touchmove", this._eventListener.touchCollector, false);
} else if (document.detachEvent) {
document.detachEvent("onload", this._eventListener.loadTimeCollector);
document.detachEvent("onmousemove", this._eventListener.mouseCollector);
document.detachEvent("keypress", this._eventListener.keyboardCollector);
}
this._collectorsStarted = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q56552
|
train
|
function (name, cb) {
var i, j, cbs=this._callbacks[name], jsTemp=[];
/* I'm not sure if this is necessary; in C++, iterating over a
* collection and modifying it at the same time is a no-no.
*/
for (j in cbs) {
if (cbs.hasOwnProperty(j) && cbs[j] === cb) {
jsTemp.push(j);
}
}
for (i=0; i<jsTemp.length; i++) {
j = jsTemp[i];
delete cbs[j];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56553
|
train
|
function () {
for (var i=0; i<4; i++) {
this._counter[i] = this._counter[i]+1 | 0;
if (this._counter[i]) { break; }
}
return this._cipher.encrypt(this._counter);
}
|
javascript
|
{
"resource": ""
}
|
|
q56554
|
train
|
function (seedWords) {
this._key = sjcl.hash.sha256.hash(this._key.concat(seedWords));
this._cipher = new sjcl.cipher.aes(this._key);
for (var i=0; i<4; i++) {
this._counter[i] = this._counter[i]+1 | 0;
if (this._counter[i]) { break; }
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56555
|
train
|
function (full) {
var reseedData = [], strength = 0, i;
this._nextReseed = reseedData[0] =
(new Date()).valueOf() + this._MILLISECONDS_PER_RESEED;
for (i=0; i<16; i++) {
/* On some browsers, this is cryptographically random. So we might
* as well toss it in the pot and stir...
*/
reseedData.push(Math.random()*0x100000000|0);
}
for (i=0; i<this._pools.length; i++) {
reseedData = reseedData.concat(this._pools[i].finalize());
strength += this._poolEntropy[i];
this._poolEntropy[i] = 0;
if (!full && (this._reseedCount & (1<<i))) { break; }
}
/* if we used the last pool, push a new one onto the stack */
if (this._reseedCount >= 1 << this._pools.length) {
this._pools.push(new sjcl.hash.sha256());
this._poolEntropy.push(0);
}
/* how strong was this reseed? */
this._poolStrength -= strength;
if (strength > this._strength) {
this._strength = strength;
}
this._reseedCount ++;
this._reseed(reseedData);
}
|
javascript
|
{
"resource": ""
}
|
|
q56556
|
train
|
function (obj) {
var i, out='{', comma='';
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!i.match(/^[a-z0-9]+$/i)) {
throw new sjcl.exception.invalid("json encode: invalid property name");
}
out += comma + '"' + i + '":';
comma = ',';
switch (typeof obj[i]) {
case 'number':
case 'boolean':
out += obj[i];
break;
case 'string':
out += '"' + escape(obj[i]) + '"';
break;
case 'object':
out += '"' + sjcl.codec.base64.fromBits(obj[i],0) + '"';
break;
default:
throw new sjcl.exception.bug("json encode: unsupported type");
}
}
}
return out+'}';
}
|
javascript
|
{
"resource": ""
}
|
|
q56557
|
train
|
function (target, src, requireSame) {
if (target === undefined) { target = {}; }
if (src === undefined) { return target; }
var i;
for (i in src) {
if (src.hasOwnProperty(i)) {
if (requireSame && target[i] !== undefined && target[i] !== src[i]) {
throw new sjcl.exception.invalid("required parameter overridden");
}
target[i] = src[i];
}
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
|
q56558
|
train
|
function (plus, minus) {
var out = {}, i;
for (i in plus) {
if (plus.hasOwnProperty(i) && plus[i] !== minus[i]) {
out[i] = plus[i];
}
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
|
q56559
|
train
|
function (src, filter) {
var out = {}, i;
for (i=0; i<filter.length; i++) {
if (src[filter[i]] !== undefined) {
out[filter[i]] = src[filter[i]];
}
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
|
q56560
|
train
|
function (singular) {
var self = this;
this.singluer = singular;
this.requireDefaultFile = false;
// [CDP customize]
this.folderName = '..\\..\\app\\res\\locales';
// [CDP customize]
this.formatLine = function (key, value) {
var v2 = '' + value;
return ' "' + key + '": "' + v2.replace(/"/g, '\\"') + '",\n';
};
this.formatLastLine = function (key, value) {
var v2 = '' + value;
return ' "' + key + '": "' + v2.replace(/"/g, '\\"') + '"\n';
};
this.formatComment = function (comment) {
return '';
};
this.formatEmptyLine = function () { return ''; };
this.formatHeader = function (localeKey) {
return self.singluer ? '{\n' : '';
};
this.formatFooter = function (localeKey) {
// [CDP customize]
return self.singluer ? '\n}' : '\n';
// [CDP customize]
};
this.getFilePath = function (folderPath, localeKey) {
return folderPath + '\\messages.' + localeKey + '.json';
};
this.normalizeLines = function (lines) {
// format: json-singluer, noop.
if (self.singluer) {
return lines;
}
// ensure JSON object
(function () {
if (typeof JSON !== 'object') {
var fileStream = fso.openTextFile('.\\json2.js');
var fileData = fileStream.readAll();
fileStream.Close();
/*jshint evil: true */
eval(fileData);
/*jshint evil: false */
}
}());
var flatJsonObj = (function () {
var flatSrc = '{\n';
for (var i = 0, n = lines.length; i < n; i++) {
var line = lines[i];
if (i === n - 1) { // last line
line = line.split(',')[0];
}
flatSrc += line;
}
flatSrc += '\n}';
return JSON.parse(flatSrc);
}());
var jsonText = (function (flat) {
var normalize = {};
for (var key in flat) {
var value = flat[key];
var keys = key.split(".");
var temp = normalize;
for (var i = 0, n = keys.length; i < n; i++) {
if (!temp[keys[i]]) {
if (i < n - 1) {
temp[keys[i]] = {};
} else {
temp[keys[i]] = value;
}
}
temp = temp[keys[i]];
}
}
return JSON.stringify(normalize, null, 4);
}(flatJsonObj));
return jsonText.split('\r\n');
};
}
|
javascript
|
{
"resource": ""
}
|
|
q56561
|
train
|
function() {
this.requireDefaultFile = true;
this.folderName = 'conf';
this.isDefaultLocale = function (localeKey) {
if (localeKey == 'en-us' || localeKey == 'en-US') {
return true;
}
return false;
};
this.getDefaultFilePath = function (folderPath) {
return folderPath + '\\' + 'messages';
};
this.formatLine = function (key, value) {
return key + '=' + value + '\n';
};
this.formatLastLine = function (key, value) {
return this.formatLine(key, value);
};
this.formatComment = function (comment) {
return comment + '\n';
};
this.formatEmptyLine = function () { return '\n'; };
this.formatHeader = function (localeKey) { return ''; };
this.formatFooter = function (localeKey) { return ''; };
this.getFilePath = function (folderPath, localeKey) {
return folderPath + '\\messages.' + localeKey;
};
this.normalizeLines = function (lines) {
// noop
return lines;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q56562
|
findExcelFile
|
train
|
function findExcelFile() {
var files = fso.getFolder(".").Files;
for (var e = new Enumerator(files) ; !e.atEnd() ; e.moveNext()) {
var file = e.item();
// [CDP customize]
var extXLSX = '.xlsx';
var extODS = '.ods';
if (file.Name.substr(file.Name.length - extXLSX.length) === extXLSX) {
return file.Path;
} else if (file.Name.substr(file.Name.length - extODS.length) === extODS) {
return file.Path;
}
// [CDP customize]
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q56563
|
getNodeFromFiles
|
train
|
function getNodeFromFiles(scriptFile, mapFile) {
if (fs.existsSync(scriptFile) && fs.existsSync(mapFile)) {
try {
return SourceNode.fromStringWithSourceMap(
getScriptFromFile(scriptFile),
new SourceMapConsumer(getMapFromMapFile(mapFile))
);
} catch (error) {
console.error('getNodeFromFiles() error: ' + error);
return new SourceNode();
}
} else {
return new SourceNode();
}
}
|
javascript
|
{
"resource": ""
}
|
q56564
|
getNodeFromCode
|
train
|
function getNodeFromCode(code) {
if (convert.mapFileCommentRegex.test(code)) {
try {
return SourceNode.fromStringWithSourceMap(
convertCode2Script(code),
new SourceMapConsumer(convert.fromComment(code).toObject())
);
} catch (error) {
console.error('getNodeFromCode() error: ' + error);
const node = new SourceNode();
node.add(convertCode2Script(code));
return node;
}
} else {
const node = new SourceNode();
node.add(convertCode2Script(code));
return node;
}
}
|
javascript
|
{
"resource": ""
}
|
q56565
|
getCodeFromNode
|
train
|
function getCodeFromNode(node, renameSources, options) {
const code_map = getCodeMap(node);
const rename = renameSources;
const objMap = code_map.map.toJSON();
let i, n;
if (rename) {
if ('string' === typeof rename) {
for (i = 0, n = objMap.sources.length; i < n; i++) {
objMap.sources[i] = rename + objMap.sources[i];
}
} else if ('function' === typeof rename) {
for (i = 0, n = objMap.sources.length; i < n; i++) {
objMap.sources[i] = rename(objMap.sources[i]);
}
} else {
console.warn('unexpected type of rename: ' + typeof rename);
}
}
return node.toString() +
convert.fromObject(objMap)
.toComment(options)
.replace(/charset=utf-8;/gm, '')
.replace('data:application/json;', 'data:application/json;charset=utf-8;') + '\n';
}
|
javascript
|
{
"resource": ""
}
|
q56566
|
separateScriptAndMapFromScriptFile
|
train
|
function separateScriptAndMapFromScriptFile(scriptFile, multiline, mapPath) {
const node = getNodeFromScriptFile(scriptFile);
mapPath = mapPath || path.basename(scriptFile) + '.map';
return {
script: node.toString().replace(/\r\n/gm, '\n') + (
multiline
? ('/*# sourceMappingURL=' + mapPath + ' */')
: ('//# sourceMappingURL=' + mapPath)
),
map: JSON.stringify(getCodeMap(node).map.toJSON()),
};
}
|
javascript
|
{
"resource": ""
}
|
q56567
|
getCodeMap
|
train
|
function getCodeMap(node) {
const code_map = node.toStringWithSourceMap();
// patch
node.walkSourceContents(function (sourceFile, sourceContent) {
if (!code_map.map._sources.has(sourceFile)) {
code_map.map._sources.add(sourceFile);
}
});
return code_map;
}
|
javascript
|
{
"resource": ""
}
|
q56568
|
Config
|
train
|
function Config(opts) {
_.extend(this, {
appName: 'ndm', // used by rc.
serviceJsonPath: path.resolve(process.cwd(), 'service.json'),
tmpServiceJsonPath: null, // used during install phase.
logsDirectory: this.defaultLogsDirectory(),
env: process.env,
uid: null,
gid: null,
console: null, // In upstart 1.4, where should logs be sent? <logged|output|owner|none>
sudo: null,
headless: false,
filter: null,
modulePrefix: '',
nodeBin: process.execPath,
baseWorkingDirectory: path.resolve(process.cwd()),
globalPackage: false,
platform: null, // override the platform ndm generates services for
platformApis: {
ubuntu: require('./platform-apis/ubuntu'),
centos: require('./platform-apis/centos'),
darwin: require('./platform-apis/darwin'),
initd: require('./platform-apis/init-d')
},
parsers: {
sudo: function(v) { return v.toString() === 'true' },
headless: function(v) { return v.toString() === 'true' },
globalPackage: function(v) { return v.toString() === 'true' }
}
}, opts);
// allow platform to be overridden.
this.platform = this.os();
// allow platform and env to be overridden before applying.
_.extend(this, this._getEnv(), opts);
this._rcOverride();
}
|
javascript
|
{
"resource": ""
}
|
q56569
|
getLaunchStoryboardContentsJSON
|
train
|
function getLaunchStoryboardContentsJSON(splashScreens, launchStoryboardImagesDir) {
var platformLaunchStoryboardImages = mapLaunchStoryboardContents(splashScreens, launchStoryboardImagesDir);
var contentsJSON = {
images: [],
info: {
author: 'Xcode',
version: 1
}
};
contentsJSON.images = platformLaunchStoryboardImages.map(function(item) {
var newItem = {
idiom: item.idiom,
scale: item.scale
};
// Xcode doesn't want any size class property if the class is "any"
// If our size class is "com", Xcode wants "compact".
if (item.width !== CDV_ANY_SIZE_CLASS) {
newItem['width-class'] = IMAGESET_COMPACT_SIZE_CLASS;
}
if (item.height !== CDV_ANY_SIZE_CLASS) {
newItem['height-class'] = IMAGESET_COMPACT_SIZE_CLASS;
}
// Xcode doesn't want a filename property if there's no image for these traits
if (item.filename) {
newItem.filename = item.filename;
}
return newItem;
});
return contentsJSON;
}
|
javascript
|
{
"resource": ""
}
|
q56570
|
checkIfBuildSettingsNeedUpdatedForLaunchStoryboard
|
train
|
function checkIfBuildSettingsNeedUpdatedForLaunchStoryboard(platformConfig, infoPlist) {
var hasLaunchStoryboardImages = platformHasLaunchStoryboardImages(platformConfig);
var hasLegacyLaunchImages = platformHasLegacyLaunchImages(platformConfig);
var currentLaunchStoryboard = infoPlist[UI_LAUNCH_STORYBOARD_NAME];
if (hasLaunchStoryboardImages && currentLaunchStoryboard == CDV_LAUNCH_STORYBOARD_NAME && !hasLegacyLaunchImages) {
// don't need legacy launch images if we are using our launch storyboard
// so we do need to update the project file
events.emit('verbose', 'Need to update build settings because project is using our launch storyboard.');
return true;
} else if (hasLegacyLaunchImages && !currentLaunchStoryboard) {
// we do need to ensure legacy launch images are used if there's no launch storyboard present
// so we do need to update the project file
events.emit('verbose', 'Need to update build settings because project is using legacy launch images and no storyboard.');
return true;
}
events.emit('verbose', 'No need to update build settings for launch storyboard support.');
return false;
}
|
javascript
|
{
"resource": ""
}
|
q56571
|
NativeBridge
|
train
|
function NativeBridge(feature, options) {
if (!(this instanceof NativeBridge)) {
return new NativeBridge(feature, options);
}
this._feature = feature;
this._objectId = "object:" + _utils.createUUID();
this._execTaskHistory = {};
}
|
javascript
|
{
"resource": ""
}
|
q56572
|
moving_maximum
|
train
|
function moving_maximum(array, n) {
var nums = [];
for (i in array) {
if (_.isNumber(array[i])) {
nums.push(array[i]);
if (nums.length > n) {
nums.splice(0,1); /* Remove the first element of the array */
}
/* Take the average of the n items in this array */
var maximum = _.max(nums);
array[i] = maximum;
}
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q56573
|
apply_moving_filter
|
train
|
function apply_moving_filter(set, filter, n) {
if (!_.isNumber(n)) { n = 3; }
for (series in set) { /* For each series */
/* Apply the filter */
set[series] = filter(set[series], n);
}
return set;
}
|
javascript
|
{
"resource": ""
}
|
q56574
|
time_format
|
train
|
function time_format(options) {
if (_.isString(options.time)) {
/* Translate the string we've been given into a format */
switch(options.time) {
case 'days':
case 'Days':
return "%d/%m";
case 'hours':
case 'Hours':
return "%H:%M";
default: /* Presume we've been given a gnuplot-readable time format string */
return options.time;
}
} else { /* Just default to hours */
return "%H:%M";
}
}
|
javascript
|
{
"resource": ""
}
|
q56575
|
setup_gnuplot
|
train
|
function setup_gnuplot(gnuplot, options) {
if (options.format === 'svg') { /* Setup gnuplot for SVG */
gnuplot.stdin.write('set term svg fname \"Helvetica\" fsize 14\n');
} else if (options.format == 'pdf') {
/* PDF: setup Gnuplot output to postscript so ps2pdf can interpret it */
gnuplot.stdin.write('set term postscript landscape enhanced color dashed' +
'\"Helvetica\" 14\n');
} else { /* Setup gnuplot for png */
gnuplot.stdin.write('set term png\n');
}
/* Formatting Options */
if (options.time) {
gnuplot.stdin.write('set xdata time\n');
gnuplot.stdin.write('set timefmt "%s"\n');
gnuplot.stdin.write('set format x "' + time_format(options.time) + '"\n');
gnuplot.stdin.write('set xlabel "time"\n');
}
if (options.title) {
gnuplot.stdin.write('set title "'+options.title+'"\n');
}
if (options.logscale) {
gnuplot.stdin.write('set logscale y\n');
}
if (options.xlabel) {
gnuplot.stdin.write('set xlabel "'+options.xlabel+'"\n');
}
if (options.ylabel) {
gnuplot.stdin.write('set ylabel "'+options.ylabel+'"\n');
}
/* Setup ticks */
gnuplot.stdin.write('set grid xtics ytics mxtics\n');
gnuplot.stdin.write('set mxtics\n');
if (options.nokey) {
gnuplot.stdin.write('set nokey\n');
}
}
|
javascript
|
{
"resource": ""
}
|
q56576
|
PlatformBase
|
train
|
function PlatformBase(opts) {
_.extend(this, {
platform: null,
// path to template to use for service generation,
// use of a template may be optional.
template: null,
logger: require('../logger')
}, opts);
}
|
javascript
|
{
"resource": ""
}
|
q56577
|
train
|
function(vector) {
var n = this.elements.length;
var V = vector.elements || vector;
if (n != V.length) { return false; }
do {
if (Math.abs(this.elements[n-1] - V[n-1]) > Sylvester.precision) { return false; }
} while (--n);
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q56578
|
train
|
function(vector) {
var V = vector.elements || vector;
var i, product = 0, n = this.elements.length;
if (n != V.length) { return null; }
do { product += this.elements[n-1] * V[n-1]; } while (--n);
return product;
}
|
javascript
|
{
"resource": ""
}
|
|
q56579
|
train
|
function(obj) {
if (obj.anchor) { return obj.distanceFrom(this); }
var V = obj.elements || obj;
if (V.length != this.elements.length) { return null; }
var sum = 0, part;
this.each(function(x, i) {
part = x - V[i-1];
sum += part * part;
});
return Math.sqrt(sum);
}
|
javascript
|
{
"resource": ""
}
|
|
q56580
|
train
|
function() {
if (!this.isSquare()) { return null; }
var tr = this.elements[0][0], n = this.elements.length - 1, k = n, i;
do { i = k - n + 1;
tr += this.elements[i][i];
} while (--n);
return tr;
}
|
javascript
|
{
"resource": ""
}
|
|
q56581
|
train
|
function(obj) {
if (obj.normal) { return obj.distanceFrom(this); }
if (obj.direction) {
// obj is a line
if (this.isParallelTo(obj)) { return this.distanceFrom(obj.anchor); }
var N = this.direction.cross(obj.direction).toUnitVector().elements;
var A = this.anchor.elements, B = obj.anchor.elements;
return Math.abs((A[0] - B[0]) * N[0] + (A[1] - B[1]) * N[1] + (A[2] - B[2]) * N[2]);
} else {
// obj is a point
var P = obj.elements || obj;
var A = this.anchor.elements, D = this.direction.elements;
var PA1 = P[0] - A[0], PA2 = P[1] - A[1], PA3 = (P[2] || 0) - A[2];
var modPA = Math.sqrt(PA1*PA1 + PA2*PA2 + PA3*PA3);
if (modPA === 0) return 0;
// Assumes direction vector is normalized
var cosTheta = (PA1 * D[0] + PA2 * D[1] + PA3 * D[2]) / modPA;
var sin2 = 1 - cosTheta*cosTheta;
return Math.abs(modPA * Math.sqrt(sin2 < 0 ? 0 : sin2));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56582
|
train
|
function(anchor, direction) {
// Need to do this so that line's properties are not
// references to the arguments passed in
anchor = Vector.create(anchor);
direction = Vector.create(direction);
if (anchor.elements.length == 2) {anchor.elements.push(0); }
if (direction.elements.length == 2) { direction.elements.push(0); }
if (anchor.elements.length > 3 || direction.elements.length > 3) { return null; }
var mod = direction.modulus();
if (mod === 0) { return null; }
this.anchor = anchor;
this.direction = Vector.create([
direction.elements[0] / mod,
direction.elements[1] / mod,
direction.elements[2] / mod
]);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q56583
|
_getExtension
|
train
|
function _getExtension(file) {
var ret;
if (file) {
var fileTypes = file.split(".");
var len = fileTypes.length;
if (0 === len) {
return ret;
}
ret = fileTypes[len - 1];
return ret;
}
}
|
javascript
|
{
"resource": ""
}
|
q56584
|
_getScriptElements
|
train
|
function _getScriptElements($typeLazy) {
var scripts;
var src = $typeLazy.attr("src");
if (!src) {
src = $typeLazy.data("src");
}
if ("js" === _getExtension(src).toLowerCase()) {
return $typeLazy;
} else {
if (requirejs && typeof requirejs.toUrl === "function") {
src = requirejs.toUrl(src);
}
$.ajax({
url: src,
method: "GET",
async: false,
dataType: "html",
success: function (data){
scripts = data;
},
error: function (data, status) {
console.error(TAG + "lazyLoad() ajax request failed. [status: " + status + "][src: " + src + "]");
}
});
return $(scripts).find("script");
}
}
|
javascript
|
{
"resource": ""
}
|
q56585
|
_appendSync
|
train
|
function _appendSync($script) {
var _src = $script.attr("src");
if (!_src) {
_src = $script.data("src");
}
var _url = function ($elem) {
var ret = _src;
if (requirejs && typeof requirejs.toUrl === "function") {
ret = requirejs.toUrl(ret);
$elem.attr("src", ret);
}
return ret;
}($script);
var toLocation = function (url) {
// 明示的に autoDomainAssign = false が指定されているときは、_src を返す
if (false === Config.autoDomainAssign) {
return _src;
} else {
var ret = url.split("?");
if (!ret || 0 === ret.length) {
return url;
} else {
return ret[0];
}
}
};
var code;
$.ajax({
url: _url,
method: "GET",
async: false,
dataType: "text",
success: function (data) {
code = data;
},
error: function (data, status) {
console.error(TAG + "lazyLoad() ajax request failed. [status: " + status + "][src: " + _url + "]");
}
});
if (code) {
// sourceURL が指定されていなければ追加
if (!code.match(/\/\/@ sourceURL=[\s\S]*?\n/g) && !code.match(/\/\/# sourceURL=[\s\S]*?\n/g)) {
code = code + "\n//# " + "sourceURL=" + toLocation(_url);
}
// script を有効化
$.globalEval(code);
// <head> に <script> として追加
$script.attr("type", "false");
document.head.appendChild($script[0]);
$script.removeAttr("type");
}
}
|
javascript
|
{
"resource": ""
}
|
q56586
|
Service
|
train
|
function Service(opts) {
_.extend(this,
{
description: '',
utils: require('./utils'),
logger: require('./logger')
},
require('./config')(),
opts
);
// scoped modules contain a '/' (@foo/bar).
// this causes problems when generating logs/scripts
// on some platforms.
this.name = this.name.replace('/', '_');
// run the script within its ndm
// node_modules directory.
this.workingDirectory = this._workingDirectory();
this.logFile = this.utils.resolve(
this.logsDirectory,
this.name + '.log'
);
this._copyFieldsFromPackageJson(); // try to grab some sane defaults from package.json.
}
|
javascript
|
{
"resource": ""
}
|
q56587
|
parseServiceJson
|
train
|
function parseServiceJson(serviceNameFilter, serviceJson) {
var services = [],
config = require('./config')();
Object.keys(serviceJson).forEach(function(serviceName) {
if (serviceName === 'env' || serviceName === 'args') return;
var serviceConfig = serviceJson[serviceName],
processCount = serviceConfig.processes || 1;
// if services have a process count > 1,
// we'll create multiple run-scripts for them.
_.range(processCount).forEach(function(i) {
// apply sane defaults as we create
// the services.
var service = new Service(_.extend(
{
module: serviceName,
name: i > 0 ? (serviceName + '-' + i) : serviceName
},
serviceConfig
));
// override env and args with global args and env.
service.env = _.extend({},
dropInterviewQuestions(serviceJson.env),
dropInterviewQuestions(serviceConfig.env)
);
service.args = serviceConfig.args;
if (_.isArray(serviceConfig.args)) {
// combine arrays of arguments, if both top-level args.
// and service-level args are an array.
if (_.isArray(serviceJson.args)) service.args = [].concat(serviceJson.args, service.args);
} else {
// merge objects together if top-level, and service level
// arguments are maps.
service.args = _.extend({},
dropInterviewQuestions(serviceJson.args),
dropInterviewQuestions(serviceConfig.args)
);
}
// we can optionaly filter to a specific service name.
if (serviceNameFilter && service.name !== serviceNameFilter && !config.globalPackage) return;
// replace placeholder variables
// in the service.json.
expandVariables(service, i);
services.push(service);
});
});
return services;
}
|
javascript
|
{
"resource": ""
}
|
q56588
|
train
|
function(uri, method, headers, data, encType) {
var config = this.config;
var flags = [];
var str;
method = method || 'GET';
if (data && method.toLowerCase() === 'get') {
uri += this.buildQueryString(data);
}
str = ['curl', this.buildFlag('X', method.toUpperCase(), 0, ''), '"' + uri + '"'].join(' ');
if (headers) {
_.each(headers, function(val, header) {
flags.push(this.buildFlag('H', header + config.HEADER_SEPARATOR + val, 5));
}, this);
}
if (data && method.toLowerCase() !== 'get') {
if (encType === undefined || encType.match(this.formatter.jsonMediaType)) {
flags.push(this.buildFlag('-data', this.formatData(data), 5, '\''));
} else if (encType === 'multipart/form-data') {
flags.push(this.buildFlag('-form', this.formatForm(data), 5, '"'));
} else {
// The non-JSON, non-multipart data is a raw string. Do not format it.
flags.push(this.buildFlag('-data', data));
}
}
if (flags.length) {
return str + config.NEW_LINE + flags.join(config.NEW_LINE);
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
|
q56589
|
findNodeModules
|
train
|
function findNodeModules(cwd) {
var parts = cwd.split(path.sep)
while (parts.length > 0) {
var target = path.join(parts.join(path.sep), 'node_modules')
if (fs.existsSync(target)) {
return target
}
parts.pop()
}
}
|
javascript
|
{
"resource": ""
}
|
q56590
|
train
|
function () {
Meta.globalTag ('dummy')
$assertEveryCalled (function (mkay1, mkay2) { var this_ = undefined
var Trait = $trait ({
somethingHappened: $trigger () })
var Other = $trait ({
somethingHappened: $dummy (function (_42) { $assert (this, this_); $assert (_42, 42); mkay1 () }) })
var Compo = $component ({
$traits: [Trait, Other],
somethingHappened: function (_42) { $assert (this, this_); $assert (_42, 42); mkay2 () } })
this_ = new Compo ()
this_.somethingHappened (42) }) }
|
javascript
|
{
"resource": ""
}
|
|
q56591
|
tryFullscreen
|
train
|
function tryFullscreen(shell) {
//Request full screen
var elem = shell.element
if(shell._wantFullscreen && !shell._fullscreenActive) {
var fs = elem.requestFullscreen ||
elem.requestFullScreen ||
elem.webkitRequestFullscreen ||
elem.webkitRequestFullScreen ||
elem.mozRequestFullscreen ||
elem.mozRequestFullScreen ||
function() {}
fs.call(elem)
}
if(shell._wantPointerLock && !shell._pointerLockActive) {
var pl = elem.requestPointerLock ||
elem.webkitRequestPointerLock ||
elem.mozRequestPointerLock ||
elem.msRequestPointerLock ||
elem.oRequestPointerLock ||
function() {}
pl.call(elem)
}
}
|
javascript
|
{
"resource": ""
}
|
q56592
|
setKeyState
|
train
|
function setKeyState(shell, key, state) {
var ps = shell._curKeyState[key]
if(ps !== state) {
if(state) {
shell._pressCount[key]++
} else {
shell._releaseCount[key]++
}
shell._curKeyState[key] = state
}
}
|
javascript
|
{
"resource": ""
}
|
q56593
|
tick
|
train
|
function tick(shell) {
var skip = hrtime() + shell.frameSkip
, pCount = shell._pressCount
, rCount = shell._releaseCount
, i, s, t
, tr = shell._tickRate
, n = keyNames.length
while(!shell._paused &&
hrtime() >= shell._lastTick + tr) {
//Skip frames if we are over budget
if(hrtime() > skip) {
shell._lastTick = hrtime() + tr
return
}
//Tick the game
s = hrtime()
shell.emit("tick")
t = hrtime()
shell.tickTime = t - s
//Update counters and time
++shell.tickCount
shell._lastTick += tr
//Shift input state
for(i=0; i<n; ++i) {
pCount[i] = rCount[i] = 0
}
if(shell._pointerLockActive) {
shell.prevMouseX = shell.mouseX = shell.width>>1
shell.prevMouseY = shell.mouseY = shell.height>>1
} else {
shell.prevMouseX = shell.mouseX
shell.prevMouseY = shell.mouseY
}
shell.scroll[0] = shell.scroll[1] = shell.scroll[2] = 0
}
}
|
javascript
|
{
"resource": ""
}
|
q56594
|
handleKeyUp
|
train
|
function handleKeyUp(shell, ev) {
handleEvent(shell, ev)
var kc = physicalKeyCode(ev.keyCode || ev.char || ev.which || ev.charCode)
if(kc >= 0) {
setKeyState(shell, kc, false)
}
}
|
javascript
|
{
"resource": ""
}
|
q56595
|
handleKeyDown
|
train
|
function handleKeyDown(shell, ev) {
if(!isFocused(shell)) {
return
}
handleEvent(shell, ev)
if(ev.metaKey) {
//Hack: Clear key state when meta gets pressed to prevent keys sticking
handleBlur(shell, ev)
} else {
var kc = physicalKeyCode(ev.keyCode || ev.char || ev.which || ev.charCode)
if(kc >= 0) {
setKeyState(shell, kc, true)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q56596
|
handleMouseWheel
|
train
|
function handleMouseWheel(shell, ev) {
handleEvent(shell, ev)
var scale = 1
switch(ev.deltaMode) {
case 0: //Pixel
scale = 1
break
case 1: //Line
scale = 12
break
case 2: //Page
scale = shell.height
break
}
//Add scroll
shell.scroll[0] += ev.deltaX * scale
shell.scroll[1] += ev.deltaY * scale
shell.scroll[2] += (ev.deltaZ * scale)||0.0
return false
}
|
javascript
|
{
"resource": ""
}
|
q56597
|
createPointerEvaluator
|
train
|
function createPointerEvaluator(target) {
// Use cache to store already received values.
var cache = {};
return function(pointer) {
if (!isValidJSONPointer(pointer)) {
// If it's not, an exception will be thrown.
throw new ReferenceError(ErrorMessage.INVALID_POINTER);
}
// First, look up in the cache.
if (cache.hasOwnProperty(pointer)) {
// If cache entry exists, return it's value.
return cache[pointer];
}
// Now, when all arguments are valid, we can start evaluation.
// First of all, let's convert JSON pointer string to tokens list.
var tokensList = parsePointer(pointer);
var token;
var value = target;
// Evaluation will be continued till tokens list is not empty
// and returned value is not an undefined.
while (!_.isUndefined(value) && !_.isUndefined(token = tokensList.pop())) {
// Evaluate the token in current context.
// `getValue()` might throw an exception, but we won't handle it.
value = getValue(value, token);
}
// Pointer evaluation is done, save value in the cache and return it.
cache[pointer] = value;
return value;
};
}
|
javascript
|
{
"resource": ""
}
|
q56598
|
isValidJSONPointer
|
train
|
function isValidJSONPointer(pointer) {
if (!_.isString(pointer)) {
// If it's not a string, it obviously is not valid.
return false;
}
// If it is string and is an empty string, it's valid.
if ('' === pointer) {
return true;
}
// If it is non-empty string, it must match spec defined format.
// Check Section 3 of specification for concrete syntax.
return validPointerRegex.test(pointer);
}
|
javascript
|
{
"resource": ""
}
|
q56599
|
getPointedValue
|
train
|
function getPointedValue(target, pointer) {
// If not object, an exception will be thrown.
if (!_.isPlainObject(target)) {
throw new ReferenceError(ErrorMessage.INVALID_DOCUMENT_TYPE);
}
// target is already parsed, create an evaluator for it.
var evaluator = createPointerEvaluator(target);
// If no pointer was provided, return evaluator function.
if (_.isUndefined(pointer)) {
return evaluator;
} else {
return evaluator(pointer);
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.