language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
static dataToFishes (data) { return data.map((fish) => { const tempFish = new Fish({...fish}) return tempFish; }) }
static dataToFishes (data) { return data.map((fish) => { const tempFish = new Fish({...fish}) return tempFish; }) }
JavaScript
function normalize ( key, value ) { var isArrayValue = key.match( /\[\]$/ ), namespace = self.unpack( key ), p = this, k; // TODO: profile this against a recursive func while ( true ) { k = namespace.shift(); if ( namespace.length === 0 ) break; p[ k ] || ( p[ k ] = {} ); p = p[ k ]; } if ( isArrayValue ) { if ( primitive(p[k]) !== 'Array' ) p[ k ] = []; p[ k ].push( value ); } else { p[ k ] = value; } return this; }
function normalize ( key, value ) { var isArrayValue = key.match( /\[\]$/ ), namespace = self.unpack( key ), p = this, k; // TODO: profile this against a recursive func while ( true ) { k = namespace.shift(); if ( namespace.length === 0 ) break; p[ k ] || ( p[ k ] = {} ); p = p[ k ]; } if ( isArrayValue ) { if ( primitive(p[k]) !== 'Array' ) p[ k ] = []; p[ k ].push( value ); } else { p[ k ] = value; } return this; }
JavaScript
didReceiveAttrs() { if (this.get("nft") !== this.get("prev_nft")) { this.uploadNFT(this.get("nft")); } this.set("prev_nft", this.get("nft")); }
didReceiveAttrs() { if (this.get("nft") !== this.get("prev_nft")) { this.uploadNFT(this.get("nft")); } this.set("prev_nft", this.get("nft")); }
JavaScript
_setupEncryption() { // TODO: this should all go in a wrapper in e2ee/ that is bootstrapped by passing in the account // and can create RoomEncryption objects and handle encrypted to_device messages and device list changes. const senderKeyLock = new LockMap(); const olmDecryption = new OlmDecryption({ account: this._e2eeAccount, pickleKey: PICKLE_KEY, olm: this._olm, storage: this._storage, now: this._platform.clock.now, ownUserId: this._user.id, senderKeyLock }); this._olmEncryption = new OlmEncryption({ account: this._e2eeAccount, pickleKey: PICKLE_KEY, olm: this._olm, storage: this._storage, now: this._platform.clock.now, ownUserId: this._user.id, olmUtil: this._olmUtil, senderKeyLock }); this._megolmEncryption = new MegOlmEncryption({ account: this._e2eeAccount, pickleKey: PICKLE_KEY, olm: this._olm, storage: this._storage, now: this._platform.clock.now, ownDeviceId: this._sessionInfo.deviceId, }); this._megolmDecryption = new MegOlmDecryption({ pickleKey: PICKLE_KEY, olm: this._olm, olmWorker: this._olmWorker, }); this._deviceMessageHandler.enableEncryption({olmDecryption, megolmDecryption: this._megolmDecryption}); }
_setupEncryption() { // TODO: this should all go in a wrapper in e2ee/ that is bootstrapped by passing in the account // and can create RoomEncryption objects and handle encrypted to_device messages and device list changes. const senderKeyLock = new LockMap(); const olmDecryption = new OlmDecryption({ account: this._e2eeAccount, pickleKey: PICKLE_KEY, olm: this._olm, storage: this._storage, now: this._platform.clock.now, ownUserId: this._user.id, senderKeyLock }); this._olmEncryption = new OlmEncryption({ account: this._e2eeAccount, pickleKey: PICKLE_KEY, olm: this._olm, storage: this._storage, now: this._platform.clock.now, ownUserId: this._user.id, olmUtil: this._olmUtil, senderKeyLock }); this._megolmEncryption = new MegOlmEncryption({ account: this._e2eeAccount, pickleKey: PICKLE_KEY, olm: this._olm, storage: this._storage, now: this._platform.clock.now, ownDeviceId: this._sessionInfo.deviceId, }); this._megolmDecryption = new MegOlmDecryption({ pickleKey: PICKLE_KEY, olm: this._olm, olmWorker: this._olmWorker, }); this._deviceMessageHandler.enableEncryption({olmDecryption, megolmDecryption: this._megolmDecryption}); }
JavaScript
async enableSecretStorage(type, credential) { if (!this._olm) { throw new Error("olm required"); } if (this._sessionBackup) { return false; } const key = await ssssKeyFromCredential(type, credential, this._storage, this._platform, this._olm); // and create session backup, which needs to read from accountData const readTxn = await this._storage.readTxn([ this._storage.storeNames.accountData, ]); await this._createSessionBackup(key, readTxn); // only after having read a secret, write the key // as we only find out if it was good if the MAC verification succeeds const writeTxn = await this._storage.readWriteTxn([ this._storage.storeNames.session, ]); try { ssssWriteKey(key, writeTxn); } catch (err) { writeTxn.abort(); throw err; } await writeTxn.complete(); this._hasSecretStorageKey.set(true); }
async enableSecretStorage(type, credential) { if (!this._olm) { throw new Error("olm required"); } if (this._sessionBackup) { return false; } const key = await ssssKeyFromCredential(type, credential, this._storage, this._platform, this._olm); // and create session backup, which needs to read from accountData const readTxn = await this._storage.readTxn([ this._storage.storeNames.accountData, ]); await this._createSessionBackup(key, readTxn); // only after having read a secret, write the key // as we only find out if it was good if the MAC verification succeeds const writeTxn = await this._storage.readWriteTxn([ this._storage.storeNames.session, ]); try { ssssWriteKey(key, writeTxn); } catch (err) { writeTxn.abort(); throw err; } await writeTxn.complete(); this._hasSecretStorageKey.set(true); }
JavaScript
async start(lastVersionResponse, log) { if (lastVersionResponse) { // store /versions response const txn = await this._storage.readWriteTxn([ this._storage.storeNames.session ]); txn.session.set("serverVersions", lastVersionResponse); // TODO: what can we do if this throws? await txn.complete(); } // enable session backup, this requests the latest backup version if (!this._sessionBackup) { const txn = await this._storage.readTxn([ this._storage.storeNames.session, this._storage.storeNames.accountData, ]); // try set up session backup if we stored the ssss key const ssssKey = await ssssReadKey(txn); if (ssssKey) { // txn will end here as this does a network request await this._createSessionBackup(ssssKey, txn); } this._hasSecretStorageKey.set(!!ssssKey); } // restore unfinished operations, like sending out room keys const opsTxn = await this._storage.readWriteTxn([ this._storage.storeNames.operations ]); const operations = await opsTxn.operations.getAll(); const operationsByScope = groupBy(operations, o => o.scope); for (const room of this._rooms.values()) { let roomOperationsByType; const roomOperations = operationsByScope.get(room.id); if (roomOperations) { roomOperationsByType = groupBy(roomOperations, r => r.type); } room.start(roomOperationsByType, log); } }
async start(lastVersionResponse, log) { if (lastVersionResponse) { // store /versions response const txn = await this._storage.readWriteTxn([ this._storage.storeNames.session ]); txn.session.set("serverVersions", lastVersionResponse); // TODO: what can we do if this throws? await txn.complete(); } // enable session backup, this requests the latest backup version if (!this._sessionBackup) { const txn = await this._storage.readTxn([ this._storage.storeNames.session, this._storage.storeNames.accountData, ]); // try set up session backup if we stored the ssss key const ssssKey = await ssssReadKey(txn); if (ssssKey) { // txn will end here as this does a network request await this._createSessionBackup(ssssKey, txn); } this._hasSecretStorageKey.set(!!ssssKey); } // restore unfinished operations, like sending out room keys const opsTxn = await this._storage.readWriteTxn([ this._storage.storeNames.operations ]); const operations = await opsTxn.operations.getAll(); const operationsByScope = groupBy(operations, o => o.scope); for (const room of this._rooms.values()) { let roomOperationsByType; const roomOperations = operationsByScope.get(room.id); if (roomOperations) { roomOperationsByType = groupBy(roomOperations, r => r.type); } room.start(roomOperationsByType, log); } }
JavaScript
createOrGetArchivedRoomForSync(roomId) { let archivedRoom = this._activeArchivedRooms.get(roomId); if (archivedRoom) { archivedRoom.retain(); } else { archivedRoom = this._createArchivedRoom(roomId); } return archivedRoom; }
createOrGetArchivedRoomForSync(roomId) { let archivedRoom = this._activeArchivedRooms.get(roomId); if (archivedRoom) { archivedRoom.retain(); } else { archivedRoom = this._createArchivedRoom(roomId); } return archivedRoom; }
JavaScript
view(view, mountOptions = undefined) { let root; try { root = view.mount(mountOptions); } catch (err) { return errorToDOM(err); } this._templateView.addSubView(view); return root; }
view(view, mountOptions = undefined) { let root; try { root = view.mount(mountOptions); } catch (err) { return errorToDOM(err); } this._templateView.addSubView(view); return root; }
JavaScript
mapView(mapFn, viewCreator) { return this._addReplaceNodeBinding(mapFn, (prevNode) => { if (prevNode && prevNode.nodeType !== Node.COMMENT_NODE) { const subViews = this._templateView._subViews; const viewIdx = subViews.findIndex(v => v.root() === prevNode); if (viewIdx !== -1) { const [view] = subViews.splice(viewIdx, 1); view.unmount(); } } const view = viewCreator(mapFn(this._value)); if (view) { return this.view(view); } else { return document.createComment("node binding placeholder"); } }); }
mapView(mapFn, viewCreator) { return this._addReplaceNodeBinding(mapFn, (prevNode) => { if (prevNode && prevNode.nodeType !== Node.COMMENT_NODE) { const subViews = this._templateView._subViews; const viewIdx = subViews.findIndex(v => v.root() === prevNode); if (viewIdx !== -1) { const [view] = subViews.splice(viewIdx, 1); view.unmount(); } } const view = viewCreator(mapFn(this._value)); if (view) { return this.view(view); } else { return document.createComment("node binding placeholder"); } }); }
JavaScript
mapSideEffect(mapFn, sideEffect) { let prevValue = mapFn(this._value); const binding = () => { const newValue = mapFn(this._value); if (prevValue !== newValue) { sideEffect(newValue, prevValue); prevValue = newValue; } }; this._addBinding(binding); sideEffect(prevValue, undefined); }
mapSideEffect(mapFn, sideEffect) { let prevValue = mapFn(this._value); const binding = () => { const newValue = mapFn(this._value); if (prevValue !== newValue) { sideEffect(newValue, prevValue); prevValue = newValue; } }; this._addBinding(binding); sideEffect(prevValue, undefined); }
JavaScript
async _findOverlappingEvents(fragmentEntry, events, txn, log) { let expectedOverlappingEventId; if (fragmentEntry.hasLinkedFragment) { expectedOverlappingEventId = await this._findExpectedOverlappingEventId(fragmentEntry, txn); } let remainingEvents = events; let nonOverlappingEvents = []; let neighbourFragmentEntry; while (remainingEvents && remainingEvents.length) { const eventIds = remainingEvents.map(e => e.event_id); const duplicateEventId = await txn.timelineEvents.findFirstOccurringEventId(this._roomId, eventIds); if (duplicateEventId) { const duplicateEventIndex = remainingEvents.findIndex(e => e.event_id === duplicateEventId); // should never happen, just being defensive as this *can't* go wrong if (duplicateEventIndex === -1) { throw new Error(`findFirstOccurringEventId returned ${duplicateEventIndex} which wasn't ` + `in [${eventIds.join(",")}] in ${this._roomId}`); } nonOverlappingEvents.push(...remainingEvents.slice(0, duplicateEventIndex)); if (!expectedOverlappingEventId || duplicateEventId === expectedOverlappingEventId) { // TODO: check here that the neighbourEvent is at the correct edge of it's fragment // get neighbour fragment to link it up later on const neighbourEvent = await txn.timelineEvents.getByEventId(this._roomId, duplicateEventId); if (neighbourEvent.fragmentId === fragmentEntry.fragmentId) { log.log("hit #160, prevent fragment linking to itself", log.level.Warn); } else { const neighbourFragment = await txn.timelineFragments.get(this._roomId, neighbourEvent.fragmentId); neighbourFragmentEntry = fragmentEntry.createNeighbourEntry(neighbourFragment); } // trim overlapping events remainingEvents = null; } else { // we've hit https://github.com/matrix-org/synapse/issues/7164, // e.g. the event id we found is already in our store but it is not // the adjacent fragment id. Ignore the event, but keep processing the ones after. remainingEvents = remainingEvents.slice(duplicateEventIndex + 1); } } else { nonOverlappingEvents.push(...remainingEvents); remainingEvents = null; } } return {nonOverlappingEvents, neighbourFragmentEntry}; }
async _findOverlappingEvents(fragmentEntry, events, txn, log) { let expectedOverlappingEventId; if (fragmentEntry.hasLinkedFragment) { expectedOverlappingEventId = await this._findExpectedOverlappingEventId(fragmentEntry, txn); } let remainingEvents = events; let nonOverlappingEvents = []; let neighbourFragmentEntry; while (remainingEvents && remainingEvents.length) { const eventIds = remainingEvents.map(e => e.event_id); const duplicateEventId = await txn.timelineEvents.findFirstOccurringEventId(this._roomId, eventIds); if (duplicateEventId) { const duplicateEventIndex = remainingEvents.findIndex(e => e.event_id === duplicateEventId); // should never happen, just being defensive as this *can't* go wrong if (duplicateEventIndex === -1) { throw new Error(`findFirstOccurringEventId returned ${duplicateEventIndex} which wasn't ` + `in [${eventIds.join(",")}] in ${this._roomId}`); } nonOverlappingEvents.push(...remainingEvents.slice(0, duplicateEventIndex)); if (!expectedOverlappingEventId || duplicateEventId === expectedOverlappingEventId) { // TODO: check here that the neighbourEvent is at the correct edge of it's fragment // get neighbour fragment to link it up later on const neighbourEvent = await txn.timelineEvents.getByEventId(this._roomId, duplicateEventId); if (neighbourEvent.fragmentId === fragmentEntry.fragmentId) { log.log("hit #160, prevent fragment linking to itself", log.level.Warn); } else { const neighbourFragment = await txn.timelineFragments.get(this._roomId, neighbourEvent.fragmentId); neighbourFragmentEntry = fragmentEntry.createNeighbourEntry(neighbourFragment); } // trim overlapping events remainingEvents = null; } else { // we've hit https://github.com/matrix-org/synapse/issues/7164, // e.g. the event id we found is already in our store but it is not // the adjacent fragment id. Ignore the event, but keep processing the ones after. remainingEvents = remainingEvents.slice(duplicateEventIndex + 1); } } else { nonOverlappingEvents.push(...remainingEvents); remainingEvents = null; } } return {nonOverlappingEvents, neighbourFragmentEntry}; }
JavaScript
function linkify(text, callback) { const matches = text.matchAll(regex); let curr = 0; for (let match of matches) { const precedingText = text.slice(curr, match.index); callback(precedingText, false); callback(match[0], true); const len = match[0].length; curr = match.index + len; } const remainingText = text.slice(curr); callback(remainingText, false); }
function linkify(text, callback) { const matches = text.matchAll(regex); let curr = 0; for (let match of matches) { const precedingText = text.slice(curr, match.index); callback(precedingText, false); callback(match[0], true); const len = match[0].length; curr = match.index + len; } const remainingText = text.slice(curr); callback(remainingText, false); }
JavaScript
function parsePlainBody(body) { const parts = []; const lines = body.split("\n"); // create callback outside of loop const linkifyCallback = (text, isLink) => { if (isLink) { parts.push(new LinkPart(text, text)); } else { parts.push(new TextPart(text)); } }; for (let i = 0; i < lines.length; i += 1) { const line = lines[i]; if (line.length) { linkify(line, linkifyCallback); } const isLastLine = i >= (lines.length - 1); if (!isLastLine) { parts.push(new NewLinePart()); } } return new MessageBody(body, parts); }
function parsePlainBody(body) { const parts = []; const lines = body.split("\n"); // create callback outside of loop const linkifyCallback = (text, isLink) => { if (isLink) { parts.push(new LinkPart(text, text)); } else { parts.push(new TextPart(text)); } }; for (let i = 0; i < lines.length; i += 1) { const line = lines[i]; if (line.length) { linkify(line, linkifyCallback); } const isLastLine = i >= (lines.length - 1); if (!isLastLine) { parts.push(new NewLinePart()); } } return new MessageBody(body, parts); }
JavaScript
function clicked() { const el = d3.event.target; if (!el || !el.parentElement || !el.parentElement.parentElement) return; const parent = el.parentElement, grand = parent.parentElement, great = grand.parentElement; const p = d3.mouse(this); const i = findCell(p[0], p[1]); if (parent.id === "rivers") editRiver(); else if (grand.id === "routes") editRoute(); else if (el.tagName === "tspan" && grand.parentNode.parentNode.id === "labels") editLabel(); else if (grand.id === "burgLabels") editBurg(); else if (grand.id === "burgIcons") editBurg(); else if (parent.id === "ice") editIce(); else if (parent.id === "terrain") editReliefIcon(); else if (parent.id === "markers") editMarker(); else if (grand.id === "coastline") editCoastline(); else if (great.id === "armies") editRegiment(); else if (pack.cells.t[i] === 1) { const node = document.getElementById("island_"+pack.cells.f[i]); editCoastline(node); } else if (grand.id === "lakes") editLake(); }
function clicked() { const el = d3.event.target; if (!el || !el.parentElement || !el.parentElement.parentElement) return; const parent = el.parentElement, grand = parent.parentElement, great = grand.parentElement; const p = d3.mouse(this); const i = findCell(p[0], p[1]); if (parent.id === "rivers") editRiver(); else if (grand.id === "routes") editRoute(); else if (el.tagName === "tspan" && grand.parentNode.parentNode.id === "labels") editLabel(); else if (grand.id === "burgLabels") editBurg(); else if (grand.id === "burgIcons") editBurg(); else if (parent.id === "ice") editIce(); else if (parent.id === "terrain") editReliefIcon(); else if (parent.id === "markers") editMarker(); else if (grand.id === "coastline") editCoastline(); else if (great.id === "armies") editRegiment(); else if (pack.cells.t[i] === 1) { const node = document.getElementById("island_"+pack.cells.f[i]); editCoastline(node); } else if (grand.id === "lakes") editLake(); }
JavaScript
function refreshAllEditors() { console.time('refreshAllEditors'); if (document.getElementById('culturesEditorRefresh').offsetParent) culturesEditorRefresh.click(); if (document.getElementById('biomesEditorRefresh').offsetParent) biomesEditorRefresh.click(); if (document.getElementById('diplomacyEditorRefresh').offsetParent) diplomacyEditorRefresh.click(); if (document.getElementById('provincesEditorRefresh').offsetParent) provincesEditorRefresh.click(); if (document.getElementById('religionsEditorRefresh').offsetParent) religionsEditorRefresh.click(); if (document.getElementById('statesEditorRefresh').offsetParent) statesEditorRefresh.click(); if (document.getElementById('zonesEditorRefresh').offsetParent) zonesEditorRefresh.click(); console.timeEnd('refreshAllEditors'); }
function refreshAllEditors() { console.time('refreshAllEditors'); if (document.getElementById('culturesEditorRefresh').offsetParent) culturesEditorRefresh.click(); if (document.getElementById('biomesEditorRefresh').offsetParent) biomesEditorRefresh.click(); if (document.getElementById('diplomacyEditorRefresh').offsetParent) diplomacyEditorRefresh.click(); if (document.getElementById('provincesEditorRefresh').offsetParent) provincesEditorRefresh.click(); if (document.getElementById('religionsEditorRefresh').offsetParent) religionsEditorRefresh.click(); if (document.getElementById('statesEditorRefresh').offsetParent) statesEditorRefresh.click(); if (document.getElementById('zonesEditorRefresh').offsetParent) zonesEditorRefresh.click(); console.timeEnd('refreshAllEditors'); }
JavaScript
function polygonclip(points, bbox, secure = 0) { var result, edge, prev, prevInside, inter, i, p, inside; // clip against each side of the clip rectangle for (edge = 1; edge <= 8; edge *= 2) { result = []; prev = points[points.length-1]; prevInside = !(bitCode(prev, bbox) & edge); for (i = 0; i < points.length; i++) { p = points[i]; inside = !(bitCode(p, bbox) & edge); inter = inside !== prevInside; // segment goes through the clip window const pi = intersect(prev, p, edge, bbox); if (inter) result.push(pi); // add an intersection point if (secure && inter) result.push(pi, pi); // add additional intersection points to secure correct d3 curve if (inside) result.push(p); // add a point if it's inside prev = p; prevInside = inside; } points = result; if (!points.length) break; } //result.forEach(p => debug.append("circle").attr("cx", p[0]).attr("cy", p[1]).attr("r", .6).attr("fill", "red")); return result; }
function polygonclip(points, bbox, secure = 0) { var result, edge, prev, prevInside, inter, i, p, inside; // clip against each side of the clip rectangle for (edge = 1; edge <= 8; edge *= 2) { result = []; prev = points[points.length-1]; prevInside = !(bitCode(prev, bbox) & edge); for (i = 0; i < points.length; i++) { p = points[i]; inside = !(bitCode(p, bbox) & edge); inter = inside !== prevInside; // segment goes through the clip window const pi = intersect(prev, p, edge, bbox); if (inter) result.push(pi); // add an intersection point if (secure && inter) result.push(pi, pi); // add additional intersection points to secure correct d3 curve if (inside) result.push(p); // add a point if it's inside prev = p; prevInside = inside; } points = result; if (!points.length) break; } //result.forEach(p => debug.append("circle").attr("cx", p[0]).attr("cy", p[1]).attr("r", .6).attr("fill", "red")); return result; }
JavaScript
function createStates() { console.time('createStates'); const states = [{i:0, name: "Neutrals"}]; const colors = getColors(burgs.length-1); burgs.forEach(function(b, i) { if (!i) return; // skip first element // burgs data b.i = b.state = i; b.culture = cells.culture[b.cell]; b.name = Names.getCultureShort(b.culture); b.feature = cells.f[b.cell]; b.capital = 1; // states data const expansionism = rn(Math.random() * powerInput.value + 1, 1); const basename = b.name.length < 9 && b.cell%5 === 0 ? b.name : Names.getCultureShort(b.culture); const name = Names.getState(basename, b.culture); const nomadic = [1, 2, 3, 4].includes(cells.biome[b.cell]); const type = nomadic ? "Nomadic" : cultures[b.culture].type === "Nomadic" ? "Generic" : cultures[b.culture].type; states.push({i, color: colors[i-1], name, expansionism, capital: i, type, center: b.cell, culture: b.culture}); cells.burg[b.cell] = i; }); console.timeEnd('createStates'); return states; }
function createStates() { console.time('createStates'); const states = [{i:0, name: "Neutrals"}]; const colors = getColors(burgs.length-1); burgs.forEach(function(b, i) { if (!i) return; // skip first element // burgs data b.i = b.state = i; b.culture = cells.culture[b.cell]; b.name = Names.getCultureShort(b.culture); b.feature = cells.f[b.cell]; b.capital = 1; // states data const expansionism = rn(Math.random() * powerInput.value + 1, 1); const basename = b.name.length < 9 && b.cell%5 === 0 ? b.name : Names.getCultureShort(b.culture); const name = Names.getState(basename, b.culture); const nomadic = [1, 2, 3, 4].includes(cells.biome[b.cell]); const type = nomadic ? "Nomadic" : cultures[b.culture].type === "Nomadic" ? "Generic" : cultures[b.culture].type; states.push({i, color: colors[i-1], name, expansionism, capital: i, type, center: b.cell, culture: b.culture}); cells.burg[b.cell] = i; }); console.timeEnd('createStates'); return states; }
JavaScript
function placeTowns() { console.time('placeTowns'); const score = new Int16Array(cells.s.map(s => s * gauss(1,3,0,20,3))); // a bit randomized cell score for towns placement const sorted = cells.i.filter(i => !cells.burg[i] && score[i] > 0 && cells.culture[i]).sort((a, b) => score[b] - score[a]); // filtered and sorted array of indexes const desiredNumber = manorsInput.value == 1000 ? rn(sorted.length / 5 / (grid.points.length / 10000) ** .8) : manorsInput.valueAsNumber; const burgsNumber = Math.min(desiredNumber, sorted.length); // towns to generate let burgsAdded = 0; const burgsTree = burgs[0]; let spacing = (graphWidth + graphHeight) / 150 / (burgsNumber ** .7 / 66); // min distance between towns while (burgsAdded < burgsNumber && spacing > 1) { for (let i=0; burgsAdded < burgsNumber && i < sorted.length; i++) { if (cells.burg[sorted[i]]) continue; const cell = sorted[i], x = cells.p[cell][0], y = cells.p[cell][1]; const s = spacing * gauss(1, .3, .2, 2, 2); // randomize to make placement not uniform if (burgsTree.find(x, y, s) !== undefined) continue; // to close to existing burg const burg = burgs.length; const culture = cells.culture[cell]; const name = Names.getCulture(culture); burgs.push({cell, x, y, state: 0, i: burg, culture, name, capital: 0, feature:cells.f[cell]}); burgsTree.add([x, y]); cells.burg[cell] = burg; burgsAdded++; } spacing *= .5; } if (manorsInput.value != 1000 && burgsAdded < desiredNumber) { console.error(`Cannot place all burgs. Requested ${desiredNumber}, placed ${burgsAdded}`); } burgs[0] = {name:undefined}; // do not store burgsTree anymore console.timeEnd('placeTowns'); }
function placeTowns() { console.time('placeTowns'); const score = new Int16Array(cells.s.map(s => s * gauss(1,3,0,20,3))); // a bit randomized cell score for towns placement const sorted = cells.i.filter(i => !cells.burg[i] && score[i] > 0 && cells.culture[i]).sort((a, b) => score[b] - score[a]); // filtered and sorted array of indexes const desiredNumber = manorsInput.value == 1000 ? rn(sorted.length / 5 / (grid.points.length / 10000) ** .8) : manorsInput.valueAsNumber; const burgsNumber = Math.min(desiredNumber, sorted.length); // towns to generate let burgsAdded = 0; const burgsTree = burgs[0]; let spacing = (graphWidth + graphHeight) / 150 / (burgsNumber ** .7 / 66); // min distance between towns while (burgsAdded < burgsNumber && spacing > 1) { for (let i=0; burgsAdded < burgsNumber && i < sorted.length; i++) { if (cells.burg[sorted[i]]) continue; const cell = sorted[i], x = cells.p[cell][0], y = cells.p[cell][1]; const s = spacing * gauss(1, .3, .2, 2, 2); // randomize to make placement not uniform if (burgsTree.find(x, y, s) !== undefined) continue; // to close to existing burg const burg = burgs.length; const culture = cells.culture[cell]; const name = Names.getCulture(culture); burgs.push({cell, x, y, state: 0, i: burg, culture, name, capital: 0, feature:cells.f[cell]}); burgsTree.add([x, y]); cells.burg[cell] = burg; burgsAdded++; } spacing *= .5; } if (manorsInput.value != 1000 && burgsAdded < desiredNumber) { console.error(`Cannot place all burgs. Requested ${desiredNumber}, placed ${burgsAdded}`); } burgs[0] = {name:undefined}; // do not store burgsTree anymore console.timeEnd('placeTowns'); }
JavaScript
function isPassable(from, to) { if (cells.f[from] !== cells.f[to]) return false; // on different islands const queue = [from], used = new Uint8Array(cells.i.length), state = cells.state[from]; while (queue.length) { const current = queue.pop(); if (current === to) return true; // way is found cells.c[current].forEach(c => { if (used[c] || cells.h[c] < 20 || cells.state[c] !== state) return; queue.push(c); used[c] = 1; }); } return false; // way is not found }
function isPassable(from, to) { if (cells.f[from] !== cells.f[to]) return false; // on different islands const queue = [from], used = new Uint8Array(cells.i.length), state = cells.state[from]; while (queue.length) { const current = queue.pop(); if (current === to) return true; // way is found cells.c[current].forEach(c => { if (used[c] || cells.h[c] < 20 || cells.state[c] !== state) return; queue.push(c); used[c] = 1; }); } return false; // way is not found }
JavaScript
function request(name, parameters) { $spinner.show(); $error.add($devices).hide(); lastRequest = name; port.postMessage({ name: name, parameters: parameters }); }
function request(name, parameters) { $spinner.show(); $error.add($devices).hide(); lastRequest = name; port.postMessage({ name: name, parameters: parameters }); }
JavaScript
function sendUrl(device) { chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) { request(METHOD_SENDURL, { device: device.uuid, enumerator: device.deviceEnumeratorName, url: tabs[0].url }); }); }
function sendUrl(device) { chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) { request(METHOD_SENDURL, { device: device.uuid, enumerator: device.deviceEnumeratorName, url: tabs[0].url }); }); }
JavaScript
idmProtocolStateToText() { switch(this.idmProtocolState) { case -1: return 'not connected'; case 0: return 'idle'; case 1: return 'init sent waiting for answer'; case 2: return 'init answer received'; case 3: return 'data requested, waiting for ack'; case 4: return 'data request ack received'; case 5: return 'data content request sent, waiting for data'; case 6: return 'data set value sent, waiting of ack'; } }
idmProtocolStateToText() { switch(this.idmProtocolState) { case -1: return 'not connected'; case 0: return 'idle'; case 1: return 'init sent waiting for answer'; case 2: return 'init answer received'; case 3: return 'data requested, waiting for ack'; case 4: return 'data request ack received'; case 5: return 'data content request sent, waiting for data'; case 6: return 'data set value sent, waiting of ack'; } }
JavaScript
handle_communication() { // first send from the sendQueue, but not more than 10 items at once let count = 0; this.maxWrites = this.config.pollinterval - (this.requestInterval * 6 + this.secondSetValueOffset)/1000; this.maxWrites = Math.floor(this.maxWrites / (2 * this.setValueDelay / 1000 )); this.log.debug('********* check if data has to be sent, max sent at once: ' + this.maxWrites); while(count++ < this.maxWrites && this.sendQueue.hasItems) { this.log.debug('********* found data to be sent'); let item = this.sendQueue.peek(); if (isFunction(item)) { const numItems = item(false); // get the number of items to be generated if (count + numItems <= this.maxWrites) { count --; item = this.sendQueue.dequeue(); item(true); // call the function that creates the messages to be sent continue; } else { break; // not enough slots free to be sent at once, so skip it this time } } item = this.sendQueue.dequeue(); this.log.info('setting values: ' + idm.get_protocol_string(item)); if (this.client) setTimeout(this.send_init.bind(this), 2*count * this.setValueDelay) if (this.client) setTimeout(this.sendSetValueMessage.bind(this, item), (2*count+1) * this.setValueDelay); if (this.client) setTimeout(this.sendSetValueMessage.bind(this, item), (2*count+1) * this.setValueDelay + this.secondSetValueOffset); } // now request the data setTimeout(this.request_data.bind(this), 2*count * this.setValueDelay + this.secondSetValueOffset); }
handle_communication() { // first send from the sendQueue, but not more than 10 items at once let count = 0; this.maxWrites = this.config.pollinterval - (this.requestInterval * 6 + this.secondSetValueOffset)/1000; this.maxWrites = Math.floor(this.maxWrites / (2 * this.setValueDelay / 1000 )); this.log.debug('********* check if data has to be sent, max sent at once: ' + this.maxWrites); while(count++ < this.maxWrites && this.sendQueue.hasItems) { this.log.debug('********* found data to be sent'); let item = this.sendQueue.peek(); if (isFunction(item)) { const numItems = item(false); // get the number of items to be generated if (count + numItems <= this.maxWrites) { count --; item = this.sendQueue.dequeue(); item(true); // call the function that creates the messages to be sent continue; } else { break; // not enough slots free to be sent at once, so skip it this time } } item = this.sendQueue.dequeue(); this.log.info('setting values: ' + idm.get_protocol_string(item)); if (this.client) setTimeout(this.send_init.bind(this), 2*count * this.setValueDelay) if (this.client) setTimeout(this.sendSetValueMessage.bind(this, item), (2*count+1) * this.setValueDelay); if (this.client) setTimeout(this.sendSetValueMessage.bind(this, item), (2*count+1) * this.setValueDelay + this.secondSetValueOffset); } // now request the data setTimeout(this.request_data.bind(this), 2*count * this.setValueDelay + this.secondSetValueOffset); }
JavaScript
send_init() { if (this.connectedToIDM === false) { this.log.info('sending initial init message to heatpump'); } if (this.idmProtocolState > 0) { this.log.info('wrong state, should be in -1 or 0 but we are in ' + this.idmProtocolState + ' resetting connection'); this.setConnected(false, true); return; } var init_message = idm.create_init_message(); this.log.silly('init message: ' + idm.get_protocol_string(init_message)); if(this.client) { this.client.write(init_message); this.idmProtocolState = 1; } }
send_init() { if (this.connectedToIDM === false) { this.log.info('sending initial init message to heatpump'); } if (this.idmProtocolState > 0) { this.log.info('wrong state, should be in -1 or 0 but we are in ' + this.idmProtocolState + ' resetting connection'); this.setConnected(false, true); return; } var init_message = idm.create_init_message(); this.log.silly('init message: ' + idm.get_protocol_string(init_message)); if(this.client) { this.client.write(init_message); this.idmProtocolState = 1; } }
JavaScript
request_data() { this.log.debug('requesting data for ' + this.version); this.haveData = true; var dataBlocks = idm.getSensorDataBlocks(this.version); // get the known data blocks for the connected version if (!dataBlocks) { this.log.debug('no sensor data blocks defined, no data will be requested'); return; } if (!this.statesCreated) { this.CreateStates(); // create the states according to the connected version } // request loop for all known sensor data blocks let i, delayMultiplier = 0; for (i = 0; i < dataBlocks.length; i++, delayMultiplier++ ) { setTimeout(this.request_data_block.bind(this, dataBlocks[i]), delayMultiplier * this.requestInterval + this.requestInitDelay); } // request the next settings datablock var dataBlocksArray = idm.getSettingsDataBlocks(this.version); if (!dataBlocksArray) { this.log.debug('no settings data blocks defined, no settings data will be requested'); return; } this.lastSettingsIndex %= dataBlocksArray.length; dataBlocks = dataBlocksArray[this.lastSettingsIndex++]; if (!dataBlocks) { this.log.debug('no sensor data blocks defined, no data will be requested'); return; } for (i = 0; i < dataBlocks.length; i++, delayMultiplier++ ) { setTimeout(this.request_data_block.bind(this, dataBlocks[i]), delayMultiplier * this.requestInterval + this.requestInitDelay); } }
request_data() { this.log.debug('requesting data for ' + this.version); this.haveData = true; var dataBlocks = idm.getSensorDataBlocks(this.version); // get the known data blocks for the connected version if (!dataBlocks) { this.log.debug('no sensor data blocks defined, no data will be requested'); return; } if (!this.statesCreated) { this.CreateStates(); // create the states according to the connected version } // request loop for all known sensor data blocks let i, delayMultiplier = 0; for (i = 0; i < dataBlocks.length; i++, delayMultiplier++ ) { setTimeout(this.request_data_block.bind(this, dataBlocks[i]), delayMultiplier * this.requestInterval + this.requestInitDelay); } // request the next settings datablock var dataBlocksArray = idm.getSettingsDataBlocks(this.version); if (!dataBlocksArray) { this.log.debug('no settings data blocks defined, no settings data will be requested'); return; } this.lastSettingsIndex %= dataBlocksArray.length; dataBlocks = dataBlocksArray[this.lastSettingsIndex++]; if (!dataBlocks) { this.log.debug('no sensor data blocks defined, no data will be requested'); return; } for (i = 0; i < dataBlocks.length; i++, delayMultiplier++ ) { setTimeout(this.request_data_block.bind(this, dataBlocks[i]), delayMultiplier * this.requestInterval + this.requestInitDelay); } }
JavaScript
request_data_content() { if (this.idmProtocolState !== 4) { this.log.info('wrong state, should be in 4 but we are in ' + this.idmProtocolState + ' resetting connection'); this.setConnected(false, true); return; } var message = idm.create_request_data_content_message(); this.log.debug('requesting data content'); if (this.client) { this.client.write(message); this.idmProtocolState = 5; } }
request_data_content() { if (this.idmProtocolState !== 4) { this.log.info('wrong state, should be in 4 but we are in ' + this.idmProtocolState + ' resetting connection'); this.setConnected(false, true); return; } var message = idm.create_request_data_content_message(); this.log.debug('requesting data content'); if (this.client) { this.client.write(message); this.idmProtocolState = 5; } }
JavaScript
receive_data(data) { var state = idm.add_to_packet(data); this.log.silly('************* receiving **************** state ' + state + ' data=' + idm.get_protocol_string(data)); if (state == 3) { // data packed received completely, let's check what we've got var received_data = idm.get_data_packet(); idm.reset(); // reset the packet reader to be ready for the next packet var protocolState = idm.protocol_state(received_data); this.log.debug('protocol state ' + protocolState); if (protocolState === 'R1') {// successful data request, we can request the real data now, after a short pause ofc. if (this.idmProtocolState !== 3) { this.log.info('wrong state, should be in 3 but we are in ' + this.idmProtocolState + ' resetting connection'); this.setConnected(false, true); return; } this.idmProtocolState = 4; setTimeout(this.request_data_content.bind(this), this.requestDataContentDelay); return; } if (protocolState === 'S1') { if (this.idmProtocolState !== 6) { this.log.info('wrong state, should be in 6 but we are in ' + this.idmProtocolState + ' resetting connection'); this.setConnected(false, true); return; } this.idmProtocolState = 0; return; } var text = idm.interpret_data(this.version, received_data, this.setIDMState.bind(this)); this.log.debug('received data: ' + received_data.length + ' - ' + text); if (protocolState.slice(0,4) == 'Data') { // received a data block, setting the according state if (this.idmProtocolState !== 5) { this.log.info('wrong state, shold be in 5 but we are in ' + this.idmProtocolState + ' resetting connection'); this.setConnected(false, true); return; } this.idmProtocolState = 0; this.setStateAsync(protocolState, text, true); return; } if (text.slice(0,1) ==="V") { // received answer to init message, if the first one after connection set the state if (this.idmProtocolState !== 1) { this.log.info('wrong state, should be in 1 but we are in ' + this.idmProtocolState + ' resetting connection'); this.setConnected(false, true); return; } this.idmProtocolState = 2; if (!this.connectedToIDM) { this.version = text.slice(9); this.setStateAsync('idm_control_version', this.version, true); this.setConnected(true); this.CreateStates(); this.idmProtocolState = 0; // this is the first contact to get the verison, we are back to idle } } else { this.log.info('not sure what to do, idm-protocol-state' + this.idmProtocolStateToText()); this.log.info('unknown protocol state ' + protocolState + ' data=' + text); } } else if (state > 3) { idm.reset(); } }
receive_data(data) { var state = idm.add_to_packet(data); this.log.silly('************* receiving **************** state ' + state + ' data=' + idm.get_protocol_string(data)); if (state == 3) { // data packed received completely, let's check what we've got var received_data = idm.get_data_packet(); idm.reset(); // reset the packet reader to be ready for the next packet var protocolState = idm.protocol_state(received_data); this.log.debug('protocol state ' + protocolState); if (protocolState === 'R1') {// successful data request, we can request the real data now, after a short pause ofc. if (this.idmProtocolState !== 3) { this.log.info('wrong state, should be in 3 but we are in ' + this.idmProtocolState + ' resetting connection'); this.setConnected(false, true); return; } this.idmProtocolState = 4; setTimeout(this.request_data_content.bind(this), this.requestDataContentDelay); return; } if (protocolState === 'S1') { if (this.idmProtocolState !== 6) { this.log.info('wrong state, should be in 6 but we are in ' + this.idmProtocolState + ' resetting connection'); this.setConnected(false, true); return; } this.idmProtocolState = 0; return; } var text = idm.interpret_data(this.version, received_data, this.setIDMState.bind(this)); this.log.debug('received data: ' + received_data.length + ' - ' + text); if (protocolState.slice(0,4) == 'Data') { // received a data block, setting the according state if (this.idmProtocolState !== 5) { this.log.info('wrong state, shold be in 5 but we are in ' + this.idmProtocolState + ' resetting connection'); this.setConnected(false, true); return; } this.idmProtocolState = 0; this.setStateAsync(protocolState, text, true); return; } if (text.slice(0,1) ==="V") { // received answer to init message, if the first one after connection set the state if (this.idmProtocolState !== 1) { this.log.info('wrong state, should be in 1 but we are in ' + this.idmProtocolState + ' resetting connection'); this.setConnected(false, true); return; } this.idmProtocolState = 2; if (!this.connectedToIDM) { this.version = text.slice(9); this.setStateAsync('idm_control_version', this.version, true); this.setConnected(true); this.CreateStates(); this.idmProtocolState = 0; // this is the first contact to get the verison, we are back to idle } } else { this.log.info('not sure what to do, idm-protocol-state' + this.idmProtocolStateToText()); this.log.info('unknown protocol state ' + protocolState + ' data=' + text); } } else if (state > 3) { idm.reset(); } }
JavaScript
function Model__ElementCreate(nameContainer) { Graph__log("Model__ElementCreate") var nameContainer = Model__CONTAINER_BASENAME + Model__currentElementID; // Update elementID while (Model__AppScope.containerExists(nameContainer)) { Model__currentElementID++; nameContainer = Model__CONTAINER_BASENAME + Model__currentElementID; } const theContainer = Model__AppScope.newContainer(nameContainer); Model__currentElementID++; return theContainer; }
function Model__ElementCreate(nameContainer) { Graph__log("Model__ElementCreate") var nameContainer = Model__CONTAINER_BASENAME + Model__currentElementID; // Update elementID while (Model__AppScope.containerExists(nameContainer)) { Model__currentElementID++; nameContainer = Model__CONTAINER_BASENAME + Model__currentElementID; } const theContainer = Model__AppScope.newContainer(nameContainer); Model__currentElementID++; return theContainer; }
JavaScript
function addSidebarElementIcon(graph, sidebar) { // Function that is executed when the image is dropped on // the graph. The cell argument points to the cell under // the mousepointer if there is one. Graph__log("addSidebarElementIcon") var funct = function(graph, evt, cell, x, y) { var nameContainer = Model__ElementCreate(); Graph__ElementCreate(graph, nameContainer, x, y); } const Graph__NetworkElementImage = 'assets/docker_image_icons/host.png'; // Creates the image which is used as the sidebar icon (drag source) var img = document.createElement('img'); img.setAttribute('src', Graph__NetworkElementImage); // img.style.width = '48px'; // img.style.height = '48px'; img.title = 'Drag this to the diagram to create a new vertex'; var ele = document.createElement('div'); ele.innerHTML = "Host"; var dragContainer = document.createElement('div'); dragContainer.className = "row sidebar-element"; // dragContainer.style.marginLeft = "40px"; // CLass settings img.classList.add("col-sm-4") ele.classList.add("col-sm-8") ele.classList.add("sidebar-inner") dragContainer.appendChild(img); dragContainer.appendChild(ele); sidebar.appendChild(dragContainer); sidebar.appendChild(document.createElement("hr")) // sidebar.appendChild(img); // sidebar.appendChild(ele); var dragElt = document.createElement('div'); dragElt.style.border = 'dashed black 1px'; dragElt.style.width = '120px'; dragElt.style.height = '120px'; // Creates the image which is used as the drag icon (preview) var ds = mxUtils.makeDraggable(img, graph, funct, dragElt, 0, 0, true, true); ds.setGuidesEnabled(true); }
function addSidebarElementIcon(graph, sidebar) { // Function that is executed when the image is dropped on // the graph. The cell argument points to the cell under // the mousepointer if there is one. Graph__log("addSidebarElementIcon") var funct = function(graph, evt, cell, x, y) { var nameContainer = Model__ElementCreate(); Graph__ElementCreate(graph, nameContainer, x, y); } const Graph__NetworkElementImage = 'assets/docker_image_icons/host.png'; // Creates the image which is used as the sidebar icon (drag source) var img = document.createElement('img'); img.setAttribute('src', Graph__NetworkElementImage); // img.style.width = '48px'; // img.style.height = '48px'; img.title = 'Drag this to the diagram to create a new vertex'; var ele = document.createElement('div'); ele.innerHTML = "Host"; var dragContainer = document.createElement('div'); dragContainer.className = "row sidebar-element"; // dragContainer.style.marginLeft = "40px"; // CLass settings img.classList.add("col-sm-4") ele.classList.add("col-sm-8") ele.classList.add("sidebar-inner") dragContainer.appendChild(img); dragContainer.appendChild(ele); sidebar.appendChild(dragContainer); sidebar.appendChild(document.createElement("hr")) // sidebar.appendChild(img); // sidebar.appendChild(ele); var dragElt = document.createElement('div'); dragElt.style.border = 'dashed black 1px'; dragElt.style.width = '120px'; dragElt.style.height = '120px'; // Creates the image which is used as the drag icon (preview) var ds = mxUtils.makeDraggable(img, graph, funct, dragElt, 0, 0, true, true); ds.setGuidesEnabled(true); }
JavaScript
function JDCGetNetworks(networkList) { const allNetworks = {}; _.each(networkList, (e) => { const subnetString = `${e.subnet}/24`; allNetworks[e.name] = { ipam: { config: [{ subnet: subnetString }] } }; }); return allNetworks; }
function JDCGetNetworks(networkList) { const allNetworks = {}; _.each(networkList, (e) => { const subnetString = `${e.subnet}/24`; allNetworks[e.name] = { ipam: { config: [{ subnet: subnetString }] } }; }); return allNetworks; }
JavaScript
function JSONDockerComposeConvert(containers, networkList) { // create top level const object = this.JDCTemplate(); const services = this.JDCGetServices(containers); const networks = this.JDCGetNetworks(networkList); object.services = services; object.networks = networks; return JSON.stringify(object); }
function JSONDockerComposeConvert(containers, networkList) { // create top level const object = this.JDCTemplate(); const services = this.JDCGetServices(containers); const networks = this.JDCGetNetworks(networkList); object.services = services; object.networks = networks; return JSON.stringify(object); }
JavaScript
function loadOptionalPorts(ports, selectedImage) { var exposedPorts = selectedImage.exposedPorts; _.each(ports, function(k, v) { // If no port of image (required ports) add to optional ports if(!_.contains(exposedPorts, v) && v != exposedPorts) { $scope.optionalPorts.push({ container:v, host:k }); } }); }
function loadOptionalPorts(ports, selectedImage) { var exposedPorts = selectedImage.exposedPorts; _.each(ports, function(k, v) { // If no port of image (required ports) add to optional ports if(!_.contains(exposedPorts, v) && v != exposedPorts) { $scope.optionalPorts.push({ container:v, host:k }); } }); }
JavaScript
function Graph__update(cell, newName, oldName) { Graph__log("Graph__update()") console.log(cell); console.log(cell.children); var label = cell.value; var $html = $('<div />',{html:label}); if(Model__AppScope) var container = Model__AppScope.getContainer(newName); if (cell.type == NETWORK_ELEMENT_TYPE) { // Get network connectors cell.children.forEach(function (interface) { if (interface.edges) { edge = interface.edges[0]; var networkName = edge.target.id; const network = _.findWhere(edge.parent.children, {id: networkName}); if (container && container.networks) { const containerNetwork = container.networks[network.name]; Graph__setEdgeLabel(theGraph, edge, containerNetwork) } } }) } // replace "Headline" with "whatever" => Doesn't work $html.find('h5').html(newName); // Info setting if (container) { const elementInfo = $html.find("#element_info") var elementVal = "<i><br>" // Port info _.forEach(_.keys(container.ports), function(pk) { pValue = container.ports[pk]; elementVal += pk + "=>" + pValue + "<br>" }) // Volume info _.forEach(container.volumes, function(v) { elementVal += v.host + "=>" + v.container + "<br>" }) // Action info for (var i = 0; i < container.actions.length; i++) { elementVal += "Action (" + i + "): " + container.actions[i].name + "<br>" }; elementVal += "</i>" elementInfo.html(elementVal) } var newValue = $html.html(); theGraph.model.setValue(cell, newValue) if (cell.type === "Network") { console.log("NETWORK TYPE") var network = Model__AppScope.getNetwork(newName); console.log(network.subnet); console.log(network); $html.find('h6').html(network.subnet); newValue = $html.html(); theGraph.model.setValue(cell, newValue) } // Update the cell id cell.setId(newName); var cells = theGraph.model.cells // Rename cell in id graphRenameProperty(cells, oldName, newName); var cellWithOldName = getCellsByName(oldName); _.each(cellWithOldName, function(e) { e.name= newName; }); // cells.remove(oldName); // cells.put(newName, cell); }
function Graph__update(cell, newName, oldName) { Graph__log("Graph__update()") console.log(cell); console.log(cell.children); var label = cell.value; var $html = $('<div />',{html:label}); if(Model__AppScope) var container = Model__AppScope.getContainer(newName); if (cell.type == NETWORK_ELEMENT_TYPE) { // Get network connectors cell.children.forEach(function (interface) { if (interface.edges) { edge = interface.edges[0]; var networkName = edge.target.id; const network = _.findWhere(edge.parent.children, {id: networkName}); if (container && container.networks) { const containerNetwork = container.networks[network.name]; Graph__setEdgeLabel(theGraph, edge, containerNetwork) } } }) } // replace "Headline" with "whatever" => Doesn't work $html.find('h5').html(newName); // Info setting if (container) { const elementInfo = $html.find("#element_info") var elementVal = "<i><br>" // Port info _.forEach(_.keys(container.ports), function(pk) { pValue = container.ports[pk]; elementVal += pk + "=>" + pValue + "<br>" }) // Volume info _.forEach(container.volumes, function(v) { elementVal += v.host + "=>" + v.container + "<br>" }) // Action info for (var i = 0; i < container.actions.length; i++) { elementVal += "Action (" + i + "): " + container.actions[i].name + "<br>" }; elementVal += "</i>" elementInfo.html(elementVal) } var newValue = $html.html(); theGraph.model.setValue(cell, newValue) if (cell.type === "Network") { console.log("NETWORK TYPE") var network = Model__AppScope.getNetwork(newName); console.log(network.subnet); console.log(network); $html.find('h6').html(network.subnet); newValue = $html.html(); theGraph.model.setValue(cell, newValue) } // Update the cell id cell.setId(newName); var cells = theGraph.model.cells // Rename cell in id graphRenameProperty(cells, oldName, newName); var cellWithOldName = getCellsByName(oldName); _.each(cellWithOldName, function(e) { e.name= newName; }); // cells.remove(oldName); // cells.put(newName, cell); }
JavaScript
function fixIntegers(o) { o = JSON.parse(JSON.stringify(o)); for( const k in o ) { if( /^(-|\+)?([0-9]+)$/.test(o[k]) ) { o[k] = parseInt(o[k]); } } return o; }
function fixIntegers(o) { o = JSON.parse(JSON.stringify(o)); for( const k in o ) { if( /^(-|\+)?([0-9]+)$/.test(o[k]) ) { o[k] = parseInt(o[k]); } } return o; }
JavaScript
function throttle(pass_along_value) { return new Promise(function(resolve) { setImmediate(resolve, pass_along_value); }); }
function throttle(pass_along_value) { return new Promise(function(resolve) { setImmediate(resolve, pass_along_value); }); }
JavaScript
function calculateScore(selector) { var score = [0, 0, 0], parts = selector.split(' '), part, match; // TODO: clean the ':not' part since the last ELEMENT_RE will pick it up while (((part = parts.shift()), typeof part == 'string')) { // find all pseudo-elements match = _find(part, PSEUDO_ELEMENTS_RE); score[2] += match; // and remove them match && (part = part.replace(PSEUDO_ELEMENTS_RE, '')); // find all pseudo-classes match = _find(part, PSEUDO_CLASSES_RE); score[1] += match; // and remove them match && (part = part.replace(PSEUDO_CLASSES_RE, '')); // find all attributes match = _find(part, ATTR_RE); score[1] += match; // and remove them match && (part = part.replace(ATTR_RE, '')); // find all IDs match = _find(part, ID_RE); score[0] += match; // and remove them match && (part = part.replace(ID_RE, '')); // find all classes match = _find(part, CLASS_RE); score[1] += match; // and remove them match && (part = part.replace(CLASS_RE, '')); // find all elements score[2] += _find(part, ELEMENT_RE); } return parseInt(score.join(''), 10); }
function calculateScore(selector) { var score = [0, 0, 0], parts = selector.split(' '), part, match; // TODO: clean the ':not' part since the last ELEMENT_RE will pick it up while (((part = parts.shift()), typeof part == 'string')) { // find all pseudo-elements match = _find(part, PSEUDO_ELEMENTS_RE); score[2] += match; // and remove them match && (part = part.replace(PSEUDO_ELEMENTS_RE, '')); // find all pseudo-classes match = _find(part, PSEUDO_CLASSES_RE); score[1] += match; // and remove them match && (part = part.replace(PSEUDO_CLASSES_RE, '')); // find all attributes match = _find(part, ATTR_RE); score[1] += match; // and remove them match && (part = part.replace(ATTR_RE, '')); // find all IDs match = _find(part, ID_RE); score[0] += match; // and remove them match && (part = part.replace(ID_RE, '')); // find all classes match = _find(part, CLASS_RE); score[1] += match; // and remove them match && (part = part.replace(CLASS_RE, '')); // find all elements score[2] += _find(part, ELEMENT_RE); } return parseInt(score.join(''), 10); }
JavaScript
function confirmOnClick(target, document) { return findClosestSiblings( 'input[type="submit"], button[type="submit"', target ); }
function confirmOnClick(target, document) { return findClosestSiblings( 'input[type="submit"], button[type="submit"', target ); }
JavaScript
function ntz(s) { for (const [ zone, replacement ] of zoneMap) { if (zone.test(s)) return s.replace(zone, replacement) } return s }
function ntz(s) { for (const [ zone, replacement ] of zoneMap) { if (zone.test(s)) return s.replace(zone, replacement) } return s }
JavaScript
function $onLoadMore() { var _this2 = this; if (!this.checking && !this.end) { if (this.loadData && typeof this.loadData === 'function') { this.loadData(); } } if (!this.checked) { this.recycleList.setLoadingDisplay('hide'); this.recycleList.setPullLoadEnable(false); } else if (!this.end) { setTimeout(function () { _this2.recycleList.setLoadingDisplay('hide'); _this2.recycleList.setPullLoadEnable(true); _this2.recycleList.resetLoadmore(); }, 400); } }
function $onLoadMore() { var _this2 = this; if (!this.checking && !this.end) { if (this.loadData && typeof this.loadData === 'function') { this.loadData(); } } if (!this.checked) { this.recycleList.setLoadingDisplay('hide'); this.recycleList.setPullLoadEnable(false); } else if (!this.end) { setTimeout(function () { _this2.recycleList.setLoadingDisplay('hide'); _this2.recycleList.setPullLoadEnable(true); _this2.recycleList.resetLoadmore(); }, 400); } }
JavaScript
function finish() { var _this3 = this; if (this.checking) { this.recycleList.getListDataSize(function (res) { var tmp = []; var checkList = []; var checkIndex = []; _this3.checking = false; _this3.recycleList.setPullLoadEnable(true); _this3.recycleList.resetLoadmore(); for (var i = 0; i < res; i++) { _this3.dataSource[i].checking = _this3.checking; _this3.dataSource[i].checked && checkList.push(_this3.dataSource[i]) && checkIndex.push(i); tmp.push(_this3.dataSource[i]); } _this3.dataSource = tmp; _this3.recycleList.setListData(_this3.dataSource); _this3.$emit('fmRcyCheckFinish', { indexs: checkIndex, values: checkList }); _this3.$emit('fmRcyCheckStateChange', false); }); } }
function finish() { var _this3 = this; if (this.checking) { this.recycleList.getListDataSize(function (res) { var tmp = []; var checkList = []; var checkIndex = []; _this3.checking = false; _this3.recycleList.setPullLoadEnable(true); _this3.recycleList.resetLoadmore(); for (var i = 0; i < res; i++) { _this3.dataSource[i].checking = _this3.checking; _this3.dataSource[i].checked && checkList.push(_this3.dataSource[i]) && checkIndex.push(i); tmp.push(_this3.dataSource[i]); } _this3.dataSource = tmp; _this3.recycleList.setListData(_this3.dataSource); _this3.$emit('fmRcyCheckFinish', { indexs: checkIndex, values: checkList }); _this3.$emit('fmRcyCheckStateChange', false); }); } }
JavaScript
function toggleAll(bool) { var _this4 = this; if (this.checking) { var tmp = []; this.recycleList.getListDataSize(function (res) { for (var i = 0; i < res; i++) { _this4.dataSource[i].checked = bool; tmp.push(_this4.dataSource[i]); } _this4.dataSource = tmp; _this4.recycleList.setListData(_this4.dataSource); _this4.$emit('fmRcyCheckValueChange', _this4.dataSource); }); } }
function toggleAll(bool) { var _this4 = this; if (this.checking) { var tmp = []; this.recycleList.getListDataSize(function (res) { for (var i = 0; i < res; i++) { _this4.dataSource[i].checked = bool; tmp.push(_this4.dataSource[i]); } _this4.dataSource = tmp; _this4.recycleList.setListData(_this4.dataSource); _this4.$emit('fmRcyCheckValueChange', _this4.dataSource); }); } }
JavaScript
function removeData(array) { this.dataSource = this.dataSource.filter(function (value, index) { return array.indexOf(index) < 0; }); this.recycleList.removeData(array); this.$emit('fmRcyCheckValueChange', this.dataSource); }
function removeData(array) { this.dataSource = this.dataSource.filter(function (value, index) { return array.indexOf(index) < 0; }); this.recycleList.removeData(array); this.$emit('fmRcyCheckValueChange', this.dataSource); }
JavaScript
function loadingEnd(tipStr) { var _this5 = this; this.end = true; this.$refs.loadText.setAttr('value', tipStr, false); setTimeout(function () { _this5.recycleList.setLoadingDisplay('hide'); _this5.recycleList.setPullLoadEnable(true); _this5.recycleList.resetLoadmore(); }, 400); }
function loadingEnd(tipStr) { var _this5 = this; this.end = true; this.$refs.loadText.setAttr('value', tipStr, false); setTimeout(function () { _this5.recycleList.setLoadingDisplay('hide'); _this5.recycleList.setPullLoadEnable(true); _this5.recycleList.resetLoadmore(); }, 400); }
JavaScript
function resetLoadMore() { this.end = true; this.recycleList.setPullLoadEnable(true); this.recycleList.resetLoadmore(); }
function resetLoadMore() { this.end = true; this.recycleList.setPullLoadEnable(true); this.recycleList.resetLoadmore(); }
JavaScript
function testRunner() { var featureNames; var feature; var aliasIdx; var result; var nameIdx; var featureName; var featureNameSplit; for (var featureIdx in tests) { featureNames = []; feature = tests[featureIdx]; // run the test, throw the return value into the Modernizr, // then based on that boolean, define an appropriate className // and push it into an array of classes we'll join later. // // If there is no name, it's an 'async' test that is run, // but not directly added to the object. That should // be done with a post-run addTest call. if (feature.name) { featureNames.push(feature.name.toLowerCase()); if (feature.options && feature.options.aliases && feature.options.aliases.length) { // Add all the aliases into the names list for (aliasIdx = 0; aliasIdx < feature.options.aliases.length; aliasIdx++) { featureNames.push(feature.options.aliases[aliasIdx].toLowerCase()); } } } // Run the test, or use the raw value if it's not a function result = is(feature.fn, 'function') ? feature.fn() : feature.fn; // Set each of the names on the Modernizr object for (nameIdx = 0; nameIdx < featureNames.length; nameIdx++) { featureName = featureNames[nameIdx]; // Support dot properties as sub tests. We don't do checking to make sure // that the implied parent tests have been added. You must call them in // order (either in the test, or make the parent test a dependency). // // Cap it to TWO to make the logic simple and because who needs that kind of subtesting // hashtag famous last words featureNameSplit = featureName.split('.'); if (featureNameSplit.length === 1) { Modernizr[featureNameSplit[0]] = result; } else { // cast to a Boolean, if not one already /* jshint -W053 */ if (Modernizr[featureNameSplit[0]] && !(Modernizr[featureNameSplit[0]] instanceof Boolean)) { Modernizr[featureNameSplit[0]] = new Boolean(Modernizr[featureNameSplit[0]]); } Modernizr[featureNameSplit[0]][featureNameSplit[1]] = result; } classes.push((result ? '' : 'no-') + featureNameSplit.join('-')); } } }
function testRunner() { var featureNames; var feature; var aliasIdx; var result; var nameIdx; var featureName; var featureNameSplit; for (var featureIdx in tests) { featureNames = []; feature = tests[featureIdx]; // run the test, throw the return value into the Modernizr, // then based on that boolean, define an appropriate className // and push it into an array of classes we'll join later. // // If there is no name, it's an 'async' test that is run, // but not directly added to the object. That should // be done with a post-run addTest call. if (feature.name) { featureNames.push(feature.name.toLowerCase()); if (feature.options && feature.options.aliases && feature.options.aliases.length) { // Add all the aliases into the names list for (aliasIdx = 0; aliasIdx < feature.options.aliases.length; aliasIdx++) { featureNames.push(feature.options.aliases[aliasIdx].toLowerCase()); } } } // Run the test, or use the raw value if it's not a function result = is(feature.fn, 'function') ? feature.fn() : feature.fn; // Set each of the names on the Modernizr object for (nameIdx = 0; nameIdx < featureNames.length; nameIdx++) { featureName = featureNames[nameIdx]; // Support dot properties as sub tests. We don't do checking to make sure // that the implied parent tests have been added. You must call them in // order (either in the test, or make the parent test a dependency). // // Cap it to TWO to make the logic simple and because who needs that kind of subtesting // hashtag famous last words featureNameSplit = featureName.split('.'); if (featureNameSplit.length === 1) { Modernizr[featureNameSplit[0]] = result; } else { // cast to a Boolean, if not one already /* jshint -W053 */ if (Modernizr[featureNameSplit[0]] && !(Modernizr[featureNameSplit[0]] instanceof Boolean)) { Modernizr[featureNameSplit[0]] = new Boolean(Modernizr[featureNameSplit[0]]); } Modernizr[featureNameSplit[0]][featureNameSplit[1]] = result; } classes.push((result ? '' : 'no-') + featureNameSplit.join('-')); } } }
JavaScript
function generatePassword() { var rtn = ""; var currentAlphabet = []; var alphabetItem = 0; alphabetsArr = []; promptUser(); /* While rtn is less than passwordLength, append alphabetsArr[random array][random array item] to rtn */ while (rtn.length < passwordLength) { currentAlphabet = alphabetsArr[Math.floor(Math.random() * alphabetsArr.length)]; alphabetItem = currentAlphabet[Math.floor(Math.random() * currentAlphabet.length)]; rtn += String(alphabetItem); } return rtn; }
function generatePassword() { var rtn = ""; var currentAlphabet = []; var alphabetItem = 0; alphabetsArr = []; promptUser(); /* While rtn is less than passwordLength, append alphabetsArr[random array][random array item] to rtn */ while (rtn.length < passwordLength) { currentAlphabet = alphabetsArr[Math.floor(Math.random() * alphabetsArr.length)]; alphabetItem = currentAlphabet[Math.floor(Math.random() * currentAlphabet.length)]; rtn += String(alphabetItem); } return rtn; }
JavaScript
function promptUser() { passwordLength = prompt( "How many characters would you like your password to consist of?" ); // Prompt password length while ( passwordLength < 8 || passwordLength > 128 || isNaN(parseInt(passwordLength)) ) { passwordLength = prompt( "'" + passwordLength + "' is not a valid input. Please enter an integer in the range [8,250]." ); } // Confirm inclusion of lowercase letters if(confirm( "Would you like your password to include lowercase letters?" )){alphabetsArr.push(lowerLettersArr)} // Confirm inclusion of uppercase letters if(confirm( "Would you like your password to include uppercase letters?" )){alphabetsArr.push(upperLettersArr)} // Confirm inclusion of integers if(confirm( "Would you like your password to include numbers?" )){alphabetsArr.push(digitsArr)} // Confirm inclusion of special characters if(confirm( "Would you like your password to include special characters?" )){alphabetsArr.push(specialCharactersArr)} }
function promptUser() { passwordLength = prompt( "How many characters would you like your password to consist of?" ); // Prompt password length while ( passwordLength < 8 || passwordLength > 128 || isNaN(parseInt(passwordLength)) ) { passwordLength = prompt( "'" + passwordLength + "' is not a valid input. Please enter an integer in the range [8,250]." ); } // Confirm inclusion of lowercase letters if(confirm( "Would you like your password to include lowercase letters?" )){alphabetsArr.push(lowerLettersArr)} // Confirm inclusion of uppercase letters if(confirm( "Would you like your password to include uppercase letters?" )){alphabetsArr.push(upperLettersArr)} // Confirm inclusion of integers if(confirm( "Would you like your password to include numbers?" )){alphabetsArr.push(digitsArr)} // Confirm inclusion of special characters if(confirm( "Would you like your password to include special characters?" )){alphabetsArr.push(specialCharactersArr)} }
JavaScript
writeLength16() { const p1 = this.m16.pop(); const p2 = this.buffer.writeOffset; this.buffer.writeOffset = p1; this.buffer.writeUInt16BE(p2 - p1 - 2); this.buffer.writeOffset = p2; }
writeLength16() { const p1 = this.m16.pop(); const p2 = this.buffer.writeOffset; this.buffer.writeOffset = p1; this.buffer.writeUInt16BE(p2 - p1 - 2); this.buffer.writeOffset = p2; }
JavaScript
writeLength32() { const p1 = this.m32.pop(); const p2 = this.buffer.writeOffset; this.buffer.writeOffset = p1; this.buffer.writeUInt32BE(p2 - p1 - 4); this.buffer.writeOffset = p2; }
writeLength32() { const p1 = this.m32.pop(); const p2 = this.buffer.writeOffset; this.buffer.writeOffset = p1; this.buffer.writeUInt32BE(p2 - p1 - 4); this.buffer.writeOffset = p2; }
JavaScript
function updateSourceCode(sourceCode) { window.document.dispatchEvent(new CustomEvent("ExternalEditorToIDE", { detail: { status: "updateCode", code: sourceCode } })); }
function updateSourceCode(sourceCode) { window.document.dispatchEvent(new CustomEvent("ExternalEditorToIDE", { detail: { status: "updateCode", code: sourceCode } })); }
JavaScript
function sort(repos, quantity = 5) { const sortedData = repos.sort( (b, a) => a.forks + a.stargazers_count - (b.forks + b.stargazers_count) ); const firstFive = sortedData.splice(0, quantity); return firstFive; }
function sort(repos, quantity = 5) { const sortedData = repos.sort( (b, a) => a.forks + a.stargazers_count - (b.forks + b.stargazers_count) ); const firstFive = sortedData.splice(0, quantity); return firstFive; }
JavaScript
function randomGradient() { var hexVars = "0123456789ABCDEF"; color = "#"; for (var i = 0; i < 6; i++) { color += hexVars[Math.floor(Math.random() * 16)]; } console.log(color); return color; }
function randomGradient() { var hexVars = "0123456789ABCDEF"; color = "#"; for (var i = 0; i < 6; i++) { color += hexVars[Math.floor(Math.random() * 16)]; } console.log(color); return color; }
JavaScript
function indexOf(collection, item) { for (var i=0, l=collection.length; i<l; i++) { if (collection[i] === item) { return i; } } return -1; }
function indexOf(collection, item) { for (var i=0, l=collection.length; i<l; i++) { if (collection[i] === item) { return i; } } return -1; }
JavaScript
function supportsTransitions() { var style = document.createElement('div').style; return 'transition' in style || 'WebkitTransition' in style || 'MozTransition' in style || 'msTransition' in style || 'OTransition' in style; }
function supportsTransitions() { var style = document.createElement('div').style; return 'transition' in style || 'WebkitTransition' in style || 'MozTransition' in style || 'msTransition' in style || 'OTransition' in style; }
JavaScript
function supportsFullScreen() { var el = document.createElement('div'); return isFunction(el.requestFullscreen) || isFunction(el.webkitRequestFullscreen) || isFunction(el.webkitRequestFullScreen) || isFunction(el.mozRequestFullScreen) || isFunction(el.msRequestFullscreen); }
function supportsFullScreen() { var el = document.createElement('div'); return isFunction(el.requestFullscreen) || isFunction(el.webkitRequestFullscreen) || isFunction(el.webkitRequestFullScreen) || isFunction(el.mozRequestFullScreen) || isFunction(el.msRequestFullscreen); }
JavaScript
function isFullScreen() { return document.fullscreenElement || document.webkitFullscreenElement || document.webkitCurrentFullScreenElement || document.mozFullScreenElement || document.msFullscreenElement; }
function isFullScreen() { return document.fullscreenElement || document.webkitFullscreenElement || document.webkitCurrentFullScreenElement || document.mozFullScreenElement || document.msFullscreenElement; }
JavaScript
function ratio(image, width, height) { var imageRatio = image.offsetWidth / image.offsetHeight, targetRatio = width / height; if (targetRatio < imageRatio) { height = width / imageRatio; } else { width = height * imageRatio; } return {w:width, h:height}; }
function ratio(image, width, height) { var imageRatio = image.offsetWidth / image.offsetHeight, targetRatio = width / height; if (targetRatio < imageRatio) { height = width / imageRatio; } else { width = height * imageRatio; } return {w:width, h:height}; }
JavaScript
function scale(image, targetWidth, targetHeight) { var size = ratio(image, targetWidth, targetHeight), width = image.offsetWidth, height = image.offsetHeight; targetWidth = size.w; targetHeight = size.h; do { // For down scaling, run multiple passes until the target size is achieved. // For up scaling, this will result in the correct size in one pass. if (width > targetWidth) width /= 2; if (width < targetWidth) width = targetWidth; if (height > targetHeight) height /= 2; if (height < targetHeight) height = targetHeight; } while (width != targetWidth || height != targetHeight); image.style.width = Math.floor(width) + 'px'; image.style.height = Math.floor(height) + 'px'; }
function scale(image, targetWidth, targetHeight) { var size = ratio(image, targetWidth, targetHeight), width = image.offsetWidth, height = image.offsetHeight; targetWidth = size.w; targetHeight = size.h; do { // For down scaling, run multiple passes until the target size is achieved. // For up scaling, this will result in the correct size in one pass. if (width > targetWidth) width /= 2; if (width < targetWidth) width = targetWidth; if (height > targetHeight) height /= 2; if (height < targetHeight) height = targetHeight; } while (width != targetWidth || height != targetHeight); image.style.width = Math.floor(width) + 'px'; image.style.height = Math.floor(height) + 'px'; }
JavaScript
function Cubiq(el) { this.el = el || document.body; this.images = []; this.thumbs = []; this.labels = []; this.support = { fullscreen: supportsFullScreen(), transitions: supportsTransitions() }; this._build(); this._bind(); }
function Cubiq(el) { this.el = el || document.body; this.images = []; this.thumbs = []; this.labels = []; this.support = { fullscreen: supportsFullScreen(), transitions: supportsTransitions() }; this._build(); this._bind(); }
JavaScript
function logMessage(level, filename, message) { var msgLevel; level = level.toUpperCase(); if (level === 'ERROR') { summary.errors++; msgLevel = chalk.red('ERROR:'); } else { summary.warnings++; msgLevel = chalk.yellow('WARNING:'); } gutil.log(msgLevel, chalk.cyan(filename), message); summary.filesWithErrors[filename] = true; }
function logMessage(level, filename, message) { var msgLevel; level = level.toUpperCase(); if (level === 'ERROR') { summary.errors++; msgLevel = chalk.red('ERROR:'); } else { summary.warnings++; msgLevel = chalk.yellow('WARNING:'); } gutil.log(msgLevel, chalk.cyan(filename), message); summary.filesWithErrors[filename] = true; }
JavaScript
function readFile(filename) { return new Promise(function(resolve, reject) { fs.readFile(filename, 'utf8', function(err, data) { summary.files++; if (err) { summary.filesWithErrors++; logError(filename, 'Unable to read file', err); reject(err); return; } resolve(data); }); }); }
function readFile(filename) { return new Promise(function(resolve, reject) { fs.readFile(filename, 'utf8', function(err, data) { summary.files++; if (err) { summary.filesWithErrors++; logError(filename, 'Unable to read file', err); reject(err); return; } resolve(data); }); }); }
JavaScript
function parseYaml(filename) { return new Promise(function(resolve, reject) { readFile(filename) .then(function(fileContents) { try { var parsed = jsYaml.safeLoad(fileContents); resolve(parsed); } catch(ex) { summary.filesWithIssues++; reject(logError(filename, 'Unable to parse YAML', ex)); } }) .catch(function(err) { reject(err); }); }); }
function parseYaml(filename) { return new Promise(function(resolve, reject) { readFile(filename) .then(function(fileContents) { try { var parsed = jsYaml.safeLoad(fileContents); resolve(parsed); } catch(ex) { summary.filesWithIssues++; reject(logError(filename, 'Unable to parse YAML', ex)); } }) .catch(function(err) { reject(err); }); }); }
JavaScript
function readAndValidateContributors() { if (GLOBAL.WF.options.verbose) { gutil.log(' ', 'Validating _contributors.yaml'); } return new Promise(function(resolve, reject) { parseYaml('./src/data/_contributors.yaml') .then(function(contributors) { var errors = 0; var prevFamilyName = ''; Object.keys(contributors).forEach(function(key) { var errMsg; var contributor = contributors[key]; var familyName = contributor.name.family || contributor.name.given; if (prevFamilyName.toLowerCase() > familyName.toLowerCase()) { errMsg = 'Contributors must be sorted by family name. '; errMsg += prevFamilyName + ' came before ' + familyName; logError('_contributors.yaml', errMsg) errors++; } if (contributor.google && typeof contributor.google !== 'string') { errMsg = 'Google+ ID for ' + key + ' must be a string'; logError('_contributors.yaml', errMsg); errors++; } prevFamilyName = familyName; }); contributorList = contributors; resolve(); }); }); }
function readAndValidateContributors() { if (GLOBAL.WF.options.verbose) { gutil.log(' ', 'Validating _contributors.yaml'); } return new Promise(function(resolve, reject) { parseYaml('./src/data/_contributors.yaml') .then(function(contributors) { var errors = 0; var prevFamilyName = ''; Object.keys(contributors).forEach(function(key) { var errMsg; var contributor = contributors[key]; var familyName = contributor.name.family || contributor.name.given; if (prevFamilyName.toLowerCase() > familyName.toLowerCase()) { errMsg = 'Contributors must be sorted by family name. '; errMsg += prevFamilyName + ' came before ' + familyName; logError('_contributors.yaml', errMsg) errors++; } if (contributor.google && typeof contributor.google !== 'string') { errMsg = 'Google+ ID for ' + key + ' must be a string'; logError('_contributors.yaml', errMsg); errors++; } prevFamilyName = familyName; }); contributorList = contributors; resolve(); }); }); }
JavaScript
function testAllYaml() { if (GLOBAL.WF.options.verbose) { gutil.log(' ', 'Validating YAML files...'); } var files = getFilelist('yaml'); return new Promise(function(resolve, reject) { var filesCompleted = 0; var filesRejected = 0; files.forEach(function(filename) { return parseYaml(filename) .catch(function() { filesRejected++; }) .then(function() { if (++filesCompleted === files.length) { resolve(); } }); }); }); }
function testAllYaml() { if (GLOBAL.WF.options.verbose) { gutil.log(' ', 'Validating YAML files...'); } var files = getFilelist('yaml'); return new Promise(function(resolve, reject) { var filesCompleted = 0; var filesRejected = 0; files.forEach(function(filename) { return parseYaml(filename) .catch(function() { filesRejected++; }) .then(function() { if (++filesCompleted === files.length) { resolve(); } }); }); }); }
JavaScript
function findBadMDExtensions() { return new Promise(function(resolve, reject) { var files = getFilelist('markdown', 'mdown'); files.forEach(function(filename) { summary.files++; logError(filename, 'File extension must be .md'); }); resolve(); }); }
function findBadMDExtensions() { return new Promise(function(resolve, reject) { var files = getFilelist('markdown', 'mdown'); files.forEach(function(filename) { summary.files++; logError(filename, 'File extension must be .md'); }); resolve(); }); }
JavaScript
function testAllMarkdown() { return readFile('./src/data/commonTags.json') .then(function(tags) { var files = getFilelist('md'); return new Promise(function(resolve, reject) { var filesCompleted = 0; var filesRejected = 0; files.forEach(function(filename) { return validateMarkdown(filename, tags) .catch(function() { filesRejected++; }) .then(function() { if (++filesCompleted === files.length) { resolve(); } }); }); }); }); }
function testAllMarkdown() { return readFile('./src/data/commonTags.json') .then(function(tags) { var files = getFilelist('md'); return new Promise(function(resolve, reject) { var filesCompleted = 0; var filesRejected = 0; files.forEach(function(filename) { return validateMarkdown(filename, tags) .catch(function() { filesRejected++; }) .then(function() { if (++filesCompleted === files.length) { resolve(); } }); }); }); }); }
JavaScript
function printSummary() { return new Promise(function(resolve, reject) { var filesWithErrors = Object.keys(summary.filesWithErrors).length; gutil.log(''); gutil.log('Test Completed.'); gutil.log('Files checked: ', gutil.colors.blue(summary.files)); gutil.log(' - with issues:', gutil.colors.yellow(filesWithErrors)); gutil.log(' - warnings: ', gutil.colors.yellow(summary.warnings)); gutil.log(' - errors: ', gutil.colors.red(summary.errors)); if (summary.errors === 0) { resolve(); return; } reject(new Error('There were ' + summary.errors + ' errors.')); }); }
function printSummary() { return new Promise(function(resolve, reject) { var filesWithErrors = Object.keys(summary.filesWithErrors).length; gutil.log(''); gutil.log('Test Completed.'); gutil.log('Files checked: ', gutil.colors.blue(summary.files)); gutil.log(' - with issues:', gutil.colors.yellow(filesWithErrors)); gutil.log(' - warnings: ', gutil.colors.yellow(summary.warnings)); gutil.log(' - errors: ', gutil.colors.red(summary.errors)); if (summary.errors === 0) { resolve(); return; } reject(new Error('There were ' + summary.errors + ' errors.')); }); }
JavaScript
function packageHelper(assetsService, treeService, eventsService, $templateCache) { return { /** Called when a package is installed, this resets a bunch of data and ensures the new package assets are loaded in */ packageInstalled: function () { //clears the tree treeService.clearCache(); //clears the template cache $templateCache.removeAll(); //emit event to notify anything else eventsService.emit("app.reInitialize"); } }; }
function packageHelper(assetsService, treeService, eventsService, $templateCache) { return { /** Called when a package is installed, this resets a bunch of data and ensures the new package assets are loaded in */ packageInstalled: function () { //clears the tree treeService.clearCache(); //clears the template cache $templateCache.removeAll(); //emit event to notify anything else eventsService.emit("app.reInitialize"); } }; }
JavaScript
function umbSessionStorage($window) { //gets the sessionStorage object if available, otherwise just uses a normal object // - required for unit tests. var storage = $window['sessionStorage'] ? $window['sessionStorage'] : {}; return { get: function (key) { return angular.fromJson(storage["umb_" + key]); }, set : function(key, value) { storage["umb_" + key] = angular.toJson(value); } }; }
function umbSessionStorage($window) { //gets the sessionStorage object if available, otherwise just uses a normal object // - required for unit tests. var storage = $window['sessionStorage'] ? $window['sessionStorage'] : {}; return { get: function (key) { return angular.fromJson(storage["umb_" + key]); }, set : function(key, value) { storage["umb_" + key] = angular.toJson(value); } }; }
JavaScript
function updateChecker($http, umbRequestHelper) { return { /** * @ngdoc function * @name umbraco.services.updateChecker#check * @methodOf umbraco.services.updateChecker * @function * * @description * Called to load in the legacy tree js which is required on startup if a user is logged in or * after login, but cannot be called until they are authenticated which is why it needs to be lazy loaded. */ check: function() { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "updateCheckApiBaseUrl", "GetCheck")), 'Failed to retrieve update status'); } }; }
function updateChecker($http, umbRequestHelper) { return { /** * @ngdoc function * @name umbraco.services.updateChecker#check * @methodOf umbraco.services.updateChecker * @function * * @description * Called to load in the legacy tree js which is required on startup if a user is logged in or * after login, but cannot be called until they are authenticated which is why it needs to be lazy loaded. */ check: function() { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "updateCheckApiBaseUrl", "GetCheck")), 'Failed to retrieve update status'); } }; }
JavaScript
function templateResource($q, $http, umbRequestHelper) { //the factory object returned return { /** * @ngdoc method * @name umbraco.resources.stylesheetResource#getAll * @methodOf umbraco.resources.stylesheetResource * * @description * Gets all registered stylesheets * * ##usage * <pre> * stylesheetResource.getAll() * .then(function(stylesheets) { * alert('its here!'); * }); * </pre> * * @returns {Promise} resourcePromise object containing the stylesheets. * */ getAll: function () { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "templateApiBaseUrl", "GetAll")), 'Failed to retrieve stylesheets '); }, /** * @ngdoc method * @name umbraco.resources.stylesheetResource#getRulesByName * @methodOf umbraco.resources.stylesheetResource * * @description * Returns all defined child rules for a stylesheet with a given name * * ##usage * <pre> * stylesheetResource.getRulesByName("ie7stylesheet") * .then(function(rules) { * alert('its here!'); * }); * </pre> * * @returns {Promise} resourcePromise object containing the rules. * */ getById: function (id) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "templateApiBaseUrl", "GetById", [{ id: id }])), 'Failed to retreive template '); }, saveAndRender: function(html, templateId, pageId){ return umbRequestHelper.resourcePromise( $http.post( umbRequestHelper.getApiUrl( "templateApiBaseUrl", "PostSaveAndRender"), {templateId: templateId, pageId: pageId, html: html }), 'Failed to retreive template '); } }; }
function templateResource($q, $http, umbRequestHelper) { //the factory object returned return { /** * @ngdoc method * @name umbraco.resources.stylesheetResource#getAll * @methodOf umbraco.resources.stylesheetResource * * @description * Gets all registered stylesheets * * ##usage * <pre> * stylesheetResource.getAll() * .then(function(stylesheets) { * alert('its here!'); * }); * </pre> * * @returns {Promise} resourcePromise object containing the stylesheets. * */ getAll: function () { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "templateApiBaseUrl", "GetAll")), 'Failed to retrieve stylesheets '); }, /** * @ngdoc method * @name umbraco.resources.stylesheetResource#getRulesByName * @methodOf umbraco.resources.stylesheetResource * * @description * Returns all defined child rules for a stylesheet with a given name * * ##usage * <pre> * stylesheetResource.getRulesByName("ie7stylesheet") * .then(function(rules) { * alert('its here!'); * }); * </pre> * * @returns {Promise} resourcePromise object containing the rules. * */ getById: function (id) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "templateApiBaseUrl", "GetById", [{ id: id }])), 'Failed to retreive template '); }, saveAndRender: function(html, templateId, pageId){ return umbRequestHelper.resourcePromise( $http.post( umbRequestHelper.getApiUrl( "templateApiBaseUrl", "PostSaveAndRender"), {templateId: templateId, pageId: pageId, html: html }), 'Failed to retreive template '); } }; }
JavaScript
function noteCount(notes) { var i = 0; for (var name in notes) { i++; } return i; }
function noteCount(notes) { var i = 0; for (var name in notes) { i++; } return i; }
JavaScript
function formatPattern(pattern, params) { params = params || {}; var _compilePattern3 = compilePattern(pattern), tokens = _compilePattern3.tokens; var parenCount = 0, pathname = '', splatIndex = 0, parenHistory = []; var token = void 0, paramName = void 0, paramValue = void 0; for (var i = 0, len = tokens.length; i < len; ++i) { token = tokens[i]; if (token === '*' || token === '**') { paramValue = Array.isArray(params.splat) ? params.splat[splatIndex++] : params.splat; !(paramValue != null || parenCount > 0) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'Missing splat #%s for path "%s"', splatIndex, pattern) : (0, _invariant2.default)(false) : void 0; if (paramValue != null) pathname += encodeURI(paramValue); } else if (token === '(') { parenHistory[parenCount] = ''; parenCount += 1; } else if (token === ')') { var parenText = parenHistory.pop(); parenCount -= 1; if (parenCount) parenHistory[parenCount - 1] += parenText;else pathname += parenText; } else if (token === '\\(') { pathname += '('; } else if (token === '\\)') { pathname += ')'; } else if (token.charAt(0) === ':') { paramName = token.substring(1); paramValue = params[paramName]; !(paramValue != null || parenCount > 0) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'Missing "%s" parameter for path "%s"', paramName, pattern) : (0, _invariant2.default)(false) : void 0; if (paramValue == null) { if (parenCount) { parenHistory[parenCount - 1] = ''; var curTokenIdx = tokens.indexOf(token); var tokensSubset = tokens.slice(curTokenIdx, tokens.length); var nextParenIdx = -1; for (var _i = 0; _i < tokensSubset.length; _i++) { if (tokensSubset[_i] == ')') { nextParenIdx = _i; break; } } !(nextParenIdx > 0) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'Path "%s" is missing end paren at segment "%s"', pattern, tokensSubset.join('')) : (0, _invariant2.default)(false) : void 0; // jump to ending paren i = curTokenIdx + nextParenIdx - 1; } } else if (parenCount) parenHistory[parenCount - 1] += encodeURIComponent(paramValue);else pathname += encodeURIComponent(paramValue); } else { if (parenCount) parenHistory[parenCount - 1] += token;else pathname += token; } } !(parenCount <= 0) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'Path "%s" is missing end paren', pattern) : (0, _invariant2.default)(false) : void 0; return pathname.replace(/\/+/g, '/'); }
function formatPattern(pattern, params) { params = params || {}; var _compilePattern3 = compilePattern(pattern), tokens = _compilePattern3.tokens; var parenCount = 0, pathname = '', splatIndex = 0, parenHistory = []; var token = void 0, paramName = void 0, paramValue = void 0; for (var i = 0, len = tokens.length; i < len; ++i) { token = tokens[i]; if (token === '*' || token === '**') { paramValue = Array.isArray(params.splat) ? params.splat[splatIndex++] : params.splat; !(paramValue != null || parenCount > 0) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'Missing splat #%s for path "%s"', splatIndex, pattern) : (0, _invariant2.default)(false) : void 0; if (paramValue != null) pathname += encodeURI(paramValue); } else if (token === '(') { parenHistory[parenCount] = ''; parenCount += 1; } else if (token === ')') { var parenText = parenHistory.pop(); parenCount -= 1; if (parenCount) parenHistory[parenCount - 1] += parenText;else pathname += parenText; } else if (token === '\\(') { pathname += '('; } else if (token === '\\)') { pathname += ')'; } else if (token.charAt(0) === ':') { paramName = token.substring(1); paramValue = params[paramName]; !(paramValue != null || parenCount > 0) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'Missing "%s" parameter for path "%s"', paramName, pattern) : (0, _invariant2.default)(false) : void 0; if (paramValue == null) { if (parenCount) { parenHistory[parenCount - 1] = ''; var curTokenIdx = tokens.indexOf(token); var tokensSubset = tokens.slice(curTokenIdx, tokens.length); var nextParenIdx = -1; for (var _i = 0; _i < tokensSubset.length; _i++) { if (tokensSubset[_i] == ')') { nextParenIdx = _i; break; } } !(nextParenIdx > 0) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'Path "%s" is missing end paren at segment "%s"', pattern, tokensSubset.join('')) : (0, _invariant2.default)(false) : void 0; // jump to ending paren i = curTokenIdx + nextParenIdx - 1; } } else if (parenCount) parenHistory[parenCount - 1] += encodeURIComponent(paramValue);else pathname += encodeURIComponent(paramValue); } else { if (parenCount) parenHistory[parenCount - 1] += token;else pathname += token; } } !(parenCount <= 0) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'Path "%s" is missing end paren', pattern) : (0, _invariant2.default)(false) : void 0; return pathname.replace(/\/+/g, '/'); }
JavaScript
function listen(listener) { function historyListener(location) { if (state.location === location) { listener(null, state); } else { match(location, function (error, redirectLocation, nextState) { if (error) { listener(error); } else if (redirectLocation) { history.replace(redirectLocation); } else if (nextState) { listener(null, nextState); } else { process.env.NODE_ENV !== 'production' ? (0, _routerWarning2.default)(false, 'Location "%s" did not match any routes', location.pathname + location.search + location.hash) : void 0; } }); } } // TODO: Only use a single history listener. Otherwise we'll end up with // multiple concurrent calls to match. // Set up the history listener first in case the initial match redirects. var unsubscribe = history.listen(historyListener); if (state.location) { // Picking up on a matchContext. listener(null, state); } else { historyListener(history.getCurrentLocation()); } return unsubscribe; }
function listen(listener) { function historyListener(location) { if (state.location === location) { listener(null, state); } else { match(location, function (error, redirectLocation, nextState) { if (error) { listener(error); } else if (redirectLocation) { history.replace(redirectLocation); } else if (nextState) { listener(null, nextState); } else { process.env.NODE_ENV !== 'production' ? (0, _routerWarning2.default)(false, 'Location "%s" did not match any routes', location.pathname + location.search + location.hash) : void 0; } }); } } // TODO: Only use a single history listener. Otherwise we'll end up with // multiple concurrent calls to match. // Set up the history listener first in case the initial match redirects. var unsubscribe = history.listen(historyListener); if (state.location) { // Picking up on a matchContext. listener(null, state); } else { historyListener(history.getCurrentLocation()); } return unsubscribe; }
JavaScript
function match(_ref, callback) { var history = _ref.history, routes = _ref.routes, location = _ref.location, options = _objectWithoutProperties(_ref, ['history', 'routes', 'location']); !(history || location) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'match needs a history or a location') : (0, _invariant2.default)(false) : void 0; history = history ? history : (0, _createMemoryHistory2.default)(options); var transitionManager = (0, _createTransitionManager2.default)(history, (0, _RouteUtils.createRoutes)(routes)); if (location) { // Allow match({ location: '/the/path', ... }) location = history.createLocation(location); } else { location = history.getCurrentLocation(); } transitionManager.match(location, function (error, redirectLocation, nextState) { var renderProps = void 0; if (nextState) { var router = (0, _RouterUtils.createRouterObject)(history, transitionManager, nextState); renderProps = _extends({}, nextState, { router: router, matchContext: { transitionManager: transitionManager, router: router } }); } callback(error, redirectLocation && history.createLocation(redirectLocation, _Actions.REPLACE), renderProps); }); }
function match(_ref, callback) { var history = _ref.history, routes = _ref.routes, location = _ref.location, options = _objectWithoutProperties(_ref, ['history', 'routes', 'location']); !(history || location) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'match needs a history or a location') : (0, _invariant2.default)(false) : void 0; history = history ? history : (0, _createMemoryHistory2.default)(options); var transitionManager = (0, _createTransitionManager2.default)(history, (0, _RouteUtils.createRoutes)(routes)); if (location) { // Allow match({ location: '/the/path', ... }) location = history.createLocation(location); } else { location = history.getCurrentLocation(); } transitionManager.match(location, function (error, redirectLocation, nextState) { var renderProps = void 0; if (nextState) { var router = (0, _RouterUtils.createRouterObject)(history, transitionManager, nextState); renderProps = _extends({}, nextState, { router: router, matchContext: { transitionManager: transitionManager, router: router } }); } callback(error, redirectLocation && history.createLocation(redirectLocation, _Actions.REPLACE), renderProps); }); }
JavaScript
function parseStartTime(url) { var match = url.match(MATCH_START_QUERY); if (match) { var stamp = match[1]; if (stamp.match(MATCH_START_STAMP)) { return parseStartStamp(stamp); } if (MATCH_NUMERIC.test(stamp)) { return parseInt(stamp, 10); } } return 0; }
function parseStartTime(url) { var match = url.match(MATCH_START_QUERY); if (match) { var stamp = match[1]; if (stamp.match(MATCH_START_STAMP)) { return parseStartStamp(stamp); } if (MATCH_NUMERIC.test(stamp)) { return parseInt(stamp, 10); } } return 0; }
JavaScript
static onUpdate(data) { // Split and categorize updated data from blockchain // We flatten it since the updatd data from blockchain is an array of array this.categorizeUpdatedDataFromBlockchain(_.flatten(data)); // Only sync the data every given period if ( !this.syncReduxStoreWithBlockchainTime || new Date().getTime() - this.syncReduxStoreWithBlockchainTime > SYNC_MIN_INTERVAL ) { // Update and delete objects if (!this.updatedObjectsByObjectIdByObjectIdPrefix.isEmpty()) { this.updateObjects(this.updatedObjectsByObjectIdByObjectIdPrefix); } if (!this.deletedObjectIdsByObjectIdPrefix.isEmpty()) { this.deleteObjects(this.deletedObjectIdsByObjectIdPrefix); } // Clear data, after we have sync them this.updatedObjectsByObjectIdByObjectIdPrefix = Immutable.Map(); this.deletedObjectIdsByObjectIdPrefix = Immutable.Map(); // Set new time this.syncReduxStoreWithBlockchainTime = new Date().getTime(); } }
static onUpdate(data) { // Split and categorize updated data from blockchain // We flatten it since the updatd data from blockchain is an array of array this.categorizeUpdatedDataFromBlockchain(_.flatten(data)); // Only sync the data every given period if ( !this.syncReduxStoreWithBlockchainTime || new Date().getTime() - this.syncReduxStoreWithBlockchainTime > SYNC_MIN_INTERVAL ) { // Update and delete objects if (!this.updatedObjectsByObjectIdByObjectIdPrefix.isEmpty()) { this.updateObjects(this.updatedObjectsByObjectIdByObjectIdPrefix); } if (!this.deletedObjectIdsByObjectIdPrefix.isEmpty()) { this.deleteObjects(this.deletedObjectIdsByObjectIdPrefix); } // Clear data, after we have sync them this.updatedObjectsByObjectIdByObjectIdPrefix = Immutable.Map(); this.deletedObjectIdsByObjectIdPrefix = Immutable.Map(); // Set new time this.syncReduxStoreWithBlockchainTime = new Date().getTime(); } }
JavaScript
static categorizeUpdatedDataFromBlockchain(data) { // Parse the data given by blockchain and categorize them _.forEach(data, (object) => { // If updatedObject is object_id instead of an object, it means that object is deleted if (ChainValidation.is_object_id(object)) { const deletedObjectId = object; const objectIdPrefix = getObjectIdPrefix(deletedObjectId); // Add this to the list if it is relevant if (isRelevantObject(objectIdPrefix)) { this.deletedObjectIdsByObjectIdPrefix = this.deletedObjectIdsByObjectIdPrefix.update( objectIdPrefix, (list) => { if (!list) { list = Immutable.List(); } return list.push(deletedObjectId); } ); } } else { const updatedObjectId = object.id; const objectIdPrefix = getObjectIdPrefix(updatedObjectId); // Add this to the list if it is relevant if (isRelevantObject(objectIdPrefix)) { this.updatedObjectsByObjectIdByObjectIdPrefix = this.updatedObjectsByObjectIdByObjectIdPrefix.update( // eslint-disable-line objectIdPrefix, (map) => { // Use map instead of list for more efficient duplicate detection if (!map) { map = Immutable.Map(); } return map.set(updatedObjectId, Immutable.fromJS(object)); } ); } } }); }
static categorizeUpdatedDataFromBlockchain(data) { // Parse the data given by blockchain and categorize them _.forEach(data, (object) => { // If updatedObject is object_id instead of an object, it means that object is deleted if (ChainValidation.is_object_id(object)) { const deletedObjectId = object; const objectIdPrefix = getObjectIdPrefix(deletedObjectId); // Add this to the list if it is relevant if (isRelevantObject(objectIdPrefix)) { this.deletedObjectIdsByObjectIdPrefix = this.deletedObjectIdsByObjectIdPrefix.update( objectIdPrefix, (list) => { if (!list) { list = Immutable.List(); } return list.push(deletedObjectId); } ); } } else { const updatedObjectId = object.id; const objectIdPrefix = getObjectIdPrefix(updatedObjectId); // Add this to the list if it is relevant if (isRelevantObject(objectIdPrefix)) { this.updatedObjectsByObjectIdByObjectIdPrefix = this.updatedObjectsByObjectIdByObjectIdPrefix.update( // eslint-disable-line objectIdPrefix, (map) => { // Use map instead of list for more efficient duplicate detection if (!map) { map = Immutable.Map(); } return map.set(updatedObjectId, Immutable.fromJS(object)); } ); } } }); }
JavaScript
static callBlockchainApi(apiPluginName, methodName, params = []) { let apiPlugin; switch (apiPluginName) { case 'bookie_api': { apiPlugin = Apis.instance().bookie_api(); break; } case 'history_api': { apiPlugin = Apis.instance().history_api(); break; } case 'db_api': { apiPlugin = Apis.instance().db_api(); break; } default: break; } if (apiPlugin) { // If it is get_objects, we want to push the id's into an array. if (methodName === 'get_objects') { let ids = params[0]; // There are cases where an immutable list is passed instead of an array. // This converts it to an array. if (!Array.isArray(ids)) { ids = ids.toJS(); } // Add the ids to the subscriptions array. // this code will create an array of unique ids, that way we don't need to duplicate // the same item if its requested more than once. subscriptions = Array.from(new Set(subscriptions.concat(ids))); } return apiPlugin .exec(methodName, params) .then((result) => { // Intercept and log if ( methodName !== 'get_binned_order_book' && methodName !== 'list_betting_market_groups' && methodName !== 'list_betting_markets' ) { //&& JSON.stringify(params[0]) === "1.20.1688"){ log.debug( `Call blockchain ${apiPluginName}\nMethod: ${methodName}\nParams: ${JSON.stringify( params )}\nResult: `, result ); } return Immutable.fromJS(result); }) .catch((error) => { // Intercept and log log.error( `Error in calling ${apiPluginName}\nMethod: ${methodName}\nParams: ${JSON.stringify( params )}\nError: `, error ); // Return an empty response rather than throwing an error. return Immutable.fromJS({}); }); } else { // If it is not yet connected to blockchain, retry again after 3 seconds return new Promise((resolve) => { setTimeout(() => { resolve(this.callBlockchainApi(apiPluginName, methodName, params)); }, 3000); }); } }
static callBlockchainApi(apiPluginName, methodName, params = []) { let apiPlugin; switch (apiPluginName) { case 'bookie_api': { apiPlugin = Apis.instance().bookie_api(); break; } case 'history_api': { apiPlugin = Apis.instance().history_api(); break; } case 'db_api': { apiPlugin = Apis.instance().db_api(); break; } default: break; } if (apiPlugin) { // If it is get_objects, we want to push the id's into an array. if (methodName === 'get_objects') { let ids = params[0]; // There are cases where an immutable list is passed instead of an array. // This converts it to an array. if (!Array.isArray(ids)) { ids = ids.toJS(); } // Add the ids to the subscriptions array. // this code will create an array of unique ids, that way we don't need to duplicate // the same item if its requested more than once. subscriptions = Array.from(new Set(subscriptions.concat(ids))); } return apiPlugin .exec(methodName, params) .then((result) => { // Intercept and log if ( methodName !== 'get_binned_order_book' && methodName !== 'list_betting_market_groups' && methodName !== 'list_betting_markets' ) { //&& JSON.stringify(params[0]) === "1.20.1688"){ log.debug( `Call blockchain ${apiPluginName}\nMethod: ${methodName}\nParams: ${JSON.stringify( params )}\nResult: `, result ); } return Immutable.fromJS(result); }) .catch((error) => { // Intercept and log log.error( `Error in calling ${apiPluginName}\nMethod: ${methodName}\nParams: ${JSON.stringify( params )}\nError: `, error ); // Return an empty response rather than throwing an error. return Immutable.fromJS({}); }); } else { // If it is not yet connected to blockchain, retry again after 3 seconds return new Promise((resolve) => { setTimeout(() => { resolve(this.callBlockchainApi(apiPluginName, methodName, params)); }, 3000); }); } }
JavaScript
static ping() { // Clear the timeout, this will help prevent zombie timeout loops. if (CommunicationService.PING_TIMEOUT) { CommunicationService.clearPing(); } CommunicationService.PING_TIMEOUT = setTimeout(CommunicationService.ping, Config.pingInterval); CommunicationService.callBlockchainDbApi('get_objects', [['2.1.0']]); }
static ping() { // Clear the timeout, this will help prevent zombie timeout loops. if (CommunicationService.PING_TIMEOUT) { CommunicationService.clearPing(); } CommunicationService.PING_TIMEOUT = setTimeout(CommunicationService.ping, Config.pingInterval); CommunicationService.callBlockchainDbApi('get_objects', [['2.1.0']]); }
JavaScript
static syncWithBlockchain(dispatch, getState, attempt = 3) { // Check if db api is ready let db_api = Apis.instance().db_api(); if (!db_api) { return Promise.reject( new Error('Api not found, please ensure Apis from peerplaysjs-lib.ws is initialized first') ); } // Get current blockchain data (dynamic global property and global property), // to ensure blockchain time is in sync // Also ask for core asset here return this.callBlockchainDbApi('get_objects', [['2.1.0', '2.0.0', Config.coreAsset]]) .then((result) => { const blockchainDynamicGlobalProperty = result.get(0); const blockchainGlobalProperty = result.get(1); const coreAsset = result.get(2); const now = new Date().getTime(); const headTime = blockchainTimeStringToDate( blockchainDynamicGlobalProperty.get('time') ).getTime(); const delta = (now - headTime) / 1000; // Continue only if delta of computer current time and the blockchain time // is less than a minute const isBlockchainTimeDifferenceAcceptable = Math.abs(delta) < 60; // const isBlockchainTimeDifferenceAcceptable = true; if (isBlockchainTimeDifferenceAcceptable) { // Subscribe to blockchain callback so the store is always has the latest data const onUpdate = this.onUpdate.bind(this); return Apis.instance() .db_api() .exec('set_subscribe_callback', [onUpdate, true]) .then(() => { // Sync success log.debug('Sync with Blockchain Success'); // Set reference to dispatch and getState this.dispatch = dispatch; this.getState = getState; // Save dynamic global property dispatch( AppActions.setBlockchainDynamicGlobalPropertyAction(blockchainDynamicGlobalProperty) ); // Save global property dispatch(AppActions.setBlockchainGlobalPropertyAction(blockchainGlobalProperty)); // Save core asset dispatch(AssetActions.addOrUpdateAssetsAction([coreAsset])); // If there are no subscriptions we can return early. if (subscriptions.length <= 0) { return; } // Request all of the objects that are currently stored in the subscriptions array. // This will resubscribe to updates from the BlockChain. this.getObjectsByIds(subscriptions).then((results) => { let resultsByPrefix = Immutable.Map(); results.map((item) => { let id = item.get('id'); // Get the id prefix let prefix = id .split('.') .slice(0, -1) .join('.'); // get the current map let current = resultsByPrefix.get(prefix); // If the item doesn't exist create a new immutable map. if (!current) { current = Immutable.Map(); } // Add the current item to the prefix map. current = current.set(id, item); // Update the resultsByPrefix map with the new or updated mapped objects. resultsByPrefix = resultsByPrefix.set(prefix, current); return item; }); // Call update objects so the application can properly refresh its data. this.updateObjects(resultsByPrefix); }); }); } else { // throw new Error(); throw new Error(I18n.t('connectionErrorModal.outOfSyncClock')); } }) .catch((error) => { log.error('Sync with Blockchain Fail', error); let desyncError = I18n.t('connectionErrorModal.outOfSyncClock'), failToSyncError = I18n.t('connectionErrorModal.failToSync'); // Retry if needed if (attempt > 0) { // Retry to connect log.info('Retry syncing with blockchain'); return CommunicationService.syncWithBlockchain(dispatch, getState, attempt - 1); } else { if (error.message === desyncError) { throw new Error(desyncError); } else { // Give up, throw an error to be caught by the outer promise handler throw new Error(failToSyncError); } } }); }
static syncWithBlockchain(dispatch, getState, attempt = 3) { // Check if db api is ready let db_api = Apis.instance().db_api(); if (!db_api) { return Promise.reject( new Error('Api not found, please ensure Apis from peerplaysjs-lib.ws is initialized first') ); } // Get current blockchain data (dynamic global property and global property), // to ensure blockchain time is in sync // Also ask for core asset here return this.callBlockchainDbApi('get_objects', [['2.1.0', '2.0.0', Config.coreAsset]]) .then((result) => { const blockchainDynamicGlobalProperty = result.get(0); const blockchainGlobalProperty = result.get(1); const coreAsset = result.get(2); const now = new Date().getTime(); const headTime = blockchainTimeStringToDate( blockchainDynamicGlobalProperty.get('time') ).getTime(); const delta = (now - headTime) / 1000; // Continue only if delta of computer current time and the blockchain time // is less than a minute const isBlockchainTimeDifferenceAcceptable = Math.abs(delta) < 60; // const isBlockchainTimeDifferenceAcceptable = true; if (isBlockchainTimeDifferenceAcceptable) { // Subscribe to blockchain callback so the store is always has the latest data const onUpdate = this.onUpdate.bind(this); return Apis.instance() .db_api() .exec('set_subscribe_callback', [onUpdate, true]) .then(() => { // Sync success log.debug('Sync with Blockchain Success'); // Set reference to dispatch and getState this.dispatch = dispatch; this.getState = getState; // Save dynamic global property dispatch( AppActions.setBlockchainDynamicGlobalPropertyAction(blockchainDynamicGlobalProperty) ); // Save global property dispatch(AppActions.setBlockchainGlobalPropertyAction(blockchainGlobalProperty)); // Save core asset dispatch(AssetActions.addOrUpdateAssetsAction([coreAsset])); // If there are no subscriptions we can return early. if (subscriptions.length <= 0) { return; } // Request all of the objects that are currently stored in the subscriptions array. // This will resubscribe to updates from the BlockChain. this.getObjectsByIds(subscriptions).then((results) => { let resultsByPrefix = Immutable.Map(); results.map((item) => { let id = item.get('id'); // Get the id prefix let prefix = id .split('.') .slice(0, -1) .join('.'); // get the current map let current = resultsByPrefix.get(prefix); // If the item doesn't exist create a new immutable map. if (!current) { current = Immutable.Map(); } // Add the current item to the prefix map. current = current.set(id, item); // Update the resultsByPrefix map with the new or updated mapped objects. resultsByPrefix = resultsByPrefix.set(prefix, current); return item; }); // Call update objects so the application can properly refresh its data. this.updateObjects(resultsByPrefix); }); }); } else { // throw new Error(); throw new Error(I18n.t('connectionErrorModal.outOfSyncClock')); } }) .catch((error) => { log.error('Sync with Blockchain Fail', error); let desyncError = I18n.t('connectionErrorModal.outOfSyncClock'), failToSyncError = I18n.t('connectionErrorModal.failToSync'); // Retry if needed if (attempt > 0) { // Retry to connect log.info('Retry syncing with blockchain'); return CommunicationService.syncWithBlockchain(dispatch, getState, attempt - 1); } else { if (error.message === desyncError) { throw new Error(desyncError); } else { // Give up, throw an error to be caught by the outer promise handler throw new Error(failToSyncError); } } }); }
JavaScript
static fetchTransactionHistory( accountId, startTxHistoryId, stopTxHistoryId, limit = Number.MAX_SAFE_INTEGER ) { // Upper limit for getting transaction is 100 const fetchUpperLimit = 100; // If the limit given is higher than upper limit, we need to call the api recursively let adjustedLimit = Math.min(Math.max(limit, 0), fetchUpperLimit); // 1.11.0 denotes the current time const currentTimeTransactionId = ObjectPrefix.OPERATION_HISTORY_PREFIX + '.0'; startTxHistoryId = startTxHistoryId || currentTimeTransactionId; stopTxHistoryId = stopTxHistoryId || currentTimeTransactionId; let result = Immutable.List(); // Note that startTxHistoryId is inclusive but stopTxHistoryId is not return this.callBlockchainHistoryApi('get_account_history', [ accountId, stopTxHistoryId, adjustedLimit, startTxHistoryId ]).then((history) => { // Concat to the result result = result.concat(history); const remainingLimit = limit - adjustedLimit; if (history.size === adjustedLimit && remainingLimit > 0) { // if we still haven't got all the data, do this again recursively // Use the latest transaction id as new startTxHistoryId const newStartTxHistoryId = history.last().get('id'); return this.fetchTransactionHistory( accountId, newStartTxHistoryId, stopTxHistoryId, remainingLimit ).then((nextHistory) => result.concat(nextHistory.shift())); } else { return history; } }); }
static fetchTransactionHistory( accountId, startTxHistoryId, stopTxHistoryId, limit = Number.MAX_SAFE_INTEGER ) { // Upper limit for getting transaction is 100 const fetchUpperLimit = 100; // If the limit given is higher than upper limit, we need to call the api recursively let adjustedLimit = Math.min(Math.max(limit, 0), fetchUpperLimit); // 1.11.0 denotes the current time const currentTimeTransactionId = ObjectPrefix.OPERATION_HISTORY_PREFIX + '.0'; startTxHistoryId = startTxHistoryId || currentTimeTransactionId; stopTxHistoryId = stopTxHistoryId || currentTimeTransactionId; let result = Immutable.List(); // Note that startTxHistoryId is inclusive but stopTxHistoryId is not return this.callBlockchainHistoryApi('get_account_history', [ accountId, stopTxHistoryId, adjustedLimit, startTxHistoryId ]).then((history) => { // Concat to the result result = result.concat(history); const remainingLimit = limit - adjustedLimit; if (history.size === adjustedLimit && remainingLimit > 0) { // if we still haven't got all the data, do this again recursively // Use the latest transaction id as new startTxHistoryId const newStartTxHistoryId = history.last().get('id'); return this.fetchTransactionHistory( accountId, newStartTxHistoryId, stopTxHistoryId, remainingLimit ).then((nextHistory) => result.concat(nextHistory.shift())); } else { return history; } }); }
JavaScript
static fetchRecentHistory(accountId, stopTxHistoryId, limit = Number.MAX_SAFE_INTEGER) { // 1.11.0 denotes the current time const currentTimeTransactionId = ObjectPrefix.OPERATION_HISTORY_PREFIX + '.0'; const startTxHistoryId = currentTimeTransactionId; return this.fetchTransactionHistory(accountId, startTxHistoryId, stopTxHistoryId, limit); }
static fetchRecentHistory(accountId, stopTxHistoryId, limit = Number.MAX_SAFE_INTEGER) { // 1.11.0 denotes the current time const currentTimeTransactionId = ObjectPrefix.OPERATION_HISTORY_PREFIX + '.0'; const startTxHistoryId = currentTimeTransactionId; return this.fetchTransactionHistory(accountId, startTxHistoryId, stopTxHistoryId, limit); }
JavaScript
isWebsocketOpen() { const websocketReadyState = Apis.instance() && Apis.instance().ws_rpc && Apis.instance().ws_rpc.ws && Apis.instance().ws_rpc.ws.readyState; return websocketReadyState === WebSocket.OPEN; }
isWebsocketOpen() { const websocketReadyState = Apis.instance() && Apis.instance().ws_rpc && Apis.instance().ws_rpc.ws && Apis.instance().ws_rpc.ws.readyState; return websocketReadyState === WebSocket.OPEN; }
JavaScript
offlineStatusCallback() { log.info('Disconnected from the internet.'); // Internet is off and websocket is open/ closed this.connectionStatusCallback(ConnectionStatus.DISCONNECTED); this.closeConnectionToBlockchain(); }
offlineStatusCallback() { log.info('Disconnected from the internet.'); // Internet is off and websocket is open/ closed this.connectionStatusCallback(ConnectionStatus.DISCONNECTED); this.closeConnectionToBlockchain(); }
JavaScript
closeConnectionToBlockchain() { // Close connection Apis.close(); // Increment the index for the next connection attempt this.blockchainUrlIndex++; // Reset the index if we've gone past the end. if (this.blockchainUrlIndex >= Config.blockchainUrls.length) { this.blockchainUrlIndex = 0; } // Stop the health check. CommunicationService.clearPing(); }
closeConnectionToBlockchain() { // Close connection Apis.close(); // Increment the index for the next connection attempt this.blockchainUrlIndex++; // Reset the index if we've gone past the end. if (this.blockchainUrlIndex >= Config.blockchainUrls.length) { this.blockchainUrlIndex = 0; } // Stop the health check. CommunicationService.clearPing(); }
JavaScript
connectToBlockchain(connectionStatusCallback) { // Set connection status callback this.connectionStatusCallback = connectionStatusCallback; // Set connection status to be connecting this.connectionStatusCallback(ConnectionStatus.CONNECTING); // Connecting to blockchain const connectionString = Config.blockchainUrls[this.blockchainUrlIndex]; return Apis.instance(connectionString, true) .init_promise.then((res) => { // Print out which blockchain we are connecting to log.debug('Connected to:', res[0] ? res[0].network_name : 'Undefined Blockchain'); }) .catch(() => { // Close residue connection to blockchain this.closeConnectionToBlockchain(); }); }
connectToBlockchain(connectionStatusCallback) { // Set connection status callback this.connectionStatusCallback = connectionStatusCallback; // Set connection status to be connecting this.connectionStatusCallback(ConnectionStatus.CONNECTING); // Connecting to blockchain const connectionString = Config.blockchainUrls[this.blockchainUrlIndex]; return Apis.instance(connectionString, true) .init_promise.then((res) => { // Print out which blockchain we are connecting to log.debug('Connected to:', res[0] ? res[0].network_name : 'Undefined Blockchain'); }) .catch(() => { // Close residue connection to blockchain this.closeConnectionToBlockchain(); }); }
JavaScript
function isArray(verifyArray) { if (verifyArray && Array.isArray(verifyArray)) { return true; } if (process.env.NODE_ENV !== 'test') { // eslint-disable-next-line console.error(`[isArray]: The array being verified is not an array: ${verifyArray}`); } return false; }
function isArray(verifyArray) { if (verifyArray && Array.isArray(verifyArray)) { return true; } if (process.env.NODE_ENV !== 'test') { // eslint-disable-next-line console.error(`[isArray]: The array being verified is not an array: ${verifyArray}`); } return false; }
JavaScript
function isObject(verifyObject) { if (verifyObject && typeof verifyObject === 'object' && verifyObject.constructor === Object) { return true; } if (process.env.NODE_ENV !== 'test') { // eslint-disable-next-line console.error(`[isObject]: The object being verified is not an object: ${verifyObject}`); } return false; }
function isObject(verifyObject) { if (verifyObject && typeof verifyObject === 'object' && verifyObject.constructor === Object) { return true; } if (process.env.NODE_ENV !== 'test') { // eslint-disable-next-line console.error(`[isObject]: The object being verified is not an object: ${verifyObject}`); } return false; }
JavaScript
function startSequencer() { return function (dispatch) { // thunks allow for pre-processing actions, calling apis, and dispatching multiple actions // in this case at this point we could call a service that would persist the fuel savings return dispatch({ type: types.START_SEQUENCER }); }; }
function startSequencer() { return function (dispatch) { // thunks allow for pre-processing actions, calling apis, and dispatching multiple actions // in this case at this point we could call a service that would persist the fuel savings return dispatch({ type: types.START_SEQUENCER }); }; }
JavaScript
function sequencerReducer(state = initialState.sequencer, action) { let currentButtonState, newState = {}; switch (action.type) { case START_SEQUENCER: return state; case STOP_SEQUENCER: return state; case RESET_SEQUENCER: return update(state,{ activeButtons: {$set: getInitialButtonState()} }); case GRID_CONTROLLER_BUTTON_PRESS: currentButtonState = state.activeButtons[action.index]; if (currentButtonState.status === ACTIVE_STATUS) { newState[action.index] = {status: INACTIVE_STATUS}; } else { newState[action.index] = {status: ACTIVE_STATUS}; } return update(state, { activeButtons: {$merge: newState} }); default: return state; } }
function sequencerReducer(state = initialState.sequencer, action) { let currentButtonState, newState = {}; switch (action.type) { case START_SEQUENCER: return state; case STOP_SEQUENCER: return state; case RESET_SEQUENCER: return update(state,{ activeButtons: {$set: getInitialButtonState()} }); case GRID_CONTROLLER_BUTTON_PRESS: currentButtonState = state.activeButtons[action.index]; if (currentButtonState.status === ACTIVE_STATUS) { newState[action.index] = {status: INACTIVE_STATUS}; } else { newState[action.index] = {status: ACTIVE_STATUS}; } return update(state, { activeButtons: {$merge: newState} }); default: return state; } }
JavaScript
function extractComponentOptions (component, parseComponent) { if (typeof (component) !== 'string') { return false } /** @type {ComputedPageOptions | false} */ let componentOptions = { locales: [], paths: {} } let contents try { contents = readFileSync(component).toString() } catch (error) { console.warn(formatMessage(`Couldn't read page component file (${/** @type {Error} */(error).message})`)) } if (!contents) { return componentOptions } const Component = parseComponent(contents) if (!Component.script || Component.script.content.length < 1) { return componentOptions } const script = Component.script.content try { const parsed = parse(script, { sourceType: 'module', plugins: [ 'nullishCoalescingOperator', 'optionalChaining', 'classProperties', 'decorators-legacy', 'dynamicImport', 'estree', 'exportDefaultFrom', 'typescript' ] }) traverse(parsed, { enter (path) { // @ts-ignore if (path.node.type === 'Property') { // @ts-ignore if (path.node.key.name === COMPONENT_OPTIONS_KEY) { // @ts-ignore const data = script.substring(path.node.start, path.node.end) componentOptions = Function(`return ({${data}})`)()[COMPONENT_OPTIONS_KEY] // eslint-disable-line } } } }) } catch (error) { // eslint-disable-next-line no-console console.warn(formatMessage(`Error parsing "${COMPONENT_OPTIONS_KEY}" component option in file "${component}"`)) } return componentOptions }
function extractComponentOptions (component, parseComponent) { if (typeof (component) !== 'string') { return false } /** @type {ComputedPageOptions | false} */ let componentOptions = { locales: [], paths: {} } let contents try { contents = readFileSync(component).toString() } catch (error) { console.warn(formatMessage(`Couldn't read page component file (${/** @type {Error} */(error).message})`)) } if (!contents) { return componentOptions } const Component = parseComponent(contents) if (!Component.script || Component.script.content.length < 1) { return componentOptions } const script = Component.script.content try { const parsed = parse(script, { sourceType: 'module', plugins: [ 'nullishCoalescingOperator', 'optionalChaining', 'classProperties', 'decorators-legacy', 'dynamicImport', 'estree', 'exportDefaultFrom', 'typescript' ] }) traverse(parsed, { enter (path) { // @ts-ignore if (path.node.type === 'Property') { // @ts-ignore if (path.node.key.name === COMPONENT_OPTIONS_KEY) { // @ts-ignore const data = script.substring(path.node.start, path.node.end) componentOptions = Function(`return ({${data}})`)()[COMPONENT_OPTIONS_KEY] // eslint-disable-line } } } }) } catch (error) { // eslint-disable-next-line no-console console.warn(formatMessage(`Error parsing "${COMPONENT_OPTIONS_KEY}" component option in file "${component}"`)) } return componentOptions }
JavaScript
function notice(type, msg, title) { this.refs.toastr[type](msg, title, { mode: 'single', timeOut: 5000, extendedTimeOut: 1000, showAnimation: 'animated bounceIn', hideAnimation: 'animated bounceOut' }); }
function notice(type, msg, title) { this.refs.toastr[type](msg, title, { mode: 'single', timeOut: 5000, extendedTimeOut: 1000, showAnimation: 'animated bounceIn', hideAnimation: 'animated bounceOut' }); }
JavaScript
function baseUnary(func) { return function(value) { return func(value); }; }
function baseUnary(func) { return function(value) { return func(value); }; }
JavaScript
function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; }
function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; }
JavaScript
function update(value, spec) { !(typeof spec === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : _prodInvariant('3', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : void 0; if (hasOwnProperty.call(spec, COMMAND_SET)) { !(Object.keys(spec).length === 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : _prodInvariant('4', COMMAND_SET) : void 0; return spec[COMMAND_SET]; } var nextValue = shallowCopy(value); if (hasOwnProperty.call(spec, COMMAND_MERGE)) { var mergeObj = spec[COMMAND_MERGE]; !(mergeObj && typeof mergeObj === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj) : _prodInvariant('5', COMMAND_MERGE, mergeObj) : void 0; !(nextValue && typeof nextValue === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue) : _prodInvariant('6', COMMAND_MERGE, nextValue) : void 0; _assign(nextValue, spec[COMMAND_MERGE]); } if (hasOwnProperty.call(spec, COMMAND_PUSH)) { invariantArrayCase(value, spec, COMMAND_PUSH); spec[COMMAND_PUSH].forEach(function (item) { nextValue.push(item); }); } if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) { invariantArrayCase(value, spec, COMMAND_UNSHIFT); spec[COMMAND_UNSHIFT].forEach(function (item) { nextValue.unshift(item); }); } if (hasOwnProperty.call(spec, COMMAND_SPLICE)) { !Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : _prodInvariant('7', COMMAND_SPLICE, value) : void 0; !Array.isArray(spec[COMMAND_SPLICE]) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : _prodInvariant('8', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : void 0; spec[COMMAND_SPLICE].forEach(function (args) { !Array.isArray(args) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : _prodInvariant('8', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : void 0; nextValue.splice.apply(nextValue, args); }); } if (hasOwnProperty.call(spec, COMMAND_APPLY)) { !(typeof spec[COMMAND_APPLY] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : _prodInvariant('9', COMMAND_APPLY, spec[COMMAND_APPLY]) : void 0; nextValue = spec[COMMAND_APPLY](nextValue); } for (var k in spec) { if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) { nextValue[k] = update(value[k], spec[k]); } } return nextValue; }
function update(value, spec) { !(typeof spec === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : _prodInvariant('3', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : void 0; if (hasOwnProperty.call(spec, COMMAND_SET)) { !(Object.keys(spec).length === 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : _prodInvariant('4', COMMAND_SET) : void 0; return spec[COMMAND_SET]; } var nextValue = shallowCopy(value); if (hasOwnProperty.call(spec, COMMAND_MERGE)) { var mergeObj = spec[COMMAND_MERGE]; !(mergeObj && typeof mergeObj === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj) : _prodInvariant('5', COMMAND_MERGE, mergeObj) : void 0; !(nextValue && typeof nextValue === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue) : _prodInvariant('6', COMMAND_MERGE, nextValue) : void 0; _assign(nextValue, spec[COMMAND_MERGE]); } if (hasOwnProperty.call(spec, COMMAND_PUSH)) { invariantArrayCase(value, spec, COMMAND_PUSH); spec[COMMAND_PUSH].forEach(function (item) { nextValue.push(item); }); } if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) { invariantArrayCase(value, spec, COMMAND_UNSHIFT); spec[COMMAND_UNSHIFT].forEach(function (item) { nextValue.unshift(item); }); } if (hasOwnProperty.call(spec, COMMAND_SPLICE)) { !Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : _prodInvariant('7', COMMAND_SPLICE, value) : void 0; !Array.isArray(spec[COMMAND_SPLICE]) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : _prodInvariant('8', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : void 0; spec[COMMAND_SPLICE].forEach(function (args) { !Array.isArray(args) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : _prodInvariant('8', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : void 0; nextValue.splice.apply(nextValue, args); }); } if (hasOwnProperty.call(spec, COMMAND_APPLY)) { !(typeof spec[COMMAND_APPLY] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : _prodInvariant('9', COMMAND_APPLY, spec[COMMAND_APPLY]) : void 0; nextValue = spec[COMMAND_APPLY](nextValue); } for (var k in spec) { if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) { nextValue[k] = update(value[k], spec[k]); } } return nextValue; }
JavaScript
function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; }
function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; }
JavaScript
function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (process.env.NODE_ENV !== 'production') { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error); if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } }
function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (process.env.NODE_ENV !== 'production') { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error); if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } }
JavaScript
function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if (process.env.NODE_ENV !== 'production') { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; if (process.env.NODE_ENV !== 'production') { warning( isMixinValid, "%s: You're attempting to include a mixin that is either null " + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec ); } } return; } _invariant( typeof spec !== 'function', "ReactClass: You're attempting to " + 'use a component class or function as a mixin. Instead, just use a ' + 'regular object.' ); _invariant( !isValidElement(spec), "ReactClass: You're attempting to " + 'use a component as a mixin. Instead, just use a regular object.' ); var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. _invariant( isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY'), 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name ); // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === 'DEFINE_MANY_MERGED') { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === 'DEFINE_MANY') { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (process.env.NODE_ENV !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } }
function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if (process.env.NODE_ENV !== 'production') { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; if (process.env.NODE_ENV !== 'production') { warning( isMixinValid, "%s: You're attempting to include a mixin that is either null " + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec ); } } return; } _invariant( typeof spec !== 'function', "ReactClass: You're attempting to " + 'use a component class or function as a mixin. Instead, just use a ' + 'regular object.' ); _invariant( !isValidElement(spec), "ReactClass: You're attempting to " + 'use a component as a mixin. Instead, just use a regular object.' ); var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. _invariant( isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY'), 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name ); // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === 'DEFINE_MANY_MERGED') { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === 'DEFINE_MANY') { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (process.env.NODE_ENV !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } }
JavaScript
function mergeIntoWithNoDuplicateKeys(one, two) { _invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.' ); for (var key in two) { if (two.hasOwnProperty(key)) { _invariant( one[key] === undefined, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key ); one[key] = two[key]; } } return one; }
function mergeIntoWithNoDuplicateKeys(one, two) { _invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.' ); for (var key in two) { if (two.hasOwnProperty(key)) { _invariant( one[key] === undefined, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key ); one[key] = two[key]; } } return one; }