_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q16400
createProducer
train
function createProducer(tapVersion) { var producers = { '12': new TAP12Producer(), '13': new TAP13Producer() }; var producer = producers[tapVersion]; if (!producer) { throw new Error( 'invalid or unsupported TAP version: ' + JSON.stringify(tapVersion) ); } return producer; }
javascript
{ "resource": "" }
q16401
NyanCat
train
function NyanCat(runner, options) { Base.call(this, runner, options); var self = this; var width = (Base.window.width * 0.75) | 0; var nyanCatWidth = (this.nyanCatWidth = 11); this.colorIndex = 0; this.numberOfLines = 4; this.rainbowColors = self.generateColors(); this.scoreboardWidth = 5; this.tick = 0; this.trajectories = [[], [], [], []]; this.trajectoryWidthMax = width - nyanCatWidth; runner.on(EVENT_RUN_BEGIN, function() { Base.cursor.hide(); self.draw(); }); runner.on(EVENT_TEST_PENDING, function() { self.draw(); }); runner.on(EVENT_TEST_PASS, function() { self.draw(); }); runner.on(EVENT_TEST_FAIL, function() { self.draw(); }); runner.once(EVENT_RUN_END, function() { Base.cursor.show(); for (var i = 0; i < self.numberOfLines; i++) { write('\n'); } self.epilogue(); }); }
javascript
{ "resource": "" }
q16402
createInvalidReporterError
train
function createInvalidReporterError(message, reporter) { var err = new TypeError(message); err.code = 'ERR_MOCHA_INVALID_REPORTER'; err.reporter = reporter; return err; }
javascript
{ "resource": "" }
q16403
createInvalidInterfaceError
train
function createInvalidInterfaceError(message, ui) { var err = new Error(message); err.code = 'ERR_MOCHA_INVALID_INTERFACE'; err.interface = ui; return err; }
javascript
{ "resource": "" }
q16404
createInvalidArgumentTypeError
train
function createInvalidArgumentTypeError(message, argument, expected) { var err = new TypeError(message); err.code = 'ERR_MOCHA_INVALID_ARG_TYPE'; err.argument = argument; err.expected = expected; err.actual = typeof argument; return err; }
javascript
{ "resource": "" }
q16405
createInvalidArgumentValueError
train
function createInvalidArgumentValueError(message, argument, value, reason) { var err = new TypeError(message); err.code = 'ERR_MOCHA_INVALID_ARG_VALUE'; err.argument = argument; err.value = value; err.reason = typeof reason !== 'undefined' ? reason : 'is invalid'; return err; }
javascript
{ "resource": "" }
q16406
createInvalidExceptionError
train
function createInvalidExceptionError(message, value) { var err = new Error(message); err.code = 'ERR_MOCHA_INVALID_EXCEPTION'; err.valueType = typeof value; err.value = value; return err; }
javascript
{ "resource": "" }
q16407
highlight
train
function highlight(js) { return js .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>') .replace(/('.*?')/gm, '<span class="string">$1</span>') .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>') .replace(/(\d+)/gm, '<span class="number">$1</span>') .replace( /\bnew[ \t]+(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>' ) .replace( /\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>' ); }
javascript
{ "resource": "" }
q16408
jsonStringify
train
function jsonStringify(object, spaces, depth) { if (typeof spaces === 'undefined') { // primitive types return _stringify(object); } depth = depth || 1; var space = spaces * depth; var str = Array.isArray(object) ? '[' : '{'; var end = Array.isArray(object) ? ']' : '}'; var length = typeof object.length === 'number' ? object.length : Object.keys(object).length; // `.repeat()` polyfill function repeat(s, n) { return new Array(n).join(s); } function _stringify(val) { switch (type(val)) { case 'null': case 'undefined': val = '[' + val + ']'; break; case 'array': case 'object': val = jsonStringify(val, spaces, depth + 1); break; case 'boolean': case 'regexp': case 'symbol': case 'number': val = val === 0 && 1 / val === -Infinity // `-0` ? '-0' : val.toString(); break; case 'date': var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString(); val = '[Date: ' + sDate + ']'; break; case 'buffer': var json = val.toJSON(); // Based on the toJSON result json = json.data && json.type ? json.data : json; val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']'; break; default: val = val === '[Function]' || val === '[Circular]' ? val : JSON.stringify(val); // string } return val; } for (var i in object) { if (!Object.prototype.hasOwnProperty.call(object, i)) { continue; // not my business } --length; str += '\n ' + repeat(' ', space) + (Array.isArray(object) ? '' : '"' + i + '": ') + // key _stringify(object[i]) + // value (length ? ',' : ''); // comma } return ( str + // [], {} (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end) ); }
javascript
{ "resource": "" }
q16409
hasMatchingExtname
train
function hasMatchingExtname(pathname, exts) { var suffix = path.extname(pathname).slice(1); return exts.some(function(element) { return suffix === element; }); }
javascript
{ "resource": "" }
q16410
emitWarning
train
function emitWarning(msg, type) { if (process.emitWarning) { process.emitWarning(msg, type); } else { process.nextTick(function() { console.warn(type + ': ' + msg); }); } }
javascript
{ "resource": "" }
q16411
Min
train
function Min(runner, options) { Base.call(this, runner, options); runner.on(EVENT_RUN_BEGIN, function() { // clear screen process.stdout.write('\u001b[2J'); // set cursor position process.stdout.write('\u001b[1;3H'); }); runner.once(EVENT_RUN_END, this.epilogue.bind(this)); }
javascript
{ "resource": "" }
q16412
Spec
train
function Spec(runner, options) { Base.call(this, runner, options); var self = this; var indents = 0; var n = 0; function indent() { return Array(indents).join(' '); } runner.on(EVENT_RUN_BEGIN, function() { console.log(); }); runner.on(EVENT_SUITE_BEGIN, function(suite) { ++indents; console.log(color('suite', '%s%s'), indent(), suite.title); }); runner.on(EVENT_SUITE_END, function() { --indents; if (indents === 1) { console.log(); } }); runner.on(EVENT_TEST_PENDING, function(test) { var fmt = indent() + color('pending', ' - %s'); console.log(fmt, test.title); }); runner.on(EVENT_TEST_PASS, function(test) { var fmt; if (test.speed === 'fast') { fmt = indent() + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s'); console.log(fmt, test.title); } else { fmt = indent() + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s') + color(test.speed, ' (%dms)'); console.log(fmt, test.title, test.duration); } }); runner.on(EVENT_TEST_FAIL, function(test) { console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); }); runner.once(EVENT_RUN_END, self.epilogue.bind(self)); }
javascript
{ "resource": "" }
q16413
Markdown
train
function Markdown(runner, options) { Base.call(this, runner, options); var level = 0; var buf = ''; function title(str) { return Array(level).join('#') + ' ' + str; } function mapTOC(suite, obj) { var ret = obj; var key = SUITE_PREFIX + suite.title; obj = obj[key] = obj[key] || {suite: suite}; suite.suites.forEach(function(suite) { mapTOC(suite, obj); }); return ret; } function stringifyTOC(obj, level) { ++level; var buf = ''; var link; for (var key in obj) { if (key === 'suite') { continue; } if (key !== SUITE_PREFIX) { link = ' - [' + key.substring(1) + ']'; link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; buf += Array(level).join(' ') + link; } buf += stringifyTOC(obj[key], level); } return buf; } function generateTOC(suite) { var obj = mapTOC(suite, {}); return stringifyTOC(obj, 0); } generateTOC(runner.suite); runner.on(EVENT_SUITE_BEGIN, function(suite) { ++level; var slug = utils.slug(suite.fullTitle()); buf += '<a name="' + slug + '"></a>' + '\n'; buf += title(suite.title) + '\n'; }); runner.on(EVENT_SUITE_END, function() { --level; }); runner.on(EVENT_TEST_PASS, function(test) { var code = utils.clean(test.body); buf += test.title + '.\n'; buf += '\n```js\n'; buf += code + '\n'; buf += '```\n\n'; }); runner.once(EVENT_RUN_END, function() { process.stdout.write('# TOC\n'); process.stdout.write(generateTOC(runner.suite)); process.stdout.write(buf); }); }
javascript
{ "resource": "" }
q16414
Mocha
train
function Mocha(options) { options = utils.assign({}, mocharc, options || {}); this.files = []; this.options = options; // root suite this.suite = new exports.Suite('', new exports.Context(), true); if ('useColors' in options) { utils.deprecate( 'useColors is DEPRECATED and will be removed from a future version of Mocha. Instead, use the "color" option' ); options.color = 'color' in options ? options.color : options.useColors; } this.grep(options.grep) .fgrep(options.fgrep) .ui(options.ui) .bail(options.bail) .reporter(options.reporter, options.reporterOptions) .useColors(options.color) .slow(options.slow) .useInlineDiffs(options.inlineDiffs) .globals(options.globals); if ('enableTimeouts' in options) { utils.deprecate( 'enableTimeouts is DEPRECATED and will be removed from a future version of Mocha. Instead, use "timeout: false" to disable timeouts.' ); if (options.enableTimeouts === false) { this.timeout(0); } } // this guard exists because Suite#timeout does not consider `undefined` to be valid input if (typeof options.timeout !== 'undefined') { this.timeout(options.timeout === false ? 0 : options.timeout); } if ('retries' in options) { this.retries(options.retries); } if ('diff' in options) { this.hideDiff(!options.diff); } [ 'allowUncaught', 'asyncOnly', 'checkLeaks', 'delay', 'forbidOnly', 'forbidPending', 'fullTrace', 'growl', 'invert' ].forEach(function(opt) { if (options[opt]) { this[opt](); } }, this); }
javascript
{ "resource": "" }
q16415
JSONStream
train
function JSONStream(runner, options) { Base.call(this, runner, options); var self = this; var total = runner.total; runner.once(EVENT_RUN_BEGIN, function() { writeEvent(['start', {total: total}]); }); runner.on(EVENT_TEST_PASS, function(test) { writeEvent(['pass', clean(test)]); }); runner.on(EVENT_TEST_FAIL, function(test, err) { test = clean(test); test.err = err.message; test.stack = err.stack || null; writeEvent(['fail', test]); }); runner.once(EVENT_RUN_END, function() { writeEvent(['end', self.stats]); }); }
javascript
{ "resource": "" }
q16416
clean
train
function clean(test) { return { title: test.title, fullTitle: test.fullTitle(), duration: test.duration, currentRetry: test.currentRetry() }; }
javascript
{ "resource": "" }
q16417
List
train
function List(runner, options) { Base.call(this, runner, options); var self = this; var n = 0; runner.on(EVENT_RUN_BEGIN, function() { console.log(); }); runner.on(EVENT_TEST_BEGIN, function(test) { process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); }); runner.on(EVENT_TEST_PENDING, function(test) { var fmt = color('checkmark', ' -') + color('pending', ' %s'); console.log(fmt, test.fullTitle()); }); runner.on(EVENT_TEST_PASS, function(test) { var fmt = color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s: ') + color(test.speed, '%dms'); cursor.CR(); console.log(fmt, test.fullTitle(), test.duration); }); runner.on(EVENT_TEST_FAIL, function(test) { cursor.CR(); console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); }); runner.once(EVENT_RUN_END, self.epilogue.bind(self)); }
javascript
{ "resource": "" }
q16418
text
train
function text(el, contents) { if (el.textContent) { el.textContent = contents; } else { el.innerText = contents; } }
javascript
{ "resource": "" }
q16419
Dot
train
function Dot(runner, options) { Base.call(this, runner, options); var self = this; var width = (Base.window.width * 0.75) | 0; var n = -1; runner.on(EVENT_RUN_BEGIN, function() { process.stdout.write('\n'); }); runner.on(EVENT_TEST_PENDING, function() { if (++n % width === 0) { process.stdout.write('\n '); } process.stdout.write(Base.color('pending', Base.symbols.comma)); }); runner.on(EVENT_TEST_PASS, function(test) { if (++n % width === 0) { process.stdout.write('\n '); } if (test.speed === 'slow') { process.stdout.write(Base.color('bright yellow', Base.symbols.dot)); } else { process.stdout.write(Base.color(test.speed, Base.symbols.dot)); } }); runner.on(EVENT_TEST_FAIL, function() { if (++n % width === 0) { process.stdout.write('\n '); } process.stdout.write(Base.color('fail', Base.symbols.bang)); }); runner.once(EVENT_RUN_END, function() { console.log(); self.epilogue(); }); }
javascript
{ "resource": "" }
q16420
extraGlobals
train
function extraGlobals() { if (typeof process === 'object' && typeof process.version === 'string') { var parts = process.version.split('.'); var nodeVersion = parts.reduce(function(a, v) { return (a << 8) | v; }); // 'errno' was renamed to process._errno in v0.9.11. if (nodeVersion < 0x00090b) { return ['errno']; } } return []; }
javascript
{ "resource": "" }
q16421
train
function(resolution) { this.width = canvas.width = window.innerWidth; this.height = canvas.height = window.innerHeight; this.resolution = resolution; this.spacing = this.width / resolution; this.focalLen = this.height / this.width; this.range = isMobile ? 9 : 18; this.lightRange = 9; this.scale = canvas.width / 1200; }
javascript
{ "resource": "" }
q16422
train
function() { var dir = game.player.dir; var sky = game.map.skybox; var ambient = game.map.light; var width = sky.width * (this.height / sky.height) * 2; var left = (dir / circle) * -width; ctx.save(); ctx.drawImage(sky.image, left, 0, width, this.height); if (left < width - this.width) { ctx.drawImage(sky.image, left + width, 0, width, this.height); } if (ambient > 0) { ctx.fillStyle = '#fff'; ctx.globalAlpha = ambient * 0.1; ctx.fillRect(0, this.height * 0.5, this.width, this.height * 0.5); } ctx.restore(); }
javascript
{ "resource": "" }
q16423
train
function() { var x, angle, ray; ctx.save(); for (var col=0; col<this.resolution; col++) { x = col / this.resolution - 0.5; angle = Math.atan2(x, this.focalLen); ray = game.map.cast(game.player, game.player.dir + angle, this.range); this.drawCol(col, ray, angle); } ctx.restore(); }
javascript
{ "resource": "" }
q16424
train
function(col, ray, angle) { var step, drops, rain, texX, wall; var tex1 = game.map.wall; var tex2 = game.map.speaker; var left = Math.floor(col * this.spacing); var width = Math.ceil(this.spacing); var hit = -1; // Find the next wall hit. while (++hit < ray.length && ray[hit].height <= 0); // Draw the wall sections and rain drops. for (var i=ray.length - 1; i>=0; i--) { step = ray[i]; drops = Math.pow(Math.random(), 100) * i; rain = (drops > 0) && this.project(0.2, angle, step.dist); var tex = (step.type === 1) ? tex1 : tex2; if (i === hit) { texX = Math.floor(tex.width * step.offset); wall = this.project(step.height, angle, step.dist); ctx.globalAlpha = 1; ctx.drawImage(tex.image, texX, 0, 1, tex.height, left, wall.top, width, wall.height); ctx.fillStyle = '#000'; ctx.globalAlpha = Math.max((step.dist + step.shading) / this.lightRange - game.map.light, 0); ctx.fillRect(left, wall.top, width, wall.height); } ctx.fillStyle = '#fff'; ctx.globalAlpha = 0.15; while (--drops > 0) { ctx.fillRect(left, Math.random() * rain.top, 1, rain.height); } } }
javascript
{ "resource": "" }
q16425
train
function() { var hand = game.player.hand; var steps = game.player.steps; var scaleFactor = this.scale * 6; // Calculate the position of each hand relative to the steps taken. var xScale = Math.cos(steps * 2); var yScale = Math.sin(steps * 4); var bobX = xScale * scaleFactor; var bobY = yScale * scaleFactor; var x = (canvas.width - (hand.width * this.scale) + scaleFactor) + bobX; var y = (canvas.height - (hand.height * this.scale) + scaleFactor) + bobY; var w = hand.width * this.scale; var h = hand.height * this.scale; ctx.drawImage(hand.image, x, y, w, h); }
javascript
{ "resource": "" }
q16426
train
function(height, angle, dist) { var z = dist * Math.cos(angle); var wallH = this.height * height / z; var bottom = this.height / 2 * (1 + 1 / z); return { top: bottom - wallH, height: wallH }; }
javascript
{ "resource": "" }
q16427
train
function(options) { var self = this; self.sounds = []; // Setup the options to define this sprite display. self._width = options.width; self._left = options.left; self._spriteMap = options.spriteMap; self._sprite = options.sprite; self.setupListeners(); // Create our audio sprite definition. self.sound = new Howl({ src: options.src, sprite: options.sprite }); // Setup a resize event and fire it to setup our sprite overlays. window.addEventListener('resize', function() { self.resize(); }, false); self.resize(); // Begin the progress step tick. requestAnimationFrame(self.step.bind(self)); }
javascript
{ "resource": "" }
q16428
train
function() { var self = this; var keys = Object.keys(self._spriteMap); keys.forEach(function(key) { window[key].addEventListener('click', function() { self.play(key); }, false); }); }
javascript
{ "resource": "" }
q16429
train
function(key) { var self = this; var sprite = self._spriteMap[key]; // Play the sprite sound and capture the ID. var id = self.sound.play(sprite); // Create a progress element and begin visually tracking it. var elm = document.createElement('div'); elm.className = 'progress'; elm.id = id; elm.dataset.sprite = sprite; window[key].appendChild(elm); self.sounds.push(elm); // When this sound is finished, remove the progress element. self.sound.once('end', function() { var index = self.sounds.indexOf(elm); if (index >= 0) { self.sounds.splice(index, 1); window[key].removeChild(elm); } }, id); }
javascript
{ "resource": "" }
q16430
train
function() { var self = this; // Calculate the scale of our window from "full" size. var scale = window.innerWidth / 3600; // Resize and reposition the sprite overlays. var keys = Object.keys(self._spriteMap); for (var i=0; i<keys.length; i++) { var sprite = window[keys[i]]; sprite.style.width = Math.round(self._width[i] * scale) + 'px'; if (self._left[i]) { sprite.style.left = Math.round(self._left[i] * scale) + 'px'; } } }
javascript
{ "resource": "" }
q16431
train
function() { var self = this; // Loop through all active sounds and update their progress bar. for (var i=0; i<self.sounds.length; i++) { var id = parseInt(self.sounds[i].id, 10); var offset = self._sprite[self.sounds[i].dataset.sprite][0]; var seek = (self.sound.seek(id) || 0) - (offset / 1000); self.sounds[i].style.width = (((seek / self.sound.duration(id)) * 100) || 0) + '%'; } requestAnimationFrame(self.step.bind(self)); }
javascript
{ "resource": "" }
q16432
train
function() { // Define our control key codes and states. this.codes = { // Arrows 37: 'left', 39: 'right', 38: 'front', 40: 'back', // WASD 65: 'left', 68: 'right', 87: 'front', 83: 'back', }; this.states = {left: false, right: false, front: false, back: false}; // Setup the DOM listeners. document.addEventListener('keydown', this.key.bind(this, true), false); document.addEventListener('keyup', this.key.bind(this, false), false); document.addEventListener('touchstart', this.touch.bind(this), false); document.addEventListener('touchmove', this.touch.bind(this), false); document.addEventListener('touchend', this.touchEnd.bind(this), false); }
javascript
{ "resource": "" }
q16433
train
function(pressed, event) { var state = this.codes[event.keyCode]; if (!state) { return; } this.states[state] = pressed; event.preventDefault && event.preventDefault(); event.stopPropagation && event.stopPropagation(); }
javascript
{ "resource": "" }
q16434
train
function(event) { var touches = event.touches[0]; // Reset the states. this.touchEnd(event); // Determine which key to simulate. if (touches.pageY < window.innerHeight * 0.3) { this.key(true, {keyCode: 38}); } else if (touches.pageY > window.innerHeight * 0.7) { this.key(true, {keyCode: 40}); } else if (touches.pageX < window.innerWidth * 0.5) { this.key(true, {keyCode: 37}); } else if (touches.pageX > window.innerWidth * 0.5) { this.key(true, {keyCode: 39}); } }
javascript
{ "resource": "" }
q16435
train
function(event) { this.states.left = false; this.states.right = false; this.states.front = false; this.states.back = false; event.preventDefault(); event.stopPropagation(); }
javascript
{ "resource": "" }
q16436
train
function() { // Loop through the tiles and setup the audio listeners. for (var i=0; i<this.grid.length; i++) { if (this.grid[i] === 2) { var y = Math.floor(i / this.size); var x = i % this.size; game.audio.speaker(x, y); } } }
javascript
{ "resource": "" }
q16437
train
function(x, y) { x = Math.floor(x); y = Math.floor(y); if (x < 0 || x > this.size - 1 || y < 0 || y > this.size - 1) { return -1; } return this.grid[y * this.size + x]; }
javascript
{ "resource": "" }
q16438
train
function(sin, cos, range, origin) { var stepX = this.step(sin, cos, origin.x, origin.y, false); var stepY = this.step(cos, sin, origin.y, origin.x, true); var inspectX = [sin, cos, stepX, 1, 0, origin.dist, stepX.y]; var inspectY = [sin, cos, stepY, 0, 1, origin.dist, stepY.x]; var next = this.inspect.apply(this, (stepX.len2 < stepY.len2) ? inspectX : inspectY); if (next.dist > range) { return [origin]; } return [origin].concat(this.ray(sin, cos, range, next)); }
javascript
{ "resource": "" }
q16439
train
function(rise, run, x, y, inverted) { if (run === 0) { return {len2: Infinity}; } var dx = run > 0 ? Math.floor(x + 1) - x : Math.ceil(x - 1) - x; var dy = dx * (rise / run); return { x: inverted ? y + dy : x + dx, y: inverted ? x + dx : y + dy, len2: dx * dx + dy * dy }; }
javascript
{ "resource": "" }
q16440
train
function(sin, cos, step, shiftX, shiftY, dist, offset) { var dx = (cos < 0) ? shiftX : 0; var dy = (sin < 0) ? shiftY : 0; step.type = this.check(step.x - dx, step.y - dy); step.height = (step.type) > 0 ? 1 : 0; step.dist = dist + Math.sqrt(step.len2); if (shiftX) { step.shading = (cos < 0) ? 2 : 0; } else { step.shading = (sin < 0) ? 2 : 1; } step.offset = offset - Math.floor(offset); return step; }
javascript
{ "resource": "" }
q16441
train
function(point, angle, range) { var sin = Math.sin(angle); var cos = Math.cos(angle); return this.ray(sin, cos, range, { x: point.x, y: point.y, height: 0, dist: 0 }); }
javascript
{ "resource": "" }
q16442
train
function(secs) { if (this.light > 0) { this.light = Math.max(this.light - 10 * secs, 0); } else if (Math.random() * 6 < secs) { this.light = 2; // Play the lightning sound. game.audio.lightning(); } }
javascript
{ "resource": "" }
q16443
train
function() { var self = this || Howler; // Create a global ID counter. self._counter = 1000; // Pool of unlocked HTML5 Audio objects. self._html5AudioPool = []; self.html5PoolSize = 10; // Internal properties. self._codecs = {}; self._howls = []; self._muted = false; self._volume = 1; self._canPlayEvent = 'canplaythrough'; self._navigator = (typeof window !== 'undefined' && window.navigator) ? window.navigator : null; // Public properties. self.masterGain = null; self.noAudio = false; self.usingWebAudio = true; self.autoSuspend = true; self.ctx = null; // Set to false to disable the auto audio unlocker. self.autoUnlock = true; // Setup the various state values for global tracking. self._setup(); return self; }
javascript
{ "resource": "" }
q16444
train
function() { var self = this || Howler; for (var i=self._howls.length-1; i>=0; i--) { self._howls[i].unload(); } // Create a new AudioContext to make sure it is fully reset. if (self.usingWebAudio && self.ctx && typeof self.ctx.close !== 'undefined') { self.ctx.close(); self.ctx = null; setupAudioContext(); } return self; }
javascript
{ "resource": "" }
q16445
train
function() { var self = this || Howler; // Keeps track of the suspend/resume state of the AudioContext. self.state = self.ctx ? self.ctx.state || 'suspended' : 'suspended'; // Automatically begin the 30-second suspend process self._autoSuspend(); // Check if audio is available. if (!self.usingWebAudio) { // No audio is available on this system if noAudio is set to true. if (typeof Audio !== 'undefined') { try { var test = new Audio(); // Check if the canplaythrough event is available. if (typeof test.oncanplaythrough === 'undefined') { self._canPlayEvent = 'canplay'; } } catch(e) { self.noAudio = true; } } else { self.noAudio = true; } } // Test to make sure audio isn't disabled in Internet Explorer. try { var test = new Audio(); if (test.muted) { self.noAudio = true; } } catch (e) {} // Check for supported codecs. if (!self.noAudio) { self._setupCodecs(); } return self; }
javascript
{ "resource": "" }
q16446
train
function() { var self = this || Howler; var audioTest = null; // Must wrap in a try/catch because IE11 in server mode throws an error. try { audioTest = (typeof Audio !== 'undefined') ? new Audio() : null; } catch (err) { return self; } if (!audioTest || typeof audioTest.canPlayType !== 'function') { return self; } var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, ''); // Opera version <33 has mixed MP3 support, so we need to check for and block it. var checkOpera = self._navigator && self._navigator.userAgent.match(/OPR\/([0-6].)/g); var isOldOpera = (checkOpera && parseInt(checkOpera[0].split('/')[1], 10) < 33); self._codecs = { mp3: !!(!isOldOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))), mpeg: !!mpegTest, opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''), ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), oga: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''), aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''), caf: !!audioTest.canPlayType('audio/x-caf;').replace(/^no$/, ''), m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''), webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''), dolby: !!audioTest.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/, ''), flac: !!(audioTest.canPlayType('audio/x-flac;') || audioTest.canPlayType('audio/flac;')).replace(/^no$/, '') }; return self; }
javascript
{ "resource": "" }
q16447
train
function() { var self = this || Howler; // Return the next object from the pool if one exists. if (self._html5AudioPool.length) { return self._html5AudioPool.pop(); } //.Check if the audio is locked and throw a warning. var testPlay = new Audio().play(); if (testPlay && typeof Promise !== 'undefined' && (testPlay instanceof Promise || typeof testPlay.then === 'function')) { testPlay.catch(function() { console.warn('HTML5 Audio pool exhausted, returning potentially locked audio object.'); }); } return new Audio(); }
javascript
{ "resource": "" }
q16448
train
function(audio) { var self = this || Howler; // Don't add audio to the pool if we don't know if it has been unlocked. if (audio._unlocked) { self._html5AudioPool.push(audio); } return self; }
javascript
{ "resource": "" }
q16449
train
function() { var self = this; if (!self.ctx || typeof self.ctx.resume === 'undefined' || !Howler.usingWebAudio) { return; } if (self.state === 'running' && self._suspendTimer) { clearTimeout(self._suspendTimer); self._suspendTimer = null; } else if (self.state === 'suspended') { self.ctx.resume().then(function() { self.state = 'running'; // Emit to all Howls that the audio has resumed. for (var i=0; i<self._howls.length; i++) { self._howls[i]._emit('resume'); } }); if (self._suspendTimer) { clearTimeout(self._suspendTimer); self._suspendTimer = null; } } else if (self.state === 'suspending') { self._resumeAfterSuspend = true; } return self; }
javascript
{ "resource": "" }
q16450
train
function() { var self = this; var url = null; // If no audio is available, quit immediately. if (Howler.noAudio) { self._emit('loaderror', null, 'No audio support.'); return; } // Make sure our source is in an array. if (typeof self._src === 'string') { self._src = [self._src]; } // Loop through the sources and pick the first one that is compatible. for (var i=0; i<self._src.length; i++) { var ext, str; if (self._format && self._format[i]) { // If an extension was specified, use that instead. ext = self._format[i]; } else { // Make sure the source is a string. str = self._src[i]; if (typeof str !== 'string') { self._emit('loaderror', null, 'Non-string found in selected audio sources - ignoring.'); continue; } // Extract the file extension from the URL or base64 data URI. ext = /^data:audio\/([^;,]+);/i.exec(str); if (!ext) { ext = /\.([^.]+)$/.exec(str.split('?', 1)[0]); } if (ext) { ext = ext[1].toLowerCase(); } } // Log a warning if no extension was found. if (!ext) { console.warn('No file extension was found. Consider using the "format" property or specify an extension.'); } // Check if this extension is available. if (ext && Howler.codecs(ext)) { url = self._src[i]; break; } } if (!url) { self._emit('loaderror', null, 'No codec support for selected audio sources.'); return; } self._src = url; self._state = 'loading'; // If the hosting page is HTTPS and the source isn't, // drop down to HTML5 Audio to avoid Mixed Content errors. if (window.location.protocol === 'https:' && url.slice(0, 5) === 'http:') { self._html5 = true; self._webAudio = false; } // Create a new sound object and add it to the pool. new Sound(self); // Load and decode the audio data for playback. if (self._webAudio) { loadBuffer(self); } return self; }
javascript
{ "resource": "" }
q16451
train
function() { sound._paused = false; sound._seek = seek; sound._start = start; sound._stop = stop; sound._loop = loop; }
javascript
{ "resource": "" }
q16452
train
function() { self._playLock = false; setParams(); self._refreshBuffer(sound); // Setup the playback params. var vol = (sound._muted || self._muted) ? 0 : sound._volume; node.gain.setValueAtTime(vol, Howler.ctx.currentTime); sound._playStart = Howler.ctx.currentTime; // Play the sound using the supported method. if (typeof node.bufferSource.start === 'undefined') { sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration); } else { sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration); } // Start a new timer if none is present. if (timeout !== Infinity) { self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); } if (!internal) { setTimeout(function() { self._emit('play', sound._id); self._loadQueue(); }, 0); } }
javascript
{ "resource": "" }
q16453
train
function() { node.currentTime = seek; node.muted = sound._muted || self._muted || Howler._muted || node.muted; node.volume = sound._volume * Howler.volume(); node.playbackRate = sound._rate; // Some browsers will throw an error if this is called without user interaction. try { var play = node.play(); // Support older browsers that don't support promises, and thus don't have this issue. if (play && typeof Promise !== 'undefined' && (play instanceof Promise || typeof play.then === 'function')) { // Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause(). self._playLock = true; // Set param values immediately. setParams(); // Releases the lock and executes queued actions. play .then(function() { self._playLock = false; node._unlocked = true; if (!internal) { self._emit('play', sound._id); self._loadQueue(); } }) .catch(function() { self._playLock = false; self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' + 'on mobile devices and Chrome where playback was not within a user interaction.'); // Reset the ended and paused values. sound._ended = true; sound._paused = true; }); } else if (!internal) { self._playLock = false; setParams(); self._emit('play', sound._id); self._loadQueue(); } // Setting rate before playing won't work in IE, so we set it again here. node.playbackRate = sound._rate; // If the node is still paused, then we can assume there was a playback issue. if (node.paused) { self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' + 'on mobile devices and Chrome where playback was not within a user interaction.'); return; } // Setup the end timer on sprites or listen for the ended event. if (sprite !== '__default' || sound._loop) { self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); } else { self._endTimers[sound._id] = function() { // Fire ended on this audio node. self._ended(sound); // Clear this listener. node.removeEventListener('ended', self._endTimers[sound._id], false); }; node.addEventListener('ended', self._endTimers[sound._id], false); } } catch (err) { self._emit('playerror', sound._id, err); } }
javascript
{ "resource": "" }
q16454
train
function(sound, from, to, len, id, isGroup) { var self = this; var vol = from; var diff = to - from; var steps = Math.abs(diff / 0.01); var stepLen = Math.max(4, (steps > 0) ? len / steps : len); var lastTick = Date.now(); // Store the value being faded to. sound._fadeTo = to; // Update the volume value on each interval tick. sound._interval = setInterval(function() { // Update the volume based on the time since the last tick. var tick = (Date.now() - lastTick) / len; lastTick = Date.now(); vol += diff * tick; // Make sure the volume is in the right bounds. vol = Math.max(0, vol); vol = Math.min(1, vol); // Round to within 2 decimal points. vol = Math.round(vol * 100) / 100; // Change the volume. if (self._webAudio) { sound._volume = vol; } else { self.volume(vol, sound._id, true); } // Set the group's volume. if (isGroup) { self._volume = vol; } // When the fade is complete, stop it and fire event. if ((to < from && vol <= to) || (to > from && vol >= to)) { clearInterval(sound._interval); sound._interval = null; sound._fadeTo = null; self.volume(to, sound._id); self._emit('fade', sound._id); } }, stepLen); }
javascript
{ "resource": "" }
q16455
train
function(id) { var self = this; var sound = self._soundById(id); if (sound && sound._interval) { if (self._webAudio) { sound._node.gain.cancelScheduledValues(Howler.ctx.currentTime); } clearInterval(sound._interval); sound._interval = null; self.volume(sound._fadeTo, id); sound._fadeTo = null; self._emit('fade', id); } return self; }
javascript
{ "resource": "" }
q16456
train
function(id) { var self = this; var duration = self._duration; // If we pass an ID, get the sound and return the sprite length. var sound = self._soundById(id); if (sound) { duration = self._sprite[sound._sprite][1] / 1000; } return duration; }
javascript
{ "resource": "" }
q16457
train
function(event, fn, id, once) { var self = this; var events = self['_on' + event]; if (typeof fn === 'function') { events.push(once ? {id: id, fn: fn, once: once} : {id: id, fn: fn}); } return self; }
javascript
{ "resource": "" }
q16458
train
function(event, fn, id) { var self = this; var events = self['_on' + event]; var i = 0; // Allow passing just an event and ID. if (typeof fn === 'number') { id = fn; fn = null; } if (fn || id) { // Loop through event store and remove the passed function. for (i=0; i<events.length; i++) { var isId = (id === events[i].id); if (fn === events[i].fn && isId || !fn && isId) { events.splice(i, 1); break; } } } else if (event) { // Clear out all events of this type. self['_on' + event] = []; } else { // Clear out all events of every type. var keys = Object.keys(self); for (i=0; i<keys.length; i++) { if ((keys[i].indexOf('_on') === 0) && Array.isArray(self[keys[i]])) { self[keys[i]] = []; } } } return self; }
javascript
{ "resource": "" }
q16459
train
function(event, fn, id) { var self = this; // Setup the event listener. self.on(event, fn, id, 1); return self; }
javascript
{ "resource": "" }
q16460
train
function(event, id, msg) { var self = this; var events = self['_on' + event]; // Loop through event store and fire all functions. for (var i=events.length-1; i>=0; i--) { // Only fire the listener if the correct ID is used. if (!events[i].id || events[i].id === id || event === 'load') { setTimeout(function(fn) { fn.call(this, id, msg); }.bind(self, events[i].fn), 0); // If this event was setup with `once`, remove it. if (events[i].once) { self.off(event, events[i].fn, events[i].id); } } } // Pass the event type into load queue so that it can continue stepping. self._loadQueue(event); return self; }
javascript
{ "resource": "" }
q16461
train
function(sound) { var self = this; var sprite = sound._sprite; // If we are using IE and there was network latency we may be clipping // audio before it completes playing. Lets check the node to make sure it // believes it has completed, before ending the playback. if (!self._webAudio && sound._node && !sound._node.paused && !sound._node.ended && sound._node.currentTime < sound._stop) { setTimeout(self._ended.bind(self, sound), 100); return self; } // Should this sound loop? var loop = !!(sound._loop || self._sprite[sprite][2]); // Fire the ended event. self._emit('end', sound._id); // Restart the playback for HTML5 Audio loop. if (!self._webAudio && loop) { self.stop(sound._id, true).play(sound._id); } // Restart this timer if on a Web Audio loop. if (self._webAudio && loop) { self._emit('play', sound._id); sound._seek = sound._start || 0; sound._rateSeek = 0; sound._playStart = Howler.ctx.currentTime; var timeout = ((sound._stop - sound._start) * 1000) / Math.abs(sound._rate); self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); } // Mark the node as paused. if (self._webAudio && !loop) { sound._paused = true; sound._ended = true; sound._seek = sound._start || 0; sound._rateSeek = 0; self._clearTimer(sound._id); // Clean up the buffer source. self._cleanBuffer(sound._node); // Attempt to auto-suspend AudioContext if no sounds are still playing. Howler._autoSuspend(); } // When using a sprite, end the track. if (!self._webAudio && !loop) { self.stop(sound._id, true); } return self; }
javascript
{ "resource": "" }
q16462
train
function(id) { var self = this; if (self._endTimers[id]) { // Clear the timeout or remove the ended listener. if (typeof self._endTimers[id] !== 'function') { clearTimeout(self._endTimers[id]); } else { var sound = self._soundById(id); if (sound && sound._node) { sound._node.removeEventListener('ended', self._endTimers[id], false); } } delete self._endTimers[id]; } return self; }
javascript
{ "resource": "" }
q16463
train
function(id) { var self = this; // Loop through all sounds and find the one with this ID. for (var i=0; i<self._sounds.length; i++) { if (id === self._sounds[i]._id) { return self._sounds[i]; } } return null; }
javascript
{ "resource": "" }
q16464
train
function() { var self = this; self._drain(); // Find the first inactive node to recycle. for (var i=0; i<self._sounds.length; i++) { if (self._sounds[i]._ended) { return self._sounds[i].reset(); } } // If no inactive node was found, create a new one. return new Sound(self); }
javascript
{ "resource": "" }
q16465
train
function() { var self = this; var limit = self._pool; var cnt = 0; var i = 0; // If there are less sounds than the max pool size, we are done. if (self._sounds.length < limit) { return; } // Count the number of inactive sounds. for (i=0; i<self._sounds.length; i++) { if (self._sounds[i]._ended) { cnt++; } } // Remove excess inactive sounds, going in reverse order. for (i=self._sounds.length - 1; i>=0; i--) { if (cnt <= limit) { return; } if (self._sounds[i]._ended) { // Disconnect the audio source when using Web Audio. if (self._webAudio && self._sounds[i]._node) { self._sounds[i]._node.disconnect(0); } // Remove sounds until we have the pool size. self._sounds.splice(i, 1); cnt--; } } }
javascript
{ "resource": "" }
q16466
train
function(id) { var self = this; if (typeof id === 'undefined') { var ids = []; for (var i=0; i<self._sounds.length; i++) { ids.push(self._sounds[i]._id); } return ids; } else { return [id]; } }
javascript
{ "resource": "" }
q16467
train
function(sound) { var self = this; // Setup the buffer source for playback. sound._node.bufferSource = Howler.ctx.createBufferSource(); sound._node.bufferSource.buffer = cache[self._src]; // Connect to the correct node. if (sound._panner) { sound._node.bufferSource.connect(sound._panner); } else { sound._node.bufferSource.connect(sound._node); } // Setup looping and playback rate. sound._node.bufferSource.loop = sound._loop; if (sound._loop) { sound._node.bufferSource.loopStart = sound._start || 0; sound._node.bufferSource.loopEnd = sound._stop || 0; } sound._node.bufferSource.playbackRate.setValueAtTime(sound._rate, Howler.ctx.currentTime); return self; }
javascript
{ "resource": "" }
q16468
train
function(node) { var self = this; var isIOS = Howler._navigator && Howler._navigator.vendor.indexOf('Apple') >= 0; if (Howler._scratchBuffer && node.bufferSource) { node.bufferSource.onended = null; node.bufferSource.disconnect(0); if (isIOS) { try { node.bufferSource.buffer = Howler._scratchBuffer; } catch(e) {} } } node.bufferSource = null; return self; }
javascript
{ "resource": "" }
q16469
train
function() { var self = this; var parent = self._parent; // Setup the default parameters. self._muted = parent._muted; self._loop = parent._loop; self._volume = parent._volume; self._rate = parent._rate; self._seek = 0; self._paused = true; self._ended = true; self._sprite = '__default'; // Generate a unique ID for this sound. self._id = ++Howler._counter; // Add itself to the parent's pool. parent._sounds.push(self); // Create the new node. self.create(); return self; }
javascript
{ "resource": "" }
q16470
train
function() { var self = this; var parent = self._parent; var volume = (Howler._muted || self._muted || self._parent._muted) ? 0 : self._volume; if (parent._webAudio) { // Create the gain node for controlling volume (the source will connect to this). self._node = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain(); self._node.gain.setValueAtTime(volume, Howler.ctx.currentTime); self._node.paused = true; self._node.connect(Howler.masterGain); } else { // Get an unlocked Audio object from the pool. self._node = Howler._obtainHtml5Audio(); // Listen for errors (http://dev.w3.org/html5/spec-author-view/spec.html#mediaerror). self._errorFn = self._errorListener.bind(self); self._node.addEventListener('error', self._errorFn, false); // Listen for 'canplaythrough' event to let us know the sound is ready. self._loadFn = self._loadListener.bind(self); self._node.addEventListener(Howler._canPlayEvent, self._loadFn, false); // Setup the new audio node. self._node.src = parent._src; self._node.preload = 'auto'; self._node.volume = volume * Howler.volume(); // Begin loading the source. self._node.load(); } return self; }
javascript
{ "resource": "" }
q16471
train
function() { var self = this; // Fire an error event and pass back the code. self._parent._emit('loaderror', self._id, self._node.error ? self._node.error.code : 0); // Clear the event listener. self._node.removeEventListener('error', self._errorFn, false); }
javascript
{ "resource": "" }
q16472
train
function() { var self = this; var parent = self._parent; // Round up the duration to account for the lower precision in HTML5 Audio. parent._duration = Math.ceil(self._node.duration * 10) / 10; // Setup a sprite if none is defined. if (Object.keys(parent._sprite).length === 0) { parent._sprite = {__default: [0, parent._duration * 1000]}; } if (parent._state !== 'loaded') { parent._state = 'loaded'; parent._emit('load'); parent._loadQueue(); } // Clear the event listener. self._node.removeEventListener(Howler._canPlayEvent, self._loadFn, false); }
javascript
{ "resource": "" }
q16473
train
function(arraybuffer, self) { // Fire a load error if something broke. var error = function() { self._emit('loaderror', null, 'Decoding audio data failed.'); }; // Load the sound on success. var success = function(buffer) { if (buffer && self._sounds.length > 0) { cache[self._src] = buffer; loadSound(self, buffer); } else { error(); } }; // Decode the buffer into an audio source. if (typeof Promise !== 'undefined' && Howler.ctx.decodeAudioData.length === 1) { Howler.ctx.decodeAudioData(arraybuffer).then(success).catch(error); } else { Howler.ctx.decodeAudioData(arraybuffer, success, error); } }
javascript
{ "resource": "" }
q16474
train
function(buffer) { if (buffer && self._sounds.length > 0) { cache[self._src] = buffer; loadSound(self, buffer); } else { error(); } }
javascript
{ "resource": "" }
q16475
train
function(self, buffer) { // Set the duration. if (buffer && !self._duration) { self._duration = buffer.duration; } // Setup a sprite if none is defined. if (Object.keys(self._sprite).length === 0) { self._sprite = {__default: [0, self._duration * 1000]}; } // Fire the loaded event. if (self._state !== 'loaded') { self._state = 'loaded'; self._emit('load'); self._loadQueue(); } }
javascript
{ "resource": "" }
q16476
train
function() { // If we have already detected that Web Audio isn't supported, don't run this step again. if (!Howler.usingWebAudio) { return; } // Check if we are using Web Audio and setup the AudioContext if we are. try { if (typeof AudioContext !== 'undefined') { Howler.ctx = new AudioContext(); } else if (typeof webkitAudioContext !== 'undefined') { Howler.ctx = new webkitAudioContext(); } else { Howler.usingWebAudio = false; } } catch(e) { Howler.usingWebAudio = false; } // If the audio context creation still failed, set using web audio to false. if (!Howler.ctx) { Howler.usingWebAudio = false; } // Check if a webview is being used on iOS8 or earlier (rather than the browser). // If it is, disable Web Audio as it causes crashing. var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform)); var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/); var version = appVersion ? parseInt(appVersion[1], 10) : null; if (iOS && version && version < 9) { var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase()); if (Howler._navigator && Howler._navigator.standalone && !safari || Howler._navigator && !Howler._navigator.standalone && !safari) { Howler.usingWebAudio = false; } } // Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage). if (Howler.usingWebAudio) { Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain(); Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : 1, Howler.ctx.currentTime); Howler.masterGain.connect(Howler.ctx.destination); } // Re-run the setup on Howler. Howler._setup(); }
javascript
{ "resource": "" }
q16477
train
function(x, y, dir, speed) { this.x = x; this.y = y; this.dir = dir; this.speed = speed || 3; this.steps = 0; this.hand = new Texture('./assets/gun.png', 512, 360); // Update the position of the audio listener. Howler.pos(this.x, this.y, -0.5); // Update the direction and orientation. this.rotate(dir); }
javascript
{ "resource": "" }
q16478
train
function(angle) { this.dir = (this.dir + angle + circle) % circle; // Calculate the rotation vector and update the orientation of the listener. var x = Math.cos(this.dir); var y = 0; var z = Math.sin(this.dir); Howler.orientation(x, y, z, 0, 1, 0); }
javascript
{ "resource": "" }
q16479
train
function(dist) { var dx = Math.cos(this.dir) * dist; var dy = Math.sin(this.dir) * dist; // Move the player if they can walk here. this.x += (game.map.check(this.x + dx, this.y) <= 0) ? dx : 0; this.y += (game.map.check(this.x, this.y + dy) <= 0) ? dy : 0; this.steps += dist; // Update the position of the audio listener. Howler.pos(this.x, this.y, -0.5); }
javascript
{ "resource": "" }
q16480
train
function(secs) { var states = game.controls.states; if (states.left) this.rotate(-Math.PI * secs); if (states.right) this.rotate(Math.PI * secs); if (states.front) this.walk(this.speed * secs); if (states.back) this.walk(-this.speed * secs); }
javascript
{ "resource": "" }
q16481
train
function() { this.lastTime = 0; // Setup our different game components. this.audio = new Sound(); this.player = new Player(10, 26, Math.PI * 1.9, 2.5); this.controls = new Controls(); this.map = new Map(25); this.camera = new Camera(isMobile ? 256 : 512); requestAnimationFrame(this.tick.bind(this)); }
javascript
{ "resource": "" }
q16482
train
function(time) { var ms = time - this.lastTime; this.lastTime = time; // Update the different components of the scene. this.map.update(ms / 1000); this.player.update(ms / 1000); this.camera.render(this.player, this.map); // Continue the game loop. requestAnimationFrame(this.tick.bind(this)); }
javascript
{ "resource": "" }
q16483
train
function(stations) { var self = this; self.stations = stations; self.index = 0; // Setup the display for each station. for (var i=0; i<self.stations.length; i++) { window['title' + i].innerHTML = '<b>' + self.stations[i].freq + '</b> ' + self.stations[i].title; window['station' + i].addEventListener('click', function(index) { var isNotPlaying = (self.stations[index].howl && !self.stations[index].howl.playing()); // Stop other sounds or the current one. radio.stop(); // If the station isn't already playing or it doesn't exist, play it. if (isNotPlaying || !self.stations[index].howl) { radio.play(index); } }.bind(self, i)); } }
javascript
{ "resource": "" }
q16484
train
function(index) { var self = this; var sound; index = typeof index === 'number' ? index : self.index; var data = self.stations[index]; // If we already loaded this track, use the current one. // Otherwise, setup and load a new Howl. if (data.howl) { sound = data.howl; } else { sound = data.howl = new Howl({ src: data.src, html5: true, // A live stream can only be played through HTML5 Audio. format: ['mp3', 'aac'] }); } // Begin playing the sound. sound.play(); // Toggle the display. self.toggleStationDisplay(index, true); // Keep track of the index we are currently playing. self.index = index; }
javascript
{ "resource": "" }
q16485
train
function() { var self = this; // Get the Howl we want to manipulate. var sound = self.stations[self.index].howl; // Toggle the display. self.toggleStationDisplay(self.index, false); // Stop the sound. if (sound) { sound.unload(); } }
javascript
{ "resource": "" }
q16486
train
function(playlist) { this.playlist = playlist; this.index = 0; // Display the title of the first track. track.innerHTML = '1. ' + playlist[0].title; // Setup the playlist display. playlist.forEach(function(song) { var div = document.createElement('div'); div.className = 'list-song'; div.innerHTML = song.title; div.onclick = function() { player.skipTo(playlist.indexOf(song)); }; list.appendChild(div); }); }
javascript
{ "resource": "" }
q16487
train
function(index) { var self = this; var sound; index = typeof index === 'number' ? index : self.index; var data = self.playlist[index]; // If we already loaded this track, use the current one. // Otherwise, setup and load a new Howl. if (data.howl) { sound = data.howl; } else { sound = data.howl = new Howl({ src: ['./audio/' + data.file + '.webm', './audio/' + data.file + '.mp3'], html5: true, // Force to HTML5 so that the audio can stream in (best for large files). onplay: function() { // Display the duration. duration.innerHTML = self.formatTime(Math.round(sound.duration())); // Start upating the progress of the track. requestAnimationFrame(self.step.bind(self)); // Start the wave animation if we have already loaded wave.container.style.display = 'block'; bar.style.display = 'none'; pauseBtn.style.display = 'block'; }, onload: function() { // Start the wave animation. wave.container.style.display = 'block'; bar.style.display = 'none'; loading.style.display = 'none'; }, onend: function() { // Stop the wave animation. wave.container.style.display = 'none'; bar.style.display = 'block'; self.skip('next'); }, onpause: function() { // Stop the wave animation. wave.container.style.display = 'none'; bar.style.display = 'block'; }, onstop: function() { // Stop the wave animation. wave.container.style.display = 'none'; bar.style.display = 'block'; }, onseek: function() { // Start upating the progress of the track. requestAnimationFrame(self.step.bind(self)); } }); } // Begin playing the sound. sound.play(); // Update the track display. track.innerHTML = (index + 1) + '. ' + data.title; // Show the pause button. if (sound.state() === 'loaded') { playBtn.style.display = 'none'; pauseBtn.style.display = 'block'; } else { loading.style.display = 'block'; playBtn.style.display = 'none'; pauseBtn.style.display = 'none'; } // Keep track of the index we are currently playing. self.index = index; }
javascript
{ "resource": "" }
q16488
train
function() { var self = this; // Get the Howl we want to manipulate. var sound = self.playlist[self.index].howl; // Puase the sound. sound.pause(); // Show the play button. playBtn.style.display = 'block'; pauseBtn.style.display = 'none'; }
javascript
{ "resource": "" }
q16489
train
function(direction) { var self = this; // Get the next track based on the direction of the track. var index = 0; if (direction === 'prev') { index = self.index - 1; if (index < 0) { index = self.playlist.length - 1; } } else { index = self.index + 1; if (index >= self.playlist.length) { index = 0; } } self.skipTo(index); }
javascript
{ "resource": "" }
q16490
train
function(index) { var self = this; // Stop the current track. if (self.playlist[self.index].howl) { self.playlist[self.index].howl.stop(); } // Reset progress. progress.style.width = '0%'; // Play the new track. self.play(index); }
javascript
{ "resource": "" }
q16491
train
function(val) { var self = this; // Update the global volume (affecting all Howls). Howler.volume(val); // Update the display on the slider. var barWidth = (val * 90) / 100; barFull.style.width = (barWidth * 100) + '%'; sliderBtn.style.left = (window.innerWidth * barWidth + window.innerWidth * 0.05 - 25) + 'px'; }
javascript
{ "resource": "" }
q16492
train
function(per) { var self = this; // Get the Howl we want to manipulate. var sound = self.playlist[self.index].howl; // Convert the percent into a seek position. if (sound.playing()) { sound.seek(sound.duration() * per); } }
javascript
{ "resource": "" }
q16493
train
function() { var self = this; // Get the Howl we want to manipulate. var sound = self.playlist[self.index].howl; // Determine our current seek position. var seek = sound.seek() || 0; timer.innerHTML = self.formatTime(Math.round(seek)); progress.style.width = (((seek / sound.duration()) * 100) || 0) + '%'; // If the sound is still playing, continue stepping. if (sound.playing()) { requestAnimationFrame(self.step.bind(self)); } }
javascript
{ "resource": "" }
q16494
train
function() { var height = window.innerHeight * 0.3; var width = window.innerWidth; wave.height = height; wave.height_2 = height / 2; wave.MAX = wave.height_2 - 4; wave.width = width; wave.width_2 = width / 2; wave.width_4 = width / 4; wave.canvas.height = height; wave.canvas.width = width; wave.container.style.margin = -(height / 2) + 'px auto'; // Update the position of the slider. var sound = player.playlist[player.index].howl; if (sound) { var vol = sound.volume(); var barWidth = (vol * 0.9); sliderBtn.style.left = (window.innerWidth * barWidth + window.innerWidth * 0.05 - 25) + 'px'; } }
javascript
{ "resource": "" }
q16495
maketoc
train
function maketoc(element, enableSections) { enableSections = (enableSections != null) ? enableSections : true; var tmp = crawlDom(document.body, 2, 4, [], 30, enableSections); if (tmp.childNodes.length > 0) { element.appendChild(tmp); } }
javascript
{ "resource": "" }
q16496
addPoint
train
function addPoint(type, x, y) { var rpt = new mxPoint(x, y); rpt.type = type; actual.push(rpt); var curr = (state.routedPoints != null) ? state.routedPoints[actual.length - 1] : null; return curr == null || curr.type != type || curr.x != x || curr.y != y; }
javascript
{ "resource": "" }
q16497
short
train
function short(str, max) { if (str.length > max) { str = str.substring(0, Math.round(max / 2)) + '...' + str.substring(str.length - Math.round(max / 4)); } return str; }
javascript
{ "resource": "" }
q16498
reference
train
function reference(node, clone) { clone.originalNode = node; node = node.firstChild; var child = clone.firstChild; while (node != null && child != null) { reference(node, child); node = node.nextSibling; child = child.nextSibling; } return clone; }
javascript
{ "resource": "" }
q16499
checkNode
train
function checkNode(node, clone) { if (node != null) { if (clone.originalNode != node) { cleanNode(node); } else { node = node.firstChild; clone = clone.firstChild; while (node != null) { var nextNode = node.nextSibling; if (clone == null) { cleanNode(node); } else { checkNode(node, clone); clone = clone.nextSibling; } node = nextNode; } } } }
javascript
{ "resource": "" }