_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q41800
train
function(list) { if (Array.isArray(list)) { this.a.push.apply(this.a, list); } else { for (var __$0 = (list)[Symbol.iterator](), __$1; __$1 = __$0.next(), !__$1.done;) { var item$0 = __$1.value; this.a.push(item$0); } } return this; }
javascript
{ "resource": "" }
q41801
train
function(obj) { if (Array.isArray(obj)) { return { at: function(skip, pos) { return obj[pos] }, rest: function(skip, pos) { return obj.slice(pos) } }; } var iter = toObject(obj)[Symbol.iterator](); return { at: function(skip) { var r; while (skip--) r = iter.next(); return r.value; }, rest: function(skip) { var a = [], r; while (--skip) r = iter.next(); while (r = iter.next(), !r.done) a.push(r.value); return a; } }; }
javascript
{ "resource": "" }
q41802
train
function(obj, map, name) { var entry = map.get(Object(obj)); if (!entry) throw new TypeError; return entry[name]; }
javascript
{ "resource": "" }
q41803
getClass
train
function getClass(o) { if (o === null || o === undefined) return "Object"; return OP_toString.call(o).slice("[object ".length, -1); }
javascript
{ "resource": "" }
q41804
equal
train
function equal(a, b) { if (Object.is(a, b)) return true; // Dates must have equal time values if (isDate(a) && isDate(b)) return a.getTime() === b.getTime(); // Non-objects must be strictly equal (types must be equal) if (!isObject(a) || !isObject(b)) return a === b; // Prototypes must be identical. getPrototypeOf may throw on // ES3 engines that don't provide access to the prototype. try { if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false; } catch (err) {} var aKeys = Object.keys(a), bKeys = Object.keys(b); // Number of own properties must be identical if (aKeys.length !== bKeys.length) return false; for (var i$0 = 0; i$0 < aKeys.length; ++i$0) { // Names of own properties must be identical if (!OP_hasOwnProperty.call(b, aKeys[i$0])) return false; // Values of own properties must be equal if (!equal(a[aKeys[i$0]], b[aKeys[i$0]])) return false; } return true; }
javascript
{ "resource": "" }
q41805
punch
train
function punch(date) { Object.defineProperty(date, '_isValid', { get: function() { return this.toDate() !== this.lang().invalidDate() } }); return date; }
javascript
{ "resource": "" }
q41806
handleSocketMessage
train
function handleSocketMessage(method, data, replyFn) { debug('%s %s %s', socket.id, method, data.url, data.payload); eyes.mark('sockets.' + method); var url = data.url; if (!url) { replyFn({ status: 400, message: 'No URL given in request!' }); return; } if (url.indexOf('/') == -1) { url += '/'; // Ensure that the URL can be routed. } var req = { context: context, method: method, url: url, remoteAddress: remoteAddress, payload: data.payload }; if (!req.payload) { req.payload = {}; } var replied = false; var res = { json: function(reply) { replyFn(reply); replied = true; debug('%s reply %s %s', socket.id, method, data.url); eyes.mark('sockets.' + method + '.status.200'); }, sendStatus: function(statusCode, message) { replyFn({ status: statusCode, message: message }); replied = true; debug('%s reply %s %s', socket.id, method, data.url, statusCode); eyes.mark('sockets.' + method + '.status.' + statusCode); } }; service.commandRouter.handle(req, res, function(err) { if (err) { console.error('Error handling %s %s:', method, data.url, err, err.stack); if (!replied) { console.error('No reply sent for %s %s...sending 500 error.', method, data.url); res.sendStatus(500, 'Server error'); } } else if (!replied) { debug('No route found for %s %s...sending 404', method, data.url); res.sendStatus(404, 'Not found: ' + data.url); } }); }
javascript
{ "resource": "" }
q41807
getParts
train
function getParts(str) { return str.replace(/\\\./g, '\uffff').split('.').map(function(s) { return s.replace(/\uffff/g, '.'); }); }
javascript
{ "resource": "" }
q41808
CachedPromiseProxy
train
function CachedPromiseProxy(target, context, cache = new WeakMap(), factory = PromiseProxy) { const cached = cache.get(target) if (cached) { return cached } const obj = factory(target, context, (target, context) => CachedPromiseProxy(target, context, cache)) cache.set(target, obj) return obj }
javascript
{ "resource": "" }
q41809
checkIfPlaying
train
function checkIfPlaying(){ runInPage(window.fetaSource.isPlayingStr(), function(result){ if(!result){ setTimeout(checkIfPlaying,500); }else{ _window.msgFromDevtools("revertRun",{data: result}); } }, function(err){ alert(errorMessage+"error playing script, line 96."); }); }
javascript
{ "resource": "" }
q41810
doFeta
train
function doFeta(msg) { if(msg){ runInPage(window.fetaSource.startStr(), function(){ btn.update("images/recording.png", "Stop Recording"); }); }else{ runInPage(window.fetaSource.stopStr(), function(result){ btn.update("images/record.png", "Start Recording"); _window.msgFromDevtools("saveFile",{data:result}); }); } }
javascript
{ "resource": "" }
q41811
makeDownload
train
function makeDownload(url,fname){ fname = fname === "" ? "feta_output.js" : fname; //this code is from SO, but I'm missing the link right now var s = "var a = document.createElement('a');"; s+= "a.href = '"+url+"';"; s+= "a.download = '"+ fname +"';"; // set the file name s+= "a.style.display = 'none';"; s+= "document.body.appendChild(a);"; s+= "a.click();"; //this is probably the key - simulatating a click on a download link s+= "delete a;";// we don't need this anymore runInPage(s,doNothing); }
javascript
{ "resource": "" }
q41812
runInPage
train
function runInPage(code,callback,errorCallback){ errorCallback = errorCallback || function(err){ alert(errorMessage+err); }; chrome.devtools.inspectedWindow["eval"]( code, function(result, isException) { if (isException) errorCallback(isException); else{ callback(result); } }); }
javascript
{ "resource": "" }
q41813
train
function(err){ //if this is already a network error just throw it if(err instanceof NetworkError){ throw err } //convert strings to errors if('string' === typeof err){ err = new Error(err) } //check if the error message matches a known TCP error var error for(var i = 0; i < tcpErrors.length; i++){ if(err.message.indexOf(tcpErrors[i]) >= 0){ //lets throw a NetworkError error = new NetworkError(err.message) //preserve the original stack trace so we can actually debug these error.stack = err.stack throw error } } //if we make it here it is not an error we can handle just throw it throw err }
javascript
{ "resource": "" }
q41814
train
function(type,options){ var cacheKey = type + ':' + options.host + ':' + options.port if(!cache[cacheKey]){ debug('cache miss',cacheKey) var reqDefaults = { rejectUnauthorized: false, json: true, timeout: +process.env.REQUEST_TIMEOUT || +options.timeout || 2147483647, //equiv to timeout max in node.js/lib/timers.js pool: pool } if(options.username || (config[type] && config[type].username)){ reqDefaults.auth = { username: options.username || config[type].username } } if(options.password || (config[type] && config[type].password)){ if(reqDefaults.auth){ reqDefaults.auth.password = options.password || config[type].password } else { reqDefaults.auth = { password: options.password || config[type].password } } } var req = request.defaults(reqDefaults) cache[cacheKey] = extendRequest(req,type,options) } else { debug('cache hit',cacheKey) } return cache[cacheKey] }
javascript
{ "resource": "" }
q41815
isMatch
train
function isMatch(file, license, rate, srcNLReg) { var srcLines = file.contents.toString('utf8').split(/\r?\n/), templateLines = license.split(/\r?\n/), type = path.extname(file.path), matchRates = 0, removed = false; // after '<?php' has new line, remove it switch (type) { case '.php': if (srcLines[1].replace(/\s/, '') === '') { srcLines.splice(1, 1); removed = true; } break; default: break; } // count match line var minLength = templateLines.length > srcLines.length ? srcLines.length : templateLines.length; for (var i = 0; i < minLength; i++) { if (templateLines[templateLines.length - 1] === '' && i === templateLines.length - 1) { matchRates += 1; } else { switch (type) { case '.php': matchRates += getMatchRate(srcLines[i + 1], templateLines[i]); break; default: matchRates += getMatchRate(srcLines[i], templateLines[i]); break; } } } // has similar license, remove the license. var matchPer = matchRates / templateLines.length; if (matchPer >= rate && matchPer < 1) { // remove switch (type) { case '.php': if (srcLines[templateLines.length].replace(/\s/, '') === '' && !removed) { // after license, should be have a blank line. if has not, we don't need remove blank line. && after '<?php' has not new line srcLines.splice(1, templateLines.length); } else { srcLines.splice(1, templateLines.length - 1); } file.contents = new Buffer(srcLines.join(srcNLReg)); break; default: // after license, should be have a blank line. if have not, we don't need remove blank line. if (srcLines[templateLines.length - 1].replace(/\s/, '') === '') { srcLines.splice(0, templateLines.length); } else { srcLines.splice(0, templateLines.length - 1); } file.contents = new Buffer(srcLines.join(srcNLReg)); break; } return false; } else if (matchPer === 1) { return true; } }
javascript
{ "resource": "" }
q41816
getMatchRate
train
function getMatchRate(src, str) { if (typeof (src) === 'undefined' || typeof (str) === 'undefined') { return 0; } var maxLength = src.length > str.length ? src.length : str.length, matchCnt = 0; if (maxLength === 0) { return 1; } for (var i = 0; i < maxLength; i++) { if (str.charAt(i) === src.charAt(i)) { matchCnt++; } } if (matchCnt === 0) { return 0; } return matchCnt / maxLength; }
javascript
{ "resource": "" }
q41817
getSeparator
train
function getSeparator(str, str2) { // 13 \r 10 \n for (var i = str.length; i > -1; i--) { if (str.charCodeAt(i) === 10) { if (str.charCodeAt(i - 1) === 13) { return '\r\n'; } if (str.charCodeAt(i + 1) === 13) { return '\n\r'; } return '\n'; } if (str.charCodeAt(i) === 13) { if (str.charCodeAt(i - 1) === 10) { return '\n\r'; } if (str.charCodeAt(i + 1) === 10) { return '\r\n'; } return '\r'; } } // if file no newline, will use template for (var i = str2.length; i > -1; i--) { if (str2.charCodeAt(i) === 10) { if (str2.charCodeAt(i - 1) === 13) { return '\r\n'; } if (str2.charCodeAt(i + 1) === 13) { return '\n\r'; } return '\n'; } if (str2.charCodeAt(i) === 13) { if (str2.charCodeAt(i - 1) === 10) { return '\n\r'; } if (str2.charCodeAt(i + 1) === 10) { return '\r\n'; } return '\r'; } } }
javascript
{ "resource": "" }
q41818
train
function(memberName) { var parent = this.super; do { parent = Object.getPrototypeOf(parent); } while (!parent.hasOwnProperty(memberName)); return parent && parent[memberName]; }
javascript
{ "resource": "" }
q41819
findSuper
train
function findSuper(methodName, childObject) { var object = childObject; while (object[methodName] === childObject[methodName]) { object = object.constructor.__super__; if (!object) { throw new Error('Class has no super method for', methodName, '. Remove the _super call to the non-existent method'); } } return object; }
javascript
{ "resource": "" }
q41820
prompt
train
function prompt (config) { const controller = new Controller() return controller .prompt(config) .then(function (answer) { controller.destroy() return answer }) }
javascript
{ "resource": "" }
q41821
train
function (gen) { var main = co.wrap(gen) const controller = new Controller() function finish () { controller.destroy() return controller.answers } function error (error) { console.error(error.stack) } return main(function (config) { return controller.prompt(config) }, register).then(finish, error) }
javascript
{ "resource": "" }
q41822
convertColorComponent
train
function convertColorComponent (input) { let result = input.toString(16); if (result.length < 2) { result = '0' + result } return result; }
javascript
{ "resource": "" }
q41823
train
function(s1, s2, s5, val){ return s1 ? [s1 + s2 + val, 'px' + s5].join(''): [s2 + val, 'px' + s5].join(''); }
javascript
{ "resource": "" }
q41824
train
function(capability, specLists) { this.capability = capability; this.numRunningInstances = 0; this.maxInstance = capability.maxInstances || 1; this.specsIndex = 0; this.specLists = specLists; }
javascript
{ "resource": "" }
q41825
addBias
train
function addBias(arr) { if (!Array.isArray(arr) || !arr.length) { throw new Error(`Expected ${arr} to be an array with length`); } else if (!arr.every(Array.isArray)) { throw new Error(`Expected every item of ${arr} to be an array`); } return arr.map(row => [1].concat(row)); }
javascript
{ "resource": "" }
q41826
getNormalizedTags
train
function getNormalizedTags(tags) { return Object.keys(tags).sort().reduce((memo, tag) => { const value = tags[tag]; if (typeof value === 'boolean') { return memo.concat(value === true ? 1 : -1); } else if (typeof value === 'number') { return memo.concat(value); } return memo; }, []); }
javascript
{ "resource": "" }
q41827
Stweam
train
function Stweam(opts) { stream.Transform.call(this); opts = opts || {}; if (!opts.consumerKey) throw new Error('consumer key is required'); if (!opts.consumerSecret) throw new Error('consumer secret is required'); if (!opts.token) throw new Error('token is required'); if (!opts.tokenSecret) throw new Error('token secret is required'); this.consumerKey = opts.consumerKey; this.consumerSecret = opts.consumerSecret; this.token = opts.token; this.tokenSecret = opts.tokenSecret; this._keywords = ''; this._language = 'en'; this._follow = ''; this._initBackoffs(); }
javascript
{ "resource": "" }
q41828
all
train
function all(callback) { var Model = this; var request = { find : 'find', model : Model }; this.dispatch('beforeAll'); this.storage.find(request, function findCallback(data) { if (callback) { callback(data); Model.dispatch('afterAll'); } }); return this; }
javascript
{ "resource": "" }
q41829
find
train
function find(id, callback) { var Model, request; Model = this; request = { action : 'findOne', model : Model, params : { id : id } }; this.storage.findOne(request, function findOneCallback(data) { if (callback) { callback(data); } }); return this; }
javascript
{ "resource": "" }
q41830
init
train
function init(properties) { this.eventListeners = []; if (typeof properties !== 'undefined') { Object.keys(properties).forEach(function (property) { this[property] = properties[property]; }, this); } return this; }
javascript
{ "resource": "" }
q41831
setProperty
train
function setProperty(property, newValue) { var originalValue; if (newValue != originalValue) { originalValue = this[property]; this[property] = newValue; this.dispatch('change:' + property, { originalValue : originalValue, newValue : newValue }); } return this; }
javascript
{ "resource": "" }
q41832
save
train
function save(callback) { var model, request; model = this; this.constructor.dispatch('beforeSave', { data : { model : this } }); this.dispatch('beforeSave'); this.isValid(function (isValid) { if (isValid) { if (model.hasOwnProperty('id') && model.id !== '') { request = { action : 'update', data : model, model : model.constructor }; model.constructor.storage.update(request, function updateCallback(data) { model.constructor.dispatch('afterSave', { data : { model : model } }); model.dispatch('afterSave'); if (callback) { callback(data); } }); } else { request = { action : 'create', data : model, model : model.constructor }; model.constructor.storage.create(request, function createCallback(data) { model.constructor.dispatch('afterSave', { data : { model : model } }); model.dispatch('afterSave'); if (callback) { callback(data); } }); } } else { if (callback) { callback(data); } } }); }
javascript
{ "resource": "" }
q41833
destroy
train
function destroy(callback) { var model = this; var request = { action : 'remove', model : model.constructor, data : this }; this.dispatch('beforeDestroy'); this.constructor.storage.remove(request, function destroyCallback() { model.setProperty('id', null); model.dispatch('afterDestroy'); if (callback) { callback(model); } }); }
javascript
{ "resource": "" }
q41834
train
function(mocha, test) { test.parent._onlyTests = test.parent._onlyTests.concat(test); mocha.options.hasOnly = true; return test; }
javascript
{ "resource": "" }
q41835
Machines
train
function Machines (sigTerm) { if (!(this instanceof Machines)) return new Machines(sigTerm); this._sigTerm = sigTerm; this._devices = {}; EventEmitter.call(this); }
javascript
{ "resource": "" }
q41836
addHook
train
function addHook(hooks, hook) { hooks.push(hook) return function () { var i = hooks.indexOf(hook) if (i >= 0) return hooks.splice(i, 1) } }
javascript
{ "resource": "" }
q41837
decodeStream
train
function decodeStream(opts) { opts || (opts = {}) var stream = Transform({ objectMode: true }) stream._transform = function (data, _, cb) { try { // decode keys even when keys or values aren't requested specifically if ((opts.keys && opts.values) || (!opts.keys && !opts.values)) { data.key = ns.decode(data.key, opts) } else if (opts.keys) { data = ns.decode(data, opts) } } catch (err) { return cb(err) } cb(null, data) } return stream }
javascript
{ "resource": "" }
q41838
train
function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } throw('Irrelon Overload: Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr)); }; } return function () {}; }
javascript
{ "resource": "" }
q41839
mergeObject
train
function mergeObject(target, source) { // create a variable to hold the target object // so it can be changed if its not an object let targetObject = target; let sourceObject = source; if (!isObj(target)) { targetObject = {}; } if (!isObj(source)) { sourceObject = {}; } // get the object keys for the target and source objects const targetKeys = Object.keys(targetObject); const sourceKeys = Object.keys(sourceObject); // create a empty object for the result const result = {}; // go through all the target keys targetKeys.forEach((key) => { // check if the source object contains the key if (sourceKeys.indexOf(key) !== -1) { // check if the target value is null if it is // set the result as the source value, this // should be fine because if the source value // is null it isn't overriding the target value // and if it isn't null it is overriding // as expected if (targetObject[key] === null) { result[key] = sourceObject[key]; } else if (isObj(targetObject[key])) { // check if the source value is an object if // it is then we need to merge both objects and // set the result value to the merged object if (isObj(sourceObject[key])) { result[key] = mergeObject(targetObject[key], sourceObject[key]); } else { // if the source value isn't an object we can // simply override the value result[key] = sourceObject[key]; } } else { // if the target value isn't an object we can // simply override the value result[key] = sourceObject[key]; } } else { // if the source doesn't contain the key set the result // as the original from the target result[key] = targetObject[key]; } }); // go through all the source keys sourceKeys.forEach((key) => { // if the target doesn't contain the key // then the value is new and should be added // to the result object if (targetKeys.indexOf(key) === -1) { result[key] = sourceObject[key]; } }); return result; }
javascript
{ "resource": "" }
q41840
train
function(str){ return str.replace(BORDER_RADIUS_RE, function(){ var ret = 'border-radius' + arguments[1] + ':' + arguments[2] + reorderBorderRadius(arguments[3], arguments[4], arguments[5], arguments[6]); if(arguments[7]) ret += ' / ' + reorderBorderRadius(arguments[8], arguments[9], arguments[10], arguments[11]); return ret; } ); }
javascript
{ "resource": "" }
q41841
invert
train
function invert(str, options){ if(!options) options = {}; if(!options.exclude) options.exclude = []; for(var rule in rules) { // Pass excluded rules if(options.exclude.indexOf(rule) != -1) continue; // Run rule str = rules[rule](str, options); } return str; }
javascript
{ "resource": "" }
q41842
reorderBorderRadius
train
function reorderBorderRadius(p1, p2, p3, p4){ if(p4) return [p2, p1, p4, p3].join(' '); if(p3) return [p2, p1, p2, p3].join(' '); if(p2) return [p2, p1].join(' '); else return p1; }
javascript
{ "resource": "" }
q41843
fixGradient
train
function fixGradient(str) { var ret = str.replace(GRADIENT_REPLACE_RE, function($0, $1, $2){ return $1 ? $0 : ($2 == 'right') ? 'left' : ($2 == 'left') ? 'right' : (parseInt($2) % 180 == 0) ? $2 : ($2.substr(0,1) == '-') ? $2.substr(1) : ('-' + $2); }); return ret; }
javascript
{ "resource": "" }
q41844
bitsToLayout
train
function bitsToLayout(bits) { var idx = 0 const map = {} for (const [ name, b ] of bits) { const mask = maskForBits(b) map[name] = [ idx, mask ] idx += b } return map }
javascript
{ "resource": "" }
q41845
train
function(prototypeProps, constructorProps) { if (typeof prototypeProps.Meta == 'undefined' || typeof prototypeProps.Meta.name == 'undefined') { throw new Error('When extending Model, you must provide a name via a Meta object.') } var options = new ModelOptions(prototypeProps.Meta) delete prototypeProps.Meta for (var prop in prototypeProps) { if (prototypeProps.hasOwnProperty(prop)) { var field = prototypeProps[prop] if (field instanceof Field || field instanceof Rel) { field.name = prop options.fields.push(field) delete prototypeProps[prop] } } } prototypeProps._meta = constructorProps._meta = options }
javascript
{ "resource": "" }
q41846
run
train
function run(cb) { // check if template is local if (/^[./]|(\w:)/.test(template)) { var templatePath = template.charAt(0) === '/' || /^\w:/.test(template) ? template : path.normalize(path.join(process.cwd(), template)) if (exists(templatePath)) { generate(name, templatePath, to, cb) } else { logger.fatal('Local template "%s" not found.', template) } } else { checkVersion(function () { if (!hasSlash) { // use official templates var officialTemplate = 'vuejs-templates/' + template if (template.indexOf('#') !== -1) { downloadAndGenerate(officialTemplate, cb) } else { if (template.indexOf('-2.0') !== -1) { warnings.v2SuffixTemplatesDeprecated(template, inPlace ? '' : name) return } warnings.v2BranchIsNowDefault(template, inPlace ? '' : name) downloadAndGenerate(officialTemplate, cb) } } else { downloadAndGenerate(template, cb) } }) } }
javascript
{ "resource": "" }
q41847
downloadAndGenerate
train
function downloadAndGenerate (template, cb) { var spinner = ora('downloading template') spinner.start() download(template, tmp, { clone: clone }, function (err) { spinner.stop() if (err) logger.fatal('Failed to download repo ' + template + ': ' + err.message.trim()) generate(name, tmp, to, cb) }) }
javascript
{ "resource": "" }
q41848
validateSeed
train
function validateSeed() { return Q.Promise(function(resolve, reject) { https.get('https://github.com/olivejs/seed-' + options.seed, function(res) { if (res.statusCode === 200) { resolve('>> seed exists'); } else { reject(new Error('Invalid seed: ' + options.seed)); } }).on('error', function(err) { logger.error('\n %s\n', err.message); reject(err); }); }); }
javascript
{ "resource": "" }
q41849
exposeAPI
train
function exposeAPI(connection){ return { query: function(stmt, params){ return _query(connection, stmt, params); }, insert: function(table, data){ return _insert(connection, table, data); }, fetchRow: function(stmt, params){ return _fetchRow(connection, stmt, params); }, fetchAll: function(stmt, params){ return _fetchAll(connection, stmt, params); }, release: function(){ return connection.release(); } }; }
javascript
{ "resource": "" }
q41850
train
function(config, defaults) { var key, subdefaults, subconfig; for (key in defaults) { subdefaults = defaults[key]; subconfig = config[key]; if ($.isPlainObject(subdefaults)) { if (!$.isPlainObject(subconfig)) { subconfig = config[key] = {}; } defaultsUpdater(subconfig, subdefaults); // } else if (subconfig === undefined) { // config[key] = null; // } } else { if (subconfig === undefined) { config[key] = subdefaults; } } } }
javascript
{ "resource": "" }
q41851
train
function(options) { EventEmitter.call(this); this.node = options.node; this.https = options.https || this.node.https; this.httpsOptions = options.httpsOptions || this.node.httpsOptions; this.bwsPort = options.bwsPort || baseConfig.port; this.messageBrokerPort = options.messageBrokerPort || 3380; if (baseConfig.lockOpts) { this.lockerPort = baseConfig.lockOpts.lockerServer.port; } this.lockerPort = options.lockerPort || this.lockerPort; }
javascript
{ "resource": "" }
q41852
availableSourcesURL
train
function availableSourcesURL(startDate, endDate) { var url = (baseURL() +'/location/datum/sources?locationId=' +locationId); if ( startDate !== undefined ) { url += '&start=' +encodeURIComponent(sn.format.dateFormat(startDate)); } if ( endDate !== undefined ) { url += '&end=' +encodeURIComponent(sn.format.dateFormat(endDate)); } return url; }
javascript
{ "resource": "" }
q41853
fill
train
function fill(fillWith, len){ var buffer = new Buffer(len); buffer.fill(fillWith); return buffer.toString(); }
javascript
{ "resource": "" }
q41854
padRight
train
function padRight(input, width, padWith){ padWith = padWith || " "; input = String(input); if (input.length < width){ return input + fill(padWith, width - input.length); } else { return input; } }
javascript
{ "resource": "" }
q41855
repeat
train
function repeat(input, times){ var output = ""; for (var i = 0; i < times; i++){ output += input; } return output; }
javascript
{ "resource": "" }
q41856
clipLeft
train
function clipLeft(input, width, prefix){ prefix = prefix || "..."; if (input.length > width){ return prefix + input.slice(-(width - prefix.length)); } else { return input; } }
javascript
{ "resource": "" }
q41857
handleStyles
train
function handleStyles(tagName, styles) { styles = (styles || []).map(style => { let code = style; return code.replace(/[\r\n]*([^%\{;\}]+?)\{/gm, (global, match) => { if (match.trim().match(/^@/)) { return match + '{'; } var selectors = match.split(',').map(selector => { selector = selector.trim(); if (selector.match(/:host\b/) || selector.match(new RegExp(`^\\s*${tagName}\\b`)) || selector.match(/^\s*(?:(?:\d+%)|(?:from)|(?:to)|(?:@\w+)|\})\s*$/)) { return selector; } return tagName + ' ' + selector; }); return global.replace(match, selectors.join(',')); }).replace(/:host\b/gm, tagName) + '\n'; }); return styles; }
javascript
{ "resource": "" }
q41858
handleText
train
function handleText(text, isAttr) { let match, result = '', lastIndex = 0; let cat = isAttr ? ' + ' : ', '; if (!text.match(syntax)) { return result += "'" + text.substr(lastIndex).replace(/\n/g, '').replace(/'/g, '\\\'') + "'" + cat; } // locate mustache syntax within the text while (match = syntax.exec(text)) { if (match.index < lastIndex) continue; let frag = text.substring(lastIndex, match.index).replace(/^\s+/g, ''); if (frag.length > 0) { result += "'" + frag.replace(/\n/g, '').replace(/'/g, '\\\'') + "'" + cat; } lastIndex = match.index + match[0].length; let key = match[1]; // of "{{#test}}" value will be "test" let value = key.substr(1); if (key[0] === '#') { // handle block start result += `spread(toArray(${getData()}, '${value}').map(function (e, i, a) { var data$${level + 1} = merge({}, data${0 >= level ? '' : '$' + level}, {'.': e, '.index': i, '.length': a.length}, e); return [].concat(`; level += 1; usesMerge = true; usesSpread = true; } else if (key[0] === '/') { // handle block end result += '\'\'); }))' + (isAttr ? '.join("")' : '') + cat; level -= 1; if (level < 0) { throw new Error('Unexpected end of block: ' + key.substr(1)); } } else if (key[0] === '^') { // handle inverted block start result += `(safeAccess(${getData()}, '${value}') && (typeof safeAccess(${getData()}, '${value}') === 'boolean' || safeAccess(${getData()}, '${value}').length > 0)) ? '' : spread([1].map(function() { var data$${level + 1} = merge({}, data${0 >= level ? '' : '$' + level}); return [].concat(`; usesMerge = true; usesSpread = true; level += 1; } else if (key[0] === '%') { // handle style rendering "{{%myvar}}" - only to be used for attribute values! result += key.substr(1).split(/\s*,\s*/).map(value => `renderStyle(safeAccess(${getData()}, '${value}'), ${getData()})`).join(' + '); usesRenderStyle = true; } else if (key[0] === '+') { // handle deep data transfer "{{+myvar}}" result += `safeAccess(${getData()}, '${value}')${cat}`; } else if (key[0] !== '{' && key[0] !== '!') { // handle non-escaping prints "{{{myvar}}}" value = key; result += `''+safeAccess(${getData()}, '${value}', true)${cat}` } else if (key[0] !== '!') { // regular prints "{{myvar}}" result += `''+safeAccess(${getData()}, '${value}')${cat}`; } // ignore comments } if (text.substr(lastIndex).length > 0) { result += "'" + text.substr(lastIndex).replace(/\n/g, '').replace(/'/g, '\\\'') + "'" + cat; } return result; }
javascript
{ "resource": "" }
q41859
makeAttributes
train
function makeAttributes(attrs) { let attributes = '{'; let attr; while ((attr = attrRegExp.exec(attrs))) { if (attributes !== '{') attributes += ', '; attributes += '"' + attr[1].toLowerCase() + '": ' + handleText(attr[2] || attr[3] || '', true).replace(/\s*[,+]\s*$/g, ''); } return attributes + '}'; }
javascript
{ "resource": "" }
q41860
bytes32ToType
train
function bytes32ToType(type, value) { switch (type) { case 'address': return `0x${ethUtil.stripHexPrefix(value).slice(24)}`; case 'bool': return (ethUtil.stripHexPrefix(value).slice(63) === '1'); case 'int': return bytes32ToInt(value); case 'uint': return bytes32ToInt(value); default: return value; } }
javascript
{ "resource": "" }
q41861
filenameInclude
train
function filenameInclude(filename, exclude, include) { // eslint-disable-line var output = true; // eslint-disable-line if (exclude) { if (globToRegExp(exclude, { extended: true }).test(filename) && !globToRegExp(include || '', { extended: true }).test(filename)) { output = false; } } return output; }
javascript
{ "resource": "" }
q41862
allImportPaths
train
function allImportPaths(contractSource) { const noCommentSource = strip.js(String(contractSource)); const rawImportStatements = execall(/^(\s*)((import)(.*?))("|')(.*?)("|')((;)|((.*?)(;)))$/gm, noCommentSource); const importPaths = rawImportStatements .map(v => String(execall(/("|')(.*?)("|')/g, v.match)[0].match) .replace(/'/g, '') .replace(/"/g, '') .replace(/^\//, '') .replace('./', '') .trim()); return importPaths.filter(path => (path !== 'wafr/Test.sol')); }
javascript
{ "resource": "" }
q41863
buildDependencyTreeFromSources
train
function buildDependencyTreeFromSources(filenames, sourcesObject) { const orgnizedFlat = {}; // build tree object filenames.forEach(sourceFileName => { orgnizedFlat[sourceFileName] = { path: sourceFileName, source: sourcesObject[sourceFileName], dependencies: buildDependencyTreeFromSources(allImportPaths(sourcesObject[sourceFileName]), sourcesObject), }; }); // return organized object return orgnizedFlat; }
javascript
{ "resource": "" }
q41864
buildFlatSourcesObjectFromTreeObject
train
function buildFlatSourcesObjectFromTreeObject(treeObject) { const currentOutputObject = Object.assign({}); currentOutputObject[treeObject.path] = treeObject.source; Object.keys(treeObject.dependencies).forEach(dependantTreeObjectFileName => { Object.assign(currentOutputObject, buildFlatSourcesObjectFromTreeObject(treeObject.dependencies[dependantTreeObjectFileName])); }); return currentOutputObject; }
javascript
{ "resource": "" }
q41865
buildDependantsSourceTree
train
function buildDependantsSourceTree(sourceFileName, sourcesObject) { const depsTree = buildDependencyTreeFromSources(Object.keys(sourcesObject), sourcesObject); return buildFlatSourcesObjectFromTreeObject(depsTree[sourceFileName]); }
javascript
{ "resource": "" }
q41866
getInputSources
train
function getInputSources(dirname, exclude, include, focusContractPath, callback) { let filesRead = 0; const sources = {}; // get all file names dir.files(dirname, (filesError, files) => { if (filesError) { throwError(`while while getting input sources ${filesError}`); } // if no files in directory, then fire callback with empty sources if (files.length === 0) { callback(null, sources); } else { // read all files dir.readFiles(dirname, (readFilesError, content, filename, next) => { if (readFilesError) { throwError(`while getting input sources ${readFilesError}`); } // parsed filename const parsedDirName = dirname.replace('./', ''); const parsedFileName = filename.replace(parsedDirName, '').replace(/^\//, ''); const onlyFilename = filename.substr(filename.lastIndexOf('/') + 1); // add input sources to output if (filename.substr(filename.lastIndexOf('.') + 1) === 'sol' && filenameInclude(filename, exclude, include) && onlyFilename.charAt(0) !== '~' && onlyFilename.charAt(0) !== '#' && onlyFilename.charAt(0) !== '.') { sources[parsedFileName] = content; } // increase files readFiles filesRead += 1; // process next file if (filesRead === files.length) { // filter sources by focus dependencies if (focusContractPath) { callback(null, buildDependantsSourceTree(focusContractPath, sources)); } else { callback(null, sources); } } else { next(); } }); } }); }
javascript
{ "resource": "" }
q41867
compareABIByMethodName
train
function compareABIByMethodName(methodObjectA, methodObjectB) { if (methodObjectA.name < methodObjectB.name) { return -1; } if (methodObjectA.name > methodObjectB.name) { return 1; } return 0; }
javascript
{ "resource": "" }
q41868
errorEnhancement
train
function errorEnhancement(inputMessage) { var message = inputMessage; // eslint-disable-line var outputMessage = null; // eslint-disable-line // if the input message is an array or object if (inputMessage !== null && !isNaN(inputMessage) && typeof inputMessage !== 'string') { message = JSON.stringify(inputMessage); } // gauentee string convertion, null and other.. message = String(message); // if message includes if (message.includes('Compiled contract not found')) { outputMessage = 'This could be due to a contract with the same name being compiled. Wafr doesnt allow two contracts with the same name. Look to see if any of your contracts have the same name.'; } // if message includes if (message.includes('invalid JUMP')) { outputMessage = `This can be caused by many things. One main cause is a 'throw' flag being used somewhere in execution. This can be caused by: 1. A 'throw' flag being used somewhere in execution (a function your calling) 2. Sending ether to a contract which does not have the 'payable' modifier on the fallback: function () payable {} 3. A send or transaction was out of gas `; } // if message includes if (message.includes('invalid opcode') || message.includes('invalid op code')) { outputMessage = 'This can be caused by a contract which compiles fine, but doesnt execute properly in the Ethereum Virtual Machine. Such as using a `0x0` as an address.'; } // if message includes if (message.includes('out of gas')) { outputMessage = `This error can be due to various scenarios: 1. A error caused somewhere in your contract 2. An error with the EVM module (npm: 'ethereumjs-vm') 3. An error caused by the wafr module 4. An error with the node simulation module (npm: 'ethereumjs-testrpc') 5. A wafr account actually being out of gas 6. The 'payable' flag not being used on a contract your sending ether too (common) If you cannot resolve this issue with reasonable investigation, report the error at: http://github.com/SilentCicero/wafr/issues If you believe the error is caused by the test node infrastructure, report the error at: http://github.com/ethereumjs/testrpc If you believe the error is caused by the EVM module, report the error at: http://github.com/ethereumjs/ethereumjs-vm `; } // return output message return outputMessage; }
javascript
{ "resource": "" }
q41869
increaseProviderTime
train
function increaseProviderTime(provider, time, callback) { if (typeof time !== 'number') { callback('error while increasing TestRPC provider time, time value must be a number.', null); return; } provider.sendAsync({ method: 'evm_increaseTime', params: [time], }, (increaseTimeError) => { if (increaseTimeError) { callback(`error while increasing TestRPC provider time: ${JSON.stringify(increaseTimeError)}`, null); } else { provider.sendAsync({ method: 'evm_mine', }, (mineError) => { if (mineError) { callback(`while mining block to increase time on TestRPC provider: ${JSON.stringify(mineError)}`, null); } else { callback(null, true); } }); } }); }
javascript
{ "resource": "" }
q41870
increaseBlockRecursively
train
function increaseBlockRecursively(provider, count, total, callback) { // if the count hits the total, stop the recursion if (count >= total) { callback(null, true); } else { // else mine a block provider.sendAsync({ method: 'evm_mine', }, (mineError) => { if (mineError) { callback(`while mining to increase block: ${JSON.stringify(mineError)}`, null); } else { increaseBlockRecursively(provider, count + 1, total, callback); } }); } }
javascript
{ "resource": "" }
q41871
getBlockIncreaseFromName
train
function getBlockIncreaseFromName(methodName) { const matchNumbers = String(methodName).match(/_increaseBlockBy(\d+)/); if (matchNumbers !== null && typeof matchNumbers[1] === 'string') { return parseInt(matchNumbers[1], 10); } return 0; }
javascript
{ "resource": "" }
q41872
getTimeIncreaseFromName
train
function getTimeIncreaseFromName(methodName) { const matchNumbers = String(methodName).match(/_increaseTimeBy(\d+)/); if (matchNumbers !== null && typeof matchNumbers[1] === 'string') { return parseInt(matchNumbers[1], 10); } return 0; }
javascript
{ "resource": "" }
q41873
cors
train
function cors(options) { options = _.merge({}, DEF_CONFIG, options); DEBUG && debug('configure http cors middleware', options); return function (req, res, next) { if (req.headers.origin) { res.header('Access-Control-Allow-Origin', options.origin === '*' ? req.headers.origin : options.origin); res.header('Access-Control-Allow-Methods', options.methods); res.header('Access-Control-Allow-Headers', options.headers); res.header('Access-Control-Allow-Credentials', options.credentials); res.header('Access-Control-Max-Age', options.maxAge); if ('OPTIONS' === req.method) { // CORS pre-flight request -> no content return res.send(errors.StatusCode.NO_CONTENT); } } return next(); }; }
javascript
{ "resource": "" }
q41874
itSucks
train
function itSucks (fileSourceData) { var errors = []; for (let sample of fileSourceData) { errors.push({ line: sample.line, message: 'This code sucks: ' + sample.text }); } return { // Too noisy to set ```errors: errors``` // It all sucks, so just say the sucking starts with the first one errors: [{ line: errors.shift().line, message: 'It sucks. Starting here.' }], pass: false }; }
javascript
{ "resource": "" }
q41875
error404
train
function error404(options) { options = _.merge({}, DEF_CONFIG, options); // pre-compile underscore template if available if (typeof options.template === 'string' && options.template.length > 0) { options.template = _.template(options.template); } return function (req, res, next) { var error = { status: options.status, code: options.code, message: options.message, cause: {path: req.path, url: req.url, originalUrl: req.originalUrl, baseUrl: req.baseUrl, query: req.query} }; res.status(error.status); switch (req.accepts(['json', 'html'])) { case 'json': return res.json(error); case 'html': if (typeof options.template === 'function') { res.type('html'); return res.send(options.template({error: error})); } return res.render(options.view, {error: error}); } return res.send(options.message); }; }
javascript
{ "resource": "" }
q41876
TemplateFileLog
train
function TemplateFileLog(src, target) { this.templateFile = { source: src, target: target }; this.isCompilationPerfect = true; this.templateTagLogs = new Table({ chars: { 'top-mid': '', 'bottom-mid': '', 'middle': '', 'mid-mid': '', }, style: {}, }); }
javascript
{ "resource": "" }
q41877
render
train
function render(data) { if (!this._rendered) { if (this.template) { if (data) { this.data = data; } var options = this._options, parentChildren = this._parentChildren, decoder = new Decoder(this.template), template = decoder.render(this.data); if (this.el) { var parent = this.el.parentNode; if (parent) { parent.replaceChild(template.fragment, this.el); } if (this.elGroup && this.elGroup.get(this.el)) { this.elGroup.delete(this.el); this.el = template.fragment; this.elGroup.set(template.fragment, this); } } else { this.el = template.fragment; } this.root = new dom.Element(template.fragment, { name: 'root', data: {} }); this.children = applyElement(template.children, options); applyParent(this, parentChildren, this.data); this.bindings = setBinders(this.children, true); if (this.data) { this.applyBinders(this.data, this); } setRoutes(this.children, this.context); addChildren(this, this.root); this.rendered.apply(this, _toConsumableArray(this._arguments)); this._rendered = true; } else { var HTMLelement = document.createElement('div'); this.root = new dom.Element(HTMLelement, { name: 'root', data: {} }); if (this.el) { var _parent = this.el.parentNode; if (_parent) { _parent.replaceChild(HTMLelement, this.el); } } this.el = HTMLelement; this.children = {}; addChildren(this, this.root); this.rendered.apply(this, _toConsumableArray(this._arguments)); this._rendered = true; } } }
javascript
{ "resource": "" }
q41878
loadCss
train
function loadCss(url) { if (this.context._cssReady.indexOf(url) === -1) { this.context._cssReady.push(url); var linkRef = document.createElement("link"); linkRef.setAttribute("rel", "stylesheet"); linkRef.setAttribute("type", "text/css"); linkRef.setAttribute("href", url); if (typeof linkRef != "undefined") { document.getElementsByTagName("head")[0].appendChild(linkRef); } } }
javascript
{ "resource": "" }
q41879
detach
train
function detach() { if (!this._placeholder) { this._placeholder = document.createElement(this.el.tagName); } if (!this._parent) { this._parent = this.el.parentNode; } if (this.el && this._parent) { this._parent.replaceChild(this._placeholder, this.el); } }
javascript
{ "resource": "" }
q41880
destroy
train
function destroy() { this.onDestroy(); this.eventBus.clear(); while (this._events.length > 0) { this._events.shift().remove(); } while (this._globalEvents.length > 0) { this._globalEvents.shift().remove(); } _destroy(this.children); if (this.elGroup !== undefined && this.el !== undefined) { this.elGroup.delete(this.el); } if (this.root && this.root.remove) { this.root.remove(); } delete this.el; }
javascript
{ "resource": "" }
q41881
addComponent
train
function addComponent(Component, options) { var name = options.name, container = options.container; if (name === undefined) { throw 'you have to define data.name for component.'; } else if (container === undefined) { throw 'You have to define container for component.'; } else if (this.children[name] !== undefined) { throw 'Component using name:' + name + '! already defined.'; } var component = this.setComponent(Component, options), instance = component.run(options.container); instance.setContext(this.context); this.children[name] = instance; return instance; }
javascript
{ "resource": "" }
q41882
open
train
function open(code, attr) { return attr ? ANSI_OPEN + attr + ';' + code + ANSI_FINAL : ANSI_OPEN + code + ANSI_FINAL; }
javascript
{ "resource": "" }
q41883
stringify
train
function stringify(value, code, attr, tag) { var s = open(code, attr); s += close(value, tag); return s; }
javascript
{ "resource": "" }
q41884
train
function(value, key, parent){ this.t = definition.colors; // table of color codes this.v = value; // value wrapped by this instance this.k = key; // property name, eg 'red' this.p = parent; // parent this.a = null; // attribute }
javascript
{ "resource": "" }
q41885
pack
train
function pack(id, type, body) { var buf = new Buffer(body.length + 14); buf.writeInt32LE(body.length + 10, 0); buf.writeInt32LE(id, 4); buf.writeInt32LE(type, 8); body.copy(buf, 12); buf[buf.length-2] = 0; buf[buf.length-1] = 0; return buf; }
javascript
{ "resource": "" }
q41886
list
train
function list(appName, callback) { if (!appName) { return callback(ArgumentError('appName')); } var uri = format('/%s/apps/%s/config/', deis.version, appName); commons.get(uri, function onListResponse(err, result) { console.log(result); callback(err, result ? extractLimits(result) : null); }); }
javascript
{ "resource": "" }
q41887
set
train
function set(appName, limits, callback) { if (!isObject(limits)) { return callback(new Error('To set a variable pass an object')); } var keyValues = {}; if (limits.hasOwnProperty('memory')) { keyValues.memory = limits.memory; } if (limits.hasOwnProperty('cpu')) { keyValues.cpu = limits.cpu; } if (Object.keys(keyValues).length === 0) { return callback(new Error('Only cpu and memory limits are valid')); } commons.post(format('/%s/apps/%s/config/', deis.version, appName), keyValues, function onSetResponse(err, result) { callback(err, result ? extractLimits(result) : null); }); }
javascript
{ "resource": "" }
q41888
unset
train
function unset(appName, limitType, procType, callback) { if (!appName) { return callback(ArgumentError('appName')); } if (!limitType) { return callback(ArgumentError('limitType')); } if (!procType) { return callback(ArgumentError('procType')); } var keyValues = {}; if (limitType === 'memory') { keyValues.memory = {}; keyValues.memory[procType] = null; } if (limitType === 'cpu') { keyValues.cpu = {}; keyValues.cpu[procType] = null; } commons.post(format('/%s/apps/%s/config/', deis.version, appName), keyValues, function onUnsetResponse(err, result) { console.log(result); callback(err, result ? extractLimits(result) : null); }); }
javascript
{ "resource": "" }
q41889
sn_format_fmt
train
function sn_format_fmt() { if ( !arguments.length ) { return; } var i = 0, formatted = arguments[i], regexp, replaceValue; for ( i = 1; i < arguments.length; i += 1 ) { regexp = new RegExp('\\{'+(i-1)+'\\}', 'gi'); replaceValue = arguments[i]; if ( replaceValue instanceof Date ) { replaceValue = (replaceValue.getUTCHours() === 0 && replaceValue.getMinutes() === 0 ? sn.format.dateFormat(replaceValue) : sn.format.dateTimeFormatURL(replaceValue)); } formatted = formatted.replace(regexp, replaceValue); } return formatted; }
javascript
{ "resource": "" }
q41890
train
function(args) { if (args.form.ngModelOptions && Object.keys(args.form.ngModelOptions).length > 0) { args.fieldFrag.firstChild.setAttribute('ng-model-options', JSON.stringify(args.form.ngModelOptions)); } }
javascript
{ "resource": "" }
q41891
train
function(items, path, state) { return build(items, decorator, templateFn, slots, path, state, lookup); }
javascript
{ "resource": "" }
q41892
train
function(form, decorator, slots, lookup) { return build(form, decorator, function(form, field) { if (form.type === 'template') { return form.template; } return $templateCache.get(field.template); }, slots, undefined, undefined, lookup); }
javascript
{ "resource": "" }
q41893
train
function(name, form) { //schemaDecorator is alias for whatever is set as default if (name === 'sfDecorator') { name = defaultDecorator; } var decorator = decorators[name]; if (decorator[form.type]) { return decorator[form.type].template; } //try default return decorator['default'].template; }
javascript
{ "resource": "" }
q41894
train
function(enm) { var titleMap = []; //canonical titleMap format is a list. enm.forEach(function(name) { titleMap.push({name: name, value: name}); }); return titleMap; }
javascript
{ "resource": "" }
q41895
train
function(titleMap, originalEnum) { if (!angular.isArray(titleMap)) { var canonical = []; if (originalEnum) { angular.forEach(originalEnum, function(value, index) { canonical.push({name: titleMap[value], value: value}); }); } else { angular.forEach(titleMap, function(name, value) { canonical.push({name: name, value: value}); }); } return canonical; } return titleMap; }
javascript
{ "resource": "" }
q41896
train
function(name, schema, options) { options = options || {}; var f = options.global && options.global.formDefaults ? angular.copy(options.global.formDefaults) : {}; if (options.global && options.global.supressPropertyTitles === true) { f.title = schema.title; } else { f.title = schema.title || name; } if (schema.description) { f.description = schema.description; } if (options.required === true || schema.required === true) { f.required = true; } if (schema.maxLength) { f.maxlength = schema.maxLength; } if (schema.minLength) { f.minlength = schema.minLength; } if (schema.readOnly || schema.readonly) { f.readonly = true; } if (schema.minimum) { f.minimum = schema.minimum + (schema.exclusiveMinimum ? 1 : 0); } if (schema.maximum) { f.maximum = schema.maximum - (schema.exclusiveMaximum ? 1 : 0); } // Non standard attributes (DONT USE DEPRECATED) // If you must set stuff like this in the schema use the x-schema-form attribute if (schema.validationMessage) { f.validationMessage = schema.validationMessage; } if (schema.enumNames) { f.titleMap = canonicalTitleMap(schema.enumNames, schema['enum']); } f.schema = schema; // Ng model options doesn't play nice with undefined, might be defined // globally though f.ngModelOptions = f.ngModelOptions || {}; return f; }
javascript
{ "resource": "" }
q41897
train
function(arr) { scope.titleMapValues = []; arr = arr || []; form.titleMap.forEach(function(item) { scope.titleMapValues.push(arr.indexOf(item.value) !== -1); }); }
javascript
{ "resource": "" }
q41898
train
function() { //scope.modelArray = modelArray; scope.modelArray = scope.$eval(attrs.sfNewArray); // validateField method is exported by schema-validate if (scope.ngModel && scope.ngModel.$pristine && scope.firstDigest && (!scope.options || scope.options.validateOnRender !== true)) { return; } else if (scope.validateField) { scope.validateField(); } }
javascript
{ "resource": "" }
q41899
train
function() { var model = scope.modelArray; if (!model) { var selection = sfPath.parse(attrs.sfNewArray); model = []; sel(selection, scope, model); scope.modelArray = model; } return model; }
javascript
{ "resource": "" }