_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q4900 | onResError | train | function onResError (ctx, err) {
// nothing we can do here other
// than delegate to the app-level
// handler and log.
if (ctx.headerSent || ctx._finished != null) {
err.headerSent = ctx.headerSent
err.context = ctx.toJSON()
return err
}
// unset headers
if (isFn(ctx.res.getHeaderNames)) {
... | javascript | {
"resource": ""
} |
q4901 | NpmApi | train | function NpmApi(options) {
if (!(this instanceof NpmApi)) {
return new NpmApi(options);
}
Base.call(this, null, options);
this.is('npmapi');
this.use(utils.plugin());
this.use(utils.option());
this.define('List', List);
this.define('View', View);
this.define('Repo', Repo);
this.define('Maintai... | javascript | {
"resource": ""
} |
q4902 | train | function () {
return this.json.weatherdata.product.time[this.json.weatherdata.product.time.length - 1].from;
} | javascript | {
"resource": ""
} | |
q4903 | train | function() {
const startDate = moment.utc(this.getFirstDateInPayload());
const baseDate = startDate.clone().set('hour', 12).startOf('hour');
let firstDate = baseDate.clone();
log(`five day summary is using ${baseDate.toString()} as a starting point`);
/* istanbul ignore else */
if (firstDate.... | javascript | {
"resource": ""
} | |
q4904 | train | function (time) {
time = moment.utc(time);
if (time.isValid() === false) {
return Promise.reject(
new Error('Invalid date provided for weather lookup')
);
}
if (time.minute() > 30) {
time.add('hours', 1).startOf('hour');
} else {
time.startOf('hour');
}
log... | javascript | {
"resource": ""
} | |
q4905 | List | train | function List (name, view) {
if (!(this instanceof List)) {
return new List(name, view);
}
this.name = name;
this.view = view;
this.config = utils.clone(config);
this.config.pathname += '/_list/' + this.view.name + '/' + this.name;
} | javascript | {
"resource": ""
} |
q4906 | Repo | train | function Repo (name, store) {
if (!(this instanceof Repo)) {
return new Repo(name);
}
Base.call(this, store);
this.is('repo');
this.name = name;
this.use(downloads());
} | javascript | {
"resource": ""
} |
q4907 | defineModel | train | function defineModel(file) {
var object = require(file),
options = object.options || {},
modelName = object.modelName;
if (debug) {
fs.writeSync(debugFD, 'var ' + modelName + ' = Sequelize.define("' + modelName + '",\n' + util.inspect(object.attributes) + ',\n' + util.inspect... | javascript | {
"resource": ""
} |
q4908 | defineRelation | train | function defineRelation(modelName, relationType, targetModelName, options) {
if (debug) {
fs.writeSync(debugFD, modelName + '.' + relationType + '(' + targetModelName + ', ' + util.inspect(options, {depth: null}) + ');\n\n');
}
models[modelName][relationType](models[targetModelName], options); // a... | javascript | {
"resource": ""
} |
q4909 | getFileList | train | function getFileList() {
var i, file, isOverridden = {}, files = [], customFiles, baseFiles;
baseFiles = fs.readdirSync(path.join(modelsPath, definitionDir));
customFiles = fs.readdirSync(path.join(modelsPath, definitionDirCustom));
for (i = 0; i < customFiles.length; i = i + 1) {
file = custom... | javascript | {
"resource": ""
} |
q4910 | init | train | function init() {
var debugFile = path.join(__dirname, 'debug.js');
if (debug) {
if (fs.existsSync(debugFile)) { fs.unlinkSync(debugFile); }
debugFD = fs.openSync(debugFile, 'a');
}
getFileList(modelsPath).forEach(defineModel);
processAllRelations(defineRelation);
if (debug) {... | javascript | {
"resource": ""
} |
q4911 | slackAPI | train | function slackAPI(args, err_cb) {
err_cb = err_cb || function () {};
var self = this;
var authtoken = args.token;
this.slackData = {};
this.token = '';
this.logging = true;
this.autoReconnect = true;
this.i = 0;
if (typeof args !== 'object') {
this.logging = true;
... | javascript | {
"resource": ""
} |
q4912 | collectTransitiveDependencies | train | function collectTransitiveDependencies(
collected,
depGraph,
fromName
) {
const immediateDeps = depGraph[fromName];
if (immediateDeps) {
Object.keys(immediateDeps).forEach(toName => {
if (!collected[toName]) {
collected[toName] = true;
collectTransitiveDependencies(collected, depGrap... | javascript | {
"resource": ""
} |
q4913 | convertMarkdown | train | function convertMarkdown(opts) {
return new Promise((resolve, reject) => {
marked(opts.data, {}, (err, content) => {
if(err) return reject(err);
return resolve(content);
});
});
} | javascript | {
"resource": ""
} |
q4914 | replaceDelimiters | train | function replaceDelimiters(str, source, escape) {
var regex = cache[source] || (cache[source] = new RegExp(source, 'g'));
var match;
while ((match = regex.exec(str))) {
var prefix = str.slice(0, match.index);
var inner = (escape ? '\\' : '') + '{{' + match[1] + '}}';
var suffix = str.slice(match.inde... | javascript | {
"resource": ""
} |
q4915 | bitArrayToArray | train | function bitArrayToArray(bitArray) {
let resultArray = [];
for (let index = 0; index < bitArray.byteLength; index++) {
let arrayByte = bitArray.readUInt8(index);
// Skip bit operations if zero -> no bit is set
if (arrayByte !== 0) {
for (let bitIndex = 0; bitIndex < 8; bitInd... | javascript | {
"resource": ""
} |
q4916 | arrayToBitArray | train | function arrayToBitArray(numberArray, bufferLength, destinationBuffer) {
const returnBuffer = destinationBuffer ? destinationBuffer : Buffer.alloc(bufferLength);
if (destinationBuffer) {
// Get the bufferLength from the destination buffer, if one is provided
bufferLength = destinationBuffer.byte... | javascript | {
"resource": ""
} |
q4917 | gnuMessage | train | function gnuMessage(message, source) {
return (source ? (source.file ? source.file : "<css input>") + ":" + source.start.line + ":" + source.start.column : "") + " " + message
} | javascript | {
"resource": ""
} |
q4918 | read | train | function read(model) {
var query = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var mode = arguments.length <= 2 || arguments[2] === undefined ? 'read' : arguments[2];
return _columns2['default'](model).then(function (modelColumns) {
var fields = query.fields && query.fields[_type... | javascript | {
"resource": ""
} |
q4919 | related | train | function related(input, relation) {
return relation.split('.').reduce(function (input, relationSegment) {
if (_is_many2['default'](input)) {
// iterate each model and add its related models to the collection
return input.reduce(function (result, model) {
var related = model.related(relationSeg... | javascript | {
"resource": ""
} |
q4920 | destroyRelation | train | function destroyRelation(model, relations) {
if (!model) {
throw new Error('No model provided.');
}
return _destructure2['default'](model, relations).then(function (destructured) {
var relations = destructured.relations;
return _transact2['default'](model, function (transaction) {
return _relate... | javascript | {
"resource": ""
} |
q4921 | Spring | train | function Spring(fromBody, toBody, length, coeff, weight) {
this.from = fromBody;
this.to = toBody;
this.length = length;
this.coeff = coeff;
this.weight = typeof weight === 'number' ? weight : 1;
} | javascript | {
"resource": ""
} |
q4922 | train | function (pos) {
if (!pos) {
throw new Error('Body position is required');
}
var body = createBody(pos);
bodies.push(body);
return body;
} | javascript | {
"resource": ""
} | |
q4923 | train | function (body) {
if (!body) { return; }
var idx = bodies.indexOf(body);
if (idx < 0) { return; }
bodies.splice(idx, 1);
if (bodies.length === 0) {
bounds.reset();
}
return true;
} | javascript | {
"resource": ""
} | |
q4924 | train | function (body1, body2, springLength, springWeight, springCoefficient) {
if (!body1 || !body2) {
throw new Error('Cannot add null spring to force simulator');
}
if (typeof springLength !== 'number') {
springLength = -1; // assume global configuration
}
var spring = new Sp... | javascript | {
"resource": ""
} | |
q4925 | train | function (spring) {
if (!spring) { return; }
var idx = springs.indexOf(spring);
if (idx > -1) {
springs.splice(idx, 1);
return true;
}
} | javascript | {
"resource": ""
} | |
q4926 | create | train | function create(model) {
var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if (!model) {
throw new Error('No model provided.');
}
return _destructure2['default'](model.forge(), params).then(function (destructured) {
var attributes = destructured.attributes;
var r... | javascript | {
"resource": ""
} |
q4927 | getVersion | train | function getVersion(req) {
var version;
if (!req.version) {
if (req.headers && req.headers['accept-version']) {
version = req.headers['accept-version'];
}
} else {
version = String(req.version);
}
return version;
} | javascript | {
"resource": ""
} |
q4928 | Swipe | train | function Swipe(game, model) {
var self = this;
self.DIRECTION_UP = 1;
self.DIRECTION_DOWN = 2;
self.DIRECTION_LEFT = 4;
self.DIRECTION_RIGHT = 8;
self.DIRECTION_UP_RIGHT = 16;
self.DIRECTION_UP_LEFT = 32;
self.DIRECTION_DOWN_RIGHT = 64;
self.DIRECTION_DOWN_LEFT = 128;
self.game = game;
self.mode... | javascript | {
"resource": ""
} |
q4929 | createRelation | train | function createRelation(model, relationName, data) {
if (!model) {
throw new Error('No model provided.');
}
return _transact2['default'](model, function (transaction) {
var existing = _related2['default'](model, relationName).map(function (rel) {
return {
id: _id2['default'](rel),
ty... | javascript | {
"resource": ""
} |
q4930 | update | train | function update(model) {
var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if (!model) {
throw new Error('No model provided.');
}
var currentState = model.toJSON({ shallow: true });
currentState.id = String(currentState.id);
return _destructure2['default'](model, pa... | javascript | {
"resource": ""
} |
q4931 | saveResource | train | function saveResource(callback) {
var self = this;
self._applyCustomDataUpdatesIfNecessary(function () {
self.dataStore.saveResource(self, callback);
});
} | javascript | {
"resource": ""
} |
q4932 | toGeoJSON | train | function toGeoJSON(json, options = Options) {
const collection = helpers.featureCollection([])
json.resourceSets[0].resources.map(result => {
// Point GeoJSON
const point = parsePoint(result)
const bbox = parseBBox(result)
let confidence = confidenceScore(bbox)
const properties = {
confide... | javascript | {
"resource": ""
} |
q4933 | error | train | function error (message) {
console.log(chalk.bgRed.white('[Error]' + message))
throw new Error(message)
} | javascript | {
"resource": ""
} |
q4934 | parseAddressComponents | train | function parseAddressComponents(components, short = Options.short) {
const results = {}
components.map(component => {
if (short) { results[component.types[0]] = component.short_name
} else { results[component.types[0]] = component.long_name }
})
return results
} | javascript | {
"resource": ""
} |
q4935 | parseBBox | train | function parseBBox(result) {
if (result.geometry) {
if (result.geometry.viewport) {
const viewport = result.geometry.viewport
return [viewport.southwest.lng, viewport.southwest.lat, viewport.northeast.lng, viewport.northeast.lat]
}
}
} | javascript | {
"resource": ""
} |
q4936 | parsePoint | train | function parsePoint(result) {
if (result.geometry) {
if (result.geometry.location) {
const {lng, lat} = result.geometry.location
return helpers.point([lng, lat])
}
}
} | javascript | {
"resource": ""
} |
q4937 | toGeoJSON | train | function toGeoJSON(json, options = Options) {
const short = options.short || Options.short
const collection = helpers.featureCollection([])
json.results.map(result => {
// Get Geometries
const point = parsePoint(result)
const bbox = parseBBox(result)
// Calculate Confidence score
const locati... | javascript | {
"resource": ""
} |
q4938 | toGeoJSON | train | function toGeoJSON(json, options = Options) {
const collection = featureCollection([])
collection.features = json.features.map(result => {
return result
})
return collection
} | javascript | {
"resource": ""
} |
q4939 | request | train | function request(url, geojsonParser, params = {}, options = utils.Options) {
// Create custom Axios instance
const instance = axios.create({})
// Remove any existing default Authorization headers
if (instance.defaults.headers.common && instance.defaults.headers.common.Authorization) { delete instance.defaults.... | javascript | {
"resource": ""
} |
q4940 | getInThere | train | function getInThere(thing, path) {
var out = thing;
var apathy = path.split('.');
for(var i =0 ; i < apathy.length; i ++ ) {
if(!out) {
return null;
}
out = out[apathy[i]];
}
return out;
} | javascript | {
"resource": ""
} |
q4941 | toGeoJSON | train | function toGeoJSON(json, options = Options) {
const languages = options.languages || Options.languages
const collection = helpers.featureCollection([])
if (json.results !== undefined) {
if (json.results.bindings !== undefined) {
json.results.bindings.map(result => {
// Standard Wikidata tags
... | javascript | {
"resource": ""
} |
q4942 | train | function ()
{
var self = this;
// Unbind events
self.$container.off('keydown', 'input');
self.$container.off('click', '[role=remove]');
self.$container.remove();
self.$element.removeData('materialtags');
self.$element.show();
... | javascript | {
"resource": ""
} | |
q4943 | OneSignal | train | function OneSignal(apiKey, appId, sandbox) {
// Default value for sandbox argument
if (typeof sandbox === 'undefined') {
sandbox = false;
}
/**
* The api key of Signal One
* @type {String}
*/
const API_KEY = apiKey;
/**
* The app id of Signal One
* @type {String}
*/
const APP_ID =... | javascript | {
"resource": ""
} |
q4944 | responseHandle | train | function responseHandle(error, response, body, reject, resolve) {
if (error) {
return reject(error);
}
try {
body = JSON.parse(body);
} catch (e) {
return reject(new Error('Wrong JSON Format'));
}
resolve(body);
} | javascript | {
"resource": ""
} |
q4945 | findFirstSeparatorChar | train | function findFirstSeparatorChar(input, startPos) {
for (let i = startPos; i < input.length; i++) {
if (separatorCharacters.indexOf(input[i]) !== -1) {
return i;
}
}
return -1;
} | javascript | {
"resource": ""
} |
q4946 | getDomainIndex | train | function getDomainIndex(input) {
let index = input.indexOf(':');
++index;
while (input[index] === '/') {
index++;
}
return index;
} | javascript | {
"resource": ""
} |
q4947 | matchOptions | train | function matchOptions(parsedFilterData, input, contextParams = {}) {
if (contextParams.elementTypeMask !== undefined && parsedFilterData.options) {
if (parsedFilterData.options.elementTypeMask !== undefined &&
!(parsedFilterData.options.elementTypeMask & contextParams.elementTypeMask)) {
return fals... | javascript | {
"resource": ""
} |
q4948 | toCursor | train | function toCursor(item, index) {
const id = item.id;
return base64(cursorPrefix + id + cursorSeparator + index);
} | javascript | {
"resource": ""
} |
q4949 | fromCursor | train | function fromCursor(cursor) {
cursor = unbase64(cursor);
cursor = cursor.substring(cursorPrefix.length, cursor.length);
const [id, index] = cursor.split(cursorSeparator);
return {
id,
index
};
} | javascript | {
"resource": ""
} |
q4950 | resolveEdge | train | function resolveEdge(item, index, queriedCursor, args = {}, source) {
if (queriedCursor) {
index = parseInt(queriedCursor.index, 10) + index;
if (index === 0) {
index = 1;
} else {
index++;
}
}
return {
cursor: toCursor(item, index),
node: item,
source
};
} | javascript | {
"resource": ""
} |
q4951 | createEdgeInfo | train | function createEdgeInfo(resultset, offset, index) {
const limit = offset - index;
// retrieve full count from the first edge
// or default 10
let fullCount = resultset[0] &&
resultset[0].fullCount &&
parseInt(resultset[0].fullCount, 10);
if (!resultset[0]) {
fullCount = 0;
}
let hasNextP... | javascript | {
"resource": ""
} |
q4952 | applyTTL | train | function applyTTL (cond) {
if (cond[key]) {
cond.$and || (cond.$and = []);
var a = {};
a[key] = cond[key];
cond.$and.push(a);
var b = {};
b[key] = { $gt: new Date };
cond.$and.push(b);
delete cond[key];
} else {
cond[key] = { $gt: new Date };
}
} | javascript | {
"resource": ""
} |
q4953 | movePropsToBackingStore | train | function movePropsToBackingStore(instance) {
var bs = getBackingStore(instance);
var proto = Object.getPrototypeOf(instance);
var stype = proto.entityType || proto.complexType;
stype.getProperties().forEach(function(prop) {
var propName = prop.name;
if (!instance... | javascript | {
"resource": ""
} |
q4954 | movePropDefsToProto | train | function movePropDefsToProto(proto) {
var stype = proto.entityType || proto.complexType;
var ctor = proto.constructor;
if (!ctor){
throw new Error("No type constructor for EntityType = "+stype.name);
}
addResetFn(ctor);
stype.getProperties().forEach(function(p... | javascript | {
"resource": ""
} |
q4955 | getAccessorFn | train | function getAccessorFn(bs, propName) {
return function () {
if (arguments.length == 0) {
return bs[propName];
} else {
bs[propName] = arguments[0];
}
};
} | javascript | {
"resource": ""
} |
q4956 | linkForInput | train | function linkForInput() {
var valTemplate = config.zValidateTemplate;
var requiredTemplate = config.zRequiredTemplate || '';
var decorator = angular.element('<span class="z-decorator"></span>');
if (attrs.zAppendTo){
angular.element(doc... | javascript | {
"resource": ""
} |
q4957 | createGetValErrs | train | function createGetValErrs(info) {
return function () {
var aspect = info.getEntityAspect();
if (aspect) {
var errs = aspect.getValidationErrors(info.propertyPath);
if (errs.length) {
return errs
... | javascript | {
"resource": ""
} |
q4958 | getIsRequired | train | function getIsRequired() {
var info = this;
if (info.isRequired !== undefined) { return info.isRequired; }
// We don't know if it is required yet.
// Once bound to the entity we can determine whether the data property is required
// Note: Not bound until *sec... | javascript | {
"resource": ""
} |
q4959 | _isList | train | function _isList(gqlTye) {
if (gqlTye instanceof GraphQLList) {
return true;
}
if (gqlTye instanceof GraphQLNonNull) {
return _isList(gqlTye.ofType);
}
return false;
} | javascript | {
"resource": ""
} |
q4960 | convertToCodecDefinition | train | function convertToCodecDefinition(r, line) {
if (!line || line[0] !== 'a') return r;
var result = reRtpMap.exec(line[1]);
if (!result) return r;
// Build the codec definition
var codec = result[2];
var typeNum = result[1];
r[codec.toUpperCase()] = {
num: typeNum,
codec: codec
... | javascript | {
"resource": ""
} |
q4961 | train | function(rawObj, arrayInst){
// create an instance
var inst = rawObj.constructor === Model ?
rawObj : new Model(rawObj);
// set a pointer to the array
inst.$$array = arrayInst;
return inst;
} | javascript | {
"resource": ""
} | |
q4962 | train | function(ref, deferred, loaderErr, schema) {
if (loaderErr) { return deferred.reject(loaderErr); }
if (!this._schemaRegistry.isRegistered(ref)) { this.register(schema, ref); }
deferred.resolve(schema);
} | javascript | {
"resource": ""
} | |
q4963 | instantSearch | train | function instantSearch() {
const q = $("#searchbox").val();
if (q === '')
return;
const matcher = "/matcher?beginsWith=" + q;
const request = host + matcher;
console.debug(request);
$.getJSON(request, '', {})
.done(data => {
$("#searchbox").autocomplete({
... | javascript | {
"resource": ""
} |
q4964 | terminator | train | function terminator(sig) {
if (typeof sig === "string") {
winston.log('info', '%s: Received %s - terminating service ...',
Date(Date.now()), sig);
process.exit(1);
}
winston.log('info', '%s: EPUB search stopped.', Date(Date.now()));
} | javascript | {
"resource": ""
} |
q4965 | train | function (config) {
var idx = new lunr.Index
idx.pipeline.add(
lunr.trimmer,
lunr.stopWordFilter,
lunr.stemmer
)
if (config) config.call(idx, idx)
return idx
} | javascript | {
"resource": ""
} | |
q4966 | merge | train | function merge() {
let i = 1
, key
, val
, obj
, target
;
// make sure we don't modify source element and it's properties
// objects are passed by reference
target = clone( arguments[0] );
while (obj = arguments[i++]) {
for (key in obj) {
if ( !hasOwn(obj, key) ) {
con... | javascript | {
"resource": ""
} |
q4967 | train | function() {
// call the base component's init function
UIComponent.prototype.init.apply(this, arguments);
// set the device model
this.setModel(models.createDeviceModel(), "device");
// create the views based on the url/hash
this.getRouter().initialize();
} | javascript | {
"resource": ""
} | |
q4968 | generateAccount | train | function generateAccount() {
let priKeyBytes = genPriKey();
let addressBytes = getAddressFromPriKey(priKeyBytes);
let address = getBase58CheckAddress(addressBytes);
let privateKey = byteArray2hexStr(priKeyBytes);
return {
privateKey,
address,
}
} | javascript | {
"resource": ""
} |
q4969 | strToDate | train | function strToDate(str) {
var tempStrs = str.split(" ");
var dateStrs = tempStrs[0].split("-");
var year = parseInt(dateStrs[0], 10);
var month = parseInt(dateStrs[1], 10) - 1;
var day = parseInt(dateStrs[2], 10);
if (tempStrs.length > 1) {
var timeStrs = tempStrs[1].split("-");
var hour = parseInt(... | javascript | {
"resource": ""
} |
q4970 | getProgramDir | train | function getProgramDir(programFile) {
const info = programFile.query_info('standard::', Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, null);
if (info.get_is_symlink()) {
const symlinkFile = programFile.get_parent().resolve_relative_path(info.get_symlink_target());
return symlinkFile.get_parent();
} ... | javascript | {
"resource": ""
} |
q4971 | fontAdded | train | function fontAdded(fontObj, url) {
function properties(obj, list) {
var moreInfo = document.createElement('table');
for (var i = 0; i < list.length; i++) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
td1.textContent = list[i];
... | javascript | {
"resource": ""
} |
q4972 | create | train | function create(pageIndex) {
var debug = document.createElement('div');
debug.id = 'stepper' + pageIndex;
debug.setAttribute('hidden', true);
debug.className = 'stepper';
stepperDiv.appendChild(debug);
var b = document.createElement('option');
b.textContent = 'Page ' + (pageInd... | javascript | {
"resource": ""
} |
q4973 | c | train | function c(tag, textContent) {
var d = document.createElement(tag);
if (textContent) {
d.textContent = textContent;
}
return d;
} | javascript | {
"resource": ""
} |
q4974 | repeatRange | train | function repeatRange(_unused, what, from, to) {
return new Array(Helpers.rand(Number(to) + 1, Number(from)) + 1).join(what);
} | javascript | {
"resource": ""
} |
q4975 | getRowBytesFromTransactionBase64 | train | function getRowBytesFromTransactionBase64(base64Data) {
let bytesDecode = base64DecodeFromString(base64Data);
let transaction = proto.protocol.Transaction.deserializeBinary(bytesDecode);
let raw = transaction.getRawData();
return raw.serializeBinary();
} | javascript | {
"resource": ""
} |
q4976 | genPriKey | train | function genPriKey() {
let ec = new EC('secp256k1');
let key = ec.genKeyPair();
let priKey = key.getPrivate();
let priKeyHex = priKey.toString('hex');
while (priKeyHex.length < 64) {
priKeyHex = "0" + priKeyHex;
}
return hexStr2byteArray(priKeyHex);
} | javascript | {
"resource": ""
} |
q4977 | getBase58CheckAddress | train | function getBase58CheckAddress(addressBytes) {
var hash0 = SHA256(addressBytes);
var hash1 = SHA256(hash0);
var checkSum = hash1.slice(0, 4);
checkSum = addressBytes.concat(checkSum);
var base58Check = encode58(checkSum);
return base58Check;
} | javascript | {
"resource": ""
} |
q4978 | getBase58CheckAddressFromPriKeyBase64String | train | function getBase58CheckAddressFromPriKeyBase64String(priKeyBase64String) {
var priKeyBytes = base64DecodeFromString(priKeyBase64String);
var pubBytes = getPubKeyFromPriKey(priKeyBytes);
var addressBytes = computeAddress(pubBytes);
return getBase58CheckAddress(addressBytes);
} | javascript | {
"resource": ""
} |
q4979 | ECKeySign | train | function ECKeySign(hashBytes, priKeyBytes) {
let ec = new EC('secp256k1');
let key = ec.keyFromPrivate(priKeyBytes, 'bytes');
let signature = key.sign(hashBytes);
let r = signature.r;
let s = signature.s;
let id = signature.recoveryParam;
let rHex = r.toString('hex');
while (rHex.length < 64) {
rHex... | javascript | {
"resource": ""
} |
q4980 | SHA256 | train | function SHA256(msgBytes) {
let shaObj = new jsSHA("SHA-256", "HEX");
let msgHex = byteArray2hexStr(msgBytes);
shaObj.update(msgHex);
let hashHex = shaObj.getHash("HEX");
return hexStr2byteArray(hashHex);
} | javascript | {
"resource": ""
} |
q4981 | register | train | function register(module, value) {
if (module in CORE_MODULES && DEBUG) {
print(`\u26A0\uFE0F ${module} already registered`);
}
CORE_MODULES[module] = value;
} | javascript | {
"resource": ""
} |
q4982 | internetAvailable | train | function internetAvailable(settings) {
// Require dns-socket module from dependencies
var dns = require('dns-socket');
settings = settings || {};
return new Promise(function(resolve, reject){
// Create instance of the DNS resolver
var socket = dns({
timeout: (settings.timeou... | javascript | {
"resource": ""
} |
q4983 | ingestSVG | train | function ingestSVG(cb) {
// :NOTE: xmlMode is important to not lowercase SVG tags
// and attributes, like viewBox and clipPath
var $ = cheerio.load(data.svg, {
xmlMode: true
});
cb(null, $, data);
} | javascript | {
"resource": ""
} |
q4984 | svgcolor | train | function svgcolor(el, color) {
var styles = window.getComputedStyle(el, null);
var fill = styles['fill'];
var stroke = styles['stroke'];
var isFill, isStroke;
if (!fill && !stroke) {
isFill = true;
}
else {
if (fill && fill !== 'none') {
isFill = tru... | javascript | {
"resource": ""
} |
q4985 | addCamelCasedVersion | train | function addCamelCasedVersion(obj) {
const regExp = /(-[a-z])/g
const replace = str => str[1].toUpperCase()
const newObj = {}
for (const key in obj) {
newObj[key] = obj[key]
newObj[key.replace(regExp, replace)] = obj[key]
}
return newObj
} | javascript | {
"resource": ""
} |
q4986 | iterate | train | function iterate(prop, value, options) {
if (!value) return value
let convertedValue = value
let type = typeof value
if (type === 'object' && Array.isArray(value)) type = 'array'
switch (type) {
case 'object':
if (prop === 'fallbacks') {
for (const innerProp in value) {
value[in... | javascript | {
"resource": ""
} |
q4987 | Flow | train | function Flow(flowControlId) {
Duplex.call(this, { objectMode: true });
this._window = this._initialWindow = INITIAL_WINDOW_SIZE;
this._flowControlId = flowControlId;
this._queue = [];
this._ended = false;
this._received = 0;
this._blocked = false;
} | javascript | {
"resource": ""
} |
q4988 | train | function(cfg) {
var sharingLink = _.get(cfg, 'links.sharing', {});
cfg.pluginsConfig.sharing = _.defaults(cfg.pluginsConfig.sharing || {}, {});
_.each(sharingLink, function(enabled, type) {
if (enabled != false) return;
if (type == 'all') cfg.plugins... | javascript | {
"resource": ""
} | |
q4989 | readLogStream | train | async function readLogStream(file, instance) {
return new Promise(resolve => {
var stream = fs.createReadStream(file, { encoding: 'utf8', highWaterMark: instance.chunkSize });
var hasStarted = false;
// Split data into chunks so we dont stall the client
stream.on('data', chunk => {
... | javascript | {
"resource": ""
} |
q4990 | momentRandom | train | function momentRandom(end = moment(), start) {
const endTime = +moment(end);
const randomNumber = (to, from = 0) =>
Math.floor(Math.random() * (to - from) + from);
if (start) {
const startTime = +moment(start);
if (startTime > endTime) {
throw new Error('End date is before start date!');
}
... | javascript | {
"resource": ""
} |
q4991 | ApiClient | train | function ApiClient(endpoint) {
if (endpoint.length > 0 && endpoint.slice(-1) != "/") {
endpoint += "/";
}
this.endpoint = endpoint;
this.namespace = null;
} | javascript | {
"resource": ""
} |
q4992 | SubscribeMixin | train | function SubscribeMixin(subscribe, key) {
var unsubscribe;
return {
componentDidMount: function () {
// this should never happen
if (unsubscribe) {
throw new Error('Cannot reuse a mixin.');
}
unsubscribe = subscribe(function (data) {
// by default, use the store's state as the component's stat... | javascript | {
"resource": ""
} |
q4993 | prepareRes | train | function prepareRes(stanza) {
var res = null;
if (stanza.is('iq') && (stanza.attr('type') == 'get' || stanza.attr('type') == 'set')) {
// TODO: When connected as a component, the from field needs to be set
// eplicitly (from = stanza.attrs.to).
res = new xmpp.Stanza('iq', { id: stanza.attr('id'... | javascript | {
"resource": ""
} |
q4994 | MutationSigner | train | function MutationSigner(privateKey) {
this.publicKey = ByteBuffer.wrap(privateKey.publicKey.toBuffer());
this._signer = bitcore.crypto.ECDSA().set({
endian: "big",
privkey: privateKey.privateKey
});
} | javascript | {
"resource": ""
} |
q4995 | splitOne | train | function splitOne(str, sep) {
let index = str.indexOf(sep);
return index < 0 ? null : [str.slice(0, index), str.slice(index + sep.length)];
} | javascript | {
"resource": ""
} |
q4996 | checkType | train | function checkType(obj, keyName) {
return obj && typeof obj === 'object' && Object.keys(obj).length === 1 &&
obj.hasOwnProperty(keyName);
} | javascript | {
"resource": ""
} |
q4997 | StanzaError | train | function StanzaError(message, type, condition) {
Error.apply(this, arguments);
Error.captureStackTrace(this, arguments.callee);
this.name = 'StanzaError';
this.message = message || null;
this.type = type || 'wait';
this.condition = condition || 'internal-server-error';
} | javascript | {
"resource": ""
} |
q4998 | create | train | function create() {
function app(stanza) { app.handle(stanza); }
utils.merge(app, application);
app._stack = [];
app._filters = [];
for (var i = 0; i < arguments.length; ++i) {
app.use(arguments[i]);
}
return app;
} | javascript | {
"resource": ""
} |
q4999 | TransactionBuilder | train | function TransactionBuilder(apiClient) {
if (typeof apiClient.namespace === "undefined" || apiClient.namespace === null) {
throw new Error("The API client has not been initialized");
}
this.client = apiClient;
this.records = [];
this.keys = [];
this.metadata = ByteBuffer.fromHe... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.