_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q14800
train
function(str, end) { return (str.length >= end.length &&
javascript
{ "resource": "" }
q14801
set
train
function set(key, module, global) { var m = null; var isGlobal = global && typeof global !== 'undefined'; // check to make sure the module has been assigned only once if (isGlobal) { if (global.hasOwnProperty(key)) { throw '[define-shim] Module ' + key + ' already exists'; } } else if (_map.hasOw...
javascript
{ "resource": "" }
q14802
insert
train
function insert (i, val, array) { array = copy(array)
javascript
{ "resource": "" }
q14803
generateFakeDataForSchema
train
function generateFakeDataForSchema(schemaName) { return new RSVP.Promise(function (resolve, reject) { agolSchemas.getSchema(schemaName).then(function (schema) { // Generate fake data
javascript
{ "resource": "" }
q14804
FullyTyped
train
function FullyTyped (configuration) { if (arguments.length === 0 || configuration === null) configuration = {}; // validate input parameter if (!util.isPlainObject(configuration)) { throw Error('If provided, the schema configuration must be a plain object. Received: ' + configuration); } /...
javascript
{ "resource": "" }
q14805
validate
train
function validate(task, options) { if (!task) { if (options.verbose) { console.log(' -', chalk.bold.yellow('[WARNING]:'), 'Task does not exist'); } return Promise.resolve(false); } return new Promise(function(resolve, reject) {
javascript
{ "resource": "" }
q14806
log
train
function log (out, desc) { logger.log(header()) if (desc) {
javascript
{ "resource": "" }
q14807
error
train
function error (out, desc) { logger.error(header()) if (desc) {
javascript
{ "resource": "" }
q14808
watch
train
function watch(glob, taskName) { var watcher = chokidar.watch(glob, {persistent: true,}); watcher.on('ready', ()=> {
javascript
{ "resource": "" }
q14809
invokeTask
train
function invokeTask(taskName) { const tc = TASKS.globals.globalTaskCollection; const t = tc.getByName(taskName); if (t === undefined) {
javascript
{ "resource": "" }
q14810
create
train
function create() { var sha1sum = crypto.createHash('sha1'); return { update: update, digest: digest }; function update(data) {
javascript
{ "resource": "" }
q14811
train
function(obj, maxNumProperties) { var result = ""; maxNumProperties = maxNumProperties === undefined ? Number.MAX_VALUE : maxNumProperties; if (obj !== undefined && obj !== null) { var separator = ""; var propCount = 0; for (var propertyName in obj) { var objValue;...
javascript
{ "resource": "" }
q14812
train
function(argumentName, defaultValue) { var result = argMap[argumentName]; if (this.isEmpty(result) && this.isNotEmpty(defaultValue)) { if (typeof defaultValue === 'object') {
javascript
{ "resource": "" }
q14813
bundle
train
function bundle() { return bundler.bundle() // log errors if they happen .on('error', gutil.log.bind(gutil, 'Browserify Error'))
javascript
{ "resource": "" }
q14814
JFP_Error
train
function JFP_Error(message) { Error.call(this, message); Object.defineProperty(this, "name", { value: this.constructor.name }); Object.defineProperty(this, "message", {
javascript
{ "resource": "" }
q14815
type
train
function type(input) { //If the input value is null, undefined or NaN the toStringTypes object shouldn't be used if (input === null || input === undefined || (input !== input && String(input) === "NaN")) { return String(input); }
javascript
{ "resource": "" }
q14816
inherits
train
function inherits(constructor, superConstructor) { constructor.super_ = superConstructor; constructor.prototype = Object.create(superConstructor.prototype, {
javascript
{ "resource": "" }
q14817
Confectioner
train
function Confectioner() { if (!(this instanceof Confectioner)) { var instance = Object.create(clazz); Confectioner.apply(instance, arguments);
javascript
{ "resource": "" }
q14818
floatFromBuffer
train
function floatFromBuffer (buf) { if (buf.length < FLOAT_ENTROPY_BYTES) { throw new Error( 'buffer must contain at least ' + FLOAT_ENTROPY_BYTES + ' bytes of entropy' ) } var position = 0 // http://stackoverflow.com/questions/15753019/floating-point-number-from-crypto-randombytes-in-javascript r...
javascript
{ "resource": "" }
q14819
applyNSync
train
function applyNSync () { var args = Array.prototype.slice.call(arguments) var fn = args.shift() var num = args.shift() var arr = [] for (var
javascript
{ "resource": "" }
q14820
applyN
train
function applyN (fn, opts, ready) { var num = opts.num || 0 var unique = opts.unique var arr = [] fn(opts, onValue) function onValue (err, value) { if (err) { return ready(err) } if (!unique || arr.indexOf(value) === -1) { arr.push(value)
javascript
{ "resource": "" }
q14821
restifyCORSSimple
train
function restifyCORSSimple(req, res, next) { var origin; if (!(origin = matchOrigin(req, origins))) { next(); return; } function corsOnHeader() { origin = req.headers.origin; if (opts.credentials) { res.setHeader(AC_ALLOW_CREDS, 'true');
javascript
{ "resource": "" }
q14822
processErrorAndData
train
function processErrorAndData (error, data) { if (_cb.beforeReturnErrorAndData) { _cb.beforeReturnErrorAndData(error, data); } if (_cb.returnErrorAndData) {
javascript
{ "resource": "" }
q14823
processError
train
function processError (error) { if (_cb.beforeReturnError) { _cb.beforeReturnError(error); } if (_cb.returnError) { _cb.returnError(error,
javascript
{ "resource": "" }
q14824
processData
train
function processData (data) { if (_cb.beforeReturnData) { _cb.beforeReturnData(data); } if (_cb.returnData) { _cb.returnData(data,
javascript
{ "resource": "" }
q14825
processNotFound
train
function processNotFound () { if (_cb.beforeReturnNotFound) { _cb.beforeReturnNotFound(); } if (_cb.returnNotFound) { _cb.returnNotFound(response);
javascript
{ "resource": "" }
q14826
train
function(token) { this.oauthClient.setCredentials(token); this.brain.set(this.TOKEN_KEY, token.access_token); if (token.refresh_token) {
javascript
{ "resource": "" }
q14827
train
function(code, cb) { var self = this; this.oauthClient.getToken(code, function(err, token) { if (err) { cb({ err: err, msg: 'Error while trying to retrieve access token' }); return; } ...
javascript
{ "resource": "" }
q14828
train
function(cb) { var at = this.brain.get(this.TOKEN_KEY), rt = this.brain.get(this.REFRESH_KEY); if (at == null || rt == null) { cb({ err: null, msg: 'Error: No tokens found. Please authorize this app and store a refresh token' }); ...
javascript
{ "resource": "" }
q14829
train
function() { return { token: this.brain.get(this.TOKEN_KEY),
javascript
{ "resource": "" }
q14830
findValueByPath
train
function findValueByPath(jsonData, path){ var errorParts = false; path.split('.').forEach(function(part){
javascript
{ "resource": "" }
q14831
requestPrice
train
function requestPrice(urlAPI, callback){ request({ method: 'GET', url: urlAPI, timeout: TIMEOUT, maxRedirects: 2 }, function(error, res, body){ if(!error){ try{
javascript
{ "resource": "" }
q14832
train
function(buildPath, manifest) { fs.stat(manifest, function(err, stat) { if (! err) { manifest = JSON.parse(fs.readFileSync(manifest));
javascript
{ "resource": "" }
q14833
train
function() { var children = this.parent.children, index = CKEDITOR.tools.indexOf( children, this ), previous = this.previous, next = this.next; previous && ( previous.next = next
javascript
{ "resource": "" }
q14834
train
function( condition ) { var checkFn = typeof condition == 'function' ? condition : typeof condition == 'string' ? function( el ) { return el.name == condition; } : function( el ) { return el.name in condition; }; var parent = this.parent; // Parent has to be
javascript
{ "resource": "" }
q14835
train
function(d) { var self = this; $('#circle-info').html(d.name); console.log(d); var focus0 = self.focus; self.focus = d; var transition = d3.transition() .duration(d3.event.altKey ? 7500 : 750) .tween("zoom", fun...
javascript
{ "resource": "" }
q14836
discoverServicesAndCharacteristics
train
function discoverServicesAndCharacteristics(error) { if (error) { return reject(error); }
javascript
{ "resource": "" }
q14837
setupEmitter
train
function setupEmitter(error) { if (error) { return reject(error); } const sensorService = getService(SERVICE_SENSOR_UUID, peripheral); const notifiable = sensorService.characteristics; const withNotified = Promise.all(notifiable.map(characteristic => new Promise((resolve, reject) => ...
javascript
{ "resource": "" }
q14838
train
function (config) { this.globals = config.globals || {}; this.templates = {}; this.config = _.extend({}, defaults, config); this.config.optionsRegex = new RegExp("^" +
javascript
{ "resource": "" }
q14839
train
function(z_real, w_copy, s_property) { // property is a function (ie: instance method) if('function' === typeof z_real[s_property]) { // implement same method name in virtual object w_copy[s_property] = function() { // forward to real class return z_real[s_property].apply(z_real, arguments); }; } // ...
javascript
{ "resource": "" }
q14840
logFn
train
function logFn(level){ return function(msg){ var args = Array.prototype.slice.call(arguments); if (level === 'hr'){ args = ['------------------------------------------------------------'];
javascript
{ "resource": "" }
q14841
disable
train
function disable(namespaces) { var split = (namespaces || '').split(/[\s,]+/); var len = split.length; function removeNamespaceFromNames(namespaces){ _.remove(exports.names, function(name){ return name.toString() === '/^' + namespaces + '$/'; }); } for (var i = 0; i < len; i++) { if (!spli...
javascript
{ "resource": "" }
q14842
XUnitZH
train
function XUnitZH(runner) { var tests = [], passes = 0, failures = 0; runner.on('pass', function(test){ test.state = 'passed'; passes++; tests.push(test); test.number = tests.length; }); runner.on('fail', function(test){ test.state = 'failed'; failures++; tests.push(...
javascript
{ "resource": "" }
q14843
toConsole
train
function toConsole(number, name, state, content){ console.log(number + ') ' + state + ' ' +
javascript
{ "resource": "" }
q14844
checkIceComponentState
train
function checkIceComponentState(key, value) { if(typeof value != 'string') throw SyntaxError(key+' param should be a String, not '+typeof value); if(!value.match('DISCONNECTED|GATHERING|CONNECTING|CONNECTED|READY|FAILED'))
javascript
{ "resource": "" }
q14845
applyStyles
train
function applyStyles (css) { return flattenDeep(css) .reduce( (classNames, declarations) => { if (!declarations) {
javascript
{ "resource": "" }
q14846
centericMap
train
function centericMap(array, callback) { var retArray = [], length, left, right; if(array) { length = array.length - 1; left = length >> 1; while(left >= 0) { retArray[left] = callback(array[left]); right = length - left;
javascript
{ "resource": "" }
q14847
train
function (children) { var allChildren = this.get('allChildren'); if(allChildren) { this._setChildren(allChildren.filter(function (child)
javascript
{ "resource": "" }
q14848
train
function (childrenToRemove) { var children = this.get('children'); if(children) { children = children.filter(function (child) { return childrenToRemove.indexOf(child) === -1;
javascript
{ "resource": "" }
q14849
train
function (property, callback, thisArg) { if(this.get(property)) {
javascript
{ "resource": "" }
q14850
train
function (depth) { this.set('depth', depth); depth++; this.get('inputs').forEach(function (input) {
javascript
{ "resource": "" }
q14851
train
function() { this.setChildren(this.get('inputs').concat(this.get('children') || [])); var ancestor = this.get('parent.parent'); if(ancestor) {
javascript
{ "resource": "" }
q14852
train
function() { this.removeChildren(this.get('inputs')); var ancestor = this.get('parent.parent'); if(ancestor) {
javascript
{ "resource": "" }
q14853
train
function () { var vertex = this.get('vertex'); this._super(); // Initialize data members this.setProperties({
javascript
{ "resource": "" }
q14854
train
function (vertex, data) { return InputDataNode.create(Ember.$.extend(data, {
javascript
{ "resource": "" }
q14855
_normalizeVertexTree
train
function _normalizeVertexTree(vertex) { var children = vertex.get('children'); if(children) { children = children.filter(function (child) { _normalizeVertexTree(child); return child.get('type') !==
javascript
{ "resource": "" }
q14856
_normalizeRawData
train
function _normalizeRawData(data) { var EmObj = Ember.Object, vertices, // Hash of vertices edges, // Hash of edges rootVertices = []; // Vertices without out-edges are considered root vertices vertices = data.vertices.reduce(function (obj, vertex) { vertex = VertexDataNod...
javascript
{ "resource": "" }
q14857
train
function (data) { var dummy = DataNode.create({ type: types.DUMMY, vertexName: 'dummy', depth: 1 }), root = RootDataNode.create({ dummy: dummy }); if(!data.vertices) { return "Vertices not found!"; } _data = _normalizeRawData(data);...
javascript
{ "resource": "" }
q14858
gather
train
function gather (variable, node) { if (node.parent) { let values = [] for (let n of Object.values(node.parent.nodes)) { if (n.type === 'decl' && n.prop === `$${variable}`) { values.push(n.value) } } values.reverse() let parentValues = node.parent.parent ?
javascript
{ "resource": "" }
q14859
train
function (selector, args, cb) { selector = selector || document; args = args || {}; var self = this; $(selector).find('*[data-view]').each(function () { var viewArgs = _.extend({}, args);
javascript
{ "resource": "" }
q14860
promisifyAll
train
function promisifyAll(sourceObject, keys){ // promisified output const promisifiedFunctions = {}; // process each object key for (const name of keys){ // function exist in source object ? if (name in sourceObject && typeof sourceObject[name] === 'function'){ // create promis...
javascript
{ "resource": "" }
q14861
train
function (name, paramd) { var self = this; paramd = (paramd !== undefined) ? paramd : {}; self.name = (name !== undefined) ? name : "unnamed-queue"; self.qitems = []; self.qurrents =
javascript
{ "resource": "" }
q14862
startSearch
train
function startSearch() { iface.question('Enter search: ', function (query) { // Get the results of our query var matches = fileFinder.query(query), len = matches.length; // If no results were found if (len === 0) { console.log('No results found for: ' + query); startSearc...
javascript
{ "resource": "" }
q14863
getAuth
train
function getAuth() { if (!auth.key || auth.key.indexOf("goes-here") !== -1) { var err = new Error("API key missing"); out.error(err.message);
javascript
{ "resource": "" }
q14864
sortComments
train
function sortComments(comments) { var moduleComments = []; var typeComments = []; var varComments = []; var methodComments = []; var typelessComments = []; comments.forEach(function (comment) { if(comment.type) { switch(comment.type) { case exports.COMMENT_TY...
javascript
{ "resource": "" }
q14865
identifyCommentType
train
function identifyCommentType(tag) { var commentType = null; for (var tagName in tag) { if (tag.hasOwnProperty(tagName)) { switch (tagName) { case exports.TAG_NAMES.API: case exports.TAG_NAMES.METHOD: case exports.TAG_NAMES.METHOD_SIGNATURE: ...
javascript
{ "resource": "" }
q14866
balance
train
function balance(a, b){ var diff = a.length - b.length var short = diff
javascript
{ "resource": "" }
q14867
activate
train
function activate(context) { // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated console.log('Congratulations, your extension "Tlid" is now active!'); // // The command has been de...
javascript
{ "resource": "" }
q14868
TypedString
train
function TypedString (config) { const string = this; // validate min length if (config.hasOwnProperty('minLength') && (!util.isInteger(config.minLength) || config.minLength < 0)) { const message = util.propertyErrorMessage('minLength', config.minLength, 'Must be an integer that is greater than or e...
javascript
{ "resource": "" }
q14869
custom
train
function custom(options, onfile, done) { if ((!options) || (typeof(options) == 'function')) throw new Error("please provide some options"); if (!options.fields) throw new Error("please
javascript
{ "resource": "" }
q14870
Ankh
train
function Ankh(kernel) { Object.defineProperty(this,'kernel',{ value: (kernel
javascript
{ "resource": "" }
q14871
notFound
train
function notFound( req, res, next ) { var err = new Error( 'Not Found' );
javascript
{ "resource": "" }
q14872
debug
train
function debug( err, req, res, next ) { res.status( err.status || 500 ); err.guid = uuid.v4(); console.error( err ); res.json( { error: err.message,
javascript
{ "resource": "" }
q14873
train
function( tmpl, data, options, parentItem ) { var ret, topLevel = !parentItem; if ( topLevel ) { // This is a top-level tmpl call (not from a nested template using {{tmpl}}) parentItem = topTmplItem; tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl ); wrappedItems = {}; // Any wrapped i...
javascript
{ "resource": "" }
q14874
train
function( elem ) { var tmplItem; if ( elem instanceof jQuery ) { elem = elem[0]; } while ( elem && elem.nodeType === 1 && !(tmplItem =
javascript
{ "resource": "" }
q14875
ConsoleLogger
train
function ConsoleLogger() { this.error = function () { if (loggingLevel(ERROR)) { console.error.apply(this, arguments); } }; this.warn = function () { if (loggingLevel(WARN)) { console.warn.apply(this, arguments); } }; this.info = function ()...
javascript
{ "resource": "" }
q14876
getNestedEditableIn
train
function getNestedEditableIn( editablesContainer, remainingEditables ) { if ( remainingEditables == null ) remainingEditables = findNestedEditables( editablesContainer ); var editable; while ( ( editable = remainingEditables.shift() ) )
javascript
{ "resource": "" }
q14877
rangeAtInnerBlockBoundary
train
function rangeAtInnerBlockBoundary( range, block, checkEnd ) { if ( !block ) return false; var testRange = range.clone(); testRange.collapse( !checkEnd );
javascript
{ "resource": "" }
q14878
orgs
train
async function orgs(users, options) { const opts = Object.assign({}, options); const acc = { orgs: [], names: [] }; if (isObject(users)) { return github('paged', '/user/orgs', users).then(res => addOrgs(acc, res)); } if (typeof users === 'string') users = [users]; if (!Array.isArray(users)) { retu...
javascript
{ "resource": "" }
q14879
init
train
function init(){ debug("Checking if there is a repository"); return co(function*(){ let repo; try { repo = yield nodegit.Repository.open(repositoryPath); } catch(err) { debug("Repository not found.");
javascript
{ "resource": "" }
q14880
_getFiles
train
function _getFiles(path){ let files = []; fs.readdirSync(path).forEach(function(file){ let subpath = path + '/' + file; if(fs.lstatSync(subpath).isDirectory()){ let filesReturned = _getFiles(subpath);
javascript
{ "resource": "" }
q14881
_commit
train
function _commit(repo, pathsToStage, message, pathsToUnstage) { return co(function*(){ repo = repo || (yield nodegit.Repository.open(repositoryPath)); debug("Adding files to the index"); let index = yield repo.refreshIndex(repositoryPath + "/.git/index"); if(path...
javascript
{ "resource": "" }
q14882
_createRepository
train
function _createRepository() { return co(function*(){ try { debug("Creating a new one"); let repo = yield nodegit.Repository.init(repositoryPath, 0); debug("Connection established"); debug("Creating main files"); yield _...
javascript
{ "resource": "" }
q14883
_createManifest
train
function _createManifest(){ let file = repositoryPath + '/manifest.json'; let manifest = { machines: {} }; return new Promise(function(resolve, reject) { debug("Creating manifest file"); jsonfile.writeFile(file, manifest, function (err) { ...
javascript
{ "resource": "" }
q14884
_createConfig
train
function _createConfig(){ let file = repositoryPath + '/config.json'; let config = { simulation: false }; return new Promise(function(resolve, reject) { jsonfile.writeFile(file, config, function (err) { if(err){
javascript
{ "resource": "" }
q14885
setManifest
train
function setManifest(manifest, withCommit, message){ jsonfile.writeFileSync(manifestPath, manifest, {spaces: 2}); if(withCommit) {
javascript
{ "resource": "" }
q14886
setConfig
train
function setConfig(config, withCommit, message){ jsonfile.writeFileSync(configPath, config, {spaces: 2}); if(withCommit) {
javascript
{ "resource": "" }
q14887
addMachine
train
function addMachine(name) { return co(function*(){ debug("Adding a new machine with the name '%s'", name); let manifest = getManifest(); if(manifest.machines[name]) { debug("Machine already exists"); throw new Error("Machine already exists"); ...
javascript
{ "resource": "" }
q14888
removeMachine
train
function removeMachine(name) { return co(function*(){ debug("Removing the machine"); let manifest = getManifest(); if(!manifest.machines[name]) { debug("Machine doesn't exists"); return; } let machinePath = machinesDir...
javascript
{ "resource": "" }
q14889
getVersionsKeys
train
function getVersionsKeys(machineName) { let manifest = getManifest(); if (!manifest.machines[machineName]) { throw new Error("Machine does not
javascript
{ "resource": "" }
q14890
getVersionRoute
train
function getVersionRoute(machineName, versionKey) { let manifest = getManifest(); if (!manifest.machines[machineName]) { throw new Error("Machine does not exists"); } if (!manifest.machines[machineName].versions[versionKey]) {
javascript
{ "resource": "" }
q14891
getVersionInfo
train
function getVersionInfo(machineName, versionKey) { let route = getVersionInfoRoute(machineName, versionKey);
javascript
{ "resource": "" }
q14892
setVersionInfo
train
function setVersionInfo(machineName, versionKey, info, withCommit, message) { let route = getVersionInfoRoute(machineName, versionKey); let previousInfo = jsonfile.readFileSync(repositoryPath + "/" + route); if(previousInfo.isSealed) { throw new Error("Cannot change the version SCXM...
javascript
{ "resource": "" }
q14893
addVersion
train
function addVersion(machineName) { return co(function*() { debug("Adding a new version to the '" + machineName + "' machine"); let manifest = getManifest(); if (!manifest.machines[machineName]) { throw new Error("Machine does not exists"); } ...
javascript
{ "resource": "" }
q14894
sealVersion
train
function sealVersion(machineName, versionKey) { return co(function*(){ debug("Attempting to seal the version '%s' of the machine '%s'", versionKey, machineName); let info = yield getVersionInfo(machineName, versionKey); if(info.isSealed) { throw new Error("Ver...
javascript
{ "resource": "" }
q14895
getVersionSCXML
train
function getVersionSCXML(machineName, versionKey) { let route = getVersionModelRoute(machineName, versionKey);
javascript
{ "resource": "" }
q14896
setVersionSCXML
train
function setVersionSCXML(machineName, versionKey, model, withCommit, message) { let route = getVersionInfoRoute(machineName, versionKey); let previousInfo = jsonfile.readFileSync(repositoryPath + "/" + route); if(previousInfo.isSealed) { throw new Error("Cannot change the version SC...
javascript
{ "resource": "" }
q14897
isSCXMLValid
train
function isSCXMLValid(model){ return new Promise(function(resolve, reject) { if(model === "") { reject("Model is empty"); return; } validator.validateXML(model, __dirname + '/xmlSchemas/scxml.xsd', function(err, result) {
javascript
{ "resource": "" }
q14898
getInstancesKeys
train
function getInstancesKeys(machineName, versionKey){ let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists"); } let version =
javascript
{ "resource": "" }
q14899
getInstanceRoute
train
function getInstanceRoute(machineName, versionKey, instanceKey){ let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists");
javascript
{ "resource": "" }