language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
_highlightCurrentPage () { const currentHref = window.location.href; const links = document.querySelectorAll('.nav-link'); if (links.length) { for (var i = links.length; i--;) { let link = links[i]; if (currentHref === link.href) { link.classList.add('active'); } else { link.classList.remove('active'); } } } }
_highlightCurrentPage () { const currentHref = window.location.href; const links = document.querySelectorAll('.nav-link'); if (links.length) { for (var i = links.length; i--;) { let link = links[i]; if (currentHref === link.href) { link.classList.add('active'); } else { link.classList.remove('active'); } } } }
JavaScript
function applyCookieExpiryPolicy () { const debug = false const cookieSetter = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie').set const cookieGetter = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie').get const lineTest = /(\()?(http[^)]+):[0-9]+:[0-9]+(\))?/ const loadPolicy = new Promise((resolve) => { loadedPolicyResolve = resolve }) defineProperty(document, 'cookie', { configurable: true, set: (value) => { // call the native document.cookie implementation. This will set the cookie immediately // if the value is valid. We will override this set later if the policy dictates that // the expiry should be changed. cookieSetter.apply(document, [value]) try { // determine the origins of the scripts in the stack const stack = new Error().stack.split('\n') const scriptOrigins = stack.reduce((origins, line) => { const res = line.match(lineTest) if (res && res[2]) { origins.add(new URL(res[2]).hostname) } return origins }, new Set()) // wait for config before doing same-site tests loadPolicy.then(({ shouldBlock, tabRegisteredDomain, policy, isTrackerFrame }) => { if (!tabRegisteredDomain || !shouldBlock) { // no site domain for this site to test against, abort debug && console.log('[ddg-cookie-policy] policy disabled on this page') return } const sameSiteScript = [...scriptOrigins].every((host) => host === tabRegisteredDomain || host.endsWith(`.${tabRegisteredDomain}`)) if (sameSiteScript) { // cookies set by scripts loaded on the same site as the site are not modified debug && console.log('[ddg-cookie-policy] ignored (sameSite)', value, [...scriptOrigins]) return } const trackerScript = [...scriptOrigins].some((host) => trackerHosts.has(host)) if (!trackerScript && !isTrackerFrame) { debug && console.log('[ddg-cookie-policy] ignored (non-tracker)', value, [...scriptOrigins]) return } // extract cookie expiry from cookie string const cookie = new Cookie(value) // apply cookie policy if (cookie.getExpiry() > policy.threshold) { // check if the cookie still exists if (document.cookie.split(';').findIndex(kv => kv.trim().startsWith(cookie.parts[0].trim())) !== -1) { cookie.maxAge = policy.maxAge debug && console.log('[ddg-cookie-policy] update', cookie.toString(), scriptOrigins) cookieSetter.apply(document, [cookie.toString()]) } else { debug && console.log('[ddg-cookie-policy] dissappeared', cookie.toString(), cookie.parts[0], scriptOrigins) } } else { debug && console.log('[ddg-cookie-policy] ignored (expiry)', value, scriptOrigins) } }) } catch (e) { // suppress error in cookie override to avoid breakage debug && console.warn('Error in cookie override', e) } }, get: cookieGetter }) }
function applyCookieExpiryPolicy () { const debug = false const cookieSetter = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie').set const cookieGetter = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie').get const lineTest = /(\()?(http[^)]+):[0-9]+:[0-9]+(\))?/ const loadPolicy = new Promise((resolve) => { loadedPolicyResolve = resolve }) defineProperty(document, 'cookie', { configurable: true, set: (value) => { // call the native document.cookie implementation. This will set the cookie immediately // if the value is valid. We will override this set later if the policy dictates that // the expiry should be changed. cookieSetter.apply(document, [value]) try { // determine the origins of the scripts in the stack const stack = new Error().stack.split('\n') const scriptOrigins = stack.reduce((origins, line) => { const res = line.match(lineTest) if (res && res[2]) { origins.add(new URL(res[2]).hostname) } return origins }, new Set()) // wait for config before doing same-site tests loadPolicy.then(({ shouldBlock, tabRegisteredDomain, policy, isTrackerFrame }) => { if (!tabRegisteredDomain || !shouldBlock) { // no site domain for this site to test against, abort debug && console.log('[ddg-cookie-policy] policy disabled on this page') return } const sameSiteScript = [...scriptOrigins].every((host) => host === tabRegisteredDomain || host.endsWith(`.${tabRegisteredDomain}`)) if (sameSiteScript) { // cookies set by scripts loaded on the same site as the site are not modified debug && console.log('[ddg-cookie-policy] ignored (sameSite)', value, [...scriptOrigins]) return } const trackerScript = [...scriptOrigins].some((host) => trackerHosts.has(host)) if (!trackerScript && !isTrackerFrame) { debug && console.log('[ddg-cookie-policy] ignored (non-tracker)', value, [...scriptOrigins]) return } // extract cookie expiry from cookie string const cookie = new Cookie(value) // apply cookie policy if (cookie.getExpiry() > policy.threshold) { // check if the cookie still exists if (document.cookie.split(';').findIndex(kv => kv.trim().startsWith(cookie.parts[0].trim())) !== -1) { cookie.maxAge = policy.maxAge debug && console.log('[ddg-cookie-policy] update', cookie.toString(), scriptOrigins) cookieSetter.apply(document, [cookie.toString()]) } else { debug && console.log('[ddg-cookie-policy] dissappeared', cookie.toString(), cookie.parts[0], scriptOrigins) } } else { debug && console.log('[ddg-cookie-policy] ignored (expiry)', value, scriptOrigins) } }) } catch (e) { // suppress error in cookie override to avoid breakage debug && console.warn('Error in cookie override', e) } }, get: cookieGetter }) }
JavaScript
function PacienteBuilder(){ var nome = "Rodrigo"; var idade = 23; var peso = 90; var altura = 1.86; var clazz = { constroi : function(){ return Paciente(nome, idade, peso, altura); }, comIdade : function(valor){ idade = valor; return this; }, comPeso : function(valor){ peso = valor; return this; } }; return clazz; }
function PacienteBuilder(){ var nome = "Rodrigo"; var idade = 23; var peso = 90; var altura = 1.86; var clazz = { constroi : function(){ return Paciente(nome, idade, peso, altura); }, comIdade : function(valor){ idade = valor; return this; }, comPeso : function(valor){ peso = valor; return this; } }; return clazz; }
JavaScript
function joinImports(app, file) { const base = fs.readFileSync(path.join(app.getAppPath(), 'src', 'themes', BASE), 'utf-8'); const mappings = fs.readFileSync(path.join(app.getAppPath(), 'src', 'themes', MAPPINGS), 'utf-8'); let contents = file.replace("@use 'base';", base); contents = contents.replace("@use 'mappings';", mappings); return contents; }
function joinImports(app, file) { const base = fs.readFileSync(path.join(app.getAppPath(), 'src', 'themes', BASE), 'utf-8'); const mappings = fs.readFileSync(path.join(app.getAppPath(), 'src', 'themes', MAPPINGS), 'utf-8'); let contents = file.replace("@use 'base';", base); contents = contents.replace("@use 'mappings';", mappings); return contents; }
JavaScript
function createWindow() { // Create the window, making it hidden initially. If we have // it on record, re-apply the window size last set by the user. const prefs = store.get('prefs') || {}; win = new BrowserWindow({ width: prefs.windowWidth || DEFAULT_WIDTH, height: prefs.windowHeight || DEFAULT_HEIGHT, icon, show: false, webPreferences: { spellcheck: true, preload: path.join(__dirname, 'preload.js'), nodeIntegration: true, contextIsolation: false } }) //win.webContents.openDevTools(); // Create the window's menu bar. let menuBar = Menu.buildFromTemplate([ { label: '&File', submenu: [ {label: '&Reload', click: () => {loadGoogleVoice();}}, // Reload Google Voice within our main window {label: 'Go to &website', click: () => {loadGoogleVoice(true);}}, // Open Google Voice externally in the user's browser {type: 'separator'}, {label: '&Settings', click: () => {showSettingsWindow()}}, // Open/display our Settings window {type: 'separator'}, {label: '&Exit', click: () => {exitApplication();}} // Exit the application ] }, { label: "Edit", submenu: [ { label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" }, { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" }, { type: "separator" }, { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" }, { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" }, { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" }, { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" } ] }, { label: '&View', submenu: [ {role: 'zoomIn', visible: false}, // Zoom in (Ctrl+Shift++) {role: 'zoomIn', accelerator: 'CommandOrControl+='}, // Zoom in (Ctrl+=) {role: 'zoomOut'}, // Zoom out (Ctrl+-) {role: 'zoomOut', visible: false, accelerator: 'CommandOrControl+Shift+_'}, // Zoom out (Ctrl+Shift+_) {role: 'resetZoom'}, // Reset zoom (Ctrl+0) {type: 'separator'}, {role: 'toggleFullScreen'}, // Toggle full screen (F11) {type: 'separator'}, {label: '&Hide menu bar', visible: !isMac(), click: () => {win.setMenuBarVisibility(false);}} // Hide the menu bar (not supported for Mac) ] }, { label: '&Help', submenu: [ {label: 'Report a &bug', click: () => {shell.openExternal(constants.URL_GITHUB_REPORT_BUG);}}, {label: 'Request a &feature', click: () => {shell.openExternal(constants.URL_GITHUB_FEATURE_REQUEST);}}, {label: 'Ask a &question', click: () => {shell.openExternal(constants.URL_GITHUB_ASK_QUESTION);}}, {label: 'View &issues', click: () => {shell.openExternal(constants.URL_GITHUB_VIEW_ISSUES);}}, {type: 'separator'}, {label: '&Security Policy', click: () => {shell.openExternal(constants.URL_GITHUB_SECURITY_POLICY);}}, {type: 'separator'}, {label: 'View &releases', click: () => {shell.openExternal(constants.URL_GITHUB_RELEASES);}}, {label: `&About (v${app.getVersion()})`, click: () => {shell.openExternal(constants.URL_GITHUB_README);}} ] } ]); // Set the menu bar's visibility. if (isMac()) { Menu.setApplicationMenu(menuBar) // On Mac, we always show the menu bar } else { // On Windows/Linux, we give the user a setting for hiding the menu bar. Add the menu bar to // the window (which ensures that its keyboard shortcuts will work regardless of the menu bar's // visibility), but make the menu bar visible only if the user hasn't asked us to hide it. win.setMenu(menuBar); if (((prefs.showMenuBar != undefined) && !prefs.showMenuBar) || !constants.DEFAULT_SETTING_SHOW_MENU_BAR) { win.setMenuBarVisibility(false); } } // Navigate the window to Google Voice. When it finishes loading, modify Google's markup as needed // to support user customizations that we allow the user to make from within our application UI. loadGoogleVoice(); win.webContents.on('did-finish-load', () => { // Re-apply the theme last selected by the user. const theme = store.get('prefs.theme') || constants.DEFAULT_SETTING_THEME; const hideDialerSidebar = store.get('prefs.hideDialerSidebar') || constants.DEFAULT_HIDE_DIALER_SIDEBAR; cssInjector = new CSSInjector(app, win); cssInjector.injectTheme(theme); cssInjector.showHideDialerSidebar(hideDialerSidebar); }); // Create our system notification area icon. if (tray) { tray.destroy; } tray = createTray(iconTray, constants.APPLICATION_NAME); badgeGenerator = new BadgeGenerator(win); win.webContents.on('new-window', function(e, url) { e.preventDefault(); // Cancel the request to open the target URL in a new window // If the target URL is a Google Voice URL, have our main window navigate to it instead of opening // it in a new window. This supports the ability to add additional accounts and switch between // them on-demand. Otherwise, for all other URLs, have the system open them using the default type // handler. This is done to force URLs to open in the user's browser, where they are likely already // signed into services that need authentication (e.g. Spotify). Note that if the user ever gets // stuck navigated somewhere that isn't the main Google Voice page, they can always use the "Reload" // item in the notification area icon context menu to get back to the Google Voice home page. const hostName = Url.parse(url).hostname; if ( hostName === 'voice.google.com' || hostName === 'accounts.google.com') { win && win.loadURL(url); } else { shell.openExternal(url); } }); // Whenever a request is made for the window to be closed, determine whether we should allow the close to // happen and terminate the application, or just hide the window and keep running in the notification area. win.on('close', function (event) { // Proceed based on the reason why the window is being closed. if (app.isQuiting) { // The window is being closed as a result of us calling app.quit() due to the // user's invocation of one of our "Exit" menu items. In this case, we'll // allow the close to happen. This will lead to termination of the application. } else { // The window is being closed as a result of the user explicitly trying to close // it. If the user has enabled the "exit on close" setting, allow the close and // subsequent termination of the application to proceed. Otherwise, cancel the // close and hide the window instead; we'll keep running in the notification area. const exitOnClose = store.get('prefs.exitOnClose') || constants.DEFAULT_SETTING_EXIT_ON_CLOSE; if (!exitOnClose) { event.preventDefault(); win.hide(); } } }); win.on('restore', function (event) { win.show(); }); win.on('resize', saveWindowSize); // Now that we've finished creating and initializing the window, show // it (unless the user has enabled the "start minimized" setting). if (!prefs.startMinimized) { win.show(); } return win; }
function createWindow() { // Create the window, making it hidden initially. If we have // it on record, re-apply the window size last set by the user. const prefs = store.get('prefs') || {}; win = new BrowserWindow({ width: prefs.windowWidth || DEFAULT_WIDTH, height: prefs.windowHeight || DEFAULT_HEIGHT, icon, show: false, webPreferences: { spellcheck: true, preload: path.join(__dirname, 'preload.js'), nodeIntegration: true, contextIsolation: false } }) //win.webContents.openDevTools(); // Create the window's menu bar. let menuBar = Menu.buildFromTemplate([ { label: '&File', submenu: [ {label: '&Reload', click: () => {loadGoogleVoice();}}, // Reload Google Voice within our main window {label: 'Go to &website', click: () => {loadGoogleVoice(true);}}, // Open Google Voice externally in the user's browser {type: 'separator'}, {label: '&Settings', click: () => {showSettingsWindow()}}, // Open/display our Settings window {type: 'separator'}, {label: '&Exit', click: () => {exitApplication();}} // Exit the application ] }, { label: "Edit", submenu: [ { label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" }, { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" }, { type: "separator" }, { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" }, { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" }, { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" }, { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" } ] }, { label: '&View', submenu: [ {role: 'zoomIn', visible: false}, // Zoom in (Ctrl+Shift++) {role: 'zoomIn', accelerator: 'CommandOrControl+='}, // Zoom in (Ctrl+=) {role: 'zoomOut'}, // Zoom out (Ctrl+-) {role: 'zoomOut', visible: false, accelerator: 'CommandOrControl+Shift+_'}, // Zoom out (Ctrl+Shift+_) {role: 'resetZoom'}, // Reset zoom (Ctrl+0) {type: 'separator'}, {role: 'toggleFullScreen'}, // Toggle full screen (F11) {type: 'separator'}, {label: '&Hide menu bar', visible: !isMac(), click: () => {win.setMenuBarVisibility(false);}} // Hide the menu bar (not supported for Mac) ] }, { label: '&Help', submenu: [ {label: 'Report a &bug', click: () => {shell.openExternal(constants.URL_GITHUB_REPORT_BUG);}}, {label: 'Request a &feature', click: () => {shell.openExternal(constants.URL_GITHUB_FEATURE_REQUEST);}}, {label: 'Ask a &question', click: () => {shell.openExternal(constants.URL_GITHUB_ASK_QUESTION);}}, {label: 'View &issues', click: () => {shell.openExternal(constants.URL_GITHUB_VIEW_ISSUES);}}, {type: 'separator'}, {label: '&Security Policy', click: () => {shell.openExternal(constants.URL_GITHUB_SECURITY_POLICY);}}, {type: 'separator'}, {label: 'View &releases', click: () => {shell.openExternal(constants.URL_GITHUB_RELEASES);}}, {label: `&About (v${app.getVersion()})`, click: () => {shell.openExternal(constants.URL_GITHUB_README);}} ] } ]); // Set the menu bar's visibility. if (isMac()) { Menu.setApplicationMenu(menuBar) // On Mac, we always show the menu bar } else { // On Windows/Linux, we give the user a setting for hiding the menu bar. Add the menu bar to // the window (which ensures that its keyboard shortcuts will work regardless of the menu bar's // visibility), but make the menu bar visible only if the user hasn't asked us to hide it. win.setMenu(menuBar); if (((prefs.showMenuBar != undefined) && !prefs.showMenuBar) || !constants.DEFAULT_SETTING_SHOW_MENU_BAR) { win.setMenuBarVisibility(false); } } // Navigate the window to Google Voice. When it finishes loading, modify Google's markup as needed // to support user customizations that we allow the user to make from within our application UI. loadGoogleVoice(); win.webContents.on('did-finish-load', () => { // Re-apply the theme last selected by the user. const theme = store.get('prefs.theme') || constants.DEFAULT_SETTING_THEME; const hideDialerSidebar = store.get('prefs.hideDialerSidebar') || constants.DEFAULT_HIDE_DIALER_SIDEBAR; cssInjector = new CSSInjector(app, win); cssInjector.injectTheme(theme); cssInjector.showHideDialerSidebar(hideDialerSidebar); }); // Create our system notification area icon. if (tray) { tray.destroy; } tray = createTray(iconTray, constants.APPLICATION_NAME); badgeGenerator = new BadgeGenerator(win); win.webContents.on('new-window', function(e, url) { e.preventDefault(); // Cancel the request to open the target URL in a new window // If the target URL is a Google Voice URL, have our main window navigate to it instead of opening // it in a new window. This supports the ability to add additional accounts and switch between // them on-demand. Otherwise, for all other URLs, have the system open them using the default type // handler. This is done to force URLs to open in the user's browser, where they are likely already // signed into services that need authentication (e.g. Spotify). Note that if the user ever gets // stuck navigated somewhere that isn't the main Google Voice page, they can always use the "Reload" // item in the notification area icon context menu to get back to the Google Voice home page. const hostName = Url.parse(url).hostname; if ( hostName === 'voice.google.com' || hostName === 'accounts.google.com') { win && win.loadURL(url); } else { shell.openExternal(url); } }); // Whenever a request is made for the window to be closed, determine whether we should allow the close to // happen and terminate the application, or just hide the window and keep running in the notification area. win.on('close', function (event) { // Proceed based on the reason why the window is being closed. if (app.isQuiting) { // The window is being closed as a result of us calling app.quit() due to the // user's invocation of one of our "Exit" menu items. In this case, we'll // allow the close to happen. This will lead to termination of the application. } else { // The window is being closed as a result of the user explicitly trying to close // it. If the user has enabled the "exit on close" setting, allow the close and // subsequent termination of the application to proceed. Otherwise, cancel the // close and hide the window instead; we'll keep running in the notification area. const exitOnClose = store.get('prefs.exitOnClose') || constants.DEFAULT_SETTING_EXIT_ON_CLOSE; if (!exitOnClose) { event.preventDefault(); win.hide(); } } }); win.on('restore', function (event) { win.show(); }); win.on('resize', saveWindowSize); // Now that we've finished creating and initializing the window, show // it (unless the user has enabled the "start minimized" setting). if (!prefs.startMinimized) { win.show(); } return win; }
JavaScript
function TacticsGame(pieces, currentPiece, hasMoved){ currentPiece = currentPiece |0; if (!pieces[currentPiece]) { raise("Current piece ", currentPiece, " is not valid (pieces: ", JSON.stringify(pieces), ")!"); } Game.call(this, pieces[currentPiece].owner); this.pieces = pieces; this.currentPiece = currentPiece; this.hasMoved = !!hasMoved; // Map of positions to pieces, used to speed up move calculations. this.__piecesByPosition__ = iterable(pieces).map(function (p) { return [p.position +'', p]; }).toObject(); }
function TacticsGame(pieces, currentPiece, hasMoved){ currentPiece = currentPiece |0; if (!pieces[currentPiece]) { raise("Current piece ", currentPiece, " is not valid (pieces: ", JSON.stringify(pieces), ")!"); } Game.call(this, pieces[currentPiece].owner); this.pieces = pieces; this.currentPiece = currentPiece; this.hasMoved = !!hasMoved; // Map of positions to pieces, used to speed up move calculations. this.__piecesByPosition__ = iterable(pieces).map(function (p) { return [p.position +'', p]; }).toObject(); }
JavaScript
function moves(){ if (!this.hasOwnProperty('__moves__')) { // this.__moves__ is used to cache the move calculations. var currentPiece = this.pieces[this.currentPiece]; if (currentPiece && !this.result()) { // There is a current piece and the game has not finished. this.__moves__ = {}; if (!this.hasMoved) { this.__moves__[currentPiece.owner] = currentPiece.moves(this); } else { this.__moves__[currentPiece.owner] = ['pass'].concat(currentPiece.possibleAttacks(this)); } } else { this.__moves__ = null; } } return this.__moves__; }
function moves(){ if (!this.hasOwnProperty('__moves__')) { // this.__moves__ is used to cache the move calculations. var currentPiece = this.pieces[this.currentPiece]; if (currentPiece && !this.result()) { // There is a current piece and the game has not finished. this.__moves__ = {}; if (!this.hasMoved) { this.__moves__[currentPiece.owner] = currentPiece.moves(this); } else { this.__moves__[currentPiece.owner] = ['pass'].concat(currentPiece.possibleAttacks(this)); } } else { this.__moves__ = null; } } return this.__moves__; }
JavaScript
function next(moves){ var currentPiece = this.pieces[this.currentPiece], newPieces = this.pieces.concat([]); if (!moves.hasOwnProperty(currentPiece.owner)) { console.log(this +"\n"+ JSON.stringify(moves) +" from "+ JSON.stringify(this.moves()) +"!");//FIXME delete this.__moves__; console.log("\t"+ JSON.stringify(this.moves()) +"?");//FIXME raise("Active player ", currentPiece.owner, " has no moves in ", JSON.stringify(moves), "!"); } var move = moves[currentPiece.owner]; if (!this.hasMoved) { newPieces[this.currentPiece] = currentPiece.moveTo(move); return new this.constructor(newPieces, this.currentPiece, true); } else { var nextPiece = this.currentPiece + 1; if (move !== 'pass') { var target = this.pieces[move], attackedPiece = currentPiece.attack(target); if (attackedPiece.isDestroyed()) { if (move < this.currentPiece) { nextPiece--; } newPieces.splice(move, 1); } else { newPieces[move] = attackedPiece; } } return new this.constructor(newPieces, nextPiece % newPieces.length, false); } }
function next(moves){ var currentPiece = this.pieces[this.currentPiece], newPieces = this.pieces.concat([]); if (!moves.hasOwnProperty(currentPiece.owner)) { console.log(this +"\n"+ JSON.stringify(moves) +" from "+ JSON.stringify(this.moves()) +"!");//FIXME delete this.__moves__; console.log("\t"+ JSON.stringify(this.moves()) +"?");//FIXME raise("Active player ", currentPiece.owner, " has no moves in ", JSON.stringify(moves), "!"); } var move = moves[currentPiece.owner]; if (!this.hasMoved) { newPieces[this.currentPiece] = currentPiece.moveTo(move); return new this.constructor(newPieces, this.currentPiece, true); } else { var nextPiece = this.currentPiece + 1; if (move !== 'pass') { var target = this.pieces[move], attackedPiece = currentPiece.attack(target); if (attackedPiece.isDestroyed()) { if (move < this.currentPiece) { nextPiece--; } newPieces.splice(move, 1); } else { newPieces[move] = attackedPiece; } } return new this.constructor(newPieces, nextPiece % newPieces.length, false); } }
JavaScript
function result(){ var game = this, pieceCounts = iterable(this.players).map(function (player) { var count = game.pieces.filter(function (piece){ return piece.owner === player; }).length; return [player, count]; }).toObject(); if (pieceCounts.Left < 1) { return this.victory('Right', pieceCounts.Right); } else if (pieceCounts.Right < 1) { return this.victory('Left', pieceCounts.Left); } else { return null; } }
function result(){ var game = this, pieceCounts = iterable(this.players).map(function (player) { var count = game.pieces.filter(function (piece){ return piece.owner === player; }).length; return [player, count]; }).toObject(); if (pieceCounts.Left < 1) { return this.victory('Right', pieceCounts.Right); } else if (pieceCounts.Right < 1) { return this.victory('Left', pieceCounts.Left); } else { return null; } }
JavaScript
function moves(game){ var visited = {}, pending = [this.position], current, up, left, right, down; for (var ms = 0; ms <= this.movement; ms++) { current = pending; pending = []; current.forEach(function (xpos) { if (!(xpos in visited)) { visited[xpos] = xpos; up = [xpos[0], xpos[1] + 1]; left = [xpos[0] - 1, xpos[1]]; right = [xpos[0] + 1, xpos[1]]; down = [xpos[0], xpos[1] - 1]; [up, left, right, down].forEach(function (p) { if (game.isPassable(p)) { pending.push(p); } }); } }); } return iterable(visited).select(1).toArray(); // Return the values of visited. }
function moves(game){ var visited = {}, pending = [this.position], current, up, left, right, down; for (var ms = 0; ms <= this.movement; ms++) { current = pending; pending = []; current.forEach(function (xpos) { if (!(xpos in visited)) { visited[xpos] = xpos; up = [xpos[0], xpos[1] + 1]; left = [xpos[0] - 1, xpos[1]]; right = [xpos[0] + 1, xpos[1]]; down = [xpos[0], xpos[1] - 1]; [up, left, right, down].forEach(function (p) { if (game.isPassable(p)) { pending.push(p); } }); } }); } return iterable(visited).select(1).toArray(); // Return the values of visited. }
JavaScript
function moveTo(position) { var r = this.clone(); r.position = position; return r; }
function moveTo(position) { var r = this.clone(); r.position = position; return r; }
JavaScript
function bresenham(game, destination) { var x0 = this.position[0], y0 = this.position[1], x1 = destination[0], y1 = destination[1], dx = Math.abs(x1 - x0), dy = Math.abs(y1 - y0); if (dx <= 1 && dy <= 1){ return true; } var sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1, err = (dx > dy ? dx : -dy) / 2, err2; while (x0 !== x1 || y0 !== y1) { if (!game.isClear([x0, y0])) { return false; } err2 = err; if (err2 > -dx) { err -= dy; x0 += sx; } if (err2 < dy) { err += dx; y0 += sy; } } return true; }
function bresenham(game, destination) { var x0 = this.position[0], y0 = this.position[1], x1 = destination[0], y1 = destination[1], dx = Math.abs(x1 - x0), dy = Math.abs(y1 - y0); if (dx <= 1 && dy <= 1){ return true; } var sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1, err = (dx > dy ? dx : -dy) / 2, err2; while (x0 !== x1 || y0 !== y1) { if (!game.isClear([x0, y0])) { return false; } err2 = err; if (err2 > -dx) { err -= dy; x0 += sx; } if (err2 < dy) { err += dx; y0 += sy; } } return true; }
JavaScript
function possibleAttacks(game){ var self = this; return iterable(game.pieces).filter(function (piece) { if (piece !== self && piece.owner != self.owner) { var dist = Math.sqrt(Math.pow(self.position[0] - piece.position[0], 2) + Math.pow(self.position[1] - piece.position[1], 2)); return dist <= self.attackRange && self.pieceInLineOfSight(game, piece); } else { return false; } }, function (piece, i) { return i; }).toArray(); }
function possibleAttacks(game){ var self = this; return iterable(game.pieces).filter(function (piece) { if (piece !== self && piece.owner != self.owner) { var dist = Math.sqrt(Math.pow(self.position[0] - piece.position[0], 2) + Math.pow(self.position[1] - piece.position[1], 2)); return dist <= self.attackRange && self.pieceInLineOfSight(game, piece); } else { return false; } }, function (piece, i) { return i; }).toArray(); }
JavaScript
function attack(piece){ piece = piece.clone(); piece.damage += this.attackDamage * this.attackChance * (1 - piece.defenseChance); return piece; }
function attack(piece){ piece = piece.clone(); piece.damage += this.attackDamage * this.attackChance * (1 - piece.defenseChance); return piece; }
JavaScript
function activePlayer() { var len = this.activePlayers.length; raiseIf(len < 1, 'There is no active player.'); raiseIf(len > 1, 'More than one player is active.'); return this.activePlayers[0]; }
function activePlayer() { var len = this.activePlayers.length; raiseIf(len < 1, 'There is no active player.'); raiseIf(len > 1, 'More than one player is active.'); return this.activePlayers[0]; }
JavaScript
function opponents(players) { players = players || this.activePlayers; return this.players.filter(function (p) { return players.indexOf(p) < 0; }); }
function opponents(players) { players = players || this.activePlayers; return this.players.filter(function (p) { return players.indexOf(p) < 0; }); }
JavaScript
function perform() { var moves = {}, move, player; for (var i = 0; i < arguments.length; i += 2) { player = arguments[i + 1]; if (typeof player === 'undefined') { player = this.activePlayer(); } moves[player] = arguments[i]; } return this.next(moves); }
function perform() { var moves = {}, move, player; for (var i = 0; i < arguments.length; i += 2) { player = arguments[i + 1]; if (typeof player === 'undefined') { player = this.activePlayer(); } moves[player] = arguments[i]; } return this.next(moves); }
JavaScript
function possibleMoves(moves) { moves = arguments.length < 1 ? this.moves() : moves; if (!moves || typeof moves !== 'object') { return []; } var activePlayers = Object.keys(moves); if (activePlayers.length === 1) { // Most common case. var activePlayer = activePlayers[0]; return moves[activePlayer].map(function (move) { return obj(activePlayer, move); }); } else { // Simultaneous games. return Iterable.product.apply(Iterable, iterable(moves).mapApply(function (player, moves) { return moves.map(function (move) { return [player, move]; }); }).toArray() ).map(function (playerMoves) { return iterable(playerMoves).toObject(); }).toArray(); } }
function possibleMoves(moves) { moves = arguments.length < 1 ? this.moves() : moves; if (!moves || typeof moves !== 'object') { return []; } var activePlayers = Object.keys(moves); if (activePlayers.length === 1) { // Most common case. var activePlayer = activePlayers[0]; return moves[activePlayer].map(function (move) { return obj(activePlayer, move); }); } else { // Simultaneous games. return Iterable.product.apply(Iterable, iterable(moves).mapApply(function (player, moves) { return moves.map(function (move) { return [player, move]; }); }).toArray() ).map(function (playerMoves) { return iterable(playerMoves).toObject(); }).toArray(); } }
JavaScript
function zerosumResult(score, players) { players = !players ? this.activePlayers : (!Array.isArray(players) ? [players] : players); score = (+score) / (players.length || 1); var result = ({}), player, opponentScore = -score / (this.players.length - players.length || 1); for (var i = 0; i < this.players.length; i++) { player = this.players[i]; result[player] = players.indexOf(player) < 0 ? opponentScore : score; } return result; }
function zerosumResult(score, players) { players = !players ? this.activePlayers : (!Array.isArray(players) ? [players] : players); score = (+score) / (players.length || 1); var result = ({}), player, opponentScore = -score / (this.players.length - players.length || 1); for (var i = 0; i < this.players.length; i++) { player = this.players[i]; result[player] = players.indexOf(player) < 0 ? opponentScore : score; } return result; }
JavaScript
function draw(players, score) { score = +(score || 0); players = players || this.players; var result = ({}); for (var player in players) { result[players[player]] = score; } return result; }
function draw(players, score) { score = +(score || 0); players = players || this.players; var result = ({}); for (var player in players) { result[players[player]] = score; } return result; }
JavaScript
function fromJSON(data) { if (typeof data === 'string') { data = JSON.parse(data); raiseIf(!Array.isArray(data) || data.length < 1, "Invalid JSON data: "+ data +"!"); } else { raiseIf(!Array.isArray(data) || data.length < 1, "Invalid JSON data: "+ data +"!"); data = data.slice(); // Shallow copy. } var cons = games[data[0]]; raiseIf(typeof cons !== 'function', "Unknown game '", data[0], "'!"); if (typeof cons.fromJSON === 'function') { return cons.fromJSON(data); // Call game's fromJSON. } else { // Call game's constructor. data[0] = this; return new (cons.bind.apply(cons, data))(); } }
function fromJSON(data) { if (typeof data === 'string') { data = JSON.parse(data); raiseIf(!Array.isArray(data) || data.length < 1, "Invalid JSON data: "+ data +"!"); } else { raiseIf(!Array.isArray(data) || data.length < 1, "Invalid JSON data: "+ data +"!"); data = data.slice(); // Shallow copy. } var cons = games[data[0]]; raiseIf(typeof cons !== 'function', "Unknown game '", data[0], "'!"); if (typeof cons.fromJSON === 'function') { return cons.fromJSON(data); // Call game's fromJSON. } else { // Call game's constructor. data[0] = this; return new (cons.bind.apply(cons, data))(); } }
JavaScript
function serialized(game) { var super_moves = game.prototype.moves, super_next = game.prototype.next; return declare(game, { /** The `moves()` of a serialized game returns the moves of the player deemed as the active player, if there are any moves. */ moves: function moves() { var fixedMoves = this.__fixedMoves__ || (this.__fixedMoves__ = {}), allMoves = super_moves.call(this), activePlayer; for (var i = 0; i < this.activePlayers.length; i++) { if (fixedMoves.hasOwnProperty(this.activePlayers[i])) { activePlayer = this.activePlayers[i]; break; } } return activePlayer && allMoves ? obj(activePlayer, allMoves[activePlayer]) : null; }, /** The `next(moves)` of a serialized game advances the actual game if with the given move all active players in the real game state have moved. Else the next player that has to move becomes active. */ next: function next(moves) { var nextFixedMoves = copy({}, this.fixedMoves || {}, moves), allMoved = iterable(this.players).all(function (p) { return nextFixedMoves.hasOwnProperty(p); }), result; if (allMoved) { result = super_next.call(this, nextFixedMoves); result.fixedMoves = {}; } else { result = this.clone(); result.fixedMoves = nextFixedMoves; } return result; } }); } // static serialized
function serialized(game) { var super_moves = game.prototype.moves, super_next = game.prototype.next; return declare(game, { /** The `moves()` of a serialized game returns the moves of the player deemed as the active player, if there are any moves. */ moves: function moves() { var fixedMoves = this.__fixedMoves__ || (this.__fixedMoves__ = {}), allMoves = super_moves.call(this), activePlayer; for (var i = 0; i < this.activePlayers.length; i++) { if (fixedMoves.hasOwnProperty(this.activePlayers[i])) { activePlayer = this.activePlayers[i]; break; } } return activePlayer && allMoves ? obj(activePlayer, allMoves[activePlayer]) : null; }, /** The `next(moves)` of a serialized game advances the actual game if with the given move all active players in the real game state have moved. Else the next player that has to move becomes active. */ next: function next(moves) { var nextFixedMoves = copy({}, this.fixedMoves || {}, moves), allMoved = iterable(this.players).all(function (p) { return nextFixedMoves.hasOwnProperty(p); }), result; if (allMoved) { result = super_next.call(this, nextFixedMoves); result.fixedMoves = {}; } else { result = this.clone(); result.fixedMoves = nextFixedMoves; } return result; } }); } // static serialized
JavaScript
function moves() { var fixedMoves = this.__fixedMoves__ || (this.__fixedMoves__ = {}), allMoves = super_moves.call(this), activePlayer; for (var i = 0; i < this.activePlayers.length; i++) { if (fixedMoves.hasOwnProperty(this.activePlayers[i])) { activePlayer = this.activePlayers[i]; break; } } return activePlayer && allMoves ? obj(activePlayer, allMoves[activePlayer]) : null; }
function moves() { var fixedMoves = this.__fixedMoves__ || (this.__fixedMoves__ = {}), allMoves = super_moves.call(this), activePlayer; for (var i = 0; i < this.activePlayers.length; i++) { if (fixedMoves.hasOwnProperty(this.activePlayers[i])) { activePlayer = this.activePlayers[i]; break; } } return activePlayer && allMoves ? obj(activePlayer, allMoves[activePlayer]) : null; }
JavaScript
function next(moves) { var nextFixedMoves = copy({}, this.fixedMoves || {}, moves), allMoved = iterable(this.players).all(function (p) { return nextFixedMoves.hasOwnProperty(p); }), result; if (allMoved) { result = super_next.call(this, nextFixedMoves); result.fixedMoves = {}; } else { result = this.clone(); result.fixedMoves = nextFixedMoves; } return result; }
function next(moves) { var nextFixedMoves = copy({}, this.fixedMoves || {}, moves), allMoved = iterable(this.players).all(function (p) { return nextFixedMoves.hasOwnProperty(p); }), result; if (allMoved) { result = super_next.call(this, nextFixedMoves); result.fixedMoves = {}; } else { result = this.clone(); result.fixedMoves = nextFixedMoves; } return result; }
JavaScript
function Match(game, players) { this.game = game; this.players = Array.isArray(players) ? iterable(game.players).zip(players).toObject() : players; /** The match records the sequence of game state in `Match.history`. */ this.history = [game]; this.events = new Events({ events: ['begin', 'move', 'next', 'end', 'quit'] }); for (var p in this.players) { // Participate the players. this.players[p] = this.players[p].participate(this, p) || this.players[p]; } }
function Match(game, players) { this.game = game; this.players = Array.isArray(players) ? iterable(game.players).zip(players).toObject() : players; /** The match records the sequence of game state in `Match.history`. */ this.history = [game]; this.events = new Events({ events: ['begin', 'move', 'next', 'end', 'quit'] }); for (var p in this.players) { // Participate the players. this.players[p] = this.players[p].participate(this, p) || this.players[p]; } }
JavaScript
function decisions(game) { game = game || this.state(); var match = this, players = this.players, activePlayers = game.activePlayers; return Future.all(activePlayers.map(function (p) { return players[p].decision(game.view(p), p); })).then(function (decisions) { var moves = iterable(activePlayers).zip(decisions).toObject(); match.onMove(game, moves); return moves; }); }
function decisions(game) { game = game || this.state(); var match = this, players = this.players, activePlayers = game.activePlayers; return Future.all(activePlayers.map(function (p) { return players[p].decision(game.view(p), p); })).then(function (decisions) { var moves = iterable(activePlayers).zip(decisions).toObject(); match.onMove(game, moves); return moves; }); }
JavaScript
function run(plys) { plys = isNaN(plys) ? Infinity : +plys; if (plys < 1) { // If the run must stop... return Future.when(this); } var ply = this.ply(), game = this.state(), results, next; if (ply < 1) { this.onBegin(game); } game = this.__advanceAleatories__(game); // Instantiate all random variables. results = game.result(); if (results) { // If the match has finished ... this.onEnd(game, results); return Future.when(this); } else { // Else the run must continue ... var match = this; return this.decisions(game).then(function (moves) { if (match.__advance__(game, moves)) { return match.run(plys - 1); } else { return match; } }); } }
function run(plys) { plys = isNaN(plys) ? Infinity : +plys; if (plys < 1) { // If the run must stop... return Future.when(this); } var ply = this.ply(), game = this.state(), results, next; if (ply < 1) { this.onBegin(game); } game = this.__advanceAleatories__(game); // Instantiate all random variables. results = game.result(); if (results) { // If the match has finished ... this.onEnd(game, results); return Future.when(this); } else { // Else the run must continue ... var match = this; return this.decisions(game).then(function (moves) { if (match.__advance__(game, moves)) { return match.run(plys - 1); } else { return match; } }); } }
JavaScript
function onNext(game, next) { this.events.emit('next', game, next, this); if (this.logger) { this.logger.info('Match advances from ', game, ' to ', next); } }
function onNext(game, next) { this.events.emit('next', game, next, this); if (this.logger) { this.logger.info('Match advances from ', game, ' to ', next); } }
JavaScript
function account(match) { var game = this.game, results = match.result(), isDraw = false, stats = this.statistics; raiseIf(!results, "Match doesn't have results. Has it finished?"); iterable(match.players).forEach(function (p) { // Player statistics. var role = p[0], player = p[1], playerResult = results[p[0]]; stats.add({key:'results', game:game.name, role:role, player:player.name}, playerResult); stats.add({key:(playerResult > 0 ? 'victories' : playerResult < 0 ? 'defeats' : 'draws'), game:game.name, role:role, player:player.name}, playerResult); stats.add({key:'length', game:game.name, role:role, player:player.name}, match.ply()); //FIXME This may not be accurate if the game has random variables. match.history.forEach(function (entry) { if (typeof entry.moves === 'function') { var moves = entry.moves(); if (moves && moves.hasOwnProperty(role) && moves[role].length > 0) { stats.add({key:'width', game:game.name, role:role, player:player.name}, moves[role].length); } } }); }); }
function account(match) { var game = this.game, results = match.result(), isDraw = false, stats = this.statistics; raiseIf(!results, "Match doesn't have results. Has it finished?"); iterable(match.players).forEach(function (p) { // Player statistics. var role = p[0], player = p[1], playerResult = results[p[0]]; stats.add({key:'results', game:game.name, role:role, player:player.name}, playerResult); stats.add({key:(playerResult > 0 ? 'victories' : playerResult < 0 ? 'defeats' : 'draws'), game:game.name, role:role, player:player.name}, playerResult); stats.add({key:'length', game:game.name, role:role, player:player.name}, match.ply()); //FIXME This may not be accurate if the game has random variables. match.history.forEach(function (entry) { if (typeof entry.moves === 'function') { var moves = entry.moves(); if (moves && moves.hasOwnProperty(role) && moves[role].length > 0) { stats.add({key:'width', game:game.name, role:role, player:player.name}, moves[role].length); } } }); }); }
JavaScript
function Aleatory(next, random) { this.random = random || Randomness.DEFAULT; if (typeof next === 'function') { this.next = next; } }
function Aleatory(next, random) { this.random = random || Randomness.DEFAULT; if (typeof next === 'function') { this.next = next; } }
JavaScript
function value() { var n = this.random.random(), v; iterable(this.distribution()).forEach(function (pair) { n -= pair[1]; if (n <= 0) { v = pair[0]; throw Iterable.STOP_ITERATION; } }); if (typeof v === 'undefined') { throw new Error("Random value could not be obtained."); } return v; }
function value() { var n = this.random.random(), v; iterable(this.distribution()).forEach(function (pair) { n -= pair[1]; if (n <= 0) { v = pair[0]; throw Iterable.STOP_ITERATION; } }); if (typeof v === 'undefined') { throw new Error("Random value could not be obtained."); } return v; }
JavaScript
function fromDistribution(dist, next, random) { var alea = new Aleatory(next, random); alea.distribution = function distribution() { return dist; }; return alea; }
function fromDistribution(dist, next, random) { var alea = new Aleatory(next, random); alea.distribution = function distribution() { return dist; }; return alea; }
JavaScript
function withDistribution(dist) { return declare(Aleatory, { distribution: function distribution() { return dist; }, }); }
function withDistribution(dist) { return declare(Aleatory, { distribution: function distribution() { return dist; }, }); }
JavaScript
function fromValues(values, next, random) { values = iterable(values).toArray(); var prob = 1 / values.length, alea = new Aleatory(next, random); alea.value = function value() { return this.random.choice(values); }; alea.distribution = function distribution() { return values.map(function (value) { return [value, prob]; }); }; return alea; }
function fromValues(values, next, random) { values = iterable(values).toArray(); var prob = 1 / values.length, alea = new Aleatory(next, random); alea.value = function value() { return this.random.choice(values); }; alea.distribution = function distribution() { return values.map(function (value) { return [value, prob]; }); }; return alea; }
JavaScript
function withValues(values) { values = iterable(values).toArray(); var prob = 1 / values.length; return declare(Aleatory, { value: function value() { return this.random.choice(values); }, distribution: function distribution() { return values.map(function (value) { return [value, prob]; }); } }); }
function withValues(values) { values = iterable(values).toArray(); var prob = 1 / values.length; return declare(Aleatory, { value: function value() { return this.random.choice(values); }, distribution: function distribution() { return values.map(function (value) { return [value, prob]; }); } }); }
JavaScript
function asString(line) { var board = this; return line.map(function (coord) { return board.square(coord); }).join(''); }
function asString(line) { var board = this; return line.map(function (coord) { return board.square(coord); }).join(''); }
JavaScript
function asRegExp(line, insideLine, outsideLine) { outsideLine = outsideLine || '.'; var width = this.width, squares = Iterable.repeat(false, width * this.height).toArray(); line.forEach(function (coord) { squares[coord[0] * width + coord[1]] = true; }); var result = '', count = 0, current; for (var i = 0; i < squares.length; count = 0) { current = squares[i]; do { ++count; } while (++i < squares.length && squares[i] === current); if (count < 2) { result += current ? insideLine : outsideLine; } else { result += (current ? insideLine : outsideLine) +'{'+ count +'}'; } } return result; }
function asRegExp(line, insideLine, outsideLine) { outsideLine = outsideLine || '.'; var width = this.width, squares = Iterable.repeat(false, width * this.height).toArray(); line.forEach(function (coord) { squares[coord[0] * width + coord[1]] = true; }); var result = '', count = 0, current; for (var i = 0; i < squares.length; count = 0) { current = squares[i]; do { ++count; } while (++i < squares.length && squares[i] === current); if (count < 2) { result += current ? insideLine : outsideLine; } else { result += (current ? insideLine : outsideLine) +'{'+ count +'}'; } } return result; }
JavaScript
function asRegExps(lines, insideLine, outsideLine) { var board = this; return lines.map(function (line) { return board.asRegExp(line, insideLine, outsideLine); }).join('|'); }
function asRegExps(lines, insideLine, outsideLine) { var board = this; return lines.map(function (line) { return board.asRegExp(line, insideLine, outsideLine); }).join('|'); }
JavaScript
function CheckerboardFromPieces(height, width, pieces, emptySquare) { Checkerboard.call(this, height, width); if (arguments.length > 3) { this.emptySquare = emptySquare; } this.pieces = iterable(pieces || []).map(function (piece) { var position = piece.position; return [position[0] * width + position[1], piece]; }).toObject(); }
function CheckerboardFromPieces(height, width, pieces, emptySquare) { Checkerboard.call(this, height, width); if (arguments.length > 3) { this.emptySquare = emptySquare; } this.pieces = iterable(pieces || []).map(function (piece) { var position = piece.position; return [position[0] * width + position[1], piece]; }).toObject(); }
JavaScript
function clone() { var newPieces = [].concat(this.pieces); if (this.hasOwnProperty('emptySquare')) { return new this.constructor(this.height, this.width, newPieces, this.emptySquare); } else { return new this.constructor(this.height, this.width, newPieces); } }
function clone() { var newPieces = [].concat(this.pieces); if (this.hasOwnProperty('emptySquare')) { return new this.constructor(this.height, this.width, newPieces, this.emptySquare); } else { return new this.constructor(this.height, this.width, newPieces); } }
JavaScript
function Scanner(config) { initialize(this, config) // + `game`: Game to scan. .object("game", { ignore: true }) // + `maxWidth=1000`: Maximum amount of game states held at each step. .integer("maxWidth", { defaultValue: 1000, coerce: true }) // + `maxLength=50`: Maximum length of simulated matches. .integer("maxLength", { defaultValue: 50, coerce: true }) // + `random=randomness.DEFAULT`: Pseudorandom number generator to use in the simulations. .object("random", { defaultValue: Randomness.DEFAULT }) // + `statistics=<new>`: Component to gather relevant statistics. .object("statistics", { defaultValue: new Statistics() }); }
function Scanner(config) { initialize(this, config) // + `game`: Game to scan. .object("game", { ignore: true }) // + `maxWidth=1000`: Maximum amount of game states held at each step. .integer("maxWidth", { defaultValue: 1000, coerce: true }) // + `maxLength=50`: Maximum length of simulated matches. .integer("maxLength", { defaultValue: 50, coerce: true }) // + `random=randomness.DEFAULT`: Pseudorandom number generator to use in the simulations. .object("random", { defaultValue: Randomness.DEFAULT }) // + `statistics=<new>`: Component to gather relevant statistics. .object("statistics", { defaultValue: new Statistics() }); }
JavaScript
function scan(players) { var scanner = this, window = arguments.length < 2 ? (this.game ? [this.game] : []) : Array.prototype.slice.call(arguments, 1), ply = 0; return Future.whileDo(function () { return window.length > 0 && ply < scanner.maxLength; }, function () { return Future.all(window.map(function (game) { return scanner.__advance__(players, game, ply); })).then(function (level) { window = iterable(level).flatten().sample(scanner.maxWidth, scanner.random).toArray(); return ++ply; }); }).then(function () { scanner.statistics.add({ key:'aborted' }, window.length); return scanner.statistics; }); }
function scan(players) { var scanner = this, window = arguments.length < 2 ? (this.game ? [this.game] : []) : Array.prototype.slice.call(arguments, 1), ply = 0; return Future.whileDo(function () { return window.length > 0 && ply < scanner.maxLength; }, function () { return Future.all(window.map(function (game) { return scanner.__advance__(players, game, ply); })).then(function (level) { window = iterable(level).flatten().sample(scanner.maxWidth, scanner.random).toArray(); return ++ply; }); }).then(function () { scanner.statistics.add({ key:'aborted' }, window.length); return scanner.statistics; }); }
JavaScript
function GameTree(parent, state, transition) { this.parent = parent; this.state = state; this.transition = transition; this.children = {}; }
function GameTree(parent, state, transition) { this.parent = parent; this.state = state; this.transition = transition; this.children = {}; }
JavaScript
function expand(transition) { var key = this.__childSerialization__(transition), child = this.children[key], nextState; if (!child) { try { nextState = this.state.next(transition); // Whether state is an instance of Game or Aleatory. } catch (err) { raise("Node expansion for ", this.state, " with ", JSON.stringify(transition), " failed with: ", err); } child = new this.constructor(this, nextState, transition); this.children[key] = child; } return child; }
function expand(transition) { var key = this.__childSerialization__(transition), child = this.children[key], nextState; if (!child) { try { nextState = this.state.next(transition); // Whether state is an instance of Game or Aleatory. } catch (err) { raise("Node expansion for ", this.state, " with ", JSON.stringify(transition), " failed with: ", err); } child = new this.constructor(this, nextState, transition); this.children[key] = child; } return child; }
JavaScript
function possibleTransitions() { if (this.state instanceof Aleatory) { return this.state.distribution(); } else if (this.state instanceof Game) { return this.state.possibleMoves(); } else { raise("Cannot get possible transitions from ("+ this.state +")! Is it a Game or Aleatory?"); } }
function possibleTransitions() { if (this.state instanceof Aleatory) { return this.state.distribution(); } else if (this.state instanceof Game) { return this.state.possibleMoves(); } else { raise("Cannot get possible transitions from ("+ this.state +")! Is it a Game or Aleatory?"); } }
JavaScript
function expandAll() { var node = this; return this.possibleTransitions().map(function (transition) { return node.expand(transition); }); }
function expandAll() { var node = this; return this.possibleTransitions().map(function (transition) { return node.expand(transition); }); }
JavaScript
function moveEvaluation(move, game, player) { if (Object.keys(move).length < 2) { // One active player. return this.stateEvaluation(game.next(move), player); } else { // Many active players. var sum = 0, count = 0; move = copy(obj(player, [move[player]]), move); game.possibleMoves(move).forEach(function (ms) { sum += this.stateEvaluation(game.next(ms), player); ++count; }); return count > 0 ? sum / count : 0; // Average all evaluations. } }
function moveEvaluation(move, game, player) { if (Object.keys(move).length < 2) { // One active player. return this.stateEvaluation(game.next(move), player); } else { // Many active players. var sum = 0, count = 0; move = copy(obj(player, [move[player]]), move); game.possibleMoves(move).forEach(function (ms) { sum += this.stateEvaluation(game.next(ms), player); ++count; }); return count > 0 ? sum / count : 0; // Average all evaluations. } }
JavaScript
function bestMoves(evaluatedMoves) { return iterable(evaluatedMoves).greater(function (pair) { return pair[1]; }).map(function (pair) { return pair[0]; }); }
function bestMoves(evaluatedMoves) { return iterable(evaluatedMoves).greater(function (pair) { return pair[1]; }).map(function (pair) { return pair[0]; }); }
JavaScript
function selectMoves(moves, game, player) { var heuristicPlayer = this, asyncEvaluations = false, evaluatedMoves = moves.map(function (move) { var e = heuristicPlayer.moveEvaluation(move, game, player); if (e instanceof Future) { asyncEvaluations = asyncEvaluations || true; return e.then(function (e) { return [move, e]; }); } else { return [move, e]; } }); if (asyncEvaluations) { // Avoid using Future if possible. return Future.all(evaluatedMoves).then(this.bestMoves); } else { return this.bestMoves(evaluatedMoves); } }
function selectMoves(moves, game, player) { var heuristicPlayer = this, asyncEvaluations = false, evaluatedMoves = moves.map(function (move) { var e = heuristicPlayer.moveEvaluation(move, game, player); if (e instanceof Future) { asyncEvaluations = asyncEvaluations || true; return e.then(function (e) { return [move, e]; }); } else { return [move, e]; } }); if (asyncEvaluations) { // Avoid using Future if possible. return Future.all(evaluatedMoves).then(this.bestMoves); } else { return this.bestMoves(evaluatedMoves); } }
JavaScript
function composite() { var components = Array.prototype.slice.call(arguments), weightSum = 0; raiseIf(components.length < 1, "HeuristicPlayer.composite() cannot take an odd number of arguments!"); for (var i = 0; i < components.length; i += 2) { raiseIf(typeof components[i] !== 'function', "HeuristicPlayer.composite() argument ", i, " (", components[i], ") is not a function!"); components[i+1] = +components[i+1]; raiseIf(isNaN(components[i+1]) || components[i+1] < 0 || components[i+1] > 1, "HeuristicPlayer.composite() argument ", i+1, " (", components[i+1], ") is not a valid weight!"); } return function compositeHeuristic(game, player) { var sum = 0; for (var i = 0; i+1 < components.length; i += 2) { sum += components[i](game, player) * components[i+1]; } return sum; }; }
function composite() { var components = Array.prototype.slice.call(arguments), weightSum = 0; raiseIf(components.length < 1, "HeuristicPlayer.composite() cannot take an odd number of arguments!"); for (var i = 0; i < components.length; i += 2) { raiseIf(typeof components[i] !== 'function', "HeuristicPlayer.composite() argument ", i, " (", components[i], ") is not a function!"); components[i+1] = +components[i+1]; raiseIf(isNaN(components[i+1]) || components[i+1] < 0 || components[i+1] > 1, "HeuristicPlayer.composite() argument ", i+1, " (", components[i+1], ") is not a valid weight!"); } return function compositeHeuristic(game, player) { var sum = 0; for (var i = 0; i+1 < components.length; i += 2) { sum += components[i](game, player) * components[i+1]; } return sum; }; }
JavaScript
function heuristic(game) { var result = {}, maxN = this; game.players.forEach(function (role) { result[role] = maxN.heuristic(game, role); }); return result; }
function heuristic(game) { var result = {}, maxN = this; game.players.forEach(function (role) { result[role] = maxN.heuristic(game, role); }); return result; }
JavaScript
function minimax(game, player, depth) { var value = this.quiescence(game, player, depth); if (isNaN(value)) { // game is not quiescent. var activePlayer = game.activePlayer(), moves = this.movesFor(game, activePlayer), comparison, next; if (moves.length < 1) { throw new Error('No moves for unfinished game '+ game +'.'); } if (activePlayer == player) { value = -Infinity; comparison = Math.max; } else { value = +Infinity; comparison = Math.min; } for (var i = 0; i < moves.length; ++i) { next = game.next(obj(activePlayer, moves[i])); value = comparison(value, this.minimax(next, player, depth + 1)); } } return value; }
function minimax(game, player, depth) { var value = this.quiescence(game, player, depth); if (isNaN(value)) { // game is not quiescent. var activePlayer = game.activePlayer(), moves = this.movesFor(game, activePlayer), comparison, next; if (moves.length < 1) { throw new Error('No moves for unfinished game '+ game +'.'); } if (activePlayer == player) { value = -Infinity; comparison = Math.max; } else { value = +Infinity; comparison = Math.min; } for (var i = 0; i < moves.length; ++i) { next = game.next(obj(activePlayer, moves[i])); value = comparison(value, this.minimax(next, player, depth + 1)); } } return value; }
JavaScript
function minimax(game, player, depth, alpha, beta) { var value = this.quiescence(game, player, depth); if (!isNaN(value)) { return value; } var activePlayer = game.activePlayer(), isActive = activePlayer == player, moves = this.movesFor(game, activePlayer), next; if (moves.length < 1) { throw new Error('No moves for unfinished game '+ game +'.'); } for (var i = 0; i < moves.length; i++) { next = game.next(obj(activePlayer, moves[i])); value = this.minimax(next, player, depth + 1, alpha, beta); if (isActive) { if (alpha < value) { // MAX alpha = value; } } else { if (beta > value) { // MIN beta = value; } } if (beta <= alpha) { break; } } return isActive ? alpha : beta; }
function minimax(game, player, depth, alpha, beta) { var value = this.quiescence(game, player, depth); if (!isNaN(value)) { return value; } var activePlayer = game.activePlayer(), isActive = activePlayer == player, moves = this.movesFor(game, activePlayer), next; if (moves.length < 1) { throw new Error('No moves for unfinished game '+ game +'.'); } for (var i = 0; i < moves.length; i++) { next = game.next(obj(activePlayer, moves[i])); value = this.minimax(next, player, depth + 1, alpha, beta); if (isActive) { if (alpha < value) { // MAX alpha = value; } } else { if (beta > value) { // MIN beta = value; } } if (beta <= alpha) { break; } } return isActive ? alpha : beta; }
JavaScript
function MonteCarloPlayer(params) { HeuristicPlayer.call(this, params); initialize(this, params) .number('simulationCount', { defaultValue: 30, coerce: true }) .number('timeCap', { defaultValue: 1000, coerce: true }) .number('horizon', { defaultValue: 500, coerce: true }); if (params) switch (typeof params.agent) { case 'function': this.agent = new HeuristicPlayer({ heuristic: params.agent }); break; case 'object': this.agent = params.agent; break; default: this.agent = null; } }
function MonteCarloPlayer(params) { HeuristicPlayer.call(this, params); initialize(this, params) .number('simulationCount', { defaultValue: 30, coerce: true }) .number('timeCap', { defaultValue: 1000, coerce: true }) .number('horizon', { defaultValue: 500, coerce: true }); if (params) switch (typeof params.agent) { case 'function': this.agent = new HeuristicPlayer({ heuristic: params.agent }); break; case 'object': this.agent = params.agent; break; default: this.agent = null; } }
JavaScript
function stateEvaluation(game, player) { var resultSum = 0, simulationCount = this.simulationCount, sim; for (var i = 0; i < simulationCount; ++i) { sim = this.simulation(game, player); resultSum += sim.result[player]; if (sim.plies < 1) { // game is final. break; } } return simulationCount > 0 ? resultSum / simulationCount : 0; }
function stateEvaluation(game, player) { var resultSum = 0, simulationCount = this.simulationCount, sim; for (var i = 0; i < simulationCount; ++i) { sim = this.simulation(game, player); resultSum += sim.result[player]; if (sim.plies < 1) { // game is final. break; } } return simulationCount > 0 ? resultSum / simulationCount : 0; }
JavaScript
function UCBPlayer(params) { MonteCarloPlayer.call(this, params); initialize(this, params) /** + `explorationConstant=sqrt(2)`: The exploration factor used in the UCT selection. */ .number('explorationConstant', { defaultValue: Math.sqrt(2), coerce: true }) ; }
function UCBPlayer(params) { MonteCarloPlayer.call(this, params); initialize(this, params) /** + `explorationConstant=sqrt(2)`: The exploration factor used in the UCT selection. */ .number('explorationConstant', { defaultValue: Math.sqrt(2), coerce: true }) ; }
JavaScript
function selectMoves(moves, game, player) { var root = new GameTree(null, game), endTime = Date.now() + this.timeCap, node, simulationResult; root.uct = { pending: this.random.shuffle(root.possibleTransitions()), visits: 0, rewards: 0 }; for (var i = 0; i < this.simulationCount && Date.now() < endTime; ++i) { node = root; while (node.uct.pending.length < 1 && node.childrenCount() > 0) { // Selection node = this.selectNode(node, i+1, this.explorationConstant); } if (node.uct.pending.length > 0) { // Expansion node = node.expand(node.uct.pending.pop()); node.uct = { pending: this.random.shuffle(node.possibleTransitions()), visits: 0, rewards: 0 }; } simulationResult = this.simulation(node.state, player); // Simulation for (; node; node = node.parent) { // Backpropagation ++node.uct.visits; node.uct.rewards += (game.normalizedResult(simulationResult.result)[player] + 1) / 2; } } moves = iterable(root.children).select(1).greater(function (n) { return n.uct.visits; }).map(function (n) { return n.transition; }); return moves; }
function selectMoves(moves, game, player) { var root = new GameTree(null, game), endTime = Date.now() + this.timeCap, node, simulationResult; root.uct = { pending: this.random.shuffle(root.possibleTransitions()), visits: 0, rewards: 0 }; for (var i = 0; i < this.simulationCount && Date.now() < endTime; ++i) { node = root; while (node.uct.pending.length < 1 && node.childrenCount() > 0) { // Selection node = this.selectNode(node, i+1, this.explorationConstant); } if (node.uct.pending.length > 0) { // Expansion node = node.expand(node.uct.pending.pop()); node.uct = { pending: this.random.shuffle(node.possibleTransitions()), visits: 0, rewards: 0 }; } simulationResult = this.simulation(node.state, player); // Simulation for (; node; node = node.parent) { // Backpropagation ++node.uct.visits; node.uct.rewards += (game.normalizedResult(simulationResult.result)[player] + 1) / 2; } } moves = iterable(root.children).select(1).greater(function (n) { return n.uct.visits; }).map(function (n) { return n.transition; }); return moves; }
JavaScript
function createWorker(playerBuilder, workerSetup) { raiseIf('string function'.indexOf(typeof playerBuilder) < 0, "Invalid player builder: "+ playerBuilder +"!"); var parallel = new base.Parallel(); return parallel.run('self.ludorum = ('+ exports.__init__ +')(self.base), "OK"').then(function () { if (typeof workerSetup === 'function') { return parallel.run('('+ workerSetup +')(), "OK"'); } }).then(function () { return parallel.run('self.PLAYER = ('+ playerBuilder +').call(self), "OK"'); }).then(function () { return parallel.worker; }); }
function createWorker(playerBuilder, workerSetup) { raiseIf('string function'.indexOf(typeof playerBuilder) < 0, "Invalid player builder: "+ playerBuilder +"!"); var parallel = new base.Parallel(); return parallel.run('self.ludorum = ('+ exports.__init__ +')(self.base), "OK"').then(function () { if (typeof workerSetup === 'function') { return parallel.run('('+ workerSetup +')(), "OK"'); } }).then(function () { return parallel.run('self.PLAYER = ('+ playerBuilder +').call(self), "OK"'); }).then(function () { return parallel.worker; }); }
JavaScript
function create(params) { var WebWorkerPlayer = this; return WebWorkerPlayer.createWorker(params.playerBuilder, params.workerSetup).then(function (worker) { return new WebWorkerPlayer({name: name, worker: worker}); }); }
function create(params) { var WebWorkerPlayer = this; return WebWorkerPlayer.createWorker(params.playerBuilder, params.workerSetup).then(function (worker) { return new WebWorkerPlayer({name: name, worker: worker}); }); }
JavaScript
function decision(game, player) { if (this.__future__ && this.__future__.isPending()) { this.__future__.resolve(Match.commandQuit); } this.__future__ = new Future(); this.worker.postMessage('PLAYER.decision(ludorum.Game.fromJSON('+ game.toJSON() +'), '+ JSON.stringify(player) +')'); return this.__future__; }
function decision(game, player) { if (this.__future__ && this.__future__.isPending()) { this.__future__.resolve(Match.commandQuit); } this.__future__ = new Future(); this.worker.postMessage('PLAYER.decision(ludorum.Game.fromJSON('+ game.toJSON() +'), '+ JSON.stringify(player) +')'); return this.__future__; }
JavaScript
function Predefined(activePlayer, results, height, width) { if (results) { this.__results__ = results; this.players = Object.keys(results); } Game.call(this, activePlayer); this.height = isNaN(height) ? 5 : +height; this.width = isNaN(width) ? 5 : +width; }
function Predefined(activePlayer, results, height, width) { if (results) { this.__results__ = results; this.players = Object.keys(results); } Game.call(this, activePlayer); this.height = isNaN(height) ? 5 : +height; this.width = isNaN(width) ? 5 : +width; }
JavaScript
function next(moves) { var activePlayer = this.activePlayer(), opponent = this.opponent(activePlayer); raiseIf(!moves.hasOwnProperty(activePlayer), 'No move for active player ', activePlayer, ' at ', this, '!'); switch (moves[activePlayer]) { case 'win': return new this.constructor(this.__turns__ - 1, opponent, activePlayer); case 'lose': return new this.constructor(this.__turns__ - 1, opponent, opponent); case 'pass': return new this.constructor(this.__turns__ - 1, opponent); default: raise('Invalid move ', moves[activePlayer], ' for player ', activePlayer, ' at ', this, '!'); } }
function next(moves) { var activePlayer = this.activePlayer(), opponent = this.opponent(activePlayer); raiseIf(!moves.hasOwnProperty(activePlayer), 'No move for active player ', activePlayer, ' at ', this, '!'); switch (moves[activePlayer]) { case 'win': return new this.constructor(this.__turns__ - 1, opponent, activePlayer); case 'lose': return new this.constructor(this.__turns__ - 1, opponent, opponent); case 'pass': return new this.constructor(this.__turns__ - 1, opponent); default: raise('Invalid move ', moves[activePlayer], ' for player ', activePlayer, ' at ', this, '!'); } }
JavaScript
function result() { if (this.hasOwnProperty('__result__')) { return this.__result__; } var lineLength = this.lineLength, lines = this.board.asStrings(this.__lines__(this.height, this.width, lineLength)).join(' '); for (var i = 0; i < this.players.length; ++i) { if (lines.indexOf(i.toString(36).repeat(lineLength)) >= 0) { return this.__result__ = this.victory([this.players[i]]); } } if (lines.indexOf('.') < 0) { // No empty squares means a tie. return this.__result__ = this.draw(); } return this.__result__ = null; // The game continues. }
function result() { if (this.hasOwnProperty('__result__')) { return this.__result__; } var lineLength = this.lineLength, lines = this.board.asStrings(this.__lines__(this.height, this.width, lineLength)).join(' '); for (var i = 0; i < this.players.length; ++i) { if (lines.indexOf(i.toString(36).repeat(lineLength)) >= 0) { return this.__result__ = this.victory([this.players[i]]); } } if (lines.indexOf('.') < 0) { // No empty squares means a tie. return this.__result__ = this.draw(); } return this.__result__ = null; // The game continues. }
JavaScript
function moves() { if (this.hasOwnProperty('__moves__')) { return this.__moves__; } else if (this.result()) { return this.__moves__ = null; } else { return this.__moves__ = obj(this.activePlayer(), iterable(this.board.string).filter(function (c) { return c === '.'; }, function (c, i) { return i; }).toArray() ); } }
function moves() { if (this.hasOwnProperty('__moves__')) { return this.__moves__; } else if (this.result()) { return this.__moves__ = null; } else { return this.__moves__ = obj(this.activePlayer(), iterable(this.board.string).filter(function (c) { return c === '.'; }, function (c, i) { return i; }).toArray() ); } }
JavaScript
function next(moves) { var activePlayer = this.activePlayer(), playerIndex = this.players.indexOf(activePlayer), squareIndex = +moves[activePlayer], row = (squareIndex / this.width) >> 0, column = squareIndex % this.width; return new this.constructor((playerIndex + 1) % this.players.length, this.board.place([row, column], playerIndex.toString(36)) ); }
function next(moves) { var activePlayer = this.activePlayer(), playerIndex = this.players.indexOf(activePlayer), squareIndex = +moves[activePlayer], row = (squareIndex / this.width) >> 0, column = squareIndex % this.width; return new this.constructor((playerIndex + 1) % this.players.length, this.board.place([row, column], playerIndex.toString(36)) ); }
JavaScript
function display(ui) { raiseIf(!ui || !(ui instanceof UserInterface.BasicHTMLInterface), "Unsupported UI!"); var moves = this.moves(), activePlayer = this.activePlayer(), board = this.board; moves = moves && moves[activePlayer]; var table = this.board.renderAsHTMLTable(ui.document, ui.container, function (data) { data.className = data.square === '.' ? 'ludorum-empty' : 'ludorum-player'+ data.square; data.innerHTML = data.square === '.' ? "&nbsp;" : "&#x25CF;"; var i = data.coord[0] * board.height + data.coord[1]; if (moves && moves.indexOf(i) >= 0) { data.move = i; data.activePlayer = activePlayer; data.onclick = ui.perform.bind(ui, data.move, activePlayer); } }); return ui; }
function display(ui) { raiseIf(!ui || !(ui instanceof UserInterface.BasicHTMLInterface), "Unsupported UI!"); var moves = this.moves(), activePlayer = this.activePlayer(), board = this.board; moves = moves && moves[activePlayer]; var table = this.board.renderAsHTMLTable(ui.document, ui.container, function (data) { data.className = data.square === '.' ? 'ludorum-empty' : 'ludorum-player'+ data.square; data.innerHTML = data.square === '.' ? "&nbsp;" : "&#x25CF;"; var i = data.coord[0] * board.height + data.coord[1]; if (moves && moves.indexOf(i) >= 0) { data.move = i; data.activePlayer = activePlayer; data.onclick = ui.perform.bind(ui, data.move, activePlayer); } }); return ui; }
JavaScript
function next(moves) { raiseIf(typeof moves.Evens !== 'number' || typeof moves.Odds !== 'number', 'Invalid moves '+ (JSON.stringify(moves) || moves) +'!'); var parity = (moves.Evens + moves.Odds) % 2 === 0; return new this.constructor(this.turns - 1, { Evens: this.points.Evens + (parity ? 1 : 0), Odds: this.points.Odds + (parity ? 0 : 1) }); }
function next(moves) { raiseIf(typeof moves.Evens !== 'number' || typeof moves.Odds !== 'number', 'Invalid moves '+ (JSON.stringify(moves) || moves) +'!'); var parity = (moves.Evens + moves.Odds) % 2 === 0; return new this.constructor(this.turns - 1, { Evens: this.points.Evens + (parity ? 1 : 0), Odds: this.points.Odds + (parity ? 0 : 1) }); }
JavaScript
function next(moves) { var activePlayer = this.activePlayer(), move = +moves[activePlayer]; if (isNaN(move) || this.board.charAt(move) !== '_') { throw new Error('Invalid move '+ JSON.stringify(moves) +' for board '+ this.board + ' (moves= '+ JSON.stringify(moves) +').'); } var newBoard = this.board.substring(0, move) + activePlayer.charAt(0) + this.board.substring(move + 1); return new this.constructor(this.opponent(activePlayer), newBoard); }
function next(moves) { var activePlayer = this.activePlayer(), move = +moves[activePlayer]; if (isNaN(move) || this.board.charAt(move) !== '_') { throw new Error('Invalid move '+ JSON.stringify(moves) +' for board '+ this.board + ' (moves= '+ JSON.stringify(moves) +').'); } var newBoard = this.board.substring(0, move) + activePlayer.charAt(0) + this.board.substring(move + 1); return new this.constructor(this.opponent(activePlayer), newBoard); }
JavaScript
function display(ui) { raiseIf(!ui || !(ui instanceof UserInterface.BasicHTMLInterface), "Unsupported UI!"); var activePlayer = this.activePlayer(), moves = this.moves(), board = this.board, classNames = { 'X': "ludorum-square-Xs", 'O': "ludorum-square-Os", '_': "ludorum-square-empty" }, squareHTML = { 'X': "X", 'O': "O", '_': "&nbsp;" }; moves = moves && moves[activePlayer] && moves[activePlayer].length > 0; (new CheckerboardFromString(3, 3, this.board, '_')) .renderAsHTMLTable(ui.document, ui.container, function (data) { data.className = classNames[data.square]; data.innerHTML = squareHTML[data.square]; if (moves && data.square === '_') { data.move = data.coord[0] * 3 + data.coord[1]; data.activePlayer = activePlayer; data.onclick = ui.perform.bind(ui, data.move, activePlayer); } }); return ui; }
function display(ui) { raiseIf(!ui || !(ui instanceof UserInterface.BasicHTMLInterface), "Unsupported UI!"); var activePlayer = this.activePlayer(), moves = this.moves(), board = this.board, classNames = { 'X': "ludorum-square-Xs", 'O': "ludorum-square-Os", '_': "ludorum-square-empty" }, squareHTML = { 'X': "X", 'O': "O", '_': "&nbsp;" }; moves = moves && moves[activePlayer] && moves[activePlayer].length > 0; (new CheckerboardFromString(3, 3, this.board, '_')) .renderAsHTMLTable(ui.document, ui.container, function (data) { data.className = classNames[data.square]; data.innerHTML = squareHTML[data.square]; if (moves && data.square === '_') { data.move = data.coord[0] * 3 + data.coord[1]; data.activePlayer = activePlayer; data.onclick = ui.perform.bind(ui, data.move, activePlayer); } }); return ui; }
JavaScript
function moves() { if (!this.result()) { var activePlayer = this.activePlayer(), currentScore = this.__scores__[activePlayer] + iterable(this.__rolls__).sum(); return obj(activePlayer, this.__rolls__.length < 1 ? ['roll'] : currentScore >= this.goal ? ['hold'] : ['roll', 'hold']); } }
function moves() { if (!this.result()) { var activePlayer = this.activePlayer(), currentScore = this.__scores__[activePlayer] + iterable(this.__rolls__).sum(); return obj(activePlayer, this.__rolls__.length < 1 ? ['roll'] : currentScore >= this.goal ? ['hold'] : ['roll', 'hold']); } }
JavaScript
function result() { var score0 = this.__scores__[this.players[0]], score1 = this.__scores__[this.players[1]]; if (score0 >= this.goal || score1 >= this.goal) { var r = {}; r[this.players[0]] = Math.min(this.goal, score0) - Math.min(this.goal, score1); r[this.players[1]] = -r[this.players[0]]; return r; } }
function result() { var score0 = this.__scores__[this.players[0]], score1 = this.__scores__[this.players[1]]; if (score0 >= this.goal || score1 >= this.goal) { var r = {}; r[this.players[0]] = Math.min(this.goal, score0) - Math.min(this.goal, score1); r[this.players[1]] = -r[this.players[0]]; return r; } }
JavaScript
function next(moves) { var activePlayer = this.activePlayer(), move = moves[activePlayer]; raiseIf(typeof move === 'undefined', 'No move for active player ', activePlayer, ' at ', this, '!'); if (move === 'hold') { var scores = copy(this.__scores__); scores[activePlayer] += iterable(this.__rolls__).sum(); return new this.constructor(this.opponent(), this.goal, scores, []); } else if (move === 'roll') { var game = this; return new aleatories.dice.D6(function (value) { value = isNaN(value) ? this.value() : +value; return (value > 1) ? new game.constructor(activePlayer, game.goal, game.__scores__, game.__rolls__.concat(value)) : new game.constructor(game.opponent(), game.goal, game.__scores__, []); }); } else { raise("Invalid moves ", JSON.stringify(moves), " at ", this, "!"); } }
function next(moves) { var activePlayer = this.activePlayer(), move = moves[activePlayer]; raiseIf(typeof move === 'undefined', 'No move for active player ', activePlayer, ' at ', this, '!'); if (move === 'hold') { var scores = copy(this.__scores__); scores[activePlayer] += iterable(this.__rolls__).sum(); return new this.constructor(this.opponent(), this.goal, scores, []); } else if (move === 'roll') { var game = this; return new aleatories.dice.D6(function (value) { value = isNaN(value) ? this.value() : +value; return (value > 1) ? new game.constructor(activePlayer, game.goal, game.__scores__, game.__rolls__.concat(value)) : new game.constructor(game.opponent(), game.goal, game.__scores__, []); }); } else { raise("Invalid moves ", JSON.stringify(moves), " at ", this, "!"); } }
JavaScript
function dealPieces(random) { random = random || this.random; var piecesPerPlayer = (this.allPieces.length / 2)|0, split1 = random.split(piecesPerPlayer, this.allPieces), split2 = random.split(piecesPerPlayer, split1[1]); return obj(this.players[0], split1[0], this.players[1], split2[0]); }
function dealPieces(random) { random = random || this.random; var piecesPerPlayer = (this.allPieces.length / 2)|0, split1 = random.split(piecesPerPlayer, this.allPieces), split2 = random.split(piecesPerPlayer, split1[1]); return obj(this.players[0], split1[0], this.players[1], split2[0]); }
JavaScript
function moveResult(piece1, piece2) { var upperBound = iterable(this.allPieces).max(0) + 1; if (piece1 < piece2) { return piece2 - piece1 <= (upperBound / 2) ? 1 : -1; } else if (piece1 > piece2) { return piece1 - piece2 >= (upperBound / 2) + 1 ? 1 : -1; } else { return 0; } }
function moveResult(piece1, piece2) { var upperBound = iterable(this.allPieces).max(0) + 1; if (piece1 < piece2) { return piece2 - piece1 <= (upperBound / 2) ? 1 : -1; } else if (piece1 > piece2) { return piece1 - piece2 >= (upperBound / 2) + 1 ? 1 : -1; } else { return 0; } }
JavaScript
function next(moves) { var player0 = this.players[0], player1 = this.players[1], move0 = moves[player0], move1 = moves[player1], pieces = this.pieces; raiseIf(pieces[player0].indexOf(move0) < 0, "Invalid move ", JSON.stringify(move0), " for player ", player0, "! (moves= ", JSON.stringify(moves), ")"); raiseIf(pieces[player1].indexOf(move1) < 0, "Invalid move ", JSON.stringify(move1), " for player ", player1, "! (moves= ", JSON.stringify(moves), ")"); var moveResult = this.moveResult(move0, move1); return new this.constructor({ random: this.random, playedPieces: this.playedPieces.concat([move0, move1]), pieces: obj( player0, pieces[player0].filter(function (p) { return p !== move0; }), player1, pieces[player1].filter(function (p) { return p !== move1; }) ), scores: obj( player0, this.__scores__[player0] + moveResult, player1, this.__scores__[player1] - moveResult ) }); }
function next(moves) { var player0 = this.players[0], player1 = this.players[1], move0 = moves[player0], move1 = moves[player1], pieces = this.pieces; raiseIf(pieces[player0].indexOf(move0) < 0, "Invalid move ", JSON.stringify(move0), " for player ", player0, "! (moves= ", JSON.stringify(moves), ")"); raiseIf(pieces[player1].indexOf(move1) < 0, "Invalid move ", JSON.stringify(move1), " for player ", player1, "! (moves= ", JSON.stringify(moves), ")"); var moveResult = this.moveResult(move0, move1); return new this.constructor({ random: this.random, playedPieces: this.playedPieces.concat([move0, move1]), pieces: obj( player0, pieces[player0].filter(function (p) { return p !== move0; }), player1, pieces[player1].filter(function (p) { return p !== move1; }) ), scores: obj( player0, this.__scores__[player0] + moveResult, player1, this.__scores__[player1] - moveResult ) }); }
JavaScript
function result() { var players = this.players; if (this.playedPieces.length >= this.allPieces.length - 1) { var scores = this.scores(); return this.zerosumResult(scores[players[0]] - scores[players[1]], players[0]); } else { return null; } }
function result() { var players = this.players; if (this.playedPieces.length >= this.allPieces.length - 1) { var scores = this.scores(); return this.zerosumResult(scores[players[0]] - scores[players[1]], players[0]); } else { return null; } }
JavaScript
function view(player) { var gameState = this, opponent = this.opponent(player), random = this.random; return Aleatory.withValues(this.__possiblePieces__(opponent), random, function (pieces) { pieces = pieces || this.value(); return new gameState.constructor({ random: random, playedPieces: gameState.playedPieces, scores: gameState.scores(), pieces: obj(player, gameState.pieces[player], opponent, pieces) }); } ); }
function view(player) { var gameState = this, opponent = this.opponent(player), random = this.random; return Aleatory.withValues(this.__possiblePieces__(opponent), random, function (pieces) { pieces = pieces || this.value(); return new gameState.constructor({ random: random, playedPieces: gameState.playedPieces, scores: gameState.scores(), pieces: obj(player, gameState.pieces[player], opponent, pieces) }); } ); }
JavaScript
function next(moves) { if (!moves) { throw new Error("Invalid moves "+ moves +"!"); } var activePlayer = this.activePlayer(), move = moves[activePlayer]; if (!Array.isArray(moves[activePlayer])) { throw new Error("Invalid moves "+ JSON.stringify(moves) +"!"); } return new this.constructor(this.opponent(), this.board.move(move[0], move[1])); }
function next(moves) { if (!moves) { throw new Error("Invalid moves "+ moves +"!"); } var activePlayer = this.activePlayer(), move = moves[activePlayer]; if (!Array.isArray(moves[activePlayer])) { throw new Error("Invalid moves "+ JSON.stringify(moves) +"!"); } return new this.constructor(this.opponent(), this.board.move(move[0], move[1])); }
JavaScript
function templateFn(data) { // Set up the defaults for the data _.defaults(data.options, defaults); // If we want to transform our variables, then transform them var transformFn = _.identity; var variableNameTransforms = data.options.variableNameTransforms; if (variableNameTransforms) { assert(Array.isArray(variableNameTransforms), '`options.variableNameTransforms` was expected to be an array but it was not'); transformFn = function (str) { var strObj = _s(str); variableNameTransforms.forEach(function runTransform (transformKey) { strObj = strObj[transformKey](); }); return strObj.value(); }; } // Generate strings for our variables templater.ensureHandlebarsVariables(data, transformFn); templater.ensureHandlebarsVariables(data.spritesheet, transformFn); templater.ensureHandlebarsVariables(data.spritesheet_info, transformFn); data.sprites.forEach(function addHandlebarsVariables (sprite) { templater.ensureHandlebarsVariables(sprite, transformFn); }); // If we have retina data, generate strings for it as well if (data.retina_sprites) { data.retina_sprites.forEach(function addHandlebarsVariables (retinaSprite) { templater.ensureHandlebarsVariables(retinaSprite, transformFn); }); } if (data.retina_spritesheet_info) { templater.ensureHandlebarsVariables(data.retina_spritesheet_info, transformFn); } if (data.retina_groups) { data.retina_groups.forEach(function addHandlebarsVariables (retinaGroup) { templater.ensureHandlebarsVariables(retinaGroup, transformFn); }); } if (data.retina_groups_info) { templater.ensureHandlebarsVariables(data.retina_groups_info, transformFn); } // Render our template var retStr = handlebars.compile(tmpl)(data); return retStr; }
function templateFn(data) { // Set up the defaults for the data _.defaults(data.options, defaults); // If we want to transform our variables, then transform them var transformFn = _.identity; var variableNameTransforms = data.options.variableNameTransforms; if (variableNameTransforms) { assert(Array.isArray(variableNameTransforms), '`options.variableNameTransforms` was expected to be an array but it was not'); transformFn = function (str) { var strObj = _s(str); variableNameTransforms.forEach(function runTransform (transformKey) { strObj = strObj[transformKey](); }); return strObj.value(); }; } // Generate strings for our variables templater.ensureHandlebarsVariables(data, transformFn); templater.ensureHandlebarsVariables(data.spritesheet, transformFn); templater.ensureHandlebarsVariables(data.spritesheet_info, transformFn); data.sprites.forEach(function addHandlebarsVariables (sprite) { templater.ensureHandlebarsVariables(sprite, transformFn); }); // If we have retina data, generate strings for it as well if (data.retina_sprites) { data.retina_sprites.forEach(function addHandlebarsVariables (retinaSprite) { templater.ensureHandlebarsVariables(retinaSprite, transformFn); }); } if (data.retina_spritesheet_info) { templater.ensureHandlebarsVariables(data.retina_spritesheet_info, transformFn); } if (data.retina_groups) { data.retina_groups.forEach(function addHandlebarsVariables (retinaGroup) { templater.ensureHandlebarsVariables(retinaGroup, transformFn); }); } if (data.retina_groups_info) { templater.ensureHandlebarsVariables(data.retina_groups_info, transformFn); } // Render our template var retStr = handlebars.compile(tmpl)(data); return retStr; }
JavaScript
function UNIXconverter(timeStamp) { dateConvert = new Date(timeStamp * 1000); dateString = dateConvert.toLocaleDateString(); dateDay = dateConvert.getUTCDay(); weekArray = ["Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"]; weekDayAndDateConverted = weekArray[dateDay] + " " + dateString; return weekDayAndDateConverted; }
function UNIXconverter(timeStamp) { dateConvert = new Date(timeStamp * 1000); dateString = dateConvert.toLocaleDateString(); dateDay = dateConvert.getUTCDay(); weekArray = ["Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"]; weekDayAndDateConverted = weekArray[dateDay] + " " + dateString; return weekDayAndDateConverted; }
JavaScript
function renderSearchHistory() { SEARCH_HISTORY_DIV.empty() for (let i = 0; i < searchHistory.length; i++) { const searchHistoryItem = $('<p>').addClass("searchHistoryItem p-3 mb-2 bg-light text-dark border border-primary"); searchHistoryItem.text(searchHistory[i]); SEARCH_HISTORY_DIV.prepend(searchHistoryItem); } }
function renderSearchHistory() { SEARCH_HISTORY_DIV.empty() for (let i = 0; i < searchHistory.length; i++) { const searchHistoryItem = $('<p>').addClass("searchHistoryItem p-3 mb-2 bg-light text-dark border border-primary"); searchHistoryItem.text(searchHistory[i]); SEARCH_HISTORY_DIV.prepend(searchHistoryItem); } }
JavaScript
function currentDate() { let today = new Date(); let dd = String(today.getDate()).padStart(2, '0'); let mm = String(today.getMonth() + 1).padStart(2, '0'); let yyyy = today.getFullYear(); let NOW = dd + '/' + mm + '/' + yyyy; return NOW; }
function currentDate() { let today = new Date(); let dd = String(today.getDate()).padStart(2, '0'); let mm = String(today.getMonth() + 1).padStart(2, '0'); let yyyy = today.getFullYear(); let NOW = dd + '/' + mm + '/' + yyyy; return NOW; }
JavaScript
function badgeComponent(cityUVIndex) { $("#uvBadge").text("UV index: " + cityUVIndex); if (cityUVIndex < 3) { $("#uvBadge").addClass("badge bg-success"); } else if (cityUVIndex > 3 && cityUVIndex < 7) { $("#uvBadge").addClass("badge bg-warning text-dark"); } else { $("#uvBadge").addClass("badge bg-danger"); } }
function badgeComponent(cityUVIndex) { $("#uvBadge").text("UV index: " + cityUVIndex); if (cityUVIndex < 3) { $("#uvBadge").addClass("badge bg-success"); } else if (cityUVIndex > 3 && cityUVIndex < 7) { $("#uvBadge").addClass("badge bg-warning text-dark"); } else { $("#uvBadge").addClass("badge bg-danger"); } }
JavaScript
function checkFramebufferFeedback(gl, getWebGLObjectString) { const framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); if (!framebuffer) { // drawing to canvas return []; } // get framebuffer texture attachments const maxColorAttachments = getMaxColorAttachments(gl); const textureAttachments = new Map(); for (let i = 0; i < maxColorAttachments; ++i) { addTextureAttachment(gl, gl.COLOR_ATTACHMENT0 + i, textureAttachments); } addTextureAttachment(gl, gl.DEPTH_ATTACHMENT, textureAttachments); addTextureAttachment(gl, gl.STENCIL_ATTACHMENT, textureAttachments); if (!isWebGL2(gl)) { addTextureAttachment(gl, gl.DEPTH_STENCIL_ATTACHMENT, textureAttachments); } const oldActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE); const program = gl.getParameter(gl.CURRENT_PROGRAM); // get the texture units used by the current program const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); const errors = []; for (let ii = 0; ii < numUniforms; ++ii) { const {name, type, size} = gl.getActiveUniform(program, ii); if (isBuiltIn(name) || !uniformTypeIsSampler(type)) { continue; } if (size > 1) { const baseName = (name.substr(-3) === '[0]') ? name.substr(0, name.length - 3) : name; for (let t = 0; t < size; ++t) { errors.push(...checkTextureUsage(gl, framebuffer, textureAttachments, program, `${baseName}[${t}]`, type, getWebGLObjectString)); } } else { errors.push(...checkTextureUsage(gl, framebuffer, textureAttachments, program, name, type, getWebGLObjectString)); } } gl.activeTexture(oldActiveTexture); return errors; }
function checkFramebufferFeedback(gl, getWebGLObjectString) { const framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); if (!framebuffer) { // drawing to canvas return []; } // get framebuffer texture attachments const maxColorAttachments = getMaxColorAttachments(gl); const textureAttachments = new Map(); for (let i = 0; i < maxColorAttachments; ++i) { addTextureAttachment(gl, gl.COLOR_ATTACHMENT0 + i, textureAttachments); } addTextureAttachment(gl, gl.DEPTH_ATTACHMENT, textureAttachments); addTextureAttachment(gl, gl.STENCIL_ATTACHMENT, textureAttachments); if (!isWebGL2(gl)) { addTextureAttachment(gl, gl.DEPTH_STENCIL_ATTACHMENT, textureAttachments); } const oldActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE); const program = gl.getParameter(gl.CURRENT_PROGRAM); // get the texture units used by the current program const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); const errors = []; for (let ii = 0; ii < numUniforms; ++ii) { const {name, type, size} = gl.getActiveUniform(program, ii); if (isBuiltIn(name) || !uniformTypeIsSampler(type)) { continue; } if (size > 1) { const baseName = (name.substr(-3) === '[0]') ? name.substr(0, name.length - 3) : name; for (let t = 0; t < size; ++t) { errors.push(...checkTextureUsage(gl, framebuffer, textureAttachments, program, `${baseName}[${t}]`, type, getWebGLObjectString)); } } else { errors.push(...checkTextureUsage(gl, framebuffer, textureAttachments, program, name, type, getWebGLObjectString)); } } gl.activeTexture(oldActiveTexture); return errors; }
JavaScript
function glEnumToString(value) { const matches = enumToStringsMap.get(value); return matches ? [...matches.keys()].map(v => `${v}`).join(' | ') : `/*UNKNOWN WebGL ENUM*/ ${typeof value === 'number' ? `0x${value.toString(16)}` : value}`; }
function glEnumToString(value) { const matches = enumToStringsMap.get(value); return matches ? [...matches.keys()].map(v => `${v}`).join(' | ') : `/*UNKNOWN WebGL ENUM*/ ${typeof value === 'number' ? `0x${value.toString(16)}` : value}`; }
JavaScript
function checkFramebufferFeedback(gl, getWebGLObjectString) { const framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); if (!framebuffer) { // drawing to canvas return []; } // get framebuffer texture attachments const maxColorAttachments = getMaxColorAttachments(gl); const textureAttachments = new Map(); for (let i = 0; i < maxColorAttachments; ++i) { addTextureAttachment(gl, gl.COLOR_ATTACHMENT0 + i, textureAttachments); } addTextureAttachment(gl, gl.DEPTH_ATTACHMENT, textureAttachments); addTextureAttachment(gl, gl.STENCIL_ATTACHMENT, textureAttachments); if (!isWebGL2(gl)) { addTextureAttachment(gl, gl.DEPTH_STENCIL_ATTACHMENT, textureAttachments); } const oldActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE); const program = gl.getParameter(gl.CURRENT_PROGRAM); // get the texture units used by the current program const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); const errors = []; for (let ii = 0; ii < numUniforms; ++ii) { const {name, type, size} = gl.getActiveUniform(program, ii); if (isBuiltIn(name) || !uniformTypeIsSampler(type)) { continue; } if (size > 1) { const baseName = (name.substr(-3) === '[0]') ? name.substr(0, name.length - 3) : name; for (let t = 0; t < size; ++t) { errors.push(...checkTextureUsage(gl, framebuffer, textureAttachments, program, `${baseName}[${t}]`, type, getWebGLObjectString)); } } else { errors.push(...checkTextureUsage(gl, framebuffer, textureAttachments, program, name, type, getWebGLObjectString)); } } gl.activeTexture(oldActiveTexture); return errors; }
function checkFramebufferFeedback(gl, getWebGLObjectString) { const framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); if (!framebuffer) { // drawing to canvas return []; } // get framebuffer texture attachments const maxColorAttachments = getMaxColorAttachments(gl); const textureAttachments = new Map(); for (let i = 0; i < maxColorAttachments; ++i) { addTextureAttachment(gl, gl.COLOR_ATTACHMENT0 + i, textureAttachments); } addTextureAttachment(gl, gl.DEPTH_ATTACHMENT, textureAttachments); addTextureAttachment(gl, gl.STENCIL_ATTACHMENT, textureAttachments); if (!isWebGL2(gl)) { addTextureAttachment(gl, gl.DEPTH_STENCIL_ATTACHMENT, textureAttachments); } const oldActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE); const program = gl.getParameter(gl.CURRENT_PROGRAM); // get the texture units used by the current program const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); const errors = []; for (let ii = 0; ii < numUniforms; ++ii) { const {name, type, size} = gl.getActiveUniform(program, ii); if (isBuiltIn(name) || !uniformTypeIsSampler(type)) { continue; } if (size > 1) { const baseName = (name.substr(-3) === '[0]') ? name.substr(0, name.length - 3) : name; for (let t = 0; t < size; ++t) { errors.push(...checkTextureUsage(gl, framebuffer, textureAttachments, program, `${baseName}[${t}]`, type, getWebGLObjectString)); } } else { errors.push(...checkTextureUsage(gl, framebuffer, textureAttachments, program, name, type, getWebGLObjectString)); } } gl.activeTexture(oldActiveTexture); return errors; }
JavaScript
function glFunctionArgToString(gl, funcName, numArgs, argumentIndex, value) { // there's apparently no easy to find out if something is a WebGLObject // as `WebGLObject` has been hidden. We could check all the types but lets // just check if the user mapped something const name = webglObjectToNamesMap.get(value); if (name) { return `${value.constructor.name}("${name}")`; } if (value instanceof WebGLUniformLocation) { const name = locationsToNamesMap.get(value); return `WebGLUniformLocation("${name}")`; } const funcInfos = glFunctionInfos[funcName]; if (funcInfos !== undefined) { const funcInfo = funcInfos[numArgs]; if (funcInfo !== undefined) { const argTypes = funcInfo.enums; if (argTypes) { const argType = argTypes[argumentIndex]; if (argType !== undefined) { if (typeof argType === 'function') { return argType(gl, value); } else { // is it a bind point // // I'm not sure what cases there are. At first I thought I'd // translate every enum representing a bind point into its corresponding // WebGLObject but that fails for `bindXXX` and for `framebufferTexture2D`'s // 3rd argument. // // Maybe it only works if it's not `bindXXX` and if its the first argument? // // issues: // * bindBufferBase, bindBufferRange, indexed // // should we do something about these? // O vertexAttrib, enable, vertex arrays implicit, buffer is implicit // Example: could print // 'Error setting attrib 4 of WebGLVertexArrayObject("sphere") to WebGLBuffer("sphere positions") // O drawBuffers implicit // Example: 'Error trying to set drawBuffers on WebGLFrameBuffer('post-processing-fb) if (!funcName.startsWith('bind') && argumentIndex === 0) { const binding = getBindingQueryEnumForBindPoint(value); if (binding) { const webglObject = gl.getParameter(binding); if (webglObject) { return `${glEnumToString(value)}{${getWebGLObjectString(webglObject)}}`; } } } return glEnumToString(value); } } } } } if (value === null) { return 'null'; } else if (value === undefined) { return 'undefined'; } else if (Array.isArray(value) || isTypedArray(value)) { if (value.length <= 32) { return `[${Array.from(value.slice(0, 32)).join(', ')}]`; } else { return `${value.constructor.name}(${value.length !== undefined ? value.length : value.byteLength})`; } } else { return value.toString(); } }
function glFunctionArgToString(gl, funcName, numArgs, argumentIndex, value) { // there's apparently no easy to find out if something is a WebGLObject // as `WebGLObject` has been hidden. We could check all the types but lets // just check if the user mapped something const name = webglObjectToNamesMap.get(value); if (name) { return `${value.constructor.name}("${name}")`; } if (value instanceof WebGLUniformLocation) { const name = locationsToNamesMap.get(value); return `WebGLUniformLocation("${name}")`; } const funcInfos = glFunctionInfos[funcName]; if (funcInfos !== undefined) { const funcInfo = funcInfos[numArgs]; if (funcInfo !== undefined) { const argTypes = funcInfo.enums; if (argTypes) { const argType = argTypes[argumentIndex]; if (argType !== undefined) { if (typeof argType === 'function') { return argType(gl, value); } else { // is it a bind point // // I'm not sure what cases there are. At first I thought I'd // translate every enum representing a bind point into its corresponding // WebGLObject but that fails for `bindXXX` and for `framebufferTexture2D`'s // 3rd argument. // // Maybe it only works if it's not `bindXXX` and if its the first argument? // // issues: // * bindBufferBase, bindBufferRange, indexed // // should we do something about these? // O vertexAttrib, enable, vertex arrays implicit, buffer is implicit // Example: could print // 'Error setting attrib 4 of WebGLVertexArrayObject("sphere") to WebGLBuffer("sphere positions") // O drawBuffers implicit // Example: 'Error trying to set drawBuffers on WebGLFrameBuffer('post-processing-fb) if (!funcName.startsWith('bind') && argumentIndex === 0) { const binding = getBindingQueryEnumForBindPoint(value); if (binding) { const webglObject = gl.getParameter(binding); if (webglObject) { return `${glEnumToString(value)}{${getWebGLObjectString(webglObject)}}`; } } } return glEnumToString(value); } } } } } if (value === null) { return 'null'; } else if (value === undefined) { return 'undefined'; } else if (Array.isArray(value) || isTypedArray(value)) { if (value.length <= 32) { return `[${Array.from(value.slice(0, 32)).join(', ')}]`; } else { return `${value.constructor.name}(${value.length !== undefined ? value.length : value.byteLength})`; } } else { return value.toString(); } }
JavaScript
function glFunctionArgsToString(ctx, funcName, args) { const numArgs = args.length; const stringifiedArgs = args.map(function(arg, ndx) { let str = glFunctionArgToString(ctx, funcName, numArgs, ndx, arg); // shorten because of long arrays if (str.length > 200) { str = str.substring(0, 200) + '...'; } return str; }); return stringifiedArgs.join(', '); }
function glFunctionArgsToString(ctx, funcName, args) { const numArgs = args.length; const stringifiedArgs = args.map(function(arg, ndx) { let str = glFunctionArgToString(ctx, funcName, numArgs, ndx, arg); // shorten because of long arrays if (str.length > 200) { str = str.substring(0, 200) + '...'; } return str; }); return stringifiedArgs.join(', '); }
JavaScript
function makeErrorWrapper(ctx, funcName) { const origFn = ctx[funcName]; const preCheck = preChecks[funcName] || noop; const postCheck = postChecks[funcName] || noop; ctx[funcName] = function(...args) { preCheck(ctx, funcName, args); checkArgs(ctx, funcName, args); if (sharedState.currentProgram && isDrawFunction(funcName)) { const msgs = checkAttributesForBufferOverflow(baseContext, funcName, args, getWebGLObjectString, getIndicesForBuffer); if (msgs.length) { reportFunctionError(ctx, funcName, args, msgs.join('\n')); } } const result = origFn.call(ctx, ...args); const gl = baseContext; const err = origGLErrorFn.call(gl); if (err !== 0) { glErrorShadow[err] = true; const msgs = [glEnumToString(err)]; if (isDrawFunction(funcName)) { if (sharedState.currentProgram) { msgs.push(...checkFramebufferFeedback(gl, getWebGLObjectString)); } } reportFunctionError(ctx, funcName, args, msgs.join('\n')); } else { postCheck(ctx, funcName, args, result); } return result; }; const extraWrapperFn = extraWrappers[funcName]; if (extraWrapperFn) { extraWrapperFn(ctx, funcName, origGLErrorFn); } }
function makeErrorWrapper(ctx, funcName) { const origFn = ctx[funcName]; const preCheck = preChecks[funcName] || noop; const postCheck = postChecks[funcName] || noop; ctx[funcName] = function(...args) { preCheck(ctx, funcName, args); checkArgs(ctx, funcName, args); if (sharedState.currentProgram && isDrawFunction(funcName)) { const msgs = checkAttributesForBufferOverflow(baseContext, funcName, args, getWebGLObjectString, getIndicesForBuffer); if (msgs.length) { reportFunctionError(ctx, funcName, args, msgs.join('\n')); } } const result = origFn.call(ctx, ...args); const gl = baseContext; const err = origGLErrorFn.call(gl); if (err !== 0) { glErrorShadow[err] = true; const msgs = [glEnumToString(err)]; if (isDrawFunction(funcName)) { if (sharedState.currentProgram) { msgs.push(...checkFramebufferFeedback(gl, getWebGLObjectString)); } } reportFunctionError(ctx, funcName, args, msgs.join('\n')); } else { postCheck(ctx, funcName, args, result); } return result; }; const extraWrapperFn = extraWrappers[funcName]; if (extraWrapperFn) { extraWrapperFn(ctx, funcName, origGLErrorFn); } }
JavaScript
function glEnumToString(value) { const matches = enumToStringsMap.get(value); return matches ? [...matches.keys()].map(v => `${v}`).join(' | ') : `/*UNKNOWN WebGL ENUM*/ ${typeof value === 'number' ? `0x${value.toString(16)}` : value}`; }
function glEnumToString(value) { const matches = enumToStringsMap.get(value); return matches ? [...matches.keys()].map(v => `${v}`).join(' | ') : `/*UNKNOWN WebGL ENUM*/ ${typeof value === 'number' ? `0x${value.toString(16)}` : value}`; }
JavaScript
function glFunctionArgToString(gl, funcName, numArgs, argumentIndex, value) { // there's apparently no easy to find out if something is a WebGLObject // as `WebGLObject` has been hidden. We could check all the types but lets // just check if the user mapped something const name = webglObjectToNamesMap.get(value); if (name) { return `${value.constructor.name}("${name}")`; } if (value instanceof WebGLUniformLocation) { const name = locationsToNamesMap.get(value); return `WebGLUniformLocation("${name}")`; } const funcInfos = glFunctionInfos[funcName]; if (funcInfos !== undefined) { const funcInfo = funcInfos[numArgs]; if (funcInfo !== undefined) { const argTypes = funcInfo.enums; if (argTypes) { const argType = argTypes[argumentIndex]; if (argType !== undefined) { if (typeof argType === 'function') { return argType(gl, value); } else { // is it a bind point // // I'm not sure what cases there are. At first I thought I'd // translate every enum representing a bind point into its corresponding // WebGLObject but that fails for `bindXXX` and for `framebufferTexture2D`'s // 3rd argument. // // Maybe it only works if it's not `bindXXX` and if its the first argument? // // issues: // * bindBufferBase, bindBufferRange, indexed // // should we do something about these? // O vertexAttrib, enable, vertex arrays implicit, buffer is implicit // Example: could print // 'Error setting attrib 4 of WebGLVertexArrayObject("sphere") to WebGLBuffer("sphere positions") // O drawBuffers implicit // Example: 'Error trying to set drawBuffers on WebGLFrameBuffer('post-processing-fb) if (!funcName.startsWith('bind') && argumentIndex === 0) { const binding = getBindingQueryEnumForBindPoint(value); if (binding) { const webglObject = gl.getParameter(binding); if (webglObject) { return `${glEnumToString(value)}{${getWebGLObjectString(webglObject)}}`; } } } return glEnumToString(value); } } } } } if (value === null) { return 'null'; } else if (value === undefined) { return 'undefined'; } else if (Array.isArray(value) || isTypedArray(value)) { if (value.length <= 32) { return `[${Array.from(value.slice(0, 32)).join(', ')}]`; } else { return `${value.constructor.name}(${value.length !== undefined ? value.length : value.byteLength})`; } } else { return value.toString(); } }
function glFunctionArgToString(gl, funcName, numArgs, argumentIndex, value) { // there's apparently no easy to find out if something is a WebGLObject // as `WebGLObject` has been hidden. We could check all the types but lets // just check if the user mapped something const name = webglObjectToNamesMap.get(value); if (name) { return `${value.constructor.name}("${name}")`; } if (value instanceof WebGLUniformLocation) { const name = locationsToNamesMap.get(value); return `WebGLUniformLocation("${name}")`; } const funcInfos = glFunctionInfos[funcName]; if (funcInfos !== undefined) { const funcInfo = funcInfos[numArgs]; if (funcInfo !== undefined) { const argTypes = funcInfo.enums; if (argTypes) { const argType = argTypes[argumentIndex]; if (argType !== undefined) { if (typeof argType === 'function') { return argType(gl, value); } else { // is it a bind point // // I'm not sure what cases there are. At first I thought I'd // translate every enum representing a bind point into its corresponding // WebGLObject but that fails for `bindXXX` and for `framebufferTexture2D`'s // 3rd argument. // // Maybe it only works if it's not `bindXXX` and if its the first argument? // // issues: // * bindBufferBase, bindBufferRange, indexed // // should we do something about these? // O vertexAttrib, enable, vertex arrays implicit, buffer is implicit // Example: could print // 'Error setting attrib 4 of WebGLVertexArrayObject("sphere") to WebGLBuffer("sphere positions") // O drawBuffers implicit // Example: 'Error trying to set drawBuffers on WebGLFrameBuffer('post-processing-fb) if (!funcName.startsWith('bind') && argumentIndex === 0) { const binding = getBindingQueryEnumForBindPoint(value); if (binding) { const webglObject = gl.getParameter(binding); if (webglObject) { return `${glEnumToString(value)}{${getWebGLObjectString(webglObject)}}`; } } } return glEnumToString(value); } } } } } if (value === null) { return 'null'; } else if (value === undefined) { return 'undefined'; } else if (Array.isArray(value) || isTypedArray(value)) { if (value.length <= 32) { return `[${Array.from(value.slice(0, 32)).join(', ')}]`; } else { return `${value.constructor.name}(${value.length !== undefined ? value.length : value.byteLength})`; } } else { return value.toString(); } }
JavaScript
function glFunctionArgsToString(ctx, funcName, args) { const numArgs = args.length; const stringifiedArgs = args.map(function(arg, ndx) { let str = glFunctionArgToString(ctx, funcName, numArgs, ndx, arg); // shorten because of long arrays if (str.length > 200) { str = str.substring(0, 200) + '...'; } return str; }); return stringifiedArgs.join(', '); }
function glFunctionArgsToString(ctx, funcName, args) { const numArgs = args.length; const stringifiedArgs = args.map(function(arg, ndx) { let str = glFunctionArgToString(ctx, funcName, numArgs, ndx, arg); // shorten because of long arrays if (str.length > 200) { str = str.substring(0, 200) + '...'; } return str; }); return stringifiedArgs.join(', '); }
JavaScript
function makeErrorWrapper(ctx, funcName) { const origFn = ctx[funcName]; const preCheck = preChecks[funcName] || noop; const postCheck = postChecks[funcName] || noop; ctx[funcName] = function(...args) { preCheck(ctx, funcName, args); checkArgs(ctx, funcName, args); if (sharedState.currentProgram && isDrawFunction(funcName)) { const msgs = checkAttributesForBufferOverflow(baseContext, funcName, args, getWebGLObjectString, getIndicesForBuffer); if (msgs.length) { reportFunctionError(ctx, funcName, args, msgs.join('\n')); } } const result = origFn.call(ctx, ...args); const gl = baseContext; const err = origGLErrorFn.call(gl); if (err !== 0) { glErrorShadow[err] = true; const msgs = [glEnumToString(err)]; if (isDrawFunction(funcName)) { if (sharedState.currentProgram) { msgs.push(...checkFramebufferFeedback(gl, getWebGLObjectString)); } } reportFunctionError(ctx, funcName, args, msgs.join('\n')); } else { postCheck(ctx, funcName, args, result); } return result; }; const extraWrapperFn = extraWrappers[funcName]; if (extraWrapperFn) { extraWrapperFn(ctx, funcName, origGLErrorFn); } }
function makeErrorWrapper(ctx, funcName) { const origFn = ctx[funcName]; const preCheck = preChecks[funcName] || noop; const postCheck = postChecks[funcName] || noop; ctx[funcName] = function(...args) { preCheck(ctx, funcName, args); checkArgs(ctx, funcName, args); if (sharedState.currentProgram && isDrawFunction(funcName)) { const msgs = checkAttributesForBufferOverflow(baseContext, funcName, args, getWebGLObjectString, getIndicesForBuffer); if (msgs.length) { reportFunctionError(ctx, funcName, args, msgs.join('\n')); } } const result = origFn.call(ctx, ...args); const gl = baseContext; const err = origGLErrorFn.call(gl); if (err !== 0) { glErrorShadow[err] = true; const msgs = [glEnumToString(err)]; if (isDrawFunction(funcName)) { if (sharedState.currentProgram) { msgs.push(...checkFramebufferFeedback(gl, getWebGLObjectString)); } } reportFunctionError(ctx, funcName, args, msgs.join('\n')); } else { postCheck(ctx, funcName, args, result); } return result; }; const extraWrapperFn = extraWrappers[funcName]; if (extraWrapperFn) { extraWrapperFn(ctx, funcName, origGLErrorFn); } }
JavaScript
function callOnce( func, wrapup ) { var called = false; return function(err, ret) { if (!called) { called = true; if (wrapup) wrapup(); if (func) func(err, ret); } } }
function callOnce( func, wrapup ) { var called = false; return function(err, ret) { if (!called) { called = true; if (wrapup) wrapup(); if (func) func(err, ret); } } }
JavaScript
computeMatch() { if (!this.group) { this.match = this.getMatch(this.location.pathname); } }
computeMatch() { if (!this.group) { this.match = this.getMatch(this.location.pathname); } }
JavaScript
function shallowEqual(objA, objB) { if (is(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; }
function shallowEqual(objA, objB) { if (is(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; }
JavaScript
function subscribeGroupMember(location, listeners, routeSubscription) { addListener(location, listeners, routeSubscription); let isSubscribed = true; return function unsubscribe() { if (!isSubscribed) { return; } const index = listeners.indexOf(routeSubscription); listeners.splice(index, 1); isSubscribed = false; }; }
function subscribeGroupMember(location, listeners, routeSubscription) { addListener(location, listeners, routeSubscription); let isSubscribed = true; return function unsubscribe() { if (!isSubscribed) { return; } const index = listeners.indexOf(routeSubscription); listeners.splice(index, 1); isSubscribed = false; }; }
JavaScript
function invoke(method, arg) { var result = generator[method](arg); var value = result.value; return value instanceof AwaitArgument ? _promise2.default.resolve(value.arg).then(invokeNext, invokeThrow) : _promise2.default.resolve(value).then(function (unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. If the Promise is rejected, however, the // result for this iteration will be rejected with the same // reason. Note that rejections of yielded Promises are not // thrown back into the generator function, as is the case // when an awaited Promise is rejected. This difference in // behavior between yield and await is important, because it // allows the consumer to decide what to do with the yielded // rejection (swallow it and continue, manually .throw it back // into the generator, abandon iteration, whatever). With // await, by contrast, there is no opportunity to examine the // rejection reason outside the generator function, so the // only option is to throw it from the await expression, and // let the generator function handle the exception. result.value = unwrapped; return result; }); }
function invoke(method, arg) { var result = generator[method](arg); var value = result.value; return value instanceof AwaitArgument ? _promise2.default.resolve(value.arg).then(invokeNext, invokeThrow) : _promise2.default.resolve(value).then(function (unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. If the Promise is rejected, however, the // result for this iteration will be rejected with the same // reason. Note that rejections of yielded Promises are not // thrown back into the generator function, as is the case // when an awaited Promise is rejected. This difference in // behavior between yield and await is important, because it // allows the consumer to decide what to do with the yielded // rejection (swallow it and continue, manually .throw it back // into the generator, abandon iteration, whatever). With // await, by contrast, there is no opportunity to examine the // rejection reason outside the generator function, so the // only option is to throw it from the await expression, and // let the generator function handle the exception. result.value = unwrapped; return result; }); }
JavaScript
function addMoreInput(){ var tekape=document.getElementById('tekape');//getElementById ambil form utama sebagai tempat muncul //KONTENER UNTUK INPUTAN var container = document.createElement('div'); container.className='form-group row'; container.id='row'+id; //#row1..dst var containerId='#row'+id; //Input-KETERANGAN var divKeterangan = document.createElement('div'); divKeterangan.className="col-lg-5"; var inputKeterangan = document.createElement('input'); inputKeterangan.type='text'; inputKeterangan.placeholder='nama akun'; inputKeterangan.name='keterangan[]'; inputKeterangan.className='form-control'; divKeterangan.appendChild(inputKeterangan); //Input-NOREF var divNoref = document.createElement('div'); divNoref.className="col-lg-1"; var inputNoref = document.createElement('input'); inputNoref.type='text'; inputNoref.placeholder='Ref'; inputNoref.name='no_ref[]'; inputNoref.className='form-control'; divNoref.appendChild(inputNoref); //Input-NOMINAL var divNominal = document.createElement('div'); divNominal.className="col-lg-3"; var inputNominal = document.createElement('input'); inputNominal.type='text'; inputNominal.placeholder='masukan nominal'; inputNominal.name='nominal[]'; inputNominal.className='form-control nominal'; divNominal.appendChild(inputNominal); //Select-JENIS var divJenis = document.createElement('div'); divJenis.className="col-lg-2"; var selectJenis = document.createElement('select'); selectJenis.className='form-control jenis'; selectJenis.name='jenis[]'; var debit = document.createElement('option'); debit.value='Debit'; debit.innerHTML="Debit"; var kredit = document.createElement('option'); kredit.value='Kredit'; kredit.innerHTML="Kredit"; selectJenis.appendChild(debit); selectJenis.appendChild(kredit); divJenis.appendChild(selectJenis); //BTNHAPUS var divHapus = document.createElement('div'); divHapus.className="col-lg-1"; var btnHapus = document.createElement('button'); btnHapus.type='button'; btnHapus.className='btn btn-danger btn-rounded btn-sm'; btnHapus.innerHTML='x'; btnHapus.onclick= function () { hapusElemen(containerId); return false; }; btnHapus.id='roww'+id; divHapus.appendChild(btnHapus); //Masukan container.appendChild(divKeterangan); container.appendChild(divNoref); container.appendChild(divNominal); container.appendChild(divJenis); container.appendChild(divHapus); tekape.append(container);//jquery id = id + 1; }
function addMoreInput(){ var tekape=document.getElementById('tekape');//getElementById ambil form utama sebagai tempat muncul //KONTENER UNTUK INPUTAN var container = document.createElement('div'); container.className='form-group row'; container.id='row'+id; //#row1..dst var containerId='#row'+id; //Input-KETERANGAN var divKeterangan = document.createElement('div'); divKeterangan.className="col-lg-5"; var inputKeterangan = document.createElement('input'); inputKeterangan.type='text'; inputKeterangan.placeholder='nama akun'; inputKeterangan.name='keterangan[]'; inputKeterangan.className='form-control'; divKeterangan.appendChild(inputKeterangan); //Input-NOREF var divNoref = document.createElement('div'); divNoref.className="col-lg-1"; var inputNoref = document.createElement('input'); inputNoref.type='text'; inputNoref.placeholder='Ref'; inputNoref.name='no_ref[]'; inputNoref.className='form-control'; divNoref.appendChild(inputNoref); //Input-NOMINAL var divNominal = document.createElement('div'); divNominal.className="col-lg-3"; var inputNominal = document.createElement('input'); inputNominal.type='text'; inputNominal.placeholder='masukan nominal'; inputNominal.name='nominal[]'; inputNominal.className='form-control nominal'; divNominal.appendChild(inputNominal); //Select-JENIS var divJenis = document.createElement('div'); divJenis.className="col-lg-2"; var selectJenis = document.createElement('select'); selectJenis.className='form-control jenis'; selectJenis.name='jenis[]'; var debit = document.createElement('option'); debit.value='Debit'; debit.innerHTML="Debit"; var kredit = document.createElement('option'); kredit.value='Kredit'; kredit.innerHTML="Kredit"; selectJenis.appendChild(debit); selectJenis.appendChild(kredit); divJenis.appendChild(selectJenis); //BTNHAPUS var divHapus = document.createElement('div'); divHapus.className="col-lg-1"; var btnHapus = document.createElement('button'); btnHapus.type='button'; btnHapus.className='btn btn-danger btn-rounded btn-sm'; btnHapus.innerHTML='x'; btnHapus.onclick= function () { hapusElemen(containerId); return false; }; btnHapus.id='roww'+id; divHapus.appendChild(btnHapus); //Masukan container.appendChild(divKeterangan); container.appendChild(divNoref); container.appendChild(divNominal); container.appendChild(divJenis); container.appendChild(divHapus); tekape.append(container);//jquery id = id + 1; }
JavaScript
function workerQueue (query, path, callback) { let killed = false const q = queue((next, cb) => { query._log('queue:work') execQuery(next, query, path, (err, done) => { // Ignore after kill if (killed) { return cb() } query._log('queue:work:done', err, done) if (err) { return cb(err) } if (done) { q.kill() killed = true return callback() } cb() }) }, query.concurrency) const fill = () => { query._log('queue:fill') while (q.length() < query.concurrency && path.peersToQuery.length > 0) { q.push(path.peersToQuery.dequeue()) } } fill() // callback handling q.error = (err) => { query._log.error('queue', err) callback(err) } q.drain = () => { query._log('queue:drain') callback() } q.unsaturated = () => { query._log('queue:unsatured') fill() } q.buffer = 0 }
function workerQueue (query, path, callback) { let killed = false const q = queue((next, cb) => { query._log('queue:work') execQuery(next, query, path, (err, done) => { // Ignore after kill if (killed) { return cb() } query._log('queue:work:done', err, done) if (err) { return cb(err) } if (done) { q.kill() killed = true return callback() } cb() }) }, query.concurrency) const fill = () => { query._log('queue:fill') while (q.length() < query.concurrency && path.peersToQuery.length > 0) { q.push(path.peersToQuery.dequeue()) } } fill() // callback handling q.error = (err) => { query._log.error('queue', err) callback(err) } q.drain = () => { query._log('queue:drain') callback() } q.unsaturated = () => { query._log('queue:unsatured') fill() } q.buffer = 0 }