_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q22400
|
train
|
function (layer) {
if (layer._spiderLeg) {
this._featureGroup.removeLayer(layer);
if (layer.clusterShow) {
layer.clusterShow();
}
//Position will be fixed up immediately in _animationUnspiderfy
if (layer.setZIndexOffset) {
layer.setZIndexOffset(0);
}
this._map.removeLayer(layer._spiderLeg);
delete layer._spiderLeg;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22401
|
train
|
function (obj, point) {
var x = this._getCoord(point.x),
y = this._getCoord(point.y),
grid = this._grid,
row = grid[y] = grid[y] || {},
cell = row[x] = row[x] || [],
i, len;
delete this._objectPoint[L.Util.stamp(obj)];
for (i = 0, len = cell.length; i < len; i++) {
if (cell[i] === obj) {
cell.splice(i, 1);
if (len === 1) {
delete row[x];
}
return true;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22402
|
clearBackground
|
train
|
function clearBackground() {
var body = document.body;
if (body.style) {
body.style.backgroundColor = 'rgba(0,0,0,0.01)';
body.style.backgroundImage = '';
setTimeout(function() {
body.style.backgroundColor = 'transparent';
}, 1);
if (body.parentNode && body.parentNode.style) {
body.parentNode.style.backgroundColor = 'transparent';
body.parentNode.style.backgroundImage = '';
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22403
|
getCameraSpecsById
|
train
|
function getCameraSpecsById(deviceId){
// return a getUserMedia Constraints
function getConstraintObj(deviceId, facingMode, width, height){
var obj = { audio: false, video: {} };
obj.video.deviceId = {exact: deviceId};
if(facingMode) {
obj.video.facingMode = {exact: facingMode};
}
if(width) {
obj.video.width = {exact: width};
}
if(height) {
obj.video.height = {exact: height};
}
return obj;
}
var facingModeConstraints = facingModes.map(function(mode){
return getConstraintObj(deviceId, mode);
});
var widthConstraints = standardWidthsAndHeights.map(function(width){
return getConstraintObj(deviceId, null, width);
});
var heightConstraints = standardWidthsAndHeights.map(function(height){
return getConstraintObj(deviceId, null, null, height);
});
// create a promise which tries to resolve the best constraints for this deviceId
// rather than reject, failures return a value of `null`
function getFirstResolvingConstraint(constraintsBestToWorst){
return new Promise(function(resolveBestConstraints){
// build a chain of promises which either resolves or continues searching
return constraintsBestToWorst.reduce(function(chain, next){
return chain.then(function(searchState){
if(searchState.found){
// The best working constraint was found. Skip further tests.
return searchState;
} else {
searchState.nextConstraint = next;
return window.navigator.mediaDevices.getUserMedia(searchState.nextConstraint).then(function(mediaStream){
// We found the first working constraint object, now we can stop
// the stream and short-circuit the search.
killStream(mediaStream);
searchState.found = true;
return searchState;
}, function(){
// didn't get a media stream. The search continues:
return searchState;
});
}
});
}, Promise.resolve({
// kick off the search:
found: false,
nextConstraint: {}
})).then(function(searchState){
if(searchState.found){
resolveBestConstraints(searchState.nextConstraint);
} else {
resolveBestConstraints(null);
}
});
});
}
return getFirstResolvingConstraint(facingModeConstraints).then(function(facingModeSpecs){
return getFirstResolvingConstraint(widthConstraints).then(function(widthSpecs){
return getFirstResolvingConstraint(heightConstraints).then(function(heightSpecs){
return {
deviceId: deviceId,
facingMode: facingModeSpecs === null ? null : facingModeSpecs.video.facingMode.exact,
width: widthSpecs === null ? null : widthSpecs.video.width.exact,
height: heightSpecs === null ? null : heightSpecs.video.height.exact
};
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q22404
|
getConstraintObj
|
train
|
function getConstraintObj(deviceId, facingMode, width, height){
var obj = { audio: false, video: {} };
obj.video.deviceId = {exact: deviceId};
if(facingMode) {
obj.video.facingMode = {exact: facingMode};
}
if(width) {
obj.video.width = {exact: width};
}
if(height) {
obj.video.height = {exact: height};
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q22405
|
getFirstResolvingConstraint
|
train
|
function getFirstResolvingConstraint(constraintsBestToWorst){
return new Promise(function(resolveBestConstraints){
// build a chain of promises which either resolves or continues searching
return constraintsBestToWorst.reduce(function(chain, next){
return chain.then(function(searchState){
if(searchState.found){
// The best working constraint was found. Skip further tests.
return searchState;
} else {
searchState.nextConstraint = next;
return window.navigator.mediaDevices.getUserMedia(searchState.nextConstraint).then(function(mediaStream){
// We found the first working constraint object, now we can stop
// the stream and short-circuit the search.
killStream(mediaStream);
searchState.found = true;
return searchState;
}, function(){
// didn't get a media stream. The search continues:
return searchState;
});
}
});
}, Promise.resolve({
// kick off the search:
found: false,
nextConstraint: {}
})).then(function(searchState){
if(searchState.found){
resolveBestConstraints(searchState.nextConstraint);
} else {
resolveBestConstraints(null);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q22406
|
convertStream
|
train
|
async function convertStream(data, streaming) {
if (!streaming && util.isStream(data)) {
return stream.readToEnd(data);
}
if (streaming && !util.isStream(data)) {
data = new ReadableStream({
start(controller) {
controller.enqueue(data);
controller.close();
}
});
}
if (streaming === 'node') {
data = stream.webToNode(data);
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q22407
|
convertStreams
|
train
|
async function convertStreams(obj, streaming, keys=[]) {
if (Object.prototype.isPrototypeOf(obj) && !Uint8Array.prototype.isPrototypeOf(obj)) {
await Promise.all(Object.entries(obj).map(async ([key, value]) => { // recursively search all children
if (util.isStream(value) || keys.includes(key)) {
obj[key] = await convertStream(value, streaming);
} else {
await convertStreams(obj[key], streaming);
}
}));
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q22408
|
linkStreams
|
train
|
function linkStreams(result, message, erroringStream) {
result.data = stream.transformPair(message.packets.stream, async (readable, writable) => {
await stream.pipe(result.data, writable, {
preventClose: true
});
const writer = stream.getWriter(writable);
try {
// Forward errors in erroringStream (defaulting to the message stream) to result.data.
await stream.readToEnd(erroringStream || readable, arr => arr);
await writer.close();
} catch(e) {
await writer.abort(e);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q22409
|
prepareSignatures
|
train
|
async function prepareSignatures(signatures) {
await Promise.all(signatures.map(async signature => {
signature.signature = await signature.signature;
try {
signature.valid = await signature.verified;
} catch(e) {
signature.valid = null;
signature.error = e;
util.print_debug_error(e);
}
}));
}
|
javascript
|
{
"resource": ""
}
|
q22410
|
onError
|
train
|
function onError(message, error) {
// log the stack trace
util.print_debug_error(error);
// update error message
try {
error.message = message + ': ' + error.message;
} catch(e) {}
throw error;
}
|
javascript
|
{
"resource": ""
}
|
q22411
|
nativeAEAD
|
train
|
function nativeAEAD() {
return config.aead_protect && (
((config.aead_protect_version !== 4 || config.aead_mode === enums.aead.experimental_gcm) && util.getWebCrypto()) ||
(config.aead_protect_version === 4 && config.aead_mode === enums.aead.eax && util.getWebCrypto())
);
}
|
javascript
|
{
"resource": ""
}
|
q22412
|
promisifyIE11Op
|
train
|
function promisifyIE11Op(keyObj, err) {
if (typeof keyObj.then !== 'function') { // IE11 KeyOperation
return new Promise(function(resolve, reject) {
keyObj.onerror = function () {
reject(new Error(err));
};
keyObj.oncomplete = function (e) {
resolve(e.target.result);
};
});
}
return keyObj;
}
|
javascript
|
{
"resource": ""
}
|
q22413
|
train
|
async function(m, n, e, d, p, q, u) {
if (n.cmp(m) <= 0) {
throw new Error('Data too large.');
}
const dq = d.mod(q.subn(1)); // d mod (q-1)
const dp = d.mod(p.subn(1)); // d mod (p-1)
const pred = new BN.red(p);
const qred = new BN.red(q);
const nred = new BN.red(n);
let blinder;
let unblinder;
if (config.rsa_blinding) {
unblinder = (await random.getRandomBN(new BN(2), n)).toRed(nred);
blinder = unblinder.redInvm().redPow(e);
m = m.toRed(nred).redMul(blinder).fromRed();
}
const mp = m.toRed(pred).redPow(dp);
const mq = m.toRed(qred).redPow(dq);
const t = mq.redSub(mp.fromRed().toRed(qred));
const h = u.toRed(qred).redMul(t).fromRed();
let result = h.mul(p).add(mp).toRed(nred);
if (config.rsa_blinding) {
result = result.redMul(unblinder);
}
return result.toArrayLike(Uint8Array, 'be', n.byteLength());
}
|
javascript
|
{
"resource": ""
}
|
|
q22414
|
train
|
async function(B, E) {
let key;
E = new BN(E, 16);
const webCrypto = util.getWebCryptoAll();
// Native RSA keygen using Web Crypto
if (webCrypto) {
let keyPair;
let keyGenOpt;
if ((window.crypto && window.crypto.subtle) || window.msCrypto) {
// current standard spec
keyGenOpt = {
name: 'RSASSA-PKCS1-v1_5',
modulusLength: B, // the specified keysize in bits
publicExponent: E.toArrayLike(Uint8Array), // take three bytes (max 65537) for exponent
hash: {
name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'
}
};
keyPair = webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']);
keyPair = await promisifyIE11Op(keyPair, 'Error generating RSA key pair.');
} else if (window.crypto && window.crypto.webkitSubtle) {
// outdated spec implemented by old Webkit
keyGenOpt = {
name: 'RSA-OAEP',
modulusLength: B, // the specified keysize in bits
publicExponent: E.toArrayLike(Uint8Array), // take three bytes (max 65537) for exponent
hash: {
name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'
}
};
keyPair = await webCrypto.generateKey(keyGenOpt, true, ['encrypt', 'decrypt']);
} else {
throw new Error('Unknown WebCrypto implementation');
}
// export the generated keys as JsonWebKey (JWK)
// https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33
let jwk = webCrypto.exportKey('jwk', keyPair.privateKey);
jwk = await promisifyIE11Op(jwk, 'Error exporting RSA key pair.');
// parse raw ArrayBuffer bytes to jwk/json (WebKit/Safari/IE11 quirk)
if (jwk instanceof ArrayBuffer) {
jwk = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(jwk)));
}
// map JWK parameters to BN
key = {};
key.n = new BN(util.b64_to_Uint8Array(jwk.n));
key.e = E;
key.d = new BN(util.b64_to_Uint8Array(jwk.d));
key.p = new BN(util.b64_to_Uint8Array(jwk.p));
key.q = new BN(util.b64_to_Uint8Array(jwk.q));
key.u = key.p.invm(key.q);
return key;
}
// RSA keygen fallback using 40 iterations of the Miller-Rabin test
// See https://stackoverflow.com/a/6330138 for justification
// Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST
let p = await prime.randomProbablePrime(B - (B >> 1), E, 40);
let q = await prime.randomProbablePrime(B >> 1, E, 40);
if (p.cmp(q) < 0) {
[p, q] = [q, p];
}
const phi = p.subn(1).mul(q.subn(1));
return {
n: p.mul(q),
e: E,
d: E.invm(phi),
p: p,
q: q,
// dp: d.mod(p.subn(1)),
// dq: d.mod(q.subn(1)),
u: p.invm(q)
};
}
|
javascript
|
{
"resource": ""
}
|
|
q22415
|
DES
|
train
|
function DES(key) {
this.key = key;
this.encrypt = function(block, padding) {
const keys = des_createKeys(this.key);
return des(keys, block, true, 0, null, padding);
};
this.decrypt = function(block, padding) {
const keys = des_createKeys(this.key);
return des(keys, block, false, 0, null, padding);
};
}
|
javascript
|
{
"resource": ""
}
|
q22416
|
train
|
function(algo) {
switch (algo) {
// Algorithm-Specific Fields for RSA secret keys:
// - multiprecision integer (MPI) of RSA secret exponent d.
// - MPI of RSA secret prime value p.
// - MPI of RSA secret prime value q (p < q).
// - MPI of u, the multiplicative inverse of p, mod q.
case enums.publicKey.rsa_encrypt:
case enums.publicKey.rsa_encrypt_sign:
case enums.publicKey.rsa_sign:
return [type_mpi, type_mpi, type_mpi, type_mpi];
// Algorithm-Specific Fields for Elgamal secret keys:
// - MPI of Elgamal secret exponent x.
case enums.publicKey.elgamal:
return [type_mpi];
// Algorithm-Specific Fields for DSA secret keys:
// - MPI of DSA secret exponent x.
case enums.publicKey.dsa:
return [type_mpi];
// Algorithm-Specific Fields for ECDSA or ECDH secret keys:
// - MPI of an integer representing the secret key.
case enums.publicKey.ecdh:
case enums.publicKey.ecdsa:
case enums.publicKey.eddsa:
return [type_mpi];
default:
throw new Error('Invalid public key encryption algorithm.');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22417
|
train
|
function(algo) {
switch (algo) {
// Algorithm-Specific Fields for RSA encrypted session keys:
// - MPI of RSA encrypted value m**e mod n.
case enums.publicKey.rsa_encrypt:
case enums.publicKey.rsa_encrypt_sign:
return [type_mpi];
// Algorithm-Specific Fields for Elgamal encrypted session keys:
// - MPI of Elgamal value g**k mod p
// - MPI of Elgamal value m * y**k mod p
case enums.publicKey.elgamal:
return [type_mpi, type_mpi];
// Algorithm-Specific Fields for ECDH encrypted session keys:
// - MPI containing the ephemeral key used to establish the shared secret
// - ECDH Symmetric Key
case enums.publicKey.ecdh:
return [type_mpi, type_ecdh_symkey];
default:
throw new Error('Invalid public key encryption algorithm.');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22418
|
train
|
function(algo, bits, oid) {
const types = [].concat(this.getPubKeyParamTypes(algo), this.getPrivKeyParamTypes(algo));
switch (algo) {
case enums.publicKey.rsa_encrypt:
case enums.publicKey.rsa_encrypt_sign:
case enums.publicKey.rsa_sign: {
return publicKey.rsa.generate(bits, "10001").then(function(keyObject) {
return constructParams(
types, [keyObject.n, keyObject.e, keyObject.d, keyObject.p, keyObject.q, keyObject.u]
);
});
}
case enums.publicKey.dsa:
case enums.publicKey.elgamal:
throw new Error('Unsupported algorithm for key generation.');
case enums.publicKey.ecdsa:
case enums.publicKey.eddsa:
return publicKey.elliptic.generate(oid).then(function (keyObject) {
return constructParams(types, [keyObject.oid, keyObject.Q, keyObject.d]);
});
case enums.publicKey.ecdh:
return publicKey.elliptic.generate(oid).then(function (keyObject) {
return constructParams(types, [keyObject.oid, keyObject.Q, [keyObject.hash, keyObject.cipher], keyObject.d]);
});
default:
throw new Error('Invalid public key algorithm.');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22419
|
train
|
async function(plaintext, nonce, adata) {
const [
omacNonce,
omacAdata
] = await Promise.all([
omac(zero, nonce),
omac(one, adata)
]);
const ciphered = await ctr(plaintext, omacNonce);
const omacCiphered = await omac(two, ciphered);
const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
for (let i = 0; i < tagLength; i++) {
tag[i] ^= omacAdata[i] ^ omacNonce[i];
}
return util.concatUint8Array([ciphered, tag]);
}
|
javascript
|
{
"resource": ""
}
|
|
q22420
|
randomCallback
|
train
|
function randomCallback() {
if (!randomQueue.length) {
self.postMessage({ event: 'request-seed', amount: MAX_SIZE_RANDOM_BUFFER });
}
return new Promise(function(resolve) {
randomQueue.push(resolve);
});
}
|
javascript
|
{
"resource": ""
}
|
q22421
|
configure
|
train
|
function configure(config) {
Object.keys(config).forEach(function(key) {
openpgp.config[key] = config[key];
});
}
|
javascript
|
{
"resource": ""
}
|
q22422
|
seedRandom
|
train
|
function seedRandom(buffer) {
if (!(buffer instanceof Uint8Array)) {
buffer = new Uint8Array(buffer);
}
openpgp.crypto.random.randomBuffer.set(buffer);
}
|
javascript
|
{
"resource": ""
}
|
q22423
|
delegate
|
train
|
function delegate(id, method, options) {
if (typeof openpgp[method] !== 'function') {
response({ id:id, event:'method-return', err:'Unknown Worker Event' });
return;
}
// construct ReadableStreams from MessagePorts
openpgp.util.restoreStreams(options);
// parse cloned packets
options = openpgp.packet.clone.parseClonedPackets(options, method);
openpgp[method](options).then(function(data) {
// clone packets (for web worker structured cloning algorithm)
response({ id:id, event:'method-return', data:openpgp.packet.clone.clonePackets(data) });
}).catch(function(e) {
openpgp.util.print_debug_error(e);
response({
id:id, event:'method-return', err:e.message, stack:e.stack
});
});
}
|
javascript
|
{
"resource": ""
}
|
q22424
|
response
|
train
|
function response(event) {
self.postMessage(event, openpgp.util.getTransferables(event.data, true));
}
|
javascript
|
{
"resource": ""
}
|
q22425
|
LocalStore
|
train
|
function LocalStore(prefix) {
prefix = prefix || 'openpgp-';
this.publicKeysItem = prefix + this.publicKeysItem;
this.privateKeysItem = prefix + this.privateKeysItem;
if (typeof window !== 'undefined' && window.localStorage) {
this.storage = window.localStorage;
} else {
this.storage = new (require('node-localstorage').LocalStorage)(config.node_store);
}
}
|
javascript
|
{
"resource": ""
}
|
q22426
|
HKP
|
train
|
function HKP(keyServerBaseUrl) {
this._baseUrl = keyServerBaseUrl || config.keyserver;
this._fetch = typeof window !== 'undefined' ? window.fetch : require('node-fetch');
}
|
javascript
|
{
"resource": ""
}
|
q22427
|
getPkcs1Padding
|
train
|
async function getPkcs1Padding(length) {
let result = '';
while (result.length < length) {
const randomBytes = await random.getRandomBytes(length - result.length);
for (let i = 0; i < randomBytes.length; i++) {
if (randomBytes[i] !== 0) {
result += String.fromCharCode(randomBytes[i]);
}
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q22428
|
train
|
async function(length) {
const buf = new Uint8Array(length);
if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
window.crypto.getRandomValues(buf);
} else if (typeof window !== 'undefined' && typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') {
window.msCrypto.getRandomValues(buf);
} else if (nodeCrypto) {
const bytes = nodeCrypto.randomBytes(buf.length);
buf.set(bytes);
} else if (this.randomBuffer.buffer) {
await this.randomBuffer.get(buf);
} else {
throw new Error('No secure random number generator available.');
}
return buf;
}
|
javascript
|
{
"resource": ""
}
|
|
q22429
|
train
|
async function(min, max) {
if (max.cmp(min) <= 0) {
throw new Error('Illegal parameter value: max <= min');
}
const modulus = max.sub(min);
const bytes = modulus.byteLength();
// Using a while loop is necessary to avoid bias introduced by the mod operation.
// However, we request 64 extra random bits so that the bias is negligible.
// Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
const r = new BN(await this.getRandomBytes(bytes + 8));
return r.mod(modulus).add(min);
}
|
javascript
|
{
"resource": ""
}
|
|
q22430
|
verifyHeaders
|
train
|
function verifyHeaders(headers, packetlist) {
const checkHashAlgos = function(hashAlgos) {
const check = packet => algo => packet.hashAlgorithm === algo;
for (let i = 0; i < packetlist.length; i++) {
if (packetlist[i].tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {
return false;
}
}
return true;
};
let oneHeader = null;
let hashAlgos = [];
headers.forEach(function(header) {
oneHeader = header.match(/Hash: (.+)/); // get header value
if (oneHeader) {
oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace
oneHeader = oneHeader.split(',');
oneHeader = oneHeader.map(function(hash) {
hash = hash.toLowerCase();
try {
return enums.write(enums.hash, hash);
} catch (e) {
throw new Error('Unknown hash algorithm in armor header: ' + hash);
}
});
hashAlgos = hashAlgos.concat(oneHeader);
} else {
throw new Error('Only "Hash" header allowed in cleartext signed message');
}
});
if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) {
throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed');
} else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {
throw new Error('Hash algorithm mismatch in armor header and signature');
}
}
|
javascript
|
{
"resource": ""
}
|
q22431
|
createVerificationObject
|
train
|
async function createVerificationObject(signature, literalDataList, keys, date=new Date()) {
let primaryKey = null;
let signingKey = null;
await Promise.all(keys.map(async function(key) {
// Look for the unique key that matches issuerKeyId of signature
const result = await key.getSigningKey(signature.issuerKeyId, null);
if (result) {
primaryKey = key;
signingKey = result;
}
}));
const signaturePacket = signature.correspondingSig || signature;
const verifiedSig = {
keyid: signature.issuerKeyId,
verified: (async () => {
if (!signingKey) {
return null;
}
const verified = await signature.verify(signingKey.keyPacket, signature.signatureType, literalDataList[0]);
const sig = await signaturePacket;
if (sig.isExpired(date) || !(
sig.created >= signingKey.getCreationTime() &&
sig.created < await (signingKey === primaryKey ?
signingKey.getExpirationTime() :
signingKey.getExpirationTime(primaryKey, date)
)
)) {
return null;
}
return verified;
})(),
signature: (async () => {
const sig = await signaturePacket;
const packetlist = new packet.List();
packetlist.push(sig);
return new Signature(packetlist);
})()
};
// Mark potential promise rejections as "handled". This is needed because in
// some cases, we reject them before the user has a reasonable chance to
// handle them (e.g. `await readToEnd(result.data); await result.verified` and
// the data stream errors).
verifiedSig.signature.catch(() => {});
verifiedSig.verified.catch(() => {});
return verifiedSig;
}
|
javascript
|
{
"resource": ""
}
|
q22432
|
SecretKey
|
train
|
function SecretKey(date=new Date()) {
publicKey.call(this, date);
/**
* Packet type
* @type {module:enums.packet}
*/
this.tag = enums.packet.secretKey;
/**
* Encrypted secret-key data
*/
this.encrypted = null;
/**
* Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.
*/
this.isEncrypted = null;
}
|
javascript
|
{
"resource": ""
}
|
q22433
|
AsyncProxy
|
train
|
function AsyncProxy({ path='openpgp.worker.js', n = 1, workers = [], config } = {}) {
/**
* Message handling
*/
const handleMessage = workerId => event => {
const msg = event.data;
switch (msg.event) {
case 'loaded':
this.workers[workerId].loadedResolve(true);
break;
case 'method-return':
if (msg.err) {
// fail
const err = new Error(msg.err);
// add worker stack
err.workerStack = msg.stack;
this.tasks[msg.id].reject(err);
} else {
// success
this.tasks[msg.id].resolve(msg.data);
}
delete this.tasks[msg.id];
this.workers[workerId].requests--;
break;
case 'request-seed':
this.seedRandom(workerId, msg.amount);
break;
default:
throw new Error('Unknown Worker Event.');
}
};
if (workers.length) {
this.workers = workers;
}
else {
this.workers = [];
while (this.workers.length < n) {
this.workers.push(new Worker(path));
}
}
let workerId = 0;
this.workers.forEach(worker => {
worker.loadedPromise = new Promise(resolve => {
worker.loadedResolve = resolve;
});
worker.requests = 0;
worker.onmessage = handleMessage(workerId++);
worker.onerror = e => {
worker.loadedResolve(false);
console.error('Unhandled error in openpgp worker: ' + e.message + ' (' + e.filename + ':' + e.lineno + ')');
return false;
};
if (config) {
worker.postMessage({ event:'configure', config });
}
});
// Cannot rely on task order being maintained, use object keyed by request ID to track tasks
this.tasks = {};
this.currentID = 0;
}
|
javascript
|
{
"resource": ""
}
|
q22434
|
isDataRevoked
|
train
|
async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date=new Date()) {
key = key || primaryKey;
const normDate = util.normalizeDate(date);
const revocationKeyIds = [];
await Promise.all(revocations.map(async function(revocationSignature) {
if (
// Note: a third-party revocation signature could legitimately revoke a
// self-signature if the signature has an authorized revocation key.
// However, we don't support passing authorized revocation keys, nor
// verifying such revocation signatures. Instead, we indicate an error
// when parsing a key with an authorized revocation key, and ignore
// third-party revocation signatures here. (It could also be revoking a
// third-party key certification, which should only affect
// `verifyAllCertifications`.)
(!signature || revocationSignature.issuerKeyId.equals(signature.issuerKeyId)) &&
!(config.revocations_expire && revocationSignature.isExpired(normDate)) &&
(revocationSignature.verified || await revocationSignature.verify(key, signatureType, dataToVerify))
) {
// TODO get an identifier of the revoked object instead
revocationKeyIds.push(revocationSignature.issuerKeyId);
return true;
}
return false;
}));
// TODO further verify that this is the signature that should be revoked
if (signature) {
signature.revoked = revocationKeyIds.some(keyId => keyId.equals(signature.issuerKeyId)) ? true :
signature.revoked || false;
return signature.revoked;
}
return revocationKeyIds.length > 0;
}
|
javascript
|
{
"resource": ""
}
|
q22435
|
randomProbablePrime
|
train
|
async function randomProbablePrime(bits, e, k) {
const min = new BN(1).shln(bits - 1);
const thirty = new BN(30);
/*
* We can avoid any multiples of 3 and 5 by looking at n mod 30
* n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
* the next possible prime is mod 30:
* 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1
*/
const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2];
let n = await random.getRandomBN(min, min.shln(1));
let i = n.mod(thirty).toNumber();
do {
n.iaddn(adds[i]);
i = (i + adds[i]) % adds.length;
// If reached the maximum, go back to the minimum.
if (n.bitLength() > bits) {
n = n.mod(min.shln(1)).iadd(min);
i = n.mod(thirty).toNumber();
}
} while (!await isProbablePrime(n, e, k));
return n;
}
|
javascript
|
{
"resource": ""
}
|
q22436
|
isProbablePrime
|
train
|
async function isProbablePrime(n, e, k) {
if (e && !n.subn(1).gcd(e).eqn(1)) {
return false;
}
if (!divisionTest(n)) {
return false;
}
if (!fermat(n)) {
return false;
}
if (!await millerRabin(n, k)) {
return false;
}
// TODO implement the Lucas test
// See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
return true;
}
|
javascript
|
{
"resource": ""
}
|
q22437
|
getType
|
train
|
function getType(text) {
const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;
const header = text.match(reHeader);
if (!header) {
throw new Error('Unknown ASCII armor type');
}
// BEGIN PGP MESSAGE, PART X/Y
// Used for multi-part messages, where the armor is split amongst Y
// parts, and this is the Xth part out of Y.
if (/MESSAGE, PART \d+\/\d+/.test(header[1])) {
return enums.armor.multipart_section;
} else
// BEGIN PGP MESSAGE, PART X
// Used for multi-part messages, where this is the Xth part of an
// unspecified number of parts. Requires the MESSAGE-ID Armor
// Header to be used.
if (/MESSAGE, PART \d+/.test(header[1])) {
return enums.armor.multipart_last;
} else
// BEGIN PGP SIGNED MESSAGE
if (/SIGNED MESSAGE/.test(header[1])) {
return enums.armor.signed;
} else
// BEGIN PGP MESSAGE
// Used for signed, encrypted, or compressed files.
if (/MESSAGE/.test(header[1])) {
return enums.armor.message;
} else
// BEGIN PGP PUBLIC KEY BLOCK
// Used for armoring public keys.
if (/PUBLIC KEY BLOCK/.test(header[1])) {
return enums.armor.public_key;
} else
// BEGIN PGP PRIVATE KEY BLOCK
// Used for armoring private keys.
if (/PRIVATE KEY BLOCK/.test(header[1])) {
return enums.armor.private_key;
} else
// BEGIN PGP SIGNATURE
// Used for detached signatures, OpenPGP/MIME signatures, and
// cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE
// for detached signatures.
if (/SIGNATURE/.test(header[1])) {
return enums.armor.signature;
}
}
|
javascript
|
{
"resource": ""
}
|
q22438
|
addheader
|
train
|
function addheader(customComment) {
let result = "";
if (config.show_version) {
result += "Version: " + config.versionstring + '\r\n';
}
if (config.show_comment) {
result += "Comment: " + config.commentstring + '\r\n';
}
if (customComment) {
result += "Comment: " + customComment + '\r\n';
}
result += '\r\n';
return result;
}
|
javascript
|
{
"resource": ""
}
|
q22439
|
splitChecksum
|
train
|
function splitChecksum(text) {
let body = text;
let checksum = "";
const lastEquals = text.lastIndexOf("=");
if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum
body = text.slice(0, lastEquals);
checksum = text.slice(lastEquals + 1).substr(0, 4);
}
return { body: body, checksum: checksum };
}
|
javascript
|
{
"resource": ""
}
|
q22440
|
armor
|
train
|
function armor(messagetype, body, partindex, parttotal, customComment) {
let text;
let hash;
if (messagetype === enums.armor.signed) {
text = body.text;
hash = body.hash;
body = body.data;
}
const bodyClone = stream.passiveClone(body);
const result = [];
switch (messagetype) {
case enums.armor.multipart_section:
result.push("-----BEGIN PGP MESSAGE, PART " + partindex + "/" + parttotal + "-----\r\n");
result.push(addheader(customComment));
result.push(base64.encode(body));
result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
result.push("-----END PGP MESSAGE, PART " + partindex + "/" + parttotal + "-----\r\n");
break;
case enums.armor.multipart_last:
result.push("-----BEGIN PGP MESSAGE, PART " + partindex + "-----\r\n");
result.push(addheader(customComment));
result.push(base64.encode(body));
result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
result.push("-----END PGP MESSAGE, PART " + partindex + "-----\r\n");
break;
case enums.armor.signed:
result.push("\r\n-----BEGIN PGP SIGNED MESSAGE-----\r\n");
result.push("Hash: " + hash + "\r\n\r\n");
result.push(text.replace(/^-/mg, "- -"));
result.push("\r\n-----BEGIN PGP SIGNATURE-----\r\n");
result.push(addheader(customComment));
result.push(base64.encode(body));
result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
result.push("-----END PGP SIGNATURE-----\r\n");
break;
case enums.armor.message:
result.push("-----BEGIN PGP MESSAGE-----\r\n");
result.push(addheader(customComment));
result.push(base64.encode(body));
result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
result.push("-----END PGP MESSAGE-----\r\n");
break;
case enums.armor.public_key:
result.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\r\n");
result.push(addheader(customComment));
result.push(base64.encode(body));
result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
result.push("-----END PGP PUBLIC KEY BLOCK-----\r\n");
break;
case enums.armor.private_key:
result.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\r\n");
result.push(addheader(customComment));
result.push(base64.encode(body));
result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
result.push("-----END PGP PRIVATE KEY BLOCK-----\r\n");
break;
case enums.armor.signature:
result.push("-----BEGIN PGP SIGNATURE-----\r\n");
result.push(addheader(customComment));
result.push(base64.encode(body));
result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
result.push("-----END PGP SIGNATURE-----\r\n");
break;
}
return util.concat(result);
}
|
javascript
|
{
"resource": ""
}
|
q22441
|
train
|
function(algo, data) {
switch (algo) {
case 1:
// - MD5 [HAC]
return this.md5(data);
case 2:
// - SHA-1 [FIPS180]
return this.sha1(data);
case 3:
// - RIPE-MD/160 [HAC]
return this.ripemd(data);
case 8:
// - SHA256 [FIPS180]
return this.sha256(data);
case 9:
// - SHA384 [FIPS180]
return this.sha384(data);
case 10:
// - SHA512 [FIPS180]
return this.sha512(data);
case 11:
// - SHA224 [FIPS180]
return this.sha224(data);
default:
throw new Error('Invalid hash function.');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22442
|
s2r
|
train
|
function s2r(t, u = false) {
// TODO check btoa alternative
const b64 = u ? b64u : b64s;
let a;
let c;
let l = 0;
let s = 0;
return stream.transform(t, value => {
const r = [];
const tl = value.length;
for (let n = 0; n < tl; n++) {
if (l && (l % 60) === 0 && !u) {
r.push("\r\n");
}
c = value[n];
if (s === 0) {
r.push(b64.charAt((c >> 2) & 63));
a = (c & 3) << 4;
} else if (s === 1) {
r.push(b64.charAt(a | ((c >> 4) & 15)));
a = (c & 15) << 2;
} else if (s === 2) {
r.push(b64.charAt(a | ((c >> 6) & 3)));
l += 1;
if ((l % 60) === 0 && !u) {
r.push("\r\n");
}
r.push(b64.charAt(c & 63));
}
l += 1;
s += 1;
if (s === 3) {
s = 0;
}
}
return r.join('');
}, () => {
const r = [];
if (s > 0) {
r.push(b64.charAt(a));
l += 1;
if ((l % 60) === 0 && !u) {
r.push("\r\n");
}
if (!u) {
r.push('=');
l += 1;
}
}
if (s === 1 && !u) {
if ((l % 60) === 0 && !u) {
r.push("\r\n");
}
r.push('=');
}
return r.join('');
});
}
|
javascript
|
{
"resource": ""
}
|
q22443
|
r2s
|
train
|
function r2s(t, u) {
// TODO check atob alternative
let c;
let s = 0;
let a = 0;
return stream.transform(t, value => {
const tl = value.length;
const r = new Uint8Array(Math.ceil(0.75 * tl));
let index = 0;
for (let n = 0; n < tl; n++) {
c = b64toByte[value.charCodeAt(n)];
if (c >= 0) {
if (s) {
r[index++] = a | ((c >> (6 - s)) & 255);
}
s = (s + 2) & 7;
a = (c << s) & 255;
}
}
return r.subarray(0, index);
});
}
|
javascript
|
{
"resource": ""
}
|
q22444
|
genPublicEphemeralKey
|
train
|
async function genPublicEphemeralKey(curve, Q) {
if (curve.name === 'curve25519') {
const { secretKey: d } = nacl.box.keyPair();
const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, d);
let { publicKey } = nacl.box.keyPair.fromSecretKey(secretKey);
publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]);
return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
}
const v = await curve.genKeyPair();
Q = curve.keyFromPublic(Q);
const publicKey = new Uint8Array(v.getPublic());
const S = v.derive(Q);
const len = curve.curve.curve.p.byteLength();
const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
return { publicKey, sharedKey };
}
|
javascript
|
{
"resource": ""
}
|
q22445
|
encrypt
|
train
|
async function encrypt(oid, cipher_algo, hash_algo, m, Q, fingerprint) {
const curve = new Curve(oid);
const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q);
const param = buildEcdhParam(enums.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint);
cipher_algo = enums.read(enums.symmetric, cipher_algo);
const Z = await kdf(hash_algo, sharedKey, cipher[cipher_algo].keySize, param);
const wrappedKey = aes_kw.wrap(Z, m.toString());
return { publicKey, wrappedKey };
}
|
javascript
|
{
"resource": ""
}
|
q22446
|
genPrivateEphemeralKey
|
train
|
async function genPrivateEphemeralKey(curve, V, d) {
if (curve.name === 'curve25519') {
const one = new BN(1);
const mask = one.ushln(255 - 3).sub(one).ushln(3);
let secretKey = new BN(d);
secretKey = secretKey.or(one.ushln(255 - 1));
secretKey = secretKey.and(mask);
secretKey = secretKey.toArrayLike(Uint8Array, 'le', 32);
const sharedKey = nacl.scalarMult(secretKey, V.subarray(1));
return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
}
V = curve.keyFromPublic(V);
d = curve.keyFromPrivate(d);
const secretKey = new Uint8Array(d.getPrivate());
const S = d.derive(V);
const len = curve.curve.curve.p.byteLength();
const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
return { secretKey, sharedKey };
}
|
javascript
|
{
"resource": ""
}
|
q22447
|
decrypt
|
train
|
async function decrypt(oid, cipher_algo, hash_algo, V, C, d, fingerprint) {
const curve = new Curve(oid);
const { sharedKey } = await genPrivateEphemeralKey(curve, V, d);
const param = buildEcdhParam(enums.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint);
cipher_algo = enums.read(enums.symmetric, cipher_algo);
let err;
for (let i = 0; i < 3; i++) {
try {
// Work around old go crypto bug and old OpenPGP.js bug, respectively.
const Z = await kdf(hash_algo, sharedKey, cipher[cipher_algo].keySize, param, i === 1, i === 2);
return new BN(aes_kw.unwrap(Z, C));
} catch (e) {
err = e;
}
}
throw err;
}
|
javascript
|
{
"resource": ""
}
|
q22448
|
emailCheck
|
train
|
function emailCheck(email, key) {
email = email.toLowerCase();
// escape email before using in regular expression
const emailEsc = email.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const emailRegex = new RegExp('<' + emailEsc + '>');
const userIds = key.getUserIds();
for (let i = 0; i < userIds.length; i++) {
const userId = userIds[i].toLowerCase();
if (email === userId || emailRegex.test(userId)) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q22449
|
keyIdCheck
|
train
|
function keyIdCheck(keyId, key) {
if (keyId.length === 16) {
return keyId === key.getKeyId().toHex();
}
return keyId === key.getFingerprint();
}
|
javascript
|
{
"resource": ""
}
|
q22450
|
write_sub_packet
|
train
|
function write_sub_packet(type, data) {
const arr = [];
arr.push(packet.writeSimpleLength(data.length + 1));
arr.push(new Uint8Array([type]));
arr.push(data);
return util.concat(arr);
}
|
javascript
|
{
"resource": ""
}
|
q22451
|
f1
|
train
|
function f1(d, m, r) {
const t = m + d;
const I = (t << r) | (t >>> (32 - r));
return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];
}
|
javascript
|
{
"resource": ""
}
|
q22452
|
decode
|
train
|
function decode(msg) {
const len = msg.length;
if (len > 0) {
const c = msg.charCodeAt(len - 1);
if (c >= 1 && c <= 8) {
const provided = msg.substr(len - c);
const computed = String.fromCharCode(c).repeat(c);
if (provided === computed) {
return msg.substr(0, len - c);
}
}
}
throw new Error('Invalid padding');
}
|
javascript
|
{
"resource": ""
}
|
q22453
|
train
|
function(batchSizeOrIteratee, iteratee) {
assert(this._wlQueryInfo.method === 'stream', 'Cannot chain `.eachBatch()` onto the `.'+this._wlQueryInfo.method+'()` method. The `.eachBatch()` method is only chainable to `.stream()`. (In fact, this shouldn\'t even be possible! So the fact that you are seeing this message at all is, itself, likely due to a bug in Waterline.)');
if (arguments.length > 2) {
throw new Error('Invalid usage for `.eachBatch()` -- no more than 2 arguments should be passed in.');
}//•
if (iteratee === undefined) {
this._wlQueryInfo.eachBatchFn = batchSizeOrIteratee;
} else {
this._wlQueryInfo.eachBatchFn = iteratee;
// Apply custom batch size:
// > If meta already exists, merge on top of it.
// > (this is important for when this method is combined with .meta()/.usingConnection()/etc)
if (this._wlQueryInfo.meta) {
_.extend(this._wlQueryInfo.meta, { batchSize: batchSizeOrIteratee });
}
else {
this._wlQueryInfo.meta = { batchSize: batchSizeOrIteratee };
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22454
|
train
|
function(values) {
if (this._wlQueryInfo.method === 'create') {
console.warn(
'Deprecation warning: In future versions of Waterline, the use of .set() with .create()\n'+
'will no longer be supported. In the past, you could use .set() to provide the initial\n'+
'skeleton of a new record to create (like `.create().set({})`)-- but really .set() should\n'+
'only be used with .update(). So instead, please change this code so that it just passes in\n'+
'the initial new record as the first argument to `.create().`'
);
this._wlQueryInfo.newRecord = values;
}
else if (this._wlQueryInfo.method === 'createEach') {
console.warn(
'Deprecation warning: In future versions of Waterline, the use of .set() with .createEach()\n'+
'will no longer be supported. In the past, you could use .set() to provide an array of\n'+
'new records to create (like `.createEach().set([{}, {}])`)-- but really .set() was designed\n'+
'to be used with .update() only. So instead, please change this code so that it just\n'+
'passes in the initial new record as the first argument to `.createEach().`'
);
this._wlQueryInfo.newRecords = values;
}
else {
this._wlQueryInfo.valuesToSet = values;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22455
|
train
|
function(limit) {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.limit = limit;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22456
|
train
|
function(skip) {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.skip = skip;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22457
|
train
|
function(sortClause) {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.sort = sortClause;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22458
|
train
|
function(selectAttributes) {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.select = selectAttributes;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22459
|
train
|
function(omitAttributes) {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.omit = omitAttributes;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22460
|
train
|
function(whereCriteria) {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.where = whereCriteria;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22461
|
extend
|
train
|
function extend(obj, props) {
for (var i in props) {
obj[i] = props[i];
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q22462
|
isNamedNode
|
train
|
function isNamedNode(node, nodeName) {
return node.normalizedNodeName === nodeName || node.nodeName.toLowerCase() === nodeName.toLowerCase();
}
|
javascript
|
{
"resource": ""
}
|
q22463
|
createNode
|
train
|
function createNode(nodeName, isSvg) {
var node = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName);
node.normalizedNodeName = nodeName;
return node;
}
|
javascript
|
{
"resource": ""
}
|
q22464
|
eventProxy
|
train
|
function eventProxy(e) {
return this._listeners[e.type]((options.event && options.event(e)) || e);
}
|
javascript
|
{
"resource": ""
}
|
q22465
|
collectComponent
|
train
|
function collectComponent(component) {
var name = component.constructor.name;
(components[name] || (components[name] = [])).push(component);
}
|
javascript
|
{
"resource": ""
}
|
q22466
|
createComponent
|
train
|
function createComponent(Ctor, props, context) {
var list = components[Ctor.name],
inst;
if (Ctor.prototype && Ctor.prototype.render) {
inst = new Ctor(props, context);
Component.call(inst, props, context);
} else {
inst = new Component(props, context);
inst.constructor = Ctor;
inst.render = doRender;
}
if (list) {
for (var i = list.length; i--; ) {
if (list[i].constructor === Ctor) {
inst.nextBase = list[i].nextBase;
list.splice(i, 1);
break;
}
}
}
return inst;
}
|
javascript
|
{
"resource": ""
}
|
q22467
|
buildComponentFromVNode
|
train
|
function buildComponentFromVNode(dom, vnode, context, mountAll) {
var c = dom && dom._component,
originalComponent = c,
oldDom = dom,
isDirectOwner = c && dom._componentConstructor === vnode.nodeName,
isOwner = isDirectOwner,
props = getNodeProps(vnode);
while (c && !isOwner && (c = c._parentComponent)) {
isOwner = c.constructor === vnode.nodeName;
}
if (c && isOwner && (!mountAll || c._component)) {
setComponentProps(c, props, 3, context, mountAll);
dom = c.base;
} else {
if (originalComponent && !isDirectOwner) {
unmountComponent(originalComponent);
dom = oldDom = null;
}
c = createComponent(vnode.nodeName, props, context);
if (dom && !c.nextBase) {
c.nextBase = dom;
// passing dom/oldDom as nextBase will recycle it if unused, so bypass recycling on L229:
oldDom = null;
}
setComponentProps(c, props, 1, context, mountAll);
dom = c.base;
if (oldDom && dom !== oldDom) {
oldDom._component = null;
recollectNodeTree(oldDom, false);
}
}
return dom;
}
|
javascript
|
{
"resource": ""
}
|
q22468
|
unmountComponent
|
train
|
function unmountComponent(component) {
if (options.beforeUnmount) options.beforeUnmount(component);
var base = component.base;
component._disable = true;
if (component.componentWillUnmount) component.componentWillUnmount();
component.base = null;
// recursively tear down & recollect high-order component children:
var inner = component._component;
if (inner) {
unmountComponent(inner);
} else if (base) {
if (base['__preactattr_'] && base['__preactattr_'].ref) base['__preactattr_'].ref(null);
component.nextBase = base;
removeNode(base);
collectComponent(component);
removeChildren(base);
}
if (component.__ref) component.__ref(null);
}
|
javascript
|
{
"resource": ""
}
|
q22469
|
setState
|
train
|
function setState(state, callback) {
var s = this.state;
if (!this.prevState) this.prevState = extend({}, s);
extend(s, typeof state === 'function' ? state(s, this.props) : state);
if (callback) (this._renderCallbacks = this._renderCallbacks || []).push(callback);
enqueueRender(this);
}
|
javascript
|
{
"resource": ""
}
|
q22470
|
linkState
|
train
|
function linkState(component, key, eventPath) {
var path = key.split('.'),
cache = component.__lsc || (component.__lsc = {});
return (
cache[key + eventPath] ||
(cache[key + eventPath] = function(e) {
var t = (e && e.target) || this,
state = {},
obj = state,
v = typeof eventPath === 'string' ? dlv(e, eventPath) : t.nodeName ? (t.type.match(/^che|rad/) ? t.checked : t.value) : e,
i = 0;
for (; i < path.length - 1; i++) {
obj = obj[path[i]] || (obj[path[i]] = (!i && component.state[path[i]]) || {});
}
obj[path[i]] = v;
component.setState(state);
})
);
}
|
javascript
|
{
"resource": ""
}
|
q22471
|
pagesCount
|
train
|
function pagesCount() {
var quotient = Math.floor(this.total / this.currentPerPage);
var remainder = this.total % this.currentPerPage;
return remainder === 0 ? quotient : quotient + 1;
}
|
javascript
|
{
"resource": ""
}
|
q22472
|
paginatedInfo
|
train
|
function paginatedInfo() {
var first = (this.currentPage - 1) * this.currentPerPage + 1;
var last = Math.min(this.total, this.currentPage * this.currentPerPage);
if (last === 0) {
first = 0;
}
return "".concat(first, " - ").concat(last, " ").concat(this.ofText, " ").concat(this.total);
}
|
javascript
|
{
"resource": ""
}
|
q22473
|
changePage
|
train
|
function changePage(pageNumber) {
var emit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (pageNumber > 0 && this.total > this.currentPerPage * (pageNumber - 1)) {
this.prevPage = this.currentPage;
this.currentPage = pageNumber;
if (emit) this.pageChanged();
}
}
|
javascript
|
{
"resource": ""
}
|
q22474
|
handlePerPage
|
train
|
function handlePerPage() {
//* if there's a custom dropdown then we use that
if (this.customRowsPerPageDropdown !== null && Array.isArray(this.customRowsPerPageDropdown) && this.customRowsPerPageDropdown.length !== 0) {
this.rowsPerPageOptions = this.customRowsPerPageDropdown;
} else {
//* otherwise we use the default rows per page dropdown
this.rowsPerPageOptions = cloneDeep(DEFAULT_ROWS_PER_PAGE_DROPDOWN);
}
if (this.perPage) {
this.currentPerPage = this.perPage; // if perPage doesn't already exist, we add it
var found = false;
for (var i = 0; i < this.rowsPerPageOptions.length; i++) {
if (this.rowsPerPageOptions[i] === this.perPage) {
found = true;
}
}
if (!found && this.perPage !== -1) {
this.rowsPerPageOptions.unshift(this.perPage);
}
} else {
// reset to default
this.currentPerPage = 10;
}
}
|
javascript
|
{
"resource": ""
}
|
q22475
|
hasFilterRow
|
train
|
function hasFilterRow() {
// if (this.mode === 'remote' || !this.globalSearchEnabled) {
for (var i = 0; i < this.columns.length; i++) {
var col = this.columns[i];
if (col.filterOptions && col.filterOptions.enabled) {
return true;
}
} // }
return false;
}
|
javascript
|
{
"resource": ""
}
|
q22476
|
getPlaceholder
|
train
|
function getPlaceholder(column) {
var placeholder = this.isFilterable(column) && column.filterOptions.placeholder || "Filter ".concat(column.label);
return placeholder;
}
|
javascript
|
{
"resource": ""
}
|
q22477
|
updateFilters
|
train
|
function updateFilters(column, value) {
var _this = this;
if (this.timer) clearTimeout(this.timer);
this.timer = setTimeout(function () {
_this.updateFiltersImmediately(column, value);
}, 400);
}
|
javascript
|
{
"resource": ""
}
|
q22478
|
onCheckboxClicked
|
train
|
function onCheckboxClicked(row, index$$1, event) {
this.$set(row, 'vgtSelected', !row.vgtSelected);
this.$emit('on-row-click', {
row: row,
pageIndex: index$$1,
selected: !!row.vgtSelected,
event: event
});
}
|
javascript
|
{
"resource": ""
}
|
q22479
|
dig
|
train
|
function dig(obj, selector) {
var result = obj;
var splitter = selector.split('.');
for (var i = 0; i < splitter.length; i++) {
if (typeof result === 'undefined' || result === null) {
return undefined;
}
result = result[splitter[i]];
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q22480
|
isSortableColumn
|
train
|
function isSortableColumn(index$$1) {
var sortable = this.columns[index$$1].sortable;
var isSortable = typeof sortable === 'boolean' ? sortable : this.sortable;
return isSortable;
}
|
javascript
|
{
"resource": ""
}
|
q22481
|
getClasses
|
train
|
function getClasses(index$$1, element, row) {
var _this$typedColumns$in = this.typedColumns[index$$1],
typeDef = _this$typedColumns$in.typeDef,
custom = _this$typedColumns$in["".concat(element, "Class")];
var isRight = typeDef.isRight;
if (this.rtl) isRight = true;
var classes = {
'vgt-right-align': isRight,
'vgt-left-align': !isRight
}; // for td we need to check if value is
// a function.
if (typeof custom === 'function') {
classes[custom(row)] = true;
} else if (typeof custom === 'string') {
classes[custom] = true;
}
return classes;
}
|
javascript
|
{
"resource": ""
}
|
q22482
|
filterRows
|
train
|
function filterRows(columnFilters) {
var _this4 = this;
var fromFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
// if (!this.rows.length) return;
// this is invoked either as a result of changing filters
// or as a result of modifying rows.
this.columnFilters = columnFilters;
var computedRows = cloneDeep(this.originalRows); // do we have a filter to care about?
// if not we don't need to do anything
if (this.columnFilters && Object.keys(this.columnFilters).length) {
// every time we filter rows, we need to set current page
// to 1
// if the mode is remote, we only need to reset, if this is
// being called from filter, not when rows are changing
if (this.mode !== 'remote' || fromFilter) {
this.changePage(1);
} // we need to emit an event and that's that.
// but this only needs to be invoked if filter is changing
// not when row object is modified.
if (fromFilter) {
this.$emit('on-column-filter', {
columnFilters: this.columnFilters
});
} // if mode is remote, we don't do any filtering here.
if (this.mode === 'remote') {
if (fromFilter) {
this.$emit('update:isLoading', true);
} else {
// if remote filtering has already been taken care of.
this.filteredRows = computedRows;
}
return;
}
var _loop = function _loop(i) {
var col = _this4.typedColumns[i];
if (_this4.columnFilters[col.field]) {
computedRows = each(computedRows, function (headerRow) {
var newChildren = headerRow.children.filter(function (row) {
// If column has a custom filter, use that.
if (col.filterOptions && typeof col.filterOptions.filterFn === 'function') {
return col.filterOptions.filterFn(_this4.collect(row, col.field), _this4.columnFilters[col.field]);
} // Otherwise Use default filters
var typeDef = col.typeDef;
return typeDef.filterPredicate(_this4.collect(row, col.field), _this4.columnFilters[col.field]);
}); // should we remove the header?
headerRow.children = newChildren;
});
}
};
for (var i = 0; i < this.typedColumns.length; i++) {
_loop(i);
}
}
this.filteredRows = computedRows;
}
|
javascript
|
{
"resource": ""
}
|
q22483
|
findRushJsonFolder
|
train
|
function findRushJsonFolder() {
if (!_rushJsonFolder) {
let basePath = __dirname;
let tempPath = __dirname;
do {
const testRushJsonPath = path.join(basePath, exports.RUSH_JSON_FILENAME);
if (fs.existsSync(testRushJsonPath)) {
_rushJsonFolder = basePath;
break;
}
else {
basePath = tempPath;
}
} while (basePath !== (tempPath = path.dirname(basePath))); // Exit the loop when we hit the disk root
if (!_rushJsonFolder) {
throw new Error('Unable to find rush.json.');
}
}
return _rushJsonFolder;
}
|
javascript
|
{
"resource": ""
}
|
q22484
|
ensureAndJoinPath
|
train
|
function ensureAndJoinPath(baseFolder, ...pathSegments) {
let joinedPath = baseFolder;
try {
for (let pathSegment of pathSegments) {
pathSegment = pathSegment.replace(/[\\\/]/g, '+');
joinedPath = path.join(joinedPath, pathSegment);
if (!fs.existsSync(joinedPath)) {
fs.mkdirSync(joinedPath);
}
}
}
catch (e) {
throw new Error(`Error building local installation folder (${path.join(baseFolder, ...pathSegments)}): ${e}`);
}
return joinedPath;
}
|
javascript
|
{
"resource": ""
}
|
q22485
|
isPackageAlreadyInstalled
|
train
|
function isPackageAlreadyInstalled(packageInstallFolder) {
try {
const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME);
if (!fs.existsSync(flagFilePath)) {
return false;
}
const fileContents = fs.readFileSync(flagFilePath).toString();
return fileContents.trim() === process.version;
}
catch (e) {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q22486
|
installPackage
|
train
|
function installPackage(packageInstallFolder, name, version) {
try {
console.log(`Installing ${name}...`);
const npmPath = getNpmPath();
const result = childProcess.spawnSync(npmPath, ['install'], {
stdio: 'inherit',
cwd: packageInstallFolder,
env: process.env
});
if (result.status !== 0) {
throw new Error('"npm install" encountered an error');
}
console.log(`Successfully installed ${name}@${version}`);
}
catch (e) {
throw new Error(`Unable to install package: ${e}`);
}
}
|
javascript
|
{
"resource": ""
}
|
q22487
|
getBinPath
|
train
|
function getBinPath(packageInstallFolder, binName) {
const binFolderPath = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME, '.bin');
const resolvedBinName = (os.platform() === 'win32') ? `${binName}.cmd` : binName;
return path.resolve(binFolderPath, resolvedBinName);
}
|
javascript
|
{
"resource": ""
}
|
q22488
|
writeFlagFile
|
train
|
function writeFlagFile(packageInstallFolder) {
try {
const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME);
fs.writeFileSync(flagFilePath, process.version);
}
catch (e) {
throw new Error(`Unable to create installed.flag file in ${packageInstallFolder}`);
}
}
|
javascript
|
{
"resource": ""
}
|
q22489
|
addMessage
|
train
|
function addMessage(from, target, text, time) {
var name = (target == '*' ? 'all' : target);
if(text === null) return;
if(time == null) {
// if the time is null or undefined, use the current time.
time = new Date();
} else if((time instanceof Date) === false) {
// if it's a timestamp, interpret it
time = new Date(time);
}
//every message you see is actually a table with 3 cols:
// the time,
// the person who caused the event,
// and the content
var messageElement = $(document.createElement("table"));
messageElement.addClass("message");
// sanitize
text = util.toStaticHTML(text);
var content = '<tr>' + ' <td class="date">' + util.timeString(time) + '</td>' + ' <td class="nick">' + util.toStaticHTML(from) + ' says to ' + name + ': ' + '</td>' + ' <td class="msg-text">' + text + '</td>' + '</tr>';
messageElement.html(content);
//the log is the stream that we view
$("#chatHistory").append(messageElement);
base += increase;
scrollDown(base);
}
|
javascript
|
{
"resource": ""
}
|
q22490
|
initUserList
|
train
|
function initUserList(data) {
users = data.users;
for(var i = 0; i < users.length; i++) {
var slElement = $(document.createElement("option"));
slElement.attr("value", users[i]);
slElement.text(users[i]);
$("#usersList").append(slElement);
}
}
|
javascript
|
{
"resource": ""
}
|
q22491
|
addUser
|
train
|
function addUser(user) {
var slElement = $(document.createElement("option"));
slElement.attr("value", user);
slElement.text(user);
$("#usersList").append(slElement);
}
|
javascript
|
{
"resource": ""
}
|
q22492
|
markPercentagesForRecord
|
train
|
function markPercentagesForRecord(record)
{
if (!(this._showShortEvents || record.isLong()))
return;
var percentages = this._overviewCalculator.computeBarGraphPercentages(record);
var end = Math.round(percentages.end);
var categoryName = record.category.name;
for (var j = Math.round(percentages.start); j <= end; ++j)
timelines[categoryName][j] = true;
}
|
javascript
|
{
"resource": ""
}
|
q22493
|
train
|
function(data) {
if(!data || !data.sys) {
return;
}
dict = data.sys.dict;
var protos = data.sys.protos;
//Init compress dict
if(dict) {
dict = dict;
abbrs = {};
for(var route in dict) {
abbrs[dict[route]] = route;
}
}
//Init protobuf protos
if(protos) {
protoVersion = protos.version || 0;
serverProtos = protos.server || {};
clientProtos = protos.client || {};
//Save protobuf protos to localStorage
window.localStorage.setItem('protos', JSON.stringify(protos));
if(!!protobuf) {
protobuf.init({encoderProtos: protos.client, decoderProtos: protos.server});
}
if(!!decodeIO_protobuf) {
decodeIO_encoder = decodeIO_protobuf.loadJson(clientProtos);
decodeIO_decoder = decodeIO_protobuf.loadJson(serverProtos);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22494
|
forwardWheelEvent
|
train
|
function forwardWheelEvent(event)
{
var clone = document.createEvent("WheelEvent");
clone.initWebKitWheelEvent(event.wheelDeltaX, event.wheelDeltaY,
event.view,
event.screenX, event.screenY,
event.clientX, event.clientY,
event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);
this._mainPanel.element.dispatchEvent(clone);
}
|
javascript
|
{
"resource": ""
}
|
q22495
|
train
|
function(oldRange, newRange, oldText, newText)
{
if (!this._internalTextChangeMode)
this._textModel.resetUndoStack();
this._mainPanel.textChanged(oldRange, newRange);
this._gutterPanel.textChanged(oldRange, newRange);
this._updatePanelOffsets();
}
|
javascript
|
{
"resource": ""
}
|
|
q22496
|
train
|
function(data){
if(!data || !data.sys) {
return;
}
pinus.data = pinus.data || {};
var dict = data.sys.dict;
var protos = data.sys.protos;
//Init compress dict
if(dict){
pinus.data.dict = dict;
pinus.data.abbrs = {};
for(var route in dict){
pinus.data.abbrs[dict[route]] = route;
}
}
//Init protobuf protos
if(protos){
pinus.data.protos = {
server : protos.server || {},
client : protos.client || {}
};
if(!!protobuf){
protobuf.init({encoderProtos: protos.client, decoderProtos: protos.server});
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22497
|
train
|
function(text)
{
if (this._uncommittedIsTop) {
this._data.pop();
delete this._uncommittedIsTop;
}
this._historyOffset = 1;
if (this._coalesceHistoryDupes && text === this._currentHistoryItem())
return;
this._data.push(text);
}
|
javascript
|
{
"resource": ""
}
|
|
q22498
|
calc_screen_size
|
train
|
function calc_screen_size(scount) {
if (!scount) { scount = $("#screens .screen").length; }
var ssize = (($(window).height() - bottom_height - 20) / scount)
- (bar_height + 53);
return ssize;
}
|
javascript
|
{
"resource": ""
}
|
q22499
|
SocketNamespace
|
train
|
function SocketNamespace (socket, name) {
this.socket = socket;
this.name = name || '';
this.flags = {};
this.json = new Flag(this, 'json');
this.ackPackets = 0;
this.acks = {};
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.