_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q56300
train
function (eventType, callback, scope) { if (callback) { scope = scope || this; // get the list for the event var list = this._eventHandlers[eventType] || (this._eventHandlers[eventType] = []); // and push the callback function if (callback instanceof EventDispatcher.EventHandler) { list.push(callback); } else { list.push(new EventDispatcher.EventHandler(callback, scope)); } } else { this.log('no eventHandler for "' + eventType + '"', "warn"); } return this; }
javascript
{ "resource": "" }
q56301
train
function (attributes, target) { this.$ = attributes; this.target = target; this.isDefaultPrevented = false; this.isPropagationStopped = false; this.isImmediatePropagationStopped = false; }
javascript
{ "resource": "" }
q56302
train
function () { this.isDefaultPrevented = true; if (this.$) { var e = this.$.orginalEvent; if (e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; // IE } } } }
javascript
{ "resource": "" }
q56303
train
function (items, options) { options = options || {}; _.defaults(options, { root: null, query: null, pageSize: null, queryParameters: {}, sortParameters: null, factory: this.$modelFactory || require('js/data/Model'), type: null }); this.$filterCache = {}; this.$sortCache = {}; this._count = { callbacks: [], state: COUNTSTATE.UNKNOWN }; if (options.root) { _.defaults(options, options.root.options); this.$modelFactory = options.root.$modelFactory; } this.callBase(items, options); this.$pageCache = []; }
javascript
{ "resource": "" }
q56304
train
function (query, options) { options.$itemsCount = undefined; var collection = new this.factory(null, options); collection.$context = this.$context; return collection; }
javascript
{ "resource": "" }
q56305
train
function (query) { if (query instanceof Query && query.query.sort) { if (this.$.query) { query.query.where = this.$.query.query.where; } var options = _.defaults({}, { query: query, root: this.getRoot() }, this.$); var sortCacheId = query.sortCacheId(); if (!this.$sortCache[sortCacheId]) { this.$sortCache[sortCacheId] = this._createSortedCollection(query, options); } return this.$sortCache[sortCacheId]; } return this; }
javascript
{ "resource": "" }
q56306
train
function (pageIndex, options, callback) { if (pageIndex < 0) { throw "pageIndex must be >= 0"; } var page = this.$pageCache[pageIndex]; if (!page) { page = this.$pageCache[pageIndex] = new Page(null, this, pageIndex); } var self = this; options = _.extend(this.$, options); page.fetch(options, function (err, page) { // insert data into items if not already inserted if (!err && !page.itemsInsertedIntoCollection) { page.itemsInsertedIntoCollection = true; // add items to collection self.add(page.$items, { index: (pageIndex || 0) * self.$.pageSize }); } if (callback) { callback(err, page, options); } }); }
javascript
{ "resource": "" }
q56307
train
function (field) { var schemaDefinition = this.schema[field]; if (!schemaDefinition) { throw "Couldn't find '" + field + "' in schema"; } var collection = this.get(field); if (!collection) { var context = this.getContextForChild(schemaDefinition.type); if (context) { collection = context.createCollection(schemaDefinition.type, null); collection.$parent = this; this.set(field, collection); } else { throw "Couldn't determine context for " + field; } } return collection; }
javascript
{ "resource": "" }
q56308
train
function (action, options) { var ret = this.callBase(); if (action === "create" && ret.hasOwnProperty(this.idField) && [this.idField] === null) { delete ret[this.idField]; } return ret; }
javascript
{ "resource": "" }
q56309
train
function (options, callback) { if (arguments.length === 1 && options instanceof Function) { callback = options; options = null; } options = options || {}; var self = this; if (this._fetch.state === FETCHSTATE.LOADING) { // currently fetching -> register callback this._fetch.callbacks.push(function (err, model) { modelFetchedComplete(err, model, options, callback); }); } else if (this._fetch.state == FETCHSTATE.LOADED && !options.noCache) { // completed loaded -> execute modelFetchedComplete(null, this, options, callback); } else { // set state and start loading self._fetch.state = FETCHSTATE.LOADING; this.$context.$dataSource.loadModel(this, options, function (err, model) { self._fetch.state = err ? FETCHSTATE.ERROR : FETCHSTATE.LOADED; // execute callbacks modelFetchedComplete.call(self, err, model, options, callback); _.each(self._fetch.callbacks, function (cb) { cb.call(self, err, model); }); }); } }
javascript
{ "resource": "" }
q56310
train
function (identifier) { var idField = this.idField; if (this.schema.hasOwnProperty(idField)) { var schemaObject = this.schema[idField]; if (schemaObject.type && schemaObject.type === Number) { return parseInt(identifier); } } return identifier; }
javascript
{ "resource": "" }
q56311
train
function (items) { var c, j; if (this.$renderedItems) { for (j = this.$renderedItems.length - 1; j >= 0; j--) { c = this.$renderedItems[j]; this.$parent.removeChild(c.component); c.component.destroy(); } } if (this.$renderedItemsMap) { var itemList; for (var key in this.$renderedItemsMap) { if (this.$renderedItemsMap.hasOwnProperty(key)) { itemList = this.$renderedItemsMap[key]; for (j = itemList.length - 1; j >= 0; j--) { c = itemList[j]; this.$parent.removeChild(c.component); c.component.destroy(); } } } } this.$renderedItems = []; this.$renderedItemsMap = {}; this.$indexOffset = 0; if (items) { for (var i = 0; i < items.length; i++) { this._innerRenderItem(items[i], i); } } this.trigger("on:itemsRendered", {}, this); }
javascript
{ "resource": "" }
q56312
train
function (child, index) { var indexOffset = this._calculateIndexOffsetForChild(child); this.$parent.addChild(child, {childIndex: index + indexOffset}); }
javascript
{ "resource": "" }
q56313
train
function (item) { var key = this._getKeyForItem(item), list = this.$renderedItems; if (key) { list = this.$renderedItemsMap[key]; } if (list) { var ri; for (var i = 0; i < list.length; i++) { ri = list[i]; if (key || ri.item === item) { return ri.component; } } } return null; }
javascript
{ "resource": "" }
q56314
train
function (operator, field) { if (!this.query.where) { return null; } function findExpression(expressions) { var expression, ret = null; for (var i = 0; i < expressions.length; i++) { expression = expressions[i]; if (expression instanceof Where) { ret = findExpression(expression.expressions); } else if (expression instanceof Comparator) { if (expression.operator == operator && expression.field == field) { ret = expression; } } if (ret) { return ret; } } return ret; } return findExpression(this.query.where.expressions); }
javascript
{ "resource": "" }
q56315
train
function (event) { for (var i = 0; i < this.events.length; i++) { if (event === this.events[i]) { return true; } } return false; }
javascript
{ "resource": "" }
q56316
train
function (domNode) { if (domNode.localName) { return domNode.localName; } var localName = LocalNameCache[domNode.tagName]; if (localName) { return localName; } var st = domNode.tagName.split(":"); LocalNameCache[domNode.tagName] = st[st.length - 1]; return LocalNameCache[domNode.tagName]; }
javascript
{ "resource": "" }
q56317
train
function (entity, action, options) { var ret = {}, data = entity.compose(action, options), schemaDefinition, schemaType, isModel = entity instanceof Model, factory = entity.factory; for (var key in entity.schema) { if (entity.schema.hasOwnProperty(key) && (!isModel || (!options || !options.includeInIndex || _.contains(options.includeInIndex, key)))) { schemaDefinition = entity.schema[key]; schemaType = schemaDefinition.type; var value; if (data[key] && schemaDefinition.isReference && schemaType.classof && schemaType.classof(Entity) && !schemaType.classof(Model)) { value = {}; value[schemaType.prototype.idField] = data[key].identifier(); } else { value = this._getCompositionValue(data[key], key, action, options, entity); } if (value !== undefined) { ret[this._getReferenceKey(key, schemaType)] = value; } } } return ret; }
javascript
{ "resource": "" }
q56318
train
function(object, extra_helpers) { object = object || {}; this._extra_helpers = extra_helpers; var v = new EJS.Helpers(object, extra_helpers || {}); return this.template.process.call(object, object,v); }
javascript
{ "resource": "" }
q56319
train
function(options, data, helpers) { if (!helpers) helpers = this._extras; if (!data) data = this._data; return new EJS(options).render(data, helpers); }
javascript
{ "resource": "" }
q56320
train
function(input, null_text) { if (input == null || input === undefined) return null_text || ''; if (input instanceof(Date)) return input.toDateString(); if (input.toString) return input.toString().replace(/\n/g, '<br />').replace(/''/g, "'"); return ''; }
javascript
{ "resource": "" }
q56321
train
function (path) { var str = []; for (var i = 0; i < path.length; i++) { var el = path[i]; if (el.type === TYPE_VAR) { str.push(el.name); } else { return false; } } return str.join("."); }
javascript
{ "resource": "" }
q56322
train
function (event) { if (!this.$) { return; } for (var i = 0; i < this.$.fnc._attributes.length; i++) { if (event.$.hasOwnProperty(this.$.fnc._attributes[i])) { this._callback(); return; } } }
javascript
{ "resource": "" }
q56323
train
function () { // binding already destroyed? if (!this.$) { return; } var e; for (var j = 0; j < this.$events.length; j++) { e = this.$events[j]; this.$.scope.unbind(e.eventType, e.callback, this); } this.$.scope.unbind('destroy', this.destroy, this); if (this.$.twoWay === true) { this.$.target.unbind(this.$.targetEvent, this._revCallback, this); } if (this.$subBinding) { this.$subBinding.destroy(); this.$subBinding = null; } // destroy parameter bindings for (var i = 0; i < this.$parameters.length; i++) { var par = this.$parameters[i]; if (par instanceof Binding) { par.destroy(); } } this.$parameters = null; this.$.scope = this.$.target = this.$.callback = null; this.$ = null; this.$targets = null; this.callBase(); bindingsDestroyed++; if (bindingsDestroyed === 500) { if (typeof(CollectGarbage) === "function") { CollectGarbage(); } bindingsDestroyed = 0; } }
javascript
{ "resource": "" }
q56324
train
function () { var parameters = []; for (var i = 0; i < this.$parameters.length; i++) { var para = this.$parameters[i]; if (para instanceof Binding) { para = para.getValue(); } parameters.push(para); } return parameters; }
javascript
{ "resource": "" }
q56325
train
function () { if (this.$subBinding) { this.$subBinding.invalidateValueCache(); return this.$subBinding.getValue(); } else { if (this.$cachedValue !== undefined && !this.$jsonObject) { return this.$cachedValue; } this.$originalValue = undefined; if (this.$.fnc && !this.$jsonObject) { this.$originalValue = this.$.fnc.apply(this.$.scope, this._getFncParameters()); } else if (this.$.path.length === 1) { this.$originalValue = this.$.scope.get(this.$.key.name); } else if (this.$jsonObject && !_.isString(this.$jsonObject)) { this.$originalValue = this.$.scope.get(this.$jsonObject, this.$.path.slice(1)); } else { this.$originalValue = this.$.scope.get(this.$.path); } this.$cachedValue = this.transform.call(this.transformScope, this.$originalValue); return this.$cachedValue; } }
javascript
{ "resource": "" }
q56326
train
function () { // get value var val = this.getContextValue(); var target, targets = this.$.root.getTargets(); if (targets) { for (var i = 0; i < targets.length; i++) { target = targets[i]; if (target.key instanceof Function) { target.key.call(target.scope, val, this); } else { target.scope.set(target.key, val); } } } }
javascript
{ "resource": "" }
q56327
train
function () { if (this._$source) { var val, attributes = {}, unsetAttributes = {}; for (var key in this.$) { if (this.$.hasOwnProperty(key)) { val = this.$[key]; if (val instanceof Bindable && val.sync()) { attributes[key] = val._$source; } else { attributes[key] = val; } } } // remove all attributes, which are not in clone for (var sourceKey in this._$source.$) { if (this._$source.$.hasOwnProperty(sourceKey)) { if (!attributes.hasOwnProperty(sourceKey)) { unsetAttributes[sourceKey] = ""; } } } this._$source.set(unsetAttributes, {unset: true}); this._$source.set(attributes); return true; } else { return false; } }
javascript
{ "resource": "" }
q56328
train
function (attribute, key) { if (this.inject && this.inject.hasOwnProperty(key)) { return attribute; } else if (attribute instanceof Bindable) { return attribute.clone(); } else if (attribute && (attribute.clone instanceof Function)) { return attribute.clone(); } else if (_.isArray(attribute)) { var retArray = []; for (var i = 0; i < attribute.length; i++) { retArray.push(this._cloneAttribute(attribute[i])); } return retArray; } else if (attribute instanceof Date) { return new Date(attribute.getTime()); } else if (_.isObject(attribute)) { var retObject = {}; for (var attrKey in attribute) { if (attribute.hasOwnProperty(attrKey)) { retObject[attrKey] = this._cloneAttribute(attribute[attrKey], attrKey); } } return retObject; } else { return attribute; } }
javascript
{ "resource": "" }
q56329
train
function (key, value, options) { if (_.isNumber(key)) { key = String(key); } if (_.isString(key)) { var attributes = {}; attributes[key] = value; } else { options = value; attributes = key; } options = options || {silent: false, unset: false, force: false}; // for un-setting attributes if (options.unset) { for (key in attributes) { if (attributes.hasOwnProperty(key)) { attributes[key] = void 0; } } } var changedAttributes = {}, changedAttributesCount = 0, now = this.$, val, prev; for (key in attributes) { if (attributes.hasOwnProperty(key)) { // get the value val = attributes[key]; // unset attribute or change it ... if (options.unset === true) { prev = now[key]; delete now[key]; changedAttributes[key] = undefined; changedAttributesCount++; this.$previousAttributes[key] = prev; } else { if (options.force || !isEqual(now[key], attributes[key])) { prev = options.initial ? null : now[key]; this.$previousAttributes[key] = prev; now[key] = attributes[key]; changedAttributes[key] = now[key]; changedAttributesCount++; } } } } var commitMethod; if (changedAttributesCount) { for (key in changedAttributes) { if (changedAttributes.hasOwnProperty(key)) { commitMethod = this['_commit' + key.charAt(0).toUpperCase() + key.substr(1)]; if (commitMethod instanceof Function) { // call method if (commitMethod.call(this, now[key], this.$previousAttributes[key], options) === false) { // false returned rollback changedAttributesCount--; now[key] = this.$previousAttributes[key]; } } } } if (changedAttributesCount) { this._commitChangedAttributes(changedAttributes, options); if (!options.silent) { for (key in changedAttributes) { if (changedAttributes.hasOwnProperty(key)) { this.trigger('change:' + key, changedAttributes[key], this); } } this.trigger('change', changedAttributes, this); } } } return this; }
javascript
{ "resource": "" }
q56330
train
function (authenticationRequest) { var authenticationProviders = this.$providers, provider; for (var i = 0; i < authenticationProviders.length; i++) { provider = authenticationProviders[i]; if (provider.isResponsibleForAuthenticationRequest(authenticationRequest)) { return provider; } } return null; }
javascript
{ "resource": "" }
q56331
train
function (context, token, callback) { var authentication = this.$.dataSource.createEntity(Authentication, token), self = this; // setup authentication this.$stage.$bus.setUp(authentication); flow() .seq("authentication", function (cb) { authentication.fetch({noCache: true}, function (err) { if (!err) { var now = new Date(); if (authentication.$.updated.getTime() < now.getTime() - (1000 * self.$.tokenLifeTime)) { // remove token authentication.remove(); // return error err = AuthenticationError.AUTHENTICATION_EXPIRED; } } else { // TODO: change to authentication not found err = AuthenticationError.AUTHENTICATION_EXPIRED; } cb(err, authentication); }); }) .seq(function (cb) { this.vars.authentication.set('updated', new Date()); this.vars.authentication.save(null, cb); }) .seq(function (cb) { // init authentication this.vars.authentication.init(cb); }) .exec(function (err, results) { authentication = results.authentication; if (!err && authentication) { context.user.addAuthentication(authentication); } callback && callback(err, authentication); }); }
javascript
{ "resource": "" }
q56332
train
function (authentication, callback) { /*** * Let's save the authentication and so the user is logged in * */ var token = generateId(); var authenticationInstance = this.$.dataSource.createEntity(Authentication, token); authenticationInstance.set(authentication.$); authenticationInstance.save(null, callback); }
javascript
{ "resource": "" }
q56333
train
function (context, callback, checkParents) { if (this.$parentResource) { var self = this; flow() .seq("parentCollection", function (cb) { self.$parentResource._findCollection(context, cb); }) .seq("parent", function (cb) { var parentCollection = this.vars.parentCollection, id = parentCollection.$modelFactory.prototype.convertIdentifier(self.$parentResource.$resourceId), parent = parentCollection.createItem(id); if (checkParents) { parent.fetch(null, cb); } else { cb(null, parent); } }) .exec(function (err, results) { if (!err) { var collection = results.parent.getCollection(self.$resourceConfiguration.$.path); callback && callback(null, collection); } else { callback && callback(err); } }); } else { var dataSource = this.$restHandler.getDataSource(context, this); callback && callback(null, dataSource.createCollection(Collection.of(this._getModelFactory()), {pageSize: 100})); } }
javascript
{ "resource": "" }
q56334
train
function () { if (this.$processUrl) { var currentFragment = this._getFragment(); if (currentFragment == this.$fragment) { return false; } this.navigate(currentFragment, !this.$.useState, true, true, emptyCallback); } this.$processUrl = true; }
javascript
{ "resource": "" }
q56335
train
function (fragment, callback) { var routeExecutionStack = []; for (var i = 0; i < this.$routers.length; i++) { routeExecutionStack = routeExecutionStack.concat(this.$routers[i].generateRoutingStack(fragment)); } if (routeExecutionStack.length === 0) { this.routeNotFound(fragment, callback); } else { flow() .seqEach(routeExecutionStack, function(routingFunction, cb){ routingFunction(cb); }) .exec(callback); } }
javascript
{ "resource": "" }
q56336
getPlugins
train
function getPlugins(){ var plugins = $p.plugins, f = function(){}; f.prototype = plugins; // do not overwrite functions if external definition f.prototype.compile = plugins.compile || compile; f.prototype.render = plugins.render || render; f.prototype.autoRender = plugins.autoRender || autoRender; f.prototype.find = plugins.find || find; // give the compiler and the error handling to the plugin context f.prototype._compiler = compiler; f.prototype._error = error; return new f(); }
javascript
{ "resource": "" }
q56337
wrapquote
train
function wrapquote(qfn, f){ return function(ctxt){ return qfn('' + f.call(ctxt.context, ctxt)); }; }
javascript
{ "resource": "" }
q56338
find
train
function find(n, sel){ if(typeof n === 'string'){ sel = n; n = false; } if(typeof document.querySelectorAll !== 'undefined'){ return (n||document).querySelectorAll( sel ); }else{ error('You can test PURE standalone with: iPhone, FF3.5+, Safari4+ and IE8+\n\nTo run PURE on your browser, you need a JS library/framework with a CSS selector engine'); } }
javascript
{ "resource": "" }
q56339
parseloopspec
train
function parseloopspec(p){ var m = p.match( /^(\w+)\s*<-\s*(\S+)?$/ ); if(m === null){ error('bad loop spec: "' + p + '"'); } if(m[1] === 'item'){ error('"item<-..." is a reserved word for the current running iteration.\n\nPlease choose another name for your loop.'); } if( !m[2] || (m[2] && (/context/i).test(m[2]))){ //undefined or space(IE) m[2] = function(ctxt){return ctxt.context;}; } return {name: m[1], sel: m[2]}; }
javascript
{ "resource": "" }
q56340
loopfn
train
function loopfn(name, dselect, inner, sorter, filter){ return function(ctxt){ var a = dselect(ctxt), old = ctxt[name], temp = { items : a }, filtered = 0, length, strs = [], buildArg = function(idx, temp, ftr, len){ ctxt.pos = temp.pos = idx; ctxt.item = temp.item = a[ idx ]; ctxt.items = a; //if array, set a length property - filtered items typeof len !== 'undefined' && (ctxt.length = len); //if filter directive if(typeof ftr === 'function' && ftr(ctxt) === false){ filtered++; return; } strs.push( inner.call(temp, ctxt ) ); }; ctxt[name] = temp; if( isArray(a) ){ length = a.length || 0; // if sort directive if(typeof sorter === 'function'){ a.sort(sorter); } //loop on array for(var i = 0, ii = length; i < ii; i++){ buildArg(i, temp, filter, length - filtered); } }else{ if(a && typeof sorter !== 'undefined'){ error('sort is only available on arrays, not objects'); } //loop on collections for(var prop in a){ a.hasOwnProperty( prop ) && buildArg(prop, temp, filter); } } typeof old !== 'undefined' ? ctxt[name] = old : delete ctxt[name]; return strs.join(''); }; }
javascript
{ "resource": "" }
q56341
loopgen
train
function loopgen(dom, sel, loop, fns){ var already = false, ls, sorter, filter, prop; for(prop in loop){ if(loop.hasOwnProperty(prop)){ if(prop === 'sort'){ sorter = loop.sort; continue; }else if(prop === 'filter'){ filter = loop.filter; continue; } if(already){ error('cannot have more than one loop on a target'); } ls = prop; already = true; } } if(!ls){ error('Error in the selector: ' + sel + '\nA directive action must be a string, a function or a loop(<-)'); } var dsel = loop[ls]; // if it's a simple data selector then we default to contents, not replacement. if(typeof(dsel) === 'string' || typeof(dsel) === 'function'){ loop = {}; loop[ls] = {root: dsel}; return loopgen(dom, sel, loop, fns); } var spec = parseloopspec(ls), itersel = dataselectfn(spec.sel), target = gettarget(dom, sel, true), nodes = target.nodes; for(i = 0; i < nodes.length; i++){ var node = nodes[i], inner = compiler(node, dsel); fns[fns.length] = wrapquote(target.quotefn, loopfn(spec.name, itersel, inner, sorter, filter)); target.nodes = [node]; // N.B. side effect on target. setsig(target, fns.length - 1); } }
javascript
{ "resource": "" }
q56342
compiler
train
function compiler(dom, directive, data, ans){ var fns = []; // autoRendering nodes parsing -> auto-nodes ans = ans || data && getAutoNodes(dom, data); if(data){ var j, jj, cspec, n, target, nodes, itersel, node, inner; // for each auto-nodes while(ans.length > 0){ cspec = ans[0].cspec; n = ans[0].n; ans.splice(0, 1); if(cspec.t === 'str'){ // if the target is a value target = gettarget(n, cspec, false); setsig(target, fns.length); fns[fns.length] = wrapquote(target.quotefn, dataselectfn(cspec.prop)); }else{ // if the target is a loop itersel = dataselectfn(cspec.sel); target = gettarget(n, cspec, true); nodes = target.nodes; for(j = 0, jj = nodes.length; j < jj; j++){ node = nodes[j]; inner = compiler(node, false, data, ans); fns[fns.length] = wrapquote(target.quotefn, loopfn(cspec.sel, itersel, inner)); target.nodes = [node]; setsig(target, fns.length - 1); } } } } // read directives var target, dsel; for(var sel in directive){ if(directive.hasOwnProperty(sel)){ dsel = directive[sel]; if(typeof(dsel) === 'function' || typeof(dsel) === 'string'){ // set the value for the node/attr target = gettarget(dom, sel, false); setsig(target, fns.length); fns[fns.length] = wrapquote(target.quotefn, dataselectfn(dsel)); }else{ // loop on node loopgen(dom, sel, dsel, fns); } } } // convert node to a string var h = outerHTML(dom), pfns = []; // IE adds an unremovable "selected, value" attribute // hard replace while waiting for a better solution h = h.replace(/<([^>]+)\s(value\=""|selected)\s?([^>]*)>/ig, "<$1 $3>"); // remove attribute prefix h = h.split(attPfx).join(''); // slice the html string at "Sig" var parts = h.split( Sig ), p; // for each slice add the return string of for(var i = 1; i < parts.length; i++){ p = parts[i]; // part is of the form "fn-number:..." as placed there by setsig. pfns[i] = fns[ parseInt(p, 10) ]; parts[i] = p.substring( p.indexOf(':') + 1 ); } return concatenator(parts, pfns); }
javascript
{ "resource": "" }
q56343
compile
train
function compile(directive, ctxt, template){ var rfn = compiler( ( template || this[0] ).cloneNode(true), directive, ctxt); return function(context){ return rfn({context:context}); }; }
javascript
{ "resource": "" }
q56344
render
train
function render(ctxt, directive){ var fn = typeof directive === 'function' ? directive : plugins.compile( directive, false, this[0] ); for(var i = 0, ii = this.length; i < ii; i++){ this[i] = replaceWith( this[i], fn( ctxt, false )); } context = null; return this; }
javascript
{ "resource": "" }
q56345
convert
train
function convert(source) { let currentKey = "", currentValue = "", objectNames = [], output = {}, parentObj = {}, lines = source.split(NEW_LINE), splitAt; let currentObj = output; let parents = []; for (let i = 0; i < lines.length; i++) { let line = lines[i]; if (line.charAt(0) === " ") { currentObj[currentKey] += line.substr(1); } else { splitAt = line.indexOf(":"); if (splitAt < 0) { continue; } currentKey = line.substr(0, splitAt); currentValue = line.substr(splitAt + 1); switch (currentKey) { case "BEGIN": parents.push(parentObj); parentObj = currentObj; if (parentObj[currentValue] == null) { parentObj[currentValue] = []; } // Create a new object, store the reference for future uses currentObj = {}; parentObj[currentValue].push(currentObj); break; case "END": currentObj = parentObj; parentObj = parents.pop(); break; default: if(currentObj[currentKey]) { if(!Array.isArray(currentObj[currentKey])) { currentObj[currentKey] = [currentObj[currentKey]]; } currentObj[currentKey].push(currentValue); } else { currentObj[currentKey] = currentValue; } } } } return output; }
javascript
{ "resource": "" }
q56346
revert
train
function revert(object) { let lines = []; for (let key in object) { let value = object[key]; if (Array.isArray(value)) { value.forEach((item) => { lines.push(`BEGIN:${key}`); lines.push(revert(item)); lines.push(`END:${key}`); }); } else { let fullLine = `${key}:${value}`; do { // According to ical spec, lines of text should be no longer // than 75 octets lines.push(fullLine.substr(0, 75)); fullLine = ' ' + fullLine.substr(75); } while (fullLine.length > 1); } } return lines.join('\n'); }
javascript
{ "resource": "" }
q56347
run
train
function run(options) { let files, filePromises = []; files = options.args || []; for (let i = 0; i < files.length; i++) { let file = files[i]; let filePath = path.resolve(cwd, file); if (!fs.existsSync(filePath)) { continue; } let stat = fs.statSync(filePath); let ext = path.extname(filePath); let isConvert = !options.revert && ext === '.ics' let isRevert = options.revert && ext === '.json' if (!stat.isFile() || (!isConvert && !isRevert)) { continue; } filePromises.push(Q.nfcall(fs.readFile, filePath) .then((buffer) => { let output; let data = buffer.toString(); if (isConvert) { output = convert(data); output = JSON.stringify(output, null, " "); } else if (isRevert) { output = revert(data); } let basename = path.basename(filePath, ext); let dirname = path.dirname(filePath); let compiledExt = isConvert ? '.json' : '.ics'; let writePath = path.join(dirname, basename) + compiledExt; return Q.nfcall(fs.writeFile, writePath, output); }) .fail((error) => { throw new Error(error); })); } return Q.all(filePromises); }
javascript
{ "resource": "" }
q56348
train
function () { if (this.factory.schema) { this.schema = this.factory.schema; return; } var base = this.base; while (base.factory.classof(Entity)) { var baseSchema = base.schema; for (var type in baseSchema) { if (baseSchema.hasOwnProperty(type) && !this.schema.hasOwnProperty(type)) { this.schema[type] = baseSchema[type]; } } base = base.base; } var schemaDefaults = { required: true, includeInIndex: false, serverOnly: false, _rewritten: true, // if true, sub models get composed and not just linked compose: false }, schemaObject; // add id schema if (this.idField && !this.schema.hasOwnProperty(this.idField)) { this.schema[this.idField] = { type: String, required: false, serverOnly: false, includeInIndex: true, generated: true }; } if (this.updatedField && !this.schema.hasOwnProperty(this.updatedField)) { this.schema[this.updatedField] = { type: Date, required: false, serverOnly: false, includeInIndex: true, generated: true }; } if (this.createdField && !this.schema.hasOwnProperty(this.createdField)) { this.schema[this.createdField] = { type: Date, required: false, includeInIndex: true, serverOnly: false, generated: true }; } // rewrite schema for (var key in this.schema) { if (this.schema.hasOwnProperty(key)) { schemaObject = this.schema[key]; if (_.isString(schemaObject) || schemaObject instanceof Array || schemaObject instanceof Function) { schemaObject = { type: schemaObject }; this.schema[key] = schemaObject; } if (_.isString(schemaObject.type)) { schemaObject.type = require(schemaObject.type.replace(/\./g, "/")); } _.defaults(schemaObject, schemaDefaults); schemaObject._key = key; } } this.factory.schema = this.schema; }
javascript
{ "resource": "" }
q56349
train
function (key, scope) { var value = this.get(key, scope); if (key && this.schema[key]) { for (var i = 0; i < this.transformers.length; i++) { value = this.transformers[i].transformValue(key, value, this.schema[key]); } } return value; }
javascript
{ "resource": "" }
q56350
train
function (options) { var ret = {}; for (var k in this.schema) { if (this.schema.hasOwnProperty(k)) { ret[k] = this.getTransformedValue(k); } } this.set(ret, options); }
javascript
{ "resource": "" }
q56351
train
function (entity, options, callback) { if (entity instanceof Entity) { entity.validate(options, callback); } else { callback("parameter is not an entity"); } }
javascript
{ "resource": "" }
q56352
train
function(keypath, content, attributes) { var attrs = {'for': this._attributesForKeyPath(keypath).name}; return simple_element('label', $.extend(attrs, attributes), content); }
javascript
{ "resource": "" }
q56353
train
function(keypath, attributes) { attributes = $.extend({type: 'hidden'}, this._attributesForKeyPath(keypath), attributes); return simple_element('input', attributes); }
javascript
{ "resource": "" }
q56354
train
function(keypath, attributes) { var current; attributes = $.extend(this._attributesForKeyPath(keypath), attributes); current = attributes.value; delete attributes['value']; return simple_element('textarea', attributes, current); }
javascript
{ "resource": "" }
q56355
train
function(keypath, value, attributes) { var selected; attributes = $.extend(this._attributesForKeyPath(keypath), attributes); selected = attributes.value; attributes.value = getStringContent(this.object, value); if (selected == attributes.value) { attributes.checked = 'checked'; } return simple_element('input', $.extend({type:'radio'}, attributes)); }
javascript
{ "resource": "" }
q56356
train
function (items, options) { options = options || {}; _.defaults(options, {silent: false, index: this.$items.length}); var index = options.index; if (!_.isArray(items)) { items = [items]; } var item, itemIndex; for (var i = 0; i < items.length; i++) { item = items[i]; if (item instanceof Bindable) { item.bind('change', this._onItemChange, this); item.bind('*', this._onItemEvent, this); } itemIndex = index + i; if (_.isUndefined(this.$items[itemIndex]) || itemIndex >= this.$items.length) { this.$items[itemIndex] = item; } else { this.$items.splice(itemIndex, 0, item); } if (options.silent !== true) { this.trigger('add', {item: item, index: itemIndex}); } } }
javascript
{ "resource": "" }
q56357
train
function (items, options) { var removed = []; if (!_.isArray(items)) { items = [items]; } var item; for (var i = 0; i < items.length; i++) { item = this.removeAt(this.indexOf(items[i]), options); item && removed.push(item); } return removed; }
javascript
{ "resource": "" }
q56358
train
function (index, options) { options = options || {}; if (index > -1 && index < this.$items.length) { var items = this.$items.splice(index, 1), item = items[0]; if (options.silent !== true) { this.trigger('remove', {item: item, index: index}); } if (item instanceof Bindable) { item.unbind('*', this._onItemEvent, this); item.unbind('change', this._onItemChange, this); } return items[0]; } return null; }
javascript
{ "resource": "" }
q56359
train
function (items, options) { items = items || []; var self = this; this.each(function (item) { if (item instanceof EventDispatcher) { item.unbind('*', self._onItemEvent, self); item.unbind('change', self._onItemChange, self); } }); this.$items = items || []; this.each(function (item) { if (item instanceof EventDispatcher) { item.bind('*', self._onItemEvent, self); item.bind('change', self._onItemChange, self); } }); options = options || {}; if (!options.silent) { this.trigger('reset', {items: items}); } }
javascript
{ "resource": "" }
q56360
train
function (fnc, scope) { scope = scope || this; for (var i = 0; i < this.$items.length; i++) { fnc.call(scope, this.$items[i], i, this.$items); } }
javascript
{ "resource": "" }
q56361
train
function (fnc, scope) { scope = scope || this; var b = false, items = this.$items, length = items.length; for (var i = 0; i < length; i++) { b = fnc.call(scope, items[i], i, this.$items); if (b === true) { break; } } return i < length ? items[i] : null; }
javascript
{ "resource": "" }
q56362
train
function () { var attributes = this._cloneAttribute(this.$); var items = this._cloneAttribute(this.$items); var ret = new this.factory(items, attributes); ret._$source = this; return ret; }
javascript
{ "resource": "" }
q56363
train
function () { if (this._$source) { var item, items = []; for (var i = 0; i < this.$items.length; i++) { item = this.$items[i]; if (item instanceof Bindable && item.sync()) { item = item._$source; } items.push(item); } this._$source.reset(items); } return this.callBase(); }
javascript
{ "resource": "" }
q56364
train
function (list) { if (list.size() !== this.size()) { return false; } var isEqual = true, a, b; for (var i = 0; i < this.$items.length; i++) { a = this.$items[i]; b = list.at(i); if (a instanceof Bindable && b instanceof Bindable) { if (!a.isDeepEqual(b)) { return false; } } else if (a instanceof Bindable || b instanceof Bindable) { return false; } else { isEqual = _.isEqual(a, b); } } return isEqual; }
javascript
{ "resource": "" }
q56365
train
function (moduleName, moduleInstance, callback, routeContext, cachedInstance) { var self = this; //noinspection JSValidateTypes flow() .seq(function (cb) { self.$moduleInstance = moduleInstance; var currentModule = self.$.currentModule; if (currentModule) { currentModule._unload(cb); } else { cb(); } }) .seq(function (cb) { // start module moduleInstance.start(function (err) { if (err || cachedInstance) { cb(err); } else { if (routeContext) { // fresh instance with maybe new routers -> exec routes for new router var routeExecutionStack = []; for (var i = 0; i < moduleInstance.$routers.length; i++) { var router = moduleInstance.$routers[i]; router.set("module", moduleInstance); routeExecutionStack = routeExecutionStack.concat(router.generateRoutingStack(routeContext.fragment)); } flow() .seqEach(routeExecutionStack, function (routingFunction, cb) { routingFunction(cb); }) .exec(cb); } else { cb(); } } }, routeContext); }) .seq(function () { if (moduleInstance === self.$moduleInstance) { self._clearContentPlaceHolders(); self.set('currentModuleName', moduleName); var contentPlaceHolders = self.getContentPlaceHolders("external"); // set content for (var i = 0; i < contentPlaceHolders.length; i++) { var contentPlaceHolder = contentPlaceHolders[i]; contentPlaceHolder.set("content", moduleInstance.findContent(contentPlaceHolder.$.name)); } } }) .exec(function (err) { var moduleInstance = self.$moduleInstance; self.set({ state: err ? 'error' : null, currentModule: moduleInstance }); self.$moduleInstance = null; if (callback) { callback(err, moduleInstance); } }); }
javascript
{ "resource": "" }
q56366
train
function (templateName, target, attributes, options) { if (!this.$container) { this.$container = this.createComponent(HtmlElement, {"class": this.$.containerClass, "tagName": "div"}); this.$stage.addChild(this.$container); } var tooltip = this.getTooltipByNameAndTarget(templateName, target); if (tooltip) { return tooltip; } else { options = options || {}; if (target && target.isRendered()) { var content = options.content, animationClass = this.$.animationClass || options.animationClass, duration = this.$.duration || options.duration; var rect = target.$el.getBoundingClientRect(); // create a instance tooltip = this.createComponent(Tooltip, { manager: this, "class": templateName, animationClass: animationClass, left: rect.left, top: rect.top, width: rect.width, height: 0 // due to missing pointer event support in IE } ); var templateInstance = this.$templates[templateName].createInstance(attributes || {}); templateInstance.$classAttributes = templateInstance.$classAttributes || []; // add class attributes for (var key in attributes) { if (attributes.hasOwnProperty(key)) { templateInstance.$classAttributes.push(key); } } // add template instance tooltip.addChild(templateInstance); tooltip.bind('dom:remove', function () { tooltip.destroy(); }); // if content if (content) { templateInstance.$children = content.getChildren(); templateInstance._renderChildren(templateInstance.$children); } this.$tooltips.push({ target: target, templateName: templateName, instance: tooltip }); this.$container.addChild(tooltip); var self = this; if (duration && duration > 0) { setTimeout(function () { self.hideTooltip(tooltip); }, duration) } return tooltip; } else { throw new Error("No target for tooltip specified"); } } }
javascript
{ "resource": "" }
q56367
train
function (tooltip, target) { if (!(tooltip instanceof Tooltip)) { tooltip = this.getTooltipByNameAndTarget(tooltip, target); } if (tooltip) { var i = this.$tooltips.indexOf(tooltip); this.$tooltips.splice(i, 1); this.$container.removeChild(tooltip); } }
javascript
{ "resource": "" }
q56368
train
function (templateName, target) { var tooltip; for (var i = 0; i < this.$tooltips.length; i++) { tooltip = this.$tooltips[i]; if (tooltip.templateName === templateName && tooltip.target === target) { return tooltip.instance; } } return null; }
javascript
{ "resource": "" }
q56369
train
function (xhr) { this.xhr = xhr; this.status = xhr.status; this.$nativeResponseHeaders = xhr.getAllResponseHeaders(); this.responses = {}; var xml = xhr.responseXML; // Construct response list if (xml && xml.documentElement) { this.responses.xml = xml; } this.responses.text = xhr.responseText; try { this.statusText = xhr.statusText; } catch (e) { this.statusText = ""; } }
javascript
{ "resource": "" }
q56370
parse_attribs
train
function parse_attribs(line) { var attributes = {}, l = line.length, i, c, count = 1, quote = false, skip = false, open, close, joiner, seperator, pair = { start: 1, middle: null, end: null }; if (!(l > 0 && (line.charAt(0) === '{' || line.charAt(0) === '('))) { return { content: line[0] === ' ' ? line.substr(1, l) : line }; } open = line.charAt(0); close = (open === '{') ? '}' : ')'; joiner = (open === '{') ? ':' : '='; seperator = (open === '{') ? ',' : ' '; function process_pair() { if (typeof pair.start === 'number' && typeof pair.middle === 'number' && typeof pair.end === 'number') { var key = line.substr(pair.start, pair.middle - pair.start).trim(), value = line.substr(pair.middle + 1, pair.end - pair.middle - 1).trim(); attributes[key] = value; } pair = { start: null, middle: null, end: null }; } for (i = 1; count > 0; i += 1) { // If we reach the end of the line, then there is a problem if (i > l) { throw "Malformed attribute block"; } c = line.charAt(i); if (skip) { skip = false; } else { if (quote) { if (c === '\\') { skip = true; } if (c === quote) { quote = false; } } else { if (c === '"' || c === "'") { quote = c; } if (count === 1) { if (c === joiner) { pair.middle = i; } if (c === seperator || c === close) { pair.end = i; process_pair(); if (c === seperator) { pair.start = i + 1; } } } if (c === open) { count += 1; } if (c === close) { count -= 1; } } } } attributes.content = line.substr(i, line.length); return attributes; }
javascript
{ "resource": "" }
q56371
parse_interpol
train
function parse_interpol(value) { var items = [], pos = 0, next = 0, match; while (true) { // Match up to embedded string next = value.substr(pos).search(embedder); if (next < 0) { if (pos < value.length) { items.push(JSON.stringify(value.substr(pos))); } break; } items.push(JSON.stringify(value.substr(pos, next))); pos += next; // Match embedded string match = value.substr(pos).match(embedder); next = match[0].length; if (next < 0) { break; } items.push(match[1] || match[2]); pos += next; } return items.filter(function (part) { return part && part.length > 0}).join(" +\n"); }
javascript
{ "resource": "" }
q56372
loadFiles
train
function loadFiles(dir, options) { var listings = fs.readdirSync(dir) , options = options || {} , obj = {}; listings.forEach(function (listing) { var file = path.join(dir, listing) , prop = listing.split('.')[0] // probably want regexp or something more robust , stat = fs.statSync(file); if (stat.isFile()) { var content = fs.readFileSync(file).toString(); if (options.operators) { options.operators.forEach(function (op) { content = op(content, options); }); } obj[prop] = content; } else if (stat.isDirectory()) { obj[listing] = loadFiles(file, options); } }); return obj; }
javascript
{ "resource": "" }
q56373
train
function () { if (arguments.length === 0) { grunt.warn(strings[options.locale]['translate.param.missing']); } var key = arguments[0]; if (!(key in strings[options.locale])) { grunt.warn(strings[options.locale]['string.key.missing'] + ': ' + key); } var string = strings[options.locale][key]; for (var i = 1; i < arguments.length; i++) { var replacementKey = '%' + i; string = string.replace(replacementKey, arguments[i]); } return string; }
javascript
{ "resource": "" }
q56374
train
function (params) { var message = translate(errors[params.caseNum]) .replace('%n', (params.lineNum + 1).toString()) .replace('%p', params.pattern) .replace('%x', params.start) .replace('%y', (params.endLineNum + 1).toString()) .replace('%f', currentFile); if (options.testMode === true) { grunt.log.writeln(message); } else { grunt.warn(message); } }
javascript
{ "resource": "" }
q56375
train
function (line, lineNum) { if (line.trim() === '') { return; } function logAnyDelimiterType(line) { blocks.forEach(function (blockDef, blockIdx) { if (blockDef.start.test(line) === true) { fileStartDelimiters.push([blockIdx, lineNum, line.trim()]); } if (blockDef.end.test(line) === true) { fileEndDelimiters.push([blockIdx, lineNum, line.trim()]); } }); } logAnyDelimiterType(line); var startCount = fileStartDelimiters.length; var endCount = fileEndDelimiters.length; /** * Checks that amount of start/end blocks are equal. * * @param blockDef * @param blockIdx */ var checkBlocksParity = function (blockDef, blockIdx) { var block = blockStats[blockIdx]; /** * 'if' for start block check */ if (blockDef.start.test(line) === true) { block.lastStartLine = lineNum; if (block.startCount > block.endCount) { generateMessage({ pattern: line.trim(), lineNum: block.lastStartLine, caseNum: 1 }); } block.startCount++; } /** * 'if' for end block check */ if (blockDef.end.test(line) === true) { block.lastEndLine = lineNum; if (block.endCount >= block.startCount) { generateMessage({ pattern: line.trim(), lineNum: block.lastEndLine, caseNum: 2 }); } block.endCount++; } }; /** * Checks if any two (or more) pairs of start/end * blocks are intersecting. * * @param blockDef * @param blockIdx */ var checkBlocksIntersection = function (blockDef, blockIdx) { if (blockDef.start.test(line)) { blocksStack.push([blockIdx, lineNum, line.trim()]); } if (blockDef.end.test(line) && typeof last(blocksStack) !== "undefined") { if (last(blocksStack)[0] === blockIdx) { blocksStack.pop(); } else { generateMessage({ start: last(blocksStack)[2], pattern: line.trim(), lineNum: last(blocksStack)[1], endLineNum: lineNum, caseNum: 3 }); } } else if (startCount - endCount > 1) { generateMessage({ start: last(blocksStack)[2], pattern: line.trim(), lineNum: last(blocksStack)[1], endLineNum: lineNum, caseNum: 3 }); } }; if (options.parityCheck === true) { blocks.forEach(checkBlocksParity); } if (options.intersectionCheck === true) { blocks.forEach(checkBlocksIntersection); } }
javascript
{ "resource": "" }
q56376
train
function(cb) { fs.exists(potterHome, function(exists) { if(exists) { cb(null); } else { mkdirp(potterHome, cb); } }); }
javascript
{ "resource": "" }
q56377
train
function(cb) { fs.exists(path.join(potterHome, 'package.json'), function(exists) { if(exists) { cb(null); } else { var packagejson = '{"dependencies":{}}'; fs.writeFile(path.join(potterHome, 'package.json'), packagejson, cb); } }); }
javascript
{ "resource": "" }
q56378
mapDefinitionsFromModel
train
function mapDefinitionsFromModel(model) { const definitionMap = []; /* istanbul ignore else */ if (model && model.definitions) { debug('Parsing %s definitions', Object.keys(model.definitions).length); for (const definitionName of Object.keys(model.definitions)) { debug(' Reading definition for %s', definitionName); const definitionKey = util.format('#/definitions/%s', definitionName); const currentDef = model.definitions[definitionName]; currentDef.definitionName = definitionName; currentDef.referencePath = definitionKey; definitionMap[definitionKey] = currentDef; } } return definitionMap; }
javascript
{ "resource": "" }
q56379
handleGet
train
function handleGet(req, res, sails, params){ validateToken(req, res, sails, params); }
javascript
{ "resource": "" }
q56380
handlePost
train
function handlePost(req, res, sails, params){ var func; if(!_.isUndefined(params.email)){ func = sendEmail; }else if(!_.isUndefined(req.session.resetToken) && req.session.resetToken && !_.isUndefined(params.password)){ func = issuePasswordReset; } if(!_.isUndefined(func)){ func(req, res, sails, params); }else{ res.status(404).json(404); } }
javascript
{ "resource": "" }
q56381
sendEmail
train
function sendEmail(req, res, sails, params){ sails.models.auth.findOne({email: params.email}).populate('user').exec(function(err, a){ if(a){ sails.models.resettoken.create({owner: a.id}).exec(function(err, t){ if(err){ return res.serverError(err); } sails.models.auth.update({id: a.id}, {resetToken: t.id}).exec(function(err){ if(err){ return res.serverError(err); } res.json(200); }); }); } else { return res.forbidden('Email not found'); } }); }
javascript
{ "resource": "" }
q56382
validateToken
train
function validateToken(req, res, sails, params){ var config = wl.config; var authConfig = wl.authConfig; if(params.token){ try{ // decode the token var _token = jwt.decode(params.token, config.jsonWebTokens.secret); // set the time of the request var _reqTime = Date.now(); // If token is expired if(_token.exp <= _reqTime){ return res.forbidden('Your token is expired.'); } // If token is early if(_reqTime <= _token.nbf){ return res.forbidden('This token is early.'); } // If audience doesn't match if(config.jsonWebTokens.audience !== _token.aud){ return res.forbidden('This token cannot be accepted for this domain.'); } // If the subject doesn't match if('password reset' !== _token.sub){ return res.forbidden('This token cannot be used for this request.'); } sails.models.auth.findOne(_token.iss).populate('resetToken').exec(function(err, auth){ if(typeof auth.resetToken === 'undefined' || params.token !== auth.resetToken.token){ return res.forbidden('This token cannot be used.'); } req.session.resetToken = auth.resetToken; if(authConfig.passwordReset.mail.forwardUrl){ res.redirect(authConfig.passwordReset.mail.forwardUrl + '?token=' + auth.resetToken.token); }else{ res.json(200); } }); } catch(err){ return res.serverError(err); } }else{ //TODO limit attempts? req.session.resetToken = false; res.forbidden(); } }
javascript
{ "resource": "" }
q56383
isMemberCall
train
function isMemberCall({ callee }, obj, prop) { return callee.type === 'MemberExpression' && callee.object.name === obj && callee.property.name === prop; }
javascript
{ "resource": "" }
q56384
train
function () { var list = slice.call(this.indexes || []); var i = 0; list.push(this.mainIndex); list.push('cid'); var l = list.length; this.models = []; this._indexes = {}; for (; i < l; i++) { this._indexes[list[i]] = {}; } }
javascript
{ "resource": "" }
q56385
handlebarsEngine
train
function handlebarsEngine(taskOptions) { debug('Initializing new instance of hbs'); const handlebars = hbs.create(); /* istanbul ignore else */ if (taskOptions.helpers) { for (const helper of Object.keys(taskOptions.helpers)) { debug(' Registering helper: %s', helper); handlebars.registerHelper(helper, taskOptions.helpers[helper]); } } return handlebars; }
javascript
{ "resource": "" }
q56386
arrayContainsItem
train
function arrayContainsItem(array, value, options) { if (array && _.indexOf(array, value) >= 0) { return options.fn(this); } return options.inverse(this); }
javascript
{ "resource": "" }
q56387
compareValues
train
function compareValues(lvalue, operator, rvalue, options) { const operators = { '==': function compareEqual(l, r) { return l === r; }, '===': function compareIdentical(l, r) { return l === r; }, '!=': function compareNotEqual(l, r) { return l !== r; }, '<': function compareLessThan(l, r) { return l < r; }, '>': function compareGreaterThan(l, r) { return l > r; }, '<=': function compareLessThanEqual(l, r) { return l <= r; }, '>=': function compareGreaterThanEqual(l, r) { return l >= r; }, typeof: function compareTypeOf(l, r) { return typeof l === r; }, }; /* istanbul ignore if */ if (!operators[operator]) { throw new Error(util.format('Unknown compare operator: %s', operator)); } const result = operators[operator](lvalue, rvalue); if (result) { return options.fn(this); } return options.inverse(this); }
javascript
{ "resource": "" }
q56388
lowercaseFirstLetter
train
function lowercaseFirstLetter(options) { const string = options.fn(this); return string.charAt(0).toLowerCase() + string.slice(1); }
javascript
{ "resource": "" }
q56389
capSplitAndJoin
train
function capSplitAndJoin(joiner, options) { const string = options.fn(this); const members = string.split(/(?=[A-Z])/); return members.join(joiner); }
javascript
{ "resource": "" }
q56390
propertyValueExtract
train
function propertyValueExtract(context, name, propName, options) { if (context[name] === undefined || context[name] === null) { return options.inverse(context); } this[propName] = context[name]; /* eslint-disable no-param-reassign */ context[propName] = context[name]; /* eslint-enable no-param-reassign */ return options.fn(context); }
javascript
{ "resource": "" }
q56391
uppercaseFirstLetter
train
function uppercaseFirstLetter(options) { const string = options.fn(this); return string.charAt(0).toUpperCase() + string.slice(1); }
javascript
{ "resource": "" }
q56392
regex
train
function regex(replacements) { return { name: 'regex', renderChunk(code) { const magicString = new MagicString(code); let hasReplacements = false; replacements.forEach(replacement => { let [find, replace = ''] = replacement; if (typeof find === 'string') find = new RegExp(find); if (!find.global) find = new RegExp(find.source, 'g' + String(find).split('/').pop()); let match, start, end; while ((match = find.exec(code))) { hasReplacements = true; start = match.index; end = start + match[0].length; magicString.overwrite(start, end, typeof replace === 'function' ? replace.apply(null, match) || '' : replace.replace(/\$(\d+)/, (str, index) => match[index])); } }); if (!hasReplacements) return null; return { code: magicString.toString(), map: magicString.generateMap({ hires: true }) }; } }; }
javascript
{ "resource": "" }
q56393
babel
train
function babel(options = {}) { return { name: 'babel', renderChunk(code) { options.presets = [['env', { modules: false }]]; options.sourceMaps = true; return transform(code, options); } }; }
javascript
{ "resource": "" }
q56394
uglify
train
function uglify(options = {}) { return { name: 'uglify', renderChunk(code) { options.sourceMap = true; return minify(code, options); } }; }
javascript
{ "resource": "" }
q56395
getGraphqlName
train
function getGraphqlName(g, iri) { const { prefixes } = g.config; const localName = getIriLocalName(iri); const namespaceIri = iri.slice(0, -localName.length); const prefix = Object.keys(prefixes).find(key => prefixes[key] === namespaceIri) || ''; return capitalize(prefix + localName).replace(/\W/g, '_'); }
javascript
{ "resource": "" }
q56396
requireGraphqlRelay
train
function requireGraphqlRelay() { if (graphqlRelay) return graphqlRelay; try { graphqlRelay = require('graphql-relay'); } catch (ex) { // Nothing } if (!graphqlRelay) { // Go up until graphql-relay is found // Inspired by https://www.npmjs.com/package/parent-require for (let parent = module.parent; parent && !graphqlRelay; parent = parent.parent) { try { graphqlRelay = parent.require('graphql-relay'); } catch (ex) { // Nothing } } // No pity if (!graphqlRelay) throw new Error('semantic-graphql was not able to find "graphql-relay" as a dependency of your project. Run "npm install graphql-relay" or set the "relay" option to false.'); } return graphqlRelay; }
javascript
{ "resource": "" }
q56397
parseArgs
train
function parseArgs() { var args = Array.prototype.slice.call(arguments); var ret = { query: args[0], params: [], options: {}, callback: undefined, endCallback: undefined }; args.shift(); // If specified, params must be an array if (args[0] instanceof Array) { ret.params = args[0]; args.shift(); } // If specified, options must be a non-Function object if (! (args[0] instanceof Function)) { ret.options = args[0]; args.shift(); } ret.callback = args[0]; ret.endCallback = args[1]; if (ret.query === undefined || ret.callback === undefined) { throw new Error('query and callback are required'); } return ret; }
javascript
{ "resource": "" }
q56398
createArgs
train
function createArgs(args, color) { var last = args[args.length - 1]; if (args.length > 1 && isObject(last && last.hash)) { args.pop(); } if (typeof color === 'string' && utils[color]) { args[0] = utils[color](args[0]); } return args; }
javascript
{ "resource": "" }
q56399
switchOutput
train
function switchOutput(type, json) { if (type[0] === '.') type = type.slice(1); var result = ''; switch (type) { case 'md': result = '' + '\n```json\n' + json + '\n```\n'; break; case 'html': result = '' + '<div class="highlight highlight-json">\n' + '<pre><code>\n' + json + '</code></pre>' + '</div>'; break; default: { result = json; break; } } return result; }
javascript
{ "resource": "" }