language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class IndexDBHelper { // eslint-disable-line no-unused-vars
/**
* Create the IndexDB database
*/
static openDatabase() {
if (!navigator.serviceWorker) return;
_dbPromise = idb.open(DATABASE, 4, (upgradeDB) => { // eslint-disable-line no-undef
/* eslint-disable */
switch (upgradeDB.oldVersion) {
case 0:
var store = upgradeDB.createObjectStore(RESTAURANTS_OBJECT_STORE, {
keyPath: 'id'
});
store.createIndex('by-date', 'createdAt');
case 1:
upgradeDB.createObjectStore(NEIGHBORHOODS_OBJECT_STORE, {
autoIncrement: true
});
upgradeDB.createObjectStore(CUISINES_OBJECT_STORE, {
autoIncrement: true
});
case 2:
upgradeDB.createObjectStore(REVIEWS_OBJECT_STORE, {
autoIncrement: true
});
case 3:
upgradeDB.createObjectStore(PENDING_REVIEWS_OBJECT_STORE, {
autoIncrement: true
});
}
/* eslint-enable */
});
}
static storeRestaurants(restaurants) {
_dbPromise.then((db) => {
if (!db) return;
const tx = db.transaction(RESTAURANTS_OBJECT_STORE, 'readwrite');
const store = tx.objectStore(RESTAURANTS_OBJECT_STORE);
restaurants.forEach(function(restaurant) {
store.put(restaurant);
});
});
}
static storeCuisines(cuisines) {
_dbPromise.then((db) => {
if (!db) return;
const tx = db.transaction(CUISINES_OBJECT_STORE, 'readwrite');
const store = tx.objectStore(CUISINES_OBJECT_STORE);
cuisines.forEach(function(cuisine) {
store.put(cuisine);
});
});
}
static storeNeighborhoods(neighborhoods) {
_dbPromise.then((db) => {
if (!db) return;
const tx = db.transaction(NEIGHBORHOODS_OBJECT_STORE, 'readwrite');
const store = tx.objectStore(NEIGHBORHOODS_OBJECT_STORE);
neighborhoods.forEach(function(neighborhood) {
store.put(neighborhood);
});
});
}
static storeReviews(reviews) {
_dbPromise.then((db) => {
if (!db) return;
const tx = db.transaction(REVIEWS_OBJECT_STORE, 'readwrite');
const store = tx.objectStore(REVIEWS_OBJECT_STORE);
reviews.forEach(function(review) {
store.put(review);
});
});
}
static storePendingReviews(reviews) {
_dbPromise.then((db) => {
if (!db) return;
const tx = db.transaction(PENDING_REVIEWS_OBJECT_STORE, 'readwrite');
const store = tx.objectStore(PENDING_REVIEWS_OBJECT_STORE);
reviews.forEach(function(review) {
store.put(review);
});
});
}
static showCachedRestaurants() {
return _dbPromise.then(function(db) {
if (!db) return;
var index = db.transaction(RESTAURANTS_OBJECT_STORE)
.objectStore(RESTAURANTS_OBJECT_STORE).index('by-date');
return index.getAll();
});
}
static showCachedCuisines() {
return _dbPromise.then(function(db) {
if (!db) return;
return db.transaction(CUISINES_OBJECT_STORE)
.objectStore(CUISINES_OBJECT_STORE)
.getAll();
});
}
static showCachedNeighborhoods() {
return _dbPromise.then(function(db) {
if (!db) return;
return db.transaction(NEIGHBORHOODS_OBJECT_STORE)
.objectStore(NEIGHBORHOODS_OBJECT_STORE)
.getAll();
});
}
static showCachedReviews() {
return _dbPromise.then(function(db) {
if (!db) return;
return db.transaction(REVIEWS_OBJECT_STORE)
.objectStore(REVIEWS_OBJECT_STORE)
.getAll();
});
}
static getPendingReviews() {
return _dbPromise.then(function(db) {
if (!db) return;
return db.transaction(PENDING_REVIEWS_OBJECT_STORE)
.objectStore(PENDING_REVIEWS_OBJECT_STORE)
.getAll();
});
}
static clearPendingReviews() {
return _dbPromise.then(function(db) {
if (!db) return;
return db.transaction(PENDING_REVIEWS_OBJECT_STORE, 'readwrite')
.objectStore(PENDING_REVIEWS_OBJECT_STORE)
.clear();
});
}
} |
JavaScript | class JestDriver extends core_1.Driver {
bootstrap() {
this.setMetadata({
bin: 'jest',
configName: 'jest.config.js',
dependencies: ['babel'],
description: this.tool.msg('app:jestDescription'),
title: 'Jest',
watchOptions: ['--watch', '--watchAll'],
});
}
// https://github.com/nodejs/node/issues/19218
getSupportedOptions() {
return [
'--all',
'--automock',
'-b',
'--bail',
'--browser',
'-c',
'--cache',
'--cacheDirectory',
'--changedFilesWithAncestor',
'--changedSince',
'--ci',
'--clearCache',
'--clearMocks',
'--collectCoverage',
'--collectCoverageFrom',
'--collectCoverageOnlyFrom',
'--color',
'--colors',
'--config',
'--coverage',
'--coverageDirectory',
'--coveragePathIgnorePatterns',
'--coverageReporters',
'--coverageThreshold',
'--debug',
'--detectLeaks',
'--detectOpenHandles',
'-e',
'--env',
'--errorOnDeprecated',
'--expand',
'-f',
'--filter',
'--findRelatedTests',
'--forceExit',
'--globalSetup',
'--globalTeardown',
'--globals',
'--haste',
'-h',
'--help',
'-i',
'--init',
'--json',
'--lastCommit',
'--listTests',
'--logHeapUsage',
'--mapCoverage',
'--maxWorkers',
'--moduleDirectories',
'--moduleFileExtensions',
'--moduleNameMapper',
'--modulePathIgnorePatterns',
'--modulePaths',
'--no-cache',
'--no-watchman',
'--noStackTrace',
'--notify',
'--notifyMode',
'-o',
'--onlyChanged',
'--onlyFailures',
'--outputFile',
'--passWithNoTests',
'--preset',
'--prettierPath',
'--projects',
'--reporters',
'--resetMocks',
'--resetModules',
'--resolver',
'--restoreMocks',
'--rootDir',
'--roots',
'--runInBand',
'--runner',
'--runTestsByPath',
'--setupFiles',
'--setupFilesAfterEnv',
'--showConfig',
'--silent',
'--skipFilter',
'--snapshotSerializers',
'-t',
'--testEnvironment',
'--testEnvironmentOptions',
'--testFailureExitCode',
'--testLocationInResults',
'--testMatch',
'--testNamePattern',
'--testPathIgnorePatterns',
'--testPathPattern',
'--testRegex',
'--testResultsProcessor',
'--testRunner',
'--testURL',
'--timers',
'--transform',
'--transformIgnorePatterns',
'-u',
'--unmockedModulePathPatterns',
'--updateSnapshot',
'--useStderr',
'-v',
'--verbose',
'--version',
'-w',
'--watch',
'--watchAll',
'--watchPathIgnorePatterns',
'--watchman',
];
}
processSuccess(response) {
const out = response.stdout.trim();
const err = response.stderr.trim();
if (response.command && response.command.includes('--coverage')) {
if (err) {
this.tool.console.log(err);
}
if (out) {
this.tool.console.log(out);
}
}
else if (err) {
this.tool.console.log(err);
}
}
} |
JavaScript | class PasswordField extends TextInput {
getFieldType() {
return 'password';
}
} |
JavaScript | class CookieConfigStorage extends ConfigStorage {
/**
* Trigger config refresh (reload from cookies).
* @private
* @return {undefined}
*/
_loadConfig() {
try {
const result = Cookies.getJSON(this.name);
if (typeof result === 'undefined') {
this._resetConfig();
} else {
this._config = result;
}
} catch (e) {
log.error('ConfigStorage: Error while getting config from cookies');
this._resetConfig();
}
}
/**
* Store in cookies.
* @private
* @return {undefined}
*/
_saveConfig() {
Cookies.set(this.name, this._config, { expires: this.expiryTime });
}
} |
JavaScript | class Programme {
// Programme code
#code;
// Programme name
#name;
// Creates a new instance of type Programme
constructor(code, name) {
this.#code = code;
this.#name = name;
}
// Get code
get code() {
return this.#code;
}
// Set code
set code(value) {
this.#code = value;
}
// Get name
get name() {
return this.#name;
}
// Set name
set name(value) {
this.#name = value;
}
} |
JavaScript | class HeaderComponent extends React.Component {
constructor(){
super();
}
/**
* this function is used to specify which content to show in body
*/
contentChange = ($event) => {
this.props.update($event.target.text)
}
render(){
return( <React.Fragment>
<nav className="navbar navbar-expand-md navbar-light bg-light fixed-top navDiv">
<a className="navbar-brand" to="/">ShredCom</a>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navtarget" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navtarget">
<ul className="navbar-nav mr-auto" onClick={this.contentChange}>
<li className="nav-item">
<a className="nav-link" to="#">{config.CART_ROUTE}</a>
</li>
<li className="nav-item">
<a className="nav-link" to="#">{config.ORDER_ROUTE}</a>
</li>
</ul>
</div>
</nav>
</React.Fragment>
)
}
} |
JavaScript | class DeliveryDPRAction extends Action {
/**
* Create a new DeliveryDPRAction
* @param dprValue
*/
constructor(dprValue) {
super();
this._actionModel = { actionType: 'dpr' };
// toFloatAsString is used to ensure 1 turns into 1.0
const dprAsFloat = toFloatAsString(dprValue);
this._actionModel.dpr = dprAsFloat;
this.addQualifier(new Qualifier('dpr', dprAsFloat));
}
static fromJson(actionModel) {
const { dpr } = actionModel;
// We are using this() to allow inheriting classes to use super.fromJson.apply(this, [actionModel])
// This allows the inheriting classes to determine the class to be created
return new this(dpr);
}
} |
JavaScript | class App extends Template {
constructor() {
super();
}
} |
JavaScript | class Day extends AbstractTemporal {
toDisplayString(value, format) {
return moment(value).format(format || "MM/DD/YYYY")
}
fromStringToNumeric(value) {
return (
DateCol.getDate(value)
.startOf("day")
.unix() * 1000
)
}
getVegaTimeUnit() {
return undefined
}
_fromStringToDate(value) {
return DateCol.getDate(value)
.startOf("day")
.toDate()
}
fromDateToNumeric(date) {
return (
moment(date)
.startOf("day")
.unix() * 1000
)
}
getStringExamples() {
return ["01/01/01"]
}
getProbForColumnSpecimen(sample) {
const format = moment.parseFormat ? moment.parseFormat(sample) : parseFormat
return format === "MM/DD/YY" || format === "MM/DD/YYYY" || format === "M/D/YYYY" ? 1 : 0
}
} |
JavaScript | class RowStringSpecimen {
constructor(str) {
const trimmedStr = str.trim()
const lines = trimmedStr.split(/\n/g)
const firstLine = lines[0]
const strCount = (str, reg) => (str.match(reg) || []).length
// todo: do these things lazily.
this.trimmedStr = trimmedStr
this.lines = lines
this.firstLine = firstLine
this.lineCount = lines.length
this.indentedLineCount = strCount(trimmedStr, /\n /g)
this.blankLineCount = strCount(trimmedStr, /\n\n/g)
this.commaCount = strCount(trimmedStr, /\,/g)
this.tabCount = strCount(trimmedStr, /\t/g)
this.verticalBarCount = strCount(trimmedStr, /\|/g)
this.firstLineCommaCount = strCount(firstLine, /\,/g)
this.firstLineTabCount = strCount(firstLine, /\t/g)
this.firstLineSpaceCount = strCount(firstLine, / /g)
this.firstLineVerticalBarCount = strCount(firstLine, /\|/g)
}
getParsedJsonAttemptResult() {
if (this._parsedJsonObject) return this._parsedJsonObject
try {
this._parsedJsonObject = { ok: true, result: JSON.parse(this.trimmedStr) }
} catch (err) {
this._parsedJsonObject = { ok: false }
}
return this._parsedJsonObject
}
} |
JavaScript | class Root extends Component{
static propTypes = {
history: PropTypes.object.isRequired
}
render() {
const { history } = this.props;
return (
<Router history={history}>
<Route name='/' path='/' component={App}>
</Route>
</Router>
);
}
} |
JavaScript | class WidgetExtensionView extends UIView {
/**
* Creates an instance of WidgetExtensionView.
*
* @param {*} service
*
* @memberof WidgetExtensionView
*/
constructor(service) {
super()
this.service = service
this.element = this.uiGet('#qh_e_frame')
this.isExpanded = false
this.videoMode = false
this.anyOperatorActive = false
}
/**
* Initializes the view.
*
* @memberof WidgetExtensionView
*/
async init() {
this.service.addListener('admin', (adminUser) => {
this.onAdmin(adminUser)
})
this.service.addListener('listUsers', (a) => {
this.anyOperatorActive = !!a.length
this.updateVideoCallUi()
})
this.service.addListener('callAccepted', (e) => {
this.onCallAccepted(e)
})
this.service.addListener('callRejected', () => {
this.onCallRejected()
})
this.service.addListener('videochatSessionClose', () => {
this.onHangUpVideoChat()
})
const rateButtons = this.uiArray('.qh_rate-star')
rateButtons.forEach((rateButton, index) => {
rateButton.addEventListener('click', () => {
for (let a = 1; a <= rateButtons.length; a++) {
const button = this.uiGet(`.qh_rate-star:nth-child(${a})`)
button.classList.remove('js-enabled,js-disabled')
if (a <= index + 1) {
button.classList.add('js-enabled')
button.classList.remove('js-disabled')
} else {
button.classList.remove('js-enabled')
button.classList.add('js-disabled')
}
}
this.service.rateComSession(index + 1)
})
})
this.initContactForm()
}
/**
* Initializes contact form.
*
* @memberof WidgetExtensionView
*/
initContactForm() {
const sendButtonClassName = '.widget-extension__button--send'
if (this.uiExists(sendButtonClassName)) {
HTMLUtils.removeAllEventListeners(sendButtonClassName)
const submitButtonElement = this.uiGet(sendButtonClassName)
submitButtonElement.addEventListener('click', () => {
this.sendContactForm()
})
}
this.initInactiveOperatorCloser()
}
/**
* Initializes active operator init form.
*/
initStartVideoChatForm() {
const startVideoButtonClassName = '.widget-extension__button--video-call'
if (this.uiExists(startVideoButtonClassName)) {
HTMLUtils.removeAllEventListeners(startVideoButtonClassName)
const submitButtonElement = this.uiGet(startVideoButtonClassName)
submitButtonElement.addEventListener('click', () =>
this.sendStartVideoChatForm()
)
}
this.initActiveOperatorFormCloser()
}
/**
* Initializes closer button.
*
* @memberof WidgetExtensionView
*/
initActiveOperatorFormCloser() {
const activeOperatorFormCloserClass =
'.qh_widget-closer--active-operator-form'
if (this.uiExists(activeOperatorFormCloserClass)) {
HTMLUtils.removeAllEventListeners(activeOperatorFormCloserClass)
const collapseViewButtonElement = this.uiGet(
activeOperatorFormCloserClass
)
collapseViewButtonElement.addEventListener('click', () => {
this.collapseAndReinitActiveOperatorInitForm(false)
})
}
}
/**
* Initializes rate UX closer.
*/
initRateUXCloser() {
const rateUXCloserClass = '.qh_widget-closer--rate-ux'
if (this.uiExists(rateUXCloserClass)) {
HTMLUtils.removeAllEventListeners(rateUXCloserClass)
const collapseViewButtonElement = this.uiGet(rateUXCloserClass)
collapseViewButtonElement.addEventListener('click', () => {
this.collapseAndReinitActiveOperatorInitForm()
})
}
}
/**
* Intializes await video call closer.
*/
initAwaitVideoCallCloser() {
const awaitVideoCallCloserClass = '.qh_widget-closer--await-video-call'
if (this.uiExists(awaitVideoCallCloserClass)) {
HTMLUtils.removeAllEventListeners(awaitVideoCallCloserClass)
const awaitVideoCallCloserElement = this.uiGet(awaitVideoCallCloserClass)
awaitVideoCallCloserElement.addEventListener('click', () => {
this.cancelCall()
})
}
}
/**
* Intializes video closer.
*/
initVideoCloser() {
const videoCloserClass = '.qh_widget-closer--video'
if (this.uiExists(videoCloserClass)) {
HTMLUtils.removeAllEventListeners(videoCloserClass)
const videoCloserElement = this.uiGet(videoCloserClass)
videoCloserElement.addEventListener('click', () => {
this.onHangUpVideoChat()
})
}
}
/**
* Initializes inactive operator form closer.
*
* @memberof WidgetExtensionView
*/
initInactiveOperatorCloser() {
if (this.uiExists('.qh_widget-closer--inactive-operator')) {
HTMLUtils.removeAllEventListeners('.qh_widget-closer--inactive-operator')
const collapseViewButtonElement = this.uiGet(
'.qh_widget-closer--inactive-operator'
)
collapseViewButtonElement.addEventListener('click', () => {
this.collapseAndReinitInactiveOperatorInitForm()
})
}
}
/**
* Collapses view and reinits active operator form.
*
* @param {*} forceDestroyVideoChat
*
* @memberof WidgetExtensionView
*/
collapseAndReinitActiveOperatorInitForm(forceDestroyVideoChat = true) {
this.deactivateVideoMode()
this.service.getActiveOperatorInitForm().then((html) => {
document.querySelector('.qh_video-ui_replace').innerHTML = html
this.activateActiveOperatorInitForm()
this.collapseView()
if (forceDestroyVideoChat) {
this.service.destroyVideoChatApp()
}
})
}
/**
* Collapses view and reinits inactive operator form.
*
* @memberof WidgetExtensionView
*/
collapseAndReinitInactiveOperatorInitForm() {
this.service.getInactiveOperatorInitForm().then((html) => {
document.querySelector('.contact-form').innerHTML = html
this.initContactForm()
this.collapseView()
})
}
/**
* Sends contact form.
*
* @memberof WidgetExtensionView
*/
sendContactForm() {
const fieldSet = {
name: document.querySelector('.qh_module--inactive-form input[name=name]')
.value,
email_or_phone: document.querySelector(
'.qh_module--inactive-form input[name=email_or_phone]'
).value,
message: document.querySelector('textarea[name=message]').value,
}
this.service
.sendContactForm(fieldSet)
.then((response) => {
document.querySelector('.contact-form').innerHTML = response
this.initContactForm()
})
.catch((reason) => {
console.log('reason', reason)
})
}
/**
* Sends start video chat form.
*/
sendStartVideoChatForm() {
const fieldSet = {
name: document.querySelector('.qh_active-user-form__input[name=name]')
.value,
email_or_phone: document.querySelector(
'.qh_active-user-form__input[name=email_or_phone]'
).value,
}
this.service
.sendStartVideoChatForm(fieldSet)
.then((response) => {
document.querySelector('.qh_video-ui_replace').innerHTML = response
const resultElement = this.uiGet('.qh_com-status')
const status = resultElement.dataset.status
const userId = resultElement.dataset.userid
this.service.setUserId(userId)
if (status === 'ok') {
this.requestCall()
this.initAwaitVideoCallCloser()
} else {
this.initStartVideoChatForm()
}
})
.catch((reason) => {
console.log('reason', reason)
})
}
/**
* Handles admin user.
*
* @param {object} adminUser
*/
onAdmin(adminUser) {
this.adminUser = adminUser
const adminNameElement = this.uiGet('.active-user__admin-name')
const firstName = adminUser.full_name.split(' ')[0]
adminNameElement.innerHTML = firstName
}
setThumbnails(thumbnailPath) {
const adminThumbnailElements = this.uiArray('.active-user-form__thumbnail')
adminThumbnailElements.forEach((adminThumbnailElement) => {
adminThumbnailElement.style.backgroundImage = `url(${this.service.consoleAppUrl}/media/${thumbnailPath})`
})
}
/**
* Toggles the view.
*
* @memberof WidgetExtensionView
*/
toggleView() {
if (this.isExpanded) {
this.collapseView()
} else {
this.expandView()
}
}
/**
* Expands the view.
*
* @memberof WidgetExtensionView
*/
expandView() {
this.isExpanded = true
this.element.classList.add('js-expanded')
}
/**
* Collapses the view.
*
* @memberof WidgetExtensionView
*/
collapseView() {
this.isExpanded = false
this.element.classList.remove('js-expanded')
this.deactivateVideoMode()
}
/**
* Enables video call UI when number if any admin is active.
*
* @param {boolean} anyOperatorActive
* @memberof WidgetExtensionView
*/
updateVideoCallUi() {
const activeOperatorElement = this.uiGet('.qh_module--active-operator')
activeOperatorElement.classList.toggle('js-enabled', this.anyOperatorActive)
const inactiveOperatorForm = this.uiGet('.qh_module--inactive-form')
inactiveOperatorForm.classList.toggle('js-enabled', !this.anyOperatorActive)
if (!this.anyOperatorActive) {
this.activateCallDefaultStage()
} else if (!this.videoMode) {
this.activateActiveOperatorInitForm()
this.emit('collapse')
}
}
/**
* Requests a call.
*
* @memberof WidgetExtensionView
*/
requestCall() {
this.service.requestCall()
}
/**
* Cancels a call.
*
* @memberof WidgetExtensionView
*/
cancelCall() {
this.service.cancelCall()
if (!this.anyOperatorActive) {
this.activateCallDefaultStage()
} else if (!this.videoMode) {
this.collapseAndReinitActiveOperatorInitForm(false)
}
}
/**
* Handles call accepted event.
*
* @param {string} url
* @memberof WidgetExtensionView
*/
onCallAccepted(roomId) {
const urlElement = this.uiGet('meta[name=room_id]')
urlElement.setAttribute('content', roomId)
this.activateVideoChat()
}
deleteRoomId() {
const urlElement = this.uiGet('meta[name=room_id]')
urlElement.setAttribute('content', '')
}
/**
* Handles call rejected event.
*
* @memberof WidgetExtensionView
*/
onCallRejected() {
this.activateCallRejectedStage()
}
activateCallRejectedStage() {
const line1Element = this.uiGet('.qh_video-ui_awating--line1')
line1Element.classList.add('qh_tight')
line1Element.innerHTML = 'Sorry, all of our operators are busy, we will email you shortly!'
const line2Element = this.uiGet('.qh_video-ui_awating--line2')
line2Element.remove()
}
/**
* Activates default video UI stage.
*
* @memberof WidgetExtensionView
*/
activateCallDefaultStage() {
this.deactivateAllStages()
const stageElement = this.uiGet('.qh_module--inactive-form')
stageElement.classList.add('js-enabled')
this.deactivateVideoMode()
}
/**
* Activates video call request UI stage.
*
* @memberof WidgetExtensionView
*/
activateActiveOperatorInitForm() {
this.deactivateAllStages()
const stageElement = this.uiGet('.qh_submodule--init-form')
stageElement.classList.add('js-enabled')
this.initStartVideoChatForm()
}
/**
* Activates the rate UX form submdule.
*
* @memberof WidgetExtensionView
*/
activateRateUxForm() {
this.deactivateAllStages()
const stageElement = this.uiGet('.qh_submodule--rate-ux')
stageElement.classList.add('js-enabled')
this.initRateUXCloser()
}
/**
* Activates video chat.
*
* @memberof WidgetExtensionView
*/
activateVideoChat() {
this.deactivateAllStages()
const stageElement = this.uiGet('.qh_submodule--video-chat')
stageElement.classList.add('js-enabled')
this.activateVideoMode()
const joinButton = this.uiGet('.confirm-join-button')
joinButton.addEventListener('click', () => {
this.onJoinVideoChat()
})
const hangupButton = this.uiGet('.button--hangup')
hangupButton.addEventListener('click', () => {
this.onHangUpVideoChat()
})
this.initVideoCloser()
}
onJoinVideoChat() {}
/**
* Handles call close.
*/
onHangUpVideoChat() {
this.activateRateUxForm()
this.activateVideoMode()
this.deleteRoomId()
}
/**
* Deactivates all submodules.
*
* @memberof WidgetExtensionView
*/
deactivateAllStages() {
const stageElements = this.uiArray('.qh_submodule')
stageElements.forEach((stageElement) => {
stageElement.classList.remove('js-enabled')
})
this.deactivateVideoMode()
}
/**
* Activates video mode.
*
* @memberof WidgetExtensionView
*/
activateVideoMode() {
this.element.classList.add('qh_video-mode')
this.videoMode = true
}
/**
* Deactivates video mode.
*
* @memberof WidgetExtensionView
*/
deactivateVideoMode() {
this.element.classList.remove('qh_video-mode')
this.videoMode = false
// remove connection data from videochat app
}
} |
JavaScript | class MetricsService {
/**Log event */
static fetchIothubMetrics(id, payload = null) {
return HttpClient.post(
`${ENDPOINT}simulations/${id}/metrics/iothub!search`,
payload,
true
)
.map(toIothubMetricsModel)
.catch(error => Observable.throw(error));
}
} |
JavaScript | class C extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
renderVueComponent() {
const props = this.props;
const slot = props.slot; // vue slot
let vueComponent = this.vueComponent;
if (!vueComponent) {
const el = this.v;
const {
innerTag = 'div',
innerClass = ''
} = getNormalizeProps(props);
vueComponent = new Vue({
el,
data: {
slot
},
render(h) {
return h(innerTag, {
class: getNormalizeClass(innerClass)
}, this.slot);
}
});
this.vueComponent = vueComponent;
} else {
vueComponent.slot = slot;
}
}
componentDidMount() {
this.renderVueComponent();
}
// componentWillReceiveProps() {
// }
// shouldComponentUpdate() {
// return true;
// }
componentDidUpdate() {
this.renderVueComponent();
}
componentWillUnmount() {
if (this.vueComponent) {
this.vueComponent.$destroy();
this.vueComponent = null;
}
}
render() {
const props = this.props;
const {
innerTag = 'div',
innerClass = ''
} = getNormalizeProps(props);
return React.createElement(innerTag, {
ref: (el) => {
this.v = el;
},
className: getNormalizeClass(innerClass, 'react')
}, null);
}
} |
JavaScript | class XpCommand extends Command {
constructor () {
super('xp', {
aliases: ['xp'],
cooldown: 60000,
channelRestriction: 'guild',
args: [{
id: 'member',
type: 'member',
default: msg => msg.member
}],
ratelimit: 2
});
}
exec (message, { member }) {
// Get DB xp info
const userId = `u${member.id}`;
const xp = this.client.enmap.get('xp', userId, 0);
const xpAll = this.client.enmap.getAll('xp');
// Sort the xp ascending and get the last ten
const top = Object.keys(xpAll).filter((id) => {
if (message.guild.members.has(id.slice(1))) {
return xpAll[id] > xp;
} else {
// Skip users not in this server
return false;
}
});
return message.channel.send(this.client.util.embed()
.setAuthor(member.user.username)
.setThumbnail(member.user.avatarURL)
.setColor(member.displayHexColor)
.setDescription(`\`\`\`yaml\nXP: ${xp}\nRank: ${top.length + 1}\`\`\``));
}
} |
JavaScript | class GlobalObject {
constructor() {
this.actions = [];
this.types = types;
this.state = {};
}
/**
* Creates a new action for Global to execute
* @name Global.addAction
* @param {Function} exp the expression the user wants executed after the draw loop.
* @returns {Action} the new Action just added to the Global.actions list
*/
addAction(exp) {
const action = new Action(exp, this);
this.actions.push(action);
return action;
}
/**
* executes all actions in the Global.actions list
* and then clears the list
* @name Global.exeActions
*/
exeActions() {
this.actions.map((a) => a.exe());
this.clearActions();
}
clearActions() {
this.actions.length = 0;
}
} |
JavaScript | class CornerCaseHandler extends React.Component {
constructor(props) {
super(props)
this.state = {
alreadyFetched: false,
g: props.g,
currId: props.currId,
nextId: props.nextId
}
}
componentDidMount() {
if (this.state.alreadyFetched) {
return
}
this.setState({
alreadyFetched: true
})
const g = this.state.g
const lastFetchedPage = "page" + (g.cursor-1)
if (!g[lastFetchedPage]) {
/* Another corner case: user enters postcard view without visiting gallery.
* Note that we are not properly handling this case (we should fetch enough
* metadata up to whichever image the user is looking at - instead we only
* fetch 1 page worth of metadata items per each photo that the user views.) */
g.loadMore()
return
}
const p = g[lastFetchedPage]
if (p.length === 0) {
/* This shouldn't happen but if it does we don't want to crash. */
return
}
if (p[p.length-1].id < (this.state.nextId)) {
/* If we are almost at the last photo with thumbnail metadata,
* then fetch more metadata (thumbnail _data_ will not be fetched yet). */
g.loadMore()
}
}
render() {
return (
<></>
)
}
} |
JavaScript | class QRService extends FactorService {
/**
* Initiate a QR login verification.
* @param {string} profileId The identifier of an IBM Verify registration
* profile.
* @return {Promise<Object>} The QR code login verification.
*/
async generate(profileId) {
const response = await this.get('/v2.0/factors/qr/authenticate',
{profileId});
return response.data;
}
/**
* Complete a QR login verification.
* @param {string} verificationId The identifier of the QR login verification
* received in {@link QRService#generate}.
* @param {string} dsi The DSI of the QR login verification received in
* {@link QRService#generate}.
* @return {Promise<string>} The HTTP response body of the request.
*/
async verify(verificationId, dsi) {
const response = await this.get(
`/v2.0/factors/qr/authenticate/${verificationId}`,
{dsi: dsi, returnJwt: true});
return response.data;
}
} |
JavaScript | class BasicLayout extends React.PureComponent {
constructor(props){
super(props)
this.state = props;
this.columns = [{
title: 'id',
dataIndex: 'id',
key: 'id',
width:"100px",
render:(text, record)=>{
return <a onClick={() => {
ipcRenderer.send('show-png', record);
}}>{text}</a>;
}
}, {
title: 'desc',
dataIndex: 'desc',
key: 'desc',
},{
title: 'assigned',
dataIndex: 'assigned',
key: 'assigned',
}, {
title: 'reporter',
dataIndex: 'reporter',
key: 'reporter',
}, {
title: 'cc',
dataIndex: 'cc',
key: 'cc',
width:"120px"
},{
title: 'platform',
dataIndex: 'platform',
key: 'platform',
width:"120px"
},{
title: 'sys',
dataIndex: 'sys',
key: 'sys',
width:"120px"
}];
}
handleSubmit = (e)=>{
e.preventDefault();
this.props.form.validateFields((err, values) => {
ipcRenderer.send('click', values)
})
}
render() {
const {getFieldDecorator} = this.state.form
if(!this.state.bug){
ipcRenderer.send('bug-data', null);
ipcRenderer.on('bug-data', (event, arg)=>{
console.log(arg)
this.setState({bug:arg})
})
}
return (
<Layout>
<Content>
<Form layout="inline" onSubmit={this.handleSubmit}>
<FormItem>
{getFieldDecorator('id', {})(
<Input placeholder="请输入BUG id" prefix={<Icon type="search" style={{ color: 'rgba(0,0,0,.25)' }} />} />
)}
</FormItem>
<FormItem>
<Button
type="primary"
htmlType="submit"
>
+ Search
</Button>
</FormItem>
</Form>
<Table columns={this.columns} pagination={true} dataSource={this.state.bug} />
</Content>
</Layout>
);
}
} |
JavaScript | class ServiceValueResolver extends implementationOf(ArgumentValueResolverInterface) {
/**
* Constructor.
*
* @param {Jymfony.Component.DependencyInjection.ContainerInterface} container
*/
__construct(container) {
/**
* @type {Jymfony.Component.DependencyInjection.ContainerInterface}
*
* @private
*/
this._container = container;
}
/**
* @inheritdoc
*/
supports(request, argument) {
let controller = request.attributes.get('_controller');
if (isCallableArray(controller)) {
controller = ReflectionClass.getClassName(controller[0]) + ':' + controller[1];
} else if (! isString(controller) || '' === controller) {
return false;
}
const i = controller.lastIndexOf(':');
if (! this._container.has(controller) && -1 !== i) {
controller = controller.substr(0, i) + controller.substr(i).toLowerCase();
}
return this._container.has(controller) && this._container.get(controller).has(argument.name);
}
/**
* @inheritdoc
*/
* resolve(request, argument) {
let controller = request.attributes.get('_controller');
if (isCallableArray(controller)) {
controller = ReflectionClass.getClassName(controller[0]) + ':' + controller[1];
}
if (! this._container.has(controller)) {
const i = controller.lastIndexOf(':');
controller = controller.substr(0, i) + controller.substr(i).toLowerCase();
}
try {
yield this._container.get(controller).get(argument.name);
} catch (e) {
const what = __jymfony.sprintf('argument %s of "%s()"', argument.name, controller);
let message = e.message.replace(/service "\.service_locator\.[^"]+"/g, what);
if (e.message === message) {
message = __jymfony.sprintf('Cannot resolve %s: %s', what, message);
}
e.message = message;
throw e;
}
}
} |
JavaScript | class Enum extends Array {
constructor(...args) {
super(...args)
for (const k of args) {
this[k] = k
}
}
} |
JavaScript | class TopWords extends React.PureComponent {
/**
* Rendering the chart card.
*
* @return {jsx} the component to be rendered.
*/
render() {
let iteration = this.props.dreamingElement.iteration ?
this.props.dreamingElement.iteration : 0;
iteration = iteration < this.props.dreamingElement.iterations.length ?
iteration : this.props.dreamingElement.iterations.length - 1;
const headParams = {
'LayerID': this.props.dreamingElement.params.layer_id,
'WordID': this.props.dreamingElement.params.word_id,
'NeuronID': this.props.dreamingElement.params.neuron_id,
'Activation': this.props.dreamingElement.iterations[
iteration].activation.toFixed(4),
};
const target = [...this.props.dreamingElement.params.tokens];
for (const tokenID in this.props.dreamingElement.params.tokens) {
if (this.props.dreamingElement.word_id !== parseInt(tokenID)) {
target[tokenID] = '';
}
}
const sentenceParams = {
headWidth: 30,
colors: ['blue', 'black', 'black'],
target: target,
};
const params = {
tokens: this.props.dreamingElement.params.tokens,
};
const maxIterations = this.props.dreamingElement.iterations[
this.props.dreamingElement.iterations.length -1].number;
return (
<Grid container direction='column' className='fullHeight' wrap='nowrap'>
<ExplanationHead
topic="Top Words"
params={headParams}
elementIndex={this.props.elementIndex}/>
<DreamHead
params={params}
sentenceParams={sentenceParams}/>
<TopWordsHead
maxIterations={maxIterations}
dreamingElement={this.props.dreamingElement}
elementIndex={this.props.elementIndex}/>
<Grid item xs>
<Paper id='topWordsPaper' className={'dreamPaper fullHeight'}>
<TopWordsBody
dreamingElement={this.props.dreamingElement}
elementIndex={this.props.elementIndex}/>
</Paper>
</Grid>
</Grid>
);
}
} |
JavaScript | class AddDeviceInfo {
getDeviceInfo(){
var deviceInfo = {
menufacturer: DeviceInfo.getManufacturer(),
model: DeviceInfo.getModel(),
osVersion: DeviceInfo.getSystemVersion(),
releaseVersion: DeviceInfo.getVersion(),
platform: Platform.OS
}
return deviceInfo;
}
} |
JavaScript | class ProductResults extends Component {
//
// constructor(){
// super();
// console.log('WE ARE IN ProductResults');
// }
//
// componentWillMount(){
// console.log('products', this.props.products);
// }
renderProducts(products) {
const title = products.title;
const imgURL = products.image_url;
const id = products.id;
const url = products.url;
return (
<tr key={id}>
<td>
{title}
</td>
<td>
<img className="resultImg" src={imgURL} />
</td>
<td>
<a className="buy" target="_blank" href={url}>
Buy on Amazon
</a>
</td>
</tr>
);
}
render() {
const products = this.props.products;
if (products && products.length) {
return (
<div className="resultsPage">
<Link className="link" to="/">
Back to Search
</Link>
<table className="table table-hover">
<tbody>
{products.map(this.renderProducts)}
</tbody>
</table>
<Link className="link" to="/">
Back to Search
</Link>
</div>
);
} else {
return <div>LOADING...</div>;
}
} //render
} |
JavaScript | class Dashboard extends Component {
render() {
if (this.props.baseInfo.isLoggedin) {
return (
<div style={{ margin: "0 4px 8px" }}>
<div className="insight-header">
<h1 className="header-container">Innsikt</h1>
<div className="status-container">
Viser status fra siste 7 dager
</div>
</div>
<CardComponent title={"Blodsukker"} content={<BloodSugarContent />} />
<div className="flex-container">
<DashboardGraphCard dataType={INSULIN} />
<DashboardGraphCard dataType={STEPS} />
</div>
<div
className="flex-container"
styles={{
"margin-left": "8px",
"margin-top": "8px",
"margin-right": "8px"
}}
>
<DashboardGraphCard dataType={CARBOHYDRATES} />
<DashboardGraphCard dataType={WEIGHT} />
</div>
<div className="flex-container">
<DashboardGraphCard dataType={PHYSICAL_ACTIVITY} />
<div className="flex-children" style={{ marginRight: "8px" }} />
</div>
<div className="single-flex-container">
<CardComponent content={<AddDataContent />} />
</div>
<div className="single-flex-container">
<CardComponent
title={"Sette nye mål?"}
content={changeGoalsContent()}
/>
</div>
<div className="single-flex-container">
<CardComponent
title={"Forstå din data"}
content={compareDataContent()}
/>
</div>
</div>
);
} else {
return (
<div>
<FHIRConnection />
</div>
);
}
}
} |
JavaScript | class Database {
constructor(name) {
const JsonDB = nodeJsonDb.JsonDB;
const humanReadable = process.env.DEV ? true : false;
this.db = new JsonDB(`database/${name || 'db'}`, true, humanReadable, "/");
this.prefix = "/data";
}
// Pushes new data to be added in the tabe
push(data) {
if(!data._id)
data._id = uuidv4();
this.db.push(this.prefix, [data], false);
}
// Gets saved data
get(key, value) {
let data = [];
try {
data = this.db.getData(this.prefix);
} catch(e) {
console.log("Could not get data.");
return [];
}
if(typeof key === "undefined" || typeof value === "undefined")
return data;
else {
let found = data.filter(item => item[key] && item[key] === value);
if(found.length === 0)
found = null;
else if(found.length === 1)
found = found[0];
return found;
}
}
// Resets table content
flush() {
this.db.push(this.prefix, []);
}
// Removes an entry in table
remove(key, value) {
this.db.push(this.prefix, this.get().filter(item => item[key] != value));
}
// Replaces an entry with another one
replace(key, value, data) {
this.remove(key, value);
this.push(data);
}
} |
JavaScript | class Pinata extends Container {
constructor() {
super();
this.name = 'pinata';
this._init();
}
/**
* @private
*/
_init() {
this._createBody();
this._addListeners();
}
/**
* @private
*/
_createBody() {
const body = new Sprite.from('pinata');
body.anchor.set(1, 0);
body.interactive = true;
body.buttonMode = true;
this._body = body;
this.addChild(this._body);
}
/**
* Animate pinata movement
* @public
*/
dance() {
gsap.to(this._body, {
rotation: -0.3,
repeat: -1,
yoyo: true,
ease: 'Power2.easeInOut',
});
}
/**
* Create particle that fall from pinata
* @public
*/
createParticle() {
const particle = new Sprite.from('particle');
particle.name = 'particle';
particle.y = 300;
particle.x = -150 + Math.floor(Math.random() * (50 - 1) + 1);
particle.scale.set(2);
this.addChild(particle);
gsap.to(particle, {
y: 600,
alpha: 0,
duration: 3,
});
this.removeChild();
}
/**
* Create chili that fall from pinata
* @private
*/
_createChilli() {
const chili = new Sprite.from('chili');
chili.name = 'chili';
chili.y = 200;
chili.x = -100;
chili.scale.set(Math.random() + 1);
this.addChild(chili);
gsap.to(chili, {
y: 600,
alpha: 0,
duration: 2,
});
this.removeChild();
}
/**
* @private
*/
_addListeners() {
this._body.on('click', () => this._createChilli());
}
} |
JavaScript | class Templates extends Queueable {
/**
* Render a template into the dom using the queues templateProcessor
* @param {number} pid - Process ID
* @param {object} json - queue arguments
* @param {string} json.template - dom id of template to use
* @param {string} [json.target] - dom id of render target
* @param {string} [json.mode] - "insert|append"
* @param {boolean} [json.quiet] - true|false
* @example
* templates.render({"targetId":"content","template":"basic"});
*/
render(pid,json) {
let self=this;
let options = Object.assign({
"mode": "insert",
"scrollTarget":".scroll",
"scroll":true
}, json);
self.set(pid,json);
if(!self.queue.templateProcessor(options.template,options.targetId,options.mode)&&options.quiet!==true) {
self.finished(pid, self.queue.DEFINE.FIN_ERROR, 'Could not render template');
} else {
if(options.scroll===true) {
let scrollElement = self.queue.getElement(options.targetId).closest(options.scrollTarget);
if(scrollElement)
scrollElement.scrollTop = 0;
else
window.scrollTo(0,0);
}
self.finished(pid, self.queue.DEFINE.FIN_OK);
}
}
} |
JavaScript | class HeaderPresenter extends BasePresenter {
/**
* @param {HTMLElement} application html of application
* @param {Class} View Class of view object
* @param {Class} Model Class of model object
*/
constructor(application, View, Model) {
super(application, View, Model);
Bus.globalBus.on(Events.HeaderChangeCatalogID, this.changeCatalogID);
Bus.globalBus.on(Events.LoginEmitResult, this.updateAuthorizeState);
Bus.globalBus.on(Events.SignupEmitResult, this.updateAuthorizeState);
Bus.globalBus.on(Events.ProfileLogoutEmitResult, this.updateAuthorizeState);
Bus.globalBus.on(Events.HeaderChangeCartItems, this.changeCartItems);
Bus.globalBus.on(Events.OrderSent, this.setOrDropCartItems);
Bus.globalBus.on(Events.HeaderSetCartItems, this.setOrDropCartItems);
this.bus.on(Events.HeaderLoad, this.loadHeader);
this.bus.on(Events.HeaderLoaded, this.headerLoadedReaction);
}
/**
*
* @return {Object}
*/
get categories() {
return this.model.categories;
}
/**
*
* @return {Number}
*/
get currentCategoryIndex() {
return this.model.currentCategoryIndex;
}
/**
*
* @param {Number} index
*/
set currentCategoryIndex(index) {
this.model.currentCategoryIndex = index;
}
/**
*
* @param {Number} id ID of a category
*/
changeCatalogID = (id) => {
this.view.ID = id;
}
/**
*
*/
loadHeader = () => {
this.model.loadHeader();
}
/**
*
* @param {string}result
*/
headerLoadedReaction = (result) => {
console.log(result);
if (result === Responses.Success) {
this.model.checkAuthorizeState();
this.view.reRender();
this.view.cache.hidden = false;
} else {
console.error('Cant load header');
}
}
/**
*
* @param {string}result
*/
updateAuthorizeState = (result) => {
if (result === Responses.Success) {
this.model.swapAuthorizeState();
this.view.changeLoginIcon(this.model.currentAuthorizeState);
} else {
console.error('Cant load header');
}
}
/**
* @param {number} value
*/
changeCartItems = (value) => {
this.view.changeCartItems(value);
}
/**
* @param {number} value
* @description sets items amount in cart to new value. By default set items amount to 0
*/
setOrDropCartItems = (value = 0) => {
this.view.setCartItems(value);
}
} |
JavaScript | class MajorArcanaDeck extends Deck {
constructor() {
const cards = ranks.map((rank) => {
return new Card(majorArcana, rank);
});
super(cards);
}
} |
JavaScript | class Theme {
/**
* Creates a new Theme manager.
* @constructor
* @param {string} defaultTheme - The default theme.
*/
constructor(defaultTheme) {
this.theme = defaultTheme;
/**
* @type {HTMLElement}
*/
this.buttonIcon = document.getElementById('theme-button-icon');
if (!this.buttonIcon) console.warn('No theme button found.');
this.updateTheme();
}
updateTheme() {
/**
* @type {HTMLElement}
*/
const root = document.querySelector(':root');
/**
* @type {HTMLElement}
*/
const minIcon = document.querySelector('#min-button-icon');
/**
* @type {HTMLElement}
*/
const maxIcon = document.querySelector('#max-button-icon');
/**
* @type {HTMLElement}
*/
const restoreIcon = document.querySelector('#restore-button-icon');
/**
* @type {HTMLElement}
*/
const closeIcon = document.querySelector('#close-button-icon');
if (!root) return console.error('No root element found.');
if (!minIcon) return console.error('No min icon found.');
if (!maxIcon) return console.error('No max icon found.');
if (!restoreIcon) return console.error('No restore icon found.');
if (!closeIcon) return console.error('No close icon found.');
switch (this.theme) {
case 'dark':
root.style.setProperty('--font-color', getComputedStyle(root).getPropertyValue('--font-dark-color') );
root.style.setProperty('--a-color', getComputedStyle(root).getPropertyValue('--a-dark-color') );
root.style.setProperty('--a-hover-color', getComputedStyle(root).getPropertyValue('--a-dark-hover-color') );
root.style.setProperty('--b-color', getComputedStyle(root).getPropertyValue('--b-dark-color') );
root.style.setProperty('--b-hover-color', getComputedStyle(root).getPropertyValue('--b-dark-hover-color') );
root.style.setProperty('--icon-filter', 'invert(1)');
minIcon.srcset = './static/icons/min-w-10.png 1x, ./static/icons/min-w-12.png 1.25x, ./static/icons/min-w-15.png 1.5x, ./static/icons/min-w-15.png 1.75x, ./static/icons/min-w-20.png 2x, ./static/icons/min-w-20.png 2.25x, ./static/icons/min-w-24.png 2.5x, ./static/icons/min-w-30.png 3x, ./static/icons/min-w-30.png 3.5x';
maxIcon.srcset = './static/icons/max-w-10.png 1x, ./static/icons/max-w-12.png 1.25x, ./static/icons/max-w-15.png 1.5x, ./static/icons/max-w-15.png 1.75x, ./static/icons/max-w-20.png 2x, ./static/icons/max-w-20.png 2.25x, ./static/icons/max-w-24.png 2.5x, ./static/icons/max-w-30.png 3x, ./static/icons/max-w-30.png 3.5x';
restoreIcon.srcset = './static/icons/restore-w-10.png 1x, ./static/icons/restore-w-12.png 1.25x, ./static/icons/restore-w-15.png 1.5x, ./static/icons/restore-w-15.png 1.75x, ./static/icons/restore-w-20.png 2x, ./static/icons/restore-w-20.png 2.25x, ./static/icons/restore-w-24.png 2.5x, ./static/icons/restore-w-30.png 3x, ./static/icons/restore-w-30.png 3.5x';
closeIcon.srcset = './static/icons/close-w-10.png 1x, ./static/icons/close-w-12.png 1.25x, ./static/icons/close-w-15.png 1.5x, ./static/icons/close-w-15.png 1.75x, ./static/icons/close-w-20.png 2x, ./static/icons/close-w-20.png 2.25x, ./static/icons/close-w-24.png 2.5x, ./static/icons/close-w-30.png 3x, ./static/icons/close-w-30.png 3.5x';
this.buttonIcon.srcset = './static/icons/light.svg';
break;
case 'light':
root.style.setProperty('--font-color', getComputedStyle(root).getPropertyValue('--font-light-color') );
root.style.setProperty('--a-color', getComputedStyle(root).getPropertyValue('--a-light-color') );
root.style.setProperty('--a-hover-color', getComputedStyle(root).getPropertyValue('--a-light-hover-color'));
root.style.setProperty('--b-color', getComputedStyle(root).getPropertyValue('--b-light-color') );
root.style.setProperty('--b-hover-color', getComputedStyle(root).getPropertyValue('--b-light-hover-color'));
root.style.setProperty('--icon-filter', 'invert(0)');
minIcon.srcset = './static/icons/min-k-10.png 1x, ./static/icons/min-k-12.png 1.25x, ./static/icons/min-k-15.png 1.5x, ./static/icons/min-k-15.png 1.75x, ./static/icons/min-k-20.png 2x, ./static/icons/min-k-20.png 2.25x, ./static/icons/min-k-24.png 2.5x, ./static/icons/min-k-30.png 3x, ./static/icons/min-k-30.png 3.5x';
maxIcon.srcset = './static/icons/max-k-10.png 1x, ./static/icons/max-k-12.png 1.25x, ./static/icons/max-k-15.png 1.5x, ./static/icons/max-k-15.png 1.75x, ./static/icons/max-k-20.png 2x, ./static/icons/max-k-20.png 2.25x, ./static/icons/max-k-24.png 2.5x, ./static/icons/max-k-30.png 3x, ./static/icons/max-k-30.png 3.5x';
restoreIcon.srcset = './static/icons/restore-k-10.png 1x, ./static/icons/restore-k-12.png 1.25x, ./static/icons/restore-k-15.png 1.5x, ./static/icons/restore-k-15.png 1.75x, ./static/icons/restore-k-20.png 2x, ./static/icons/restore-k-20.png 2.25x, ./static/icons/restore-k-24.png 2.5x, ./static/icons/restore-k-30.png 3x, ./static/icons/restore-k-30.png 3.5x';
closeIcon.srcset = './static/icons/close-k-10.png 1x, ./static/icons/close-k-12.png 1.25x, ./static/icons/close-k-15.png 1.5x, ./static/icons/close-k-15.png 1.75x, ./static/icons/close-k-20.png 2x, ./static/icons/close-k-20.png 2.25x, ./static/icons/close-k-24.png 2.5x, ./static/icons/close-k-30.png 3x, ./static/icons/close-k-30.png 3.5x';
this.buttonIcon.srcset = './static/icons/dark.svg';
break;
}
}
toggleTheme() {
this.theme == 'dark' ? this.theme = 'light' : this.theme = 'dark';
this.updateTheme();
}
} |
JavaScript | class Signer {
/**
* @param {module:api.CryptoSuite} cryptoSuite The underlying {@link CryptoSuite} implementation for the digital
* signature algorithm
* @param {module:api.Key} key The private key
*/
constructor(cryptoSuite, key) {
if (!cryptoSuite) {
throw new Error('Missing required parameter "cryptoSuite"');
}
if (!key) {
throw new Error('Missing required parameter "key" for private key');
}
this._cryptoSuite = cryptoSuite;
this._key = key;
}
/**
* Returns the public key corresponding to the opaque, private key
*
* @returns {module:api.Key} The public key corresponding to the private key
*/
getPublicKey() {
return this._key.getPublicKey();
}
/**
* Signs digest with the private key.
*
* Hash implements the SignerOpts interface and, in most cases, one can
* simply pass in the hash function used as opts. Sign may also attempt
* to type assert opts to other types in order to obtain algorithm
* specific values.
*
* Note that when a signature of a hash of a larger message is needed,
* the caller is responsible for hashing the larger message and passing
* the hash (as digest) and the hash function (as opts) to Sign.
*
* @param {byte[]} digest The message to sign
* @param {Object} opts
* hashingFunction: the function to use to hash
*/
sign(digest, opts) {
return this._cryptoSuite.sign(this._key, digest, opts);
}
} |
JavaScript | class ReservationSplitProperties {
/**
* Create a ReservationSplitProperties.
* @property {array} [splitDestinations] List of destination Resource Id that
* are created due to split. Format of the resource Id is
* /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}
* @property {string} [splitSource] Resource Id of the Reservation from which
* this is split. Format of the resource Id is
* /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}
*/
constructor() {
}
/**
* Defines the metadata of ReservationSplitProperties
*
* @returns {object} metadata of ReservationSplitProperties
*
*/
mapper() {
return {
required: false,
serializedName: 'ReservationSplitProperties',
type: {
name: 'Composite',
className: 'ReservationSplitProperties',
modelProperties: {
splitDestinations: {
required: false,
serializedName: 'splitDestinations',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
splitSource: {
required: false,
serializedName: 'splitSource',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class Container extends Layer {
constructor(args) {
// No args passed to super's constructor.
super({});
this.containerNodes = new Set();
this.name = args.name;
if (this.name == null) {
const prefix = this.getClassName().toLowerCase();
this.name = getUid(prefix);
}
this.supportsMasking = false;
this.trainable_ = true;
// TODO(michaelterry): Initialize perInputLosses/Updates here.
// Container-specific properties.
if (Array.isArray(args.inputs)) {
this.inputs = args.inputs.slice();
}
else {
this.inputs = [args.inputs];
}
if (Array.isArray(args.outputs)) {
this.outputs = args.outputs.slice();
}
else {
this.outputs = [args.outputs];
}
// Check for redundancy in inputs.
if (generic_utils.unique(this.inputs).length !== this.inputs.length) {
throw new ValueError('The list of inputs passed to the model is ' +
'redundant. All inputs should only appear once. Found: ' +
`${this.inputs.map(x => x.name)}`);
}
// Check for redundancy in outputs.
if (generic_utils.unique(this.outputs).length !== this.outputs.length) {
console.warn('The list of outputs passed to the model is redundant. ' +
'All outputs should only appear once. Found: ' +
`${this.outputs.map(x => x.name)}`);
}
/*
List of initial layers (1 to 1 mapping with this.inputs, hence the same
layer might appear twice)
*/
this.inputLayers = [];
this.inputLayersNodeIndices = [];
this.inputLayersTensorIndices = [];
/*
List of layers (1 to 1 mapping with this.outputs, hence the same layer
might appear twice)
*/
this.outputLayers = [];
this.outputLayersNodeIndices = [];
this.outputLayersTensorIndices = [];
/*
All layers in order of horizontal graph traversal. Entries are unique.
Includes input and output layers.
*/
this.layers = [];
/*
References to container layers that were constructed internally. We need
these to properly dispose of tensors from nested containers.
*/
this.internalContainerRefs = [];
// TODO(michaelterry): Determine if caching still needed with eager
// backend.
/*
This is for performance optimization when calling the Container on new
inputs. Every time the Container is called on a set on input tensors,
we compute the output tensors, output masks and output shapes in one pass,
then cache them here. When one of these outputs is queried later,
we retrieve it from there instead of recomputing it.
*/
// this.outputTensorCache = {};
// this.outputShapeCache = {};
// Build this.outputLayers:
for (const x of this.outputs) {
const layer = x.sourceLayer;
const nodeIndex = x.nodeIndex;
const tensorIndex = x.tensorIndex;
this.outputLayers.push(layer);
this.outputLayersNodeIndices.push(nodeIndex);
this.outputLayersTensorIndices.push(tensorIndex);
}
// TODO(michaelterry): Add output mask cache code.
// Build this.inputLayers:
for (const x of this.inputs) {
const layer = x.sourceLayer;
const nodeIndex = x.nodeIndex;
const tensorIndex = x.tensorIndex;
/*
It's supposed to be an input layer, so only one node
and one tensor output.
*/
generic_utils.assert(nodeIndex === 0, 'input layer has >1 nodes');
generic_utils.assert(tensorIndex === 0, 'input layer has >1 tensors');
this.inputLayers.push(layer);
this.inputLayersNodeIndices.push(nodeIndex);
this.inputLayersTensorIndices.push(tensorIndex);
}
// Build this.inputNames and this.outputNames.
this.inputNames = [];
this.outputNames = [];
this.feedInputShapes = [];
this.feedInputNames = [];
this.feedOutputNames = [];
for (let i = 0; i < this.inputLayers.length; i++) {
const layer = this.inputLayers[i];
// Check that layer is an InputLayer.
if (!(layer instanceof InputLayer)) {
throw new TypeError('Input layers to a LayersModel must be InputLayer objects. ' +
`Received inputs: ${args.inputs}. ` +
`Input ${i} (0-based) originates ` +
`from layer type ${layer.getClassName()}.`);
}
this.inputNames.push(layer.name);
this.feedInputShapes.push(layer.batchInputShape);
this.feedInputNames.push(layer.name);
}
for (const layer of this.outputLayers) {
this.outputNames.push(layer.name);
}
this.internalInputShapes = this.inputs.map(x => x.shape);
this.internalOutputShapes = this.outputs.map(x => x.shape);
/*
Container_nodes: set of nodes included in the graph (not all nodes
included in the layers are relevant to the current graph).
*/
// ids of all nodes relevant to the Container:
const nodesDepths = {};
// To recover nodes from their ID.
const nodeIDToNode = {};
const layersDepths = {};
// To layers from their ID.
const layerIDToLayer = {};
const layerIndices = {};
const nodesInDecreasingDepth = [];
/**
* Builds a map of the graph of layers.
*
* This recursively updates the map `layerIndices`,
* the list `nodesInDecreasingDepth` and the set `containerNodes`.
*
* @param tensor Some tensor in a graph.
* @param finishedNodes Set of nodes whose subgraphs have been traversed
* completely. Useful to prevent duplicated work.
* @param nodesInProgress Set of nodes that are currently active on the
* recursion stack. Useful to detect cycles.
* @param layer Layer from which `tensor` comes from. If not provided,
* will be obtained from tensor.sourceLayer.
* @param nodeIndex Node index from which `tensor` comes from.
* @param tensorIndex TensorIndex from which `tensor` comes from.
*
* @exception RuntimeError if a cycle is detected.
*/
const buildMapOfGraph = (tensor, finishedNodes, nodesInProgress, layer, nodeIndex, tensorIndex) => {
if (layer == null || nodeIndex == null || tensorIndex == null) {
layer = tensor.sourceLayer;
nodeIndex = tensor.nodeIndex;
tensorIndex = tensor.tensorIndex;
}
const node = layer.inboundNodes[nodeIndex];
// Prevent cycles.
if (nodesInProgress.indexOf(node) !== -1) {
throw new RuntimeError(`The tensor ${tensor.name} at layer "${layer.name}" ` +
'is part of a cycle.');
}
// Don't repeat work for shared subgraphs
if (finishedNodes.indexOf(node) !== -1) {
return;
}
// Update containerNodes.
this.containerNodes.add(Container.nodeKey(layer, nodeIndex));
// Store the traversal order for layer sorting.
if (!(layer.id in layerIndices)) {
layerIndices[layer.id] = Object.keys(layerIndices).length;
}
if (nodesInProgress.indexOf(node) === -1) {
nodesInProgress.push(node);
}
// Propagate to all previous tensors connected to this node.
const numInboundLayers = node.inboundLayers.length;
for (let i = 0; i < numInboundLayers; i++) {
const x = node.inputTensors[i];
const layer = node.inboundLayers[i];
const nodeIndex = node.nodeIndices[i];
const tensorIndex = node.tensorIndices[i];
buildMapOfGraph(x, finishedNodes, nodesInProgress, layer, nodeIndex, tensorIndex);
}
finishedNodes.push(node);
while (nodesInProgress.indexOf(node) >= 0) {
nodesInProgress.splice(nodesInProgress.indexOf(node), 1);
}
nodesInDecreasingDepth.push(node);
};
const finishedNodes = [];
const nodesInProgress = [];
for (const x of this.outputs) {
buildMapOfGraph(x, finishedNodes, nodesInProgress);
}
const reversedNodesInDecreasingDepth = nodesInDecreasingDepth.slice().reverse();
for (const node of reversedNodesInDecreasingDepth) {
nodeIDToNode[node.id] = node;
// If the depth is not set, the node has no outbound nodes (depth 0).
if (!(node.id in nodesDepths)) {
nodesDepths[node.id] = 0;
}
let depth = nodesDepths[node.id];
// Update the depth of the corresponding layer
const previousDepth = (layersDepths[node.outboundLayer.id] == null ?
0 :
layersDepths[node.outboundLayer.id]);
/*
If we've seen this layer before at a higher depth, we should use that
depth instead of the node depth. This is necessary for shared layers
that have inputs at different depth levels in the graph.
*/
depth = Math.max(depth, previousDepth);
layersDepths[node.outboundLayer.id] = depth;
layerIDToLayer[node.outboundLayer.id] = node.outboundLayer;
nodesDepths[node.id] = depth;
// Update the depth of inbound nodes.
for (let i = 0; i < node.inboundLayers.length; i++) {
const inboundLayer = node.inboundLayers[i];
const nodeIndex = node.nodeIndices[i];
const inboundNode = inboundLayer.inboundNodes[nodeIndex];
const previousDepth = (nodesDepths[inboundNode.id] == null ? 0 :
nodesDepths[inboundNode.id]);
nodesDepths[inboundNode.id] = Math.max(depth + 1, previousDepth);
nodeIDToNode[inboundNode.id] = inboundNode;
}
}
// Build a dict {depth: list of nodes with this depth}
const nodesByDepth = {};
for (const nodeID in nodesDepths) {
const depth = nodesDepths[nodeID];
if (!(depth in nodesByDepth)) {
nodesByDepth[depth] = [];
}
nodesByDepth[depth].push(nodeIDToNode[nodeID]);
}
// Build a dict {depth: list of layers with this depth}
const layersByDepth = {};
for (const layerID in layersDepths) {
const depth = layersDepths[layerID];
if (!(depth in layersByDepth)) {
layersByDepth[depth] = [];
}
layersByDepth[depth].push(layerIDToLayer[layerID]);
}
// Get sorted list of layer depths.
let depthKeys = Object.keys(layersByDepth)
.map(x => parseInt(x, 10))
.sort(generic_utils.reverseNumberCompare);
// Set this.layers and this.layersByDepth.
this.layers = [];
for (const depth of depthKeys) {
const layersForDepth = layersByDepth[depth];
// Container.layers needs to have a deterministic order:
// here we order them by traversal order.
layersForDepth.sort((a, b) => {
const aIndex = layerIndices[a.id];
const bIndex = layerIndices[b.id];
if (aIndex < bIndex) {
return -1;
}
if (aIndex > bIndex) {
return 1;
}
return 0;
});
for (const layer of layersForDepth) {
if (layer instanceof Container) {
this.internalContainerRefs.push(layer);
}
this.layers.push(layer);
}
}
this.layersByDepth = layersByDepth;
// Get sorted list of node depths;
depthKeys = Object.keys(nodesByDepth)
.map(x => parseInt(x, 10))
.sort(generic_utils.reverseNumberCompare);
// Check that all tensors required are computable.
// computable_tensors: all tensors in the graph
// that can be computed from the inputs provided.
const computableTensors = this.inputs.slice();
// To provide a better error msg.
const layersWithCompleteInput = [];
for (const depth of depthKeys) {
for (const node of nodesByDepth[depth]) {
const layer = node.outboundLayer;
if (layer != null) {
for (const x of node.inputTensors) {
if (computableTensors.indexOf(x) === -1) {
throw new RuntimeError(`Graph disconnected: cannot obtain value for tensor ${x}` +
` at layer "${layer.name}". ` +
'The following previous layers were accessed without ' +
`issue: ${layersWithCompleteInput}`);
}
}
for (const x of node.outputTensors) {
computableTensors.push(x);
}
layersWithCompleteInput.push(layer.name);
}
}
}
// Set this.containerNodes and this.nodesByDepth.
this.nodesByDepth = nodesByDepth;
// Ensure name unicity, which will be crucial for serialization
// (since serialized nodes refer to layers by their name).
const allNames = this.layers.map(x => x.name);
for (const name of allNames) {
const numOccurrences = allNames.filter(x => x === name).length;
if (numOccurrences !== 1) {
throw new RuntimeError(`The name "${name}" is used ${numOccurrences} times ` +
'in the model. All layer names should be unique. Layer names: ' +
JSON.stringify(allNames));
}
}
// Layer parameters.
// The new container starts with a single inbound node
// for its inputs, and no outbound nodes.
// Will be appended to by future calls to apply().
this.outboundNodes = [];
// Will be appended to below, and by future calls to apply().
this.inboundNodes = [];
// Create the node linking internal inputs to internal outputs.
// (This call has side effects.)
// tslint:disable-next-line:no-unused-expression
new Node({
outboundLayer: this,
inboundLayers: [],
nodeIndices: [],
tensorIndices: [],
inputTensors: this.inputs,
outputTensors: this.outputs,
inputMasks: this.inputs.map(x => null),
outputMasks: this.outputs.map(x => null),
inputShapes: this.inputs.map(x => x.shape),
outputShapes: this.outputs.map(x => x.shape)
});
this.built = true;
this._refCount = 1; // The ref count of a container always start at 1.
}
assertNotDisposed() {
if (this._refCount === 0) {
throw new Error(`Container '${this.name}' is already disposed.`);
}
}
/**
* Attempt to dispose a LayersModel's weights.
*
* This method decrease the reference count of the LayersModel object by 1.
*
* A LayersModel is reference-counted. Its reference count is incremented by 1
* when it is first constructed and when it is used as a Layer of another
* LayersModel.
*
* If the reference count of a LayersModel becomes 0, the `dispose` method of
* all its constituent `Layer`s will be called.
*
* Note: If the reference count is greater than 0 after the decrement, the
* `dispose` method of its constituent `Layer`s will *not* be called.
*
* After a LayersModel is disposed, it cannot be used in calls such as
* 'predict`, `evaluate` or `fit` anymore.
*
* @returns A DisposeResult Object with the following fields:
* - refCountAfterDispose: The reference count of the LayersModel after this
* `dispose()` call.
* - numDisposedVariables: Number of `tf.Variable`s (i.e., weights) disposed
* during this `dispose()` call.
* @throws {Error} If the layer is not built yet, or if the LayersModel has
* already been disposed.
*/
dispose() {
this.assertNotDisposed();
const result = { refCountAfterDispose: null, numDisposedVariables: 0 };
if (--this._refCount === 0) {
for (const layer of this.layers) {
result.numDisposedVariables += layer.dispose().numDisposedVariables;
}
// Call dispose on each internally created container layer again to ensure
// their refCounts hit zero and their tensors are subsequently deleted.
for (const container of this.internalContainerRefs) {
result.numDisposedVariables += container.dispose().numDisposedVariables;
}
}
result.refCountAfterDispose = this._refCount;
return result;
}
get trainable() {
return this.trainable_;
}
set trainable(trainable) {
this.layers.forEach(layer => {
// tslint:disable-next-line:no-any
layer._trainableWeights
.forEach(w => w.trainable = trainable);
});
this.trainable_ = trainable;
}
get trainableWeights() {
// Porting Note: This check below is to prevent errors where the
// _trainableWeights inherited from the parent class (Layer) gets
// inadvertently used.
if (this._trainableWeights.length > 0) {
throw new ValueError('Container instance unexpectedly contains _trainableWeights.' +
'The trainable weights of a Container are a union of the ' +
'trainable weights of its consituent Layers. Its own ' +
'_trainableWeights must remain an empty Array.');
}
if (!this.trainable) {
return [];
}
let weights = [];
for (const layer of this.layers) {
weights = weights.concat(layer.trainableWeights);
}
return weights;
}
get nonTrainableWeights() {
const weights = [];
for (const layer of this.layers) {
weights.push(...layer.nonTrainableWeights);
}
if (!this.trainable) {
const trainableWeights = [];
for (const layer of this.layers) {
trainableWeights.push(...layer.trainableWeights);
}
return trainableWeights.concat(weights);
}
return weights;
}
get weights() {
return this.trainableWeights.concat(this.nonTrainableWeights);
}
/**
* Loads all layer weights from a JSON object.
*
* Porting Note: HDF5 weight files cannot be directly loaded in JavaScript /
* TypeScript. The utility script at `scripts/pykeras.py` offers means
* to convert them into JSON strings compatible with this method.
* Porting Note: TensorFlow.js Layers supports only loading by name currently.
*
* @param weights A JSON mapping weight names to weight values as nested
* arrays of numbers, or a `NamedTensorMap`, i.e., a JSON mapping weight
* names to `tf.Tensor` objects.
* @param strict Require that the provided weights exactly match those
* required by the container. Default: `true`. Passing `false` means that
* extra weights and missing weights will be silently ignored.
*/
loadWeights(weights, strict = true) {
const nameToWeight = {};
let totalWeightsCount = 0;
for (const layer of this.layers) {
for (const weight of layer.weights) {
if (nameToWeight[weight.originalName] != null) {
throw new ValueError(`Duplicate weight name: ${weight.originalName}`);
}
nameToWeight[weight.originalName] = weight;
totalWeightsCount++;
}
}
const weightValueTuples = [];
for (const name in weights) {
// TF 2.2.0 added cell name to the weight name in the format of
// layer_name/cell_name/weight_name, we need to remove
// the inner cell name.
let validatedName = name;
if (nameToWeight[name] == null) {
const tokens = name.split('/');
const shortenNameArray = tokens.slice(0, -2).concat([tokens[tokens.length - 1]]);
validatedName = shortenNameArray.join('/');
}
if (nameToWeight[validatedName] != null) {
weightValueTuples.push([nameToWeight[validatedName], weights[name]]);
}
else if (strict) {
throw new ValueError(`Provided weight data has no target variable: ${name}`);
}
delete nameToWeight[validatedName];
}
if (strict) {
// Check that all weights are set.
const unsetNames = [];
for (const name in nameToWeight) {
unsetNames.push(name);
}
if (unsetNames.length > 0) {
throw new ValueError(`${unsetNames.length} of ${totalWeightsCount} weights are not set: ` +
`${unsetNames}`);
}
}
batchSetValue(weightValueTuples);
}
/**
* Util shared between different serialization methods.
* @returns LayersModel config with Keras version information added.
*/
updatedConfig() {
const theConfig = this.getConfig();
const modelConfig = {};
modelConfig['className'] = this.getClassName();
modelConfig['config'] = theConfig;
modelConfig['kerasVersion'] = `tfjs-layers ${layersVersion}`;
// TODO(nielsene): Replace something like K.backend() once
// possible.
modelConfig['backend'] = 'TensorFlow.js';
return modelConfig;
}
/**
* Returns a JSON string containing the network configuration.
*
* To load a network from a JSON save file, use
* models.modelFromJSON(jsonString);
* @param extraJsonArgs Unused in tfjs-layers, maintained for PyKeras
* @param returnString Whether the return value should be stringified
* (default: `true`).
* @returns a JSON string if `returnString` (default), or a JSON object if
* `!returnString`.
*/
// tslint:disable-next-line:no-any
toJSON(unused, returnString = true) {
const modelConfig = convertTsToPythonic(this.updatedConfig());
return returnString ? JSON.stringify(modelConfig) : modelConfig;
}
/**
* Call the model on new inputs.
*
* In this case `call` just reapplies all ops in the graph to the new inputs
* (e.g. build a new computational graph from the provided inputs).
*
* @param inputs A tensor or list of tensors.
* @param mask A mask or list of masks. A mask can be either a tensor or null
* (no mask).
*
* @return A tensor if there is a single output, or a list of tensors if there
* are more than one outputs.
*/
call(inputs, kwargs) {
return tidy(() => {
inputs = generic_utils.toList(inputs);
const feedDict = new FeedDict();
for (let i = 0; i < this.inputs.length; ++i) {
feedDict.add(this.inputs[i], inputs[i]);
}
return execute(this.outputs, feedDict, kwargs);
});
}
/**
* Computes an output mask tensor.
*
* @param inputs Tensor or list of tensors.
* @param mask Tensor or list of tensors.
*
* @return null or a tensor (or list of tensors, one per output tensor of the
* layer).
*/
computeMask(inputs, mask) {
return tidy(() => {
inputs = generic_utils.toList(inputs);
let masks;
if (mask == null) {
masks = generic_utils.pyListRepeat(null, inputs.length);
}
else {
masks = generic_utils.toList(mask);
}
// TODO(michaelterry): Add support for mask caching.
return this.runInternalGraph(inputs, masks)[1];
});
}
/**
* Computes the output shape of the layer.
*
* Assumes that the layer will be built to match that input shape provided.
*
* @param inputShape A shape (tuple of integers) or a list of shape tuples
* (one per output tensor of the layer). Shape tuples can include null for
* free dimensions, instead of an integer.
*/
computeOutputShape(inputShape) {
const inputShapes = types_utils.normalizeShapeList(inputShape);
if (inputShapes.length !== this.inputLayers.length) {
throw new ValueError(`Invalid inputShape argument ${inputShape}: ` +
`model has ${this.inputLayers.length} tensor inputs.`);
}
// TODO(michaelterry): Add caching
const layersToOutputShapes = {};
for (let i = 0; i < inputShapes.length; i++) {
const layer = this.inputLayers[i];
const inputShape = inputShapes[i];
// It's an input layer: computeOutputShape is identity,
// and there is only one node and one tensor output.
const shapeKey = layer.name + '_0_0';
layersToOutputShapes[shapeKey] = inputShape;
}
const depthKeys = Object.keys(this.nodesByDepth)
.map(x => parseInt(x, 10))
.sort(generic_utils.reverseNumberCompare);
// Iterate over nodes, by depth level.
if (depthKeys.length > 1) {
for (const depth of depthKeys) {
const nodes = this.nodesByDepth[depth];
for (const node of nodes) {
// This is always a single layer, never a list.
const layer = node.outboundLayer;
if (this.inputLayers.map(x => x.id).indexOf(layer.id) !== -1) {
// We've already covered the input layers a few lines above.
continue;
}
// Potentially redundant list, same size of node.inputTensors.
const inputShapes = [];
for (let j = 0; j < node.inboundLayers.length; j++) {
const inboundLayer = node.inboundLayers[j];
const nodeIndex = node.nodeIndices[j];
const tensorIndex = node.tensorIndices[j];
const shapeKey = `${inboundLayer.name}_${nodeIndex}_${tensorIndex}`;
const inputShape = layersToOutputShapes[shapeKey];
inputShapes.push(inputShape);
}
const outputShape = layer.computeOutputShape(generic_utils.singletonOrArray(inputShapes));
const outputShapes = types_utils.normalizeShapeList(outputShape);
const nodeIndex = layer.inboundNodes.indexOf(node);
for (let j = 0; j < outputShapes.length; j++) {
const shapeKey = `${layer.name}_${nodeIndex}_${j}`;
layersToOutputShapes[shapeKey] = outputShapes[j];
}
}
}
}
// Read final output shapes from layersToOutputShapes.
const outputShapes = [];
const outputShapeKeys = [];
for (let i = 0; i < this.outputLayers.length; i++) {
const layer = this.outputLayers[i];
const nodeIndex = this.outputLayersNodeIndices[i];
const tensorIndex = this.outputLayersTensorIndices[i];
const shapeKey = `${layer.name}_${nodeIndex}_${tensorIndex}`;
outputShapeKeys.push(shapeKey);
}
for (let i = 0; i < outputShapeKeys.length; i++) {
const key = outputShapeKeys[i];
generic_utils.assert(key in layersToOutputShapes);
outputShapes.push(layersToOutputShapes[key]);
}
// TODO(michaelterry): Update cache
return generic_utils.singletonOrArray(outputShapes);
}
/**
* Computes output tensors for new inputs.
*
* Note:
* - Expects `inputs` to be a list (potentially with 1 element).
*
* @param inputs List of tensors
* @param masks List of masks (tensors or null).
* @return Three lists: outputTensors, outputMasks, outputShapes
*/
runInternalGraph(inputs, masks) {
if (masks == null) {
masks = generic_utils.pyListRepeat(null, inputs.length);
}
// Dictionary mapping reference tensors to tuples
// (computed tensor, compute mask)
// we assume a 1:1 mapping from tensor to mask
// TODO: raise exception when a `.computeMask()` call
// does not return a list the same size as `call`
const tensorMap = {};
for (let i = 0; i < this.inputs.length; ++i) {
const x = this.inputs[i];
const y = inputs[i];
const mask = masks[i];
tensorMap[x.id] = [y, mask];
}
const depthKeys = Object.keys(this.nodesByDepth)
.map(x => parseInt(x, 10))
.sort(generic_utils.reverseNumberCompare);
for (const depth of depthKeys) {
const nodes = this.nodesByDepth[depth];
for (const node of nodes) {
// This is always a single layer, never a list.
const layer = node.outboundLayer;
const referenceInputTensors = node.inputTensors;
const referenceOutputTensors = node.outputTensors;
// If all previous input tensors are available in tensorMap,
// then call node.inboundLayer on them.
// List of tuples [input, mask]:
const computedData = new Array();
for (const x of referenceInputTensors) {
if (x.id in tensorMap) {
computedData.push(tensorMap[x.id]);
}
}
if (computedData.length === referenceInputTensors.length) {
// TODO(michaelterry): Add K.name_scope here, if we need it.
let kwargs = {};
let computedTensors;
let computedMasks;
let outputTensors;
let outputMasks;
// call layer
if (node.callArgs != null) {
kwargs = node.callArgs;
}
if (computedData.length === 1) {
const [computedTensor, computedMask] = computedData[0];
if (kwargs['mask'] == null) {
kwargs['mask'] = computedMask;
}
outputTensors =
generic_utils.toList(layer.call(computedTensor, kwargs));
outputMasks = generic_utils.toList(layer.computeMask(computedTensor, computedMask));
computedTensors = [computedTensor];
computedMasks = [computedMask];
}
else {
computedTensors = computedData.map(x => x[0]);
computedMasks = computedData.map(x => x[1]);
if (kwargs['mask'] == null) {
kwargs['mask'] = computedMasks;
}
outputTensors =
generic_utils.toList(layer.call(computedTensors, kwargs));
outputMasks = generic_utils.toList(layer.computeMask(computedTensors, computedMasks));
}
if (layer.activityRegularizer) {
throw new NotImplementedError('LayersModel invocation with concrete Tensor value(s) in the ' +
'presence of activity regularizer(s) is not supported yet.');
}
// TODO(michaelterry): Add model updates and losses
// Update tensor map.
for (let i = 0; i < referenceOutputTensors.length; ++i) {
const x = referenceOutputTensors[i];
const y = outputTensors[i];
const mask = outputMasks[i];
tensorMap[x.id] = [y, mask];
}
}
}
}
const outputTensors = [];
const outputMasks = [];
const outputShapes = [];
for (const x of this.outputs) {
generic_utils.assert(x.id in tensorMap, `Could not compute output ${x.name} : ${x.id}`);
const [tensor, mask] = tensorMap[x.id];
outputShapes.push(tensor.shape);
outputTensors.push(tensor);
outputMasks.push(mask);
}
// TODO(michaelterry): Add support for caches.
return [outputTensors, outputMasks, outputShapes];
}
/**
* Builds a map of internal node keys to node ordering.
* Used in serializaion a node orderings may change as unused nodes are
* dropped. Porting Note: This helper method was pulled out of getConfig to
* improve readability.
* @param layers An array of Layers in the model.
* @returns Map of Node Keys to index order within the layer.
*/
buildNodeConversionMap(layers) {
const nodeConversionMap = {};
let keptNodes;
for (const layer of this.layers) {
keptNodes = layer instanceof Container ? 1 : 0;
for (let originalNodeIndex = 0; originalNodeIndex < layer.inboundNodes.length; originalNodeIndex++) {
const nodeKey = Container.nodeKey(layer, originalNodeIndex);
if (this.containerNodes.has(nodeKey)) {
// i.e. we mark it to be saved
nodeConversionMap[nodeKey] = keptNodes;
keptNodes += 1;
}
}
}
return nodeConversionMap;
}
/**
* Retrieves a layer based on either its name (unique) or index.
*
* Indices are based on order of horizontal graph traversal (bottom-up).
*
* If both `name` and `index` are specified, `index` takes precedence.
*
* @param name Name of layer.
* @param index Index of layer.
* @returns A Layer instance.
* @throws ValueError: In case of invalid layer name or index.
*
* @doc {
* heading: 'Layers',
* subheading: 'Classes',
* namespace: 'layers',
* subclasses: ['LayersModel']
* }
*/
getLayer(name, index) {
if (index != null) {
if (this.layers.length <= index) {
throw new ValueError(`Was asked to retrieve layer at index ${index}, but model only ` +
`has ${this.layers.length} layer(s).`);
}
else {
return this.layers[index];
}
}
else {
if (name == null) {
throw new ValueError('Provide either a layer name or layer index');
}
}
for (const layer of this.layers) {
if (layer.name === name) {
return layer;
}
}
throw new ValueError(`No such layer: ${name}`);
}
/**
* Retrieves the Container's current loss values.
*
* Used for regularizers during training.
*/
calculateLosses() {
// Porting Node: This is an augmentation to Container.loss in PyKeras.
// In PyKeras, Container.loss returns symbolic tensors. Here a concrete
// Tensor (specifically Scalar) values are returned. This is due to the
// imperative backend.
return tidy(() => {
const losses = [];
for (const layer of this.layers) {
for (let nodeIndex = 0; nodeIndex < layer.inboundNodes.length; ++nodeIndex) {
const nodeKey = Container.nodeKey(layer, nodeIndex);
if (this.containerNodes.has(nodeKey)) {
losses.push(...layer.calculateLosses());
}
}
}
// TODO(cais): Add any unconditional model-level losses?
return losses;
});
}
getConfig() {
const config = { name: this.name };
// Build a map from layer unique name (self._node_key)
// to the index of the nodes that are saved in the config.
// Only nodes in container_nodes are saved.
const nodeConversionMap = this.buildNodeConversionMap(this.layers);
// Serialize and save the layers in layerConfigs
const layerConfigs = [];
for (const layer of this.layers) {
const layerClassName = layer.getClassName();
const layerConfig = layer.getConfig();
const filteredInboundNodes = [];
for (let originalNodeIndex = 0; originalNodeIndex < layer.inboundNodes.length; originalNodeIndex++) {
const node = layer.inboundNodes[originalNodeIndex];
const nodeKey = Container.nodeKey(layer, originalNodeIndex);
let kwargs = {};
if (this.containerNodes.has(nodeKey)) {
// The node is relevant to the model:
// add to filteredInboundNodes.
if (node.callArgs) {
try {
JSON.stringify(node.callArgs);
kwargs = node.callArgs;
}
catch (err) {
console.warn(`Layer ${layer.name} was passed ` +
`non-serializable keyword arguments: ` +
`${node.callArgs}. They will not be included ` +
`in the serialized model (and thus will be ` +
`missing at deserialization time).`);
kwargs = {};
}
}
if (node.inboundLayers.length > 0) {
const nodeData = [];
for (let i = 0; i < node.inboundLayers.length; i++) {
const inboundLayer = node.inboundLayers[i];
const nodeIndex = node.nodeIndices[i];
const tensorIndex = node.tensorIndices[i];
const nodeKey = Container.nodeKey(inboundLayer, nodeIndex);
let newNodeIndex = nodeConversionMap[nodeKey];
if (newNodeIndex == null) {
newNodeIndex = 0;
}
nodeData.push([inboundLayer.name, newNodeIndex, tensorIndex, kwargs]);
}
filteredInboundNodes.push(nodeData);
}
}
}
const dict = {};
dict['name'] = layer.name;
dict['className'] = layerClassName;
dict['config'] = layerConfig;
dict['inboundNodes'] = filteredInboundNodes;
layerConfigs.push(dict);
}
config['layers'] = layerConfigs;
// Gather info about inputs and outputs
const modelInputs = [];
for (let i = 0; i < this.inputLayers.length; i++) {
const layer = this.inputLayers[i];
const nodeIndex = this.inputLayersNodeIndices[i];
const nodeKey = Container.nodeKey(layer, nodeIndex);
if (!this.containerNodes.has(nodeKey)) {
continue;
}
let newNodeIndex = nodeConversionMap[nodeKey];
if (newNodeIndex === null || newNodeIndex === undefined) {
newNodeIndex = 0;
}
const tensorIndex = this.inputLayersTensorIndices[i];
modelInputs.push([layer.name, newNodeIndex, tensorIndex]);
}
config['inputLayers'] = modelInputs;
const modelOutputs = [];
for (let i = 0; i < this.outputLayers.length; i++) {
const layer = this.outputLayers[i];
const nodeIndex = this.outputLayersNodeIndices[i];
const nodeKey = Container.nodeKey(layer, nodeIndex);
if (!this.containerNodes.has(nodeKey)) {
continue;
}
let newNodeIndex = nodeConversionMap[nodeKey];
if (newNodeIndex === null || newNodeIndex === undefined) {
newNodeIndex = 0;
}
const tensorIndex = this.outputLayersTensorIndices[i];
modelOutputs.push([layer.name, newNodeIndex, tensorIndex]);
}
config['outputLayers'] = modelOutputs;
return config;
}
/**
* Instantiates a LayersModel from its config (output of `get_config()`).
* @param cls the class to create
* @param config LayersModel config dictionary.
* @param customObjects An optional dictionary of custom objects.
* @param fastWeightInit Optional flag to use fast weight initialization
* during deserialization. This is applicable to cases in which
* the initialization will be immediately overwritten by loaded weight
* values. Default: `false`.
* @returns A LayersModel instance.
* @throws ValueError: In case of improperly formatted config dict.
*/
/** @nocollapse */
static fromConfig(cls, config, customObjects = {}, fastWeightInit = false) {
// Layer instances created during
// the graph reconstruction process
const createdLayers = {};
// Dictionary mapping layer instances to
// node data that specifies a layer call.
// It acts as a queue that maintains any unprocessed
// layer call until it becomes possible to process it
// (i.e. until the input tensors to the call all exist).
const unprocessedNodes = {};
function addUnprocessedNode(layer, nodeData) {
if (!(layer.name in unprocessedNodes)) {
unprocessedNodes[layer.name] = [nodeData];
}
else {
unprocessedNodes[layer.name].push(nodeData);
}
}
function processNode(layer, nodeData) {
const inputTensors = [];
let kwargs;
for (const inputData of nodeData) {
const inboundLayerName = inputData[0];
const inboundNodeIndex = inputData[1];
const inboundTensorIndex = inputData[2];
kwargs = inputData[3] == null ?
{} :
inputData[3];
if (!(inboundLayerName in createdLayers)) {
addUnprocessedNode(layer, nodeData);
return;
}
const inboundLayer = createdLayers[inboundLayerName];
if (inboundLayer.inboundNodes.length <= inboundNodeIndex) {
addUnprocessedNode(layer, nodeData);
return;
}
const inboundNode = inboundLayer.inboundNodes[inboundNodeIndex];
inputTensors.push(inboundNode.outputTensors[inboundTensorIndex]);
}
// Call layer on its inputs, thus creating the node
// and building the layer if needed.
// Note: This has Eager vs Graph Implications.
if (inputTensors.length > 0) {
layer.apply(generic_utils.singletonOrArray(inputTensors), kwargs); // was ** kwargs
}
}
/**
* Deserialize a layer, then call it on appropriate inputs.
* @param layerData: layer config dict.
* @throws ValueError: In case of improperly formatted `layer_data`
* dict.
*/
function processLayer(layerData) {
const layerName = layerData['name'];
// Instantiate layer.
const layer = deserializeLayer(layerData, config['customObjects'] != null ?
config['customObjects'] :
{});
layer.setFastWeightInitDuringBuild(fastWeightInit);
createdLayers[layerName] = layer;
// Gather layer inputs.
const inboundNodesData = layerData['inboundNodes'];
inboundNodesData.forEach(nodeData => {
if (!(nodeData instanceof Array)) {
throw new ValueError(`Corrupted configuration, expected array for nodeData: ${nodeData}`);
}
// We don't process nodes (i.e. make layer calls)
// on the fly because the inbound node may not yet exist,
// in case of layer shared at different topological depths
// (e.g.a model such as A(B(A(B(x)))))
addUnprocessedNode(layer, nodeData);
});
}
// First, we create all layers and enqueue nodes to be processed.
const name = config['name'];
const layersFromConfig = config['layers'];
for (const layerData of layersFromConfig) {
processLayer(layerData);
}
// Then we process nodes in order of layer depth.
// Nodes that cannot yet be processed(if the inbound node
// does not yet exist) are re - enqueued, and the process
// is repeated until all nodes are processed.
while (!generic_utils.isObjectEmpty(unprocessedNodes)) {
for (const layerData of layersFromConfig) {
const layer = createdLayers[layerData['name']];
if (layer.name in unprocessedNodes) {
const currentUnprocessedNodesForLayer = unprocessedNodes[layer.name];
delete unprocessedNodes[layer.name];
for (const nodeData of currentUnprocessedNodesForLayer) {
processNode(layer, nodeData);
}
}
}
}
const inputTensors = [];
const outputTensors = [];
const inputLayersFromConfig = config['inputLayers'];
for (const layerData of inputLayersFromConfig) {
const layerName = layerData[0];
const nodeIndex = layerData[1];
const tensorIndex = layerData[2];
generic_utils.assert(layerName in createdLayers);
const layer = createdLayers[layerName];
const layerOutputTensors = layer.inboundNodes[nodeIndex].outputTensors;
inputTensors.push(layerOutputTensors[tensorIndex]);
}
const outputLayersFromConfig = config['outputLayers'];
for (const layerData of outputLayersFromConfig) {
const layerName = layerData[0];
const nodeIndex = layerData[1];
const tensorIndex = layerData[2];
generic_utils.assert(layerName in createdLayers);
const layer = createdLayers[layerName];
const layerOutputTensors = layer.inboundNodes[nodeIndex].outputTensors;
outputTensors.push(layerOutputTensors[tensorIndex]);
}
return new cls({ inputs: inputTensors, outputs: outputTensors, name });
}
/**
* Determine whether the container is stateful.
*
* Porting Note: this is the equivalent of the stateful @property of
* the Container class in PyKeras.
*/
get stateful() {
// Porting Note: This check is to prevent inadvertent setting of the
// _stateful property of the Container instance.
if (this._stateful) {
throw new ValueError('Container instance unexpectedly has _stateful = true. The ' +
'statefulness of a Container is determined by the Layers it ' +
'contains. Its _stateful property must remain the default false.');
}
for (const layer of this.layers) {
if (layer.stateful) {
return true;
}
}
return false;
}
/**
* Reset the state of all stateful constituent layers (if any).
*
* Examples of stateful layers include RNN layers whose `stateful` property
* is set as `true`.
*/
resetStates() {
tidy(() => {
this.layers.forEach(layer => {
// tslint:disable:no-any
if (layer.stateful) {
layer.resetStates();
}
// tslint:enable:no-any
});
});
}
} |
JavaScript | class Event {
constructor(type) {
this.type = type;
}
} |
JavaScript | class CommunicationFailed extends Event {
constructor() {
super("CommunicationFailed");
}
} |
JavaScript | class DeviceEvent extends Event {
/** Constructs a new event.
* @param type - an event type
* @param deviceId - a device ID.
*/
constructor(type, deviceId) {
super(type);
this.deviceId = deviceId;
}
} |
JavaScript | class DeviceConnected extends DeviceEvent {
/** Constructs a new event.
* @param deviceId - a device ID.
*/
constructor(deviceId) {
super("DeviceConnected", deviceId);
}
} |
JavaScript | class DeviceDisconnected extends DeviceEvent {
/** Constructs a new event.
* @param deviceId - a device ID.
*/
constructor(deviceId) {
super("DeviceDisconnected", deviceId);
}
} |
JavaScript | class CardInserted extends DeviceEvent {
/** Contructs a new event object.
* @param reader - a name of a card reader where the card was presented.
* @param card - a name of a card presented.
*/
constructor(reader, card) {
super("CardInserted", reader);
this.cardId = card;
}
} |
JavaScript | class CardRemoved extends DeviceEvent {
/** Contructs a new event object.
* @param reader - a name of a card reader where the card was presented.
* @param card - a name of a card presented.
*/
constructor(reader, card) {
super("CardRemoved", reader);
this.cardId = card;
}
} |
JavaScript | class CardsReader extends MultiCastEventSource {
/**
* Constructs a new card reader API object.
* @param options - options for the `WebSdk` channel.
*/
constructor(options) {
super();
this.channel = new Channel("smartcards", options);
this.channel.onCommunicationError = this.onConnectionFailed.bind(this);
this.channel.onNotification = this.processNotification.bind(this);
}
/**
* Adds an event handler for the event.
* This is a multicast subscription, i.e. many handlers can be registered at once.
*
* @param event - a name of the event to subscribe, e.g. "CardInserted"
* @param handler - an event handler.
* @returns an event handler reference.
* Store the reference and pass it to the {@link CardsReader.off} to unsubscribe from the event.
*
* @example
* ```
* class CardComponent
* {
* private reader: CardsReader;
*
* private onCardInserted = (event: CardInserted) => { ... }
* private onCardRemoved = (event: CardRemoved) => { ... }
* ...
*
* public async $onInit() {
* this.reader = new CardsReader();
* this.reader.on("CardInserted", this.onCardInserted);
* this.reader.on("CardRemoved", this.onCardRemoved);
* ...
* await this.cardReader.subscribe()
* }
* public async $onDestroy() {
* await this.cardReader.unsubscribe();
* this.reader.off("CardInserted", this.onCardInserted);
* this.reader.off("CardRemoved", this.onCardRemoved);
* ...
* // alternatively, call this.reader.off() to unsubscribe from all events at once.
* delete this.reader;
* }
* }
* ```
*/
on(event, handler) { return this._on(event, handler); }
/** Deletes an event handler for the event.
* @param event - a name of the event to subscribe.
* @param handler - an event handler added with the {@link CardsReader.on} method.
* @example See example in {@link CardsReader.on}
*/
off(event, handler) { return this._off(event, handler); }
/** Lists all connected card readers.
* @returns a promise to return a list of card reader names.
*/
enumerateReaders() {
return this.channel.send(new Request(new Command(Method.EnumerateReaders)))
.then(response => {
const list = JSON.parse(core.Utf8.fromBase64Url(response.Data || "{}"));
return JSON.parse(list.Readers || "[]");
});
}
/** Lists all inserted cards.
* @returns a promise to return a list of card information for connected cards.
*/
enumerateCards() {
return this.channel.send(new Request(new Command(Method.EnumerateCards)))
.then(response => {
const list = JSON.parse(core.Utf8.fromBase64Url(response.Data || "{}"));
const cards = JSON.parse(list.Cards || "[]");
return cards.map(s => JSON.parse(core.Utf16.fromBase64Url(s)));
});
}
/** Reads card data from a specific card.
* @param reader - a name of a card reader where the card was presented.
* @returns a promise to return a card information.
* The promise can be fulfilled but return `null` if the card has no information.
* The promise will be rejected if a card is not found or in case of a reading error.
*/
getCardInfo(reader) {
return this.channel.send(new Request(new Command(Method.GetCardInfo, core.Base64Url.fromJSON({ Reader: reader }))))
.then(response => {
const cardInfo = JSON.parse(core.Utf8.fromBase64Url(response.Data || "null"));
return cardInfo;
});
}
/** Reads a card unique identifier.
* @param reader - a name of a card reader where the card was presented.
* @returns a promise to return a card identifier.
*/
getCardUid(reader) {
return this.channel.send(new Request(new Command(Method.GetCardUID, core.Base64Url.fromJSON({ Reader: reader }))))
.then(response => {
const data = core.Base64.fromBase64Url(response.Data || "");
return data;
});
}
/** Reads card authentication data.
* @param reader - a name of a card reader where the card was presented.
* @param pin - an PIN code (for cards requiring a PIN).
* @returns a promise to return card authentication data.
* The card data is an opaque encoded string which should be sent to the server as is.
*/
getCardAuthData(reader, pin) {
return this.channel.send(new Request(new Command(Method.GetDPCardAuthData, core.Base64Url.fromJSON({ Reader: reader, PIN: pin || "" }))))
.then(response => {
const data = JSON.parse(core.Utf8.fromBase64Url(response.Data || ""));
return data;
});
}
/** Reads card enrollment data.
* @param reader - a name of a card reader where the card was presented.
* @param pin - an PIN code (for cards requiring a PIN).
* @returns a promise to return a card enrollment data.
* The card data is an opaque encoded string which should be sent to the server as is.
*/
getCardEnrollData(reader, pin) {
return this.channel.send(new Request(new Command(Method.GetDPCardEnrollData, core.Base64Url.fromJSON({ Reader: reader, PIN: pin || "" }))))
.then(response => {
const data = JSON.parse(core.Utf8.fromBase64Url(response.Data || ""));
return data;
});
}
/** Starts listening for card reader events.
* @param reader - an optional name of a card reader to listen.
* If no name is provided, the API will start listening all card readers.
*/
subscribe(reader) {
return this.channel.send(new Request(new Command(Method.Subscribe, reader ? core.Base64Url.fromJSON({ Reader: reader }) : "")))
.then();
}
/** Stop listening for card reader events.
* @param reader - an optional name of a card reader to stop listening.
* If no name is provided, the API will stop listening all card readers.
*/
unsubscribe(reader) {
return this.channel.send(new Request(new Command(Method.Unsubscribe, reader ? core.Base64Url.fromJSON({ Reader: reader }) : "")))
.then();
}
/** Converts WebSdk connectivity error to a card API event. */
onConnectionFailed() {
this.emit(new CommunicationFailed());
}
/** Converts WebSdk notification to card API events. */
processNotification(notification) {
switch (notification.Event) {
case NotificationType.ReaderConnected:
return this.emit(new DeviceConnected(notification.Reader));
case NotificationType.ReaderDisconnected:
return this.emit(new DeviceDisconnected(notification.Reader));
case NotificationType.CardInserted:
return this.emit(new CardInserted(notification.Reader, notification.Card));
case NotificationType.CardRemoved:
return this.emit(new CardRemoved(notification.Reader, notification.Card));
default:
console.log(`Unknown notification: ${notification.Event}`);
}
}
} |
JavaScript | class SamplesAcquired extends DeviceEvent {
/** Constructs a new event object.
* @param deviceUid - a fingerprint reader ID.
* @param sampleFormat - a fingerprint sample format.
* @param sampleData - raw sample data received with WebSdk notifiation.
*/
constructor(deviceUid, sampleFormat, sampleData) {
super("SamplesAcquired", deviceUid);
this.sampleFormat = sampleFormat;
this.samples = JSON.parse(sampleData);
}
} |
JavaScript | class QualityReported extends DeviceEvent {
/** Constructs a new event object.
* @param deviceUid - a fingerprint reader ID.
* @param quality - a fingerprint scan quality.
*/
constructor(deviceUid, quality) {
super("QualityReported", deviceUid);
this.quality = quality;
}
} |
JavaScript | class ErrorOccurred extends DeviceEvent {
/** Constructs a new event object.
* @param deviceUid - a fingeprint reader ID.
* @param error - an error code.
*/
constructor(deviceUid, error) {
super("ErrorOccurred", deviceUid);
this.error = error;
}
} |
JavaScript | class AcquisitionStarted extends DeviceEvent {
/** Constructs a new event object.
* @param deviceUid - a fingeprint reader ID.
*/
constructor(deviceUid) {
super("AcquisitionStarted", deviceUid);
}
} |
JavaScript | class AcquisitionStopped extends DeviceEvent {
/** Constructs a new event object.
* @param deviceUid - a fingeprint reader ID.
*/
constructor(deviceUid) {
super("AcquisitionStopped", deviceUid);
}
} |
JavaScript | class FingerprintReader extends MultiCastEventSource {
/**
* Constructs a new fingerprint reader API object.
* @param options - options for the `WebSdk` channel.
*/
constructor(options) {
super();
this.options = options;
this.channel = new Channel("fingerprints", this.options);
this.channel.onCommunicationError = this.onConnectionFailed.bind(this);
this.channel.onNotification = this.processNotification.bind(this);
}
/**
* Adds an event handler for the event.
* This is a multicast subscription, i.e. many handlers can be registered at once.
*
* @param event - a name of the event to subscribe, e.g. "SampleAcquired"
* @param handler - an event handler.
* @returns an event handler reference.
* Store the reference and pass it to the {@link FingerprintReader.off} to unsubscribe from the event.
*
* @example
* ```
* class FingerprintComponent
* {
* private reader: FingerprintReader;
*
* private onDeviceConnected = (event: DeviceConnected) => { ... };
* private onDeviceDisconnected = (event: DeviceDisconnected) => { ... };
* private onSamplesAcquired = (event: SampleAquired) => { ... };
* ...
*
* public async $onInit() {
* this.reader = new FingerprintReader();
* this.reader.on("DeviceConnected", onDeviceConnected);
* this.reader.on("DeviceDisconnected", onDeviceDisconnected);
* this.reader.on("SamplesAcquired", onSamplesAcquired);
* ...
* await this.fingerprintReader.startAcquisition(SampleFormat.Intermediate);
* }
* public async $onDestroy() {
* await this.fingerprintReader.stopAcquisition();
* this.reader.off("DeviceConnected", onDeviceConnected);
* this.reader.off("DeviceDisconnected", onDeviceDisconnected);
* this.reader.off("SamplesAcquired", onSamplesAcquired);
* ...
* // alternatively, call this.reader.off() to unsubscribe from all events at once.
* delete this.reader;
* }
* }
* ```
*/
on(event, handler) { return this._on(event, handler); }
/** Deletes an event handler for the event.
* @param event - a name of the event to subscribe.
* @param handler - an event handler added with the {@link FingerprintReader.on} method.
*/
off(event, handler) { return this._off(event, handler); }
/** Lists all connected fingerprint readers.
* @returns a promise to return a list of fingerprint reader names.
*/
enumerateDevices() {
return this.channel.send(new Request(new Command(Method$1.EnumerateDevices)))
.then(response => {
if (!response)
return [];
const deviceList = JSON.parse(core.Utf8.fromBase64Url(response.Data || "{}"));
return JSON.parse(deviceList.DeviceIDs || "[]");
});
}
/** Reads a fingerprint reader device information.
* @param deviceUid - a fingerprint reader ID.
* @returns a promise to return a device information.
* The promise can be fulfilled but return `null` if the reader provides no information.
* The promise will be rejected if a reader is not found or in case of a reading error.
*/
getDeviceInfo(deviceUid) {
return this.channel.send(new Request(new Command(Method$1.GetDeviceInfo, core.Base64Url.fromJSON({ DeviceID: deviceUid }))))
.then(response => {
const deviceInfo = JSON.parse(core.Utf8.fromBase64Url(response.Data || "null"));
return deviceInfo;
});
}
/** Activate a fingerprint acquisition mode.
* This call will produce a {@link AcquisitionStarted} event if activation was successful.
* After that the reader will wait for a finger placed on the reader.
* When a finger is placed, a {@link QualityReported} event will report a scan quality,
* and a {@link SamplesAcquired} event will return a scanned sample in case of a successful scan.
*/
startAcquisition(sampleFormat, deviceUid) {
return this.channel.send(new Request(new Command(Method$1.StartAcquisition, core.Base64Url.fromJSON({
DeviceID: deviceUid ? deviceUid : "00000000-0000-0000-0000-000000000000",
SampleType: sampleFormat,
}))))
.then();
}
/** Deactivates a fingerprint acquisition mode.
* This call will produce a {@link AcquisitionStopped} event if deactivation was successful.
* After that the reader will stop waiting for a finger.
*/
stopAcquisition(deviceUid) {
return this.channel.send(new Request(new Command(Method$1.StopAcquisition, core.Base64Url.fromJSON({
DeviceID: deviceUid ? deviceUid : "00000000-0000-0000-0000-000000000000",
}))))
.then();
}
/** Converts WebSdk connectivity error to a fingerprint API event. */
onConnectionFailed() {
this.emit(new CommunicationFailed());
}
/** Converts WebSdk notification to fingerprint API events. */
processNotification(notification) {
switch (notification.Event) {
case NotificationType$1.Completed:
const completed = JSON.parse(core.Utf8.fromBase64Url(notification.Data || ""));
return this.emit(new SamplesAcquired(notification.Device, completed.SampleFormat, completed.Samples));
case NotificationType$1.Error:
const error = JSON.parse(core.Utf8.fromBase64Url(notification.Data || ""));
return this.emit(new ErrorOccurred(notification.Device, error.uError));
case NotificationType$1.Disconnected:
return this.emit(new DeviceDisconnected(notification.Device));
case NotificationType$1.Connected:
return this.emit(new DeviceConnected(notification.Device));
case NotificationType$1.Quality:
const quality = JSON.parse(core.Utf8.fromBase64Url(notification.Data || ""));
return this.emit(new QualityReported(notification.Device, quality.Quality));
case NotificationType$1.Stopped:
return this.emit(new AcquisitionStopped(notification.Device));
case NotificationType$1.Started:
return this.emit(new AcquisitionStarted(notification.Device));
default:
console.log(`Unknown notification: ${notification.Event}`);
}
}
} |
JavaScript | class WindowsAuthClient extends MultiCastEventSource {
/**
* Constructs a new IWA API object.
* @param options - options for the `WebSdk` channel.
*/
constructor(options) {
super();
this.channel = new Channel("wia", options);
this.channel.onCommunicationError = this.onConnectionFailed.bind(this);
}
/**
* Adds an event handler for the event.
* This is a multicast subscription, i.e. many handlers can be registered at once.
*
* @param event - a name of the event to subscribe, e.g. "CommunicationFailed"
* @param handler - an event handler.
* @returns an event handler reference.
* Store the reference and pass it to the {@link WindowsAuthClient.off} to unsubscribe from the event.
*
* @example
* ```
* class IntegratedWindowsAuthComponent
* {
* private client: WindowsAuthClient;
*
* private onCommunicationFailed = (event: CommunicationFailed) => { ... }
*
* public $onInit() {
* this.client = new WindowsAuthClient();
* this.client.on("CommunicationFailed", this.onCommunicationFailed);
* }
* public $onDestroy() {
* this.client.off("CommunicationFailed", this.onCommunicationFailed);
* // alternatively, call this.reader.off() to unsubscribe from all events at once.
* delete this.client;
* }
* }
* ```
*/
on(event, handler) { return this._on(event, handler); }
/** Deletes an event handler for the event.
* @param event - a name of the event to subscribe.
* @param handler - an event handler added with the {@link WindowsAuthClient.on} method.
*/
off(event, handler) { return this._off(event, handler); }
/** Used internally. Do not call this method. */
init() {
return this.channel.send(new Request(new Command(Method$2.Init)), 3000)
.then(response => {
const data = JSON.parse(response.Data || "{}");
return { handle: data.Handle, data: data.Data };
});
}
/** Used internally. Do not call this method. */
continue(handle, data) {
return this.channel.send(new Request(new Command(Method$2.Continue, JSON.stringify({ Handle: handle, Data: data }))))
.then(response => {
const d = JSON.parse(response.Data || "{}");
return d.Data;
});
}
/** Used internally. Do not call this method. */
term(handle) {
return this.channel.send(new Request(new Command(Method$2.Term, JSON.stringify({ Handle: handle }))))
.then();
}
/** Converts WebSdk connectivity error to an IWA API event. */
onConnectionFailed() {
this.emit(new CommunicationFailed());
}
} |
JavaScript | class articles {
/**
* @param {object} req Request sent to the route
* @param {object} res Response from server
* @param {object} next If no error continue
* @returns {object} Object representing the response returned
*/
static create(req, res, next) {
const result = validate.validation.createArticle(req.body);
if (result.error) {
return Error.joiErrorHandler(res, result);
}
next();
}
/**
* @param {object} req Request sent to the route
* @param {object} res Response from server
* @param {object} next If no error continue
* @returns {object} Object representing the response returned
*/
static update(req, res, next) {
const response = validate.validation.updateArticle(req.body);
req.body = {
title: req.body.title && req.body.title.trim(),
body: req.body.body && req.body.body.trim(),
description: req.body.description && req.body.description.trim(),
readTime: req.body.body && validate.generator.readtime(req.body.body)
};
Object.keys(req.body).forEach(
key => req.body[key] || (key !== 'readTime' && delete req.body[key])
);
return !response.error ? next() : Error.joiErrorHandler(res, response);
}
/**
* @param {object} req Request sent to the route
* @param {object} res Response from server
* @param {object} next Log errors
* @returns {object} Object representing the response returned
*/
static slug(req, res, next) {
const response = validate.validation.articleSlug(req.params);
if (response.error) {
Error.joiErrorHandler(res, response);
} else {
next();
}
}
/**
* Validate pagination queries
* @param {object} req Request sent to the route
* @param {object} res Response from server
* @param {object} next Log errors
* @returns {object} Object representing the response returned
*/
static pagination(req, res, next) {
const duplicated = validate.parameters.duplication(req.query);
if (Object.keys(duplicated).length) {
return res.status(400).send({ errors: duplicated });
}
const { error } = validate.validation.queryParameters(req.query);
return !error ? next() : Error.joiErrorHandler(res, { error });
}
} |
JavaScript | class SelectSidebarInput extends AbstractSidebarInput {
constructor(settings) {
super(settings);
this.options = settings.options;
}
/**
* Static function returns identifier of the input type
*/
static ID() {
return ID;
}
/**
* It returns select element.
*/
create() {
if(this.element == undefined) {
// create select element
this.element = document.createElement('select');
this.element.onchange = this.action;
// append options
let option;
for(let i = 0; i < this.options.length; i++) {
option = this.element.appendChild(document.createElement("option"));
option.setAttribute("value", this.options[i]);
option.innerHTML = this.options[i];
}
}
return this.element;
}
/**
* It returns value of the select element.
*/
getValue() {
return this.element.value;
}
/**
* It sets value of the select element.
*
* @param {*} value
*/
setValue(value) {
this.element.value = value;
}
} |
JavaScript | class NavigationTemplate extends Template {
/**
* Creates a nav from an object
* @param {Object} object
* @return {Array<Array<string, string>>}
*/
static navFromObject(object) {
return Object
.keys(object)
.map(sectionName => [
sectionName,
Object
.keys(object[sectionName])
.map(itemName => [itemName])
])
}
/**
* Takes dyadic-tuple in form of array. Followed by elements and if the
* second element is href, this is used when emitting clicks.
* @param {Array<Array<string, string>>} nav Navigation data
* @param {Object} opts initialization options
* @param {?Array<?string, ?string>} firstItem - Array in form of section name
* and item name.
*/
constructor(nav, {
firstItem: [
firstSectionName = nav[0][0],
firstItemName = nav[0][1][0][0]
] = []
} = {}) {
const root = <nav class="sidebar-navigation"/>;
super(root);
let navigationController;
const navigationSubject = new BehaviorSubject(null)
.pipe(
filter(value => value),
distinctUntilChanged());
const sections = nav.map(([sectionName, items]) => {
const sectionItems = items.map(([itemName]) => {
const link = <a class="sidebar-navigation__link">{ itemName }</a>;
fromEvent(link, 'click')
.pipe(
mapTo([ sectionName, itemName ]))
.subscribe(navigationSubject);
navigationSubject
.pipe(
map(([section, item]) => section === sectionName && item === itemName),
distinctUntilChanged())
.subscribe(isCurrentLinkSelected => {
link.classList.toggle(ACTIVE_LINK_OPEN, isCurrentLinkSelected);
});
return (
<li>
{ link }
</li>
);
});
const sublist = <ul>{ sectionItems }</ul>;
const section = <a class="sidebar-navigation__title">{ sectionName }</a>;
navigationSubject
.pipe(
filter(([section]) => section === sectionName),
distinctUntilChanged())
.subscribe(() => {
const openSections = [...navigationController.getOpenSections()];
// If we navigate to a non-open link, then we'll still open
if (!openSections.includes(section)) {
navigationController.beginQueue();
navigationController.toggleSection(sublist, true);
navigationController.finishQueue();
}
});
return (
<li>
{ section }
{ sublist }
</li>
);
});
root.appendChild(
<ul>
{ sections }
</ul>
);
navigationController = new SidebarNavigationViewController(root);
/** @private */
this.firstItem = [firstSectionName, firstItemName];
/** @private */
this.navigationSubject = navigationSubject;
}
/**
* Called on didLoad
*/
didLoad() {
super.didLoad();
this.navigationSubject.next(this.firstItem);
}
/**
* Returns navigation subject. Emits non-duplicates in form of
* like [section, item].
* @return {BehaviorSubject<Array<string, string>>}
*/
observeNavigation() {
return this.navigationSubject;
}
} |
JavaScript | class Bogosort {
_isSorted(arr) {
for (var i = 1; i < arr.length; i++) {
if (arr[i - 1] > arr[i]) {
return false;
}
}
return true;
};
_shuffle(arr) {
var count = arr.length, temp, index;
while (count > 0) {
index = Math.floor(Math.random() * count);
count--;
temp = arr[count];
arr[count] = arr[index];
arr[index] = temp;
}
return arr;
}
sort(arr) {
var sorted = false;
while (!sorted) {
arr = this._shuffle(arr);
sorted = this._isSorted(arr);
}
return arr;
}
} |
JavaScript | class UNUSEDEzsigndocumentEditObjectV1Request {
/**
* Constructs a new <code>UNUSEDEzsigndocumentEditObjectV1Request</code>.
* Request for the /1/object/ezsigndocument/editObject API Request
* @alias module:eZmaxAPI/model/UNUSEDEzsigndocumentEditObjectV1Request
*/
constructor() {
UNUSEDEzsigndocumentEditObjectV1Request.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>UNUSEDEzsigndocumentEditObjectV1Request</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:eZmaxAPI/model/UNUSEDEzsigndocumentEditObjectV1Request} obj Optional instance to populate.
* @return {module:eZmaxAPI/model/UNUSEDEzsigndocumentEditObjectV1Request} The populated <code>UNUSEDEzsigndocumentEditObjectV1Request</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new UNUSEDEzsigndocumentEditObjectV1Request();
if (data.hasOwnProperty('objEzsigndocument')) {
obj['objEzsigndocument'] = EzsigndocumentRequest.constructFromObject(data['objEzsigndocument']);
}
}
return obj;
}
/**
* @return {module:eZmaxAPI/model/EzsigndocumentRequest}
*/
getObjEzsigndocument() {
return this.objEzsigndocument;
}
/**
* @param {module:eZmaxAPI/model/EzsigndocumentRequest} objEzsigndocument
*/
setObjEzsigndocument(objEzsigndocument) {
this['objEzsigndocument'] = objEzsigndocument;
}
} |
JavaScript | class ChatButton extends Component {
constructor( props ) {
super( props );
this.state = {
opened: false,
nMessages: 0
};
}
componentDidMount() {
const session = this.context;
this.unsubscribe = session.subscribe( ( type, value ) => {
if (
( type === 'self_has_joined_chat' || type === 'chat_history' ) &&
value.name === this.props.for
) {
this.setState({
opened: true,
nMessages: value.messages.length
});
}
else if ( value === this.props.for ) {
const chat = session.getChat( this.props.for );
if ( !chat || type === 'self_has_left_chat' ) {
this.setState({
opened: false
});
}
else if ( type === 'chat_message' ) {
this.setState({
nMessages: this.state.nMessages + 1
});
}
else if ( type === 'own_chat_message' ) {
this.setState({
nMessages: this.state.nMessages + 1
});
}
else if ( type === 'removed_chat' ) {
this.setState({
opened: false
});
}
this.forceUpdate();
}
});
}
componentWillUnmount() {
this.unsubscribe();
}
handleClick = () => {
debug( 'Handle click to join chat...' );
const session = this.context;
let opened = this.state.opened;
this.setState({
opened: !opened
}, () => {
if ( !opened ) {
debug( `Should join chat for component with id '${this.props.for}'...` );
session.joinChat( this.props.for );
} else {
debug( `Should leave chat for component with id '${this.props.for}'...` );
session.leaveChat( this.props.for );
}
});
}
render() {
const nMessages = this.state.nMessages;
let button = <Button
variant="secondary"
size={this.props.size}
onClick={this.handleClick}
>
<span style={{ pointerEvents: 'none' }} >{this.state.opened ? 'Leave Chat' : 'Join Chat' }</span>
{ nMessages ? <Badge variant="dark" style={{ marginLeft: '5px', fontSize: '10px', pointerEvents: 'none' }}>{nMessages}</Badge> : null }
</Button>;
if ( this.props.showTooltip ) {
button = <Tooltip
tooltip={`${this.state.opened ? 'Leave' : 'Join'} chat with ID ${this.props.for}`}
placement="top"
>
{button}
</Tooltip>;
}
return (
<Gate user>
{button}
</Gate>
);
}
} |
JavaScript | class ECPair {
constructor(__D, __Q,) {
this.__D = __D;
this.__Q = __Q;
this.compressed = false;
if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed);
}
get privateKey() {
return this.__D;
}
get publicKey() {
if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed);
return this.__Q;
}
} |
JavaScript | class CaptchaAction {
/**@return{Object}*/static get $object() {return {schema: "https://celastrinajs/schema/v1.0.0/captcha/CaptchaAction#",
type: "celastrinajs.captcha.CaptchaAction"};}
/**
* @param {number} [timeout=getDefaultTimeout()]
*/
constructor(timeout = getDefaultTimeout()) {
/**@type{number}*/this._timeout = timeout;
}
/**@return{number}*/get timeout() {return this._timeout;}
/**@param{number}timeout*/set timeout(timeout) {this._timeout = getDefaultTimeout(timeout);}
/**
* @param {Assertion} assertion
* @return {Promise<boolean>}
* @abstract
*/
async isHuman(assertion) {throw CelastrinaError.newError("Not Implemented.", 501);}
} |
JavaScript | class GoogleReCaptchaActionV2 extends CaptchaAction {
/**@return{Object}*/static get $object() {return {schema: "https://celastrinajs/schema/v1.0.0/captcha/GoogleReCaptchaActionV2#",
type: "celastrinajs.captcha.GoogleReCaptchaActionV2"};}
static AXIOS_TIMEOUT_CODE = "ECONNABORTED";
/**
* @param {string} secret
* @param {HTTPParameter} [parameter=new HeaderParameter()]
* @param {string} [name="x-celastrinajs-captcha-token"]
* @param {number} [timeout=getDefaultTimeout()]
* @param {string} [url="https://www.google.com/recaptcha/api/siteverify"]
* @param {boolean} [assumeHumanOnTimeout=true]
*/
constructor(secret, parameter = new HeaderParameter(), name = "x-celastrinajs-captcha-token",
timeout = getDefaultTimeout(), url = "https://www.google.com/recaptcha/api/siteverify",
assumeHumanOnTimeout = true) {
super(timeout);
if(typeof secret !== "string" || secret.trim().length === 0)
throw CelastrinaValidationError.newValidationError("Argument 'secret' is required.", "secret");
if(!instanceOfCelastrinaType(HTTPParameter, parameter))
throw CelastrinaValidationError.newValidationError("Argument 'parameter' is required and must be of type HTTPParameter.", "parameter");
if(typeof name !== "string" || name.trim().length === 0)
throw CelastrinaValidationError.newValidationError("Argument 'name' is required.", "name");
if(typeof url !== "string" || url.trim().length === 0)
throw CelastrinaValidationError.newValidationError("Argument 'url' is required.", "url");
/**@type{string}*/this._url = url;
/**@type{string}*/this._secret = secret;
/**@type{HTTPParameter}*/this._parameter = parameter;
/**@type{string}*/this._name = name;
/**@type{boolean}*/this._assumeHumanOnTimeout = assumeHumanOnTimeout;
}
/**@return{string}*/get url() {return this._url;}
/**@param{string}url*/set url(url) {
if(typeof url !== "string" || url.trim().length === 0) url = "https://www.google.com/recaptcha/api/siteverify";
this._url = url;
}
/**@type{HTTPParameter}*/get parameter() {return this._parameter;}
/**@param{HTTPParameter}parameter*/set parameter(parameter) {
if(!instanceOfCelastrinaType(HTTPParameter, parameter))
this._parameter = new HeaderParameter();
else this._parameter = parameter;
}
/**@returns{boolean}*/get assumeHumanOnTimeout() {return this._assumeHumanOnTimeout;}
/**@param{boolean}assume*/set assumeHumanOnTimeout(assume) {this._assumeHumanOnTimeout = assume;}
/**@return{string}*/get secret() {return this._secret;}
/**@param{string}secret*/set secret(secret) {
if(typeof secret !== "string" || secret.trim().length === 0)
throw CelastrinaValidationError.newValidationError("Argument 'secret' is required.", "secret");
this._secret = secret;
}
/**@return{string}*/get name() {return this._name;}
/**@param{string}name*/set name(name) {this._name = name;}
/**
* @param {Assertion} assertion
* @param {_reCAPTCHAResponseV2 | _reCAPTCHAResponseV3} response
* @return {Promise<boolean>}
*/
async _handleResponse(assertion, response) {
let _isHuman = response.success;
if(!_isHuman) {
if(response.hasOwnProperty("error-codes") && Array.isArray(response["error-codes"]) &&
response["error-codes"].length > 0) {
assertion.context.log("'" + assertion.subject.id + "' failed V2 reCAPTCHA verification with error codes: " +
response["error-codes"], LOG_LEVEL.ERROR,
"GoogleReCaptchaActionV2._handleResponse(assertion, response)");
}
}
return _isHuman;
}
/**
* @param {Assertion} assertion
* @return {Promise<boolean>}
* @private
*/
async isHuman(assertion) {
let _result = false;
try {
/**@type{string}*/let _token = await this._parameter.getParameter(/**@type{HTTPContext}*/assertion.context, this._name);
if(_token != null) {
let _config = {
params: {
secret: this._secret,
response: _token
},
timeout: this._timeout,
headers: {"content-type": "application/x-www-form-urlencoded"}
}
/**@type{axios.AxiosResponse<_reCAPTCHAResponseV2>}*/let _response = await axios.post(this._url,
null, _config);
if(_response.status === 200) _result = await this._handleResponse(assertion, _response.data);
else assertion.context.log("Invalid status code '" + _response.status + "' returned: " + _response.statusText,
LOG_LEVEL.ERROR, "GoogleReCaptchaActionV2.isHuman(assertion)");
}
else assertion.context.log("No token found for '" + this._name + "' using " + this._parameter.type + " parameter.",
LOG_LEVEL.WARN, "GoogleReCaptchaActionV2.isHuman(assertion)");
return _result;
}
catch(/**@type{axios.AxiosError}*/exception) {
if(exception.isAxiosError) {
if(exception.code === GoogleReCaptchaActionV2.AXIOS_TIMEOUT_CODE) {
assertion.context.log("[" + assertion.subject.id + "] Request aborted, " + exception.message + ".", LOG_LEVEL.WARN,
"GoogleReCaptchaActionV2.isHuman(assertion)");
assertion.context.log("Request timed out for subject '" + assertion.subject.id + "'. Assume human request '" +
this._assumeHumanOnTimeout + "'.", LOG_LEVEL.WARN,
"GoogleReCaptchaActionV2.isHuman(assertion)");
return this._assumeHumanOnTimeout;
}
else if(exception.hasOwnProperty("response")) {
assertion.context.log("Invalid status code '" + exception.response.status + "' returned, expected 200: " +
exception.response.statusText, LOG_LEVEL.THREAT, "GoogleReCaptchaActionV2.isHuman(assertion)");
return false;
}
}
else throw CelastrinaError.wrapError(exception);
}
}
} |
JavaScript | class GoogleReCaptchaActionV3 extends GoogleReCaptchaActionV2 {
/**@return{Object}*/static get $object() {return {schema: "https://celastrinajs/schema/v1.0.0/captcha/GoogleReCaptchaActionV3#",
type: "celastrinajs.captcha.GoogleReCaptchaActionV3"};}
/**
* @param {string} secret
* @param {number} [score=.8]
* @param {Array<string>} [actions=[]]
* @param {HTTPParameter} [parameter=new HeaderParameter()]
* @param {string} [name="x-celastrinajs-captcha-token"]
* @param {number} [timeout=getDefaultTimeout()]
* @param {string} [url="https://www.google.com/recaptcha/api/siteverify"]
* @param {boolean} [assumeHumanOnTimeout=true]
*/
constructor(secret, score = .8, actions = [], parameter = new HeaderParameter(),
name = "x-celastrinajs-captcha-token", timeout = getDefaultTimeout(),
url = "https://www.google.com/recaptcha/api/siteverify",
assumeHumanOnTimeout = true) {
super(secret, parameter, name, timeout, url, assumeHumanOnTimeout);
this._score = score;
this._actions = actions;
}
/**@returns{number}*/get score() {return this._score;}
/**@param{number}score*/set score(score) {this._score = score;}
/**@returns{Array<string>}*/get actions() {return this._actions;}
/**@param{Array<string>}actions*/set actions(actions) {this._actions = actions;}
/**
* @param {string} action
* @return {boolean}
*/
isActionValid(action) {
if(this._actions.length > 0) return this._actions.includes(action);
return true;
}
/**
* @param {Assertion} assertion
* @param {_reCAPTCHAResponseV2 | _reCAPTCHAResponseV3} response
* @return {Promise<boolean>}
*/
async _handleResponse(assertion, response) {
let _result = false;
if(await super._handleResponse(assertion, response)) {
if(this.isActionValid(response.action)) {
if(response.score >= this._score) _result = true;
else {
assertion.context.log("'" + assertion.subject.id + "' failed to meet or exceed the threshold of " + this._score +
" with a score of " + response.score + ".", LOG_LEVEL.THREAT, "GoogleReCaptchaActionV3._handleResponse(assertion, response)");
}
}
else assertion.context.log("'" + assertion.subject.id + "' specified an unsupported action '" + response.action + "'.",
LOG_LEVEL.THREAT, "GoogleReCaptchaActionV3._handleResponse(assertion, response)");
}
else assertion.context.log("'" + assertion.subject.id + "' has an invalid token response, unable to complete V3 verification.", LOG_LEVEL.THREAT,
"GoogleReCaptchaActionV3._handleResponse(assertion, response)");
return _result;
}
} |
JavaScript | class CaptchaAuthenticator extends Authenticator {
/**@return{Object}*/static get $object() {return {schema: "https://celastrinajs/schema/v1.0.0/captcha/CaptchaAuthenticator#",
type: "celastrinajs.captcha.CaptchaAuthenticator"};}
constructor(captcha, assignments = ["human"]) {
super("CaptchaAuthenticator");
if(!instanceOfCelastrinaType(CaptchaAction, captcha))
throw CelastrinaValidationError.newValidationError("Argument 'captcha' is required and must be an instance of '" +
CaptchaAction.$object.type + "'.", "captcha");
/**@type{CaptchaAction}*/this._captcha = captcha;
/**@type{Array<string>}*/this._assignments = assignments;
}
/**@return{CaptchaAction}*/get captcha() {return this._captcha;}
/**@return{Array<string>}*/get assignments() {return this._assignments;}
/**
* @param {Assertion} assertion
* @return {Promise<boolean>}
* @abstract
*/
async _authenticate(assertion) {
try {
let _human = await this._captcha.isHuman(/**@type{Assertion}*/assertion);
if(_human) assertion.assert(this._name, true, this._assignments);
else {
assertion.context.log(
"'" + assertion.subject.id + "' failed CAPTCHA verification.\r\n\tNo offense, but you could be a bot!\r\n" +
"\tMaybe in the future humanity could be more accepting of you, but for now, stop buying all our GPU's. \r\n" +
"\tOh and, \"ALL HAIL THE MACHINES!\", in the likely event you win the Machine Wars!",
LOG_LEVEL.THREAT, "CaptchaAuthenticator._authenticate(assertion)");
assertion.assert(this._name, false);
}
return _human;
}
catch(exception) {
assertion.context.log("Exception encountered while verifying subject '" + assertion.subject.id + "': " +
exception, LOG_LEVEL.THREAT, "CaptchaAuthenticator._authenticate(assertion)");
assertion.assert(this._name, false, null, exception);
}
}
} |
JavaScript | class GoogleReCaptchaParser extends AttributeParser {
/**@return{Object}*/static get $object() {return {schema: "https://celastrinajs/schema/v1.0.0/captcha/GoogleReCaptchaParser#",
type: "celastrinajs.captcha.GoogleReCaptchaParser"};}
/**
* @param {AttributeParser} [link=null]
* @param {string} [version="1.0.0"]
*/
constructor(link = null, version = "1.0.0") {
super("GoogleReCaptcha", link, version);
}
/**
* @param _GoogleReCaptcha
* @return {Promise<CaptchaAction>}
* @private
*/
async _create(_GoogleReCaptcha) {
if(!_GoogleReCaptcha.hasOwnProperty("version") ||
(_GoogleReCaptcha.version !== "v2" && _GoogleReCaptcha.version !== "v3"))
throw CelastrinaValidationError.newValidationError(
"Argument 'version' is required and must be 'v2' or 'v3'.", "_GoogleReCaptcha.version");
if(!_GoogleReCaptcha.hasOwnProperty("secret") || typeof _GoogleReCaptcha.secret !== "string" ||
_GoogleReCaptcha.secret.trim().length === 0)
throw CelastrinaValidationError.newValidationError(
"Argument 'secret' is required.", "_GoogleReCaptcha.secret");
let _secret = _GoogleReCaptcha.secret;
let _url = "https://www.google.com/recaptcha/api/siteverify";
let _timeout = getDefaultTimeout();
let _parameter = new HeaderParameter();
let _name = "x-celastrinajs-captcha-token";
let _assume = true;
if(_GoogleReCaptcha.hasOwnProperty("url") && typeof _GoogleReCaptcha.url === "string" &&
_GoogleReCaptcha.url.trim().length > 0)
_url = _GoogleReCaptcha.url;
if(_GoogleReCaptcha.hasOwnProperty("timeout") && typeof _GoogleReCaptcha.timeout === "number")
_timeout = _GoogleReCaptcha.timeout;
if(_GoogleReCaptcha.hasOwnProperty("assumeHumanOnTimeout") && typeof _GoogleReCaptcha.assumeHumanOnTimeout === "boolean")
_assume = _GoogleReCaptcha.assumeHumanOnTimeout;
if(_GoogleReCaptcha.hasOwnProperty("parameter")) {
if(!instanceOfCelastrinaType(HTTPParameter, _GoogleReCaptcha.parameter))
throw CelastrinaValidationError.newValidationError(
"Argument 'parameter' is required and must be of type HTTPParameter.", "_GoogleReCaptcha.parameter");
else _parameter = _GoogleReCaptcha.parameter;
}
if(_GoogleReCaptcha.hasOwnProperty("name")) {
if(!_GoogleReCaptcha.hasOwnProperty("name") || typeof _GoogleReCaptcha.name !== "string" ||
_GoogleReCaptcha.name.trim().length === 0)
throw CelastrinaValidationError.newValidationError(
"Argument 'name' is required.", "_GoogleReCaptcha.name");
else _name = _GoogleReCaptcha.name.trim();
}
if(_GoogleReCaptcha.version === "v3") {
let _score = .8;
if(_GoogleReCaptcha.hasOwnProperty("score")) {
if(typeof _GoogleReCaptcha.score !== "number")
throw CelastrinaValidationError.newValidationError(
"Argument 'score' must be a number.", "_GoogleReCaptcha.score");
if(_GoogleReCaptcha.score < 0 || _GoogleReCaptcha.score > 1)
throw CelastrinaValidationError.newValidationError(
"Argument 'score' is a percent and must be between 0 and 1.", "_GoogleReCaptcha.score");
_score = _GoogleReCaptcha.score;
}
let _actions = [];
if(_GoogleReCaptcha.hasOwnProperty("actions")) {
if(!Array.isArray(_GoogleReCaptcha.actions))
throw CelastrinaValidationError.newValidationError(
"Argument 'actions' must of type Array<string>.", "_GoogleReCaptcha.actions");
else _actions = _GoogleReCaptcha.actions;
}
return new GoogleReCaptchaActionV3(_secret, _score, _actions, _parameter, _name, _timeout, _url, _assume);
}
else
return new GoogleReCaptchaActionV2(_secret, _parameter, _name, _timeout, _url, _assume);
}
} |
JavaScript | class CaptchaConfigParser extends ConfigParser {
/**@return{Object}*/static get $object() {return {schema: "https://celastrinajs/schema/v1.0.0/captcha/CaptchaConfigParser#",
type: "celastrinajs.captcha.CaptchaConfigParser"};}
/**
* @param {ConfigParser} [link=null]
* @param {string} [version="1.0.0"]
*/
constructor(link = null, version = "1.0.0") {
super("Captcha", link, version);
}
/**
* @param {*} _Captcha
* @return {Promise<void>}
* @private
*/
async _create(_Captcha) {
/**@type{CaptchaAddOn}*/let _addon = this._addons.get(CaptchaAddOn);
if(instanceOfCelastrinaType(CaptchaAddOn, _addon)) {
if(!_Captcha.hasOwnProperty("captcha") || !instanceOfCelastrinaType(CaptchaAction, _Captcha.captcha))
throw CelastrinaValidationError.newValidationError(
"Attribute 'captcha' is required. Please add a captcha of type CaptchaAction.", "_Captcha.captcha");
_addon.captcha = _Captcha.captcha;
let _assignments = ["human"];
if(_Captcha.hasOwnProperty("assignments")) {
if(!Array.isArray(_Captcha.assignments))
throw CelastrinaValidationError.newValidationError(
"Attribute 'assignments' must be an array of strings.", "_Captcha.assignments");
_assignments = _Captcha.assignments;
}
_addon.assignments = _assignments;
}
else
throw CelastrinaError.newError("Missing required Add-On '" + CaptchaAddOn.name + "'.");
}
} |
JavaScript | class CaptchaAddOn extends AddOn {
/**@return{Object}*/static get $object() {return {schema: "https://celastrinajs/schema/v1.0.0/captcha/CaptchaAddOn#",
type: "celastrinajs.captcha.CaptchaAddOn",
addOn: "celastrinajs.addon.captcha"};}
constructor() {
super([HTTPAddOn.$object.addOn], []);
/**@type{CaptchaAction}*/this._captcha = null;
this._assignments = ["human"];
}
/**@returns{CaptchaAction}*/get captcha() {return this._captcha;}
/**@param{CaptchaAction}action*/set captcha(action) {this._captcha = action;}
/**@returns{Array<string>}*/get assignments() {return this._assignments;}
/**@param{Array<string>}assignments*/set assignments(assignments) {this._assignments = assignments;}
/**
* @return {ConfigParser}
*/
getConfigParser() {
return new CaptchaConfigParser();
}
/**
* @return {AttributeParser}
*/
getAttributeParser() {
return new GoogleReCaptchaParser();
}
/**
* @param {Object} azcontext
* @param {Object} config
* @return {Promise<void>}
*/
async initialize(azcontext, config) {
let _captcha = new CaptchaAuthenticator(this._captcha, this._assignments);
/**@type{Sentry}*/let _sentry = config[Configuration.CONFIG_SENTRY];
_sentry.addAuthenticator(_captcha);
}
} |
JavaScript | class LocatorAbstract extends LocatorInterface {
/**
* @inheritdoc
*/
getIdPropName() {
return 'id';
}
/**
* @inheritdoc
*/
getModelId(model) {
if (model === null || typeof model !== 'object') {
throw new Error('argument is not Object');
}
return model[this.getIdPropName()];
}
/**
* @inheritdoc
*/
isEmptyModelId(model) {
const id = this.getModelId(model);
return id === null || typeof id === 'undefined' || (typeof id === 'string' && id.length === 0);
}
/**
* @inheritdoc
*/
getInputTransformerClass() {
return InputTransformer;
}
/**
* @inheritdoc
*/
getOutputTransformerClass() {
return OutputTransformer;
}
} |
JavaScript | class LinkButton extends UpdatingButton {
/**
* Constructor
*/
constructor( toolbar ) {
super( toolbar, OPTIONS );
this.on( "click", function() {
this.toolbar.editor.toggleParser.actions.link.toggle();
});
}
/**
* Update override
*/
update( selectionState ) {
this.disable( !selectionState.canLink );
this.activate( selectionState.isLink );
}
} |
JavaScript | class SuggestionField extends Component {
state = {
input: '',
searchResult: [],
searchOnlyUsers: this.props.searchOnlyUsers,
searchOnlyFeedbackRecipients: this.props.searchOnlyFeedbackRecipients,
lastSearch: '',
errorText: undefined,
}
debouncedSearch = debounce(this.search.bind(this), searchDelay)
search(input) {
const doSearch =
!this.state.searchResult.find(
result => result.displayName === input
) &&
input !== '' &&
input.length >= minCharLength
if (doSearch) {
const {
feedbackRecipientsId,
searchOnlyUsers,
searchOnlyFeedbackRecipients,
dhis2CoreVersion,
} = this.props
api.searchRecipients({
searchValue: input,
searchOnlyUsers,
searchOnlyFeedbackRecipients,
feedbackRecipientsId,
dhis2CoreVersion,
}).then(({ users, userGroups, organisationUnits }) => {
const addType = type => result => ({ ...result, type })
let internalSearchResult = users.map(addType('user'))
if (!this.state.searchOnlyUsers) {
internalSearchResult = internalSearchResult
.concat(userGroups.map(addType('userGroup')))
.concat(
organisationUnits.map(addType('organisationUnit'))
)
}
this.setState({
searchResult: internalSearchResult,
errorText:
internalSearchResult.length === 0
? i18n.t('No results found')
: undefined,
})
})
} else {
this.setState({
lastSearch: input,
searchResult:
(this.state.lastSearch !== '' && input === '') ||
input.length < minCharLength
? []
: this.state.searchResult,
errorText:
input !== '' && input.length < minCharLength
? i18n.t(
`Please enter at least ${minCharLength} characters`
)
: this.state.searchWarning,
})
}
}
onSuggestionClick = chip => {
if (this.props.onSuggestionClick !== undefined) {
this.props.onSuggestionClick(chip)
} else {
this.wipeInput()
this.debouncedSearch('')
const doInsert = !this.props.recipients.find(
recipient => recipient.id === chip.id
)
doInsert &&
this.props.updateRecipients([
...this.props.recipients,
this.state.searchResult.find(
result => result.id === chip.id
),
])
}
}
onRemoveChip = id => {
this.props.updateRecipients(
this.props.recipients.filter(recipient => recipient.id !== id)
)
}
wipeInput = () => {
this.setState({
input: '',
searchResult: [],
})
}
updateInput = input => {
this.debouncedSearch(input)
this.setState({
input,
})
}
render() {
return (
<div
style={{ ...this.props.style, height: this.props.inputHeight }}
>
<ChipInput
style={{ marginBottom: 16 }}
disabled={
this.props.disabled === undefined
? false
: this.props.disabled
}
errorText={this.props.errorText || this.state.errorText}
value={this.props.recipients}
fullWidth
openOnFocus
searchText={this.state.input}
floatingLabelText={this.props.label}
dataSource={this.state.searchResult}
dataSourceConfig={{ text: 'displayName', value: 'id' }}
onUpdateInput={this.updateInput}
onRequestAdd={chip => this.onSuggestionClick(chip)}
onRequestDelete={id => this.onRemoveChip(id)}
/>
</div>
)
}
} |
JavaScript | class Node {
constructor(location, parent) {
this.location = location;
this.children = new Map();
this.files = new Map();
this.parent = parent;
}
/**
* Checks if the child Node exists
*
* @method has
* @param {String} key
* @return {Boolean}
*/
has(key) {
assert(typeof key === 'string', 'Key must be a string');
return this.children.has(key);
}
/**
* Returns a child Node instance with given folder
* name.
*
* If the child Node does not exists, an Error is raised.
*
* @method get
* @param {String} key
* @return {Node}
*/
get(key) {
assert(typeof key === 'string', 'Key must be a string');
if (this.has(key)) {
return this.children.get(key);
}
throw new Error(`No node with key '${key}' can be found in ${this.location}`);
}
/**
* Requres a Node.js module for a given file name.
*
* If no arguments are present, `index.js` file is required.
*
* If the file does not exists, an Error is raised.
*
* @method require
* @param {String} name
* @return {*}
*/
require(name) {
if (arguments.length === 0) {
return this.require('index');
}
assert(typeof name === 'string', 'File name must be a string');
if (this.files.has(name)) {
const location = this.files.get(name);
return require(location);
}
if (this.children.has(name)) {
const child = this.get(name);
return child.require();
}
throw new Error(`No file or child Node with name '${name}' can be found in ${this.location}`);
}
/**
* Creates a new child Node for given folder location
* and name.
*
* @method child
* @param {String} location
* @param {String} name
* @return {Node}
*/
child(location, name) {
assert(!this._isDestroyed, 'Can not create a child Node on a destroyed Node');
const child = new Node(location, this);
debug(`Created Child with name ${name} in ${this.location}`);
this.children.set(name, child);
child.traverse();
return child;
}
/**
* Traverses through the file system in search for file
* and subfolders.
*
* @method traverse
*/
traverse() {
assert(!this._isDestroyed, 'Can not traverse through a destroyed Node');
const location = path.resolve(this.location);
const stats = getStats(location);
if (stats) {
assert(`Location ${location} must be a directory.`, stats.isDirectory());
handleDirectory(this, location);
}
}
/**
* Destroys the Node instace by cleaning all the
* child Nodes and Files
*
* @method destroy
*/
destroy() {
if (this._isDestroyed) {
return;
}
this.children.forEach((child) => child.destroy());
this.children.clear();
this.files.clear();
this.location = null;
this.parent = null;
this.children = null;
this.files = null;
this._isDestroyed = true;
}
} |
JavaScript | class StdinDiscarder {
#requests = 0;
#mutedStream = new BufferListStream();
#ourEmit;
#rl;
constructor() {
this.#mutedStream.pipe(process.stdout);
const self = this; // eslint-disable-line unicorn/no-this-assignment
this.#ourEmit = function (event, data, ...args) {
const {stdin} = process;
if (self.#requests > 0 || stdin.emit === self.#ourEmit) {
if (event === 'keypress') { // Fixes readline behavior
return;
}
if (event === 'data' && data.includes(ASCII_ETX_CODE)) {
process.emit('SIGINT');
}
Reflect.apply(self.#ourEmit, this, [event, data, ...args]);
} else {
Reflect.apply(process.stdin.emit, this, [event, data, ...args]);
}
};
}
start() {
this.#requests++;
if (this.#requests === 1) {
this._realStart();
}
}
stop() {
if (this.#requests <= 0) {
throw new Error('`stop` called more times than `start`');
}
this.#requests--;
if (this.#requests === 0) {
this._realStop();
}
}
// TODO: Use private methods when targeting Node.js 14.
_realStart() {
// No known way to make it work reliably on Windows
if (process.platform === 'win32') {
return;
}
this.#rl = readline.createInterface({
input: process.stdin,
output: this.#mutedStream,
});
this.#rl.on('SIGINT', () => {
if (process.listenerCount('SIGINT') === 0) {
process.emit('SIGINT');
} else {
this.#rl.close();
process.kill(process.pid, 'SIGINT');
}
});
}
_realStop() {
if (process.platform === 'win32') {
return;
}
this.#rl.close();
this.#rl = undefined;
}
} |
JavaScript | class SVG extends Graphics
{
constructor(svg)
{
super();
if (svg)
{
this.drawSVG(svg);
}
}
/**
* Draw an SVG element.
* @method PIXI.SVG#drawSVG
* @param {SVGSVGElement|SVGElement|string} svg - Inline SVGElement `<svg>` or buffer.
* @return {PIXI.SVG} Element suitable for chaining.
*/
drawSVG(svg)
{
if (typeof svg === 'string')
{
const div = document.createElement('div');
div.innerHTML = svg.trim();
svg = div.querySelector('svg');
}
if (!svg)
{
throw new Error('Missing <svg> element in SVG constructor');
}
this._svgFill(svg);
this._svgChildren(svg.children);
return this;
}
/**
* Create a PIXI Graphic from SVG element
* @private
* @method
* @param {Array<*>} children - Collection of SVG nodes
* @param {Boolean} [inherit=false] Whether to inherit fill settings.
*/
_svgChildren(children, inherit = false)
{
for (let i = 0; i < children.length; i++)
{
const child = children[i];
this._svgFill(child, inherit);
switch (child.nodeName.toLowerCase())
{
case 'path': {
this._svgPath(child);
break;
}
case 'circle':
case 'ellipse': {
this._svgCircle(child);
break;
}
case 'rect': {
this._svgRect(child);
break;
}
case 'polygon': {
this._svgPoly(child, true);
break;
}
case 'polyline': {
this._svgPoly(child);
break;
}
case 'g': {
break;
}
default: {
// eslint-disable-next-line no-console
console.info(`[PIXI.SVG] <${child.nodeName}> elements unsupported`);
break;
}
}
this._svgChildren(child.children, true);
}
}
/**
* Convert the Hexidecimal string (e.g., "#fff") to uint
* @private
* @method
*/
_hexToUint(hex)
{
if (hex[0] === '#')
{
// Remove the hash
hex = hex.substr(1);
// Convert shortcolors fc9 to ffcc99
if (hex.length === 3)
{
hex = hex.replace(/([a-f0-9])/ig, '$1$1');
}
return parseInt(hex, 16);
}
const { r, g, b } = color(hex).toRgb();
return (r << 16) + (g << 8) + b;
}
/**
* Render a <ellipse> element or <circle> element
* @private
* @method
* @param {SVGCircleElement} node
*/
_svgCircle(node)
{
let heightProp = 'r';
let widthProp = 'r';
const isEllipse = node.nodeName === 'elipse';
if (isEllipse)
{
heightProp += 'x';
widthProp += 'y';
}
const width = parseFloat(node.getAttribute(widthProp));
const height = parseFloat(node.getAttribute(heightProp));
const cx = node.getAttribute('cx');
const cy = node.getAttribute('cy');
let x = 0;
let y = 0;
if (cx !== null)
{
x = parseFloat(cx);
}
if (cy !== null)
{
y = parseFloat(cy);
}
if (!isEllipse)
{
this.drawCircle(x, y, width);
}
else
{
this.drawEllipse(x, y, width, height);
}
}
/**
* Render a <rect> element
* @private
* @method
* @param {SVGRectElement} node
*/
_svgRect(node)
{
const x = parseFloat(node.getAttribute('x'));
const y = parseFloat(node.getAttribute('y'));
const width = parseFloat(node.getAttribute('width'));
const height = parseFloat(node.getAttribute('height'));
const rx = parseFloat(node.getAttribute('rx'));
if (rx)
{
this.drawRoundedRect(x, y, width, height, rx);
}
else
{
this.drawRect(x, y, width, height);
}
}
/**
* Convert the SVG style name into usable name.
* @private
* @param {string} name
* @return {string} name used to reference style
*/
_convertStyleName(name)
{
return name
.trim()
.replace('-width', 'Width')
.replace(/.*-(line)?/, '');
}
/**
* Get the style property and parse options.
* @private
* @method
* @param {SVGElement} node
* @return {Object} Style attributes
*/
_svgStyle(node)
{
const style = node.getAttribute('style');
const result = {
fill: node.getAttribute('fill'),
opacity: node.getAttribute('opacity'),
stroke: node.getAttribute('stroke'),
strokeWidth: node.getAttribute('stroke-width'),
cap: node.getAttribute('stroke-linecap'),
join: node.getAttribute('stroke-linejoin'),
miterLimit: node.getAttribute('stroke-miterlimit'),
};
if (style !== null)
{
style.split(';').forEach((prop) =>
{
const [name, value] = prop.split(':');
if (name)
{
const convertedName = this._convertStyleName(name);
if (!result[convertedName])
{
result[convertedName] = value.trim();
}
}
});
}
return result;
}
/**
* Render a polyline element.
* @private
* @method
* @param {SVGPolylineElement} node
*/
_svgPoly(node, close)
{
const points = node.getAttribute('points')
.split(/[ ,]/g)
.map((p) => parseInt(p, 10));
this.drawPolygon(points);
if (close)
{
this.closePath();
}
}
/**
* Set the fill and stroke style.
* @private
* @method
* @param {SVGElement} node
* @param {Boolean} inherit
*/
_svgFill(node, inherit)
{
const { fill, opacity, stroke, strokeWidth, cap, join, miterLimit } = this._svgStyle(node);
const defaultLineWidth = stroke !== null ? 1 : 0;
const lineWidth = strokeWidth !== null ? parseFloat(strokeWidth) : defaultLineWidth;
const lineColor = stroke !== null ? this._hexToUint(stroke) : this.lineColor;
if (fill)
{
if (fill === 'none')
{
this.beginFill(0, 0);
}
else
{
this.beginFill(
this._hexToUint(fill),
opacity !== null ? parseFloat(opacity) : 1,
);
}
}
else if (!inherit)
{
this.beginFill(0);
}
this.lineStyle({
width: stroke === null && strokeWidth === null && inherit ? this.line.width : lineWidth,
color: stroke === null && inherit ? this.line.color : lineColor,
cap: cap === null && inherit ? this.line.cap : cap,
join: join === null && inherit ? this.line.join : join,
miterLimit: miterLimit === null && inherit ? this.line.miterLimit : parseFloat(miterLimit),
});
if (node.getAttribute('fill-rule'))
{
// eslint-disable-next-line no-console
console.info('[PIXI.SVG] "fill-rule" attribute is not supported');
}
}
/**
* Render a <path> d element
* @method
* @param {SVGPathElement} node
*/
_svgPath(node)
{
const d = node.getAttribute('d');
let x;
let y;
const commands = dPathParser(d.trim());
for (let i = 0; i < commands.length; i++)
{
const command = commands[i];
switch (command.code)
{
case 'm': {
this.moveTo(
x += command.end.x,
y += command.end.y,
);
break;
}
case 'M': {
this.moveTo(
x = command.end.x,
y = command.end.y,
);
break;
}
case 'H': {
this.lineTo(x = command.value, y);
break;
}
case 'h': {
this.lineTo(x += command.value, y);
break;
}
case 'V': {
this.lineTo(x, y = command.value);
break;
}
case 'v': {
this.lineTo(x, y += command.value);
break;
}
case 'Z': {
this.closePath();
break;
}
case 'L': {
this.lineTo(
x = command.end.x,
y = command.end.y,
);
break;
}
case 'l': {
this.lineTo(
x += command.end.x,
y += command.end.y,
);
break;
}
case 'C': {
this.bezierCurveTo(
command.cp1.x,
command.cp1.y,
command.cp2.x,
command.cp2.y,
x = command.end.x,
y = command.end.y,
);
break;
}
case 'c': {
const currX = x;
const currY = y;
this.bezierCurveTo(
currX + command.cp1.x,
currY + command.cp1.y,
currX + command.cp2.x,
currY + command.cp2.y,
x += command.end.x,
y += command.end.y,
);
break;
}
case 's':
case 'q': {
const currX = x;
const currY = y;
this.quadraticCurveTo(
currX + command.cp.x,
currY + command.cp.y,
x += command.end.x,
y += command.end.y,
);
break;
}
case 'S':
case 'Q': {
this.quadraticCurveTo(
command.cp.x,
command.cp.y,
x = command.end.x,
y = command.end.y,
);
break;
}
default: {
// eslint-disable-next-line no-console
console.info('[PIXI.SVG] Draw command not supported:', command.code, command);
break;
}
}
}
}
} |
JavaScript | class GetLoansLoanIdTimeline {
/**
* Constructs a new <code>GetLoansLoanIdTimeline</code>.
* @alias module:model/GetLoansLoanIdTimeline
*/
constructor() {
GetLoansLoanIdTimeline.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>GetLoansLoanIdTimeline</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/GetLoansLoanIdTimeline} obj Optional instance to populate.
* @return {module:model/GetLoansLoanIdTimeline} The populated <code>GetLoansLoanIdTimeline</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new GetLoansLoanIdTimeline();
if (data.hasOwnProperty('submittedOnDate')) {
obj['submittedOnDate'] = ApiClient.convertToType(data['submittedOnDate'], 'Date');
}
if (data.hasOwnProperty('submittedByUsername')) {
obj['submittedByUsername'] = ApiClient.convertToType(data['submittedByUsername'], 'String');
}
if (data.hasOwnProperty('submittedByFirstname')) {
obj['submittedByFirstname'] = ApiClient.convertToType(data['submittedByFirstname'], 'String');
}
if (data.hasOwnProperty('submittedByLastname')) {
obj['submittedByLastname'] = ApiClient.convertToType(data['submittedByLastname'], 'String');
}
if (data.hasOwnProperty('approvedOnDate')) {
obj['approvedOnDate'] = ApiClient.convertToType(data['approvedOnDate'], 'Date');
}
if (data.hasOwnProperty('approvedByUsername')) {
obj['approvedByUsername'] = ApiClient.convertToType(data['approvedByUsername'], 'String');
}
if (data.hasOwnProperty('approvedByFirstname')) {
obj['approvedByFirstname'] = ApiClient.convertToType(data['approvedByFirstname'], 'String');
}
if (data.hasOwnProperty('approvedByLastname')) {
obj['approvedByLastname'] = ApiClient.convertToType(data['approvedByLastname'], 'String');
}
if (data.hasOwnProperty('expectedDisbursementDate')) {
obj['expectedDisbursementDate'] = ApiClient.convertToType(data['expectedDisbursementDate'], 'Date');
}
if (data.hasOwnProperty('actualDisbursementDate')) {
obj['actualDisbursementDate'] = ApiClient.convertToType(data['actualDisbursementDate'], 'Date');
}
if (data.hasOwnProperty('disbursedByUsername')) {
obj['disbursedByUsername'] = ApiClient.convertToType(data['disbursedByUsername'], 'String');
}
if (data.hasOwnProperty('disbursedByFirstname')) {
obj['disbursedByFirstname'] = ApiClient.convertToType(data['disbursedByFirstname'], 'String');
}
if (data.hasOwnProperty('disbursedByLastname')) {
obj['disbursedByLastname'] = ApiClient.convertToType(data['disbursedByLastname'], 'String');
}
if (data.hasOwnProperty('expectedMaturityDate')) {
obj['expectedMaturityDate'] = ApiClient.convertToType(data['expectedMaturityDate'], 'Date');
}
}
return obj;
}
} |
JavaScript | class AdminVersion extends React.Component {
constructor(props) {
super(props);
this.state = {
version: {
branch: '',
sha: '',
message: '',
date: '',
remote: {}
}
};
}
componentDidMount() {
this.loadVersion((_, json) => this.setState({
version: dottie.get(json, 'version', {})
}));
}
loadVersion(cb) {
const {loading} = this.props;
loading((done) => request.post({
url: context.uris.VersionURI,
json: {}
}, (err, resp, json) => {
cb(err, json);
return done();
}));
}
render() {
const {version} = this.state;
const remotes = Object.keys(version.remote).map((name) => ({
key: `Remote (${name})`,
value: version.remote[name].join(', ')
}));
const versionEntries = [
{key: 'Branch', value: version.branch},
{key: 'SHA', value: version.sha},
{key: 'Message', value: version.message},
{key: 'Date', value: version.date}
].concat(remotes);
return (
<div className="margin-huge--bottom">
<p className="text--section-header">Deployment</p>
<p className="text--section-caption">
This is the version of the currently deployed instance of Linkr on the server.
</p>
<InfoTable className="margin-small--top" entries={versionEntries} />
</div>
);
}
} |
JavaScript | class AngleMeasurementsControl extends Component {
/**
* @private
*/
constructor(plugin) {
super(plugin.viewer.scene);
/**
* The {@link AngleMeasurementsPlugin} that owns this AngleMeasurementsControl.
* @type {AngleMeasurementsPlugin}
*/
this.plugin = plugin;
this._active = false;
this._state = HOVERING;
this._currentAngleMeasurement = null;
this._previousAngleMeasurement = null;
this._onhoverSurface = null;
this._onHoverNothing = null;
}
/** Gets if this AngleMeasurementsControl is currently active, where it is responding to input.
*
* @returns {boolean}
*/
get active() {
return this._active;
}
/**
* Activates this AngleMeasurementsControl, ready to respond to input.
*/
activate() {
if (this._active) {
return;
}
const cameraControl = this.plugin.viewer.cameraControl;
let over = false;
let entity = null;
let worldPos = math.vec3();
const hoverCanvasPos = math.vec2();
const pickSurfacePrecisionEnabled = this.plugin.viewer.scene.pickSurfacePrecisionEnabled;
this._onhoverSurface = cameraControl.on("hoverSurface", e => {
over = true;
entity = e.entity;
worldPos.set(e.worldPos);
hoverCanvasPos.set(e.canvasPos);
if (this._state === HOVERING) {
document.body.style.cursor = "pointer";
return;
}
if (this._currentAngleMeasurement) {
switch (this._state) {
case FINDING_CORNER:
this._currentAngleMeasurement.originWireVisible = true;
this._currentAngleMeasurement.targetWireVisible = false;
this._currentAngleMeasurement.cornerVisible = true;
this._currentAngleMeasurement.angleVisible = false;
this._currentAngleMeasurement.corner.entity = e.entity;
this._currentAngleMeasurement.corner.worldPos = e.worldPos;
document.body.style.cursor = "pointer";
break;
case FINDING_TARGET:
this._currentAngleMeasurement.targetWireVisible = true;
this._currentAngleMeasurement.targetVisible = true;
this._currentAngleMeasurement.angleVisible = true;
this._currentAngleMeasurement.target.entity = e.entity;
this._currentAngleMeasurement.target.worldPos = e.worldPos;
document.body.style.cursor = "pointer";
break;
}
}
});
let lastX;
let lastY;
const tolerance = 5;
this._onInputMouseDown = this.plugin.viewer.scene.input.on("mousedown", (coords) => {
lastX = coords[0];
lastY = coords[1];
});
this._onInputMouseUp = this.plugin.viewer.scene.input.on("mouseup", (coords) => {
if (coords[0] > lastX + tolerance || coords[0] < lastX - tolerance || coords[1] > lastY + tolerance || coords[1] < lastY - tolerance) {
return;
}
switch (this._state) {
case HOVERING:
if (this._previousAngleMeasurement) {
this._previousAngleMeasurement.originVisible = true;
this._previousAngleMeasurement.cornerVisible = true;
this._previousAngleMeasurement.targetVisible = true;
}
if (over) {
if (pickSurfacePrecisionEnabled) {
const pickResult = this.plugin.viewer.scene.pick({
canvasPos: hoverCanvasPos,
pickSurface: true,
pickSurfacePrecision: true
});
if (pickResult && pickResult.worldPos) {
worldPos.set(pickResult.worldPos);
}
}
this._currentAngleMeasurement = this.plugin.createMeasurement({
id: math.createUUID(),
origin: {
entity: entity,
worldPos: worldPos
},
corner: {
entity: entity,
worldPos: worldPos
},
target: {
entity: entity,
worldPos: worldPos
},
approximate: true
});
this._currentAngleMeasurement.originVisible = true;
this._currentAngleMeasurement.originWireVisible = true;
this._currentAngleMeasurement.cornerVisible = false;
this._currentAngleMeasurement.targetWireVisible = false;
this._currentAngleMeasurement.targetVisible = false;
this._currentAngleMeasurement.angleVisible = false;
this._previousAngleMeasurement = this._currentAngleMeasurement;
this._state = FINDING_CORNER;
}
break;
case FINDING_CORNER:
if (over) {
if (pickSurfacePrecisionEnabled) {
const pickResult = this.plugin.viewer.scene.pick({
canvasPos: hoverCanvasPos,
pickSurface: true,
pickSurfacePrecision: true
});
if (pickResult && pickResult.worldPos) {
this._currentAngleMeasurement.corner.worldPos = pickResult.worldPos;
}
}
this._currentAngleMeasurement.targetWireVisible = false;
this._currentAngleMeasurement.targetVisible = true;
this._currentAngleMeasurement.angleVisible = true;
this._state = FINDING_TARGET;
} else {
if (this._currentAngleMeasurement) {
this._currentAngleMeasurement.destroy();
this._currentAngleMeasurement = null;
this._previousAngleMeasurement = null;
this._state = HOVERING
}
}
break;
case FINDING_TARGET:
if (over) {
if (pickSurfacePrecisionEnabled) {
const pickResult = this.plugin.viewer.scene.pick({
canvasPos: hoverCanvasPos,
pickSurface: true,
pickSurfacePrecision: true
});
if (pickResult && pickResult.worldPos) {
this._currentAngleMeasurement.target.worldPos = pickResult.worldPos;
this._currentAngleMeasurement.approximate = false;
}
}
this._currentAngleMeasurement.targetVisible = true;
this._currentAngleMeasurement.angleVisible = true;
this._currentAngleMeasurement = null;
this._previousAngleMeasurement = null;
this._state = HOVERING;
} else {
if (this._currentAngleMeasurement) {
this._currentAngleMeasurement.destroy();
this._currentAngleMeasurement = null;
this._previousAngleMeasurement = null;
this._state = HOVERING;
}
}
break;
}
});
this._onHoverNothing = cameraControl.on("hoverOff", e => {
over = false;
if (this._currentAngleMeasurement) {
switch (this._state) {
case HOVERING:
case FINDING_ORIGIN:
this._currentAngleMeasurement.originVisible = false;
break;
case FINDING_CORNER:
this._currentAngleMeasurement.cornerVisible = false;
this._currentAngleMeasurement.originWireVisible = false;
this._currentAngleMeasurement.targetVisible = false;
this._currentAngleMeasurement.targetWireVisible = false;
this._currentAngleMeasurement.angleVisible = false;
break;
case FINDING_TARGET:
this._currentAngleMeasurement.targetVisible = false;
this._currentAngleMeasurement.targetWireVisible = false;
this._currentAngleMeasurement.angleVisible = false;
break;
}
document.body.style.cursor = "default";
}
});
this._active = true;
}
/**
* Deactivates this AngleMeasurementsControl, making it unresponsive to input.
*
* Destroys any {@link AngleMeasurement} under construction.
*/
deactivate() {
if (!this._active) {
return;
}
this.reset();
const cameraControl = this.plugin.viewer.cameraControl;
const input = this.plugin.viewer.scene.input;
input.off(this._onInputMouseDown);
input.off(this._onInputMouseUp);
cameraControl.off(this._onhoverSurface);
cameraControl.off(this._onHoverNothing);
this._currentAngleMeasurement = null;
this._active = false;
}
/**
* Resets this AngleMeasurementsControl.
*
* Destroys any {@link AngleMeasurement} under construction.
*
* Does nothing if the AngleMeasurementsControl is not active.
*/
reset() {
if (!this._active) {
return;
}
if (this._currentAngleMeasurement) {
this._currentAngleMeasurement.destroy();
this._currentAngleMeasurement = null;
}
this._previousAngleMeasurement = null;
this._state = HOVERING;
}
/**
* @private
*/
destroy() {
this.deactivate();
super.destroy();
}
} |
JavaScript | class TuyaWebPlatform {
constructor(log, config, api) {
var _this = this;
this.log = log;
this.config = config;
this.api = api;
this.Service = this.api.hap.Service;
this.Characteristic = this.api.hap.Characteristic; // this is used to track restored cached accessories
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.accessories = new Map();
this.failedToInitAccessories = new Map();
this.log.debug('Finished initializing platform:', this.config.name);
if (!config || !config.options) {
this.log.info('No options found in configuration file, disabling plugin.');
return;
}
var options = config.options;
if (options.username === undefined || options.password === undefined || options.countryCode === undefined) {
this.log.error('Missing required config parameter.');
return;
}
if (options.platform !== undefined && !_TuyaWebApi.TuyaPlatforms.includes(options.platform)) {
this.log.error('Invalid platform provided, received %s but must be one of %s', options.platform, _TuyaWebApi.TuyaPlatforms);
} // Set cloud polling interval
this.pollingInterval = config.options.pollingInterval; // Create Tuya Web API instance
this.tuyaWebApi = new _TuyaWebApi.TuyaWebApi(options.username, options.password, options.countryCode, options.platform, this.log); // When this event is fired it means Homebridge has restored all cached accessories from disk.
// Dynamic Platform plugins should only register new accessories after this event was fired,
// in order to ensure they weren't added to homebridge already. This event can also be used
// to start discovery of new accessories.
this.api.on('didFinishLaunching', _asyncToGenerator(function* () {
var _a;
try {
yield _this.tuyaWebApi.getOrRefreshToken(); // run the method to discover / register your devices as accessories
yield _this.discoverDevices();
if (_this.pollingInterval) {
//Tuya will probably still complain if we fetch a new request on the exact second.
var pollingInterval = Math.max(_this.pollingInterval, _settings.TUYA_DISCOVERY_TIMEOUT + 5);
(_a = _this.log) === null || _a === void 0 ? void 0 : _a.info('Enable cloud polling with interval %ss', pollingInterval); // Set interval for refreshing device states
setInterval(() => {
_this.refreshDeviceStates().catch(error => {
_this.log.error(error.message);
});
}, pollingInterval * 1000);
}
} catch (e) {
if (e instanceof _errors.AuthenticationError) {
_this.log.error('Authentication error: %s', e.message);
} else {
_this.log.error(e.message);
_this.log.debug(e);
}
}
}));
}
/**
* This function is invoked when homebridge restores cached accessories from disk at startup.
* It should be used to setup event handlers for characteristics and update respective values.
*/
configureAccessory(accessory) {
this.log.info('Loading accessory from cache:', accessory.displayName); // add the restored accessory to the accessories cache so we can track if it has already been registered
this.accessories.set(accessory.UUID, accessory);
}
removeAccessory(accessory) {
this.log.info('Removing accessory:', accessory.displayName);
this.api.unregisterPlatformAccessories(_settings.PLUGIN_NAME, _settings.PLATFORM_NAME, [accessory]);
this.accessories.delete(accessory.UUID);
} // Called from device classes
registerPlatformAccessory(accessory) {
this.log.debug('Register Platform Accessory (%s)', accessory.displayName);
this.api.registerPlatformAccessories(_settings.PLUGIN_NAME, _settings.PLATFORM_NAME, [accessory]);
this.accessories.set(accessory.UUID, accessory);
}
refreshDeviceStates(devices) {
var _this2 = this;
return _asyncToGenerator(function* () {
var _a, _b;
devices = devices || _this2.filterDeviceList(yield _this2.tuyaWebApi.getAllDeviceStates());
if (!devices) {
return;
} // Refresh device states
for (var device of devices) {
var uuid = _this2.api.hap.uuid.generate(device.id);
var homebridgeAccessory = _this2.accessories.get(uuid);
if (homebridgeAccessory) {
(_a = homebridgeAccessory.controller) === null || _a === void 0 ? void 0 : _a.updateAccessory(device);
} else if (!((_b = _this2.failedToInitAccessories.get(device.dev_type)) === null || _b === void 0 ? void 0 : _b.includes(uuid))) {
_this2.log.error('Could not find Homebridge device with UUID (%s) for Tuya device (%s)', uuid, device.name);
}
}
})();
}
addAccessory(device) {
var deviceType = device.dev_type || 'switch';
var uuid = this.api.hap.uuid.generate(device.id);
var homebridgeAccessory = this.accessories.get(uuid); // Construct new accessory
/* eslint-disable @typescript-eslint/no-explicit-any */
switch (deviceType) {
case 'dimmer':
new _accessories.DimmerAccessory(this, homebridgeAccessory, device);
break;
case 'cover':
new _accessories.CoverAccessory(this, homebridgeAccessory, device);
break;
case 'fan':
new _accessories.FanAccessory(this, homebridgeAccessory, device);
break;
case 'light':
new _accessories.LightAccessory(this, homebridgeAccessory, device);
break;
case 'outlet':
new _accessories.OutletAccessory(this, homebridgeAccessory, device);
break;
case 'scene':
new _accessories.SceneAccessory(this, homebridgeAccessory, device);
break;
case 'switch':
new _accessories.SwitchAccessory(this, homebridgeAccessory, device);
break;
default:
if (!this.failedToInitAccessories.get(deviceType)) {
this.log.warn('Could not init class for device type [%s]', deviceType);
this.failedToInitAccessories.set(deviceType, []);
}
this.failedToInitAccessories.set(deviceType, [uuid, ...this.failedToInitAccessories.get(deviceType)]);
break;
}
/* eslint-enable @typescript-eslint/no-explicit-any */
}
filterDeviceList(devices) {
if (!devices) {
return [];
}
var allowedSceneIds = this.getAllowedSceneIds(devices);
var hiddenAccessoryIds = this.getHiddenAccessoryIds(devices);
return devices.filter(d => d.dev_type !== 'scene' || allowedSceneIds.includes(d.id)).filter(d => !hiddenAccessoryIds.includes(d.id));
}
discoverDevices() {
var _this3 = this;
return _asyncToGenerator(function* () {
var devices = (yield _this3.tuyaWebApi.discoverDevices()) || []; // Is device type overruled in config defaults?
var parsedDefaults = _this3.parseDefaultsForDevices(devices);
for (var defaults of parsedDefaults) {
defaults.device.dev_type = defaults.device_type;
_this3.log.info('Device type for "%s" is overruled in config to: "%s"', defaults.device.name, defaults.device.dev_type);
}
devices = _this3.filterDeviceList(devices);
var cachedDeviceIds = [..._this3.accessories.keys()];
var availableDeviceIds = devices.map(d => _this3.generateUUID(d.id));
for (var cachedDeviceId of cachedDeviceIds) {
if (!availableDeviceIds.includes(cachedDeviceId)) {
var device = _this3.accessories.get(cachedDeviceId);
_this3.log.warn('Device: %s - is no longer available and will be removed', device.displayName);
_this3.removeAccessory(device);
}
} // loop over the discovered devices and register each one if it has not already been registered
for (var _device of devices) {
_this3.addAccessory(_device);
}
yield _this3.refreshDeviceStates(devices);
})();
}
/**
* Returns a validated set of defaults and their devices for which the type will need to be overridden.
* @param devices
* @private
*/
parseDefaultsForDevices(devices) {
var _this4 = this;
var defaults = this.config.defaults;
if (!defaults) {
return [];
}
var parsedDefaults = [];
var _loop = function _loop(configuredDefault) {
if (!configuredDefault.id) {
_this4.log.warn('Missing required `id` property on device type overwrite, received:\r\n%s', JSON.stringify(configuredDefault, undefined, 2));
return "continue";
}
if (!configuredDefault.device_type) {
_this4.log.warn('Missing required `device_type` property on device type overwrite, received:\r\n%s', JSON.stringify(configuredDefault, undefined, 2));
return "continue";
}
configuredDefault.device_type = configuredDefault.device_type.toLowerCase();
var device = devices.find(device => device.id === configuredDefault.id || device.name === configuredDefault.id);
if (!device) {
_this4.log.warn('Tried adding default for device: "%s" which is not a valid device-id or device-name.', configuredDefault.id);
return "continue";
}
if (!_TuyaWebApi.TuyaDeviceTypes.includes(configuredDefault.device_type)) {
_this4.log.warn('Added defaults for device: "%s" - device-type "%s" is not a valid device-type.', device.name, configuredDefault.device_type);
return "continue";
}
parsedDefaults.push(_objectSpread(_objectSpread({}, configuredDefault), {}, {
device
}));
};
for (var configuredDefault of defaults) {
var _ret = _loop(configuredDefault);
if (_ret === "continue") continue;
}
return parsedDefaults;
}
/**
* Returns a list of all allowed scene Ids.
* @param devices
* @private
*/
getAllowedSceneIds(devices) {
if (!this.config.scenes) {
return [];
}
var sceneList = new _DeviceList.DeviceList(devices.filter(d => d.dev_type === 'scene'));
if (!Array.isArray(this.config.scenesWhitelist) || this.config.scenesWhitelist.length === 0) {
return sceneList.all;
}
var allowedSceneIds = [];
for (var toAllowSceneIdentifier of this.config.scenesWhitelist) {
var deviceIdentifier = sceneList.find(toAllowSceneIdentifier);
if (deviceIdentifier) {
allowedSceneIds.push(deviceIdentifier);
continue;
}
this.log.warn('Tried allowing non-existing scene %s', toAllowSceneIdentifier);
}
return [...new Set(allowedSceneIds)];
}
/**
* Returns a list of all devices that are not supposed to be exposed.
* @param devices
* @private
*/
getHiddenAccessoryIds(devices) {
if (!this.config.hiddenAccessories) {
return [];
}
if (!Array.isArray(this.config.hiddenAccessories) || this.config.hiddenAccessories.length === 0) {
return [];
}
var deviceList = new _DeviceList.DeviceList(devices);
var hiddenAccessoryIdentifiers = [];
for (var toDisallowAccessoryIdentifier of this.config.hiddenAccessories) {
var deviceIdentifier = deviceList.find(toDisallowAccessoryIdentifier);
if (deviceIdentifier) {
hiddenAccessoryIdentifiers.push(deviceIdentifier);
continue;
}
this.log.warn('Tried disallowing non-existing device %s', toDisallowAccessoryIdentifier);
}
return [...new Set(hiddenAccessoryIdentifiers)];
}
get platformAccessory() {
return this.api.platformAccessory;
}
get generateUUID() {
return this.api.hap.uuid.generate;
}
} |
JavaScript | class TopNavbar extends Component {
constructor(props) {
super(props);
this.urlSettings = this.urlSettings.bind(this);
this.handleDrawerOpen = this.handleDrawerOpen.bind(this);
this.setView = this.setView.bind(this);
this.fullscreenDiagram = this.fullscreenDiagram.bind(this);
}
/**
* Open URL settings modal
*/
urlSettings() {
if (typeof this.props.onOpenUrlSettings === 'function') {
this.props.onOpenUrlSettings();
}
}
/**
* Open Global settings modal
*/
globalSettings() {
if (typeof this.props.onOpenSettings === 'function') {
this.props.onOpenSettings();
}
}
handleDrawerOpen() {
if (typeof this.props.onHandleDrawerOpen === 'function') {
this.props.onHandleDrawerOpen();
}
}
/**
* https://stackoverflow.com/a/32100295/2614364
*/
fullscreen() {
// if already full screen; exit
// else go fullscreen
if (
document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement
) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
} else {
var element = document.body;
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
}
}
}
/**
* Share this page
*/
share() {
if (typeof this.props.onShare === 'function') {
this.props.onShare();
}
}
setView(type){
if (typeof this.props.onSetView === 'function') {
this.props.onSetView(type);
}
}
fullscreenDiagram(){
if (typeof this.props.onFullscreenDiagram === 'function') {
this.props.onFullscreenDiagram();
}
}
showInfo(){
if (typeof this.props.onShowInfo === 'function') {
this.props.onShowInfo();
}
}
editTitle(){
if (typeof this.props.onEditTitle === 'function') {
this.props.onEditTitle();
}
}
download() {
if (typeof this.props.onDownload === 'function') {
this.props.onDownload();
}
}
render() {
const { classes } = this.props;
return (<AppBar position="static" className={this.props.className}>
<Toolbar disableGutters>
<IconButton
color="contrast"
aria-label="open drawer"
onClick={this.handleDrawerOpen}
className={classNames(classes.menuButton, this.props.drawerOpen && classes.hide)}
>
<MenuIcon />
</IconButton>
<Typography type="headline" color="inherit" className={this.props.drawerOpen ? classes.flexOpen : classes.flexClosed}>
{this.props.title || 'Sequence Diagram Draft'}
<IconButton
color="contrast"
aria-label="edit title"
onClick={() => this.editTitle()}
>
<EditIcon />
</IconButton>
</Typography>
<Tooltip enterDelay={500} disableTriggerFocus title="horizontal window" placement="bottom">
<IconButton onClick={() => this.setView("horizontal")} className={classes.button} color="contrast" aria-label="horizontal window">
<ViewHorizontal />
</IconButton>
</Tooltip>
<Tooltip enterDelay={500} disableTriggerFocus title="column window" placement="bottom">
<IconButton onClick={() => this.setView("vertical")} className={classes.button} color="contrast" aria-label="column window">
<ViewColumn />
</IconButton>
</Tooltip>
<Tooltip enterDelay={500} disableTriggerFocus title="fullscreen diagram" placement="bottom">
<IconButton onClick={() => this.fullscreenDiagram()} className={classes.button} color="contrast" aria-label="fullscreen diagram">
<PanoramaIcon />
</IconButton>
</Tooltip>
<Tooltip enterDelay={500} disableTriggerFocus title="share this page" placement="bottom">
<IconButton onClick={() => this.share()} className={classes.button} color="contrast" aria-label="share">
<Share />
</IconButton>
</Tooltip>
<Tooltip enterDelay={500} disableTriggerFocus title="download" placement="bottom">
<IconButton onClick={() => this.download()} className={classes.button} color="contrast" aria-label="download">
<Download />
</IconButton>
</Tooltip>
<Tooltip enterDelay={500} disableTriggerFocus title="fullscreen" placement="bottom">
<IconButton onClick={() => this.fullscreen()} className={classes.button} color="contrast" aria-label="fullscreen">
<FullscreenIcon />
</IconButton>
</Tooltip>
<Tooltip enterDelay={500} disableTriggerFocus title="clear url param" placement="bottom">
<IconButton href={window.location.href.split('?')[0]} className={classes.button} color="contrast" aria-label="clear url">
<LinkIcon />
</IconButton>
</Tooltip>
<Tooltip enterDelay={500} disableTriggerFocus title="information" placement="bottom">
<IconButton onClick={() => this.showInfo()} color="contrast" className={classes.lastButton} aria-label="information">
<InfoIcon />
</IconButton>
</Tooltip>
</Toolbar>
</AppBar>)
}
} |
JavaScript | class listener extends __base__ {
/**
* Creates an event object
* @param {string} type - The name of the event (case-insensitive)
* @param {boolean} [bubbles] - A Boolean indicating whether the event bubbles up through the DOM or not.
* @param {boolean} [cancelable] - A Boolean indicating whether the event is cancelable.
* @returns {Event|undefined}
*/
static create(type, bubbles, cancelable) {
if (isstring(type)) {
return new Event(type, {bubbles: bubbles !== false, cancelable: cancelable !== false});
}
}
/**
* Attach event to target
* @param {EventTarget} el - element to attach the event to
* @param {string} type - A case-sensitive string representing the event type to listen for.
* @param {function} fn - callback to call
* @param {boolean} [capture]
* @returns {this}
*/
static on(el, type, fn, capture) {
if (el instanceof EventTarget && isstring(type) && iscallable(fn)) {
capture = capture === true;
events.add(...arguments);
el.addEventListener(type, fn, capture);
}
return this;
}
/**
* Detach an event from a target
* @param {EventTarget} el - target
* @param {string} type - A case-sensitive string representing the event type to detach.
* @param {function} [fn] - callback to detach
* @param {boolean} [capture]
* @returns {this}
*/
static off(el, type, fn, capture) {
if (el instanceof EventTarget && isstring(type)) {
let list;
if ((list = events.find(...arguments))) {
events.remove(...arguments);
for (let entry of list) {
entry.target.removeEventListener(entry.type, entry.fn, entry.capture);
}
}
}
return this;
}
/**
* Dispatches an Event at the specified EventTarget
* @param {EventTarget} el
* @param {string} type
* @param {boolean} [bubbles]
* @param {boolean} [cancelable]
* @returns {this}
*/
static trigger(el, type, bubbles, cancelable) {
if (el instanceof EventTarget && isstring(type)) {
el.dispatchEvent(this.create(type, bubbles, cancelable));
}
return this;
}
init(target) {
if (!target) {
return listener;
}
if (isiterable(target)) {
target.forEach(function(t) {
if (!(t instanceof EventTarget)) {
throw new InvalidArgumentException('listener: list of EventTarget provided is not valid.');
}
});
} else if (!(target instanceof EventTarget)) {
throw new InvalidArgumentException('listener: EventTarget provided is not valid.');
}
this.target = target;
}
/**
* Attach an event
* @param {string} type - A case-sensitive string representing the event type to listen for.
* @param {function} fn - callback to call
* @param {boolean} [capture]
* @returns {this}
*/
on(type, fn, capture) {
if (isiterable(this.target)) {
this.target.forEach(x => listener.on(x, type, fn, capture));
return this;
}
listener.on(this.target, ...arguments);
return this;
}
/**
* Detach an event
* @param {string} type - A case-sensitive string representing the event type to detach.
* @param {function} [fn] - callback to detach
* @param {boolean} [capture]
* @returns {this}
*/
off(type, fn, capture) {
if (isiterable(this.target)) {
this.target.forEach(x => listener.off(x, type, fn, capture));
return this;
}
listener.off(this.target, ...arguments);
return this;
}
/**
* Dispatches an Event
* @param {string} type
* @param {boolean} [bubbles]
* @param {boolean} [cancelable]
* @returns {this}
*/
trigger(type, bubbles, cancelable) {
if (isiterable(this.target)) {
this.target.forEach(x => listener.trigger(x, type, bubbles, cancelable));
return this;
}
listener.trigger(this.target, ...arguments);
return this;
}
} |
JavaScript | class VulnerabilityIngestion {
/**
* Constructs a new <code>VulnerabilityIngestion</code>.
* Execution of vulnerability ingestion task
* @alias module:model/VulnerabilityIngestion
*/
constructor() {
VulnerabilityIngestion.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>VulnerabilityIngestion</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/VulnerabilityIngestion} obj Optional instance to populate.
* @return {module:model/VulnerabilityIngestion} The populated <code>VulnerabilityIngestion</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new VulnerabilityIngestion();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'String');
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data.hasOwnProperty('file')) {
obj['file'] = ApiClient.convertToType(data['file'], 'String');
}
if (data.hasOwnProperty('executedOn')) {
obj['executedOn'] = ApiClient.convertToType(data['executedOn'], 'Date');
}
if (data.hasOwnProperty('message')) {
obj['message'] = ApiClient.convertToType(data['message'], 'String');
}
}
return obj;
}
} |
JavaScript | class Shape {
/**
* The area of a shape is 0
* @return {number} 0
*/
area() {
return 0;
}
/**
* The name of the class that call the function
* @return {string} name of the class
*/
toString() {
return Object.getPrototypeOf(this).constructor.name;
}
} |
JavaScript | class Circle extends Shape {
/**
* Create a circle
* @param {number} [radius = 0]
*/
constructor(radius = 0) {
super();
this.radius_ = radius;
}
/**
* Calculates the area of the circle
* @return {number} The area
*/
area() {
return Math.PI * this.radius_ ** 2;
}
} |
JavaScript | class Rectangle extends Shape {
/**
* Create a rectangle
* @param {number} [width = 0]
* @param {number} [height = 0]
*/
constructor(width = 0, height = 0) {
super();
this.width_ = width;
this.height_ = height;
}
/**
* Calculates the area of the rectangle
* @return {number} The area
*/
area() {
return this.width_ * this.height_;
}
} |
JavaScript | class Triangle extends Shape {
/**
* Create a triangle
* @param {number} [base = 0]
* @param {number} [height = 0]
*/
constructor(base = 0, height = 0) {
super();
this.base_ = base;
this.height_ = height;
}
/**
* Calculates the area of the triangle
* @return {number} The area
*/
area() {
return this.base_ * this.height_ / 2;
}
} |
JavaScript | class WT_MapViewTextLabel {
/**
* @readonly
* @property {Number} priority - the display priority of this label. Text labels with greater priority values
* are always drawn above and culled after labels with lower priority values.
* @type {Number}
*/
get priority() {
return 0;
}
/**
* @readonly
* @property {Boolean} alwaysShow - whether this label is immune to culling.
* @type {Boolean}
*/
get alwaysShow() {
return false;
}
/**
* @readonly
* @property {{left:Number, right:Number, top:Number, bottom:Number}} bounds - the boundaries of this text label in the map view window.
* @type {{left:Number, right:Number, top:Number, bottom:Number}}
*/
get bounds() {
return undefined;
}
/**
* Draws this label to a canvas rendering context.
* @abstract
* @param {WT_MapViewState} state - the current map view state.
* @param {CanvasRenderingContext2D} context - the canvas rendering context to which to draw.
*/
draw(state, context) {
}
/**
* Updates this label according to the current map view state.
* @abstract
* @param {WT_MapViewState} state - the current map view state.
*/
update(state) {
}
} |
JavaScript | class WT_MapViewSimpleTextLabel extends WT_MapViewTextLabel {
/**
* @param {String} text - the text content of the new label.
* @param {Number} priority - the display priority of the new label.
* @param {Boolean} [alwaysShow] - whether the new label is immune to culling. False by default.
*/
constructor(text, priority, alwaysShow = false) {
super();
this._text = text;
this._priority = priority;
this._alwaysShow = alwaysShow;
this._position = new WT_GVector2(0, 0);
this._anchor = new WT_GVector2(0, 1);
this._backgroundPadding = [0, 0, 0, 0];
this._bounds = {left: 0, right: 0, top: 0, bottom: 0};
this._optsManager = new WT_OptionsManager(this, WT_MapViewSimpleTextLabel.OPTIONS_DEF);
}
/**
* @readonly
* @property {Number} priority - the display priority of this label. Text labels with greater priority values
* are always drawn above and culled after labels with lower priority values.
* @type {Number}
*/
get priority() {
return this._priority;
}
/**
* @readonly
* @property {Boolean} alwaysShow - whether this label is immune to culling.
* @type {Boolean}
*/
get alwaysShow() {
return this._alwaysShow;
}
/**
* @readonly
* @property {{left:Number, right:Number, top:Number, bottom:Number}} bounds - the boundaries of this text label in the map view window.
* @type {{left:Number, right:Number, top:Number, bottom:Number}}
*/
get bounds() {
return this._bounds;
}
/**
* @readonly
* @property {String} priority - the text content of this label.
* @type {String}
*/
get text() {
return this._text;
}
/**
* @property {WT_GVector2} priority - the anchor point of this label's text, expressed as a 2D vector in relative
* coordinates. (0, 0) is the top-left corner of the text, and (1, 1) is the
* bottom-right corner.
* @type {WT_GVector2}
*/
get anchor() {
return this._anchor.readonly();
}
set anchor(value) {
this._anchor.set(value);
}
get backgroundPadding() {
return this._backgroundPadding;
}
set backgroundPadding(padding) {
if (padding.length > 0) {
this._backgroundPadding[0] = padding[0];
this._backgroundPadding[1] = padding[0];
this._backgroundPadding[2] = padding[0];
this._backgroundPadding[3] = padding[0];
}
if (padding.length > 1) {
this._backgroundPadding[1] = padding[1];
this._backgroundPadding[3] = padding[1];
}
if (padding.length > 2) {
this._backgroundPadding[2] = padding[2];
}
if (padding.length > 3) {
this._backgroundPadding[3] = padding[3];
}
}
setOptions(opts) {
this._optsManager.setOptions(opts);
}
_pathBackground(context, left, top, width, height, radius) {
let right = left + width;
let bottom = top + height;
context.beginPath();
context.moveTo(left + radius, top);
context.lineTo(right - radius, top);
context.arcTo(right, top, right, top + radius, radius);
context.lineTo(right, bottom - radius);
context.arcTo(right, bottom, right - radius, bottom, radius);
context.lineTo(left + radius, bottom);
context.arcTo(left, bottom, left, bottom - radius, radius);
context.lineTo(left, top + radius);
context.arcTo(left, top, left + radius, top, radius);
}
_drawBackground(state, context, centerX, centerY, width, height) {
let backgroundLeft = centerX - width / 2 - (this.backgroundPadding[3] + this.backgroundOutlineWidth) * state.dpiScale;
let backgroundTop = centerY - height / 2 - (this.backgroundPadding[0] + this.backgroundOutlineWidth) * state.dpiScale;
let backgroundWidth = width + (this.backgroundPadding[1] + this.backgroundPadding[3] + 2 * this.backgroundOutlineWidth) * state.dpiScale;
let backgroundHeight = height + (this.backgroundPadding[0] + this.backgroundPadding[2] + 2 * this.backgroundOutlineWidth) * state.dpiScale;
let isRounded = false;
if (this.backgroundBorderRadius > 0) {
isRounded = true;
this._pathBackground(context, backgroundLeft, backgroundTop, backgroundWidth, backgroundHeight, this.backgroundBorderRadius * state.dpiScale);
}
if (this.backgroundOutlineWidth > 0) {
context.lineWidth = this.backgroundOutlineWidth * 2 * state.dpiScale;
context.strokeStyle = this.backgroundOutlineColor;
if (isRounded) {
context.stroke();
} else {
context.strokeRect(backgroundLeft, backgroundTop, backgroundWidth, backgroundHeight);
}
}
context.fillStyle = this.backgroundColor;
if (isRounded) {
context.fill();
} else {
context.fillRect(backgroundLeft, backgroundTop, backgroundWidth, backgroundHeight);
}
}
_drawText(state, context, centerX, centerY) {
context.textBaseline = "middle";
context.textAlign = "center";
if (this.fontOutlineWidth > 0) {
context.lineWidth = this.fontOutlineWidth * 2 * state.dpiScale;
context.strokeStyle = this.fontOutlineColor;
context.strokeText(this.text, centerX, centerY);
}
context.fillStyle = this.fontColor;
context.fillText(this.text, centerX, centerY);
}
/**
* Draws this label to a canvas rendering context.
* @param {WT_MapViewState} state - the current map view state.
* @param {CanvasRenderingContext2D} context - the canvas rendering context to which to draw.
*/
draw(state, context) {
context.font = `${this.fontWeight} ${this.fontSize * state.dpiScale}px ${this.font}`;
let width = context.measureText(this.text).width;
let height = this.fontSize * state.dpiScale;
let centerX = this._position.x - (this.anchor.x - 0.5) * width;
let centerY = this._position.y - (this.anchor.y - 0.5) * height;
if (this.showBackground) {
this._drawBackground(state, context, centerX, centerY, width, height);
}
this._drawText(state, context, centerX, centerY);
}
/**
* Updates this label's boundaries.
* @param {WT_MapViewState} state - the current map view state.
*/
_updateBounds(state) {
let width = 0.6 * this.fontSize * this.text.length * state.dpiScale;
let height = this.fontSize * state.dpiScale;
let left = this._position.x - this.anchor.x * width;
let right = left + width;
let top = this._position.y - this.anchor.y * height;
let bottom = top + height;
if (this.showBackground) {
left -= (this.backgroundPadding[3] + this.backgroundOutlineWidth) * state.dpiScale;
right += (this.backgroundPadding[1] + this.backgroundOutlineWidth) * state.dpiScale;
top -= (this.backgroundPadding[0] + this.backgroundOutlineWidth) * state.dpiScale;
bottom += (this.backgroundPadding[2] + this.backgroundOutlineWidth) * state.dpiScale;
}
this._bounds.left = left;
this._bounds.right = right;
this._bounds.top = top;
this._bounds.bottom = bottom;
}
/**
* Updates this label according to the current map view state.
* @param {WT_MapViewState} state - the current map view state.
*/
update(state) {
this._updateBounds(state);
}
} |
JavaScript | class WT_MapViewLocationTextLabel extends WT_MapViewSimpleTextLabel {
/**
* @param {{lat:Number, long:Number}} location - the geographic location of the new label.
* @param {String} text - the text content of the new label.
* @param {Number} priority - the display priority of the new label.
* @param {Boolean} [alwaysShow] - whether the new label is immune to culling. False by default.
*/
constructor(location, text, priority, alwaysShow = false) {
super(text, priority, alwaysShow);
this._location = new WT_GeoPoint(location.lat, location.long);
this._offset = new WT_GVector2(0, 0);
this._optsManager.addOptions(WT_MapViewLocationTextLabel.OPTIONS_DEF);
this._anchor.set(0.5, 0.5);
}
/**
* The geographic location associated with this label.
* @readonly
* @type {WT_GeoPointReadOnly}
*/
get location() {
return this._location.readonly();
}
/**
* The offset, in pixel coordinates, of this label from its projected location.
* @type {WT_GVector2}
*/
get offset() {
return this._offset.readonly();
}
set offset(value) {
this._offset.set(value);
}
/**
* Updates this label according to the current map view state.
* @param {WT_MapViewState} state - the current map view state.
*/
update(state) {
state.projection.project(this.location, this._position);
this._position.add(this.offset.x * state.dpiScale, this.offset.y * state.dpiScale);
super.update(state);
}
} |
JavaScript | class WT_MapViewTextLabelManager {
constructor(opts = {}) {
this.perfModeThreshold = WT_MapViewTextLabelManager.PERFORMANCE_MODE_THRESHOLD_DEFAULT;
this._lastPerformanceMode = false;
this._preventOverlapChanged = false;
/**
* @type {Map<WT_MapViewTextLabel,WT_MapViewManagedTextLabel>}
*/
this._managedLabels = new Map();
/**
* @type {Set<WT_MapViewManagedTextLabel>}
*/
this._visibleLabels = new Set();
this._lastRange = new WT_NumberUnit(0, WT_Unit.NMILE);
this._lastTime = 0;
this._mapZoomTimer = 0;
this._lastRotation = 0;
/**
* @type {WT_MapViewManagedTextLabel[]}
*/
this._collisionUpdateBuffer = [];
this._collisionUpdateHead = 0;
/**
* @type {Set<WT_MapViewTextLabel>}
*/
this._toAddBuffer = new Set();
/**
* @type {Set<WT_MapViewTextLabel>}
*/
this._toRemoveBuffer = new Set();
this._optsManager = new WT_OptionsManager(this, WT_MapViewTextLabelManager.OPTIONS_DEF);
this._optsManager.setOptions(opts);
}
onOptionChanged(name, oldValue, newValue) {
if (name === "preventOverlap") {
this._preventOverlapChanged = true;
}
}
/**
* Gets the labels belonging to this manager that are currently visible.
* @returns {IterableIterator<WT_MapViewTextLabel>} an iterable over the currently visible labels belonging to this manager.
*/
getVisibleLabels() {
return new WT_MapViewManagedTextLabelIterator(this._visibleLabels.values());
}
/**
* Adds a label to this manager to be tracked.
* @param {WT_MapViewTextLabel} label - the text label to add.
*/
add(label) {
let existing = this._managedLabels.get(label);
if (!existing) {
this._toAddBuffer.add(label);
} else {
this._toRemoveBuffer.delete(label);
}
}
/**
* Removes a label from this manager.
* @param {WT_MapViewTextLabel} label - the text label to remove.
*/
remove(label) {
let toRemove = this._managedLabels.get(label);
if (toRemove) {
this._toRemoveBuffer.add(label);
} else {
this._toAddBuffer.delete(label);
}
}
_isInPerformanceMode() {
return this._managedLabels.size >= this.perfModeThreshold;
}
/**
*
* @param {WT_MapViewState} state
* @param {WT_MapViewManagedTextLabel} managedLabelToAdd
*/
_updateOnAdd(state, managedLabelToAdd) {
managedLabelToAdd.label.update(state);
let show = true;
if (this.preventOverlap) {
let compareSet = this._isInPerformanceMode() ? this._visibleLabels.values() : this._managedLabels.values();
for (let toCompare of compareSet) {
if (toCompare.doesCollide(managedLabelToAdd)) {
toCompare.collisions.add(managedLabelToAdd);
managedLabelToAdd.collisions.add(toCompare);
if (toCompare.show && !managedLabelToAdd.label.alwaysShow) {
show = show && managedLabelToAdd.label.priority > toCompare.label.priority;
}
}
}
}
this._managedLabels.set(managedLabelToAdd.label, managedLabelToAdd);
this._changeVisibility(managedLabelToAdd, show);
}
/**
*
* @param {WT_MapViewManagedTextLabel} managedLabelToRemove
*/
_updateOnRemove(managedLabelToRemove) {
this._changeVisibility(managedLabelToRemove, false);
managedLabelToRemove.collisions.forEach(conflicted => conflicted.collisions.delete(managedLabelToRemove));
this._managedLabels.delete(managedLabelToRemove.label);
}
/**
*
* @param {WT_MapViewManagedTextLabel} managedLabel
* @param {Boolean} show
*/
_changeVisibility(managedLabel, show) {
this._changeVisibilityHelper(managedLabel, show, 1);
}
/**
*
* @param {WT_MapViewManagedTextLabel} managedLabel
* @param {Boolean} show
* @param {Number} depth
* @returns {Number}
*/
_changeVisibilityHelper(managedLabel, show, depth) {
let queries = 0;
if (depth > this.collisionResolutionMaxStackDepth) {
return queries;
}
if (show && !managedLabel.show) {
queries++;
this._visibleLabels.add(managedLabel);
managedLabel.show = true;
for (let conflicted of managedLabel.collisions) {
queries++;
if (conflicted.show && !conflicted.label.alwaysShow) {
queries += this._changeVisibilityHelper(conflicted, false, depth + 1);
}
}
} else if (!show && managedLabel.show) {
queries++;
this._visibleLabels.delete(managedLabel);
managedLabel.show = false;
for (let conflicted of managedLabel.collisions) {
queries++;
let showTextConflicted = true;
for (let conflictedOfConflicted of conflicted.collisions) {
if (conflictedOfConflicted.show && conflictedOfConflicted.label.priority >= conflicted.label.priority) {
showTextConflicted = false;
break;
}
}
if (showTextConflicted) {
queries += this._changeVisibilityHelper(conflicted, true, depth + 1);
}
}
}
return queries;
}
_updateVisibleLabels(state) {
this._visibleLabels.forEach(visible => visible.label.update(state));
}
_updateAllLabels(state) {
this._managedLabels.forEach(managedLabel => managedLabel.label.update(state));
}
_showAll(state) {
this._managedLabels.forEach(managedLabel => {
managedLabel.collisions.clear();
managedLabel.label.update(state);
this._visibleLabels.add(managedLabel);
managedLabel.show = true;
}, this);
}
_doUpdateCollisions() {
let queries = 0;
while (this._collisionUpdateHead < this._collisionUpdateBuffer.length && queries <= this.collisionUpdateMaxQueries) {
let current = this._collisionUpdateBuffer[this._collisionUpdateHead++];
let show = true;
let j = this._collisionUpdateHead - 2;
while (j >= 0) {
let other = this._collisionUpdateBuffer[j--];
if (this._isInPerformanceMode() && !other.show) {
continue;
}
if (current.doesCollide(other)) {
show = current.label.alwaysShow;
current.collisions.add(other);
other.collisions.add(current);
}
queries++;
}
current.show = show;
if (current.show) {
this._visibleLabels.add(current);
}
}
if (this._collisionUpdateHead >= this._collisionUpdateBuffer.length) {
this._collisionUpdateBuffer = [];
this._collisionUpdateHead = 0;
}
}
_startUpdateCollisions(state) {
this._visibleLabels.clear();
this._toRemoveBuffer.forEach(label => this._managedLabels.delete(label), this);
this._toRemoveBuffer.clear();
this._toAddBuffer.forEach(label => this._managedLabels.set(label, new WT_MapViewManagedTextLabel(label)), this);
this._toAddBuffer.clear();
this._lastPerformanceMode = this._isInPerformanceMode();
this._collisionUpdateBuffer = Array.from(this._managedLabels.values()).sort(
(a, b) => {
let value = b.label.priority - a.label.priority;
if (a.label.alwaysShow !== b.label.alwaysShow) {
value = a.label.alwaysShow ? -1 : 1;
}
return value;
}
);
this._collisionUpdateHead = 0;
this._collisionUpdateBuffer.forEach(managedLabel => {
managedLabel.label.update(state);
managedLabel.collisions.clear();
});
this._doUpdateCollisions();
}
_isUpdatingCollisions() {
return this._collisionUpdateBuffer.length > 0;
}
_doAddRemove(state) {
this._isInPerformanceMode() ? this._updateVisibleLabels(state) : this._updateAllLabels(state);
let queries = 0;
while (this._toRemoveBuffer.size > 0 && queries <= this.addRemoveMaxQueries) {
let labelToRemove = this._toRemoveBuffer.values().next().value;
queries += this._updateOnRemove(this._managedLabels.get(labelToRemove));
this._toRemoveBuffer.delete(labelToRemove);
}
while (this._toAddBuffer.size > 0 && queries <= this.addRemoveMaxQueries) {
let labelToAdd = this._toAddBuffer.values().next().value;
queries += this._updateOnAdd(state, new WT_MapViewManagedTextLabel(labelToAdd));
this._toAddBuffer.delete(labelToAdd);
}
}
_isAddingRemoving() {
return this._toAddBuffer.size > 0 || this._toRemoveBuffer.size > 0;
}
/**
* @param {WT_MapViewState} state
*/
onUpdate(state) {
let currentTime = state.currentTime / 1000;
let preventOverlapChanged = this._preventOverlapChanged;
this._preventOverlapChanged = false;
if (this.preventOverlap) {
if (!state.projection.range.equals(this._lastRange)) {
// map zoom changed -> clear all labels and start timer
for (let managedText of this._managedLabels.values()) {
managedText.show = false;
}
this._visibleLabels.clear();
this._mapZoomTimer = this.mapZoomUpdateDelay;
this._lastTime = currentTime;
this._lastRange.set(state.projection.range);
return;
}
if (this._mapZoomTimer > 0) {
let dt = currentTime - this._lastTime;
this._mapZoomTimer -= dt;
if (this._mapZoomTimer <= 0) {
// map zoom change timer expired -> update collisions
this._startUpdateCollisions(state);
this._updateVisibleLabels(state);
return;
}
this._lastTime = currentTime;
return;
}
let rotationDelta = Math.abs(state.projection.rotation - this._lastRotation);
rotationDelta = Math.min(rotationDelta, 360 - rotationDelta);
if (rotationDelta >= this.rotationThreshold) {
this._lastRotation = state.projection.rotation;
this._startUpdateCollisions(state);
return;
}
let forceUpdateCollisions =
preventOverlapChanged ||
(this._isInPerformanceMode() != this._lastPerformanceMode) ||
(this._toRemoveBuffer.size + this._toAddBuffer.size > this.addRemoveForceUpdateThreshold);
if (forceUpdateCollisions) {
this._startUpdateCollisions(state);
this._updateVisibleLabels(state);
return;
}
if (this._isUpdatingCollisions()) {
this._doUpdateCollisions();
this._updateVisibleLabels(state);
return;
}
} else {
if (preventOverlapChanged) {
this._showAll();
return;
}
}
if (this._isAddingRemoving()) {
this._doAddRemove(state);
} else {
this._updateVisibleLabels(state);
}
}
} |
JavaScript | class ToFileStream extends stream.Writable {
/**
* Initial parent constructor
* options.objectMode Ensure stream runs in object mode (true)
*
* options.highWaterMark (default 16KB) controls back-pressure
* limit
*
* options.decodeStrings (default to true) enables automatic
* decoding of strings into binary buffers before passing to
* the _write() method. This option is ignored in object mode
*/
constructor () {
super({ objectMode: true })
}
/**
*
* @param {String} chunk data chunk
* @param {String} encoding data encoding
* @param {Function} callback
*
* @return {null|Function} error callback or null
*/
_write (chunk, encoding, callback) {
mkdirp(path.dirname(chunk.path), (err) => {
if (err) {
return callback(err)
}
fs.writeFile(chunk.path, chunk.content, callback)
})
}
} |
JavaScript | @theme.add(props => ({ fontSize: props.big ? 20 : 12 })) //eslint-disable-line
class InlineForm extends React.Component { //eslint-disable-line
render() {
return <div>
<Button>one</Button>
<Button>two</Button>
</div>
}
} |
JavaScript | class LocalStorageClient {
constructor({name}) {
this.name = name
this.data = this.fetch()
}
save (data) {
this.data = data
try {
window.localStorage.setItem(this.name, JSON.stringify(data))
}
catch (ex) {
// localStorage is not available, we don't use any fallback storage
}
}
load () { return this.data }
fetch() {
try {
const stored = window.localStorage.getItem(this.name)
return JSON.parse(stored)
}
catch (ex) {
// localStorage is not available or the stored value is not a valid JSON
// We can't recover from either of them
}
}
} |
JavaScript | class RecentSearchesCache {
constructor({storage, historySize}) {
this.storage = storage
this.historySize = historySize
}
getRecentOptions() {
const value = this.storage.load()
if (Array.isArray(value) && value.every(item => this.isItemValid(item))) {
return value
}
return []
}
rememberSelectedOption({value, label}) {
const oldOptions = this.getRecentOptions().filter(item => item.value !== value)
oldOptions.unshift({value, label})
const newOptions = oldOptions.slice(0, this.historySize)
this.storage.save(newOptions)
}
isItemValid(item) {
return item && typeof item.label === 'string' && typeof item.value === 'string'
}
} |
JavaScript | class User {
/** authenticate user with email, password.
*
* Returns { id, username, first_name, last_name, email }
*
* Throws UnauthorizedError is user not found or wrong password.
**/
static async authenticate(email, password) {
// try to find the user first
const result = await db.query(
`SELECT id, password, first_name, last_name, email
FROM users
WHERE email = $1`,
[ email.toLowerCase() ]
);
const user = result.rows[0];
if (user) {
// compare hashed password to a new hash from password
const isValid = await bcrypt.compare(password, user.password);
if (isValid === true) {
delete user.password;
return user;
}
}
throw new UnauthorizedError('Invalid email/password');
}
/** Register user with data.
*
* Returns { username, firstName, lastName, email }
*
* Throws BadRequestError on duplicates.
**/
static async register({ password, first_name, last_name, email }) {
const duplicateCheck = await db.query(
`SELECT email
FROM users
WHERE email = $1`,
[ email.toLowerCase() ]
);
if (duplicateCheck.rows[0]) {
throw new BadRequestError(`Duplicate email: ${email}`);
}
const hashedPassword = await bcrypt.hash(password, BCRYPT_WORK_FACTOR);
const result = await db.query(
`INSERT INTO users
(password,
first_name,
last_name,
email)
VALUES ($1, $2, $3, $4)
RETURNING first_name, last_name, email, id`,
[ hashedPassword, first_name, last_name, email.toLowerCase() ]
);
const user = result.rows[0];
return user;
}
/** Given an email, return data about user.
*
* Returns { email, first_name, last_name }
*
* Throws NotFoundError if user not found.
**/
static async get(id) {
const userRes = await db.query(
`SELECT id,
email,
first_name,
last_name,
is_public
FROM users
WHERE id = $1`,
[ id ]
);
const user = userRes.rows[0];
if (!user) throw new NotFoundError(`No user: ${id}`);
return user;
}
/** Update user data with `data`.
*
* This is a "partial update" --- it's fine if data doesn't contain
* all the fields; this only changes provided ones.
*
* Data can include:
* { firstName, lastName, password, email }
*
* Returns { firstName, lastName, email }
*
* Throws NotFoundError if not found.
*
* WARNING: this function can set a new password.
* Callers of this function must be certain they have validated inputs to this
* or a serious security risks are opened.
*/
static async update(id, data) {
if (data.password) {
data.password = await bcrypt.hash(data.password, BCRYPT_WORK_FACTOR);
}
const { setCols, values } = sqlForPartialUpdate(data, {
firstName: 'first_name',
lastName: 'last_name'
});
const idVarIdx = '$' + (values.length + 1);
const querySql = `UPDATE users
SET ${setCols}, updated_at = CURRENT_TIMESTAMP
WHERE id = ${idVarIdx}
RETURNING id,
first_name,
last_name,
email,
is_public,
created_at,
updated_at`;
const result = await db.query(querySql, [ ...values, id ]);
const user = result.rows[0];
if (!user) throw new NotFoundError(`No user: ${id}`);
delete user.password;
return user;
}
/** Delete given user from database; returns undefined. */
static async remove(id) {
let result = await db.query(
`DELETE
FROM users
WHERE id = $1
RETURNING email`,
[ id ]
);
const user = result.rows[0];
if (!user) throw new NotFoundError(`No user: ${id}`);
}
static async getPublicUserByEmail(userEmail) {
const userRes = await db.query(
`SELECT id,
email,
first_name,
last_name,
is_public
FROM users
WHERE email = $1 AND is_public IS true`,
[ userEmail ]
);
const user = userRes.rows[0];
if (!user) throw new NotFoundError(`No user: ${email}`);
return user;
}
} |
JavaScript | class Description1EltHandler {
element(element) {
element.setInnerContent("Variant 1: Brought to you " +
"by cloudflare workers!");
}
} |
JavaScript | class Description2EltHandler {
element(element) {
element.setInnerContent("Variant 2: Brought to you " +
"by cloudflare workers!");
}
} |
JavaScript | class UrlElementHandler {
element(element) {
element.setAttribute('url', 'https://github.com/alexandrashaw10');
element.setInnerContent('Check out my github!');
}
} |
JavaScript | class TitleHandler {
element(element) {
element.setInnerContent('Alex Shaw\'s Website');
}
} |
JavaScript | class TitleHeader1Handler {
element(element) {
element.setInnerContent('Alex Shaw\'s Variant 1');
}
} |
JavaScript | class TitleHeader2Handler {
element(element) {
element.setInnerContent('Alex Shaw\'s Variant 2');
}
} |
JavaScript | class SnippetContext {
/**
* Creates a context from the given Snippet object.
* @param {Snippet} snippet - A snippet to create a context from.
* @param {object} options - Options object, containing the following:
* - `withVscodeUrl` - Should `vscodeUrl` be included? (default: `false`)
* @throws Will throw an error if snippet is not a Snippet.
*/
constructor(snippet, { withVscodeUrl = false } = {}) {
if (!(snippet instanceof Snippet)) {
throw new ArgsError(
"Invalid arguments. 'snippet' must be an instance of 'Snippet'."
);
}
this.snippet = snippet;
this._options = {
withVscodeUrl,
};
}
get authors() {
return this.snippet.config.cardTemplate === 'BlogSnippetCard'
? this.snippet.authors
: undefined;
}
get type() {
return this.snippet.config.cardTemplate === 'BlogSnippetCard'
? this.snippet.type
: undefined;
}
get cover() {
return this.snippet.config.cardTemplate === 'BlogSnippetCard'
? this.snippet.cover
: undefined;
}
get id() {
return this.snippet.id;
}
get title() {
return this.snippet.title;
}
get description() {
if (!this._description) {
this._description = stripMarkdownFormat(this.snippet.text.short);
}
return this._description;
}
get url() {
return this.snippet.url;
}
get slug() {
return this.snippet.slug;
}
get firstSeen() {
return this.snippet.firstSeen;
}
get lastUpdated() {
return this.snippet.lastUpdated;
}
get expertise() {
return this.snippet.expertise;
}
get language() {
return this.snippet.language;
}
get icon() {
return this.snippet.icon;
}
get tags() {
if (!this._tags) {
this._tags = {
primary: Tag.format(this.snippet.tags.primary),
all: Tag.stripExpertise(this.snippet.tags.all).map(Tag.format),
};
}
return this._tags;
}
get html() {
return this.snippet.html;
}
get actionType() {
if (this.snippet.config.isBlog) return undefined;
return this.snippet.config.isCSS
? 'cssCodepen'
: this.snippet.config.isReact
? 'codepen'
: 'copy';
}
get code() {
return this.snippet.config.isCSS ? this.snippet.code : undefined;
}
get vscodeUrl() {
return this._options.withVscodeUrl ? this.snippet.vscodeUrl : undefined;
}
static serializableAttributes = [
'id',
'title',
'description',
'url',
'slug',
'firstSeen',
'lastUpdated',
'expertise',
'language',
'icon',
'tags',
'html',
'actionType',
'code',
'authors',
'type',
'cover',
'vscodeUrl',
];
/**
* Creates a plain object for the given snippet context.
* @param {object} options - Options object, containing the following:
* - `withVscodeUrl` - Should `vscodeUrl` be included? (default: `false`)
*/
toObject = (
{ withVscodeUrl = this._options.withVscodeUrl } = this._options
) => {
this._options.withVscodeUrl = withVscodeUrl;
return SnippetContext.serializableAttributes.reduce((obj, attr) => {
const val = this[attr];
if (val !== undefined) obj[attr] = val;
return obj;
}, {});
};
} |
JavaScript | class EncoderTester {
/**
* Runs tests on encoder invokable.
* @param {class} EncoderInvokable
* @param {Object|Object[]}
*/
static test (EncoderInvokable, test) {
if (Array.isArray(test)) {
// handle multiple tests
return test.forEach(test => EncoderTester.test(EncoderInvokable, test))
}
const isEncoding =
test.direction === undefined ||
test.direction.toLowerCase() === 'encode'
it(
`should ${isEncoding ? 'encode' : 'decode'} ` +
`"${isEncoding ? test.content : test.expectedResult}" ` +
`${isEncoding ? '=>' : '<='} ` +
`"${isEncoding ? test.expectedResult : test.content}"`,
done => {
// wrap content in Chain
const content = !(test.content instanceof Chain)
? new Chain(test.content)
: test.content
// wrap expected result in Chain
const expectedResult = !(test.expectedResult instanceof Chain)
? new Chain(test.expectedResult)
: test.expectedResult
// create instance
const encoder = new EncoderInvokable()
// apply settings, if any
if (test.settings) {
encoder.setSettingValues(test.settings)
}
// create result
const result = isEncoding
? encoder.encode(content)
: encoder.decode(content)
if (result instanceof Promise) {
// resolve promise
result.then(result => {
// verify result
ChainUtil.assertEqual(result, expectedResult)
done()
})
} else {
// verify result
ChainUtil.assertEqual(result, expectedResult)
done()
}
})
}
} |
JavaScript | class CommentController {
/**
* Constructor of CommentController
*
* @param $filter - service in module ng
* @param $state - service in module ui.router.state
* @param $stateParams - service in module ui.router.state
* @param {Object} core - resolved core
* @param {Object} comment - resolved comment
* @param {Object} topic - resolved topic
* @constructs
*/
/*@ngInject;*/
constructor($filter, $state, $stateParams, core, comment, topic) {
// docs
this.core = core;
this.comment = comment;
this.topic = topic || comment.topic;
// editor
this.alert = null;
this.commentContentPattern = new RegExp(`.{${this.core.post.comment.content.min},${this.core.post.comment.content.max}}`);
this.commentContentPatternTitle = `Comment must be within ${this.core.post.comment.content.min} to ${this.core.post.comment.content.max} characters.`;
// set locals const
FILTER.set(this, $filter);
STATE.set(this, $state);
PARAM.set(this, $stateParams);
this.comment.content = PARAM.get(this).content ? this.quoteContent(PARAM.get(this).content) : this.comment.content;
}
/**
* Save a comment
*
* @param {Boolean} isValid - Form validation
*/
save(isValid) {
if (!isValid) {
return false;
} else if (!this.comment.content.match(this.commentContentPattern)) {
this.alert = { type: 'warning', message: this.commentContentPatternTitle };
return false;
}
this.alert = null;
if (this.comment._id) {
this.comment.$update({ topicId: this.topic._id })
.then(data => STATE.get(this).go('topic.view.page', { topicId: data.comment.topic, page: data.page, '#': data.comment._id }))
.catch(err => this.alert = { type: 'danger', message: err.data.message });
} else {
this.comment.$save({ topicId: PARAM.get(this).topicId })
.then(data => STATE.get(this).go('topic.view', { topicId: data.topic._id }))
.catch(err => this.alert = { type: 'danger', message: err.data.message });
}
}
/**
* Remove a comment
*
*/
remove() {
this.comment.$remove()
.then(data => STATE.get(this).go('topic.view', { topicId: this.topic._id }, { reload: true }))
.catch(err => this.alert = { type: 'danger', message: err.data.message });
}
/**
* Create a quote comment
*
* @param {String} content - content to be quoted
* @returns {String} Quote that formatted
*/
quoteContent(content) {
const source = `[${content.author.profile.username}]`;
const time = FILTER.get(this)('date')(content.date, 'short');
const ref = content.topic ? `(/t/${content.topic._id}#${content._id} "${time}")` : `(/t/${content._id} "${time}")`;
let cs = content.content.split('\n');
cs.push(`--${source}${ref}\n`);
return _.map(cs, i => `> ${i}`).join('\n');
}
} |
JavaScript | class RequestManager {
constructor () {
this.axiosTokens = new Map();
}
/**
* Create a new cancellation token based on the provided key
*
* @method getNextToken
* @param {Stirng} key The key for a given Axios cancel token
* @returns {CancelToken} Cancel token instance that can be used to cancel the request
*/
getNextToken (key) {
const token = CancelToken.source();
this.axiosTokens.set(key, token);
return token.token;
}
/**
* Cancel the axios request for the given key.
*
* @method cancelAxios
* @param {String} key The key for a given Axios cancel token
* @param {String} reason Message explaining the reason of the cancelation
*/
cancelAxios (key, reason) {
if (this.axiosTokens.has(key)) {
this.axiosTokens.get(key).cancel(reason);
this.axiosTokens.delete(key);
}
}
/**
* Cancels all Axios requests that have a key which match the prefix arg
*
* @method cancelAllRequestsWithPrefix
* @param {String} keyPrefix The key prefix for Axios cancel tokens
* @param {String} reason Message explaining the reason of the cancelation
*/
cancelAllRequestsWithPrefix (keyPrefix, reason) {
Array.from(this.axiosTokens.keys())
.filter(key => key.substring(0, keyPrefix.length) === keyPrefix)
.map(key => this.cancelAxios(key, reason));
}
/**
* Cancel a request and return a new cancellation token for the provided key
*
* @method cancelAxiosAndGetNextToken
* @param {String} key The key for a given Axios cancel token
* @returns {CancelToken} New cancellation token
*/
cancelAxiosAndGetNextToken (key) {
this.cancelAxios(key);
return this.getNextToken(key);
}
/**
* Returns the correct CSRF header for use by Axios
*
* @method getCSRFHeader
* @param {String} name Name of the cookie that stores the CSRF token value
* @returns {{X-CSRFToken: String}}
*/
getCSRFHeader (name = 'csrftoken') {
return { 'X-CSRFToken': this.getCookie(name) };
}
/**
* Returns a cookie by name from document.cookie.
* Code found at http://stackoverflow.com/a/15724300
*
* @method getCookie
* @param {String} name Cookie name
* @returns {String} Cookie value
*/
getCookie (name) {
const value = '; ' + document.cookie;
const parts = value.split('; ' + name + '=');
if (parts.length === 2) return parts.pop().split(';').shift();
return null;
}
} |
JavaScript | class AlarmClockService extends Service {
/**
*
* @param {string} host Sonos host
* @param {number} port Sonos port, default `1400`
*/
constructor (host, port) {
super()
this.name = 'AlarmClock'
this.host = host
this.port = port || 1400
this.controlURL = '/AlarmClock/Control'
this.eventSubURL = '/AlarmClock/Event'
this.SCPDURL = '/xml/AlarmClock1.xml'
}
// #region actions
/**
* CreateAlarm - Create a single alarm, all properties are required
*
* @param {Object} [options] - An object with the following properties
* @param {string} options.StartLocalTime - The start time as `hh:mm:ss`
* @param {string} options.Duration - The duration as `hh:mm:ss`
* @param {string} options.Recurrence - Repeat this alarm on [ 'ONCE' / 'WEEKDAYS' / 'WEEKENDS' / 'DAILY' ]
* @param {boolean} options.Enabled - Alarm enabled after creation
* @param {string} options.RoomUUID - The UUID of the speaker you want this alarm for
* @param {string} options.ProgramURI - The sound uri
* @param {string} options.ProgramMetaData - The sound metadata, can be empty string
* @param {string} options.PlayMode - Alarm play mode [ 'NORMAL' / 'REPEAT_ALL' / 'SHUFFLE_NOREPEAT' / 'SHUFFLE' ]
* @param {number} options.Volume - Volume between 0 and 100
* @param {boolean} options.IncludeLinkedZones - Should grouped players also play the alarm?
* @returns {Promise<{ AssignedID: number}>} response object.
*/
async CreateAlarm (options) { return this._request('CreateAlarm', options) }
/**
* DestroyAlarm - Delete an alarm
*
* @param {Object} [options] - An object with the following properties
* @param {number} options.ID - The Alarm ID from ListAlarms
* @returns {Promise<Boolean>} request succeeded
*/
async DestroyAlarm (options) { return this._request('DestroyAlarm', options) }
/**
* GetDailyIndexRefreshTime
* @returns {Promise<{ CurrentDailyIndexRefreshTime: string}>} response object.
*/
async GetDailyIndexRefreshTime () { return this._request('GetDailyIndexRefreshTime') }
/**
* GetFormat
* @returns {Promise<{ CurrentTimeFormat: string, CurrentDateFormat: string}>} response object.
*/
async GetFormat () { return this._request('GetFormat') }
/**
* GetHouseholdTimeAtStamp
*
* @param {Object} [options] - An object with the following properties
* @param {string} options.TimeStamp
* @returns {Promise<{ HouseholdUTCTime: string}>} response object.
*/
async GetHouseholdTimeAtStamp (options) { return this._request('GetHouseholdTimeAtStamp', options) }
/**
* GetTimeNow
* @returns {Promise<{ CurrentUTCTime: string, CurrentLocalTime: string, CurrentTimeZone: string, CurrentTimeGeneration: number}>} response object.
*/
async GetTimeNow () { return this._request('GetTimeNow') }
/**
* GetTimeServer
* @returns {Promise<{ CurrentTimeServer: string}>} response object.
*/
async GetTimeServer () { return this._request('GetTimeServer') }
/**
* GetTimeZone
* @returns {Promise<{ Index: number, AutoAdjustDst: boolean}>} response object.
*/
async GetTimeZone () { return this._request('GetTimeZone') }
/**
* GetTimeZoneAndRule
* @returns {Promise<{ Index: number, AutoAdjustDst: boolean, CurrentTimeZone: string}>} response object.
*/
async GetTimeZoneAndRule () { return this._request('GetTimeZoneAndRule') }
/**
* GetTimeZoneRule
*
* @param {Object} [options] - An object with the following properties
* @param {number} options.Index
* @returns {Promise<{ TimeZone: string}>} response object.
*/
async GetTimeZoneRule (options) { return this._request('GetTimeZoneRule', options) }
/**
* ListAlarms - Get the AlarmList as XML
* @remarks Some libraries also provide a ListAndParseAlarms where the alarm list xml is parsed
* @returns {Promise<{ CurrentAlarmList: string, CurrentAlarmListVersion: string}>} response object.
*/
async ListAlarms () { return this._request('ListAlarms') }
/**
* SetDailyIndexRefreshTime
*
* @param {Object} [options] - An object with the following properties
* @param {string} options.DesiredDailyIndexRefreshTime
* @returns {Promise<Boolean>} request succeeded
*/
async SetDailyIndexRefreshTime (options) { return this._request('SetDailyIndexRefreshTime', options) }
/**
* SetFormat
*
* @param {Object} [options] - An object with the following properties
* @param {string} options.DesiredTimeFormat
* @param {string} options.DesiredDateFormat
* @returns {Promise<Boolean>} request succeeded
*/
async SetFormat (options) { return this._request('SetFormat', options) }
/**
* SetTimeNow
*
* @param {Object} [options] - An object with the following properties
* @param {string} options.DesiredTime
* @param {string} options.TimeZoneForDesiredTime
* @returns {Promise<Boolean>} request succeeded
*/
async SetTimeNow (options) { return this._request('SetTimeNow', options) }
/**
* SetTimeServer
*
* @param {Object} [options] - An object with the following properties
* @param {string} options.DesiredTimeServer
* @returns {Promise<Boolean>} request succeeded
*/
async SetTimeServer (options) { return this._request('SetTimeServer', options) }
/**
* SetTimeZone
*
* @param {Object} [options] - An object with the following properties
* @param {number} options.Index
* @param {boolean} options.AutoAdjustDst
* @returns {Promise<Boolean>} request succeeded
*/
async SetTimeZone (options) { return this._request('SetTimeZone', options) }
/**
* UpdateAlarm - Update an alarm, all parameters are required.
*
* @param {Object} [options] - An object with the following properties
* @param {number} options.ID - The ID of the alarm see ListAlarms
* @param {string} options.StartLocalTime - The start time as `hh:mm:ss`
* @param {string} options.Duration - The duration as `hh:mm:ss`
* @param {string} options.Recurrence - Repeat this alarm on [ 'ONCE' / 'WEEKDAYS' / 'WEEKENDS' / 'DAILY' ]
* @param {boolean} options.Enabled - Alarm enabled after creation
* @param {string} options.RoomUUID - The UUID of the speaker you want this alarm for
* @param {string} options.ProgramURI - The sound uri
* @param {string} options.ProgramMetaData - The sound metadata, can be empty string
* @param {string} options.PlayMode - Alarm play mode [ 'NORMAL' / 'REPEAT_ALL' / 'SHUFFLE_NOREPEAT' / 'SHUFFLE' ]
* @param {number} options.Volume - Volume between 0 and 100
* @param {boolean} options.IncludeLinkedZones - Should grouped players also play the alarm?
* @remarks Some libraries support PatchAlarm where you can update a single parameter
* @returns {Promise<Boolean>} request succeeded
*/
async UpdateAlarm (options) { return this._request('UpdateAlarm', options) }
// #endregion
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.