_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q33700
_anyFailingRequired
train
function _anyFailingRequired(attributes) { for (var i in attributes) { var key = attributes[i]; if ( ! _resolvers.validateRequired(key, self.date[key])) { return true; } } return false; }
javascript
{ "resource": "" }
q33701
train
function(rule, message) { if (is_object(rule)) { _messages = extend({}, _messages, rule); } else if (is_string(rule)) { _messages[rule] = message; } }
javascript
{ "resource": "" }
q33702
train
function(attribute, alias) { if (is_object(attribute)) { _attributes = extend({}, _attributes, attribute); } else if (is_string(attribute)) { _attributes[attribute] = alias; } }
javascript
{ "resource": "" }
q33703
train
function(value, alias) { if (is_object(value)) { _values = extend({}, _values, value); } else if (is_string(rule)) { _values[value] = alias; } }
javascript
{ "resource": "" }
q33704
train
function(rule, fn) { if (is_object(rule)) { _replacers = extend({}, _replacers, rule); } else if (is_string(rule)) { _replacers[rule] = fn; } }
javascript
{ "resource": "" }
q33705
makeHoliday
train
function makeHoliday(date, info, observedInfo) { // always make the holiday. var holiday = { info: info, date: { month: date.getMonth(), day : date.getDate() } } // if the holiday info's `bank` value has a function then // give it the date so it can evaluate the value. if ('function' === typeof info.bank) { info.bank = info.bank(date) } // without an observed holiday we return only the main holiday if (date.observed == null) { return holiday } // there's an observed date so return both holidays in an array. else { return [ holiday, // main holiday { // observed holiday info: observedInfo, date: { month: date.observed.getMonth(), day : date.observed.getDate() } } ] } }
javascript
{ "resource": "" }
q33706
newYearsSpecial
train
function newYearsSpecial(year) { // 1. hold onto the date, we'll need it in #3 var date = holidays.newYearsDay(year) // 2. do the usual. var newYears = makeHoliday( date, { name: 'New Year\'s Day', bank: !date.observed }, { name: 'New Year\'s Day (Observed)', bank: true } ) // 3. check if the observed date is in the previous year... if (date.observed && date.observed.getFullYear() < year) { // specify that year in the observed holiday's date. newYears[1].date.year = year - 1 } return newYears }
javascript
{ "resource": "" }
q33707
train
function(action, implementation){ this.performableActions = this.performableActions || {}; this.performableActions[action] = this.performableActions[action] || {}; this.performableActions[action].actionName = this.performableActions[action].actionName || action; implementation = implementation || RL.PerformableAction.Types[action]; this.performableActions[action] = Object.create(implementation); // merge could be used instead of Object.create but is less desirable // RL.Util.merge(this.performableAction.Types[action], implementation); if(this.performableActions[action].init){ this.performableActions[action].init.call(this); } }
javascript
{ "resource": "" }
q33708
train
function(action, settings){ var handler = this.performableActions[action]; if(!handler){ return false; } if(!handler.getTargetsForAction){ return false; } settings = settings || {}; if(!settings.skipCanPerformAction && !this.canPerformAction(action, settings)){ return false; } return handler.getTargetsForAction.call(this, settings); }
javascript
{ "resource": "" }
q33709
train
function(action, target, settings){ if(!this.performableActions){ return false; } var handler = this.performableActions[action]; if(!handler){ return false; } // target cannot resolve any actions if(!target.canResolveAction){ return false; } settings = settings || {}; if(!settings.skipCanPerformAction && !this.canPerformAction(action, settings)){ return false; } if(!(handler.canPerformActionOnTarget === true || handler.canPerformActionOnTarget.call(this, target, settings))){ return false; } return target.canResolveAction(action, this, settings); }
javascript
{ "resource": "" }
q33710
train
function(action, target, settings){ if(!this.performableActions){ return false; } var handler = this.performableActions[action]; if(!handler){ return false; } settings = settings || {}; // the functions are in this order because `this.canPerformActionOnTarget` will check `this.canPerformAction` // unless flaged to be skipped. if(!settings.skipCanPerformActionOnTarget && !this.canPerformActionOnTarget(action, target, settings)){ return false; } else if(!settings.skipCanPerformAction && !this.canPerformAction(action, settings)){ return false; } var result; if(handler.performAction === true){ result = {}; } else { result = handler.performAction.call(this, target, settings); } if(result === false){ return false; } settings.result = result; var outcome = target.resolveAction(action, this, settings); if(outcome && handler.afterPerformActionSuccess){ handler.afterPerformActionSuccess.call(this, target, settings); } else if(!outcome && handler.afterPerformActionFailure){ handler.afterPerformActionFailure.call(this, target, settings); } return outcome; }
javascript
{ "resource": "" }
q33711
train
function(action, implementation){ this.resolvableActions = this.resolvableActions || {}; this.resolvableActions[action] = this.resolvableActions[action] || {}; this.resolvableActions[action].actionName = this.resolvableActions[action].actionName || action; implementation = implementation || RL.ResolvableAction.Types[action]; this.resolvableActions[action] = Object.create(implementation); // merge could be used instead of Object.create but is less desirable // RL.Util.merge(this.resolvableAction.Types[action], implementation); if(this.resolvableActions[action].init){ this.resolvableActions[action].init.call(this); } }
javascript
{ "resource": "" }
q33712
train
function(action, source, settings){ if(!this.resolvableActions){ return false; } var handler = this.resolvableActions[action]; if(!handler){ return false; } if(handler.canResolveAction === false){ return false; } if(handler.canResolveAction === true){ return true; } return handler.canResolveAction.call(this, source, settings); }
javascript
{ "resource": "" }
q33713
train
function(action, source, settings){ if(!this.resolvableActions){ return false; } var handler = this.resolvableActions[action]; if(!handler){ return false; } settings = settings || {}; if(!settings.skipCanResolveAction && !this.canResolveAction(action, source, settings)){ return false; } if(handler.resolveAction === false){ return false; } if(handler.resolveAction === true){ return true; } return handler.resolveAction.call(this, source, settings); }
javascript
{ "resource": "" }
q33714
train
function (metric) { var now = (new Date().getTime()).toFixed(0) var line = null if (metric.sct === 'OS' && /collectd/.test(metric.name)) { line = this.collectdFormatLine(metric) } else { if (metric.sct === 'OS') { // new OS metric format if (metric.filters instanceof Array) { line = util.format('%d\t%s\t%d\t%s\t%s', now, metric.name, metric.ts, formatArray(metric.filters), formatArray(metric.value)) } else { line = util.format('%d\t%s\t%d\t%s', now, metric.name, metric.ts, formatArray(metric.value)) } logger.log(line) } else { line = util.format('%d\t%s\t%d\t%s\t%s', now, (metric.type || this.defaultType) + '-' + metric.name, metric.ts, formatArray(metric.filters), formatArray(metric.value)) logger.log(line) } } return line }
javascript
{ "resource": "" }
q33715
monitor
train
function monitor() { if(!child.pid) { // If the number of periodic starts exceeds the max, kill the process if (starts >= options.maxRetries) { if ((Date.now() - startTime) > maxMilliseconds) { console.error( `Too many restarts within the last ${maxMilliseconds / 1000} seconds. Please check the script.` ) process.exit(1) } } setTimeout(() => { wait = wait * options.growPercentage attempts += 1; if (attempts > options.maxRestarts && options.maxRestarts >= 0){ console.error( `${options.name} will not be restarted because the maximum number of total restarts has been exceeded.` ) process.exit() } else { launch() } }, wait) } else { attempts = 0 wait = options.restartDelay * 1000 } }
javascript
{ "resource": "" }
q33716
Game
train
function Game() { // un-populated instance of Array2d this.map = new RL.Map(this); this.entityManager = new RL.ObjectManager(this, RL.Entity); this.renderer = new RL.Renderer(this); this.console = new RL.Console(this); this.lighting = new RL.LightingROT(this); // player purposefully not added to entity manager (matter of preference) this.player = new RL.Player(this); // make sure "this" is this instance of Game when this.onKeyAction is called this.onKeyAction = this.onKeyAction.bind(this); this.onClick = this.onClick.bind(this); this.onHover = this.onHover.bind(this); this.input = new RL.Input(this.onKeyAction); this.mouse = new RL.Mouse(this.onClick, this.onHover); var el = this.renderer.canvas; this.mouse.startListening(el); }
javascript
{ "resource": "" }
q33717
train
function(width, height){ this.map.setSize(width, height); this.player.fov.setSize(width, height); this.entityManager.setSize(width, height); this.lighting.setSize(width, height); }
javascript
{ "resource": "" }
q33718
train
function(action) { if(!this.gameOver){ var result = this.player.update(action); if(result){ this.entityManager.update(this.player); this.player.updateFov(); this.lighting.update(); this.renderer.setCenter(this.player.x, this.player.y); this.renderer.draw(); } else if(this.queueDraw){ this.renderer.draw(); } } this.queueDraw = false; }
javascript
{ "resource": "" }
q33719
train
function(x, y){ var coords = this.renderer.mouseToTileCoords(x, y), tile = this.map.get(coords.x, coords.y); if(!tile){ return; } var entityTile = this.entityManager.get(tile.x, tile.y); if(entityTile){ this.console.log('Looks like a <strong>' + entityTile.name + '</strong> standing on a <strong>' + tile.name + '</strong> to me.'); } else{ this.console.log('Looks like a <strong>' + tile.name + '</strong> to me.'); } }
javascript
{ "resource": "" }
q33720
train
function(x, y){ var coords = this.renderer.mouseToTileCoords(x, y), tile = this.map.get(coords.x, coords.y); if(tile){ this.renderer.hoveredTileX = tile.x; this.renderer.hoveredTileY = tile.y; } else { this.renderer.hoveredTileX = null; this.renderer.hoveredTileY = null; } this.renderer.draw(); }
javascript
{ "resource": "" }
q33721
train
function(x, y){ var result = []; var entity = this.entityManager.get(x, y); if(entity){ result.push(entity); } // add items or any other objects that can be placed at a tile coord position return result; }
javascript
{ "resource": "" }
q33722
train
function(entity, x, y){ var tile = this.map.get(x, y); // if tile blocks movement if(!tile || !tile.passable){ return false; } return true; }
javascript
{ "resource": "" }
q33723
train
function(entity, x, y){ if(!this.entityCanMoveThrough(entity, x, y)){ return false; } // check if occupied by entity if(this.entityManager.get(x, y)){ return false; } return true; }
javascript
{ "resource": "" }
q33724
train
function(entity, x, y){ var tile = this.map.get(x, y); return tile && !tile.blocksLos; }
javascript
{ "resource": "" }
q33725
handleRecipeFiles
train
function handleRecipeFiles(folderPath) { if (handled[folderPath]) { return; } handled[folderPath] = true; handleRecipeFile(path.join(folderPath, 'tsconfig.json')); handleRecipeFiles(path.dirname(folderPath)); }
javascript
{ "resource": "" }
q33726
handleRecipeFile
train
function handleRecipeFile(recipePath) { var contents = null; try { contents = fs.readFileSync(recipePath); } catch (err) { // Not finding a recipe is OK return; } var config = null; try { config = JSON.parse(contents.toString()); } catch (err) { // Finding a recipe that cannot be parsed is a disaster console.log('Error in parsing JSON for ' + recipePath); process.exit(-1); } // Determine the glob patterns var filesGlob = ['**/*.ts']; if (typeof config.filesGlob === 'string') { filesGlob = [config.filesGlob]; } else if (Array.isArray(config.filesGlob)) { filesGlob = config.filesGlob; } var resultConfig = {}; for (var prop in config) { resultConfig[prop] = config[prop]; } resultConfig.files = findFiles(recipePath, filesGlob); var resultTxt = JSON.stringify(resultConfig, null, ' '); var resultPath = path.join(path.dirname(recipePath), 'tsconfig.json'); fs.writeFileSync(resultPath, resultTxt); console.log('Updated ' + resultPath); }
javascript
{ "resource": "" }
q33727
middleware
train
function middleware (opts) { opts = Object.assign({maxSize: 100, logAll: false}, opts) const log = opts.logAll ? new CustomLog() : void (0) const loggers = new Loggers(opts.maxSize) return function (req, res) { let query = req.query if (!req.query) { query = qsParse(urlParse(req.url).query) } res.setHeader('Cache-Control', 'no-store, no-cache') res.write(gif) res.end() const str = query.log if (!str) return if (/^{.*?}\s*$/.test(str)) { // check if `str` looks like JSON try { const obj = JSON.parse(str) const level = adjustLevel(String(obj.level), DEBUG) const name = String(obj.name).substr(0, 50) if (obj.name && name) { const l = loggers.get(name) if (l.enabled[level]) { if (req.ip) obj.ip = req.ip delete obj.name delete obj.level l._log(level, [obj]) } return } } catch (e) {} } log && log.log(str) } }
javascript
{ "resource": "" }
q33728
train
function(base){ if(typeof base === 'undefined'){ throw new Error("Too few arguments in RollingHash constructor"); }else if(typeof base !== 'number'){ throw new TypeError("Invalid argument; expected a number in RollingHash constructor"); } // The base of the number system this.BASE = base; // The internal hash value of the window this.state = 0; // A block of expensive code we will cache in order to optimize runtime this.CACHE = 1; // The amount of digits a number can hold given the base // TODO: unused.. figure out why I thought I needed this this.BUFFER_SIZE = Math.log(base) * Math.LOG10E + 1 | 0; // The modular inverse of the base this.INVERSE_BASE = modInverse(this.BASE, PRIME_BASE) % PRIME_BASE; // An offset to add when calculating a modular product, to make sure it can not go negative this.OFFSET_IF_NEGATIVE = PRIME_BASE * this.BASE; }
javascript
{ "resource": "" }
q33729
Lexerific
train
function Lexerific(config, _, FSM, Lexeme, StateGenerator, Token, TreeNode) { var _this = this; this._ = _; // Create a finite state machine for lexing this.fsm = new FSM({ name: 'lexerific', debug: true, resetAtRoot: true // erase history for every root bound transition }); this.fsm.on('return', function (data) { _this.push(data.toObject()); }); this.Lexeme = Lexeme; this.Token = Token; this.stateGenerator = new StateGenerator(this._, this.Token, TreeNode); /** * Either 'string' or 'token' to determine what type of input stream to expect */ this._mode = config.mode; /** * In `string` mode, we need a list of regular expression patterns (as strings) * to differentiate between text that is important in our lexicon and text * that is not. */ this._specialCharacters = config.specialCharacters; /** * Indicates whether the FSM has been initialized with all of the states */ this._isReady = false; // We always read and write token objects TransformStream.call(this, { objectMode: true, readableObjectMode: true, writableObjectMode: true }); }
javascript
{ "resource": "" }
q33730
train
function() { return { char: this.char, color: this.color, bgColor: this.bgColor, borderColor: this.borderColor, borderWidth: this.borderWidth, charStrokeColor: this.charStrokeColor, charStrokeWidth: this.charStrokeWidth, font: this.font, fontSize: this.fontSize, textAlign: this.textAlign, textBaseline: this.textBaseline, offsetX: this.offsetX, offsetY: this.offsetY, }; }
javascript
{ "resource": "" }
q33731
train
function(defaults, settings) { var out = {}; for (var key in defaults) { if (key in settings) { out[key] = settings[key]; } else { out[key] = defaults[key]; } } return out; }
javascript
{ "resource": "" }
q33732
train
function(destination){ var sources = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < sources.length; i++) { var source = sources[i]; for(var key in source){ destination[key] = source[key]; } } return destination; }
javascript
{ "resource": "" }
q33733
train
function(x1, y1, x2, y2, diagonalMovement){ if(!diagonalMovement){ return Math.abs(x2 - x1) + Math.abs(y2 - y1); } else { return Math.max(Math.abs(x2 - x1), Math.abs(y2 - y1)); } }
javascript
{ "resource": "" }
q33734
train
function(jsStr, __parObj){ if (!__parObj){ return eval(jsStr); }; var s = ""; var n; for (n in __parObj){ s += "var " + n + " = __parObj." + n + ";"; }; //s = "(function(){" + s; s += jsStr; //s += "})();"; return eval(s); }
javascript
{ "resource": "" }
q33735
HlrLookupClient
train
function HlrLookupClient(username, password, noSsl) { this.username = username; this.password = password; this.url = (noSsl ? 'http' : 'https') + '://www.hlr-lookups.com/api'; }
javascript
{ "resource": "" }
q33736
RendererLayer
train
function RendererLayer(game, type, settings) { this.game = game; this.type = type; var typeData = RendererLayer.Types[type]; RL.Util.merge(this, typeData); for(var key in settings){ if(this[key] !== void 0){ this[key] = settings[key]; } } }
javascript
{ "resource": "" }
q33737
train
function(x, y, prevTileData){ var tileData = this.getTileData(x, y, prevTileData); if(this.mergeWithPrevLayer && prevTileData){ return this.mergeTileData(prevTileData, tileData); } return tileData; }
javascript
{ "resource": "" }
q33738
train
function(tileData1, tileData2){ var result = {}, key, val; for(key in tileData1){ result[key] = tileData1[key]; } for(key in tileData2){ val = tileData2[key]; if(val !== false && val !== void 0){ result[key] = val; } } return result; }
javascript
{ "resource": "" }
q33739
endStream
train
function endStream(cb) { // If no files were passed in, no files go out ... if (!latestFile || (Object.keys(concats).length === 0 && concats.constructor === Object)) { cb(); return; } // Prepare a method for pushing the stream const pushJoinedFile = (joinedBase) => { const joinedFile = new File({ path: joinedBase, contents: concats[joinedBase].concat.content, stat: concats[joinedBase].stats }); if (concats[joinedBase].concat.sourceMapping) { joinedFile.sourceMap = JSON.parse(concats[joinedBase].concat.sourceMap); } this.push(joinedFile); delete concats[joinedBase]; }; // Refine the dependency graph const refinedDependencyMap = []; dependencyGraph.forEach(edge => { if ((edge[0] in nameBaseMap) && (edge[1] in nameBaseMap)) { refinedDependencyMap.push([nameBaseMap[edge[0]], nameBaseMap[edge[1]]]); } }); const sortedDependencies = refinedDependencyMap.length ? toposort(refinedDependencyMap).reverse() : []; sortedDependencies.map(pushJoinedFile); // Run through all registered contact instances for (const targetBase in concats) { pushJoinedFile(targetBase); } cb(); }
javascript
{ "resource": "" }
q33740
ContentRange
train
function ContentRange(unit, range, length) { this.unit = unit; this.range = range; this.length = length; if (this.range.high && this.length && this.length <= this.range.high) { throw new Error('Length is less than or equal to the range'); } }
javascript
{ "resource": "" }
q33741
load
train
function load() { Desktop.fetch('localStorage', 'getAll').then((storage) => { Meteor._localStorage.storage = storage; }).catch(() => { retries += 1; if (retries < 5) { load(); } else { console.error('failed to load localStorage contents'); } }); }
javascript
{ "resource": "" }
q33742
LightingROT
train
function LightingROT(game, settings) { settings = settings || {}; this.game = game; this.lightingMap = new RL.Array2d(); this.lightingMap.set = this.lightingMap.set.bind(this.lightingMap); this.checkVisible = this.checkVisible.bind(this); this._fov = new ROT.FOV.PreciseShadowcasting(this.checkVisible); settings = RL.Util.mergeDefaults({ range: 5, passes: 2, emissionThreshold: 100, }, settings); this.getTileReflectivity = this.getTileReflectivity.bind(this); this._lighting = new ROT.Lighting(this.getTileReflectivity, settings); this._lighting.setFOV(this._fov); // copy instance this.ambientLight = this.ambientLight.slice(); }
javascript
{ "resource": "" }
q33743
train
function(x, y, tileData){ var light = this.ambientLight; var lighting = this.get(x, y); var overlay = function(c1, c2){ var out = c1.slice(); for (var i = 0; i < 3; i++) { var a = c1[i], b = c2[i]; if(b < 128){ out[i] = Math.round(2 * a * b / 255); } else { out[i] = Math.round(255 - 2 * (255 - a) * (255 - b) / 255); } } return out; }; if(lighting){ light = ROT.Color.add(this.ambientLight, lighting); } if(tileData.color){ var color = ROT.Color.fromString(tileData.color); color = overlay(light, color); tileData.color = ROT.Color.toRGB(color); } if(tileData.bgColor){ var bgColor = ROT.Color.fromString(tileData.bgColor); bgColor = overlay(light, bgColor); tileData.bgColor = ROT.Color.toRGB(bgColor); } return tileData; }
javascript
{ "resource": "" }
q33744
train
function(x, y, r, g, b){ this._lighting.setLight(x, y, [r, g, b]); this._dirty = true; }
javascript
{ "resource": "" }
q33745
train
function(x, y){ var tile = this.game.map.get(x, y); if(!tile){ return 0; } if(tile.lightingReflectivity){ return tile.lightingReflectivity; } if(tile.blocksLos){ return this.defaultWallReflectivity; } else { return this.defaultFloorReflectivity; } }
javascript
{ "resource": "" }
q33746
train
function(next) { if (!inNativeApp) return next(null, false, null, null, null); if (resourceIsBinary(filePath)) { var fullPath = shared.removeUrlMultislashes(fileFullPathRoot + '/' + filePath), xhr; xhr = new XMLHttpRequest(); xhr.open("GET", cacheUrl, true); xhr.responseType = "blob"; xhr.onload = function(e) { next(null, true, fullPath, xhr.response, null); }; xhr.onerror = function(e) { next(null, false) } xhr.send(null); } else { ajax(cacheUrl, null, compileData, function(err, data, compiled) { next(null, !err, null, data, compiled); }); } }
javascript
{ "resource": "" }
q33747
train
function(foundInCacheSeed, fullPath, data, compiled, next) { if (foundInCacheSeed) { debugLog("Found resource in cache seed: " + cacheUrl) if (data) { async.waterfall([ function(next) { if (url.match(/\.css$/)) { processStylesheet(rootUrl, version, url, data, timeout, onCacheMiss, next); } else { next(null, data); } }, ], function(err, data) { if (err) return next(err); writeToFile(filePath, data, function(err, fullPath) { next(err, fullPath, data, compiled, null); }); }); } else { next(null, fullPath, data, compiled, null); } } else { getServerResource(next); } }
javascript
{ "resource": "" }
q33748
UInt
train
function UInt(args) { // Assign default valus this._value = null; this._bytes = null; this._bits = null; this._isHex = false; // Set constraints if present if(args && (isNatural(args.bits) || isNatural(args.bytes))) { // Set the size if either is used this._bits = args.bits || 0; this._bytes = args.bytes || 0; // Normalize the byte/bit counts this._bytes += Math.floor(this._bits / 8); this._bits = this._bits % 8; } // Set the value and check if present if(args && (_(args.value).isNumber() || _(args.value).isString() || _(args.value).isArray())) { var result = normalize(args.value); this._value = result.value; // Set the sizes or validate if present if(_(this._bytes).isNull() && _(this._bits).isNull()) { this._bytes = result.bytes; this._bits = result.bits; } else if(this._bytes < result.bytes || (this._bytes === result.bytes && this._bits < result.bits)) { throw 'Value is larger than size constraints: ' + args.value + ' ' + this._bytes + ':' + this._bits; } // Insert any necessary leading zeros if(_(this._value).isArray()) { _(this._bytes - this._value.length).times(function() { this._value.splice(0, 0, 0); }, this); // Handle the case of user supplied array boundary but small value } else if(this._bytes > 4) { var tmp = []; _(this._bytes).times(function(i) { if(i < 4) { tmp.splice(0, 0, this._value % 256); this._value = Math.floor(this._value / 256); } else { tmp.splice(0, 0, 0); } }, this); this._value = tmp; } } //Set isHex if string starts with 0x if(args && _(args.value).isString()){ var arr = args.value.match(/^0x/i); if(arr !== null){ this._isHex = true; } else{ this._isHex = false; } } }
javascript
{ "resource": "" }
q33749
reduceRight
train
function reduceRight(collection, callback, accumulator, thisArg) { if (!collection) { return accumulator; } var length = collection.length, noaccum = arguments.length < 3; if(thisArg) { callback = iteratorBind(callback, thisArg); } if (length === length >>> 0) { if (length && noaccum) { accumulator = collection[--length]; } while (length--) { accumulator = callback(accumulator, collection[length], length, collection); } return accumulator; } var prop, props = keys(collection); length = props.length; if (length && noaccum) { accumulator = collection[props[--length]]; } while (length--) { prop = props[length]; accumulator = callback(accumulator, collection[prop], prop, collection); } return accumulator; }
javascript
{ "resource": "" }
q33750
toArray
train
function toArray(collection) { if (!collection) { return []; } if (toString.call(collection.toArray) == funcClass) { return collection.toArray(); } var length = collection.length; if (length === length >>> 0) { return slice.call(collection); } return values(collection); }
javascript
{ "resource": "" }
q33751
initial
train
function initial(array, n, guard) { if (!array) { return []; } return slice.call(array, 0, -((n == undefined || guard) ? 1 : n)); }
javascript
{ "resource": "" }
q33752
intersection
train
function intersection(array) { var result = []; if (!array) { return result; } var value, index = -1, length = array.length, others = slice.call(arguments, 1); while (++index < length) { value = array[index]; if (indexOf(result, value) < 0 && every(others, function(other) { return indexOf(other, value) > -1; })) { result.push(value); } } return result; }
javascript
{ "resource": "" }
q33753
last
train
function last(array, n, guard) { if (array) { var length = array.length; return (n == undefined || guard) ? array[length - 1] : slice.call(array, -n || length); } }
javascript
{ "resource": "" }
q33754
union
train
function union() { var index = -1, result = [], flattened = concat.apply(result, arguments), length = flattened.length; while (++index < length) { if (indexOf(result, flattened[index]) < 0) { result.push(flattened[index]); } } return result; }
javascript
{ "resource": "" }
q33755
bind
train
function bind(func, thisArg) { var methodName, isFunc = toString.call(func) == funcClass; // juggle arguments if (!isFunc) { methodName = thisArg; thisArg = func; } // use if `Function#bind` is faster else if (nativeBind) { return nativeBind.call.apply(nativeBind, arguments); } var partialArgs = slice.call(arguments, 2); function bound() { // `Function#bind` spec // http://es5.github.com/#x15.3.4.5 var args = arguments, thisBinding = thisArg; if (!isFunc) { func = thisArg[methodName]; } if (partialArgs.length) { args = args.length ? concat.apply(partialArgs, args) : partialArgs; } if (this instanceof bound) { // get `func` instance if `bound` is invoked in a `new` expression noop.prototype = func.prototype; thisBinding = new noop; // mimic the constructor's `return` behavior // http://es5.github.com/#x13.2.2 var result = func.apply(thisBinding, args); return valueTypes[typeof result] && result !== null ? result : thisBinding } return func.apply(thisBinding, args); } return bound; }
javascript
{ "resource": "" }
q33756
bindAll
train
function bindAll(object) { var funcs = arguments, index = 1; if (funcs.length == 1) { index = 0; funcs = functions(object); } for (var length = funcs.length; index < length; index++) { object[funcs[index]] = bind(object[funcs[index]], object); } return object; }
javascript
{ "resource": "" }
q33757
debounce
train
function debounce(func, wait, immediate) { var args, result, thisArg, timeoutId; function delayed() { timeoutId = undefined; if (!immediate) { func.apply(thisArg, args); } } return function() { var isImmediate = immediate && !timeoutId; args = arguments; thisArg = this; clearTimeout(timeoutId); timeoutId = setTimeout(delayed, wait); if (isImmediate) { result = func.apply(thisArg, args); } return result; }; }
javascript
{ "resource": "" }
q33758
memoize
train
function memoize(func, resolver) { var cache = {}; return function() { var prop = resolver ? resolver.apply(this, arguments) : arguments[0]; return hasOwnProperty.call(cache, prop) ? cache[prop] : (cache[prop] = func.apply(this, arguments)); }; }
javascript
{ "resource": "" }
q33759
once
train
function once(func) { var result, ran = false; return function() { if (ran) { return result; } ran = true; result = func.apply(this, arguments); return result; }; }
javascript
{ "resource": "" }
q33760
throttle
train
function throttle(func, wait) { var args, result, thisArg, timeoutId, lastCalled = 0; function trailingCall() { lastCalled = new Date; timeoutId = undefined; func.apply(thisArg, args); } return function() { var now = new Date, remain = wait - (now - lastCalled); args = arguments; thisArg = this; if (remain <= 0) { lastCalled = now; result = func.apply(thisArg, args); } else if (!timeoutId) { timeoutId = setTimeout(trailingCall, remain); } return result; }; }
javascript
{ "resource": "" }
q33761
wrap
train
function wrap(func, wrapper) { return function() { var args = [func]; if (arguments.length) { push.apply(args, arguments); } return wrapper.apply(this, args); }; }
javascript
{ "resource": "" }
q33762
pick
train
function pick(object) { var prop, index = 0, props = concat.apply(ArrayProto, arguments), length = props.length, result = {}; // start `index` at `1` to skip `object` while (++index < length) { prop = props[index]; if (prop in object) { result[prop] = object[prop]; } } return result; }
javascript
{ "resource": "" }
q33763
size
train
function size(value) { var className = toString.call(value); return className == arrayClass || className == stringClass ? value.length : keys(value).length; }
javascript
{ "resource": "" }
q33764
result
train
function result(object, property) { // based on Backbone's private `getValue` function // https://github.com/documentcloud/backbone/blob/0.9.9/backbone.js#L1419-1424 if (!object) { return null; } var value = object[property]; return toString.call(value) == funcClass ? object[property]() : value; }
javascript
{ "resource": "" }
q33765
template
train
function template(text, data, options) { options || (options = {}); var result, defaults = lodash.templateSettings, escapeDelimiter = options.escape, evaluateDelimiter = options.evaluate, interpolateDelimiter = options.interpolate, variable = options.variable; // use template defaults if no option is provided if (escapeDelimiter == null) { escapeDelimiter = defaults.escape; } if (evaluateDelimiter == null) { evaluateDelimiter = defaults.evaluate; } if (interpolateDelimiter == null) { interpolateDelimiter = defaults.interpolate; } // tokenize delimiters to avoid escaping them if (escapeDelimiter) { text = text.replace(escapeDelimiter, tokenizeEscape); } if (interpolateDelimiter) { text = text.replace(interpolateDelimiter, tokenizeInterpolate); } if (evaluateDelimiter) { text = text.replace(evaluateDelimiter, tokenizeEvaluate); } // escape characters that cannot be included in string literals and // detokenize delimiter code snippets text = "__p='" + text .replace(reUnescapedString, escapeStringChar) .replace(reToken, detokenize) + "';\n"; // clear stored code snippets tokenized.length = 0; // if `options.variable` is not specified, add `data` to the top of the scope chain if (!variable) { variable = defaults.variable; text = 'with (' + variable + ' || {}) {\n' + text + '\n}\n'; } text = 'function(' + variable + ') {\n' + 'var __p, __t, __j = Array.prototype.join;\n' + 'function print() { __p += __j.call(arguments, \'\') }\n' + text + 'return __p\n}'; // add a sourceURL for easier debugging // http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl if (useSourceURL) { text += '\n//@ sourceURL=/lodash/template/source[' + (templateCounter++) + ']'; } result = Function('_', 'return ' + text)(lodash); if (data) { return result(data); } // provide the compiled function's source via its `toString()` method, in // supported environments, or the `source` property as a convenience for // build time precompilation result.source = text; return result; }
javascript
{ "resource": "" }
q33766
FidonetURL
train
function FidonetURL(initialString){ if(!( this instanceof FidonetURL )){ return new FidonetURL(initialString); } parseFundamentalSections.call(this, initialString); parseOptionalPart.call(this); parseRequiredPart.call(this); }
javascript
{ "resource": "" }
q33767
checking
train
function checking(desc, args, body, n, options) { if (typeof n === 'undefined') { n = 1000; options = {}; } if (typeof options === 'undefined' && typeof n !== 'number') { options = n; n = 1000; } it(desc, function() { checkers.forAll(args, body).check(n, options); }); }
javascript
{ "resource": "" }
q33768
train
function(str, maxWidth) { var result = []; /* first tokenization pass - split texts and color formatting commands */ var offset = 0; str.replace(this.RE_COLORS, function(match, type, name, index) { /* string before */ var part = str.substring(offset, index); if (part.length) { result.push({ type: ROT.Text.TYPE_TEXT, value: part }); } /* color command */ result.push({ type: (type == "c" ? ROT.Text.TYPE_FG : ROT.Text.TYPE_BG), value: name.trim() }); offset = index + match.length; return ""; }); /* last remaining part */ var part = str.substring(offset); if (part.length) { result.push({ type: ROT.Text.TYPE_TEXT, value: part }); } return this._breakLines(result, maxWidth); }
javascript
{ "resource": "" }
q33769
train
function(color1, color2) { var result = color1.slice(); for (var i=0;i<3;i++) { for (var j=1;j<arguments.length;j++) { result[i] += arguments[j][i]; } } return result; }
javascript
{ "resource": "" }
q33770
train
function(color1, color2) { for (var i=0;i<3;i++) { for (var j=1;j<arguments.length;j++) { color1[i] += arguments[j][i]; } } return color1; }
javascript
{ "resource": "" }
q33771
train
function(color, diff) { if (!(diff instanceof Array)) { diff = ROT.RNG.getNormal(0, diff); } var result = color.slice(); for (var i=0;i<3;i++) { result[i] += (diff instanceof Array ? Math.round(ROT.RNG.getNormal(0, diff[i])) : diff); } return result; }
javascript
{ "resource": "" }
q33772
train
function(color) { var l = color[2]; if (color[1] == 0) { l = Math.round(l*255); return [l, l, l]; } else { function hue2rgb(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1/6) return p + (q - p) * 6 * t; if (t < 1/2) return q; if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; } var s = color[1]; var q = (l < 0.5 ? l * (1 + s) : l + s - l * s); var p = 2 * l - q; var r = hue2rgb(p, q, color[0] + 1/3); var g = hue2rgb(p, q, color[0]); var b = hue2rgb(p, q, color[0] - 1/3); return [Math.round(r*255), Math.round(g*255), Math.round(b*255)]; } }
javascript
{ "resource": "" }
q33773
dict
train
function dict(options = {}) { if (options.lowerCase) { return dictCache[0] || (dictCache[0] = require("../dict/lc-dictionary.json")); } else { return dictCache[1] || (dictCache[1] = require("../dict/dictionary.json")); } }
javascript
{ "resource": "" }
q33774
correctWordsFor
train
function correctWordsFor(word, options = {}) { word = String(word || ""); const found = (options.caseSensitive ? dict()[word] : dict({ lowerCase: true })[word.toLowerCase()] ); return found ? found.split(",") : []; }
javascript
{ "resource": "" }
q33775
correct
train
function correct(str, options, callback) { if (typeof options === "function") { callback = options; options = {}; } const {caseSensitive, overrideCases} = options || {}; str = String(str || ""); const dic = dict({ lowerCase: true }); const re = regexp(caseSensitive ? "g" : "ig"); return str.replace(re, (misspell) => { const csv = dic[misspell.toLowerCase()]; if (!csv) return misspell; const corrects = csv.split(","); let corrected; if (callback) { corrected = callback(misspell, corrects); if (typeof corrected === "undefined" || corrected === null) return misspell; corrected = String(corrected); } else { corrected = corrects[0]; } if (!overrideCases) { corrected = mapCases(misspell, corrected); } return corrected; }); }
javascript
{ "resource": "" }
q33776
Renderer
train
function Renderer(game, width, height, tileSize, canvasClassName) { this.layers = []; this.game = game; this.canvas = document.createElement('canvas'); this.ctx = this.canvas.getContext('2d'); this.canvas.className = canvasClassName || 'renderer'; this.buffer = this.canvas.cloneNode(); this.bufferCtx = this.buffer.getContext('2d'); this.tileSize = tileSize || this.tileSize; this.resize(width, height); }
javascript
{ "resource": "" }
q33777
train
function(x, y, tileData, ctx) { ctx = ctx || this.bufferCtx; var originalX = x, originalY = y; x -= this.originX; y -= this.originY; if(tileData.bgColor){ ctx.fillStyle = tileData.bgColor; ctx.fillRect( x * this.tileSize, y * this.tileSize, this.tileSize, this.tileSize ); } if(tileData.before !== void 0){ this.drawTileToCanvas(originalX, originalY, tileData.before, ctx); } if(tileData.char && tileData.color){ if(tileData.mask){ ctx.save(); ctx.beginPath(); ctx.rect( x * this.tileSize, y * this.tileSize, this.tileSize, this.tileSize ); ctx.clip(); ctx.closePath(); } var fontSize = tileData.fontSize || this.tileSize; var textX = x * (this.tileSize) + (this.tileSize * 0.5) + (tileData.offsetX || 0); var textY = y * (this.tileSize) + (this.tileSize * 0.5) + (tileData.offsetY || 0); ctx.fillStyle = tileData.color; ctx.textAlign = tileData.textAlign || 'center'; ctx.textBaseline = tileData.textBaseline || 'middle'; ctx.font = fontSize + 'px ' + (tileData.font || this.font); if(tileData.charStrokeColor){ ctx.strokeStyle = tileData.charStrokeColor; ctx.lineWidth = tileData.charStrokeWidth || 1; ctx.strokeText( tileData.char, textX, textY ); ctx.strokeText( tileData.char, textX, textY+1 ); } ctx.fillText( tileData.char, textX, textY ); if(tileData.mask){ ctx.restore(); } } if(tileData.after !== void 0){ this.drawTileToCanvas(originalX, originalY, tileData.after, ctx); } if(tileData.borderColor){ var borderWidth = tileData.borderWidth || 1; var borderOffset = Math.floor(borderWidth * 0.5); var borderRectSize = this.tileSize - borderWidth; if(borderWidth % 2 !== 0){ borderOffset += 0.5; } ctx.lineWidth = borderWidth; ctx.strokeStyle = tileData.borderColor; var bx = x * this.tileSize + borderOffset; var by = y * this.tileSize + borderOffset; ctx.strokeRect(bx, by, borderRectSize, borderRectSize); } }
javascript
{ "resource": "" }
q33778
train
function(x, y){ var pos = this.canvas.getBoundingClientRect(), mx = x - pos.left, my = y - pos.top; return this.pixelToTileCoords(mx, my); }
javascript
{ "resource": "" }
q33779
train
function(x, y){ return { x: Math.floor(x / this.tileSize) + this.originX, y: Math.floor(y / this.tileSize) + this.originY }; }
javascript
{ "resource": "" }
q33780
train
function(color, ctx){ ctx = ctx || this.bufferCtx; ctx.fillStyle = color || this.bgColor; ctx.fillRect( 0, 0, this.canvas.width, this.canvas.height ); }
javascript
{ "resource": "" }
q33781
train
function(width, height) { this.width = width; this.height = height; for (var i = 0; i < this.width; i++) { if(!this.data){ this.data = []; } if(this.data[i] === void 0){ this.data[i] = []; } } }
javascript
{ "resource": "" }
q33782
train
function(x, y, settings) { settings = settings || {}; var filter = settings.filter !== void 0 ? settings.filter : false, withCoords = settings.withCoords !== void 0 ? settings.withCoords : false, withDiagonals = settings.withDiagonals !== void 0 ? settings.withDiagonals : true; var _this = this, out = [], ax, ay; var add = function(x, y) { var val = _this.get(x, y); if (filter === false || (filter(val, x, y))) { if (withCoords) { out.push({ x: x, y: y, value: val }); } else { out.push(val); } } }; // top ax = x; ay = y - 1; add(ax, ay); // bottom ax = x; ay = y + 1; add(ax, ay); // left ax = x - 1; ay = y; add(ax, ay); // right ax = x + 1; ay = y; add(ax, ay); if(withDiagonals){ // top left ax = x - 1; ay = y - 1; add(ax, ay); // top right ax = x + 1; ay = y - 1; add(ax, ay); // bottom left ax = x - 1; ay = y + 1; add(ax, ay); // bottom right ax = x + 1; ay = y + 1; add(ax, ay); } return out; }
javascript
{ "resource": "" }
q33783
train
function(x, y, settings) { settings = settings || {}; var radius = settings.radius || 1, filter = settings.filter || false, withCoords = settings.withCoords || false, includeTarget = settings.includeTarget || false; var tileX = x, tileY = y; var minX = tileX - radius, maxX = tileX + radius, minY = tileY - radius, maxY = tileY + radius, output = [], val; if (minX < 0) { minX = 0; } if (minY < 0) { minY = 0; } if (maxX > this.width - 1) { maxX = this.width - 1; } if (maxY > this.height - 1) { maxY = this.height - 1; } for (x = minX; x <= maxX; x++) { for (y = minY; y <= maxY; y++) { if (!includeTarget && tileX === x && tileY === y) { continue; } val = this.data[x][y]; if (filter === false || filter(val, x, y)) { if (withCoords) { output.push({ x: x, y: y, value: val }); } else { output.push(val); } } } } return output; }
javascript
{ "resource": "" }
q33784
train
function(x0, y0, x1, y1, condition, withCoords) { withCoords = withCoords || false; condition = condition || false; var output = [], dx = Math.abs(x1 - x0), dy = Math.abs(y1 - y0), sx = (x0 < x1) ? 1 : -1, sy = (y0 < y1) ? 1 : -1, err = dx - dy, e2, val; while (true) { if (x0 < 0 || x0 >= this.width || y0 < 0 || y0 >= this.height) { break; } val = this.get(x0, y0); if (withCoords) { output.push({ x: x0, y: y0, value: val }); } else { output.push(val); } if (condition !== false && condition(val, x0, y0)) { break; } e2 = 2 * err; if (e2 > -dy) { err -= dy; x0 += sx; } if (e2 < dx) { err += dx; y0 += sy; } } return output; }
javascript
{ "resource": "" }
q33785
train
function(startX, startY, settings) { settings = settings || {}; var maxRadius = settings.maxRadius || 1, filter = settings.filter || false, withCoords = settings.withCoords || false; var currentDistance = 1, results = [], x, y; var checkVal = function(val, x, y) { var result; if ((filter && filter(val, x, y)) || (!filter && val)) { if (withCoords) { results.push({ x: x, y: y, value: val }); } else { return results.push(val); } } }; while (currentDistance <= maxRadius) { var minX = startX - currentDistance, maxX = startX + currentDistance, minY = startY - currentDistance, maxY = startY + currentDistance, len = currentDistance * 2 + 1; for (var i = len - 1; i >= 0; i--) { var val; // top and bottom edges skip first and last coords to prevent double checking if (i < len - 1 && i > 0) { // top edge if (minY >= 0) { x = minX + i; y = minY; val = this.get(x, y); checkVal(val, x, y); } if (maxY < this.height) { // bottom edge x = minX + i; y = maxY; val = this.get(x, y); checkVal(val, x, y); } } if (minX >= 0) { // left edge x = minX; y = minY + i; val = this.get(x, y); checkVal(val, x, y); } if (maxX < this.width) { // right edge x = maxX; y = minY + i; val = this.get(x, y); checkVal(val, x, y); } } if (results.length) { return results; } currentDistance++; } return false; }
javascript
{ "resource": "" }
q33786
train
function(filter, withCoords){ withCoords = withCoords || false; var output = []; for (var x = 0; x < this.width; x++) { for (var y = 0; y < this.height; y++) { var val = this.get(x, y); if(filter(val, x, y)){ if (withCoords) { output.push({ x: x, y: y, value: val }); } else { output.push(val); } } } } return output; }
javascript
{ "resource": "" }
q33787
train
function(){ var newArray = new Array2d(this.width, this.height); for(var x = this.width - 1; x >= 0; x--){ for(var y = this.height - 1; y >= 0; y--){ var val = this.get(x, y); if(val !== void 0){ newArray.set(x, y, val); } } } return newArray; }
javascript
{ "resource": "" }
q33788
train
function(func, context){ for(var x = this.width - 1; x >= 0; x--){ for(var y = this.height - 1; y >= 0; y--){ var val = this.get(x, y); if(context){ func.call(context, val, x, y); } else { func(val, x, y); } } } }
javascript
{ "resource": "" }
q33789
buildInputsArray
train
function buildInputsArray(rawInputsString) { let returnArray = []; // eslint-disable-line const rawMethodInputs = rawInputsString.split(','); // no inputs if (typeof rawMethodInputs === 'undefined' || rawMethodInputs.length === 0) { return []; } rawMethodInputs.forEach((rawMethodInput) => { const inputData = rawMethodInput.trim().split(' '); const type = inputData[0]; const name = inputData[1] || ''; // if type exists if (type !== '' && typeof type !== 'undefined') { returnArray.push({ type, name, }); } }); return returnArray; }
javascript
{ "resource": "" }
q33790
solidityToABI
train
function solidityToABI(methodInterface) { // count open and clsoed const methodABIObject = {}; // not a string if (typeof methodInterface !== 'string') { throw new Error(`Method interface must be a string, currently ${typeof methodInterface}`); } // empty string if (methodInterface.length === 0) { throw new Error(`Solidity method interface must have a length greater than zero, currently ${methodInterface.length}`); } // count open brackets, closed brackets, colon count, outpouts and invalid characters const openBrackets = (methodInterface.match(/\(/g) || []).length; const closedBrackets = (methodInterface.match(/\)/g) || []).length; const colonCount = (methodInterface.match(/:/g) || []).length; const hasOutputs = openBrackets === 2 && closedBrackets === 2 && colonCount === 1; const hasInvalidCharacters = methodInterface.replace(/([A-Za-z0-9\_\s\,\:(\)]+)/g, '').trim().length > 0; // eslint-disable-line // invalid characters if (hasInvalidCharacters) { throw new Error('Invalid Solidity method interface, your method interface contains invalid chars. Only letters, numbers, spaces, commas, underscores, brackets and colons.'); } // method ABI object assembly methodABIObject.name = methodInterface.slice(0, methodInterface.indexOf('(')); methodABIObject.type = 'function'; methodABIObject.constant = false; const methodInputsString = methodInterface.slice(methodInterface.indexOf('(') + 1, methodInterface.indexOf(')')).trim(); const methodOutputString = (hasOutputs && methodInterface.slice(methodInterface.lastIndexOf('(') + 1, methodInterface.lastIndexOf(')')) || '').trim(); methodABIObject.inputs = buildInputsArray(methodInputsString); methodABIObject.outputs = buildInputsArray(methodOutputString); // check open brackets if (methodABIObject.name === '' || typeof methodABIObject.name === 'undefined') { throw new Error('Invalid Solidity method interface, no method name'); } // check open brackets if (openBrackets !== 1 && openBrackets !== 2) { throw new Error(`Invalid Solidity method interface, too many or too little open brackets in solidity interface, currenlty only ${openBrackets} open brackets!`); } // check open brackets if (openBrackets !== 1 && openBrackets !== 2) { throw new Error('Invalid Solidity method interface, too many or too little open brackets in solidity interface!'); } // check closed brackets if (closedBrackets !== 1 && closedBrackets !== 2) { throw new Error('Invalid Solidity method interface, too many or too little closed brackets in solidity interface!'); } // check colon count if (colonCount !== 0 && colonCount !== 1) { throw new Error('Invalid Solidity method interface, to many or too little colons.'); } // return method abi object return methodABIObject; }
javascript
{ "resource": "" }
q33791
train
function(obj){ if(ko.isWriteableObservable(obj)) return ko.observable(obj()); if(obj === null || typeof obj !== 'object') return obj; var temp = obj.constructor(); for (var key in obj) { temp[key] = Utils.cloneObjKnockout(obj[key]); } return temp; }
javascript
{ "resource": "" }
q33792
train
function(_options){ var self = this, //model options = _options || {}, success = options.success; //custom success function passed in _options options.success = function(data){ delete data[self.idAttribute]; var defaults = Utils.cloneObjKnockout(self.defaults); self.attributes = Utils.extendObjKnockout(defaults, data); if(success) success(self, data); }; return this.sync.call(this, 'fetch', this, options); }
javascript
{ "resource": "" }
q33793
train
function(model_s, create, options){ var toAdd = model_s instanceof Array ? model_s : [model_s], self = this; ko.utils.arrayForEach(toAdd, function(attributes){ var model; if(attributes instanceof Model){ model = attributes; model.collection = self; }else{ model = new self.model(attributes, {collection: self}); } self.models.push(model); if(create) model.save(options); }); }
javascript
{ "resource": "" }
q33794
train
function(_options){ var self = this, //collection options = _options || {}, success = options.success; //custom success function passed in _options options.success = function(data){ var toAdd = []; for(var model in data){ toAdd.push(data[model]); } self.reset(); //reset the collection if(toAdd.length > 0) self.add(toAdd); if(success) success(self, data); }; return this.sync.call(this, 'fetch', this, options); }
javascript
{ "resource": "" }
q33795
Tile
train
function Tile(game, type, x, y) { this.game = game; this.x = x; this.y = y; this.type = type; var typeData = Tile.Types[type]; RL.Util.merge(this, typeData); this.id = tileId++; if(this.init){ this.init(game, type, x, y); } }
javascript
{ "resource": "" }
q33796
baseTranspose
train
function baseTranspose(matrix) { return map(head(matrix), function (column, index) { return map(matrix, function (row) { return row[index]; }); }); }
javascript
{ "resource": "" }
q33797
train
function(game, targets, settings){ this.game = game; settings = settings || {}; this.typeSortPriority = settings.typeSortPriority || [].concat(this.typeSortPriority); var width = settings.mapWidth || this.game.map.width; var height = settings.mapWidth || this.game.map.width; this.map = new RL.MultiObjectManager(this.game, null, width, height); this.setTargets(targets); if(!settings.skipSort){ this.sort(); } }
javascript
{ "resource": "" }
q33798
train
function(targets){ targets = targets || []; this.targets = targets; this.map.reset(); for(var i = targets.length - 1; i >= 0; i--){ var target = targets[i]; this.map.add(target.x, target.y, target); } }
javascript
{ "resource": "" }
q33799
train
function(target){ var index = this.targets.indexOf(target); if(index !== -1){ this.current = target; return true; } return false; }
javascript
{ "resource": "" }