language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class Checkbox extends Field {
//region Config
static get $name() {
return 'Checkbox';
}
// Factoryable type name
static get type() {
return 'checkbox';
}
// Factoryable type alias
static get alias() {
return 'check';
}
static get defaultConfig() {
return {
inputType : 'checkbox',
/**
* Text to display on checkbox label
* @config {String}
*/
text : '',
/**
* Checkbox color, must have match in css
* @config {String}
*/
color : null,
/**
* Sets input fields value attribute
* @config {String}
*/
value : '',
toggleGroup : null,
defaultBindProperty : 'value',
localizableProperties : ['label', 'text']
};
}
//endregion
//region Init
construct(config) {
super.construct(config);
const me = this;
if (me.initialConfig.readOnly) me.readOnly = true;
me.isConfiguring = true;
if (me.initialConfig.checked) me.checked = true;
me.isConfiguring = false;
}
// Implementation needed at this level because it has two inner elements in its inputWrap
get innerElements() {
return [
this.inputElement,
{
tag : 'label',
class : 'b-checkbox-label',
for : `${this.id}-input`,
reference : 'textLabel',
html : this.text || ''
}
];
}
get inputElement() {
const
me = this,
config = super.inputElement;
if (me.toggleGroup) {
config.dataset = {
group : me.toggleGroup
};
}
return config;
}
set element(element) {
const me = this;
super.element = element;
if (me.color) {
me.element.classList.add(me.color);
}
if (me.text) {
me.element.classList.add('b-text');
}
}
get element() {
return super.element;
}
//endregion
//region Toggle
/**
* Get/set label
* @property {String}
*/
get text() {
return this._text;
}
set text(value) {
this._text = value;
if (this.textLabel) {
this.textLabel.innerHTML = value;
}
}
/**
* Get/set value
* @property {String}
*/
get value() {
return this.checked;
}
set value(value) {
this.checked = value === 'false' ? false : Boolean(value);
}
/**
* Get/set checked state
* @property {Boolean}
*/
get checked() {
return this.input.checked;
}
set checked(checked) {
const me = this;
checked = Boolean(checked);
// Only do action if change needed.
if (!me.inputting && me.input.checked !== checked) {
me.input.checked = checked;
me.uncheckToggleGroupMembers();
// The change event does not fire on programmatic change of input.
if (!me.isConfiguring) {
me.triggerChange(false);
}
}
}
getToggleGroupMembers() {
const
me = this,
{ checked, toggleGroup, input : checkedElement } = me,
result = [];
if (checked && toggleGroup) {
DomHelper.forEachSelector(`input[type=checkbox][data-group=${toggleGroup}]`, inputEl => {
if (inputEl !== checkedElement) {
const partnerCheckbox = Widget.fromElement(inputEl);
partnerCheckbox && result.push(partnerCheckbox);
}
});
}
return result;
}
uncheckToggleGroupMembers() {
if (this.checked && this.toggleGroup) {
this.getToggleGroupMembers().forEach(widget => widget.checked = false);
}
}
/**
* Get/set readonly state (disabled underlying input)
* @property {Boolean} readOnly
*/
updateReadOnly(readOnly) {
this.input.disabled = readOnly;
// Field and Widget have a say too. Widget adds the class and fires the event
super.updateReadOnly(readOnly);
}
/**
* Check the box
*/
check() {
this.checked = true;
}
/**
* Uncheck the box
*/
uncheck() {
this.checked = false;
}
/**
* Toggle checked state. If you want to force a certain state, assign to {@link #property-checked} instead.
*/
toggle() {
this.checked = !this.checked;
}
//endregion
//region Events
/**
* Triggers events when user toggles the checkbox
* @fires beforeChange
* @fires change
* @fires action
* @private
*/
internalOnChange(event) {
/**
* Fired before checkbox is toggled. Returning false from a listener prevents the checkbox from being toggled.
* @event beforeChange
* @preventable
* @param {Core.widget.Checkbox} source Checkbox
* @param {Boolean} checked Checked or not
*/
/**
* Fired when checkbox is toggled
* @event change
* @param {Core.widget.Checkbox} source Checkbox
* @param {Boolean} checked Checked or not
*/
this.triggerChange(true);
}
/**
* Triggers events when checked state is changed
* @fires beforeChange
* @fires change
* @fires action
* @private
*/
triggerChange(userAction) {
const me = this,
{ checked } = me.input;
// Prevent uncheck if this checkbox is part of a toggleGroup (radio-button mode) ..also ensure the group has visible active members
const prevented = (!checked && userAction && me.toggleGroup && me.getToggleGroupMembers().filter(widget => widget.isVisible && !widget.disabled).length) ||
// Since Widget has Events mixed in configured with 'callOnFunctions' this will also call onBeforeChange, onChange and onAction
!me.callPreventable(
'change',
{ checked, value : checked, userAction, valid : true },
eventObject => {
me.triggerFieldChange(eventObject, false);
if (userAction) {
me.uncheckToggleGroupMembers();
}
/**
* User performed the default action (toggled the checkbox)
* @event action
* @param {Core.widget.Checkbox} source Checkbox
* @param {Boolean} checked Checked or not
*/
me.trigger('action', eventObject);
return true;
}
);
// If prevented need to rollback the checkbox input
if (prevented) {
// Input change is not preventable, so need to revert the changes
// The change event does not fire on programmatic change of input, so no need to suspend
me.input.checked = !me.input.checked;
}
}
//endregion
} |
JavaScript | class DialogItemsSample extends imodeljs_frontend_1.Extension {
constructor(name) {
super(name);
// args might override this.
}
/** Invoked the first time this extension is loaded. */
async onLoad(_args) {
/** Register the localized strings for this extension
* We'll pass the i18n member to the rest of the classes in the Extension to allow them to translate strings in the UI they implement.
*/
this._i18NNamespace = this.i18n.registerNamespace("dialogItemsSample");
await this._i18NNamespace.readFinished;
const message = this.i18n.translate("dialogItemsSample:Messages.Start");
const msgDetails = new imodeljs_frontend_1.NotifyMessageDetails(imodeljs_frontend_1.OutputMessagePriority.Info, message);
imodeljs_frontend_1.IModelApp.notifications.outputMessage(msgDetails);
if (undefined === this.uiProvider) {
this.uiProvider = new SampleUiItemsProvider_1.SampleUiItemsProvider(this.i18n);
ui_abstract_1.UiItemsManager.register(this.uiProvider);
}
SampleTool_1.SampleTool.register(this._i18NNamespace, this.i18n);
}
/** Invoked each time this extension is loaded. */
async onExecute(_args) {
// currently, everything is done in onLoad.
}
} |
JavaScript | class UnitsPopup extends React.Component {
constructor(props, context) {
super(props, context);
this._handleOK = () => {
imodeljs_frontend_1.IModelApp.quantityFormatter.useImperialFormats = (this.option === UnitsOptions.Metric ? false : true);
this._closeDialog();
};
this._handleCancel = () => {
this._closeDialog();
};
this._closeDialog = () => {
this.setState((_prevState) => ({
opened: false,
}), () => {
if (!this.state.opened)
ui_framework_1.ModalDialogManager.closeDialog();
});
};
this._optionsValue = imodeljs_frontend_1.IModelApp.quantityFormatter.useImperialFormats ? { value: UnitsOptions.Imperial } : { value: UnitsOptions.Metric };
this.applyUiPropertyChange = (updatedValue) => {
this.option = updatedValue.value.value;
};
UnitsPopup.i18n = props.i18N;
this.state = {
opened: this.props.opened,
};
this._itemsManager = new ui_abstract_1.DialogItemsManager();
this._itemsManager.applyUiPropertyChange = this.applyUiPropertyChange;
}
/** The DefaultDialogGridContainer lays out a grid React components generated from DialogItem interfaces. */
render() {
const item = { value: this._optionsValue, property: UnitsPopup._getEnumAsPicklistDescription(), editorPosition: { rowPriority: 0, columnIndex: 2 } };
this._itemsManager.items = [item];
return (React.createElement(ui_core_1.Dialog, { title: UnitsPopup.i18n.translate("dialogItemsSample:StatusBar.Units"), opened: this.state.opened, modal: true, buttonCluster: [
{ type: ui_core_1.DialogButtonType.OK, onClick: () => { this._handleOK(); } },
{ type: ui_core_1.DialogButtonType.Cancel, onClick: () => { this._handleCancel(); } },
], onClose: () => this._handleCancel(), onEscape: () => this._handleCancel(), maxWidth: 150 },
React.createElement(ui_framework_1.DefaultDialogGridContainer, { itemsManager: this._itemsManager, key: Date.now() })));
}
get option() {
return this._optionsValue.value;
}
set option(option) {
this._optionsValue = { value: option };
}
} |
JavaScript | class Interaction extends Base {
constructor(client, data, syncHandle) {
super(client);
this.syncHandle = syncHandle;
this._patch(data);
}
_patch(data) {
/**
* The ID of this interaction.
* @type {Snowflake}
* @readonly
*/
this.id = data.id;
/**
* The token of this interaction.
* @type {string}
* @readonly
*/
this.token = data.token;
/**
* The ID of the invoked command.
* @type {Snowflake}
* @readonly
*/
this.commandID = data.data.id;
/**
* The name of the invoked command.
* @type {string}
* @readonly
*/
this.commandName = data.data.name;
/**
* The options passed to the command.
* @type {Object}
* @readonly
*/
this.options = data.data.options;
/**
* The channel this interaction was sent in.
* @type {?Channel}
* @readonly
*/
this.channel = this.client.channels?.cache.get(data.channel_id) || null;
/**
* The guild this interaction was sent in, if any.
* @type {?Guild}
* @readonly
*/
this.guild = data.guild_id ? this.client.guilds?.cache.get(data.guild_id) : null;
/**
* If this interaction was sent in a guild, the member which sent it.
* @type {?Member}
* @readonly
*/
this.member = data.member ? this.guild?.members.add(data.member, false) : null;
}
/**
* The timestamp the interaction was created at.
* @type {number}
* @readonly
*/
get createdTimestamp() {
return Snowflake.deconstruct(this.id).timestamp;
}
/**
* The time the interaction was created at.
* @type {Date}
* @readonly
*/
get createdAt() {
return new Date(this.createdTimestamp);
}
/**
* Acknowledge this interaction without content.
*/
async acknowledge() {
await this.syncHandle.acknowledge();
}
/**
* Reply to this interaction.
* @param {(StringResolvable | APIMessage)?} content The content for the message.
* @param {(MessageOptions | MessageAdditions)?} options The options to provide.
*/
async reply(content, options) {
let apiMessage;
if (content instanceof APIMessage) {
apiMessage = content.resolveData();
} else {
apiMessage = APIMessage.create(this, content, options).resolveData();
if (Array.isArray(apiMessage.data.content)) {
throw new Error('Message is too long');
}
}
const resolved = await apiMessage.resolveFiles();
if (!this.syncHandle.reply(resolved)) {
const clientID =
this.client.interactionClient.clientID || (await this.client.api.oauth2.applications('@me').get()).id;
await this.client.api.webhooks(clientID, this.token).post({
auth: false,
data: resolved.data,
files: resolved.files,
});
}
}
} |
JavaScript | class UserSettings extends React.Component {
/**
* If you don’t initialize the state and you don’t bind methods, you don’t need to implement a constructor for your React component.
* The constructor for a React component is called before it is mounted (rendered).
* In this case the initial state is defined in the constructor. The state is a JS object containing two fields: name and username
* These fields are then handled in the onChange() methods in the resp. InputFields
*/
constructor() {
super();
this.state = {
username: null,
password: null,
location: null
};
}
/**
* HTTP POST request is sent to the backend.
* If the request is successful, a new user is returned to the front-end
* and its token is stored in the localStorage.
*/
async submit() {
try {
const requestBody = JSON.stringify({
username: this.state.username,
password: this.state.password,
location: this.state.location,
token: localStorage.getItem('token')
});
const response = await api.patch(`/users/profiles/${localStorage.getItem('token')}`, requestBody);
// User settings changed successfully --> navigate back to /main
this.props.history.push(`/main`);
} catch (error) {
store.addNotification({
title: 'Error',
width:300,
height:100,
message: `Something went wrong during editing the user settings: \n${handleError(error)}`,
type: 'warning', // 'default', 'success', 'info', 'warning'
container: 'top-left', // where to position the notifications
animationIn: ["animated", "fadeIn"], // animate.css classes that's applied
animationOut: ["animated", "fadeOut"], // animate.css classes that's applied
dismiss: {
duration: 4000
}
})
}
}
/**
* Every time the user enters something in the input field, the state gets updated.
* @param key (the key of the state for identifying the field that needs to be updated)
* @param value (the value that gets assigned to the identified state key)
*/
handleInputChange(key, value) {
// Example: if the key is username, this statement is the equivalent to the following one:
// this.setState({'username': value});
this.setState({ [key]: value });
}
/**
* componentDidMount() is invoked immediately after a component is mounted (inserted into the tree).
* Initialization that requires DOM nodes should go here.
* If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
* You may call setState() immediately in componentDidMount().
* It will trigger an extra rendering, but it will happen before the browser updates the screen.
*/
componentDidMount() {}
render() {
return (
<div style={sectionStyle}>
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Orbitron&family=Press+Start+2P&display=swap"
rel="stylesheet"
/>
<BaseContainer>
<FormContainer>
<Title>User Settings</Title>
<Form>
<Label>Username</Label>
<InputField
placeholder="Enter new username..."
onChange={e => {
this.handleInputChange('username', e.target.value);
}}
/>
<Label>Password</Label>
<PasswordInputField
placeholder="Enter new password.."
onChange={e => {
this.handleInputChange('password', e.target.value);
}}
/>
<Label>Location</Label>
<InputField
placeholder="Enter new location..."
onChange={e => {
this.handleInputChange('location', e.target.value);
}}
/>
<ButtonContainer>
<Button3
disabled={!this.state.username && !this.state.password && !this.state.location}
width="50%"
onClick={() => {
this.submit();
}}
>
Submit
</Button3>
</ButtonContainer>
<ButtonContainer>
<Button3
width="50%"
onClick={() => {
//this.login();
this.props.history.push(`/main`);
}}
>
Go back to main menu
</Button3>
</ButtonContainer>
</Form>
</FormContainer>
</BaseContainer>
</div>
);
}
} |
JavaScript | class NoopMarshaller extends MemoMarshaller {
marshal(value) {
return new MemoFrame({
value,
});
}
unmarshal(frame) {
return frame.value;
}
} |
JavaScript | class HistorizedManager {
constructor() {
this._actions = [];
this._lastActionId = -1;
}
/**
* Cancel last edit made by user (if any)
*/
undo() {
throw new Error("Should be overridden by subclass");
}
/**
* Restore last edit made by user (if any)
*/
redo() {
if(this.canRedo()) {
const restore = this._actions[this._lastActionId+1];
this._lastActionId++;
this._do(restore, true);
}
}
/**
* Is there any action to undo ?
* @return {boolean} True if some actions can be canceled
*/
canUndo() {
return this._lastActionId > -1;
}
/**
* Is there any action to redo ?
* @return {boolean} True if some actions can be restored
*/
canRedo() {
return this._lastActionId < this._actions.length - 1;
}
/**
* Get the amount of edits currently taken into account
* @return {int} Amount of edits
*/
getAmountEdits() {
return this._lastActionId + 1;
}
/**
* Save an action into stack
*/
_do(action, noSave) {
throw new Error("Should be overridden by subclass");
}
} |
JavaScript | class Action {
/**
* Apply action
* @param {C} context
*/
apply(context) {
}
/**
* Revert action, restoring state to just before this action was applied
* @param {C} context
*/
revert(context) {
}
} |
JavaScript | class DeployableAsset {
static init(){
this.createInstance()
}
static js(...args){ return this.instance.js(...args) }
static css(...args){ return this.instance.css(...args) }
static path(...args){ return this.instance.path(...args) }
static font(...args){ return this.instance.font(...args) }
static googleFont(...args){ return this.instance.googleFont(...args) }
static createInstance(options){
let defaults = { prefix: 'assets' }
let opts = Object.assign({}, defaults, options)
return this.instance = new this(opts)
}
constructor ( options = {} ){
this.prefix = options.prefix
}
// Create a js script tag from the asset path
js ( file_path ) {
return `<script src="${this.path(file_path)}" type="application/javascript"></script>`
}
// Create a css link tag from the asset path
css ( file_path ) {
return `<link rel="stylesheet" type="text/css" href="${this.path(file_path)}"/>`
}
// Create a html font tag from the asset path
font ( name, file_path, options = {} ) {
if ( name === undefined ) throw new Error(`Asset font requires a name`)
let defaults = {
local_name: name,
style: 'normal',
weight: '400',
format: 'woff2'
}
let opts = Object.assign({}, defaults, options)
let css = `<style type="text/css">
@font-face {
font-family: '${name}';
font-style: ${opts.style};
font-weight: ${opts.weight};
src: local('${opts.local_name}'), local('${opts.local_name}'), url(${this.path(file_path)}) format('${opts.format}');
}
</style>`
return css
}
// Use a google font
googleFont ( name ) {
if ( name === undefined ) throw new Error(`Asset google font requires a name `)
let css = `<link href="https://fonts.googleapis.com/css?family=${name}" rel="stylesheet">`
return css
}
// Generate a path, can take an array
path ( file_path ) {
if ( file_path === undefined ) throw new Error(`Asset "path" requires a file path`)
if (file_path && file_path.join) return `${this.prefix}/${file_path.join('/')}`
return `${this.prefix}/${file_path}`
}
} |
JavaScript | class OutOfBoundsGeometryDialog extends Component {
render() {
return <Modal show={this.props.show} onHide={this.props.onClose} size="lg">
<Modal.Header closeButton>
<Modal.Title>{I18n.t("Geometry outside of the bounds")}</Modal.Title>
</Modal.Header>
<Modal.Body>
{this.props.mode === Body.MODE_LEVELS && I18n.t("The level contour you just edited is partially or completely outside of the building contour. Please make sure that the level contour is mostly contained in the building.")}
{this.props.mode === Body.MODE_FEATURES && I18n.t("The feature contour you just edited is partially or completely outside of the level contour. Please make sure that the feature contour is mostly contained in the floor.")}
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={this.props.onClose}>
{I18n.t("OK")}
</Button>
</Modal.Footer>
</Modal>;
}
} |
JavaScript | class AuthComponent extends Component {
constructor (config = {}) {
const {username, password} = Config.merge(DEFAULT_CONFIG, config)
let lastSentMessage, authHeader
const outgoing = new Transform({
objectMode: true,
transform: function (msg, encoding, callback) {
if (msg.type === RTSP) {
lastSentMessage = msg
if (authHeader) {
msg.headers.Authorization = authHeader
}
}
callback(null, msg)
}
})
const incoming = new Transform({
objectMode: true,
transform: function (msg, encoding, callback) {
if (msg.type === RTSP && Rtsp.statusCode(msg.data) === UNAUTHORIZED) {
authHeader = 'Basic ' + Buffer.from(username + ':' + password).toString('base64')
const headers = msg.data.toString().split('\n')
const wwwAuth = headers.find((header) => header.match('WWW-Auth'))
const authenticator = wwwAuthenticate(username, password)(wwwAuth)
authHeader = authenticator.authorize(lastSentMessage.method, '/axis-media/media.amp')
// Retry last RTSP message
// Write will fire our outgoing transform function.
outgoing.write(lastSentMessage, callback)
} else {
// Not a message we should handle
callback(null, msg)
}
}
})
super(incoming, outgoing)
}
} |
JavaScript | class CallError extends Error {
constructor(code, error) {
super(`pRPC call failed with code ${codeToStr(code)}: ${error}`);
this.name = 'CallError';
this.code = code;
this.error = error;
}
} |
JavaScript | class AnonymousCredentialPolicy extends CredentialPolicy {
/**
* Creates an instance of AnonymousCredentialPolicy.
* @param nextPolicy -
* @param options -
*/
// The base class has a protected constructor. Adding a public one to enable constructing of this class.
/* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/
constructor(nextPolicy, options) {
super(nextPolicy, options);
}
} |
JavaScript | class AutomationClient extends ServiceClient {
/**
* Create a AutomationClient.
* @param {credentials} credentials - Credentials needed for the client to connect to Azure.
* @param {string} subscriptionId - Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.
* @param {string} [baseUri] - The base URI of the service.
* @param {object} [options] - The parameter options
* @param {Array} [options.filters] - Filters to be added to the request pipeline
* @param {object} [options.requestOptions] - Options for the underlying request object
* {@link https://github.com/request/request#requestoptions-callback Options doc}
* @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy
* @param {string} [options.acceptLanguage] - Gets or sets the preferred language for the response.
* @param {number} [options.longRunningOperationRetryTimeout] - Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30.
* @param {boolean} [options.generateClientRequestId] - When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true.
*/
constructor(credentials, subscriptionId, baseUri, options) {
if (credentials === null || credentials === undefined) {
throw new Error('\'credentials\' cannot be null.');
}
if (subscriptionId === null || subscriptionId === undefined) {
throw new Error('\'subscriptionId\' cannot be null.');
}
if (!options) options = {};
super(credentials, options);
this.apiVersion = '2015-10-31';
this.acceptLanguage = 'en-US';
this.longRunningOperationRetryTimeout = 30;
this.generateClientRequestId = true;
this.baseUri = baseUri;
if (!this.baseUri) {
this.baseUri = 'https://management.azure.com';
}
this.credentials = credentials;
this.subscriptionId = subscriptionId;
let packageInfo = this.getPackageJsonInfo(__dirname);
this.addUserAgentInfo(`${packageInfo.name}/${packageInfo.version}`);
if(options.acceptLanguage !== null && options.acceptLanguage !== undefined) {
this.acceptLanguage = options.acceptLanguage;
}
if(options.longRunningOperationRetryTimeout !== null && options.longRunningOperationRetryTimeout !== undefined) {
this.longRunningOperationRetryTimeout = options.longRunningOperationRetryTimeout;
}
if(options.generateClientRequestId !== null && options.generateClientRequestId !== undefined) {
this.generateClientRequestId = options.generateClientRequestId;
}
this.automationAccountOperations = new operations.AutomationAccountOperations(this);
this.operations = new operations.Operations(this);
this.statisticsOperations = new operations.StatisticsOperations(this);
this.usages = new operations.Usages(this);
this.certificateOperations = new operations.CertificateOperations(this);
this.connectionOperations = new operations.ConnectionOperations(this);
this.connectionTypeOperations = new operations.ConnectionTypeOperations(this);
this.credentialOperations = new operations.CredentialOperations(this);
this.dscCompilationJobOperations = new operations.DscCompilationJobOperations(this);
this.dscConfigurationOperations = new operations.DscConfigurationOperations(this);
this.agentRegistrationInformation = new operations.AgentRegistrationInformation(this);
this.dscNodeOperations = new operations.DscNodeOperations(this);
this.nodeReports = new operations.NodeReports(this);
this.dscNodeConfigurationOperations = new operations.DscNodeConfigurationOperations(this);
this.hybridRunbookWorkerGroupOperations = new operations.HybridRunbookWorkerGroupOperations(this);
this.jobOperations = new operations.JobOperations(this);
this.jobStreamOperations = new operations.JobStreamOperations(this);
this.jobScheduleOperations = new operations.JobScheduleOperations(this);
this.activityOperations = new operations.ActivityOperations(this);
this.moduleOperations = new operations.ModuleOperations(this);
this.objectDataTypes = new operations.ObjectDataTypes(this);
this.fields = new operations.Fields(this);
this.runbookDraftOperations = new operations.RunbookDraftOperations(this);
this.runbookOperations = new operations.RunbookOperations(this);
this.testJobStreams = new operations.TestJobStreams(this);
this.testJobs = new operations.TestJobs(this);
this.scheduleOperations = new operations.ScheduleOperations(this);
this.variableOperations = new operations.VariableOperations(this);
this.webhookOperations = new operations.WebhookOperations(this);
this.models = models;
msRest.addSerializationMixin(this);
}
} |
JavaScript | class GicsRequest {
/**
* Constructs a new <code>GicsRequest</code>.
* @alias module:model/GicsRequest
* @param ids {Array.<String>} The requested list of security identifiers. Accepted ID types include Market Tickers, SEDOL, ISINs, CUSIPs, or FactSet Permanent Ids. <p>***ids limit** = 1000 per request*</p> *<p>Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \"POST\" method.</p>*
*/
constructor(ids) {
GicsRequest.initialize(this, ids);
}
/**
* 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, ids) {
obj['ids'] = ids;
}
/**
* Constructs a <code>GicsRequest</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/GicsRequest} obj Optional instance to populate.
* @return {module:model/GicsRequest} The populated <code>GicsRequest</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new GicsRequest();
if (data.hasOwnProperty('ids')) {
obj['ids'] = ApiClient.convertToType(data['ids'], ['String']);
}
if (data.hasOwnProperty('startDate')) {
obj['startDate'] = ApiClient.convertToType(data['startDate'], 'String');
}
if (data.hasOwnProperty('endDate')) {
obj['endDate'] = ApiClient.convertToType(data['endDate'], 'String');
}
if (data.hasOwnProperty('frequency')) {
obj['frequency'] = Frequency.constructFromObject(data['frequency']);
}
if (data.hasOwnProperty('calendar')) {
obj['calendar'] = Calendar.constructFromObject(data['calendar']);
}
}
return obj;
}
} |
JavaScript | class FeatureAnnotation extends AbstractAnnotation {
/**
* Constructor.
* @param {!Feature} feature The OpenLayers feature.
*/
constructor(feature) {
super();
/**
* The overlay.
* @type {WebGLOverlay}
* @protected
*/
this.overlay = null;
/**
* The OpenLayers feature.
* @type {!Feature}
* @protected
*/
this.feature = feature;
listen(this.feature, EventType.CHANGE, this.handleFeatureChange, this);
this.createUI();
}
/**
* @inheritDoc
*/
disposeInternal() {
super.disposeInternal();
unlisten(this.feature, EventType.CHANGE, this.handleFeatureChange, this);
}
/**
* @inheritDoc
*/
getOptions() {
return /** @type {osx.annotation.Options|undefined} */ (this.feature.get(OPTIONS_FIELD));
}
/**
* @inheritDoc
*/
setOptions(options) {
this.feature.set(OPTIONS_FIELD, options);
}
/**
* @inheritDoc
*/
setVisibleInternal() {
if (this.overlay && this.feature) {
var options = this.getOptions();
// Only show when both the feature and the annotation config flags are true.
// Note: the overlay position is the only good way to control the visibility externally. If you try to call
// the protected setVisible function on the overlay, much pain will be in your future.
var showOverlay = this.visible && options.show;
var position = options.position;
this.overlay.setPosition(showOverlay ? position : null);
}
}
/**
* @inheritDoc
*/
createUI() {
this.options = this.getOptions();
if (this.overlay || !this.options) {
// don't create the overlay if it already exists or options are missing
return;
}
if (!this.options.position) {
var geometry = this.feature.getGeometry();
var coordinate = geometry instanceof SimpleGeometry ? geometry.getFirstCoordinate() : undefined;
this.options.position = coordinate;
}
// don't initialize with a position value as this seems to cause the overlay to jiggle on show/hide
this.overlay = new WebGLOverlay({
id: getUid(this.feature),
offset: this.options.offset,
positioning: OverlayPositioning.CENTER_CENTER
});
// create an Angular scope for the annotation UI
var compile = /** @type {!angular.$compile} */ (ui.injector.get('$compile'));
this.scope = /** @type {!angular.Scope} */ (ui.injector.get('$rootScope').$new());
Object.assign(this.scope, {
'feature': this.feature,
'overlay': this.overlay
});
// compile the template and assign the element to the overlay
var template = `<${annotationUi} feature="feature" overlay="overlay"></${annotationUi}>`;
this.element = /** @type {Element} */ (compile(template)(this.scope)[0]);
this.overlay.setElement(this.element);
// add the overlay to the map
var map = getMapContainer().getMap();
if (map) {
map.addOverlay(this.overlay);
}
this.setVisibleInternal();
}
/**
* @inheritDoc
*/
disposeUI() {
if (this.overlay) {
// remove the overlay from the map
var map = getMapContainer().getMap();
if (map) {
map.removeOverlay(this.overlay);
}
// dispose of the overlay
this.overlay.dispose();
this.overlay = null;
}
// destroy the scope
if (this.scope) {
this.scope.$destroy();
this.scope = null;
}
this.element = null;
}
/**
* Update the annotation when the feature changes.
*
* @protected
*/
handleFeatureChange() {
this.setVisibleInternal();
}
} |
JavaScript | class RecordService extends React.Component {
constructor(props) {
super(props);
const {nowMoment} = props;
this.state = {
serviceTypeId: null,
providedByEducatorName: '' ,
dateStartedText: nowMoment.format('MM/DD/YYYY'),
estimatedEndDateText: this.defaultEstimatedEndDate(nowMoment).format('MM/DD/YYYY')
};
this.onDateTextChanged = this.onDateTextChanged.bind(this);
this.onEstimatedEndDateTextChanged = this.onEstimatedEndDateTextChanged.bind(this);
this.onProvidedByEducatorTyping = this.onProvidedByEducatorTyping.bind(this);
this.onProvidedByEducatorDropdownSelect = this.onProvidedByEducatorDropdownSelect.bind(this);
this.onServiceClicked = this.onServiceClicked.bind(this);
this.onClickCancel = this.onClickCancel.bind(this);
this.onClickSave = this.onClickSave.bind(this);
}
// The default is to assume the service will last until the end of the school year.
defaultEstimatedEndDate(nowMoment) {
const schoolYear = toSchoolYear(nowMoment);
return lastDayOfSchool(schoolYear);
}
// Normalize input date text into format Rails expects, tolerating empty string as null.
// If the date is not valid, an error will be raised.
formatDateTextForRails(dateText) {
if (dateText === '') return null;
const moment = toMoment(dateText);
if (!moment.isValid()) throw new Error('invalid date: ' + dateText);
return moment.format('YYYY-MM-DD');
}
isFormComplete() {
const {serviceTypeId, providedByEducatorName} = this.state;
if (serviceTypeId === null) return false;
if (providedByEducatorName === '') return false;
return true;
}
// Both dates need to be valid, but an empty end date is allowed.
areDatesValid() {
const {dateStartedText, estimatedEndDateText} = this.state;
if (!toMoment(dateStartedText).isValid()) return false;
if (estimatedEndDateText !== '' && !toMoment(estimatedEndDateText).isValid()) return false;
return true;
}
onDateTextChanged(dateStartedText) {
this.setState({dateStartedText});
}
onEstimatedEndDateTextChanged(estimatedEndDateText) {
this.setState({estimatedEndDateText});
}
onProvidedByEducatorTyping(string) {
this.setState({ providedByEducatorName: string });
}
onProvidedByEducatorDropdownSelect(string) {
this.setState({ providedByEducatorName: string });
}
onServiceClicked(serviceTypeId, event) {
this.setState({ serviceTypeId: serviceTypeId });
}
onClickCancel(event) {
this.props.onCancel();
}
onClickSave(event) {
const {currentEducator} = this.props;
const {serviceTypeId, providedByEducatorName, dateStartedText, estimatedEndDateText} = this.state;
if (!this.isFormComplete()) {
console.error('onClickSave when form is not complete, aborting save...'); // eslint-disable-line no-console
return;
}
this.props.onSave({
serviceTypeId,
providedByEducatorName,
dateStartedText: this.formatDateTextForRails(dateStartedText),
estimatedEndDateText: this.formatDateTextForRails(estimatedEndDateText),
recordedByEducatorId: currentEducator.id
});
}
render() {
return (
<div className="RecordService" style={styles.dialog}>
{this.renderWhichService()}
{this.renderWhoAndWhen()}
{this.renderButtons()}
</div>
);
}
renderWhichService() {
const {districtKey} = this.context;
const {serviceTypeId} = this.state;
const {leftServiceTypeIds, rightServiceTypeIds} = recordServiceChoices(districtKey);
return (
<div>
<div style={{ marginBottom: 5, display: 'inline-block' }}>
Which service?
</div>
<div style={{display: 'flex', flexDirection: 'row'}}>
<div>
{leftServiceTypeIds.map(this.renderServiceButton, this)}
</div>
<div>
{rightServiceTypeIds.map(this.renderServiceButton, this)}
</div>
</div>
<div className="RecordService-service-info-box">
{this.renderServiceInfoBox(serviceTypeId)}
</div>
</div>
);
}
renderServiceInfoBox(serviceTypeId) {
const {districtKey} = this.context;
const {currentEducator, serviceTypesIndex, servicesInfoDocUrl} = this.props;
const isEnabled = (
showServicesInfo(districtKey) ||
(currentEducator.labels.indexOf('show_services_info') !== -1)
);
if (!isEnabled) return null;
// nothing selected
if (serviceTypeId === null) {
return (
<div style={{...styles.infoBox, opacity: 0.25}}>
<div>Select a service for more description.</div>
<div><Nbsp /></div>
<div><Nbsp /></div>
<div style={{marginTop: 5}}><Nbsp /></div>
</div>
);
}
// no service info
const service = serviceTypesIndex[serviceTypeId];
if (!service || (!service.description && !service.data_owner)) {
return (
<div style={{...styles.infoBox, opacity: 0.5}}>
<div>No service info found.</div>
<div><Nbsp /></div>
<div><Nbsp /></div>
<div style={{marginTop: 5}}><Nbsp /></div>
</div>
);
}
// show info
return (
<div style={styles.infoBox}>
{service.description && <div>{service.description}</div>}
{service.intensity && <div>{service.intensity}</div>}
{service.data_owner && <div>Data owner: {service.data_owner}</div>}
{servicesInfoDocUrl && (
<div style={{marginTop: 5}}>
<a href={servicesInfoDocUrl} style={{fontSize: 12}} target="_blank" rel="noopener noreferrer">Learn more</a>
</div>
)}
</div>
);
}
renderServiceInfoText(serviceTypeId) {
const {serviceTypesIndex} = this.props;
const service = serviceTypesIndex[serviceTypeId];
return _.compact([
service.name,
service.description ? service.description : null,
service.intensity ? service.intensity : null,
service.data_owner ? `Data owner: ${service.data_owner}` : null
]).join("\n");
}
renderServiceButton(serviceTypeId) {
const serviceText = this.props.serviceTypesIndex[serviceTypeId].name;
const color = serviceColor(serviceTypeId);
return (
<button
key={serviceTypeId}
className={`btn service-type service-type-${serviceTypeId}`}
onClick={this.onServiceClicked.bind(this, serviceTypeId)}
tabIndex={-1}
title={this.renderServiceInfoText(serviceTypeId)}
style={merge(styles.serviceButton, {
background: color,
outline: 0,
border: (this.state.serviceTypeId === serviceTypeId)
? '4px solid rgba(49, 119, 201, 0.75)'
: '4px solid white'
})}>
<span style={styles.serviceButtonText}>{serviceText}</span>
</button>
);
}
renderEducatorSelect() {
return (
<ProvidedByEducatorDropdown
onUserTyping={this.onProvidedByEducatorTyping}
onUserDropdownSelect={this.onProvidedByEducatorDropdownSelect}
/>
);
}
renderWhoAndWhen() {
return (
<div>
<div style={{ marginTop: 20 }}>
<div>
{'Who is working with ' + this.props.studentFirstName + '?'}
</div>
<div>
{this.renderEducatorSelect()}
</div>
</div>
<div style={{ marginTop: 20 }}>
When did they start?
</div>
<Datepicker
styles={{
datepicker: styles.datepicker,
input: styles.datepickerInput
}}
value={this.state.dateStartedText}
onChange={this.onDateTextChanged}
datepickerOptions={{
showOn: 'both',
dateFormat: 'mm/dd/yy',
minDate: undefined,
maxDate: new Date
}} />
<div style={{ marginTop: 20 }}>
When did/will they end?
</div>
<Datepicker
styles={{
datepicker: styles.datepicker,
input: styles.datepickerInput
}}
value={this.state.estimatedEndDateText}
onChange={this.onEstimatedEndDateTextChanged}
datepickerOptions={{
showOn: 'both',
dateFormat: 'mm/dd/yy',
minDate: undefined
}} />
<div style={{height: '2em'}}>
{!this.areDatesValid() && <div className="RecordService-warning" style={styles.invalidDate}>Choose a valid date (end date is optional)</div>}
</div>
</div>
);
}
renderButtons() {
const isFormComplete = this.isFormComplete();
return (
<div style={{ marginTop: 20 }}>
<button
style={{background: (isFormComplete) ? undefined : '#ccc'}}
disabled={!isFormComplete}
className="btn save"
onClick={this.onClickSave}>
Record service
</button>
<button
className="btn cancel"
style={styles.cancelRecordServiceButton}
onClick={this.onClickCancel}>
Cancel
</button>
{(this.props.requestState === 'pending') ? <span>
Saving...
</span> : this.props.requestState}
</div>
);
}
} |
JavaScript | @Radium
class EmptyPlaceholder extends React.Component {
render() {
const { iconElement, title, subtitle, style } = this.props;
return (
<StyleRoot>
<div style={[styles.container, style]}>
{ iconElement ? iconElement : <AssignmentIcon color={colorPalette.accentColor} style={styles.icon}/> }
<h3 style={styles.title}>{ title }</h3>
<small style={styles.subtitle}>{ subtitle ? subtitle : null}</small>
</div>
</StyleRoot>
);
}
} |
JavaScript | class BucketMemState {
constructor(config) {
this._config = config;
// i.e.: { bucketName: BucketInfo() }
this._memo = {};
this._config.on('bootstrap-list-update', this._cleanup.bind(this));
}
/**
* if the user somehow removes the ingestion location while kafka entries
* for the given location are still queued to be processed, we should
* remove any in-mem state for the location. This will lead to an error
* propagated by `MongoQueueProcessor.processKafkaEntry` where mongoClient
* makes a call to `getBucketAttributes`
* @return {undefined}
*/
_cleanup() {
const bootstrapList = this._config.getBootstrapList();
const sites = bootstrapList.map(b => b.site);
// all locations in memo should have an associated bootstrapList site
Object.keys(this._memo).forEach(bucket => {
const bucketInfo = this._memo[bucket];
if (bucketInfo &&
sites.indexOf(bucketInfo.getLocationConstraint()) === -1) {
delete this._memo[bucket];
}
});
}
/**
* save bucket info in memory up to REFRESH_TIMER
* @param {String} bucketName - bucket name
* @param {BucketInfo} bucketInfo - instance of BucketInfo
* @return {undefined}
*/
memoize(bucketName, bucketInfo) {
this._memo[bucketName] = bucketInfo;
// add expiry
setTimeout(() => {
delete this._memo[bucketName];
}, REFRESH_TIMER);
}
getBucketInfo(bucketName) {
return this._memo[bucketName];
}
} |
JavaScript | class M100InventoryDatacentersResponse extends BaseModel {
/**
* @constructor
* @param {Object} obj The object passed to constructor
*/
constructor(obj) {
super(obj);
if (obj === undefined || obj === null) return;
this.cityname = this.constructor.getValue(obj.cityname);
this.countryname = this.constructor.getValue(obj.countryname);
this.datacentername = this.constructor.getValue(obj.datacentername);
this.datacentercode = this.constructor.getValue(obj.datacentercode);
this.datacenteruuid = this.constructor.getValue(obj.datacenteruuid);
this.interfacetypes = this.constructor.getValue(obj.interfacetypes);
this.operatorname = this.constructor.getValue(obj.operatorname);
}
/**
* Function containing information about the fields of this model
* @return {array} Array of objects containing information about the fields
*/
static mappingInfo() {
return super.mappingInfo().concat([
{ name: 'cityname', realName: 'cityname' },
{ name: 'countryname', realName: 'countryname' },
{ name: 'datacentername', realName: 'datacentername' },
{ name: 'datacentercode', realName: 'datacentercode' },
{ name: 'datacenteruuid', realName: 'datacenteruuid' },
{ name: 'interfacetypes', realName: 'interfacetypes', array: true },
{ name: 'operatorname', realName: 'operatorname' },
]);
}
/**
* Function containing information about discriminator values
* mapped with their corresponding model class names
*
* @return {object} Object containing Key-Value pairs mapping discriminator
* values with their corresponding model classes
*/
static discriminatorMap() {
return {};
}
} |
JavaScript | class HelloComponent extends React.Component {
static propTyles = {
message: PropTypes.string,
pending: PropTypes.bool.isRequired,
sayHello: PropTypes.func.isRequuired,
sayHelloAsync: PropTypes.func.isRequuired
};
constructor(props) {
super(props);
this.state = {message: ''};
}
onSubmit = (values) => {
log.debug('submitting form');
let fn = values.async ? this.props.sayHelloAsync : this.props.sayHello;
fn(values.message);
}
render() {
const { handleSubmit } = this.props
const buttonStyle={padding:'1em', margin: '1em'};
const inputStyle={padding: '1em', margin: '1em'};
const labelStyle={marginLeft: '1em'};
return (
<div style={{padding:'2em'}}>
<form onSubmit={handleSubmit(this.onSubmit)}>
<Field
inputStyle={inputStyle}
labelStyle={labelStyle}
name="message"
type="text"
label="Message"
component={renderField}
/>
<div style={{marginLeft:'1em'}}>
Async
<Field
name="async"
id="async"
component="input"
type="checkbox"
style={{marginLeft:'1em'}}
/>
</div>
<br/>
<button style={buttonStyle} disabled={this.props.pending} onClick={this.hello}>Say Hello</button>
</form>
<div style={{padding:'1em'}}>
{this.props.pending ? 'please wait...': ''}
{this.props.message ? 'Hello ' + this.props.message : ''}
</div>
</div>
);
}
} |
JavaScript | class TileBaseFile {
/**
* @constructor
*
* @param {String} loc Location of TileBase file
*/
constructor(loc) {
this.isopen = false;
this.loc = loc;
this.handler = false
}
async open() {
this.handler = await fs.open((new URL(this.loc)).pathname);
this.isopen = true;
}
/**
* Return a buffer containing the requested bytes
*
* @param {BigInt} position Byte to start reading
* @param {BigInt} size Number of bytes to read
*
* @returns {Buffer}
*/
async read(position, size) {
const buff = Buffer.alloc(size);
await this.handler.read(buff, 0, size, position);
return buff;
}
async close() {
await this.handler.close();
this.isopen = false;
}
} |
JavaScript | class MesaSpeechRecognizerService extends SpeechRecognizerServiceCore {
// TODO: Document
constructor(...args) {
super(MesaSubscriptionKeyManagementService, ...args);
this.setTitle("Mesa Speech Recognizer Service");
}
/**
* For documentation purposes, retrieves the service provider URL which
* supplies the speech recognition to ReShell.
*
* @return {string}
*/
getServiceProviderURL() {
return "https://azure.microsoft.com/en-us/services/cognitive-services/speech-to-text/";
}
/**
* @param {MediaStream} mediaStream
* @param {Object} props TODO: Document props
* @return {Promise<DeepgramSpeechRecognizer>}
*/
async _createRecognizer(mediaStream, { subscriptionKey }) {
return new MesaSpeechRecognizer(mediaStream, subscriptionKey);
}
/**
* Starts the speech recognition engine.
*
* @return {Promise<void>}
*/
async startRecognizing() {
const subscriptionKey = await this._apiKeyManagementService.acquireAPIKey();
return super.startRecognizing({ subscriptionKey });
}
} |
JavaScript | class EventObjectEmitterView {
/**
* @param {ModelInstance} instance
* @param {EventObjectEmitter} emitter
*/
constructor(instance, emitter) {
this.instance = instance;
this.emitter = emitter;
this.lastValue = 0;
this.currentEmission = 0;
}
/**
*
*/
reset() {
this.lastValue = 0;
}
/**
*
*/
update() {
if (this.instance.allowParticleSpawn) {
this.emitter.getValue(valueHeap, this.instance);
let value = valueHeap[0];
if (value === 1 && value !== this.lastValue) {
this.currentEmission += 1;
}
this.lastValue = value;
}
}
} |
JavaScript | class UserServices {
/**
* Fetches a User by his/her email.
* @memberof UserService
* @param { String } email - The email address of the user.
* @returns { Promise< Object | Error | Null > } A promise that resolves or rejects
* with a user resource or a DB Error.
*/
static async fetchUserByEmail(email) {
return db.oneOrNone(findUserByEmail, [email]);
}
/**
* Fetches a User by his/her email.
* @memberof UserService
* @param { String } username - The username of the user.
* @returns { Promise< Object | Error | Null > } A promise that resolves or rejects
* with a user resource or a DB Error.
*/
static async fetchUserByUsername(username) {
return db.oneOrNone(findUserByUsername, [username]);
}
/**
* Fetches a User by his/her phone_no.
* @memberof UserService
* @param { String } phone_number - The username of the user.
* @returns { Promise< Object | Error | Null > } A promise that resolves or rejects
* with a user resource or a DB Error.
*/
static async fetchUserByPhone(phone_number) {
return db.oneOrNone(findUserByPhone, [phone_number]);
}
/**
* Creates a User.
* @memberof UserService
* @param { Object } body - The body containing user info.
* @returns { Promise< Object | Error | Null > } A promise that resolves or rejects
* with a user resource or a DB Error.
*/
static async createUser(body) {
const {
first_name, middle_name, last_name, username, email, phone_number,
date_of_birth, address, password
} = body;
const { hash, salt } = hashPassword(password);
const payload = [
first_name, middle_name, last_name, username, email, phone_number,
date_of_birth, address, hash, salt
];
const result = await db.oneOrNone(createUser, payload);
logger.info(result, 'SUCCESS');
return result;
}
/**
* Fetches a User by his/her email.
* @memberof UserService
* @param { String } login_details - The username of the user.
* @returns { Promise< Object | Error | Null > } A promise that resolves or rejects
* with a user resource or a DB Error.
*/
static async fetchUserByEmailOrUsername(login_details) {
return db.oneOrNone(findUserByEmailOrUsername, [login_details]);
}
/**
* Login a User by his/her email or username.
* @memberof UserService
* @param { String } body - The username of the user.
* @returns { Promise< Object | Error | Null > } A promise that resolves or rejects
* with a user resource or a DB Error.
*/
static async loginUser(body) {
const { login_details } = body;
const result = await db.oneOrNone(findUserByEmailOrUsername, [login_details]);
const {
id, first_name, middle_name, last_name, username, email,
phone_no, date_of_birth, transaction_pin
} = result;
const token = Helper.addTokenToUser(result);
const data = {
id,
first_name,
middle_name,
last_name,
email,
username,
phone_no,
date_of_birth,
token,
hasPin: !!transaction_pin
};
logger.info(data, 'SUCCESS');
return data;
}
/**
* Saves a user eth wallet password
* @memberof UserService
* @param { String } password - The password of the user
* @param { String } id - The id of the user
* @returns { Promise< Object | Error | Null > } A promise that resolves or rejects
* with a user resource or a DB Error.
*/
static async saveEthPassword(password, id) {
return db.none(saveUserEthPassword, [password, id]);
}
/**
* Saves user wallet address
* @memberof UserService
* @param { String } user_id - The id of the user.
* @param { String } coin - The type of coin.
* @param { String } address - The address of the user.
* @returns { Promise< Object | Error | Null > } A promise that resolves or rejects
* with a user resource or a DB Error.
*/
static async saveWalletAddress(user_id, coin, address) {
return db.oneOrNone(saveWalletAddress, [user_id, coin, address]);
}
/**
* Saves user wallet address
* @memberof UserService
* @param { String } pin - The pin for tx
* @param { String } userId - The id of the user.
* @returns { Promise< Object | Error | Null > } A promise that resolves or rejects
* with a user resource or a DB Error.
*/
static updateTxPin(pin, userId) {
const { hash, salt } = hashPIN(pin);
return db.none(addPinToUser, [hash, salt, userId]);
}
/**
* Saves user wallet key
* @memberof UserService
* @param { String } user_id - The id of the user.
* @param { String } coin - The type of coin.
* @param { String } address - The address of the user.
* @returns { Promise< Object | Error | Null > } A promise that resolves or rejects
* with a user resource or a DB Error.
*/
static async saveBtcWalletAddress(user_id, coin, address, private_key, public_key, passphrase) {
const result = await this.saveWalletAddress(user_id, coin, address);
return db.none(saveWalletKey, [result.id, private_key, public_key, passphrase]);
}
} |
JavaScript | class VRView {
/**
* Create a volume rendering scene
* @param {HTMLElement} element - the target html element to render the scene
*/
constructor(element) {
this.VERBOSE = false;
this.element = element;
this.renderer = null;
this.renderWindow = null;
this._genericRenderWindow = null;
this.actor = null;
this._raysDistance = null;
this._blurOnInteraction = null;
// piecewise gaussian widget stuff
this.PGwidgetElement = null;
this.PGwidget = null;
this.gaussians = null;
this._PGwidgetLoaded = false;
// crop widget
this._cropWidget = null;
// normalized ww wl
this.ww = 0.1;
this.wl = 0.4;
// absolute ww wl
this.wwwl = [0, 0];
// LUT options
this._rangeLUT = null;
this._rescaleLUT = false; // cannot initialize true (must set lut before)
// measurement state
this._measurementState = null;
this.initVR();
}
/**
* wwwl
* @type {Array}
*/
set wwwl(value) {
if (!this.actor) {
return;
}
const dataArray = this.actor
.getMapper()
.getInputData()
.getPointData()
.getScalars();
const range = dataArray.getRange();
let rel_ww = value[0] / (range[1] - range[0]);
let rel_wl = (value[1] - range[0]) / range[1];
this.wl = rel_wl;
this.ww = rel_ww;
if (this.PGwidget) {
this.updateWidget();
}
}
get wwwl() {
const dataArray = this.actor
.getMapper()
.getInputData()
.getPointData()
.getScalars();
const range = dataArray.getRange();
let abs_ww = rel_ww * (range[1] - range[0]);
let abs_wl = rel_wl * range[1] + range[0];
return [abs_ww, abs_wl];
}
/**
* raysDistance
* @type {Number}
*/
set resolution(value) {
this._raysDistance = 1 / value;
this.actor.getMapper().setSampleDistance(this._raysDistance);
let maxSamples = value > 1 ? value * 1000 : 1000;
this.actor.getMapper().setMaximumSamplesPerRay(maxSamples);
this.renderWindow.render();
}
get resolution() {
return Math.round(1 / this._raysDistance);
}
/**
* Presets
* @type {Array}
*/
get presetsList() {
return vtkColorMaps.rgbPresetNames;
}
/**
* PGwidgetElement (set null to hide)
* @type {HTMLelement}
*/
set widgetElement(element) {
this.PGwidgetElement = element;
let h = element.offsetHeight ? element.offsetHeight - 5 : 100;
let w = element.offsetWidth ? element.offsetWidth - 5 : 300;
this.PGwidget.setSize(w, h);
this.PGwidget.setContainer(this.PGwidgetElement);
this.PGwidget.render();
}
/**
* Flag to set lut rescaling on opacity range
* @type {bool}
*/
set rescaleLUT(bool) {
this._rescaleLUT = bool;
let range;
if (this._rescaleLUT && this.PGwidget) {
range = this.PGwidget.getOpacityRange();
} else {
range = this.actor
.getMapper()
.getInputData()
.getPointData()
.getScalars()
.getRange();
}
this.ctfun.setMappingRange(...range);
this.ctfun.updateRange();
}
/**
* Set range to apply lut !!! WIP
* @type {Array}
*/
set rangeLUT([min, max]) {
this._rangeLUT = [min, max];
this.actor
.getProperty()
.getRGBTransferFunction(0)
.setMappingRange(min, max);
}
/**
* Crop widget on / off
* @type {bool}
*/
set cropWidget(visible) {
if (!this._cropWidget) this.setupCropWidget();
this._cropWidget.setVisibility(visible);
this._widgetManager.renderWidgets();
this.renderWindow.render();
}
/**
* Set colormap and opacity function
* lutName - as in presets list
* @type {String}
*/
set lut(lutName) {
// set up color transfer function
const lookupTable = vtkColorTransferFunction.newInstance();
lookupTable.applyColorMap(vtkColorMaps.getPresetByName(lutName));
// update lookup table mapping range based on input dataset
let range;
if (this._rescaleLUT && this._PGwidgetLoaded) {
range = this.PGwidget.getOpacityRange();
} else {
range = this.actor
.getMapper()
.getInputData()
.getPointData()
.getScalars()
.getRange();
}
// TODO a function to set custom mapping range (unbind from opacity)
lookupTable.setMappingRange(...range);
lookupTable.updateRange();
this.actor.getProperty().setRGBTransferFunction(0, lookupTable);
// set up opacity function (values will be set by PGwidget)
const piecewiseFun = vtkPiecewiseFunction.newInstance();
this.actor.getProperty().setScalarOpacity(0, piecewiseFun);
this.ctfun = lookupTable;
this.ofun = piecewiseFun;
this.updateWidget();
}
/**
* Toggle blurring on interaction (Increase performance)
* @type {bool} toggle - if true, blur on interaction
*/
set blurOnInteraction(toggle) {
this._blurOnInteraction = toggle;
let interactor = this.renderWindow.getInteractor();
let mapper = this.actor.getMapper();
if (toggle) {
interactor.onLeftButtonPress(() => {
mapper.setSampleDistance(this._raysDistance * 5);
});
interactor.onLeftButtonRelease(() => {
mapper.setSampleDistance(this._raysDistance);
// update picking plane
let camera = this.renderer.getActiveCamera();
if (this._pickingPlane)
this._pickingPlane.setNormal(camera.getDirectionOfProjection());
this.renderWindow.render();
});
} else {
interactor.onLeftButtonPress(() => {
mapper.setSampleDistance(this._raysDistance);
});
interactor.onLeftButtonRelease(() => {
mapper.setSampleDistance(this._raysDistance);
// update picking plane
let camera = this.renderer.getActiveCamera();
if (this._pickingPlane)
this._pickingPlane.setNormal(camera.getDirectionOfProjection());
this.renderWindow.render();
});
}
}
/**
* Initialize rendering scene
* @private
*/
initVR() {
const genericRenderWindow = vtkGenericRenderWindow.newInstance();
genericRenderWindow.setContainer(this.element);
genericRenderWindow.setBackground([0, 0, 0]);
//add custom resize cb
genericRenderWindow.onResize(() => {
// bypass genericRenderWindow resize method (do not consider devicePixelRatio)
// https://kitware.github.io/vtk-js/api/Rendering_Misc_GenericRenderWindow.html
let size = [
genericRenderWindow.getContainer().getBoundingClientRect().width,
genericRenderWindow.getContainer().getBoundingClientRect().height
];
genericRenderWindow
.getRenderWindow()
.getViews()[0]
.setSize(size);
if (this.VERBOSE) console.log("resize", size);
});
// resize callback
window.addEventListener("resize", evt => {
genericRenderWindow.resize();
});
genericRenderWindow.resize();
this.renderer = genericRenderWindow.getRenderer();
this.renderWindow = genericRenderWindow.getRenderWindow();
this._genericRenderWindow = genericRenderWindow;
this.setupPGwidget();
}
/**
* Set the image to be rendered
* @param {ArrayBuffer} image - The image content data as buffer array
*/
setImage(image) {
// clean scene
this.renderer.removeAllVolumes();
let actor = createVolumeActor(image);
this.actor = actor;
this.lut = "Grayscale";
this.resolution = 2;
this.renderer.addVolume(actor);
this.setCamera(actor.getCenter());
if (this.PGwidget) {
this.updateWidget();
this.setWidgetCallbacks();
}
// TODO implement a strategy to set rays distance
// TODO interactors switching (ex. blurring or wwwl or crop)
this.setActorProperties();
this.setupInteractor();
this.blurOnInteraction = true;
this._genericRenderWindow.resize();
this.renderer.resetCamera();
this.renderWindow.render();
}
/**
* Set camera lookat point
* @param {Array} center - As [x,y,z]
*/
setCamera(center) {
this.renderer.resetCamera();
this.renderer.getActiveCamera().zoom(1.5);
this.renderer.getActiveCamera().elevation(70);
this.renderer.getActiveCamera().setViewUp(0, 0, 1);
this.renderer
.getActiveCamera()
.setFocalPoint(center[0], center[1], center[2]);
this.renderer
.getActiveCamera()
.setPosition(center[0], center[1] - 2000, center[2]);
this.renderer.getActiveCamera().setThickness(10000);
this.renderer.getActiveCamera().setParallelProjection(true);
}
/**
* Get vtk LUTs list
* @returns {Array} - Lut list as array of strings
*/
getLutList() {
return vtkColorMaps.rgbPresetNames;
}
/**
* Set actor appearance properties
* TODO
*/
setActorProperties() {
this.actor.getProperty().setScalarOpacityUnitDistance(0, 30.0);
this.actor.getProperty().setInterpolationTypeToLinear();
this.actor.getProperty().setUseGradientOpacity(0, true);
this.actor.getProperty().setGradientOpacityMinimumValue(0, 2);
this.actor.getProperty().setGradientOpacityMinimumOpacity(0, 0.0);
this.actor.getProperty().setGradientOpacityMaximumValue(0, 20);
this.actor.getProperty().setGradientOpacityMaximumOpacity(0, 2.0);
this.actor.getProperty().setShade(true);
this.actor.getProperty().setAmbient(0.3);
this.actor.getProperty().setDiffuse(0.7);
this.actor.getProperty().setSpecular(0.3);
this.actor.getProperty().setSpecularPower(0.8);
}
/**
* Setup crop widget
*/
setupCropWidget() {
const widgetManager = vtkWidgetManager.newInstance();
widgetManager.setRenderer(this.renderer);
const widget = vtkImageCroppingWidget.newInstance();
const viewWidget = widgetManager.addWidget(widget);
const cropState = widget.getWidgetState().getCroppingPlanes();
cropState.onModified(() => {
const planes = getCroppingPlanes(image, cropState.getPlanes());
mapper.removeAllClippingPlanes();
planes.forEach(plane => {
mapper.addClippingPlane(plane);
});
mapper.modified();
});
// wire up the reader, crop filter, and mapper
let mapper = this.actor.getMapper();
let image = mapper.getInputData();
widget.copyImageDataDescription(image);
widget.set({
faceHandlesEnabled: true,
edgeHandlesEnabled: true,
cornerHandlesEnabled: true
});
widgetManager.enablePicking();
this._widgetManager = widgetManager;
this._cropWidget = widget; // or viewWidget ?
this.renderWindow.render();
}
/**
* Append a vtkPiecewiseGaussianWidget into the target element
* @private
* @param {HTMLElement} widgetContainer - The target element to place the widget
*/
setupPGwidget() {
let containerWidth = this.PGwidgetElement
? this.PGwidgetElement.offsetWidth - 5
: 300;
let containerHeight = this.PGwidgetElement
? this.PGwidgetElement.offsetHeight - 5
: 100;
const PGwidget = vtkPiecewiseGaussianWidget.newInstance({
numberOfBins: 256,
size: [containerWidth, containerHeight]
});
// TODO expose style
PGwidget.updateStyle({
backgroundColor: "rgba(255, 255, 255, 0.6)",
histogramColor: "rgba(50, 50, 50, 0.8)",
strokeColor: "rgb(0, 0, 0)",
activeColor: "rgb(255, 255, 255)",
handleColor: "rgb(50, 150, 50)",
buttonDisableFillColor: "rgba(255, 255, 255, 0.5)",
buttonDisableStrokeColor: "rgba(0, 0, 0, 0.5)",
buttonStrokeColor: "rgba(0, 0, 0, 1)",
buttonFillColor: "rgba(255, 255, 255, 1)",
strokeWidth: 1,
activeStrokeWidth: 1.5,
buttonStrokeWidth: 1,
handleWidth: 1,
iconSize: 0, // Can be 0 if you want to remove buttons (dblClick for (+) / rightClick for (-))
padding: 1
});
// to hide widget
PGwidget.setContainer(this.PGwidgetElement); // Set to null to hide
// resize callback
window.addEventListener("resize", evt => {
PGwidget.setSize(
this.PGwidgetElement.offsetWidth - 5,
this.PGwidgetElement.offsetHeight - 5
);
PGwidget.render();
});
this.PGwidget = PGwidget;
}
/**
* Update the PGwidget after an image has been loaded
* @private
*/
updateWidget() {
const dataArray = this.actor
.getMapper()
.getInputData()
.getPointData()
.getScalars();
this.PGwidget.setDataArray(dataArray.getData());
let gaussians = this.PGwidget.getGaussians();
if (gaussians.length > 0) {
let gaussian = gaussians[0];
gaussian.position = this.wl;
gaussian.width = this.ww;
this.PGwidget.setGaussians([gaussian]);
} else {
// TODO initilize in a smarter way
const default_opacity = 1.0;
const default_bias = 0.0; // xBias
const default_skew = 1.8; // yBias
this.PGwidget.addGaussian(
this.wl,
default_opacity,
this.ww,
default_bias,
default_skew
); // x, y, ampiezza, sbilanciamento, andamento
}
this.PGwidget.applyOpacity(this.ofun);
this.PGwidget.setColorTransferFunction(this.ctfun);
this.ctfun.onModified(() => {
this.PGwidget.render();
this.renderWindow.render();
});
this._PGwidgetLoaded = true;
}
/**
* Binds callbacks to user interactions on PGwidget
* @private
*/
setWidgetCallbacks() {
this.PGwidget.bindMouseListeners();
this.PGwidget.onAnimation(start => {
if (start) {
this.renderWindow.getInteractor().requestAnimation(this.PGwidget);
} else {
this.renderWindow.getInteractor().cancelAnimation(this.PGwidget);
}
});
this.PGwidget.onOpacityChange(widget => {
this.PGwidget = widget;
this.gaussians = widget.getGaussians().slice(); // store
this.PGwidget.applyOpacity(this.ofun);
if (!this.renderWindow.getInteractor().isAnimating()) {
this.renderWindow.render();
}
if (this._rescaleLUT && this.PGwidget) {
const range = this.PGwidget.getOpacityRange();
this.ctfun.setMappingRange(...range);
this.ctfun.updateRange();
}
});
}
/**
* Init interactor
* @private
*/
setupInteractor() {
// TODO setup from user
const rotateManipulator = vtkMouseCameraTrackballRotateManipulator.newInstance(
{ button: 1 }
);
const panManipulator = vtkMouseCameraTrackballPanManipulator.newInstance({
button: 3,
control: true
});
const zoomManipulator = vtkMouseCameraTrackballZoomManipulator.newInstance({
button: 3,
scrollEnabled: true
});
const rangeManipulator = vtkMouseRangeManipulator.newInstance({
button: 1,
shift: true
});
let self = this;
function getWL() {
return self.wl;
}
function getWW() {
return self.ww;
}
function setWL(v) {
let wl = self.wl + (v - self.wl) / 25;
self.wl = wl;
let gaussians = self.PGwidget.getGaussians().slice(); // NOTE: slice() to clone!
gaussians[0].position = self.wl; //TODO: foreach
self.PGwidget.setGaussians(gaussians);
}
function setWW(v) {
let ww = self.ww + (v - self.ww) / 5;
self.ww = ww;
let gaussians = self.PGwidget.getGaussians().slice(); // NOTE: slice() to clone!
gaussians[0].width = self.ww; //TODO: foreach
self.PGwidget.setGaussians(gaussians);
}
rangeManipulator.setVerticalListener(-1, 1, 0.001, getWL, setWL);
rangeManipulator.setHorizontalListener(0.1, 2.1, 0.001, getWW, setWW);
const interactorStyle = vtkInteractorStyleManipulator.newInstance();
interactorStyle.addMouseManipulator(rangeManipulator);
interactorStyle.addMouseManipulator(rotateManipulator);
interactorStyle.addMouseManipulator(panManipulator);
interactorStyle.addMouseManipulator(zoomManipulator);
interactorStyle.setCenterOfRotation(this.actor.getCenter());
this.renderWindow.getInteractor().setInteractorStyle(interactorStyle);
// clear measurements on interactions
this.renderWindow
.getInteractor()
.onMouseWheel(() => this.resetMeasurementState());
this.renderWindow
.getInteractor()
.onRightButtonPress(() => this.resetMeasurementState());
}
/**
* Reset measurement state to default
* @param {*} measurementState
*/
resetMeasurementState(state) {
if (this._measurementState) {
this._measurementState.p1 = new Array(2);
this._measurementState.p2 = new Array(2);
this._measurementState.p3 = new Array(2);
this._measurementState.p1_world = new Array(2);
this._measurementState.p2_world = new Array(2);
this._measurementState.p3_world = new Array(2);
this._measurementState.label = null;
} else if (state) {
state.p1 = new Array(2);
state.p2 = new Array(2);
state.p3 = new Array(2);
state.p1_world = new Array(2);
state.p2_world = new Array(2);
state.p3_world = new Array(2);
state.label = null;
}
}
/**
* Set active tool
* ("Length/Angle", {mouseButtonMask:1}, measurementState)
* * @param {*} toolName
* @param {*} options
* @param {*} measurementState
*/
setTool(toolName, options, measurementState) {
if (this._leftButtonCb) {
this._leftButtonCb.unsubscribe();
}
switch (toolName) {
case "Length":
this._initPicker(measurementState, toolName);
break;
case "Angle":
this._initPicker(measurementState, toolName);
break;
case "Rotation":
this.resetMeasurementState(measurementState);
this.setupInteractor();
break;
default:
console.warn("No tool found for", toolName);
}
}
/**
* initPicker
*/
_initPicker(state, mode) {
// no blur when measure
this.blurOnInteraction = false;
// de-activate rotation
let rotateManipulator = this.renderWindow
.getInteractor()
.getInteractorStyle()
.getMouseManipulators()
.filter(i => {
return i.getClassName() == "vtkMouseCameraTrackballRotateManipulator";
})
.pop();
this.renderWindow
.getInteractor()
.getInteractorStyle()
.removeMouseManipulator(rotateManipulator);
// ----------------------------------------------------------------------------
// Setup picking interaction
// ----------------------------------------------------------------------------
// Only try to pick points
const picker = vtkPointPicker.newInstance();
picker.setPickFromList(1);
picker.initializePickList();
if (!this._pickingPlane) {
// add a 1000x1000 plane
// TODO this is slow the first time we pick, maybe we could use cellPicker and decrease resolution
const plane = vtkPlaneSource.newInstance({
xResolution: 1000,
yResolution: 1000
});
let camera = this.renderer.getActiveCamera();
plane.setPoint1(0, 0, 1000);
plane.setPoint2(1000, 0, 0);
plane.setCenter(this.actor.getCenter());
plane.setNormal(camera.getDirectionOfProjection());
const mapper = vtkMapper.newInstance();
mapper.setInputConnection(plane.getOutputPort());
const planeActor = vtkActor.newInstance();
planeActor.setMapper(mapper);
planeActor.getProperty().setOpacity(0.01); // with opacity = 0 it is ignored by picking
this.renderer.addActor(planeActor);
this._pickingPlane = plane;
this._planeActor = planeActor;
}
// add picking plane to pick list
picker.addPickList(this._planeActor);
// Pick on mouse left click
this._leftButtonCb = this.renderWindow
.getInteractor()
.onLeftButtonPress(callData => {
if (this.renderer !== callData.pokedRenderer) {
return;
}
const pos = callData.position;
const point = [pos.x, pos.y, 0.0];
picker.pick(point, this.renderer);
if (picker.getActors().length === 0) {
const pickedPoint = picker.getPickPosition();
if (this.VERBOSE)
console.log(`No point picked, default: ${pickedPoint}`);
// const sphere = vtkSphereSource.newInstance();
// sphere.setCenter(pickedPoint);
// sphere.setRadius(0.01);
// const sphereMapper = vtkMapper.newInstance();
// sphereMapper.setInputData(sphere.getOutputData());
// const sphereActor = vtkActor.newInstance();
// sphereActor.setMapper(sphereMapper);
// sphereActor.getProperty().setColor(1.0, 0.0, 0.0);
// this.renderer.addActor(sphereActor);
} else {
const pickedPoints = picker.getPickedPositions();
const pickedPoint = pickedPoints[0]; // always a single point on a plane
if (this.VERBOSE) console.log(`Picked: ${pickedPoint}`);
// const sphere = vtkSphereSource.newInstance();
// sphere.setCenter(pickedPoint);
// sphere.setRadius(10);
// const sphereMapper = vtkMapper.newInstance();
// sphereMapper.setInputData(sphere.getOutputData());
// const sphereActor = vtkActor.newInstance();
// sphereActor.setMapper(sphereMapper);
// sphereActor.getProperty().setColor(0.0, 1.0, 0.0);
// this.renderer.addActor(sphereActor);
// canvas coord
const wPos = vtkCoordinate.newInstance();
wPos.setCoordinateSystemToWorld();
wPos.setValue(...pickedPoint);
const displayPosition = wPos.getComputedDisplayValue(this.renderer);
// apply changes on state based on active tool
applyStrategy(state, displayPosition, pickedPoint, mode);
if (this.VERBOSE) console.log(state);
this._measurementState = state;
}
this.renderWindow.render();
});
}
/**
* Reset view
*/
resetView() {
let center = this.actor.getCenter();
console.log(center);
this.setCamera(center);
this.renderWindow.render();
}
/**
* on resize callback
*/
resize() {
// TODO: debounce for performance reasons?
this._genericRenderWindow.resize();
}
/**
* Destroy webgl content and release listeners
*/
destroy() {
// leave these comments for now
// this.PGwidget.delete();
// this.actor.getMapper().delete();
// this.actor.delete();
// this.renderWindow.getInteractor().delete();
// this.renderWindow.delete();
// this.renderer.delete();
// this.renderer.delete();
// this.renderer = null;
// this.renderWindow.getInteractor().delete();
// this.renderWindow.delete();
// this.renderWindow = null;
this.element = null;
this._genericRenderWindow.delete();
this._genericRenderWindow = null;
if (this.actor) {
this.actor.getMapper().delete();
this.actor.delete();
this.actor = null;
}
if (this._planeActor) {
this._planeActor.getMapper().delete();
this._planeActor.delete();
this._planeActor = null;
}
if (this.PGwidgetElement) {
this.PGwidgetElement = null;
this.PGwidget.getCanvas().remove();
this.PGwidget.delete();
this.PGwidget = null;
this.gaussians = null;
}
if (this._cropWidget) {
this._cropWidget.delete();
this._cropWidget = null;
}
}
} |
JavaScript | class OwnPropertyDescriptor extends AsyncObject {
constructor (obj, prop) {
super(obj, prop)
}
syncCall () {
return (obj, prop) => {
return Object.getOwnPropertyDescriptor(obj, prop)
}
}
} |
JavaScript | class UpdatedBinary extends AsyncObject {
constructor(binary, byte_value) {
super(binary, byte_value);
}
definedSyncCall() {
return (binary, byte_value) => {
binary.put(byte_value);
return binary;
}
}
} |
JavaScript | class Welcome extends Component {
state = {
status: 'ingesting',
allTime: null,
};
// Only need this client-side
componentDidMount() {
// Set user value in local storage
if (typeof window !== 'undefined' && window.localStorage) {
localStorage.setItem('TMLAthleteId', this.props.id);
}
this.fetchAthlete();
}
fetchAthlete = async () => {
if (this.state.status !== 'ingesting') {
return;
}
APIRequest(`/athletes/${this.props.id}`, {}, {})
.then((apiResponse) => {
if (!apiResponse.length || apiResponse[0].status === 'error') {
this.setState({ status: 'error' });
return;
}
if (apiResponse[0].status === 'ready') {
window.location = `/rider/${this.props.id}`;
return;
}
setTimeout(this.fetchAthlete, 1000);
});
};
renderIngesting = (id) => (
<div style={{ textAlign: 'center' }}>
<h3>{"We're"} building your profile!</h3>
<p>
You’ll be redirected to{' '}
<a href={`/rider/${id}`}>your rider page</a>
after {"we've"} downloaded your laps history from Strava.
</p>
<p>
Or if you want to go ride some laps, you can come back later to <br />
<a href={`/rider/${id}`}>https://themostlaps.com/rider/{id}</a>
</p>
</div>
);
renderError = (id) => (
<div style={{ textAlign: 'center' }}>
<h3>Something went wrong.</h3>
<p>
An error occurred while we were building{' '}
<Link href={`/rider?athleteId=${id}`} as={`/rider/${id}`}>
<a>your rider page</a>
</Link>.
</p>
<p>
We’re looking into it;{' '}
please email <a href="mailto:[email protected]">[email protected]</a>{' '}
with any questions. Thanks!
</p>
</div>
);
renderReady = (id) => (
<div style={{ textAlign: 'center' }}>
<h3>Your profile is ready!</h3>
<p>
<Link href={`/rider?athleteId=${id}`} as={`/rider/${id}`}>
<a>Click here</a>
</Link>{' '}
if you are not automatically redirected to view your laps.
</p>
</div>
);
render() {
const renderContent = () => {
switch (this.state.status) {
case 'error':
return this.renderError(this.props.id);
case 'ready':
return this.renderReady(this.props.id);
case 'ingesting':
default:
return this.renderIngesting(this.props.id);
}
};
return (<Layout
pathname="/welcome"
query={{}}
>
<h1>
{this.state.status !== 'error'
? '🎉🚴 Welcome 🎉🚴'
: '😞🚴 Welcome 🚴😞'
}
</h1>
{renderContent()}
<div
style={{ textAlign: 'center' }}
dangerouslySetInnerHTML={{ __html: LapPath('', 80) }}
/>
</Layout>);
}
} |
JavaScript | class FacetList extends Component {
constructor(props) {
super(props);
this.state = {
collapsed: true // hide more than COLLAPSED_LENGTH?
}
}
render() {
if (this.props.facets == undefined ||
this.props.facets.length == 0) {
// no facets, so return an empty list
return <ul className="app_ul"></ul>;
}
const multiselect = this.props.multiselect;
const collapsible = this.props.facets.length > COLLAPSED_LENGTH;
let facitems = null;
// collapse long facet list by default
const facets = (collapsible && this.state.collapsed) ?
this.props.facets.slice(0, COLLAPSED_LENGTH) : this.props.facets;
/*
* the <li> elements are different depending on whether we have multiselect
* facets. If so, we use checkboxes to make this obvious. Otherwise, we
* use links.
*/
if (multiselect) {
facitems = facets.map((x) => {
const key = "facet_" + x.filter;
const handler = (event) => {
event.preventDefault();
this.setFilter(event.target.value, event.target.checked);
};
return <li key={key}>
<input id={key} type="checkbox" onChange={handler}
value={x.filter} checked={x.selected}/>{" "}
<label for={key}>{x.label} ({x.count})</label>
</li>;
});
} else {
facitems = facets.map((x) => {
const key = "facet_" + x.filter;
if (x.selected) {
return <li key={key}><label className="app_bold">
{x.label + " (" + x.count + ")"}</label>
</li>;
} else {
const handler = (event) => {
event.preventDefault();
this.setFilter(x.filter, true);
};
return <li key={key}>
<a href="#" onClick={handler}><label>{x.label}</label></a>
{ " (" + x.count + ")"}
</li>;
}
});
}
/*
* display a collapse toggle?
*/
const collapseLink = collapsible ?
<li><a href="#" onClick={this.toggleShowAll.bind(this)}>
<em>{this.state.collapsed ? "show more" : "show fewer"}</em>
</a></li> : "";
/*
* the "any" link should only be active when a facet is selected
*/
const any = facets.find(x => x.selected) === undefined ?
<em>any</em> :
<a href="#" onClick={this.unsetAll.bind(this)}><em>any</em></a>;
return <ul className="app_ul">
{facitems}
{collapseLink}
<li>{any}</li>
</ul>;
}
// set/unset a single filter
setFilter(filter, apply) {
if (apply && ! this.props.multiselect) {
this.props.handleActions([
makeClearFiltersAction(this.props.fieldname),
makeSetFilterAction(filter, apply)
]);
} else {
this.props.handleActions([
makeSetFilterAction(filter, apply)
]);
}
}
// unset all selected filters
unsetAll(event) {
event.preventDefault();
this.props.handleActions([makeClearFiltersAction(this.props.fieldname)]);
}
toggleShowAll(event) {
event.preventDefault();
this.setState({ collapsed: !this.state.collapsed });
}
} |
JavaScript | class RaycastAlgorithm extends ColorableAlgorithm {
/**
* Creates a new RaycastAlgorithm.
* @param {RaycastAlgorithmOptions} [options={}] Algorithm options.
*/
constructor(options = {}) {
super(options);
// Only supports either filling or coloring.
onlyOneTrue({
fill: this.options.fill,
color: this.options.color
});
this.seeker = new Vector3();
this.bbox = new Box3();
this.size = new Vector3();
this.center = new Vector3();
this.startRotation = new Euler();
this.startPosition = new Vector3();
}
/**
* The default options for this raycasting algorithm.
* @type {RaycastAlgorithmOptions}
*/
get defaults() {
return {
...super.defaults
};
}
/**
* Samples a mesh based 3D object into voxels.
* @param {Mesh|Object3D} model mesh based 3D object.
* @param {number} resolution resolution of voxelization.
* @returns {Volume} Volume data representation of the mesh.
*/
sample(model, resolution = 10) {
let object = new Object3D().add(model.clone());
this.resolution = resolution;
if (this.options.color) {
this.colorExtractor = new ColorExtractor(object);
}
object.traverse(function (child) {
if (child instanceof Mesh) {
child.material.side = DoubleSide;
child.geometry.computeBoundingSphere();
child.geometry.computeBoundingBox();
child.geometry.computeFaceNormals();
child.geometry.boundsTree = new MeshBVH(child.geometry);
}
});
// Store initial rotation of object
this.startRotation.copy(object.rotation);
this.startPosition.copy(object.position);
object.updateMatrixWorld();
object.updateMatrix();
this.updateBoundingBox(object);
this.step = Math.max(this.width, this.height, this.depth) / (resolution - 1);
this.raycaster = new Raycaster();
// Prepare object
object.rotateOnAxis(new Vector3(1, 1, 1), 0.00001); // Reduce error by minor rotation.
new Box3().setFromObject(object).getCenter(object.position).multiplyScalar(- 1);
object.updateMatrixWorld();
this.updateBoundingBox(object);
let frontSide = this.sampleSide(object);
object.rotateOnAxis(new Vector3(0, 1, 0), Math.PI / 2);
object.updateMatrixWorld();
this.updateBoundingBox(object);
let leftSide = this.sampleSide(object);
object.rotateOnAxis(new Vector3(0, 0, 1), Math.PI / 2);
object.updateMatrixWorld();
this.updateBoundingBox(object);
let topSide = this.sampleSide(object);
try {
this.mergeMatrixes(frontSide, leftSide, 'ZY@X')
this.mergeMatrixes(frontSide, topSide, 'ZXY');
} catch (error) {
throw error;
} finally {
// Reset polygon to initial values.
object.rotation.copy(this.startRotation);
object.position.copy(this.startPosition);
object.updateMatrixWorld()
}
return frontSide;
}
/**
* Merges two ndarrays, preserving '1' values.
* @param {ndarray} volume1 ndarray used as base for merging into.
* @param {ndarray} volume2 ndarray to merge into volume1.
*/
mergeMatrixes(volume1, volume2, order) {
let reverse = [];
let matrix1 = volume1.voxels;
let matrix2 = volume2.voxels;
if (this.options.color) {
var colors1 = volume1.colors;
var colors2 = volume2.colors;
}
for (let index = 0; index < order.length; index++) {
let char = order[index];
if (char === '@') {
reverse.push(true);
index++;
} else {
reverse.push(false)
}
}
// remove @'s
order = order.replace(/@/g, '');
let indexes = { X: 0, Y: 0, Z: 0 };
let maxIndexes = {
X: matrix1.shape[0] - 1,
Y: matrix1.shape[1] - 1,
Z: matrix1.shape[2] - 1
};
// Validate matrix dimentions
if (
maxIndexes[order[0]] + 1 !== matrix2.shape[0] ||
maxIndexes[order[1]] + 1 !== matrix2.shape[1] ||
maxIndexes[order[2]] + 1 !== matrix2.shape[2]
) {
throw new Error('Sampled matrix dimentions do not lign up.');
}
var i, j, k;
for (indexes.X = 0; indexes.X < matrix1.shape[0]; indexes.X++) {
for (indexes.Y = 0; indexes.Y < matrix1.shape[1]; indexes.Y++) {
for (indexes.Z = 0; indexes.Z < matrix1.shape[2]; indexes.Z++) {
if (matrix1.get(indexes.X, indexes.Y, indexes.Z) === 0) {
i = indexes[order[0]];
j = indexes[order[1]];
k = indexes[order[2]];
if (reverse[0]) {
i = maxIndexes[order[0]] - i;
}
if (reverse[1]) {
j = maxIndexes[order[1]] - j;
}
if (reverse[2]) {
k = maxIndexes[order[2]] - k;
}
// TODO replace object references with switch case front, right, top.
// TODO move if up over i, j, k, ...
//matrix1[indexes.X][indexes.Y][indexes.Z] = matrix2[i][j][k];
let value = matrix2.get(i, j, k);
matrix1.set(indexes.X, indexes.Y, indexes.Z, value);
if (this.options.color) {
let r = colors2.get(i, j, k, 0);
let g = colors2.get(i, j, k, 1);
let b = colors2.get(i, j, k, 2);
colors1.set(indexes.X, indexes.Y, indexes.Z, 0, r);
colors1.set(indexes.X, indexes.Y, indexes.Z, 1, g);
colors1.set(indexes.X, indexes.Y, indexes.Z, 2, b);
}
}
}
}
}
}
/**
* Update this class's bounding box object data based on the object passed as parameter.
* @param {Object3D} object The object to compute bounding box data from.
*/
updateBoundingBox(object) {
this.bbox.setFromObject(object);
this.bbox.getSize(this.size);
this.bbox.getCenter(this.center);
this.width = this.size.x
this.height = this.size.y
this.depth = this.size.z
}
/**
* Samples the side of the object passed as parameter.
* The sampling is done in the direction x, y, z,
* where z runs fastest, then y, then x.
* Sampling is based on raycasting.
* @param {Mesh|Object3D} object mesh based 3D object.
* @returns {Volume} the sampled volume data.
*/
sampleSide(object) {
let matrix = new ndarray(new Uint8Array(this.resolution ** 3),
[
(Math.floor(this.width / this.step) + 1),
(Math.floor(this.height / this.step) + 1),
(Math.floor(this.depth / this.step) + 1)
]);
// Handle coloring if option is set.
let colors = null;
if (this.options.color) {
colors = new ndarray(new Uint8ClampedArray((this.resolution ** 3) * 3),
[
(Math.floor(this.width / this.step) + 1),
(Math.floor(this.height / this.step) + 1),
(Math.floor(this.depth / this.step) + 1),
3
]);
// Fill colors array with white rgb(255, 255, 255) as the default value.
ndarrayFill(colors, () => {
return 255;
});
}
let direction = new Vector3(0, 0, -1);
let head_x = this.bbox.min.x;
this.direction = direction;
this.seeker.setZ(this.bbox.max.z);
let i = 0;
while (head_x <= this.bbox.max.x) {
this.seeker.setX(head_x);
let head_y = this.bbox.min.y;
let j = 0;
while (head_y <= this.bbox.max.y) {
this.seeker.setY(head_y);
this.raycaster.set(this.seeker, direction);
const intersects = this.raycaster.intersectObject(object, true);
let depthView = matrix.lo(i, j).hi(1, 1);
if (this.options.color) {
let colorView = colors.lo(i, j).hi(1, 1);
this._handleIntersects(intersects, depthView, colorView);
} else {
this._handleIntersects(intersects, depthView);
}
head_y += this.step;
j++;
}
head_x += this.step;
i++;
}
return new Volume(matrix, colors);
}
/**
* Handle the intersects, meaning results in z direction.
* @param {*} intersects The intersects to be handled.
* @param {*} voxels The array to store the voxel data into.
* @param {*} colors The array to store the voxel color data into.
* @private
*/
_handleIntersects(intersects, voxels, colors = null) {
let inside = 0;
let numSteps = Math.floor(this.depth / this.step);
let currentDist = this.bbox.min.z;
for (let i = 0; i <= numSteps; i++) {
//voxels[i] = inside;
voxels.set(0, 0, i, inside);
for (let j = 0; j < intersects.length; j++) {
let intersect = intersects[j];
let distance = this.seeker.z - intersect.distance;
if (distance <= currentDist + this.step
&& distance > currentDist) {
voxels.set(0, 0, i, 1);
// Handle filling/solid voxelisation.
if (this.options.fill) {
inside = !inside;
}
// Handle coloring of the voxels.
if (this.options.color) {
let color = this.colorExtractor.getColorAtIntersect(intersect);
colors.set(0, 0, i, 0, color.r * 255);
colors.set(0, 0, i, 1, color.g * 255);
colors.set(0, 0, i, 2, color.b * 255);
}
}
}
currentDist += this.step;
}
}
} |
JavaScript | class OhTutorialStarter extends HTMLElement {
constructor() {
super();
this.clickBound = () => this.clicked();
}
connectedCallback() {
this.style.display = "none";
const forid = this.getAttribute("for");
this.target = document.getElementById(forid);
if (!this.target) {
this.target = this.nextElementSibling;
}
if (!this.target) {
console.warn("Failed to find target", forid);
return;
}
this.target.addEventListener("click", this.clickBound, { passive: true });
}
disconnectedCallback() {
if (this.target) this.target.removeEventListener("click", this.clickBound, { passive: true });
}
async clicked() {
let m = await importModule('./js/tutorial.js');
m.startTutorial(this.getAttribute("subject"));
}
} |
JavaScript | class EditDistance {
constructor () {
this.baseChar1Costs = []
this.basePrevChar1Costs = []
}
compare (string1, string2, maxDistance) {
return this.distance(string1, string2, maxDistance)
}
/// <summary>Compute and return the Damerau-Levenshtein optimal string
/// alignment edit distance between two strings.</summary>
/// <remarks>https://github.com/softwx/SoftWx.Match
/// This method is not threadsafe.</remarks>
/// <param name="string1">One of the strings to compare.</param>
/// <param name="string2">The other string to compare.</param>
/// <param name="maxDistance">The maximum distance that is of interest.</param>
/// <returns>-1 if the distance is greater than the maxDistance, 0 if the strings
/// are equivalent, otherwise a positive number whose magnitude increases as
/// difference between the strings increases.</returns>
distance (string1 = null, string2 = null, maxDistance) {
if (string1 === null || string2 === null) {
return Helpers.nullDistanceResults(string1, string2, maxDistance)
}
if (maxDistance <= 0) {
return (string1 === string2) ? 0 : -1
}
maxDistance = Math.ceil(maxDistance)
const iMaxDistance = (maxDistance <= Number.MAX_SAFE_INTEGER) ? maxDistance : Number.MAX_SAFE_INTEGER
// if strings of different lengths, ensure shorter string is in string1. This can result in a little faster speed by spending more time spinning just the inner loop during the main processing.
if (string1.length > string2.length) {
const t = string1
string1 = string2
string2 = t
}
if (string2.length - string1.length > iMaxDistance) {
return -1
}
// identify common suffix and/or prefix that can be ignored
const { len1, len2, start } = Helpers.prefixSuffixPrep(string1, string2)
if (len1 === 0) {
return (len2 <= iMaxDistance) ? len2 : -1
}
if (len2 > this.baseChar1Costs.length) {
this.baseChar1Costs = new Array(len2)
this.basePrevChar1Costs = new Array(len2)
}
if (iMaxDistance < len2) {
return this._distanceMax(string1, string2, len1, len2, start, iMaxDistance, this.baseChar1Costs, this.basePrevChar1Costs)
}
return this._distance(string1, string2, len1, len2, start, this.baseChar1Costs, this.basePrevChar1Costs)
}
/// <summary>Internal implementation of the core Damerau-Levenshtein, optimal string alignment algorithm.</summary>
/// <remarks>https://github.com/softwx/SoftWx.Match</remarks>
_distance (string1, string2, len1, len2, start, char1Costs, prevChar1Costs) {
char1Costs = []
for (let j = 0; j < len2;) {
char1Costs[j] = ++j
}
let char1 = ' '
let currentCost = 0
for (let i = 0; i < len1; ++i) {
const prevChar1 = char1
char1 = string1[start + i]
let char2 = ' '
let aboveCharCost = i
let leftCharCost = i
let nextTransCost = 0
for (let j = 0; j < len2; ++j) {
const thisTransCost = nextTransCost
nextTransCost = prevChar1Costs[j]
currentCost = leftCharCost
prevChar1Costs[j] = leftCharCost // cost of diagonal (substitution)
leftCharCost = char1Costs[j] // left now equals current cost (which will be diagonal at next iteration)
const prevChar2 = char2
char2 = string2[start + j]
if (char1 !== char2) {
// substitution if neither of two conditions below
if (aboveCharCost < currentCost) {
currentCost = aboveCharCost // deletion
}
if (leftCharCost < currentCost) {
currentCost = leftCharCost // insertion
}
++currentCost
if ((i !== 0) && (j !== 0) &&
(char1 === prevChar2) &&
(prevChar1 === char2) &&
(thisTransCost + 1 < currentCost)) {
currentCost = thisTransCost + 1 // transposition
}
}
char1Costs[j] = aboveCharCost = currentCost
}
}
return currentCost
}
/// <summary>Internal implementation of the core Damerau-Levenshtein, optimal string alignment algorithm
/// that accepts a maxDistance.</summary>
/// <remarks>https://github.com/softwx/SoftWx.Match</remarks>
_distanceMax (string1, string2, len1, len2, start, maxDistance, char1Costs, prevChar1Costs) {
char1Costs = []
for (let j = 0; j < len2; j++) {
if (j < maxDistance) {
char1Costs[j] = j + 1
}
else {
char1Costs[j] = maxDistance + 1
}
}
const lenDiff = len2 - len1
const jStartOffset = maxDistance - lenDiff
let jStart = 0
let jEnd = maxDistance
let char1 = ' '
let currentCost = 0
for (let i = 0; i < len1; ++i) {
const prevChar1 = char1
char1 = string1[start + i]
let char2 = ' '
let leftCharCost = i
let aboveCharCost = i
let nextTransCost = 0
// no need to look beyond window of lower right diagonal - maxDistance cells (lower right diag is i - lenDiff)
// and the upper left diagonal + maxDistance cells (upper left is i)
jStart += (i > jStartOffset) ? 1 : 0
jEnd += (jEnd < len2) ? 1 : 0
for (let j = jStart; j < jEnd; ++j) {
const thisTransCost = nextTransCost
nextTransCost = prevChar1Costs[j]
currentCost = leftCharCost
prevChar1Costs[j] = leftCharCost // cost on diagonal (substitution)
leftCharCost = char1Costs[j] // left now equals current cost (which will be diagonal at next iteration)
const prevChar2 = char2
char2 = string2[start + j]
if (char1 !== char2) {
// substitution if neither of two conditions below
if (aboveCharCost < currentCost) {
currentCost = aboveCharCost // deletion
}
if (leftCharCost < currentCost) {
currentCost = leftCharCost // insertion
}
currentCost += 1
if (i !== 0 && j !== 0 &&
char1 === prevChar2 &&
prevChar1 === char2 &&
thisTransCost + 1 < currentCost) {
currentCost = thisTransCost + 1 // transposition
}
}
aboveCharCost = currentCost
char1Costs[j] = currentCost
}
if (char1Costs[i + lenDiff] > maxDistance) {
return -1
}
}
return (currentCost <= maxDistance) ? currentCost : -1
}
} |
JavaScript | class ApiCall extends Component {
constructor(props) {
super(props);
// Create DOM references to be able to call a function on it
this.apiCallSearchComponent = React.createRef();
this.apiCallResultComponent = React.createRef();
// Get config
this.host = document.getElementById('dashboard').dataset.host;
console.log(this.host);
}
/**
* Perform search by calling remote API, get result and change state on result component to trigger refresh
*/
performSearch(searchKeyword) {
if (searchKeyword == "") {
this.apiCallResultComponent.current.setResults([]);
return;
}
fetch(this.host + '/actuator/apicalls/find/' + encodeURI(searchKeyword))
.then(response => response.json())
.then(json => this.apiCallResultComponent.current.setResults(json));
}
/**
* Note that we set a property function reference to be able to call performSearch from child component
*/
render() {
return (
<div className="m-3">
<ApiCallSearch ref={this.apiCallSearchComponent} performSearch={(searchKeyword) => this.performSearch(searchKeyword)}/>
<ApiCallResult ref={this.apiCallResultComponent} />
</div>
);
}
} |
JavaScript | class StrategyBuilder {
withProvider(auth_provider) {
this.auth_provider = auth_provider;
return this;
}
withCredentials(client_id, client_secret) {
this.client_id = client_id;
this.client_secret = client_secret;
return this;
}
withCallbackURL(callback_url) {
this.callback_url = callback_url;
return this;
}
withVerifyer(fn) {
this.verifyer = fn;
return this;
}
getError() {
return this.error;
}
buildStrategy() {
let strategy_impl = StrategyFactory.getStrategy(this.auth_provider);
if (strategy_impl instanceof Error) {
this.error = strategy_impl;
return null;
}
let strategy = new strategy_impl({
clientID: this.client_id,
consumerKey: this.client_id,
clientSecret: this.client_secret,
consumerSecret: this.client_secret,
callbackURL: this.callback_url
}, this.verifyer);
if (strategy._requestTokenStore) { // OAuth 1 requires a session
strategy._requestTokenStore.get = function (req, token, cb) {
// NOTE: The oauth_verifier parameter will be supplied in the query portion
// of the redirect URL, if the server supports OAuth 1.0a.
let oauth_verifier = req.query.oauth_verifier || null;
return cb(null, oauth_verifier);
};
strategy._requestTokenStore.destroy = function (req, token, cb) {
// simply invoke the callback directly
cb();
}
}
return strategy;
}
} |
JavaScript | class ESDoc {
/**
* Generate documentation.
* @param {ESDocConfig} config - config for generation.
* @param {function(results: Object[], asts: Object[], config: ESDocConfig)} publisher - callback for output html.
*/
static generate(config, publisher) {
(0, _assert2.default)(typeof publisher === 'function');
(0, _assert2.default)(config.source);
(0, _assert2.default)(config.destination);
_Plugin2.default.init(config.plugins);
_Plugin2.default.onStart();
config = _Plugin2.default.onHandleConfig(config);
this._setDefaultConfig(config);
this._deprecatedConfig(config);
_colorLogger2.default.debug = !!config.debug;
const includes = config.includes.map(v => new RegExp(v));
const excludes = config.excludes.map(v => new RegExp(v));
let packageName = null;
let mainFilePath = null;
if (config.package) {
try {
const packageJSON = _fs2.default.readFileSync(config.package, { encode: 'utf8' });
const packageConfig = JSON.parse(packageJSON);
packageName = packageConfig.name;
mainFilePath = packageConfig.main;
} catch (e) {
// ignore
}
}
let results = [];
const asts = [];
const sourceDirPath = _path2.default.resolve(config.source);
this._walk(config.source, filePath => {
const relativeFilePath = _path2.default.relative(sourceDirPath, filePath);
let match = false;
for (const reg of includes) {
if (relativeFilePath.match(reg)) {
match = true;
break;
}
}
if (!match) return;
for (const reg of excludes) {
if (relativeFilePath.match(reg)) return;
}
console.log(`parse: ${ filePath }`);
const temp = this._traverse(config, config.source, filePath, packageName, mainFilePath);
if (!temp) return;
results.push(...temp.results);
asts.push({ filePath: `source${ _path2.default.sep }${ relativeFilePath }`, ast: temp.ast });
});
if (config.builtinExternal) {
this._useBuiltinExternal(config, results);
}
if (config.test) {
this._generateForTest(config, results, asts);
}
results = _Plugin2.default.onHandleTag(results);
try {
publisher(results, asts, config);
} catch (e) {
_InvalidCodeLogger2.default.showError(e);
process.exit(1);
}
_Plugin2.default.onComplete();
}
/**
* Generate document from test code.
* @param {ESDocConfig} config - config for generating.
* @param {DocObject[]} results - push DocObject to this.
* @param {AST[]} asts - push ast to this.
* @private
*/
static _generateForTest(config, results, asts) {
const includes = config.test.includes.map(v => new RegExp(v));
const excludes = config.test.excludes.map(v => new RegExp(v));
const sourceDirPath = _path2.default.resolve(config.test.source);
this._walk(config.test.source, filePath => {
const relativeFilePath = _path2.default.relative(sourceDirPath, filePath);
let match = false;
for (const reg of includes) {
if (relativeFilePath.match(reg)) {
match = true;
break;
}
}
if (!match) return;
for (const reg of excludes) {
if (relativeFilePath.match(reg)) return;
}
console.log(`parse: ${ filePath }`);
const temp = this._traverseForTest(config, config.test.type, config.test.source, filePath);
if (!temp) return;
results.push(...temp.results);
asts.push({ filePath: `test${ _path2.default.sep }${ relativeFilePath }`, ast: temp.ast });
});
}
/**
* set default config to specified config.
* @param {ESDocConfig} config - specified config.
* @private
*/
static _setDefaultConfig(config) {
if (!config.includes) config.includes = ['\\.(js|es6)$'];
if (!config.excludes) config.excludes = ['\\.config\\.(js|es6)$'];
if (!config.access) config.access = ['public', 'protected'];
if (!('autoPrivate' in config)) config.autoPrivate = true;
if (!('unexportIdentifier' in config)) config.unexportIdentifier = false;
if (!('builtinExternal' in config)) config.builtinExternal = true;
if (!('undocumentIdentifier' in config)) config.undocumentIdentifier = true;
if (!('coverage' in config)) config.coverage = true;
if (!('includeSource' in config)) config.includeSource = true;
if (!('lint' in config)) config.lint = true;
if (!config.index) config.index = './README.md';
if (!config.package) config.package = './package.json';
if (!config.styles) config.styles = [];
if (!config.scripts) config.scripts = [];
if (config.test) {
(0, _assert2.default)(config.test.type);
(0, _assert2.default)(config.test.source);
if (!config.test.includes) config.test.includes = ['(spec|Spec|test|Test)\\.(js|es6)$'];
if (!config.test.excludes) config.test.excludes = ['\\.config\\.(js|es6)$'];
}
if (config.manual) {
if (!('coverage' in config.manual)) config.manual.coverage = true;
}
}
/* eslint-disable no-unused-vars */
static _deprecatedConfig(config) {}
// do nothing
/**
* Use built-in external document.
* built-in external has number, string, boolean, etc...
* @param {ESDocConfig} config - config of esdoc.
* @param {DocObject[]} results - this method pushes DocObject to this param.
* @private
* @see {@link src/BuiltinExternal/ECMAScriptExternal.js}
*/
static _useBuiltinExternal(config, results) {
const dirPath = _path2.default.resolve(__dirname, './BuiltinExternal/');
this._walk(dirPath, filePath => {
const temp = this._traverse(config, dirPath, filePath);
/* eslint-disable no-return-assign */
temp.results.forEach(v => v.builtinExternal = true);
const res = temp.results.filter(v => v.kind === 'external');
results.push(...res);
});
}
/**
* walk recursive in directory.
* @param {string} dirPath - target directory path.
* @param {function(entryPath: string)} callback - callback for find file.
* @private
*/
static _walk(dirPath, callback) {
const entries = _fs2.default.readdirSync(dirPath);
for (const entry of entries) {
const entryPath = _path2.default.resolve(dirPath, entry);
const stat = _fs2.default.statSync(entryPath);
if (stat.isFile()) {
callback(entryPath);
} else if (stat.isDirectory()) {
this._walk(entryPath, callback);
}
}
}
/**
* traverse doc comment in JavaScript file.
* @param {ESDocConfig} config - config of esdoc.
* @param {string} inDirPath - root directory path.
* @param {string} filePath - target JavaScript file path.
* @param {string} [packageName] - npm package name of target.
* @param {string} [mainFilePath] - npm main file path of target.
* @returns {Object} - return document that is traversed.
* @property {DocObject[]} results - this is contained JavaScript file.
* @property {AST} ast - this is AST of JavaScript file.
* @private
*/
static _traverse(config, inDirPath, filePath, packageName, mainFilePath) {
logger.i(`parsing: ${ filePath }`);
let ast;
try {
ast = _ESParser2.default.parse(config, filePath);
} catch (e) {
_InvalidCodeLogger2.default.showFile(filePath, e);
return null;
}
const pathResolver = new _PathResolver2.default(inDirPath, filePath, packageName, mainFilePath);
const factory = new _DocFactory2.default(ast, pathResolver);
_ASTUtil2.default.traverse(ast, (node, parent) => {
try {
factory.push(node, parent);
} catch (e) {
_InvalidCodeLogger2.default.show(filePath, node);
throw e;
}
});
return { results: factory.results, ast: ast };
}
/**
* traverse doc comment in test code file.
* @param {ESDocConfig} config - config of esdoc.
* @param {string} type - test code type.
* @param {string} inDirPath - root directory path.
* @param {string} filePath - target test code file path.
* @returns {Object} return document info that is traversed.
* @property {DocObject[]} results - this is contained test code.
* @property {AST} ast - this is AST of test code.
* @private
*/
static _traverseForTest(config, type, inDirPath, filePath) {
let ast;
try {
ast = _ESParser2.default.parse(config, filePath);
} catch (e) {
_InvalidCodeLogger2.default.showFile(filePath, e);
return null;
}
const pathResolver = new _PathResolver2.default(inDirPath, filePath);
const factory = new _TestDocFactory2.default(type, ast, pathResolver);
_ASTUtil2.default.traverse(ast, (node, parent) => {
try {
factory.push(node, parent);
} catch (e) {
_InvalidCodeLogger2.default.show(filePath, node);
throw e;
}
});
return { results: factory.results, ast: ast };
}
} |
JavaScript | class Template {
/**
* Constructor
*/
constructor() {
}
/**
* Sets title of template
* @param {string} title
* @return {Template}
*/
setTitle(title) {
this.title = title;
return this;
}
/**
* Sets token of template
* @param {string} token
* @return {Template}
*/
setToken(token) {
this.token = token;
return this;
}
/**
* Sets back-button visibility
* @param {'HIDDEN'|'VISIBLE'} visibility
* @return {Template}
*/
setBackButton(visibility) {
let validTypes = ['VISIBLE', 'HIDDEN'];
if (validTypes.indexOf(visibility) === -1) {
throw new Error('Invalid visibility type');
}
this.backButton = visibility;
return this;
}
/**
* Sets background Image
* @param {*|string} backgroundImage
* @return {Template}
*/
setBackgroundImage(backgroundImage) {
this.backgroundImage = Template.makeImage(backgroundImage);
return this;
}
/**
* Creates textContent object
* @param {*} primaryText
* @param {*} secondaryText
* @param {*} tertiaryText
* @return {{}}
*/
static makeTextContent(primaryText, secondaryText, tertiaryText) {
let textContent = {};
textContent.primaryText = Template.makeRichText(primaryText);
if (secondaryText) {
textContent.secondaryText = Template.makeRichText(secondaryText);
}
if (tertiaryText) {
textContent.tertiaryText = Template.makeRichText(tertiaryText);
}
return textContent;
}
/**
* Creates rich text object
* @param {string} text
* @return {{text: *, type: string}}
*/
static makeRichText(text) {
if (typeof text === 'string') {
return {
text: text,
type: 'RichText',
};
} else if (text.text && text.type) {
return text;
}
}
/**
* Creates plain text object
* @param {string} text
* @return {*}
*/
static makePlainText(text) {
if (typeof text === 'string') {
return {
text: text,
type: 'PlainText',
};
} else if (text.text && text.type) {
return text;
}
}
/**
* Creates image object
* @param {*} image
* @param {string} description
* @return {*}
*/
static makeImage(image, description) {
if (typeof image === 'string') {
let img = {
sources: [
{
url: image,
},
],
};
if (description) {
img.contentDescription = description;
}
return img;
} else if (image && image.url) {
if (image.description) {
return Template.makeImage(image.url, image.description);
} else {
return Template.makeImage(image.url);
}
} else {
return image;
}
}
/**
* Builds template object
* @deprecated
* @return {{}|*}
*/
build() {
return this;
}
} |
JavaScript | class UpdateApplicationResponse {
constructor(params) {
params = params || {};
this.apiId = params.apiId;
this.message = params.message;
}
} |
JavaScript | class ApplicationInterface extends PlivoResourceInterface {
constructor(client, data = {}) {
super(action, Application, idField, client);
extend(this, data);
this[clientKey] = client;
}
/**
* get application by given id
* @method
* @param {string} id - id of application
* @promise {object} return {@link Application} object
* @fail {Error} return Error
*/
get(id) {
let params = {}
params.isVoiceRequest = 'true'
let client = this[clientKey];
return new Promise((resolve, reject) => {
if (action !== '' && !id) {
reject(new Error(this[idKey] + ' must be set'));
}
client('GET', action + (id ? id + '/' : ''), params)
.then(response => {
resolve(new RetrieveApplicationResponse(response.body, client));
})
.catch(error => {
reject(error);
});
});
}
/**
* list applications
* @method
* @param {object} params - params to list applications
* @param {string} [params.subaccount] - ID of the subaccount if present
* @param {integer} [params.limit] - To display no of results per page
* @param {integer} [params.offset] - No of value items by which results should be offset
*/
list(params = {}) {
let client = this[clientKey];
params.isVoiceRequest = true;
return new Promise((resolve, reject) => {
client('GET', action, params)
.then(response => {
let objects = [];
Object.defineProperty(objects, 'meta', {
value: response.body.meta,
enumerable: true
});
response.body.objects.forEach(item => {
objects.push(new ListAllApplicationResponse(item, client));
});
resolve(objects);
})
.catch(error => {
reject(error);
});
});
}
/**
* create Application
* @method
* @param {string} appName - name of application
* @param {object} params - params to create application
* @param {string} [params.answerUrl] - answer url
* @param {string} [params.appName] The name of your application
* @param {string} [params.answerUrl] The URL invoked by Plivo when a call executes this application.
* @param {string} [params.answerMethod] The method used to call the answer_url. Defaults to POST.
* @param {string} [params.hangupUrl] The URL that is notified by Plivo when the call hangs up.
* @param {string} [params.hangupMethod] The method used to call the hangup_url. Defaults to POST
* @param {string} [params.fallbackAnswerUrl] Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response.
* @param {string} [params.fallbackMethod] The method used to call the fallback_answer_url. Defaults to POST.
* @param {string} [params.messageUrl] The URL that is notified by Plivo when an inbound message is received. Defaults not set.
* @param {string} [params.messageMethod] The method used to call the message_url. Defaults to POST.
* @param {boolean} [params.defaultNumberApp] If set to true, associates all newly created Plivo numbers that have not specified an app_id, to this application.
* @param {boolean} [params.defaultEndpointApp] If set to true, associates all newly created Plivo endpoints that have not specified an app_id, to this application.
* @param {string} [params.subaccount] Id of the subaccount, in case only subaccount applications are needed.
* @param {boolean} [params.logIncomingMessages] flag to control incoming message logs.
* @promise {object} return {@link PlivoGenericResponse} object
* @fail {Error} return Error
*/
create(appName, params = {}) {
let errors = validate([{
field: 'app_name',
value: appName,
validators: ['isRequired', 'isString']
}]);
if (errors) {
return errors;
}
params.app_name = appName;
params.isVoiceRequest = 'true';
let client = this[clientKey];
return new Promise((resolve, reject) => {
console.log(action, params)
client('POST', action, params)
.then(response => {
resolve(new CreateApplicationResponse(response.body, idField));
})
.catch(error => {
reject(error);
});
})
}
/**
* update Application
* @method
* @param {string} id - id of application
* @param {object} params - to update application
* @param {string} [params.answerUrl] The URL invoked by Plivo when a call executes this application.
* @param {string} [params.answerMethod] The method used to call the answer_url. Defaults to POST.
* @param {string} [params.hangupUrl] The URL that is notified by Plivo when the call hangs up.
* @param {string} [params.hangupMethod] The method used to call the hangup_url. Defaults to POST
* @param {string} [params.fallbackAnswerUrl] Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response.
* @param {string} [params.fallbackMethod] The method used to call the fallback_answer_url. Defaults to POST.
* @param {string} [params.messageUrl] The URL that is notified by Plivo when an inbound message is received. Defaults not set.
* @param {string} [params.messageMethod] The method used to call the message_url. Defaults to POST.
* @param {boolean} [params.defaultNumberApp] If set to true, associates all newly created Plivo numbers that have not specified an app_id, to this application.
* @param {boolean} [params.defaultEndpointApp] If set to true, associates all newly created Plivo endpoints that have not specified an app_id, to this application.
* @param {string} [params.subaccount] Id of the subaccount, in case only subaccount applications are needed.
* @param {boolean} [params.logIncomingMessages] flag to control incoming message logs.
* @promise {object} return {@link Application} object
* @fail {Error} return Error
*/
update(id, params) {
let errors = validate([{
field: 'id',
value: id,
validators: ['isRequired']
}]);
if (errors) {
return errors;
}
return new Application(this[clientKey], {
id: id
}).update(params);
}
/**
* delete Application
* @method
* @param {string} id - id of application
* @param {object} params - params to delete application
* @param {boolean} [params.cascade] - delete associated endpoints
* @param {string} [params.newEndpointApplication] - link associated endpoints with app
* @promise {object} return true on success
* @fail {Error} return Error
*/
delete(id, params = {}) {
if (typeof params.cascade === 'boolean') {
params.cascade = params.cascade.toString();
}
return new Application(this[clientKey], {
id: id
}).delete(params, id);
}
} |
JavaScript | class MapService {
/**
*
* @param {mapDefinitionProvider} [provider=getBvvMapDefinitions]
*/
constructor(mapDefinitionProvider = getBvvMapDefinitions) {
const { CoordinateService } = $injector.inject('CoordinateService');
this._coordinateService = CoordinateService;
this._definitions = mapDefinitionProvider();
}
/**
* Internal srid of the map
* @returns {number} srid
*/
getSrid() {
return this._definitions.srid;
}
/**
* Default SRID suitable for the UI.
* @returns {number} srid
*/
getDefaultSridForView() {
return this._definitions.defaultSridForView;
}
/**
* Returns a list with all SridDefinition suitable for the UI. When a coordinate is provided, the list contains
* suitable SridDefinition regarding this coordinate.
* @param {Coordinate} [coordinateInMapProjection] - coordinate in map projection
* @returns {Array<SridDefinition>} srids
*/
getSridDefinitionsForView(coordinateInMapProjection) {
return this._definitions.sridDefinitionsForView(coordinateInMapProjection);
}
/**
* Default SRID for geodatic tasks.
* @returns {number} srid
*/
getDefaultGeodeticSrid() {
return this._definitions.defaultGeodeticSrid;
}
/**
* Return the default extent of the map.
* @param {number} srid
* @returns {Extent} extent
*/
getDefaultMapExtent(srid = this.getSrid()) {
switch (srid) {
case 3857:
return this._definitions.defaultExtent;
case 4326:
return this._coordinateService.toLonLatExtent(this._definitions.defaultExtent);
}
throw new Error('Unsupported SRID ' + srid);
}
/**
* Return the minimal zoom level the map supports
* @returns {Number} zoom level
*/
getMinZoomLevel() {
return this._definitions.minZoomLevel;
}
/**
* Return the maximal zoom level the map supports
* @returns {Number} zoom level
*/
getMaxZoomLevel() {
return this._definitions.maxZoomLevel;
}
/**
* Returns the minimal angle in radians when rotation of the map should be accepted and applied.
* @returns threshold value for rotating the map in radians.
*/
getMinimalRotation() {
return .3;
}
/**
* Calculates the resolution at a specific degree of latitude in meters per pixel.
* @param {number} zoom Zoom level to calculate resolution at
* @param {Coordinate} [coordinate] Coordinate to calculate resolution at (required for non-geodetic map projections like `3857`)
* @param {number} [srid] Spatial Reference Id. Default is `3857`
* @param {number} [tileSize] tileSize The size of the tiles in the tile pyramid. Default is `256`
*/
calcResolution(zoom, coordinateInMapProjection = null, srid = this.getSrid(), tileSize = 256) {
switch (srid) {
case 3857:
if (!coordinateInMapProjection) {
throw new Error(`Parameter 'coordinateInMapProjection' must not be Null when using SRID ${srid}`);
}
return calc3857MapResolution(this._coordinateService.toLonLat(coordinateInMapProjection)[1], zoom, tileSize);
}
throw new Error(`Unsupported SRID ${srid}`);
}
/**
* Returns an HTMLElement acting as a container for a scale line component.
* @returns {HTMLElement|null} element or `null`;
*/
getScaleLineContainer() {
const element = document.querySelector('ba-footer')?.shadowRoot.querySelector('.scale');
return element ?? null;
}
} |
JavaScript | class Bookings{
/**
* @description create booking for user
* @param { Object } request
* @param { Object } response
* @return { JSON } return
*/
static async book (request, response){
try {
//check if trip is available
const checkTripID = await trip.select(['buses.capacity, *'],[`trips.id='${request.body.trip_id}'`]);
if(!checkTripID[0]){
return response.status(404).json({
status: 404,
error: 'Trip ID does not match any of the available trip'
})
}
let seat_number;
const { bus_id, trip_date} = checkTripID[0];
const { id, first_name, last_name, email } = request.userData;
if(!request.body.seat_number){
seat_number = Math.floor(Math.random() * checkTripID[0].capacity) + 1;
}
const data = await bookings.insert(['user_id', 'trip_id', 'bus_id', 'trip_date', 'seat_number', 'first_name', 'last_name', 'email'],
[`'${id}','${request.body.trip_id}', '${bus_id}','${trip_date}','${seat_number}','${first_name}','${last_name}','${email}'`]);
return response.status(201).json({
status: 201,
data,
message: 'Your booking was successful'
})
} catch (error) {
return response.status(503).json({
status: 503,
error: 'Something went wrong, service not available'
});
}
}
/**
* @description view user booking, while is_admin true views all bookings
* @param { Object } request
* @param { Object } response
* @return { JSON } return
*/
static async bookings(request, response){
try {
if(request.userData.is_admin === false){
const user_id = request.userData.id;
const userBookings = await bookings.select(['*'], [`user_id=${user_id}`]);
if(!userBookings[0]){
return response.status(404).json({
status: 404,
error: 'No booking record found'
})
}
return response.status(200).json({
status: 200,
data: userBookings,
message: 'Your bookings'
})
}
const booking = await bookings.selectAll();
return response.status(200).json({
status: 200,
data: booking
})
} catch (error) {
return response.status(503).json({
status: 503,
error: 'Something went wrong, service not available'
});
}
}
/**
* @description delete booking
* @param { Object } request
* @param { Object } response
* @return { JSON } return
*/
static async deleteBookings(request, response){
try {
const booking = await bookings.delete([`id='${request.params.bookingId}'`]);
if(!booking.rowCount>0){
return response.status(404).json({
status: 404,
error: 'Booking ID does not exist'
})
}
const data = { message: 'Booking was successfully deleted' }
return response.status(200).json({
status: 204,
data
})
} catch (error) {
return response.status(503).json({
status: 503,
error: 'Something went wrong, service not available'
});
}
}
static async changeSeat(request, response){
try {
const checkTrip = await trips.select(['*'],[`id=${request.params.tripId} AND status='active'`]);
if(!checkTrip[0]){
return response.status(404).json({
status: 404,
error: 'Trip ID does not match any of the available trip'
})
}
const data = await bookings.update([`seat_number='${request.body.seat_number}'`], [`trip_id='${request.params.tripId}' AND user_id='${request.userData.id}'`]);
if(!data[0]){
return response.status(404).json({
status: 404,
error: `You didn't book for this trip. Hence, you can't change seat`
})
}
return response.status(200).json({
status: 200,
data,
message: 'Your seat has been successfully changed'
})
} catch (error) {
return response.status(503).json({
status: 503,
error: 'Something went wrong, service not available'
})
}
}
} |
JavaScript | class PageC extends Component {
/**
* @param {object} props - The props used to construct. */
constructor(props) {
super(props);
this.state = {
/**
* Used to decide which subpage to show
* 0: Checking page (initial status)
* 1: Checking succeed page */
status: false,
};
this.checking = this.checking.bind(this);
this.reset = this.reset.bind(this);
}
/**
* Post the current checking data into backend, and switch into
* succeed page if the post request succeed. */
checking() {
axios.post(apiConfig.sqlCheck, {
username: this.username.value,
})
.then((res) => {
console.log(res.data);
this.setState({ status: true });
})
.catch((err) => {
console.log(err);
});
}
/**
* switch subpage back to initial status */
reset() {
this.setState({ status: false });
}
/**
* @return {JSX} - A syntax extension to JavaScript, which will be
* eventually compiled into html code. */
render() {
return (
<div className="center">
{this.state.status === false
?
<div>
PageC - CheckUserExist
<input type="text" placeholder="帳號" ref={(input) => { this.username = input; }} />
<button onClick={this.checkIn}>Find User</button>
</div>
:
<div>
<button onClick={this.reset}>Go Back</button>
</div>
}
</div>
);
}
} |
JavaScript | class ParameterTable extends React.Component {
COLUMNS = [
{ Header: 'Name', accessor: 'name' },
{ Header: 'Value', accessor: 'value', Cell: this.renderEditable.bind(this) },
{ Header: 'Units', accessor: 'units' },
{ Header: 'Comment', accessor: 'comments', Cell: this.renderEditable.bind(this) },
];
constructor(props) {
super(props);
this.state = { data: this.props.parameters };
}
renderEditable(cellInfo) {
return (
<div
style={{ backgroundColor: "#fafafa" }}
contentEditable
suppressContentEditableWarning
onBlur={e => {
const data = [...this.state.data];
let leafNode = e.target;
while (leafNode.children.length > 0) {
leafNode = leafNode.childNodes[0];
}
data[cellInfo.index][cellInfo.column.id] = leafNode.innerHTML;
this.setState({ data });
}}
dangerouslySetInnerHTML={{
__html: this.state.data[cellInfo.index][cellInfo.column.id]
}}
/>
);
}
componentDidMount() {
}
/** @override */
render() {
return (
<ReactTable
data={this.props.parameters}
columns={this.COLUMNS}
defaultPageSize={10}
/>
);
}
} |
JavaScript | class RepoInfo {
/**
* Creates a RepoInfo
*
* @param {string} nameWithOwner - name and author of repository
* @param {string} url - url of the repository
* @param {string} description - description
* @param {number} stargazersCount - amount of stars
* @param {string} language - programming language
* @param {number} forks - amount of forks
* @param {string} license - repository license
*/
constructor(nameWithOwner, url, description, stargazersCount, language, forks, license) {
this.nameWithOwner = nameWithOwner;
this.url = url;
this.description = description;
this.stargazersCount = stargazersCount;
this.language = language;
this.forks = forks;
this.license = license;
}
/**
* Creates RepoInfo from Github API data
*
* @param {object} item - repository data from Github API
* @returns {RepoInfo}
*/
static fromGithubRes(item) {
const { description, language, forks } = item;
const license = item.license ? item.license.spdx_id : null;
return new RepoInfo(
item.full_name,
item.html_url,
description,
item.stargazers_count,
language,
forks,
license
);
}
} |
JavaScript | class Context {
/**
* Active state of the context.
*/
get active() {
return this._active;
}
/**
* Disabled state of the context.
*/
get disabled() {
return this._disabled || !this.element.isConnected;
}
/**
* Create a new context.
* @param {HTMLElement} element The root element of the context.
* @param {ContextOptions} options A set of options for the context.
* @param {import('./Manager.js').Manager} [parent] A set of options for the context.
*/
constructor(element, options = {}, parent) {
this.element = element;
setContext(element, this);
/**
* @protected
*/
this.focusableSelectors = DEFAULT_SELECTORS;
/**
* @protected
*/
this.ignoredSelectors = [];
/**
* @protected
* @type {boolean|DismissFunction}
*/
this.dismiss = true;
/**
* @protected
*/
this.parent = parent;
/**
* @private
*/
this._active = false;
/**
* @private
*/
this._currentElement = null;
/**
* @private
*/
this._lastKeydownTime = Date.now();
/**
* @private
*/
this._tabIndex = element.getAttribute('tabindex') || '0';
if (options.selectors) {
this.setFocusableSelectors(options.selectors);
}
if (options.ignore) {
this.setIgnoredSelectors(options.ignore);
}
if (options.dismiss != null) {
this.setDismiss(options.dismiss);
}
/**
* @private
*/
this.onClick = (event) => {
if (this.disabled) {
return;
}
const elements = this.findFocusableChildren();
let target = event.target;
while (element.contains(target) || target === element) {
if (elements.indexOf(target) !== -1) {
target.focus();
break;
}
if (target === element) {
element.focus();
break;
}
target = target.parentNode;
}
};
if (options.disabled) {
this.disable();
} else {
this.enable();
}
}
/**
* Set focusable selectors.
* @param {string|string[]} selectors The selectors to set.
*/
setFocusableSelectors(selectors) {
if (Array.isArray(selectors)) {
this.focusableSelectors = selectors;
} else if (typeof selectors === 'string' && selectors) {
this.focusableSelectors = selectors.split(',');
} else {
throw new Error('invalid selectors list');
}
}
/**
* Set selectors for elements to ignore.
* @param {string|string[]} selectors The selectors to ignore,
*/
setIgnoredSelectors(selectors) {
if (Array.isArray(selectors)) {
this.ignoredSelectors = selectors;
} else if (typeof selectors === 'string' && selectors) {
this.ignoredSelectors = selectors.split(',');
} else {
throw new Error('invalid selectors list');
}
}
/**
* Returns focusable children elements.
*
* @return {Array<HTMLElement>} focusable children of root element.
*/
findFocusableChildren() {
const focusable = this.element.querySelectorAll(
this.focusableSelectors.map((selector) => `${selector}:not([type=hidden]):not([tabindex="-1"]):not([disabled]):not([aria-hidden]):not([display=none])`).join(', ')
);
const elements = [].slice.call(focusable);
const ignore = this.ignoredSelectors.length ? [].slice.call(this.element.querySelectorAll(this.ignoredSelectors.join(','))) : [];
return elements
.filter((elem) => !ignore.some((area) => elem === area || area.contains(elem)))
.filter((elem) => {
const { width, height } = elem.getBoundingClientRect();
return !!height && !!width;
});
}
/**
*
* @param {boolean|DismissFunction} dismiss
*/
setDismiss(dismiss) {
this.dismiss = dismiss;
}
/**
* Active previous focusable element.
*
* @return {void}
*/
prev() {
if (this.disabled) {
return;
}
const children = this.findFocusableChildren();
if (!children.length) {
this.restore();
return;
}
let io = children.indexOf(this._currentElement);
if (io === 0) {
io = children.length - 1;
} else if (io !== -1) {
io = io - 1;
} else {
io = children.length - 1;
}
this.setCurrentElement(children[io]);
}
/**
* Active next focusable element.
*
* @return {void}
*/
next() {
if (this.disabled) {
return;
}
const children = this.findFocusableChildren();
if (!children.length) {
this.restore();
return;
}
let io = children.indexOf(this._currentElement);
if (io === children.length - 1) {
io = 0;
} else if (io !== -1) {
io = io + 1;
} else {
io = 0;
}
this.setCurrentElement(children[io]);
}
/**
* Entering the context.
*
* @return {Promise<void>}
*/
async enter() {
if (this.disabled) {
return;
}
if (this.active) {
return;
}
const element = this.element;
this._active = true;
if (!element.hasAttribute('aria-label') &&
!element.hasAttribute('aria-labelledby') &&
!element.hasAttribute('aria-describedby')) {
// eslint-disable-next-line
console.warn('created a Context without aria-label', this);
}
await dispatchAsyncEvent(element, 'focusenter', this);
this.restore();
}
/**
* Restore the focus on the last element.
* @return {void}
*/
restore() {
if (this.disabled) {
return;
}
if (this._currentElement) {
this._currentElement.focus();
} else {
this.element.focus();
}
}
/**
* Exit from the context.
*
* @return {Promise<boolean>}
*/
async exit() {
if (this.disabled) {
return false;
}
if (!this.active) {
return false;
}
if (this.dismiss === false) {
return false;
}
if (typeof this.dismiss === 'function') {
const result = await this.dismiss(this);
if (result === false) {
return false;
}
}
await this.forceExit();
return true;
}
/**
* Force exit from the context.
*
* @return {Promise<void>}
*/
async forceExit() {
if (this.disabled) {
return;
}
this._active = false;
this.unsetCurrentElement();
await dispatchAsyncEvent(this.element, 'focusexit', this);
}
/**
* Set the current element of the context.
* @param {HTMLElement} element
*/
setCurrentElement(element) {
this._currentElement = element;
element.focus();
}
/**
* Unset the current element of the context.
*/
unsetCurrentElement() {
this._currentElement = null;
}
/**
* Attach the context to a Loock instance.
* @param {import('./Manager.js').Manager} parent The parent loock instance.
*/
attach(parent) {
if (this.parent && this.parent !== parent) {
this.detach();
}
this.parent = parent;
}
/**
* Detach the context from the current Loock instance.
*/
detach() {
this.forceExit();
this.parent.removeContext(this);
this.parent = null;
}
/**
* Enable the context that has been disabled.
*/
enable() {
if (this._disabled === false) {
return;
}
this._disabled = false;
this.element.setAttribute('tabindex', this._tabIndex);
this.element.addEventListener('click', this.onClick);
}
/**
* Disable the context.
*/
disable() {
if (this._disabled) {
return;
}
this.forceExit();
this._disabled = true;
this.element.setAttribute('tabindex', '-1');
this.element.removeEventListener('click', this.onClick);
}
} |
JavaScript | class HumanLabels extends React.Component {
state = { activeGroups: [] }
componentWillMount() {
if (this.props.activeGroups) {
this.setState({ activeGroups: this.props.activeGroups })
}
}
onToggleGroup = (group) => {
const { activeGroups } = this.state
if (activeGroups.length > 0 && activeGroups[0] === group) {
this.setState({ activeGroups: [] })
} else {
this.setState({ activeGroups: [group] })
}
}
render() {
let {
bins = [],
heights = [],
interpolation = 'catmullRom',
title = '',
labelCounts,
labelNames = [],
stackProps = {},
children,
colors,
yAxisProps = {
label: '',
},
probChart = false,
} = data
if (typeof window === 'undefined') {
return null
}
const stdDev = 1.477
const width = 1300
const { activeGroups } = this.state
const isGroupActive = (group) => includes(activeGroups, group)
const hasActiveGroup = activeGroups.length > 0
if (probChart) {
yAxisProps.tickFormat = (t) => `${t.toExponential()}`
yAxisProps.dy = -30
stackProps.domain = { y: [0, 0.0000022] }
}
const iconSize = 62.3
const Label = ({ index, dse, children, count }) => (
<Surface
cursor="pointer"
marginRight={5}
opacity={0.8}
width={iconSize * 2}
onClick={() => {
this.onToggleGroup(index)
}}
>
{(hovering) => {
const showActive = hovering || isGroupActive(index)
return (
<Surface padding={6} background={showActive && 'rgba(0,0,0,0.06)'}>
<Surface
flexFlow="row"
alignItems="center"
transition="100ms ease-out all"
paddingBottom={2}
borderBottom={`6px solid ${colors[index]}`}
>
<Surface>
<Text
fontFamily="Arial"
fontWeight={600}
fontSize={12}
lineHeight={1.2}
>
{children}
</Text>
<Text
fontFamily="Arial"
fontSize={12}
fontWeight={400}
lineHeight={1.2}
>
{labelCounts[index]} images
</Text>
</Surface>
</Surface>
{dse && (
<Surface flexFlow="row">
{dse.slice(0, 2).map((img) => (
<div
style={{
border: '1px solid ' + colors[index],
width: iconSize,
height: iconSize,
}}
>
<img src={img} height={iconSize} width={iconSize} />
</div>
))}
</Surface>
)}
</Surface>
)
}}
</Surface>
)
const Valence = ({ name, children }) => {
return (
<Surface marginRight={20}>
<Text
fontSize={12}
opacity={0.8}
fontWeight={500}
textDecoration="uppercase"
>
{name} Valence
</Text>
<Surface flexFlow="row" transform="translateX(-6px)">
{children}
</Surface>
</Surface>
)
}
return (
<figure className="fullscreen-diagram" id="figure-5">
<Surface width={width} margin="auto">
<Surface flexFlow="row" marginLeft={60}>
<Valence name="High">
<Label index={8} dse={gamesDse}>
Music & Sports
</Label>
<Label index={7} dse={petsDse}>
Travel, Food, Pet
</Label>
</Valence>
<Valence name="Neutral">
<Label index={6} dse={unrelatedDse}>
Unrelated
</Label>
<Label index={4} dse={drugsDse}>
Drugs & Medicine
</Label>
<Label index={5} dse={wordsDse}>
Like "psychology"
</Label>
</Valence>
<Valence name="Low">
<Label index={3} dse={sadJokeDse}>
Depressing Joke
</Label>
<Label index={2} dse={badEmotionDse}>
Bad Feeling
</Label>
<Label index={1} dse={anxietyDse}>
Anxiety
</Label>
<Label index={0} dse={depressionDse}>
Depression / Sad
</Label>
</Valence>
</Surface>
<Surface
width={width}
alignSelf="center"
transform="translateY(-20px)"
>
<VictoryChart width={width} height={400} {...stackProps}>
<VictoryStack
colorScale={colors}
// interpolation={interpolation}
// interpolation="none"
animate={{
duration: 800,
}}
>
{heights.map((height, index) => {
const isZero = hasActiveGroup && !isGroupActive(index)
const victoryData = bins
.map((binValue, bin) => {
if (isZero) return { y: 0, x: binValue / stdDev }
return { x: binValue / stdDev, y: height[bin] }
})
.filter((i) => i !== null)
const addInterpolation = interpolation
? { interpolation }
: {}
return (
<VictoryGroup data={victoryData} key={index}>
<VictoryArea
// {...addInterpolation}
events={[
{
target: 'data',
eventHandlers: {
onClick: () => {
this.onToggleGroup(index)
},
},
},
]}
/>
</VictoryGroup>
)
})}
</VictoryStack>
<VictoryAxis
crossAxis={false}
tickCount={17}
label="Standard Deviations from Zero Activation"
axisLabelComponent={<VictoryLabel dy={7} />}
/>
<VictoryAxis
axisLabelComponent={<VictoryLabel dy={-13} />}
tickCount={5}
offsetX={50}
dependentAxis
{...yAxisProps}
/>
<VictoryLine
style={{
data: { strokeWidth: 1, stroke: 'rgba(0, 0, 0, 0.6)' },
}}
data={[
{ x: 0, y: 1 },
{ x: 0, y: 0 },
]}
/>
</VictoryChart>
</Surface>
<figcaption
style={{
width: 703,
marginTop: -20,
alignSelf: 'center',
}}
>
<a href='#figure-5' class='figure-anchor' style={{fontWeight: 'bold'}}>Figure 5:</a> To understand the "mental illness neuron" in more depth, we
collected images that cause it to fire different amounts and labeled
them by hand into categories we created. This lets us estimate the
conditional probability of a label at a given activation level. See{' '}
<a href="#conditional-probability">the appendix</a> for details.
During the labeling process we couldn't see how much it made the
neuron fire. We see that the strongest activations all belong to
labels corresponding to low-valence mental states. On the other
hand, many images with a negative pre-ReLU activation are of scenes
we may typically consider high-valence, like photos with pets,
travel photos, and or pictures of sporting events.
</figcaption>
</Surface>
</figure>
)
}
} |
JavaScript | class Base {
constructor() {
this.result = new Result();
this.data = null;
}
} |
JavaScript | class Node {
constructor(data, next = null) {
this.data = data;
this.next = next
}
} |
JavaScript | class LinkedList {
constructor() {
this.head = null
this.length = 0
}
// create methods to use the linkedlist
//1. Insert data at the head of the linked list
//--------> think of it this way ; we have a current node before we start in this linked list; now we want to add a new node at the begining so-------->
//1. create a new node instance and set the data to the value and teh next attribute to this.head so that your new node's next method reference the previous one
//2. define the head of your new linked list to be this newly created node
insertAtHead(data) {
const newNode = new Node(data, this.head);
this.head = newNode;
this.length++;
}
// 1. define a new node
//2. define current
// if statement -- if the list is empty (how do we check for that ? !this.head or this.head === null) then define the head as the new node ---
// else ===> where the list is not empty 1. define the current to be this.head to use as pointer
// 2. run a loop where the condition is (current.next) which means as long as the attribute next exists do the following.
//3. set the current = current.next to loop through the nodes.
//4. after the while and inside the else we define the next attribute of the current to equal this new node.
//5. outside the if-else statement increase the length.
insertLast(data) {
let newNode = new Node(data);
let current;
if (!this.head) {
this.head = newNode;
}
else {
current = this.head;
while (current.next) {
current = current.next
}
current.next = newNode;
}
this.length++;
}
// insert data at a certain index
insertAtIndex(data, index) {
// edge case if index is more than zero but out of the length - out of range
if (index > 0 && index > this.length) {
return;
}
// if index is zero
if (index === 0) {
this.head = new Node(data, this.head);
return;
}
let node = new Node(data);
let current, previous;
current = this.head;
let count = 0;
// ex: linked list of four nodes >> insert 300 at index 2 >>
//1. define current to be this.head and start a count from zero
// 2. start a while loop while the countis less than index do the following
// 3. set the previous to current (which is a pointer at this.head)
// 4. increase the count to step forward
// 5.define the new current to be current.next
while (count < index) {
previous = current;
count++;
current = current.next;
}
node.next = current;
previous.next = node;
this.length++;
}
getAt(index) {
let current = this.head;
let count = 0;
while (current) {
if (count === index) {
console.log(current.data);
}
count++;
current = current.next;
}
return null;
}
removeAt(index) {
if (index > 0 && index > this.length) {
return;
}
let current = this.head;
let previous;
let count = 0;
// remove first
if (index === 0) {
this.head = current.next;
}
else {
while (count < index) {
count++;
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.length--;
}
clearAll() {
this.head = null;
this.length = 0;
}
// add before
addbefore(value, valueToAddBefore) {
let current = this.head;
if (!current.next) {
return false
}
while (current.next) {
if (current.next.data === valueToAddBefore) {
const newNode = new Node(value);
newNode.next = current.next;
current.next = newNode;
this.length++;
return true;
}
current = current.next;
}
return false;
}
//add after
addAfter(value, value2A) {
let current = this.head;
if (!current) {
return false;
}
while (current) {
if (current.data === value2A) {
const newNode = new Node(value);
newNode.next = current.next;
current.next = newNode;
this.length++;
return true;
}
current = current.next;
}
return false;
}
// includes a value
includesVal(value) {
let current = this.head;
while (current) {
if (current.data === value)
return true;
current = current.next;
}
return false;
}
toString() {
let current = this.head;
if (!current) throw new Error('Can not turn a null linked list into strings, add head.');
let finalString = '';
while (current) {
finalString = finalString + `{${current.data}} -> `;
current = current.next;
}
return finalString + 'null';
}
kth(k) {
let current = this.head;
// if (!current) throw new Error('haed does not exist');
let count = this.length; // to start from zero at the tail not one
console.log(count, k);
while (current) {
if (k === count) {
return current.data;
}
count--;
current = current.next;
}
return "exception";
}
//reverse a linkedList
reverseList(list) {
let node = this.head;
const list2 = new LinkedList();
while (node) {
list2.insertAtHead(node.data);
node = node.next;
}
return list2;
}
isPalindrome() {
let flag = true;
let slow = this.head;
let stack = [];
while (slow) {
stack.push(slow.data);
slow = slow.next;
}
while (this.head) {
let i = stack.pop();
if (this.head.data === i) {
flag = true;
} else {
flag = false;
break;
}
this.head = this.head.next
}
return flag;
}
isPalindrome() {
let slow = this.head;
fast = this.head;
prev, temp;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
prev = slow;
slow = slow.next;
prev.next = null;
while (slow != null) {
temp = slow.next;
slow.next = prev;
prev = slow;
slow = temp;
}
fast = head;
slow = prev;
while (slow != null) {
if (fast.val != slow.val) return false;
fast = fast.next;
slow = slow.next;
}
return true;
}
//print data
printData() {
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
} |
JavaScript | class NotFoundError extends BaseError {
/**
* Creates a new NotFoundError.
*
* @param {string} message - The error message.
* @param {Error} inner - An optional error that caused the NotFoundError.
*/
constructor(message, inner) {
super(message, inner);
this.name = 'NotFoundError';
}
} |
JavaScript | class SyncState {
constructor(obj, opts) {
this.id = crypto.randomBytes(4).toString("hex");
this.observer = null;
this.version = 0;
this.obj = obj;
this.opts = opts || {};
if (this.opts.gzip === undefined) {
this.opts.gzip = true;
}
this.subscribers = [];
this.push = throttle(this.push.bind(this), 75);
this.push.state = this;
this.push(); //compute first payload
}
async handle(req, res) {
//manually execute compression middleware
if (this.opts.gzip) {
await new Promise(resolve => {
compressor(req, res, resolve);
});
}
//handle for realz
await this._handle(req, res);
}
async _handle(req, res) {
//connect this request to the sync state
let conn = new Connection(this);
//perform sse/websocket handshake
if (!await conn.setup(req, res)) {
return;
}
//block here and subscribe to changes
await conn.wait();
}
push() {
let currObj = jsonpatch.deepClone(this.obj);
let json = JSON.stringify(currObj);
if (this.json === json) {
return;
}
this.version++;
//compute diff
if (this.prevObj) {
this.delta = JSON.stringify(jsonpatch.compare(this.prevObj, currObj));
}
this.json = json;
this.prevObj = currObj;
//push to all subscribers
for (let i = 0; i < this.subscribers.length; i++) {
let conn = this.subscribers[i];
conn.push();
}
}
subscribe(conn) {
let i = this.subscribers.indexOf(conn);
if (i >= 0) {
return;
}
this.subscribers.push(conn);
//push curr state to just this connection
conn.push();
}
unsubscribe(conn) {
let i = this.subscribers.indexOf(conn);
if (i >= 0) {
this.subscribers.splice(i, 1);
}
}
debug() {
if (this.opts.debug) {
let args = Array.from(arguments);
console.log.apply(console, ["sync-state#" + this.id + ":"].concat(args));
}
}
} |
JavaScript | class LoadIonic extends LoadCollection
{
static get is(){ return 'load-ionic'}
docs(pkg){ return 'https://ionicframework.com/docs' }
isDisabledByDefault(pkg){}
initDependencies()
{ const init= i => this.initModule(i);
return [
// init(x=>import("@stencil/core/" )),
init(x=>import("@ionic/core/dist/ionic/ionic.esm" )),
// init(x=>import("@ionic/core/dist/esm/ionic.mjs" )),
]
}
} |
JavaScript | class DelinquentValidator {
constructor(data = {}) {
const state = store.getState()
const { formType = formTypes.SF86 } = state.application.Settings
this.data = data
this.formType = formType
}
validHasDelinquent() {
return validateModel(this.data, { HasDelinquent: delinquentItemsModel.HasDelinquent }) === true
}
validList() {
const requiredFinancialDelinquentName = requireFinancialDelinquentName(this.formType)
const requiredFinancialDelinquentInfraction = requireFinancialDelinquentInfraction(
this.formType
)
return validateModel(
this.data,
{ List: delinquentItemsModel.List },
{ requiredFinancialDelinquentName, requiredFinancialDelinquentInfraction },
) === true
}
isValid() {
return validateFinancialDelinquent(this.data, this.formType) === true
}
} |
JavaScript | class PostsIndex extends Component {
// when component is about to be shown on screen, make call to API using
// action creator using componentDidMountlifecycle method
componentDidMount() {
this.props.fetchPosts();
}
// use lodash map function to generate a list of <li> elements containing
// links to individual posts
renderPosts() {
return _.map(this.props.posts, post => {
return (
<li className="list-group-item" key={post.id}>
<Link to={`/posts/${post.id}`}>
{post.title}
</Link>
</li>
)
});
}
// Use React <Link /> component with "to" property indicating
// destination route
render() {
return(
<div>
<div className="text-xs-right">
<Link className="btn btn-primary" to="/posts/new">
Add a Post
</Link>
</div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
);
}
} |
JavaScript | class CancelToken extends EventEmitter {
/**
* Create a new cancellation token.
*
* The `executor` callback is called immediately by this constructor.
* It gets passed the `cancel` callback, which should be called on a cancellation request.
*
* @example this token is cancelled after a second passes:
* ```typescript
* const token = new CancelToken((cancel) => setTimeout(cancel, 1000));
* ```
*/
constructor(executor) {
super();
this._isCanceled = false;
executor(() => this._cancel());
}
get isCanceled() {
return this._isCanceled;
}
_cancel() {
this._isCanceled = true;
this._error = new errors.CancelError();
this.emit("_cancel");
}
/** @internal */
_onCancel(log, handler) {
this.once("_cancel", () => {
log.info(this._error);
handler(this._error);
});
}
/** @internal */
_throwIfCanceled(log) {
if (this._isCanceled) {
log.info(this._error);
throw this._error;
}
}
/** @internal */
_rejectOnCancel(log) {
return new Promise((_, reject) => {
this.once("_cancel", () => {
log.info(this._error);
reject(this._error);
});
});
}
/**
* Create a token that is automatically cancelled after `ms` milliseconds.
*/
static cancelAfter(ms) {
return new CancelToken((cancel) => setTimeout(cancel, ms));
}
} |
JavaScript | class CanvasRenderer extends ElementRenderer {
/**
* Constructor.
* @param {Object=} opt_options Options to configure the renderer
*/
constructor(opt_options) {
super(opt_options);
}
/**
* @inheritDoc
*/
getCanvas() {
var canvas = this.getRenderElement();
if (capture.isTainted(canvas)) {
return Promise.reject('The HTML 2D canvas has been tainted');
}
if (canvas) {
var targetPixelRatio = capture.getPixelRatio();
var canvasRect = canvas.getBoundingClientRect();
var canvasPixelRatio = canvas.width / canvasRect.width;
if (canvasPixelRatio !== targetPixelRatio) {
// create a new canvas and write the overlay to it
var pixelScale = targetPixelRatio / canvasPixelRatio;
var scaled = /** @type {HTMLCanvasElement} */ (document.createElement('canvas'));
scaled.width = canvas.width * pixelScale;
scaled.height = canvas.height * pixelScale;
// draw the original to the scaled canvas
var ctx = scaled.getContext('2d');
ctx.drawImage(canvas,
0, 0, canvas.width, canvas.height,
0, 0, scaled.width, scaled.height);
canvas = scaled;
}
}
return Promise.resolve(canvas);
}
} |
JavaScript | class VRMSmoothLookAtImporter extends ThreeVRM.VRMLookAtImporter {
import( gltf, firstPerson, blendShapeProxy, humanBodyBones ) {
const vrmExt = gltf.parser.json.extensions && gltf.parser.json.extensions.VRM;
if ( ! vrmExt ) return null;
const schemaFirstPerson = vrmExt.firstPerson;
if ( ! schemaFirstPerson ) return null;
const applyer = this._importApplyer( schemaFirstPerson, blendShapeProxy, humanBodyBones );
return new VRMSmoothLookAtHead( firstPerson, applyer || undefined );
}
} |
JavaScript | class DigestCoder extends CompositeType {
/**
* Constructor
*/
constructor() {
super('tx_op_digest');
this.description('Digest encoder for a Transaction operation.');
// config for digest creation
this.addSubType(
new Coding.Pascal.AccountNumber('sender')
.description('The sender account.')
);
this.addSubType(
new Coding.Pascal.NOperation('nOperation')
.description('The next n_operation value of the sender.')
);
this.addSubType(
new Coding.Pascal.AccountNumber('target')
.description('The receiving account.')
);
this.addSubType(
new Coding.Pascal.Currency('amount')
.description('The amount that is sent from sender to receiver.')
);
this.addSubType(
new Coding.Pascal.Currency('fee')
.description('The fee included in the operation.')
);
this.addSubType(
new Coding.Core.BytesWithoutLength('payload')
.description('The payload of the operation.')
);
this.addSubType(
new Coding.Pascal.Keys.Curve('v2_pubkey_curve')
.description('Curve ID 0 - previously active in <= v2.')
.withFixedValue(PublicKey.empty().curve)
);
this.addSubType(
new Coding.Pascal.OpType('optype', 1)
.description('Operation type.')
.withFixedValue(1)
);
}
/**
* @inheritDoc AbstractType#typeInfo
*/
/* istanbul ignore next */
get typeInfo() {
let info = super.typeInfo;
info.name = 'Transaction Operation (DIGEST)';
info.hierarchy.push(info.name);
return info;
}
/**
* @inheritDoc AbstractType#canDecode
*/
get canDecode() {
return false;
}
} |
JavaScript | class CustomLoadableRenderer extends LoadableRenderer {
componentDidMount() {
this.afterRender();
}
componentDidUpdate() {
this.afterRender();
}
afterRender() {
const {
loaded,
loading,
error
} = this.state;
const {
onRenderFailure,
onRenderSuccess
} = this.props;
if (!loading) {
if (error) {
onRenderFailure(error);
} else if (loaded && Object.keys(loaded).length > 0) {
onRenderSuccess();
}
}
}
} |
JavaScript | class Negotiator {
// other code
constructor(filter = {}, options = {}) {
let XMLconfig = {
attestationOrigin: "https://stage.attestation.id",
tokensOrigin: "https://devcontickets.herokuapp.com/outlet/",
tokenUrlName: 'ticket',
tokenSecretName: 'secret',
unsignedTokenDataName: 'ticket',
// tokenParserUrl: '',
tokenParser: SignedDevconTicket,
localStorageItemName: 'dcTokens'
};
this.queuedCommand = false;
this.filter = filter;
this.debug = 0;
this.hideTokensIframe = 1;
this.tokensOrigin = XMLconfig.tokensOrigin;
this.attestationOrigin = XMLconfig.attestationOrigin;
this.tokenUrlName = XMLconfig.tokenUrlName;
this.tokenSecretName = XMLconfig.tokenSecretName;
this.unsignedTokenDataName = XMLconfig.unsignedTokenDataName;
this.tokenParser = XMLconfig.tokenParser;
this.localStorageItemName = XMLconfig.localStorageItemName;
if (options.hasOwnProperty('debug')) this.debug = options.debug;
if (options.hasOwnProperty('attestationOrigin')) this.attestationOrigin = options.attestationOrigin;
if (options.hasOwnProperty('tokensOrigin')) this.tokensOrigin = options.tokensOrigin;
this.isTokenOriginWebsite = false;
if (this.attestationOrigin) {
// if attestationOrigin filled then token need attestaion
let currentURL = new URL(window.location.href);
let tokensOriginURL = new URL(this.tokensOrigin);
if (currentURL.origin === tokensOriginURL.origin) {
console.log('this is tokenOrigin. fire listener and read params');
// its tokens website, where tokens saved in localStorage
// lets chech url params and save token data to the local storage
this.isTokenOriginWebsite = true;
this.readMagicUrl();
}
}
// do we inside iframe?
if (window !== window.parent){
this.debug && console.log('negotiator: its iframe, lets return tokens to the parent');
// its iframe, listen for requests
this.attachPostMessageListener(this.listenForParentMessages.bind(this))
// send ready message to start interaction
let referrer = new URL(document.referrer);
window.parent.postMessage({iframeCommand: "iframeReady", iframeData: ''}, referrer.origin);
}
}
listenForParentMessages(event){
// listen only parent
let referrer = new URL(document.referrer);
if (event.origin !== referrer.origin) {
return;
}
// console.log('iframe: event = ', event.data);
// parentCommand+parentData required for interaction
if (
typeof event.data.parentCommand === "undefined"
|| typeof event.data.parentData === "undefined"
) {
return;
}
// parentCommand contain command code
let command = event.data.parentCommand;
// parentData contains command content (token to sign or empty object)
let data = event.data.parentData;
console.log('iframe: command, data = ', command, data);
switch (command) {
case "signToken":
console.log('let Auth data:', data);
if (typeof window.Authenticator === "undefined"){
console.log('Authenticator not defined.');
return;
}
let rawTokenData = this.getRawToken(data);
// console.log('rawTokenData: ',rawTokenData);
let base64ticket = rawTokenData.token;
let ticketSecret = rawTokenData.secret;
this.authenticator = new Authenticator(this);
this.authenticator.getAuthenticationBlob({
ticketBlob: base64ticket,
ticketSecret: ticketSecret,
attestationOrigin: this.attestationOrigin,
}, res => {
console.log('sign result:',res);
window.parent.postMessage({iframeCommand: "useTokenData", iframeData: {useToken: res, message: '', success: !!res}}, referrer.origin);
});
break;
case "tokensList":
// TODO update
console.log('let return tokens');
this.returnTokensToParent();
break;
default:
}
}
commandDisplayIframe(){
let referrer = new URL(document.referrer);
window.parent.postMessage({iframeCommand: "iframeWrap", iframeData: 'show'}, referrer.origin);
}
commandHideIframe(){
let referrer = new URL(document.referrer);
window.parent.postMessage({iframeCommand: "iframeWrap", iframeData: 'hide'}, referrer.origin);
}
returnTokensToParent(){
let tokensOutput = this.readTokens();
if (tokensOutput.success && !tokensOutput.noTokens) {
let decodedTokens = this.decodeTokens(tokensOutput.tokens);
let filteredTokens = this.filterTokens(decodedTokens);
tokensOutput.tokens = filteredTokens;
}
let referrer = new URL(document.referrer);
window.parent.postMessage({iframeCommand: "tokensData", iframeData: tokensOutput}, referrer.origin);
}
readMagicUrl() {
const urlParams = new URLSearchParams(window.location.search);
const tokenFromQuery = urlParams.get(this.tokenUrlName);
const secretFromQuery = urlParams.get(this.tokenSecretName);
if (! (tokenFromQuery && secretFromQuery) ) {
return;
}
// Get the current Storage Tokens
let tokensOutput = this.readTokens();
let tokens = [];
let isNewQueryTicket = true;
if (!tokensOutput.noTokens) {
// Build new list of tickets from current and query ticket { ticket, secret }
tokens = tokensOutput.tokens;
tokens.map(tokenData => {
if (tokenData.token === tokenFromQuery) {
isNewQueryTicket = false;
}
});
}
// Add ticket if new
// if (isNewQueryTicket && tokenFromQuery && secretFromQuery) {
if (isNewQueryTicket) {
tokens.push({token: tokenFromQuery, secret: secretFromQuery}); // new raw object
}
// Set New tokens list raw only, websters will be decoded each time
localStorage.setItem(this.localStorageItemName, JSON.stringify(tokens));
}
/*
* Return token objects satisfying the current negotiator's requirements
*/
filterTokens(decodedTokens, filter = {}) {
if (Object.keys(filter).length == 0) {
filter = this.filter;
}
let res = [];
if (
decodedTokens.length
&& typeof filter === "object"
&& Object.keys(filter).length
) {
let filterKeys = Object.keys(filter);
decodedTokens.forEach(token => {
let fitFilter = 1;
this.debug && console.log('test token:',token);
filterKeys.forEach(key => {
if (token[key].toString() != filter[key].toString()) fitFilter = 0;
})
if (fitFilter) {
res.push(token);
this.debug && console.log('token fits:',token);
}
})
return res;
} else {
return decodedTokens;
}
}
compareObjects(o1, o2){
for(var p in o1){
if(o1.hasOwnProperty(p)){
if(o1[p].toString() !== o2[p].toString()){
return false;
}
}
}
for(var p in o2){
if(o2.hasOwnProperty(p)){
if(o1[p].toString() !== o2[p].toString()){
return false;
}
}
}
return true;
};
// read tokens from local storage and return as object {tokens: [], noTokens: boolean, success: boolean}
readTokens(){
const storageTickets = localStorage.getItem(this.localStorageItemName);
let tokens = [];
let output = {tokens: [], noTokens: true, success: true};
try {
if (storageTickets && storageTickets.length) {
// Build new list of tickets from current and query ticket { ticket, secret }
tokens = JSON.parse(storageTickets);
if (tokens.length !== 0) {
// output.tokens = tokens;
tokens.forEach(item => {
if (item.token && item.secret) {
output.tokens.push({
token: item.token,
secret: item.secret
})
}
})
}
if (output.tokens.length) {
output.noTokens = false;
}
}
} catch (e) {
console.log('Cant parse tokens in LocalStorage');
if (typeof callBack === "function") {
output.success = false;
}
}
return output;
}
getRawToken(unsignedToken){
let tokensOutput = this.readTokens();
if (tokensOutput.success && !tokensOutput.noTokens) {
let rawTokens = tokensOutput.tokens;
let token = false;
if (rawTokens.length) {
rawTokens.forEach(tokenData=> {
if (tokenData.token){
let decodedToken = new this.tokenParser(this.base64ToUint8array(tokenData.token).buffer);
if (decodedToken && decodedToken[this.unsignedTokenDataName]) {
let decodedTokenData = decodedToken[this.unsignedTokenDataName];
if (this.compareObjects(decodedTokenData, unsignedToken)){
token = tokenData;
}
}
} else {
console.log('empty token data received');
}
})
}
return token;
}
}
listenForIframeMessages(event){
let tokensOriginURL = new URL(this.tokensOrigin);
// listen only tokensOriginURL
if (event.origin !== tokensOriginURL.origin) {
return;
}
// console.log('parent: event = ', event.data);
// iframeCommand required for interaction
if (
typeof event.data.iframeCommand === "undefined"
|| typeof event.data.iframeData === "undefined"
) {
return;
}
// iframeCommand contain command code
let command = event.data.iframeCommand;
// iframeData contains command content (tokens data, useToken , hide/display iframe)
let data = event.data.iframeData;
console.log('parent: command, data = ', command, data);
switch (command) {
case "iframeWrap":
if (data == "show") {
this.tokenIframeWrap.style.display = 'block';
} else if (data == "hide"){
this.tokenIframeWrap.style.display = 'none';
}
break;
case "tokensData":
// tokens received, disable listener
this.detachPostMessageListener(this.listenForIframeMessages);
// TODO remove iframeWraper
this.tokenIframeWrap.remove();
if (data.success && !data.noTokens) {
data.tokens = this.filterTokens(data.tokens);
}
this.negotiateCallback(data);
break;
case "useTokenData":
this.tokenIframeWrap.remove();
// if (data.success) {
// console.log('useTokenData: ' + data.useToken)
// } else {
// console.log('useTokenData error message: ' + data.message)
// }
console.log('this.signCallback(data)');
this.signCallback && this.signCallback(data);
this.signCallback = false;
break;
case "iframeReady":
event.source.postMessage(this.queuedCommand, event.origin);
this.queuedCommand = '';
break;
default:
}
}
signToken(unsignedToken, signCallback){
this.signCallback = signCallback;
// open iframe and request tokens
this.queuedCommand = {parentCommand: 'signToken',parentData: unsignedToken};
this.createIframe();
}
negotiate(callBack) {
// callback function required
if (typeof callBack !== "function") {
return false;
}
console.log('negotiateCallback added;');
this.negotiateCallback = callBack;
console.log('attestationOrigin = '+this.attestationOrigin);
if (this.attestationOrigin) {
if (window.location.href === this.tokensOrigin) {
// just read an return tokens
let tokensOutput = this.readTokens();
if (tokensOutput.success && !tokensOutput.noTokens) {
let decodedTokens = this.decodeTokens(tokensOutput.tokens);
let filteredTokens = this.filterTokens(decodedTokens);
tokensOutput.tokens = filteredTokens;
this.negotiateCallback(tokensOutput);
}
} else {
this.queuedCommand = {parentCommand: 'tokensList',parentData: ''};
this.createIframe()
}
} else {
console.log('no attestationOrigin...');
// TODO test token against blockchain and show tokens as usual view
}
}
createIframe(){
console.log('open iframe');
// open iframe and request tokens
this.attachPostMessageListener(this.listenForIframeMessages.bind(this));
const iframe = document.createElement('iframe');
this.iframe = iframe;
iframe.src = this.tokensOrigin;
iframe.style.width = '800px';
iframe.style.height = '700px';
iframe.style.maxWidth = '100%';
iframe.style.background = '#fff';
let iframeWrap = document.createElement('div');
this.tokenIframeWrap = iframeWrap;
iframeWrap.setAttribute('style', 'width:100%; min-height: 100vh; position: fixed; align-items: center; justify-content: center; display: none; top: 0; left: 0; background: #fffa');
iframeWrap.appendChild(iframe);
document.body.appendChild(iframeWrap);
}
base64ToUint8array( base64str ) {
// decode base64url to base64. it will do nothing for base64
base64str = base64str.split('-').join('+')
.split('_').join('/')
.split('.').join('=');
let res;
if (typeof Buffer !== 'undefined') {
res = Uint8Array.from(Buffer.from(base64str, 'base64'));
} else {
res = Uint8Array.from(atob(base64str), c => c.charCodeAt(0));
}
return res;
}
decodeTokens(rawTokens){
if (this.debug) {
console.log('decodeTokens fired');
console.log(rawTokens);
}
let decodedTokens = [];
if (rawTokens.length) {
rawTokens.forEach(tokenData=> {
if (tokenData.token){
let decodedToken = new this.tokenParser(this.base64ToUint8array(tokenData.token).buffer);
if (decodedToken && decodedToken[this.unsignedTokenDataName]) decodedTokens.push(decodedToken[this.unsignedTokenDataName]);
} else {
console.log('empty token data received');
}
})
}
return decodedTokens;
}
attachPostMessageListener(listener){
if (window.addEventListener) {
window.addEventListener("message", listener, false);
} else {
// IE8
window.attachEvent("onmessage", listener);
}
}
detachPostMessageListener(listener){
if (window.addEventListener) {
window.removeEventListener("message", listener, false);
} else {
// IE8
window.detachEvent("onmessage", listener);
}
}
} |
JavaScript | class WinScene extends Phaser.Scene {
/**
* Creates an instance of WinScene.
* @memberof WinScene
*/
constructor() {
super('WinScene');
}
/**
* Creates the content of the WinScene.
*
* @param {*} data
* @memberof WinScene
*/
create(data) {
this.cameras.main.fadeIn(3000);
const bg = this.add.image(512, 288, 'bg');
bg.setDepth(-3);
this.scene.get('MusicScene').play(2);
this.add.image(490, 262, 'sprites', 'newhorizons');
const nowwanus = this.physics.add.image(1200, 262, 'sprites', 'nowwanus');
nowwanus.setVelocityX(-25);
this.time.addEvent({
delay: 15000,
callback: () => {
this.cameras.main.fadeOut(3000, 255, 255, 255);
},
});
const offscreen = new Phaser.Geom.Rectangle(1024, 0, 1, 576);
const onscreen = new Phaser.Geom.Rectangle(0, 0, 1025, 576);
const dustGraphics = this.make.graphics();
dustGraphics.fillStyle(0xffffff);
dustGraphics.fillPoint(0, 0, 4);
dustGraphics.generateTexture('dust', 4, 4);
this.add.particles('dust', [{
emitZone: {
source: offscreen,
},
deathZone: {
source: onscreen,
type: 'onLeave',
},
frequency: 250,
speedX: {
min: -20,
max: -100,
},
lifespan: 15000,
}]);
this.add.text(16, 16, `In 2026 NASA\'s New Horizons probe
made the most distant flyby in space history`, {
fontSize: '20px',
fontFamily: 'font2',
lineSpacing: 8,
}).setOrigin(0);
const mid = this.add.text(16, 116, `After a dramatic 20-year long journey
New Horizons reached it's marvelous destination:
Nowwanus`, {
fontSize: '20px',
fontFamily: 'font2',
lineSpacing: 8,
}).setOrigin(0).setAlpha(0);
this.tweens.add({
delay: 5000,
targets: mid,
alpha: 1,
duration: 1000,
});
const bottom = this.add.text(16, 468, `But this is still not the end.
Beyond the outer edge of the Kuiper Belt,
the next destination awaits...`, {
fontSize: '20px',
fontFamily: 'font2',
lineSpacing: 8,
}).setOrigin(0).setAlpha(0);
this.tweens.add({
delay: 10000,
targets: bottom,
alpha: 1,
duration: 1000,
});
this.cameras.main.on('camerafadeoutcomplete', () => {
this.scene.start('MenuScene', data);
});
}
} |
JavaScript | class FileMetricsRow extends Component {
/**
* builds our metrics item for our console
* @param props
*/
constructor(props) {
super(props);
this.name = "[FileMetricsRow]";
this.state = {};
}
/**
* handles clicking on our metrics item. This will eventually allow for opening a chart or stats
* related to the file. No-op for now.
*/
handleOnClickRow = () => {
// this.props.onRowClick(this);
};
/**
* renders our box cell in the grid.
* @returns {*}
*/
getBoxCellContent() {
let extraModClass = "";
if (this.props.modified === "true") {
extraModClass = " modifiedfile";
}
return (
<div className={"chunkText" + extraModClass}>
{this.props.box}
</div>
);
}
/**
* renders our filename cell in the grid.
* @returns {*}
*/
getFileNameCellContent() {
let fileName = this.props.filePath;
if (fileName != null && fileName.includes("/")) {
fileName = fileName.substr(
this.props.filePath.lastIndexOf("/") + 1
);
}
let extraModClass = "";
if (this.props.modified === "true") {
extraModClass = " modifiedfile";
}
return (
<div className={"chunkText" + extraModClass}>
{fileName}
</div>
);
}
/**
* renders our duration cell in our grid
* @returns {*}
*/
getDurationCellContent() {
let extraModClass = "";
if (this.props.modified === "true") {
extraModClass = " modifiedduration";
}
return (
<div className={"chunkText" + extraModClass}>
{this.props.duration}
</div>
);
}
/**
* renders our gui for the popup information.
* @returns {*}
*/
getPopupContent() {
let fileName = this.props.filePath;
if (fileName != null && fileName.includes("/")) {
fileName = fileName.substr(
this.props.filePath.lastIndexOf("/") + 1
);
}
return (
<div>
<div>
<b>
<span className="tipHighlight">
{" "}
{fileName}{" "}
</span>
</b>
<Divider />
</div>
<div>{this.props.filePath}</div>
</div>
);
}
/**
* renders our metrics item in our grid for the console
* @returns {*}
*/
render() {
let boxCell = this.getBoxCellContent(),
filenameCell = this.getFileNameCellContent(),
durationCell = this.getDurationCellContent(),
popupContent = this.getPopupContent();
return (
<Grid.Row
id={1}
className={"metricRow"}
onClick={this.handleOnClickRow}
>
<Grid.Column width={3}>
<Popup
flowing
trigger={boxCell}
className="metricContent"
content={popupContent}
position="bottom left"
inverted
hideOnScroll
/>
</Grid.Column>
<Grid.Column width={9}>
<Popup
flowing
trigger={filenameCell}
className="metricContent"
content={popupContent}
position="bottom left"
inverted
hideOnScroll
/>
</Grid.Column>
<Grid.Column width={4}>
<Popup
flowing
trigger={durationCell}
className="metricContent"
content={popupContent}
position="bottom left"
inverted
/>
</Grid.Column>
</Grid.Row>
);
}
} |
JavaScript | class Empty extends AntHill {
/**
* @param {string} name
* @param {Widget} containment
* @param opts
* @constructor
*/
constructor(name, containment, opts) {
super(name || 'Empty', null, true);
/**
* Define containment
* @property Empty
* @type {Widget}
*/
this.containment = containment;
/**
* Define image
* @property Empty
*/
this.image = image;
/**
* Define referrer
* @property Empty
* @type {*}
*/
this.referrer = undefined;
this.initContent(opts);
}
/**
* @memberOf Empty
* @param opts
*/
initContent(opts) {
/**
* @constant DEFAULTS
* @type {{
* plugin: boolean,
* html: {
* style: string,
* header: boolean,
* footer: boolean,
* padding: {top: number, right: number, bottom: number, left: number}
* }
* }}
*/
const DEFAULTS = {
plugin: true,
html: {
style: 'default',
header: false,
footer: false,
padding: {
top: 0,
right: 0,
bottom: 0,
left: 0
}
}
};
/**
* @constant components
* @type {{Controller, Model, View, EventManager, Permission}}
*/
const components = Empty.fetchComponents();
/**
* @type {MVC}
*/
new MVC({
scope: this,
config: [
{uuid: this.containment.model.getContentUUID()},
DEFAULTS
],
components: [
components.Controller,
components.Model,
components.View,
components.EventManager,
components.Permission
],
render: true
});
this.observer.publish(this.eventManager.eventList.initWidget, opts);
}
/**
* @method init
* @memberOf Empty
* @static
* @returns {*}
*/
static fetchComponents() {
return {
Controller: EmptyController,
Model: EmptyModel,
View: EmptyView,
EventManager: EmptyEventManager,
Permission: EmptyPermission
};
}
} |
JavaScript | class DropDown extends Element{
/**
* creates DropDown object by calling Element Constructor with type "Drop Down"
* @constructor
* @param {number} x the x-coordinate of Drop Down element
* @param {number} y the y-coordinate of Drop Down element
* @param {number} width width of the element
* @param {number} height height of the element
*/
constructor(x, y, width, height){
super(x, y, width, height, "Drop Down");
}
/**
* checks if there is a collision on specific side of the element
* @param {Entity} entity the entity that collides with this
* @param {number} side the side where collision occurs
* @param {number} entityX the x-coordinate of the entity
* @param {number} entityY the y-coordinate of the entity
* @returns {boolean} returns true if collision occurs on any side other than 2
*/
collision(entity, side, entityX, entityY){
if(side === 2){
let relFeetHeight = entityY - entity.box.height/2 - this.pos.y;
if( relFeetHeight > -this.box.height && relFeetHeight < this.box.height/2){
return false;
}
}
return true;
}
} |
JavaScript | class Functions {
/**
* Create a Functions.
* @param {StreamAnalyticsManagementClient} client Reference to the service client.
*/
constructor(client) {
this.client = client;
this._createOrReplace = _createOrReplace;
this._update = _update;
this._deleteMethod = _deleteMethod;
this._get = _get;
this._listByStreamingJob = _listByStreamingJob;
this._test = _test;
this._retrieveDefaultDefinition = _retrieveDefaultDefinition;
this._beginTest = _beginTest;
this._listByStreamingJobNext = _listByStreamingJobNext;
}
/**
* Creates a function or replaces an already existing function under an
* existing streaming job.
*
* @param {object} functionParameter The definition of the function that will
* be used to create a new function or replace the existing one under the
* streaming job.
*
* @param {object} [functionParameter.properties] The properties that are
* associated with a function.
*
* @param {string} functionParameter.properties.type Polymorphic Discriminator
*
* @param {string} [functionParameter.name] Resource name
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.ifMatch] The ETag of the function. Omit this value
* to always overwrite the current function. Specify the last-seen ETag value
* to prevent accidentally overwritting concurrent changes.
*
* @param {string} [options.ifNoneMatch] Set to '*' to allow a new function to
* be created, but to prevent updating an existing function. Other values will
* result in a 412 Pre-condition Failed response.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<FunctionModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
createOrReplaceWithHttpOperationResponse(functionParameter, resourceGroupName, jobName, functionName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._createOrReplace(functionParameter, resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Creates a function or replaces an already existing function under an
* existing streaming job.
*
* @param {object} functionParameter The definition of the function that will
* be used to create a new function or replace the existing one under the
* streaming job.
*
* @param {object} [functionParameter.properties] The properties that are
* associated with a function.
*
* @param {string} functionParameter.properties.type Polymorphic Discriminator
*
* @param {string} [functionParameter.name] Resource name
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.ifMatch] The ETag of the function. Omit this value
* to always overwrite the current function. Specify the last-seen ETag value
* to prevent accidentally overwritting concurrent changes.
*
* @param {string} [options.ifNoneMatch] Set to '*' to allow a new function to
* be created, but to prevent updating an existing function. Other values will
* result in a 412 Pre-condition Failed response.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {FunctionModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link FunctionModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
createOrReplace(functionParameter, resourceGroupName, jobName, functionName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._createOrReplace(functionParameter, resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._createOrReplace(functionParameter, resourceGroupName, jobName, functionName, options, optionalCallback);
}
}
/**
* Updates an existing function under an existing streaming job. This can be
* used to partially update (ie. update one or two properties) a function
* without affecting the rest the job or function definition.
*
* @param {object} functionParameter A function object. The properties
* specified here will overwrite the corresponding properties in the existing
* function (ie. Those properties will be updated). Any properties that are set
* to null here will mean that the corresponding property in the existing
* function will remain the same and not change as a result of this PATCH
* operation.
*
* @param {object} [functionParameter.properties] The properties that are
* associated with a function.
*
* @param {string} functionParameter.properties.type Polymorphic Discriminator
*
* @param {string} [functionParameter.name] Resource name
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.ifMatch] The ETag of the function. Omit this value
* to always overwrite the current function. Specify the last-seen ETag value
* to prevent accidentally overwritting concurrent changes.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<FunctionModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
updateWithHttpOperationResponse(functionParameter, resourceGroupName, jobName, functionName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._update(functionParameter, resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Updates an existing function under an existing streaming job. This can be
* used to partially update (ie. update one or two properties) a function
* without affecting the rest the job or function definition.
*
* @param {object} functionParameter A function object. The properties
* specified here will overwrite the corresponding properties in the existing
* function (ie. Those properties will be updated). Any properties that are set
* to null here will mean that the corresponding property in the existing
* function will remain the same and not change as a result of this PATCH
* operation.
*
* @param {object} [functionParameter.properties] The properties that are
* associated with a function.
*
* @param {string} functionParameter.properties.type Polymorphic Discriminator
*
* @param {string} [functionParameter.name] Resource name
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.ifMatch] The ETag of the function. Omit this value
* to always overwrite the current function. Specify the last-seen ETag value
* to prevent accidentally overwritting concurrent changes.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {FunctionModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link FunctionModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
update(functionParameter, resourceGroupName, jobName, functionName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._update(functionParameter, resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._update(functionParameter, resourceGroupName, jobName, functionName, options, optionalCallback);
}
}
/**
* Deletes a function from the streaming job.
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName, jobName, functionName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._deleteMethod(resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Deletes a function from the streaming job.
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName, jobName, functionName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._deleteMethod(resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._deleteMethod(resourceGroupName, jobName, functionName, options, optionalCallback);
}
}
/**
* Gets details about the specified function.
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<FunctionModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName, jobName, functionName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._get(resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Gets details about the specified function.
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {FunctionModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link FunctionModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName, jobName, functionName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._get(resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._get(resourceGroupName, jobName, functionName, options, optionalCallback);
}
}
/**
* Lists all of the functions under the specified streaming job.
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.select] The $select OData query parameter. This is
* a comma-separated list of structural properties to include in the response,
* or “*” to include all properties. By default, all properties are returned
* except diagnostics. Currently only accepts '*' as a valid value.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<FunctionListResult>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
listByStreamingJobWithHttpOperationResponse(resourceGroupName, jobName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._listByStreamingJob(resourceGroupName, jobName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Lists all of the functions under the specified streaming job.
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.select] The $select OData query parameter. This is
* a comma-separated list of structural properties to include in the response,
* or “*” to include all properties. By default, all properties are returned
* except diagnostics. Currently only accepts '*' as a valid value.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {FunctionListResult} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link FunctionListResult} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
listByStreamingJob(resourceGroupName, jobName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._listByStreamingJob(resourceGroupName, jobName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._listByStreamingJob(resourceGroupName, jobName, options, optionalCallback);
}
}
/**
* Tests if the information provided for a function is valid. This can range
* from testing the connection to the underlying web service behind the
* function or making sure the function code provided is syntactically correct.
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.functionProperty] If the function specified does
* not already exist, this parameter must contain the full function definition
* intended to be tested. If the function specified already exists, this
* parameter can be left null to test the existing function as is or if
* specified, the properties specified will overwrite the corresponding
* properties in the existing function (exactly like a PATCH operation) and the
* resulting function will be tested.
*
* @param {object} [options.functionProperty.properties] The properties that
* are associated with a function.
*
* @param {string} options.functionProperty.properties.type Polymorphic
* Discriminator
*
* @param {string} [options.functionProperty.name] Resource name
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ResourceTestStatus>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
testWithHttpOperationResponse(resourceGroupName, jobName, functionName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._test(resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Tests if the information provided for a function is valid. This can range
* from testing the connection to the underlying web service behind the
* function or making sure the function code provided is syntactically correct.
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.functionProperty] If the function specified does
* not already exist, this parameter must contain the full function definition
* intended to be tested. If the function specified already exists, this
* parameter can be left null to test the existing function as is or if
* specified, the properties specified will overwrite the corresponding
* properties in the existing function (exactly like a PATCH operation) and the
* resulting function will be tested.
*
* @param {object} [options.functionProperty.properties] The properties that
* are associated with a function.
*
* @param {string} options.functionProperty.properties.type Polymorphic
* Discriminator
*
* @param {string} [options.functionProperty.name] Resource name
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {ResourceTestStatus} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link ResourceTestStatus} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
test(resourceGroupName, jobName, functionName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._test(resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._test(resourceGroupName, jobName, functionName, options, optionalCallback);
}
}
/**
* Retrieves the default definition of a function based on the parameters
* specified.
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.functionRetrieveDefaultDefinitionParameters]
* Parameters used to specify the type of function to retrieve the default
* definition for.
*
* @param {string}
* options.functionRetrieveDefaultDefinitionParameters.bindingType Polymorphic
* Discriminator
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<FunctionModel>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
retrieveDefaultDefinitionWithHttpOperationResponse(resourceGroupName, jobName, functionName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._retrieveDefaultDefinition(resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Retrieves the default definition of a function based on the parameters
* specified.
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.functionRetrieveDefaultDefinitionParameters]
* Parameters used to specify the type of function to retrieve the default
* definition for.
*
* @param {string}
* options.functionRetrieveDefaultDefinitionParameters.bindingType Polymorphic
* Discriminator
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {FunctionModel} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link FunctionModel} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
retrieveDefaultDefinition(resourceGroupName, jobName, functionName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._retrieveDefaultDefinition(resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._retrieveDefaultDefinition(resourceGroupName, jobName, functionName, options, optionalCallback);
}
}
/**
* Tests if the information provided for a function is valid. This can range
* from testing the connection to the underlying web service behind the
* function or making sure the function code provided is syntactically correct.
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.functionProperty] If the function specified does
* not already exist, this parameter must contain the full function definition
* intended to be tested. If the function specified already exists, this
* parameter can be left null to test the existing function as is or if
* specified, the properties specified will overwrite the corresponding
* properties in the existing function (exactly like a PATCH operation) and the
* resulting function will be tested.
*
* @param {object} [options.functionProperty.properties] The properties that
* are associated with a function.
*
* @param {string} options.functionProperty.properties.type Polymorphic
* Discriminator
*
* @param {string} [options.functionProperty.name] Resource name
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ResourceTestStatus>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
beginTestWithHttpOperationResponse(resourceGroupName, jobName, functionName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._beginTest(resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Tests if the information provided for a function is valid. This can range
* from testing the connection to the underlying web service behind the
* function or making sure the function code provided is syntactically correct.
*
* @param {string} resourceGroupName The name of the resource group that
* contains the resource. You can obtain this value from the Azure Resource
* Manager API or the portal.
*
* @param {string} jobName The name of the streaming job.
*
* @param {string} functionName The name of the function.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.functionProperty] If the function specified does
* not already exist, this parameter must contain the full function definition
* intended to be tested. If the function specified already exists, this
* parameter can be left null to test the existing function as is or if
* specified, the properties specified will overwrite the corresponding
* properties in the existing function (exactly like a PATCH operation) and the
* resulting function will be tested.
*
* @param {object} [options.functionProperty.properties] The properties that
* are associated with a function.
*
* @param {string} options.functionProperty.properties.type Polymorphic
* Discriminator
*
* @param {string} [options.functionProperty.name] Resource name
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {ResourceTestStatus} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link ResourceTestStatus} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
beginTest(resourceGroupName, jobName, functionName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._beginTest(resourceGroupName, jobName, functionName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._beginTest(resourceGroupName, jobName, functionName, options, optionalCallback);
}
}
/**
* Lists all of the functions under the specified streaming job.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<FunctionListResult>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
listByStreamingJobNextWithHttpOperationResponse(nextPageLink, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._listByStreamingJobNext(nextPageLink, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Lists all of the functions under the specified streaming job.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {FunctionListResult} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link FunctionListResult} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
listByStreamingJobNext(nextPageLink, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._listByStreamingJobNext(nextPageLink, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._listByStreamingJobNext(nextPageLink, options, optionalCallback);
}
}
} |
JavaScript | class WebDialog extends HTMLElement {
/**
* Attaches the shadow root.
*/
constructor() {
super();
this.$scrollContainer = document.documentElement;
this.$previousActiveElement = null;
const shadow = this.attachShadow({ mode: "open" });
shadow.appendChild(template.content.cloneNode(true));
this.$dialog = shadow.querySelector("#dialog");
this.$backdrop = shadow.querySelector("#backdrop");
this.onBackdropClick = this.onBackdropClick.bind(this);
this.onKeyDown = this.onKeyDown.bind(this);
// Set aria attributes
this.$dialog.setAttribute("role", "alertdialog");
}
static get observedAttributes() {
return ["open", "center"];
}
/**
* Whether the dialog is opened.
* @attr
*/
get open() {
return this.hasAttribute("open");
}
set open(value) {
value ? this.setAttribute("open", "") : this.removeAttribute("open");
}
/**
* Whether the dialog is centered on the page.
* @attr
*/
get center() {
return this.hasAttribute("center");
}
set center(value) {
value ? this.setAttribute("center", "") : this.removeAttribute("center");
}
/**
* Attaches event listeners when connected.
*/
connectedCallback() {
this.setAttribute("aria-modal", "true");
this.$backdrop.addEventListener("click", this.onBackdropClick);
}
/**
* Removes event listeners when disconnected.
*/
disconnectedCallback() {
this.$backdrop.removeEventListener("click", this.onBackdropClick);
// If the dialog is open when it is removed from the DOM
// we need to cleanup the event listeners and side effects.
if (this.open) {
this.didClose();
}
}
/**
* Shows the dialog.
*/
show() {
this.open = true;
}
/**
* Closes the dialog with a result.
* @param result
*/
close(result) {
this.result = result;
this.open = false;
}
/**
* Closes the dialog when the backdrop is clicked.
*/
onBackdropClick() {
if (this.assertClosing()) {
this.close();
}
}
/**
* Closes the dialog when escape is pressed.
*/
onKeyDown(e) {
switch (e.code) {
case "Escape":
if (this.assertClosing()) {
this.close();
// If there are more dialogs, we don't want to close those also :-)
e.stopImmediatePropagation();
}
break;
}
}
/**
* Dispatches an event that, if asserts whether the dialog can be closed.
* If "preventDefault()" is called on the event, assertClosing will return true
* if the event was not cancelled. It will return false if the event was cancelled.
*/
assertClosing() {
return this.dispatchEvent(new CustomEvent("closing", { cancelable: true }));
}
/**
* Setup the dialog after it has opened.
*/
didOpen() {
// Save the current active element so we have a way of restoring the focus when the dialog is closed.
this.$previousActiveElement = traverseActiveElements(document.activeElement);
// Focus the first element in the focus trap.
// Wait for the dialog to show its content before we try to focus inside it.
// We request an animation frame to make sure the content is now visible.
requestAnimationFrame(() => {
this.$dialog.focusFirstElement();
});
// Make the dialog focusable
this.tabIndex = 0;
// Block the scrolling on the scroll container to avoid the outside content to scroll.
this.$scrollContainer.style.overflow = `hidden`;
// Listen for key down events to close the dialog when escape is pressed.
this.addEventListener("keydown", this.onKeyDown, { capture: true, passive: true });
// Increment the dialog count with one to keep track of how many dialogs are currently nested.
setDialogCount(this.$scrollContainer, getDialogCount(this.$scrollContainer) + 1);
// Dispatch an event so the rest of the world knows the dialog opened.
this.dispatchEvent(new CustomEvent("open"));
}
/**
* Clean up the dialog after it has closed.
*/
didClose() {
// Remove the listener listening for key events
this.removeEventListener("keydown", this.onKeyDown, { capture: true });
// Decrement the dialog count with one to keep track of how many dialogs are currently nested.
setDialogCount(this.$scrollContainer, Math.max(0, getDialogCount(this.$scrollContainer) - 1));
// If there are now 0 active dialogs we unblock the scrolling from the scroll container.
// This is because we know that no other dialogs are currently nested within the scroll container.
if (getDialogCount(this.$scrollContainer) <= 0) {
this.$scrollContainer.style.overflow = ``;
}
// Make the dialog unfocusable.
this.tabIndex = -1;
// Restore previous active element.
if (this.$previousActiveElement != null) {
this.$previousActiveElement.focus();
this.$previousActiveElement = null;
}
// Dispatch an event so the rest of the world knows the dialog closed.
// If a result has been set, the result is added to the detail property of the event.
this.dispatchEvent(new CustomEvent("close", { detail: this.result }));
}
/**
* Reacts when an observed attribute changes.
*/
attributeChangedCallback(name, newValue, oldValue) {
switch (name) {
case "open":
this.open ? this.didOpen() : this.didClose();
break;
}
}
} |
JavaScript | class IconManager {
constructor(options) {
this.options = Object.assign({}, IconManager.defaultOptions, options)
if (!this.options.svgJsonFile) {
throw new Error('No SVG json data file given!')
}
if (!this.options.svgSpriteFile) {
throw new Error('No SVG sprite file given!')
}
this.$svgSprite = document.createElement('div')
}
/**
* Inject markup of svg sprite into the page.
* @param {Function} cb - Callback when finished.
* @param {Function} [polyfillAlreadyLoadedIcons=true] - Whether already loaded icons should be polyfilled (ie11)
*/
injectSprite(cb, polyfillAlreadyLoadedIcons = true) {
var request = new XMLHttpRequest()
request.open('GET', this.options.svgSpriteFile, true)
request.send()
request.onload = e => {
this.$svgSprite.innerHTML = request.responseText
document.body.insertBefore(this.$svgSprite, document.body.childNodes[0])
cb(this, e)
}
}
/**
* Load icon metadata.
* @param {Function} cb - Callback when finished.
*/
loadData(cb) {
var request = new XMLHttpRequest()
request.open('GET', this.options.svgJsonFile, true)
request.send()
request.onload = e => {
this.iconsData = JSON.parse(request.responseText)
cb(this, e)
}
}
/**
* Return metadata of given icon.
*
* @param {String} iconId - Icon id to return metadata from.
* @returns {Object}
*/
getIconFromData(iconId) {
var iconData = this.iconsData.icons[iconId]
if (!iconData)
throw new Error(
`No icon "${iconId}" found in icon json data file "${
this.options.svgJsonFile
}"!`
)
return this.iconsData.icons[iconId]
}
/**
* Return svg element from sprite.
*
* @param {String} iconId - Icon id of the element to return.
* @returns {Element}
*/
getIconFromSprite(iconId) {
var $spriteIcon = this.$svgSprite.querySelector(
`#${this.options.prefixId}${iconId}`
)
if (!$spriteIcon)
throw new Error(
`No icon "${iconId}" found in svg sprite file "${
this.options.svgSpriteFile
}"!`
)
return $spriteIcon
}
} |
JavaScript | class CoursePageModel {
/**
* Declares an array to use for the cards for each course's subtopic.
* @constructor constructor
*/
constructor() {
this.cards = [1, 2, 3, 4, 5, 6, 7, 8, 9];
this.dict = {1: "Software Process",2: "Software Analysis",
3: "Software Architecture",4: "Software Design",5: "Software Code Generation",
6: "Test 6",7: "Test 7",8: "Test 8",
9: "Test 9"};
}
/**
* @method getCards
* @returns this instance's course topics list model cards.
*/
getCards()
{
return this.cards;
}
/**
* Uses course ID to get each course's information
* @method getData
* @param {int} id - Course ID to distinguish different courses.
* @returns Course topics from database and stores it in this instance's list model cards.
*/
getData = async (id) => {
try {
const data = await axios.get(
`http://localhost:4000/courses/${id}`
);
return data.data
} catch(e) {
console.log(e);
}
};
} |
JavaScript | class LinearEquation3 {
constructor( a, b, c, d ) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.coefficients = [ a, b, c ];
this.constant = d;
this.numberOfVariables = 3;
}
clone() {
return new this.constructor( this.a, this.b, this.c, this.d );
}
multiplyScalar( k ) {
let _ = this.coefficients;
this.a = _[ 0 ] *= k;
this.b = _[ 1 ] *= k;
this.c = _[ 2 ] *= k;
this.d = this.constant *= k;
return this;
}
negate() {
return this.multiplyScalar( - 1 );
}
add( equation ) {
let _ = this.coefficients;
let e = equation.coefficients;
this.a = _[ 0 ] += e[ 0 ];
this.b = _[ 1 ] += e[ 1 ];
this.c = _[ 2 ] += e[ 2 ];
this.d = this.constant += equation.constant;
return this;
}
subtract( equation ) {
let _ = this.coefficients;
let e = equation.coefficients;
this.a = _[ 0 ] -= e[ 0 ];
this.b = _[ 1 ] -= e[ 1 ];
this.c = _[ 2 ] -= e[ 2 ];
this.d = this.constant -= equation.constant;
return this;
}
} |
JavaScript | class FieldMixin extends Vue {
@Inject({
default: null
})
form
@Prop(String) id
@Prop(String) name
@Prop() value
@Prop() defaultValue
@Prop({
type: [String, Boolean],
default: null
})
label
@Prop(String) labelClass
@Prop(String) placeholder
@Prop(String) notice
@Prop([Boolean, null])
required
@Prop([String, null])
requiredText
@Prop([String, null])
optionalText
@Prop(Boolean) disabled
@Prop(Boolean) loading
localValue = null
hash = Math.random()
.toString(36)
.substring(2, 10)
get cForm() {
return this.form ? this.form : null
}
/**
* The computed name of the form container, used for the creation of the input fields id.
* A random string is used if no name is supplied.
*
* @returns string
*/
get formName() {
return this.cForm ? this.cForm.name : ''
}
/**
* Retrieve the configuration options for this form.
*
* @returns object
*/
get config() {
return this.cForm ? this.cForm.config : {}
}
/**
* The computed id of this field.
*
* @returns string
*/
get cId() {
return this.id ? this.id : this.formName + '-' + (this.name || this.hash)
}
/**
* The computed value of this field.
* This function attempts to derive the value from a number of possible sources.
* If the value prop was supplied directly, that's what will be used.
* If the parent form has data and a field with the corresponding name, it'll return that instead.
* If nothing is found, the defaultValue prop will be used.
* And if that isn't set either just an empty string will be returned.
*
* @returns {any}
*/
get cValue() {
if (!this.isEmpty(this.value)) {
return this.value
}
const data = this.cForm ? this.cForm.localData : {}
if (this.name && data) {
const val = data[this.name]
if (!this.isEmpty(val)) {
return get(data, this.name)
}
}
if (!this.isEmpty(this.localValue)) {
return this.localValue
}
if (this.defaultValue) {
return this.defaultValue || ''
}
return null
}
/**
* Helper function to check whether the parent form is in a loading state.
*
* @returns string|array
*/
get formLoading() {
return this.cForm ? this.cForm.loading : false
}
/**
* Retrieve the errors for this particular input field.
*
* @returns string|array
*/
get errors() {
const errors = this.cForm ? this.cForm.errors : null
return errors && errors[this.name] ? errors[this.name] : null
}
/**
* Check if a value is either null, undefined or an empty string.
* Zeroes are viewed as non-empty.
*
* @returns {boolean}
*/
isEmpty(val) {
return val === null || val === undefined
}
/**
* The updateValue method updates this fields value within the parent forms localData.
* Emits an "updated" event with the new and old value as attributes
*
* @param {Event|Boolean|String} e
* @returns {void}
*/
updateValue(e) {
const value = e !== null && typeof e === 'object' && e.target ? e.target.value : e
this.$emit('updated', value, this.cValue)
if (this.name && this.cForm) {
this.cForm.setValue(this.name, value)
} else {
this.localValue = value
}
}
/**
* Save the initial field value to local data on mount.
*/
mounted() {
if (this.name && this.cForm) {
this.cForm.setValue(this.name, this.cValue)
}
}
} |
JavaScript | class DefaultValue {
/**
* @param {any} value The wrapped default value.
* @param {string} description A description of the contained value. Used to produce
* the comment string.
*/
constructor(value, description) {
this.value = value;
this.description = description;
}
/**
* Duplicate the current default value.
* <p>
* Wrapped value will be shallow copied.
*
* @returns {module:core/schema~DefaultValue} A new instance of the current default value.
*/
clone() {
const result = new DefaultValue(this.value, this.description);
if (result.value instanceof DefaultValue) {
result.value = result.value.clone();
} else if (typeOf(result.value) === 'array') {
result.value = [].concat(result.value);
} else if (typeOf(result.value) === 'object') {
result.value = Object.assign({}, result.value);
}
return result;
}
/**
* Unwrap current {module:core/schema~DefaultValue} if its wrapped value is also a
* {module:core/schema~DefaultValue}.
* <p>
* The description will also be replaced with wrapped value description, if exists.
*/
flatten() {
if (this.value instanceof DefaultValue) {
this.value.flatten();
if (hasOwnProperty(this.value, 'description') && this.value.description) {
this.description = this.value.description;
}
this.value = this.value.value;
}
}
/**
* Merge current default value with another default value.
*
* @param {module:core/schema~DefaultValue} source The input object to be merged with. Should have the
* same wrapped value type as current wrapped default value.
*/
merge(source) {
if (hasOwnProperty(source, 'value') && source.value !== null) {
this.flatten();
if (source.value instanceof DefaultValue) {
source = source.clone();
source.flatten();
}
if (typeOf(source.value) === typeOf(this.value)) {
if (typeOf(this.value) === 'array') {
this.value = this.value.concat(source.value);
} else if (typeOf(this.value) === 'object') {
Object.keys(source.value).forEach(key => {
this.value[key] = source.value[key];
});
} else {
this.value = source.value;
}
} else if (typeOf(this.value) === 'undefined' || typeOf(this.value) === 'null') {
this.value = source.value;
}
}
if (hasOwnProperty(source, 'description') && source.description) {
this.description = source.description;
}
}
/**
* Create a new array with comments inserted as new elements right before each child element.
* <p>
* If current wrapped value is an array and some of its elements are instances of
* {@link module:core/schema~DefaultValue}, the element's description will be inserted as a new child
* right before the element.
* The element itself will also be converted into its commented version using the <code>toCommented</code>
* method.
*
* @returns {Array} A new array with comments and the original elements in the commented form.
*/
toCommentedArray() {
return [].concat(...this.value.map(item => {
if (item instanceof DefaultValue) {
if (typeOf(item.description) !== 'string' || !item.description.trim()) {
return [item.toCommented()];
}
return item.description.split('\n').map((line, i) => {
return MAGIC + i + ': ' + line;
}).concat(item.toCommented());
} else if (typeOf(item) === 'array' || typeOf(item) === 'object') {
return new DefaultValue(item).toCommented();
}
return [item];
}));
}
/**
* Create a new object with comments inserted as new properties right before every original properties.
* <p>
* Works similar to {@link module:core/schema~DefaultValue#toCommentedArray}.
*
* @returns {Object} A new object with comments and the original property values in the commented form.
*/
toCommentedObject() {
if (this.value instanceof DefaultValue) {
return this.value.toCommented();
}
const result = {};
for (const key in this.value) {
const item = this.value[key];
if (item instanceof DefaultValue) {
if (typeOf(item.description) === 'string' && item.description.trim()) {
item.description.split('\n').forEach((line, i) => {
result[MAGIC + key + i] = line;
});
}
result[key] = item.toCommented();
} else if (typeOf(item) === 'array' || typeOf(item) === 'object') {
result[key] = new DefaultValue(item).toCommented();
} else {
result[key] = item;
}
}
return result;
}
/**
* Call {@link module:core/schema~DefaultValue#toCommentedArray} or
* {@link module:core/schema~DefaultValue#toCommentedObject} based on the type of the wrapped value.
* <p>
* If neither applies, directly return the wrapped value.
*
* @returns {any} The commented object/array, or the original wrapped value.
*/
toCommented() {
if (typeOf(this.value) === 'array') {
return this.toCommentedArray();
} else if (typeOf(this.value) === 'object') {
return this.toCommentedObject();
}
return this.value;
}
/**
* Create the YAML string with all the comments from current default value.
*
* @returns {string} The formatted YAML string.
*/
toYaml() {
const regex = new RegExp("^(\\s*)(?:-\\s*\\')?" + MAGIC + ".*?:\\s*\\'?(.*?)\\'*$", 'mg');
return yaml.stringify(this.toCommented()).replace(regex, '$1# $2'); // restore comments
}
} |
JavaScript | class Schema {
/**
* @param {module:core/schema~SchemaLoader} loader JSON schema loader.
* @param {Object} def The JSON schema definition.
*/
constructor(loader, def) {
if (!(loader instanceof SchemaLoader)) {
throw new Error('loader must be an instance of SchemaLoader');
}
if (typeOf(def) !== 'object') {
throw new Error('schema definition must be an object');
}
this.loader = loader;
this.def = def;
this.compiledSchema = null;
}
/**
* Validate an object against the JSON schema.
*
* @param {any} obj Object to be validated.
* @returns {boolean|Object} True if Object is valid, or validation errors.
*/
validate(obj) {
if (!this.compiledSchema) {
this.compiledSchema = this.loader.compileValidator(this.def.$id);
}
return this.compiledSchema(obj) ? true : this.compiledSchema.errors;
}
/**
* Create the {@link module:core/schema~DefaultValue} for an array-typed JSON schema.
* <p>
* Each possible type of the array elements defined in <code>oneOf</code> will be processed and a
* {@link module:core/schema~DefaultValue} will be added to the result array.
*
* @param {Object} def JSON schema definition of the array.
* @returns {@link module:core/schema~DefaultValue} The {@link module:core/schema~DefaultValue} for the
* array definition.
*/
getArrayDefaultValue(def) {
const defaultValue = new DefaultValue(null, def.description); // all array elements have the same type, return the default value for that type
if (typeOf(def.items) === 'object') {
const items = Object.assign({}, def.items);
delete items.oneOf;
let value = this.getDefaultValue(items); // additionally, if each array element can be in one of the provided types in <code>oneOf</code>
if (typeOf(def.items.oneOf) === 'array') {
// for each <code>oneOf</code> element, return a {@link module:core/schema~DefaultValue}
defaultValue.value = def.items.oneOf.map(one => {
// if the <code>items</code> definition also exists, merge it with the <code>oneOf</code>
// {@link module:core/schema~DefaultValue}
const clone = value.clone();
clone.merge(this.getDefaultValue(one));
return clone;
});
} else {
if (typeOf(value) !== 'array') {
value = [value];
}
defaultValue.value = value;
}
}
return defaultValue;
}
/**
* Create the {@link module:core/schema~DefaultValue} for an object-typed JSON schema.
* <p>
* The first possible type of the object element defined in <code>oneOf</code> will be processed and its
* {@link module:core/schema~DefaultValue} will be merged with the {@link module:core/schema~DefaultValue}
* created from the <code>properties</code> definition.
*
* @param {Object} def JSON schema definition of the object.
* @returns {@link module:core/schema~DefaultValue} The {@link module:core/schema~DefaultValue} for the
* object definition.
*/
getObjectDefaultValue(def) {
const value = {};
if (typeOf(def.properties) === 'object') {
for (const property in def.properties) {
value[property] = this.getDefaultValue(def.properties[property]);
}
}
const defaultValue = new DefaultValue(value, def.description); // only the first one of the possible types will be merged with {@link module:core/schema~DefaultValue}
// for the <code>properties</code> definition.
if (typeOf(def.oneOf) === 'array' && def.oneOf.length) {
defaultValue.merge(this.getDefaultValue(def.oneOf[0]));
defaultValue.description = def.description;
}
return defaultValue;
}
/**
* Create the {@link module:core/schema~DefaultValue} for any typed JSON schema that is not purely defined
* by its <code>$ref</code>.
* <p>
* If the definition also contains a <code>$ref</code>, the {@link module:core/schema~DefaultValue} for the
* <code>$ref</code> definition will be merged to the {@link module:core/schema~DefaultValue} of the current
* definition.
* <p>
* If <code>type</code> of the JSON schema is of primitive types, and the <code>nullable</code> is set to
* <code>false</code> in the schema definition, primitive default values will be set insided the result
* {@link module:core/schema~DefaultValue}.
*
* @param {Object} def JSON schema definition.
* @returns {@link module:core/schema~DefaultValue} The {@link module:core/schema~DefaultValue} for the
* definition.
* @throws {Error} If <code>type</code> is undefined or it is 'array', 'object', or primitive types.
*/
getTypedDefaultValue(def) {
let defaultValue;
const type = typeOf(def.type) === 'array' ? def.type[0] : def.type;
if (type === 'array') {
defaultValue = this.getArrayDefaultValue(def);
} else if (type === 'object') {
defaultValue = this.getObjectDefaultValue(def);
} else if (hasOwnProperty(PRIMITIVE_DEFAULTS, type)) {
if (hasOwnProperty(def, 'nullable') && def.nullable) {
defaultValue = new DefaultValue(null, def.description);
} else {
defaultValue = new DefaultValue(PRIMITIVE_DEFAULTS[type], def.description);
}
} else {
throw new Error(`Cannot get default value for type ${type}`);
} // referred default value always get overwritten by its parent default value
if (hasOwnProperty(def, '$ref') && def.$ref) {
const refDefaultValue = this.getReferredDefaultValue(def);
refDefaultValue.merge(defaultValue);
defaultValue = refDefaultValue;
}
return defaultValue;
}
/**
* Create the {@link module:core/schema~DefaultValue} for any JSON schema that is purely defined by its
* <code>$ref</code>.
*
* @param {Object} def JSON schema definition.
* @returns {@link module:core/schema~DefaultValue} The {@link module:core/schema~DefaultValue} for the
* definition.
*/
getReferredDefaultValue(def) {
const schema = this.loader.getSchema(def.$ref);
if (!schema) {
throw new Error(`Schema ${def.$ref} is not loaded`);
}
const defaultValue = this.getDefaultValue(schema.def);
defaultValue.merge({
description: def.description
});
return defaultValue;
}
/**
* Create the {@link module:core/schema~DefaultValue} for any JSON schema.
*
* @param {Object} def JSON schema definition.
* @returns {@link module:core/schema~DefaultValue} The {@link module:core/schema~DefaultValue} for the
* definition.
*/
getDefaultValue(def = null) {
if (!def) {
def = this.def;
}
if (hasOwnProperty(def, 'const')) {
return new DefaultValue(def.const, def.description);
}
if (hasOwnProperty(def, 'default')) {
return new DefaultValue(def.default, def.description);
}
if (hasOwnProperty(def, 'examples') && typeOf(def.examples) === 'array' && def.examples.length) {
return new DefaultValue(def.examples[0], def.description);
}
if (hasOwnProperty(def, 'type') && def.type) {
return this.getTypedDefaultValue(def);
} // $ref only schemas
if (hasOwnProperty(def, '$ref') && def.$ref) {
return this.getReferredDefaultValue(def);
}
throw new Error('The following schema definition must have at least one of the ' + '["const", "default", "examples", "type", "$ref"] fields:\n' + JSON.stringify(def, null, 2));
}
} |
JavaScript | class SchemaLoader {
constructor() {
this.schemas = {};
this.ajv = new Ajv({
nullable: true
});
}
/**
* Get JSON schema definition by its <code>$id</code>.
*
* @param {string} $id JSON schema <code>$id</code>.
* @returns {Object} JSON schema definition.
*/
getSchema($id) {
return this.schemas[$id];
}
/**
* Add a JSON schema definition to the collection.
*
* @param {Object} JSON schema definition.
* @throws {Error} If JSON schema definition does not have an <code>$id</code>.
*/
addSchema(def) {
if (!hasOwnProperty(def, '$id')) {
throw new Error('The schema definition does not have an $id field');
}
this.ajv.addSchema(def);
this.schemas[def.$id] = new Schema(this, def);
}
/**
* Remove a JSON schema definition to the collection.
*
* @param {string} $id JSON schema <code>$id</code>.
*/
removeSchema($id) {
this.ajv.removeSchema($id);
delete this.schemas[$id];
}
/**
* Create a JSON schema validation function for a given schema identified by its <code>$id</code>.
*
* @param {*} $id $id JSON schema <code>$id</code>.
* @returns {Function} JSON schema validation function.
*/
compileValidator($id) {
return this.ajv.compile(this.getSchema($id).def);
}
} |
JavaScript | class query extends Component {
constructor() {
super();
this.state = {
userquery:'',
queries:[]
};
}
onChange = (e) => {
const state = this.state
state[e.target.name] = e.target.value;
this.setState(state);
}
componentDidMount(){
fetch('http://localhost:5000/query').
then((Response)=>Response.json()).
then(data =>{
console.log("data is:",data);
this.setState({queries:data})
console.log(this.state.queries[0].query);
})
}
render() {
const {userquery } = this.state;
return (
<div class="container">
<form class= "postcss" action="http://localhost:5000/queries" method="POST">
<h3 color ="blue">Want to ask something? ask here!</h3>
<label for="inputQuery" class="sr-only">query</label>
<input type="text" class="querycss" placeholder="Want to ask something? Ask here!" name="userquery" required/>
<button class="btn btn-lg btn-primary button_position" >Ask</button>
</form>
<section>
<h2 > Recent Queries</h2>
</section>
{this.state.queries.map(function(item, key) {
return(
<div class="container">
<hr/>
<div className="list-group-item list-group-item-secondary row posting_style " >
{item.query}
</div>
</div>
)
})}
</div>
);
}
} |
JavaScript | class TimeLine extends HTMLElement {
/**
* @static
* Returns a list of observed attributes
*/
static get observedAttributes() { return [eventsAttributeName]; }
/**
* Constructor of the class. It's called when an instance of the element is created or upgraded.
* Useful for initializing state, settings up event listeners, or creating shadow dom.
* See the spec for restrictions on what you can do in the constructor.
*/
constructor() {
super();
const content = createTemplate().content;
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(content.cloneNode(true));
}
/**
* Called every time the element is inserted into the DOM.
* Useful for running setup code, such as fetching resources or rendering.
* Generally, you should try to delay work until this time.
*/
connectedCallback() {
}
/**
* Called every time the element is removed from the DOM.
* Useful for running clean up code.
*/
disconnectedCallback() {
}
/**
* Called when an observed attribute listed in the "static observedAttributes" has been added, removed, updated, or replaced
* @param {string} attrName - the name of the attribute that changed
* @param {string} oldVal - the name of the attribute that changed
* @param {string} newVal - the name of the attribute that changed
* @see observedAttributes
*/
attributeChangedCallback(attrName, oldVal, newVal) {
if (attrName === eventsAttributeName) {
let eventList;
if (typeof newVal === 'string') {
try {
eventList = JSON.parse(newVal);
} catch(e) {
// webcomponent should fail silently
}
}
if (Array.isArray(eventList)) {
this.setEvents(eventList);
}
}
}
setEvents(eventList) {
this.emptyTimelineView();
this._events = eventList;
eventList.forEach(event => {
event.date = new Date(event.date);
this.shadowRoot.querySelector('.timeline__container').appendChild(this.createBlock(event));
});
}
emptyTimelineView() {
this.shadowRoot.querySelector('.timeline__container').innerHTML = "";
}
/**
* Create the block from the content
* @param {object} data - is the data describing an event in the timeline
* @param {date} data.date - the date of the event.
* @param {string} data.title - the title of the event.
* @param {string} data.icon - the icon for the event.
* @param {string} data.bgColor - the pill's background-color for the event.
* @param {string} data.summary - the summary of the event.
* @param {string} [data.link] - the url to the detail of the event.
*/
createBlock(data) {
const content = document.importNode(createTemplate().content, true);
const block = content.querySelector('.timeline__block');
block.querySelector('.timeline__date').innerHTML = data.date.toLocaleDateString();
block.querySelector('.timeline__title').innerHTML = data.title;
block.querySelector('.timeline__description').innerHTML = data.summary;
const imgBlock = block.querySelector('.timeline__pill');
imgBlock.innerHTML = data.icon || '☻'
imgBlock.style.backgroundColor = '#c71cf5';
const btn = block.querySelector('.timeline__read-more');
if (data.link) {
btn.innerHTML = 'Read more...';
btn.setAttribute('href', data.link);
} else {
btn.parentNode.removeChild(btn);
}
return block;
}
} |
JavaScript | class Towers extends React.Component {
drawTowers() {
let currentState = this.props.currentState,
towDimTowers = this.props.towDimTowers,
towersResult = [],
towersRow = [];
/**
*break in case the in no valid 2dim array to wotk with
*/
if (!towDimTowers && !towDimTowers.length)
return;
for (let i = 0; i < towDimTowers.length; i++) {
towersRow = [];
for (let j = 0; j < towDimTowers[i].length; j++) {
let value = towDimTowers[i][j],
blockClass;
value ?
blockClass = `block ${currentState === CURENT.STATE.RAINY && value === 'x' ? 'water_block' : (value === 'x' ? 'hidden' : '')}` :
blockClass = `block non_visible`;
towersRow.push(<div className={blockClass}></div>)
}
towersResult.push(<div className="blocks_row">{towersRow}</div>)
}
return towersResult;
}
render() {
let towersResult = this.drawTowers();
return (
<div className="towers_container">
{towersResult}
</div>
);
}
} |
JavaScript | class LogAxStepCollection extends StepCollection {
constructor (steps) {
super()
this.steps = []
if (steps !== null && steps !== undefined) {
for (const step of steps) {
this.steps.push(new LogAxStep(step))
}
}
this.stepsHistory = [JSON.parse(JSON.stringify(this.steps))]
this.stepsHistoryIndex = 0
}
/**
Adds a one way step to the collection.
@param {OneWayStep} onewayStep - The oneway step.
*/
push (step) {
this.steps.push(step)
this.steps.sort((a, b) => a.number > b.number)
}
getObject () {
const stepsObject = []
for (const step of this.steps) {
stepsObject.push(step.getObject())
}
return stepsObject
}
newSet (steps) {
this.steps = []
// Delete redo history
this.stepsHistory = this.stepsHistory.slice(0, this.stepsHistoryIndex + 1)
for (const responseStep of steps) {
const newStep = new LogAxStep(responseStep)
this.steps.push(newStep)
// highlight differences
let found = false
for (const oldStep of this.stepsHistory[this.stepsHistoryIndex]) {
if (newStep.number === oldStep.number) {
if (newStep.rule !== oldStep.rule) {
newStep.highlightRule = true
}
if (newStep.term !== oldStep.term) {
newStep.highlightTerm = true
}
found = true
break
}
}
if (!found) {
newStep.highlightStep = true
newStep.highlightRule = true
newStep.highlightTerm = true
}
}
this.stepsHistory.push(JSON.parse(JSON.stringify(this.steps)))
this.stepsHistoryIndex += 1
}
setHistoryIndex (newIndex) {
this.stepsHistoryIndex = newIndex
this.steps = []
for (const responseStep of this.stepsHistory[newIndex]) {
this.steps.push(new LogAxStep(responseStep))
}
}
} |
JavaScript | class Sidebar extends React.Component {
componentWillMount() {
if (this.props.filters.resource === EnumInputType.OUTPUT) {
this.props.filterResource(this.props.filters.resource);
}
}
/**
* Resolves selected item
*
* @returns the selected item
* @memberof Sidebar
*/
getSelectedItem() {
switch (this.props.active.type) {
case EnumSelection.Resource:
return this.props.resources.find((resource) => {
return ((resource.key === this.props.active.item) && (resource.inputType === EnumInputType.CATALOG));
}) || null;
default:
return null;
}
}
/**
* Renders a single {@link ProcessInput}.
*
* @param {any} resource
* @returns a {@link ProcessInput} component instance
* @memberof Sidebar
*/
renderResource(resource) {
return (
<ProcessInput
key={resource.key}
resource={resource}
remove={this.props.removeResourceFromBag}
setActiveResource={this.props.setActiveResource}
active={this.props.active.type === EnumSelection.Resource && this.props.active.item === resource.key}
/>
);
}
render() {
const filter = filters.find((f) => f.id === this.props.filters.resource);
return (
<div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
<Row className="slipo-re-sidebar-resource-list-wrapper">
<Col className="slipo-re-sidebar-resource-list-wrapper">
<div style={{ borderBottom: '1px solid #cfd8dc', padding: '0.7rem' }}>
Resource Bag
<ButtonToolbar style={{ position: 'absolute', right: 20, top: 4 }}>
<ButtonGroup data-toggle="buttons" aria-label="First group">
{filters.map((f) => (
<Label
key={f.id}
htmlFor={f.id}
className={f.id === this.props.filters.resource ? "btn btn-outline-secondary active" : "btn btn-outline-secondary "}
check={f.id === this.props.filters.resource}
style={{ border: 'none', padding: '0.5rem 0.7rem' }}
title={f.title}
>
<Input type="radio" name="resourceFilter" id={f.id} onClick={() => this.props.filterResource(f.id)} />
<i className={f.iconClass}></i>
</Label>))
}
</ButtonGroup>
</ButtonToolbar>
</div>
<div className="text-muted slipo-pd-tip" style={{ paddingLeft: 11 }}>{filter ? filter.description : 'Displaying all resources'}</div>
<div className={
classnames({
"slipo-re-sidebar-resource-list": true,
"slipo-re-sidebar-resource-list-empty": (this.props.resources.length === 0),
})
}>
{this.props.resources.length > 0 &&
this.props.resources.filter((r) => r.inputType === EnumInputType.CATALOG).map((r) => this.renderResource(r))
}
{this.props.resources.length === 0 &&
<div className="text-muted slipo-pd-tip" style={{ paddingLeft: 1 }}>No resources selected</div>
}
</div>
</Col>
</Row>
</div >
);
}
} |
JavaScript | class App extends Component {
/**
* Create an App object.
* @constructor
*/
constructor(props) {
super(props);
this.state = {
apexSeries: []
};
this.apexOptions = {
chart: {
type: 'line',
shadow: {
enabled: false,
color: '#bbb',
top: 3,
left: 2,
blur: 3,
opacity: 1
},
},
stroke: {
width: 3,
curve: 'smooth'
},
xaxis: {
type: "datetime",
labels: {
/**
* Custom formatter for xaxis labels.
* @param { String } value The default value generated
* @param { Number } timestamp In a datetime series, this is the raw timestamp
*/
formatter: (value, timestamp) => {
return new Date(timestamp).toLocaleDateString();
}
}
},
fill: {
type: 'gradient',
gradient: {
shade: 'dark',
gradientToColors: ['#6aaaf9'],
shadeIntensity: 1,
type: 'horizontal',
opacityFrom: 1,
opacityTo: 1,
stops: [0, 100, 100, 100]
},
},
markers: {
size: 3,
opacity: 1,
colors: ["#ababab"],
strokeColor: "#fff",
strokeWidth: 1,
hover: {
size: 7,
}
},
yaxis: {
labels: {
/**
* Custom formatter for yaxis labels.
* @param { String } value The generated value of the y-axis tick
* @param { index } index of the tick / currently executing iteration in yaxis labels array
*/
formatter: (value, index) => {
return '$' + value.toFixed(2);
}
}
}
};
}
/**
* Invoked by React immediately after a component is mounted (inserted into the tree).
* @public
*/
componentDidMount() {
axios.get(`https://api.nomics.com/v1/candles?key=2018-09-demo-dont-deploy-b69315e440beb145&interval=1d¤cy=BTC&start=2018-04-14T00%3A00%3A00Z&end=2018-05-14T00%3A00%3A00Z`)
.then(res => {
const apexData = res.data.map((candle) => {
return {x: candle.timestamp, y: candle.close};
});
const apexSeries = [{
name: 'BTC Price',
data: apexData
}]
this.setState({
apexSeries: apexSeries
});
});
}
/**
* Return a reference to a React element to render into the DOM.
* @return {Object} A reference to a React element to render into the DOM.
* @public
*/
render() {
return (
<div className="app">
<div className="row">
<div className="mixed-chart">
<ReactApexChart
options={this.apexOptions}
series={this.state.apexSeries}
width="500"
/>
</div>
</div>
</div>
);
}
} |
JavaScript | class FilterScaffold {
constructor(queryCase = SNAKE_CASE, fieldCase = CAMEL_CASE) {
this.queryCase = queryCase;
this.fieldCase = fieldCase;
this.schema = {};
}
addFilterSchema(name, type = FILTER_TYPE_STRING, options = {}) {
let mappingKey = type;
if (Object.keys(filterTypes).includes(type) === false) {
mappingKey = FILTER_TYPE_STRING;
}
const {
format = null,
description = null,
defaultValue = null,
enumerate = null
} = options;
mappingKey = format || mappingKey;
let { operators = null } = options;
if (!operators) {
operators = operatorMapping[mappingKey];
}
const schema = {
type,
description,
operators,
defaultValue,
enumerate
};
this.schema[name] = schema;
return this;
}
getFilterSchema() {
return this.schema;
}
setFilterSchema(schema) {
//TODO: add check
this.schema = schema;
return this;
}
getFieldAndOperator(key) {
const keyArray = key.split('_');
let operator = keyArray.pop();
let field = key;
if (Object.values(supportOperators).includes(operator) === true) {
field = keyArray.join('_');
} else {
operator = null;
}
if (this.fieldCase === CAMEL_CASE) {
field = camelCase(field);
} else {
field = snakeCase(field);
}
return [field, operator];
}
getConditions(query) {
const conditions = {};
const { schema } = this;
const schemaKeys = Object.keys(schema);
for (const [key, value] of Object.entries(query)) {
if (value === null) {
continue;
}
const [field, operator] = this.getFieldAndOperator(key);
if (schemaKeys.includes(field) === false) {
continue;
}
const schemaAllowOperators = schema[field].operators;
if (operator && !schemaAllowOperators.includes(operator)) {
continue;
}
if ({}.hasOwnProperty.call(conditions, field) === false) {
if (!operator) {
conditions[field] = value;
} else {
conditions[field] = { [operator]: value };
}
continue;
}
if (operator && typeof conditions[field] === 'object') {
conditions[field][operator] = value;
continue;
}
throw new InvalidArgumentException('Condition conflict');
}
return conditions;
}
getConditionsByString(queryString, baseWhere = {}) {
return merge(baseWhere, JSON.parse(queryString));
}
} |
JavaScript | class TwigLoader {
constructor() {
/**
* All base-paths
* @type {Array}
*/
this.path_base = [];
/**
* all namespaced paths with `path: namespace`
* @type {{}}
*/
this.path_ns = {};
}
/**
* @param path
* @param namespace
*/
addPath(path, namespace = false) {
if(false === namespace) {
this.path_base.push(path);
return;
}
if('undefined' === typeof this.path_ns[namespace]) {
this.path_ns[namespace] = [];
}
this.path_ns[namespace].push(path);
}
/**
*
* @param {Twig} twig
* @param {Twig.Templates} templates
* @param {string} location
* @param {{}} params
* @param {Function} callback
* @param {Function} error_callback
*/
load(twig, templates, location, params, callback, error_callback) {
if(!fs || !path) {
throw new twig.Error('Unsupported platform: Unable to load from file ' +
'because there is no "fs" or "path" implementation');
}
params.path = params.path || location;
const loadNs = (path_pure, fileLoader) => {
let path_ns = [...this.path_base];
const loadNsOne = (path_n) => {
return fileLoader(path_n + '/' + path_pure);
};
loadNsOne(path_ns.shift()).then((success) => {
if(false === success) {
loadNsOne(path_ns.shift());
}
});
};
const loadBase = (path_pure, fileLoader) => {
let path_base = [...this.path_base];
const loadBaseOne = (path_b) => {
return fileLoader(path_b + '/' + path_pure);
};
return loadBaseOne(path_base.shift()).then((success) => {
if(false === success) {
return loadBaseOne(path_base.shift());
}
return Promise.resolve();
});
};
let {ns, path_pure} = TwigLoader.parsePath(params.path);
if(params.async) {
const loadFile = (path) => {
return new Promise((resolve) => {
fs.stat(path, function(err, stats) {
if(err || !stats.isFile()) {
if(typeof error_callback === 'function') {
error_callback(new twig.Error('Unable to find template file ' + path));
}
resolve(false);
}
fs.readFile(path, 'utf8', TwigLoader.parseLoaded(params, templates, callback, error_callback));
resolve(true);
});
});
};
if(false === ns) {
loadBase(path_pure, loadFile);
} else {
if(this.path_ns[ns]) {
loadNs(path_pure, loadFile);
} else {
console.error('!# FormantaBlocks.TwigLoader: namespace `' + ns + '` not found in registered views');
}
}
// TODO: return deferred promise
return true;
}
let pathBase;
if(false === ns) {
let path_base = [...this.path_base];
pathBase = path_base.shift() + '/' + path_pure;
try {
if(!fs.statSync(pathBase).isFile()) {
pathBase = path_base.shift() + '/' + path_pure;
}
} catch(error) {
//throw new twig.Error('Unable to find template file ' + params.path + '. ' + error);
}
try {
if(!fs.statSync(pathBase).isFile()) {
throw new twig.Error('Unable to find template file ' + params.path);
}
} catch(error) {
//throw new twig.Error('Unable to find template file ' + params.path + '. ' + error);
}
} else {
// todo: support ns on sync
}
return TwigLoader.parseLoaded(params, templates, callback, error_callback)(undefined, fs.readFileSync(pathBase, 'utf8'));
}
/**
* Parsing relative path to template into namespace and pure-path
*
* @todo implement absolute path
* @param {string} path
* @returns {{ns: boolean, path_pure: *}}
*/
static parsePath(path) {
let ns = false;
let path_pure = path;
let colon_pos = path.indexOf('::');
if(-1 !== colon_pos) {
if(colon_pos < path.indexOf('/')) {
ns = path.substr(0, colon_pos);
path_pure = path.replace(ns + '::', '');
}
} else if(0 === path.indexOf('@')) {
let path_pos = path.indexOf('/');
if(-1 !== path_pos) {
ns = path.substr(1, (path_pos - 1));
path_pure = path.replace('@' + ns + '/', '');
}
}
return {
ns,
path_pure
};
}
/**
*
* @param {{}} params
* @param {Twig.Templates} templates
* @param {Function} callback
* @param {Function} error_callback
* @returns {Function}
*/
static parseLoaded(params, templates, callback, error_callback) {
let precompiled = params.precompiled;
let parser = templates.parsers[params.parser] || templates.parser.twig;
return function(err, data) {
if(err) {
if(typeof error_callback === 'function') {
error_callback(err);
}
return;
}
if(precompiled === true) {
data = JSON.parse(data);
}
params.data = data;
//params.path = params.path;
// template is in data
let template = parser.call(templates, params);
if(typeof callback === 'function') {
callback(template);
}
return template
};
}
/**
*
* @returns {Function}
*/
registerLoader() {
const loader = this;
return (twig) => {
if(!twig) {
console.error('TwigLoader: twig to attach not set');
return;
}
twig.Templates.registerLoader('fs', function(location, params, callback, error_callback) {
return loader.load(twig, this, location, params, callback, error_callback);
});
};
}
} |
JavaScript | class Paddle extends Sprite {
constructor(/* Bitmap */ image, /* int */ x, /* int */ y, /* int */ width, /* int */ height, /* Game */ game) {
super(image, x, y, width, height, game);
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.game = game;
this.velocityX = 0;
this.velocityY = 0;
// Note: image may be null if this sprite is drawn programmatically
this.image = image;
}
/**
* @description Draws the current object to the game screen.
*/
/* public void */ draw(/* Canvas */ canvas) {
let paint = new Paint();
paint.setColor( Color.GRAY );
paint.setStyle( Paint.Style.FILL );
canvas.drawRect(new Rect(this.x, this.y, this.x + this.width, this.y + this.height), paint);
}
/**
* @description Performs state updates to the current instance for the current game loop cycle.
*/
/* public void */ update() {
// This sprite moves based on user's direct input, not the animation loop
}
/** Returns the width of this sprite in the game. */
/* public int */ getWidth() {
return this.width;
}
/** Returns the height of this sprite in the game. */
/* public int */ getHeight() {
return this.height;
}
/** Returns this sprite's `x` {number} property. */
/* public int */ getX() {
return this.x;
}
/**
* Sets this sprite's `x` property.
* @param {number} newX - The new value for this sprite's x.
*/
/* public void */ setX(/* int */ newX) {
this.x = newX;
}
/** Returns this sprite's `y` {number} property. */
/* public int */ getY() {
return this.y;
}
/**
* Sets this sprite's `y` property.
* @param {number} newY - The new value for this sprite's y.
*/
/* public void */ setY(/* int */ newY) {
this.y = newY;
}
} |
JavaScript | class PitchShift extends FeedbackEffect {
constructor() {
super(optionsFromArguments(PitchShift.getDefaults(), arguments, ["pitch"]));
this.name = "PitchShift";
const options = optionsFromArguments(PitchShift.getDefaults(), arguments, ["pitch"]);
this._frequency = new Signal({ context: this.context });
this._delayA = new Delay({
maxDelay: 1,
context: this.context
});
this._lfoA = new LFO({
context: this.context,
min: 0,
max: 0.1,
type: "sawtooth"
}).connect(this._delayA.delayTime);
this._delayB = new Delay({
maxDelay: 1,
context: this.context
});
this._lfoB = new LFO({
context: this.context,
min: 0,
max: 0.1,
type: "sawtooth",
phase: 180
}).connect(this._delayB.delayTime);
this._crossFade = new CrossFade({ context: this.context });
this._crossFadeLFO = new LFO({
context: this.context,
min: 0,
max: 1,
type: "triangle",
phase: 90
}).connect(this._crossFade.fade);
this._feedbackDelay = new Delay({
delayTime: options.delayTime,
context: this.context,
});
this.delayTime = this._feedbackDelay.delayTime;
readOnly(this, "delayTime");
this._pitch = options.pitch;
this._windowSize = options.windowSize;
// connect the two delay lines up
this._delayA.connect(this._crossFade.a);
this._delayB.connect(this._crossFade.b);
// connect the frequency
this._frequency.fan(this._lfoA.frequency, this._lfoB.frequency, this._crossFadeLFO.frequency);
// route the input
this.effectSend.fan(this._delayA, this._delayB);
this._crossFade.chain(this._feedbackDelay, this.effectReturn);
// start the LFOs at the same time
const now = this.now();
this._lfoA.start(now);
this._lfoB.start(now);
this._crossFadeLFO.start(now);
// set the initial value
this.windowSize = this._windowSize;
}
static getDefaults() {
return Object.assign(FeedbackEffect.getDefaults(), {
pitch: 0,
windowSize: 0.1,
delayTime: 0,
feedback: 0
});
}
/**
* Repitch the incoming signal by some interval (measured in semi-tones).
* @example
* const pitchShift = new Tone.PitchShift().toDestination();
* const osc = new Tone.Oscillator().connect(pitchShift).start().toDestination();
* pitchShift.pitch = -12; // down one octave
* pitchShift.pitch = 7; // up a fifth
*/
get pitch() {
return this._pitch;
}
set pitch(interval) {
this._pitch = interval;
let factor = 0;
if (interval < 0) {
this._lfoA.min = 0;
this._lfoA.max = this._windowSize;
this._lfoB.min = 0;
this._lfoB.max = this._windowSize;
factor = intervalToFrequencyRatio(interval - 1) + 1;
}
else {
this._lfoA.min = this._windowSize;
this._lfoA.max = 0;
this._lfoB.min = this._windowSize;
this._lfoB.max = 0;
factor = intervalToFrequencyRatio(interval) - 1;
}
this._frequency.value = factor * (1.2 / this._windowSize);
}
/**
* The window size corresponds roughly to the sample length in a looping sampler.
* Smaller values are desirable for a less noticeable delay time of the pitch shifted
* signal, but larger values will result in smoother pitch shifting for larger intervals.
* A nominal range of 0.03 to 0.1 is recommended.
*/
get windowSize() {
return this._windowSize;
}
set windowSize(size) {
this._windowSize = this.toSeconds(size);
this.pitch = this._pitch;
}
dispose() {
super.dispose();
this._frequency.dispose();
this._delayA.dispose();
this._delayB.dispose();
this._lfoA.dispose();
this._lfoB.dispose();
this._crossFade.dispose();
this._crossFadeLFO.dispose();
this._feedbackDelay.dispose();
return this;
}
} |
JavaScript | class Book {
constructor(name, file) {
this.name = name;
this.file = file;
}
} |
JavaScript | class Encrypt extends Transform {
constructor(password, options) {
super(options);
this.password = password;
this.cipher = null;
this.hmac = null;
this.contentLength = 0;
// Delay initialization.
}
// Create a small helper static method if you just want to encrypt a whole
// Buffer all at once.
// Note: There is a bit of duplication with the Decrypt version of this method.
static buffer(password, buffer) {
return new Promise((resolve, reject) => {
toStream(buffer)
.pipe(new Encrypt(password))
.pipe(withStream(contents => {
resolve(contents);
}))
.on('error', reject);
});
}
_transform(chunk, _, callback) {
// Okay, we have data. Let's initialize.
this._init();
// This is unnecessary, but makes tslint keep quiet.
if (this.cipher == null) {
return;
}
if (this.hmac == null) {
return;
}
// Track the file contents size.
this.contentLength += chunk.length;
// Encrypt this chunk and push it.
const encChunk = this.cipher.update(chunk);
this.push(encChunk);
// And add the encrypted cipher block to the signature.
this.hmac.update(encChunk);
callback();
}
_flush(callback) {
// Make sure we have initialized (even if it is an empty file).
this._init();
// This is unnecessary, but makes tslint keep quiet.
if (this.cipher == null) {
return;
}
if (this.hmac == null) {
return;
}
// Store the size of the last block and determin the padding.
const lenMod16 = this.contentLength % 16;
const padding = 16 - lenMod16;
// Encrypt and sign the padding.
const encChunk = this.cipher.update(Buffer.alloc(padding, padding));
this.push(encChunk);
this.hmac.update(encChunk);
// Push down the final encryption, size of the last content block and the signature.
this.push(this.cipher.final()); // This one should be unnecessary, as we are disabling the padding, but just in case.
this.push(Buffer.from([lenMod16]));
this.push(this.hmac.digest());
callback();
}
_init() {
if (this.cipher == null) {
this._pushFileHeader();
this._pushExtensions();
const credentials = this._getCredentials(this.password);
this._pushCredentials(credentials);
this.cipher = this._getCipher(credentials.encKey, credentials.encIV);
this.hmac = getHMAC(credentials.encKey);
delete this.password; // Don't need this anymore.
return true;
}
return false;
}
_pushFileHeader() {
const buff = Buffer.alloc(3 + 1 + 1);
buff.write('AES', 0);
buff.writeUInt8(AESCRYPT_FILE_FORMAT_VERSION, 3);
this.push(buff);
}
_pushExtensions() {
const extensions = {
CREATED_BY: NAME + ' ' + VERSION,
};
// Calculate the final length of the extensions.
const capacity = Object.keys(extensions).reduce((acc, k) => acc + 2 + k.length + 1 + extensions[k].length, 0) + // Extensions
(2 + 128) + // extension container
2; // end extensions
// Allocate a single buffer for all the extensions.
const buff = Buffer.alloc(capacity);
let len = 0;
Object.keys(extensions).forEach(k => {
len = buff.writeUInt16BE(k.length + 1 + extensions[k].length, len);
len += buff.write(k, len);
len += 1; // Delimiter
len += buff.write(extensions[k], len);
});
len = buff.writeUInt16BE(128, len);
// We don't need to actually "create" the extension container, as it is just
// 0x00s, and that is the default fill from Buffer.alloc().
this.push(buff);
}
_getCredentials(password) {
const credIV = randomBytes(16);
return {
credIV,
credKey: getKey(credIV, password),
encIV: randomBytes(16),
encKey: randomBytes(32),
};
}
_pushCredentials(credentials) {
const { credIV, credKey, encIV, encKey } = credentials;
// Encrypt our credentials.
const credCipher = this._getCipher(credKey, credIV);
const credBlock = Buffer.concat([
credCipher.update(encIV),
credCipher.update(encKey),
credCipher.final(),
]);
// Sign them.
const credHMAC = getHMAC(credKey)
.update(credBlock)
.digest();
// Than push them downstream.
this.push(credIV);
this.push(credBlock);
this.push(credHMAC);
}
_getCipher(key, iv) {
const encCipher = createCipheriv('aes-256-cbc', key, iv);
encCipher.setAutoPadding(false);
return encCipher;
}
} |
JavaScript | class LoadScene extends Phaser.Scene{
constructor(){
super({
key: CST.SCENES.LOAD
})
}
init()
{
}
preload() //Make assets preload
{
this.load.image("logo", "./assets/image/logo.png"); //preload logo, buttons,backgrounds
this.load.image("p1_button", "./assets/image/p1_button.png");
this.load.image("p2_button", "./assets/image/p2_button.png");
this.load.image("title_bg", "./assets/image/title_bg2.png");
this.load.image("playsceneBG", "./assets/image/playsceneBG.png")
this.load.image("A_button", "./assets/image/A_button.png");//preload option buttons
this.load.image("B_button", "./assets/image/B_button.png");
this.load.image("YES_button", "./assets/image/YES_button.png");
this.load.image("NO_button", "./assets/image/NO_button.png");
this.load.image("A_button_S", "./assets/image/A_button_S.png");
this.load.image("B_button_S", "./assets/image/B_button_S.png");
this.load.image("YES_button_S", "./assets/image/YES_button_S.png");
this.load.image("NO_button_S", "./assets/image/NO_button_S.png");
this.load.image("p1_button_S", "./assets/image/p1_button_S.png");
this.load.image("p2_button_S", "./assets/image/p2_button_S.png");
this.load.image("NextButton", "./assets/image/NextButton.png");
this.load.image("NextButton_S", "./assets/image/NextButton_S.png");
this.load.image("Q1", "./assets/image/questions/Q1.png"); //preload questions
this.load.image("Q2", "./assets/image/questions/Q2.png");
this.load.image("Q3", "./assets/image/questions/Q3.png");
this.load.image("Q4", "./assets/image/questions/Q4.png");
this.load.image("Q5", "./assets/image/questions/Q5.png");
this.load.image("Q6", "./assets/image/questions/Q6.png");
this.load.image("Q7", "./assets/image/questions/Q7.png");
this.load.image("Q8", "./assets/image/questions/Q8.png");
this.load.image("Q9", "./assets/image/questions/Q9.png");
this.load.image("Q10", "./assets/image/questions/Q10.png");
({
frameWidth: 32,
frameHeight: 32
});
this.load.audio("title_music", "./assets/audio/game_audio.mp3"); //preload audio
let loadingBar = this.add.graphics //Add loading bar
({
fillStyle: //Color loading bar
{
color: 0xADFF2F
}
})
this.load.on("progress", (percent)=>{ //Make it load depending on percent
loadingBar.fillRect(0, this.game.renderer.height / 2, this.game.renderer.width * percent, 50);
})
var width = this.cameras.main.width; //make width and height variables
var height = this.cameras.main.height;
var loadingText = this.make.text({ //Add loading text
x: width / 2, //Position text
y: height / 2 - 50,
text: '✈ Loading...',
style: { //Pick font and color for text
font: '20px monospace',
fill: '#ADFF2F'
}
});
loadingText.setOrigin(0.5, 0.5); //Furthermore position text
}
create()
{
this.scene.start(CST.SCENES.MENU); //Start menu scene after loading finishes
}
} |
JavaScript | class MemberSearchResponse extends Response {
/**
* @constructor
* @param {Object} obj The object passed to constructor
*/
constructor(obj) {
super(obj);
if (obj === undefined || obj === null) return;
this.tierType = this.constructor.getValue(obj.tierType || obj.tier_type);
this.baseMiles = this.constructor.getValue(obj.baseMiles || obj.base_miles);
this.promoMiles = this.constructor.getValue(obj.promoMiles || obj.promo_miles);
}
/**
* Function containing information about the fields of this model
* @return {array} Array of objects containing information about the fields
*/
static mappingInfo() {
return super.mappingInfo().concat([
{ name: 'tierType', realName: 'tier_type' },
{ name: 'baseMiles', realName: 'base_miles' },
{ name: 'promoMiles', realName: 'promo_miles' },
]);
}
/**
* Function containing information about discriminator values
* mapped with their corresponding model class names
*
* @return {object} Object containing Key-Value pairs mapping discriminator
* values with their corresponding model classes
*/
static discriminatorMap() {
return {
};
}
} |
JavaScript | class CommandExecutor {
constructor() {
this.didStack = [];
this.undidStack = [];
}
/**
*
* Execute a command and place it on the undo stack. Also clears the redo stack()
*
* @param {object} command An object with two parameterless functions, do() and undo()
*/
do(command, self) {
if(typeof command.do != 'function' || typeof command.undo != 'function')
throw "Command objects must implement both a do() and undo() function."
this.undidStack = [];
this.didStack.push(command);
command.do(self);
}
/**
* Pop the last item on the undo stack, call its undo function, and push it on the redo stack.
* Throws an error if there is no undo stack.
* If the last object was the includeWithPrevious flag set, it will undo the previous command
* until the undo stack is empty or a command is found without the includeWithPrevious or a command
* with that flag set to false.
*/
undo(self) {
let toUndo = {};
do {
if (this.didStack.length == 0) return;
toUndo = this.didStack.splice(this.didStack.length - 1, 1)[0];
toUndo.undo(self);
this.undidStack.push(toUndo);
} while (toUndo.includeWithPrevious == true);
}
/**
* Pop the last item off the redo stack, call its do() functions, and push it on the undo stack.
* Throws an error if there is no redo stack.
* If the following object(s) have the includeWithPrevious flag set, it will redo the following commands
* until the redo stack is empty or a command is found with the includeWithPrevious flag or a command
* with that flag set to false.
*/
redo(self) {
let toRedo = {};
if (this.undidStack.length == 0) return;
toRedo = this.undidStack.splice(this.undidStack.length - 1, 1)[0];
toRedo.do(self);
this.didStack.push(toRedo);
//Now check to see if the following ones can also be redone
while (this.undidStack.length != 0 && this.undidStack[this.undidStack.length - 1].includeWithPrevious) {
toRedo = this.undidStack.splice(this.undidStack.length - 1, 1)[0];
toRedo.do(self);
this.didStack.push(toRedo);
}
}
/**
* Check to see if the undo stack has at least one object.
*/
canUndo() {
return this.didStack.length != 0;
}
/**
* Check to see if the redo stack has at least one object.
*/
canRedo() {
return this.undidStack.length != 0;
}
} |
JavaScript | class AbstractSQLGenerator extends AbstractGenerator {
constructor(options = {}) {
super(options);
this.data = []; // Will contain default data to insert into the database if any
this.filesContent = {}; // Will contain the final content for all output files (key = fileName, value = content)
// Will contain pre-final generated strings (whose concatenation gives the final output)
this.schemas = {
'create': {},
'drop': {}
};
this.inserts = {};
}
addEntity(entity) {
super.addEntity(entity);
if (this.options['insert-into']) {
this.inserts[entity.plural.toLowerCase()] = [];
}
}
buildOutputFilesContent() {
var allowedOptions = ['create', 'drop', 'insert-into', 'data'];
var fileName;
var self = this;
this.filesContent['execute.sh'] = this.getExecuteScriptContent();
if (this.options.data) {
if (this.entities.length === 1) {
fileName = 'insert-into-table-' + this.entities[0].plural.toLowerCase() + '-default-data.sql';
}
else {
this.sortData();
fileName = 'insert-into-database-default-data.sql';
}
this.filesContent[fileName] = this.data.map(function(item) {
return item.toSQLStatement(self);
}).join('\n\n') + '\n';
}
else {
if (this.options.create) {
var content = '';
if (this.entities.length === 1) {
var key = this.entities[0].plural.toLowerCase();
fileName = 'create-table-' + key + '.sql';
content = this.schemas.create[key] + '\n';
}
else {
var keys = Object.keys(this.schemas.create);
var l = keys.length;
fileName = 'create-database.sql';
for (let i = 0; i < l; i++) {
content += this.schemas.create[keys[i]];
if (i < (l - 1))
content += '\n\n';
else
content += '\n';
}
}
this.filesContent[fileName] = content;
}
if (this.options.drop) {
var content = '';
if (this.entities.length === 1) {
var key = this.entities[0].plural.toLowerCase();
fileName = 'drop-table-' + key + '.sql';
content = this.schemas.drop[key] + '\n';
}
else {
var keys = Object.keys(this.schemas.drop);
var l = keys.length;
fileName = 'drop-database.sql';
for (let i = 0; i < l; i++) {
content += this.schemas.drop[keys[i]];
if (i < (l - 1))
content += '\n\n';
else
content += '\n';
}
}
this.filesContent[fileName] = content;
}
if (this.options['insert-into']) {
var content = '';
if (this.entities.length === 1) {
var key = this.entities[0].plural.toLowerCase();
fileName = 'insert-into-table-' + key + '.sql';
content = this.inserts[key].join('\n\n') + '\n';
}
else {
var l = this.entities.length;
fileName = 'insert-into-database.sql';
for (let i = 0; i < this.entities.length; i++) {
content += this.inserts[this.entities[i].plural.toLowerCase()].join('\n\n');
if (i < (l - 1))
content += '\n\n';
else
content += '\n';
}
}
this.filesContent[fileName] = content;
}
}
}
/*
* Must be overrided by sub-classes.
*/
connectDatabase(name) {
return null;
}
createColumn(attr) {
if (attr.primaryKey)
return this.createColumnPrimaryKey(attr.name);
var str = this.escapeColumnName(attr.name) + ' ' + this.toSQLType(attr);
if (!attr.nullable)
str += ' NOT NULL';
if (attr.defaultValue !== undefined)
str += ' DEFAULT ' + this.toSQLValue(attr, true);
else if (attr.nullable)
str += ' DEFAULT NULL';
if (attr.unique)
str += ' UNIQUE';
return str;
}
createColumnForeignKey(ref) {
var str = '';
str += this.escapeColumnName(ref.alias) + ' ' + this.toSQLType({ type: 'Integer' });
if (!ref.nullable)
str += ' NOT NULL';
if (ref.defaultValue !== undefined)
str += ' DEFAULT ' + this.toSQLValue({
defaultValue: ref.defaultValue,
type: 'Integer'
}, true);
else if (ref.nullable)
str += ' DEFAULT NULL';
return str;
}
/*
* Must be overrided by sub-classes.
*/
createColumnPrimaryKey(name) {
return null;
}
/*
* Must be overrided by sub-classes.
*/
createDatabase(name) {
return null;
}
createForeignKey(name, tableName, columnName) {
return 'FOREIGN KEY (' + this.escapeColumnName(name) + ') REFERENCES ' + tableName + ' (' + columnName + ')';
}
createTable(name) {
return 'CREATE TABLE ' + name;
}
/*
* Must be overrided by sub-classes.
*/
dropDatabase(name) {
return null;
}
dropTable(name) {
return 'DROP TABLE IF EXISTS ' + name + ';';
}
/**
* Used in rare cases, for example when `name === 'user'` which is not allowed in PostgreSQL unless quoted (e.g. "user"). It's the responsibility of this method to do so.
*/
escapeColumnName(name) {
return name;
}
/*
* Should generate code based on the 'entities' array.
*/
generate() {
if (!(this.options.create || this.options.drop || this.options['insert-into'] || this.options.data))
throw 'You must specify an operation as CLI argument, e.g. --create / --data / --drop / --insert-into <count>';
if (this.options.data) {
if (this.options.create || this.options.drop || this.options['insert-into'])
console.log('Warning: You can not use arguments --create, --drop and --insert-into when using the --data arg. Using one of them along with --data has no effect.\n');
this.generateData();
}
else {
if (this.options.create)
this.generateCreate();
if (this.options.drop)
this.generateDrop();
if (this.options['insert-into']) {
var n = 10;
if (typeof this.options['insert-into'] === 'number')
n = this.options['insert-into'];
this.generateInserts(n);
}
}
this.buildOutputFilesContent();
}
generateAttributes(e) {
var self = this;
var str = '';
this.indentation++;
e.attributes.forEach(function(attr, i) {
str += self.indent() + self.createColumn(attr);
if (i != (e.attributes.length - 1))
str += ',\n';
});
if ((e.attributes.length > 0) && (e.references.length > 0))
str += ',\n';
e.references.forEach(function(ref, i) {
str += self.indent() + self.createColumnForeignKey(ref);
if (i < (e.references.length - 1))
str += ',\n';
});
this.indentation--;
return str;
}
generateCreate() {
this.sortEntities();
var self = this;
this.entities.forEach(function(e, i) {
var str = '';
str += self.createTable(e.plural) + ' (\n';
str += self.generateAttributes(e);
if (e.references.length > 0) {
str += ',\n';
str += '\n';
str += self.generateForeignKeys(e);
}
str += '\n';
str += ');';
self.schemas['create'][e.plural.toLowerCase()] = str;
});
}
generateData() {
// Does nothing, output file's content is generated in buildOutputFileContent()
}
generateDrop() {
this.sortEntities();
this.entities.reverse();
var self = this;
this.entities.forEach(function(e, i) {
var str = '';
str += self.dropTable(e.plural);
self.schemas['drop'][e.plural.toLowerCase()] = str;
});
}
generateForeignKeys(entity) {
var e = entity;
var self = this;
var str = '';
this.indentation++;
e.references.forEach(function(ref, i) {
str += self.indent() + self.createForeignKey(ref.alias, ref.entity.plural, ref.attribute);
if (i < (e.references.length - 1)) {
str += ',\n';
}
});
this.indentation--;
return str;
}
generateInserts(n) {
this.sortEntities();
var self = this;
this.entities.forEach(function(e, i) {
for (var i = 0; i < n; i++) {
var values = {};
e.attributes.forEach(function(attr) {
if (attr.primaryKey)
return;
if (attr.defaultValueIsFunction)
values[attr.name] = self.toSQLValue(attr);
else {
values[attr.name] = self.toSQLValue({
defaultValue: Random.value(attr),
type: attr.type
});
}
});
e.references.forEach(function(ref) {
var otherRefs = [];
if (values[ref.alias] === undefined) // If no foreign key id set for this reference yet
values[ref.alias] = Random.integer(1, n); // Choose a random foreign key id from the number of insert statements generated
e.references.forEach(function(ref2) {
if (ref2 == ref)
return;
otherRefs = otherRefs.concat(
ref2.entity.references.filter(function(ref3) {
return (ref3.entity === ref.entity)
&& (ref3.attribute === ref.attribute);
})
);
});
// If another reference from this entity points to an entity having a reference to the same Entity-Attribute pair as the current reference
if (otherRefs.length > 0) {
// Ensure that the value for this foreign key is the same as the other entity's foreign key's value as they should both point to the same table record (for data integrity)
otherRefs.forEach(function(ref3) {
var referencedEntityName = ref3.source.plural.toLowerCase();
var referencedEntityInserts = self.inserts[referencedEntityName];
if (referencedEntityInserts === undefined)
return; // No inserts for this entity
var ref2 = e.references.filter(function(r) {
return (r.source === ref.source) && (r.entity === ref3.source);
})[0];
// Look for an insert statement which has a foreign key to the same table & field and which value is the same as the randomly generated current foreign key id
var inserts = referencedEntityInserts.filter(function(val, i) {
return (val.values[ref3.alias] === values[ref.alias]);
});
if (inserts.length === 0) // No inserts on the second table with the same value for the same foreign key
values[ref2.alias] = null;
else {
// Choose randomly between the matching inserts
values[ref2.alias] = referencedEntityInserts.indexOf(
inserts[Random.integer(1, inserts.length) - 1]
) + 1;
}
});
}
});
self.inserts[e.plural.toLowerCase()].push(self.insertInto(e, values));
}
});
}
getAllowedOptions() {
return {
'create': 'For each entity, will generate the SQL query to create the related database table.',
'data': 'If used, Jane will look for a "data/" sub-directory for default data to generate INSERT INTO statements for.',
'drop': 'For each entity, will generate the SQL query to drop the related database table.',
'insert-into <rows-count>': 'For each entity, will generate <rows-count> SQL queries to insert randomly generated data in the related database table.'
};
}
getAutoIncrementString() {
return '';
}
getContent(fileName) {
return this.filesContent[fileName];
}
/*
* Should return the content of the 'execute.sh' file placed in every output directory after generation to execute generated SQL files.
*
* Must be overrided by sub-classes.
*/
getExecuteScriptContent() {
return null;
}
getOutputFilesNames() {
var names = [];
if (this.options.data) {
if (this.entities.length === 1)
names.push('insert-into-table-' + this.entities[0].plural.toLowerCase() + '-default-data.sql');
else
names.push('insert-into-database-default-data.sql');
}
else {
for (var opt of [ 'create', 'drop', 'insert-into' ]) {
if (!this.options[opt])
continue;
if (this.entities.length === 1)
names.push(opt + '-table-' + this.entities[0].plural.toLowerCase() + '.sql');
else {
names.push(opt + '-database.sql');
}
}
}
names.push('execute.sh');
return names;
}
/*
* Returns `this.indentation * 2` whitespaces (e.g. 2, 4...).
*/
indent() {
var str = '';
for (var i = 0; i < this.indentation * 2; i++)
str += ' ';
return str;
}
insertInto(entity, values) {
return new InsertIntoStatement(this, entity, values);
}
setOptions(val) {
this.filesContent = {};
this.options = val;
for (let e of this.entities) {
this.inserts[e.plural.toLowerCase()] = [];
}
}
sortData() {
this.data.sort(function(a, b) {
return a.entity.references.length - b.entity.references.length;
});
}
sortEntities() {
this.entities.sort(function(a, b) {
return a.references.length - b.references.length;
});
}
/**
* Returns the SQL type corresponding to the given Jane attribute's type (e.g. VARCHAR(<...>) for String etc.) with desired length if appropriated (e.g. VARCHAR(255) etc.)
*
* Should be overrided by sub-classes only if needed.
*/
toSQLType(attr) {
var res = null;
switch (attr.type) {
case 'Decimal': {
res = 'DECIMAL(' + attr.precision + ',' + attr.scale + ')';
}
break;
default: { // sql type == js type
res = new String(attr.type).toUpperCase();
}
break;
}
return res;
}
/**
* Returns the SQL value corresponding to the given JS value (e.g. for 'false' should return 0 for SQLite, and FALSE for MySQL etc.)
*
* Should be overrided by sub-classes only if needed.
*/
toSQLValue(attr, createStatement = false) {
var res = null;
if (attr.defaultValueIsFunction && (this.name !== 'sqlite')) {
switch (attr.defaultValue) {
case 'DATE()': {
res = 'CURRENT_DATE'; // sql value == js value
}
break;
case 'DATETIME()': {
res = 'CURRENT_TIMESTAMP'; // sql value == js value
}
break;
case 'TIME()': {
res = 'CURRENT_TIME'; // sql value == js value
}
break;
default: {
console.log('Unknown function ' + attr.defaultValue);
}
}
}
else if (this.name === 'sqlite') {
if (createStatement)
res = '(' + attr.defaultValue + ')';
else
res = attr.defaultValue;
}
return res;
}
} |
JavaScript | class ChangeNameForm extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
this.props.txMethod(this.state.name);
event.preventDefault();
}
handleChange(event) {
this.setState({name: event.target.value});
}
render() {
const {
text,
name
} = this.props;
return(
<div>
<p>{text + name}</p>
<form onSubmit={this.handleSubmit}>
<label>
<input type="text" value={this.state.name} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
</div>
)
}
} |
JavaScript | class Mesh {
m_object; m_indices;
m_model_M;
m_texture;
m_gl_pipeline; m_gl_context;
m_vertexBuffer; m_indexBuffer; m_colorBuffer; m_normalBuffer; // GL buffers that will be used.
m_vertexLocation; m_colorLocation; m_normalLocation; // Attributes locations.
m_modelMatrixLocation;
/**
*
* @param {[float]} vertices : Array of float that determines the mesh vertices position.
* @param {[Int]} indices : Array of the indices. Index is used to specify the location of the next vertex to render in the vertiices array.
* @param {GL Program} gl_pipeline : gl pipeline, or what so called gl program. This program holds the pipeline that will be used during this object rednering.
* @param {[float]} colors : array off colours that correspond to the vertices. It should have the same size as the vertices.
* @param {[Vectors]} normals : Array of Normals that corresponds to the vertix.
* @param {[2D Vectoro]} texcords : Array of 2d vectors that specify the coordinate of the textures corresponding to a vertex.
* @param {GL Texture} texture : A texture loaded earlier by Web GL.
* @param {4x4 Matrix} model_M : Matrix that determines the mesh transformation in the world space.
*/
constructor(vertices, indices, gl_pipeline, gl_context, colors = null, normals = null, texcords = null, texture = null, model_M = mat4.create()){
this.m_model_M = model_M;
this.m_object = new Object_3D(vertices, colors, normals, texcords);
this.m_indices = indices;
this.m_gl_context = gl_context;
this.m_gl_pipeline = gl_pipeline;
/** Buffer creations */
this.m_vertexBuffer = gl_context.createBuffer();
this.m_colorBuffer = gl_context.createBuffer();
this.m_normalBuffer = gl_context.createBuffer();
this.m_indexBuffer = gl_context.createBuffer();
/** Filling the buffers with data */
gl_context.bindBuffer(gl_context.ARRAY_BUFFER, this.m_vertexBuffer);
gl_context.bufferData(gl_context.ARRAY_BUFFER, new Float32Array(this.m_object.m_positions), gl_context.STATIC_DRAW);
gl_context.bindBuffer(gl_context.ELEMENT_ARRAY_BUFFER, this.m_indexBuffer);
gl_context.bufferData(gl_context.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl_context.STATIC_DRAW);
/** Finding the attributes in the vertex shader in the pipeline */
this.m_vertexLocation = gl_context.getAttribLocation(this.m_gl_pipeline, 'position');
//m_colorLocation = gl.getAttribLocation(gl_pipeline, 'color');
//m_normalLocation = gl.getAttribLocation(gl_pipeline, 'normal');
this.m_modelMatrixLocation = gl_context.getUniformLocation(this.m_gl_pipeline, 'model_M');
mat4.translate(this.m_model_M, this.m_model_M, [-0.0, 0.0, -6.0]);
}
/**
* Binds the mesh data. to the program. and use the program.
*/
bind(){
/** Binding the pipeline */
this.m_gl_context.useProgram(this.m_gl_pipeline);
/** Passing vertex values to attributes */
{
this.m_gl_context.bindBuffer(this.m_gl_context.ARRAY_BUFFER, this.m_vertexBuffer); // Bind the buffer
this.m_gl_context.vertexAttribPointer(this.m_vertexLocation, 3, this.m_gl_context.FLOAT, false, 0, 0); // Fill the attribute
this.m_gl_context.enableVertexAttribArray(this.m_vertexLocation);
}
/** Passing Color values to attributes */
{
//this.m_gl_context.bindBuffer(gl.ARRAY_BUFFER, m_colorBuffer);
//this.m_gl_context.vertexAttribPointer(this.m_colorLocation, 4, gl.FLOAT, false, 0, 0);
//this.m_gl_context.enableVertexAttribArray(this.m_colorLocation);
}
/** Binding the mesh model matrix */
this.m_gl_context.uniformMatrix4fv(this.m_modelMatrixLocation , false, this.m_model_M);
}
/** Renders the mesh to the assigned pipeline. */
render(){
this.m_gl_context.bindBuffer(this.m_gl_context.ELEMENT_ARRAY_BUFFER, this.m_indexBuffer);
this.m_gl_context.drawElements(this.m_gl_context.TRIANGLES, this.m_indices.length, this.m_gl_context.UNSIGNED_SHORT, 0);
}
/**
* A rotation interpolation of the rotation matrix. It interpolates and changes the current mesh matrix with the destination matrix.
* @param {*} dst_M - Distination matrix
* @param {*} ratio - Ratio of rotation. It is the ratio between the current object matrix and the next matrix.
*/
rotateSync(dst_M, ratio){
}
/**
* A rotation interpolation of the rotation matrix. It interpolates and changes the current mesh matrix with the destination matrix.
* @param {*} dst_M - Distination matrix
* @param {*} ratio - Ratio of rotation. It is the ratio between the current object matrix and the next matrix.
*/
rotateAsync(dst_M, ratio, ms){
}
// ------------------------------------ SETTERS AREA -----------------------------
/** Sets the object pipeline */
set pipeline(newPipeline){}
} |
JavaScript | class StreamEdit extends React.Component {
componentDidMount() {
this.props.fetchStream(this.props.match.params.id)
}
onSubmit = (formValues) => {
this.props.editStream(this.props.match.params.id, formValues)
}
render() {
console.log(this.props)
if (!this.props.stream) {
return <div>Waiting...</div>
}
return(
<div>
<h3>Edit a Stream</h3>
<StreamForm
// lodash.pick() use only the field "title" and "description" as initial field value
initialValues={_.pick(this.props.stream, 'title', 'description')}
onSubmit={this.onSubmit}
/>
</div>
)
}
} |
JavaScript | class BaseFontLoader {
constructor({
docId,
onUnsupportedFeature,
ownerDocument = globalThis.document,
// For testing only.
styleElement = null
}) {
if (this.constructor === BaseFontLoader) {
unreachable("Cannot initialize BaseFontLoader.");
}
this.docId = docId;
this._onUnsupportedFeature = onUnsupportedFeature;
this._document = ownerDocument;
this.nativeFontFaces = [];
this.styleElement = typeof PDFJSDev === "undefined" || PDFJSDev.test("!PRODUCTION || TESTING") ? styleElement : null;
}
addNativeFontFace(nativeFontFace) {
this.nativeFontFaces.push(nativeFontFace);
this._document.fonts.add(nativeFontFace);
}
insertRule(rule) {
let styleElement = this.styleElement;
if (!styleElement) {
styleElement = this.styleElement = this._document.createElement("style");
styleElement.id = `PDFJS_FONT_STYLE_TAG_${this.docId}`;
this._document.documentElement.getElementsByTagName("head")[0].appendChild(styleElement);
}
const styleSheet = styleElement.sheet;
styleSheet.insertRule(rule, styleSheet.cssRules.length);
}
clear() {
for (const nativeFontFace of this.nativeFontFaces) {
this._document.fonts.delete(nativeFontFace);
}
this.nativeFontFaces.length = 0;
if (this.styleElement) {
// Note: ChildNode.remove doesn't throw if the parentNode is undefined.
this.styleElement.remove();
this.styleElement = null;
}
}
async bind(font) {
// Add the font to the DOM only once; skip if the font is already loaded.
if (font.attached || font.missingFile) {
return;
}
font.attached = true;
if (this.isFontLoadingAPISupported) {
const nativeFontFace = font.createNativeFontFace();
if (nativeFontFace) {
this.addNativeFontFace(nativeFontFace);
try {
await nativeFontFace.loaded;
} catch (ex) {
this._onUnsupportedFeature({
featureId: UNSUPPORTED_FEATURES.errorFontLoadNative
});
warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`); // When font loading failed, fall back to the built-in font renderer.
font.disableFontFace = true;
throw ex;
}
}
return; // The font was, asynchronously, loaded.
} // !this.isFontLoadingAPISupported
const rule = font.createFontFaceRule();
if (rule) {
this.insertRule(rule);
if (this.isSyncFontLoadingSupported) {
return; // The font was, synchronously, loaded.
}
await new Promise(resolve => {
const request = this._queueLoadingCallback(resolve);
this._prepareFontLoadEvent([rule], [font], request);
}); // The font was, asynchronously, loaded.
}
}
_queueLoadingCallback(callback) {
unreachable("Abstract method `_queueLoadingCallback`.");
}
get isFontLoadingAPISupported() {
var _this$_document;
const hasFonts = !!((_this$_document = this._document) !== null && _this$_document !== void 0 && _this$_document.fonts);
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("!PRODUCTION || TESTING")) {
return shadow(this, "isFontLoadingAPISupported", hasFonts && !this.styleElement);
}
return shadow(this, "isFontLoadingAPISupported", hasFonts);
} // eslint-disable-next-line getter-return
get isSyncFontLoadingSupported() {
unreachable("Abstract method `isSyncFontLoadingSupported`.");
} // eslint-disable-next-line getter-return
get _loadTestFont() {
unreachable("Abstract method `_loadTestFont`.");
}
_prepareFontLoadEvent(rules, fontsToLoad, request) {
unreachable("Abstract method `_prepareFontLoadEvent`.");
}
} |
JavaScript | class AnnotationStorage {
constructor() {
this._storage = new Map();
this._modified = false; // Callbacks to signal when the modification state is set or reset.
// This is used by the viewer to only bind on `beforeunload` if forms
// are actually edited to prevent doing so unconditionally since that
// can have undesirable effects.
this.onSetModified = null;
this.onResetModified = null;
}
/**
* Get the value for a given key if it exists, or return the default value.
*
* @public
* @memberof AnnotationStorage
* @param {string} key
* @param {Object} defaultValue
* @returns {Object}
*/
getValue(key, defaultValue) {
const obj = this._storage.get(key);
return obj !== undefined ? obj : defaultValue;
}
/**
* Set the value for a given key
*
* @public
* @memberof AnnotationStorage
* @param {string} key
* @param {Object} value
*/
setValue(key, value) {
const obj = this._storage.get(key);
let modified = false;
if (obj !== undefined) {
for (const [entry, val] of Object.entries(value)) {
if (obj[entry] !== val) {
modified = true;
obj[entry] = val;
}
}
} else {
this._storage.set(key, value);
modified = true;
}
if (modified) {
this._setModified();
}
}
getAll() {
return this._storage.size > 0 ? objectFromMap(this._storage) : null;
}
get size() {
return this._storage.size;
}
/**
* @private
*/
_setModified() {
if (!this._modified) {
this._modified = true;
if (typeof this.onSetModified === "function") {
this.onSetModified();
}
}
}
resetModified() {
if (this._modified) {
this._modified = false;
if (typeof this.onResetModified === "function") {
this.onResetModified();
}
}
}
/**
* PLEASE NOTE: Only intended for usage within the API itself.
* @ignore
*/
get serializable() {
return this._storage.size > 0 ? this._storage : null;
}
} |
JavaScript | class Metadata {
constructor({
parsedData,
rawData
}) {
this._metadataMap = parsedData;
this._data = rawData;
}
getRaw() {
return this._data;
}
get(name) {
var _this$_metadataMap$ge;
return (_this$_metadataMap$ge = this._metadataMap.get(name)) !== null && _this$_metadataMap$ge !== void 0 ? _this$_metadataMap$ge : null;
}
getAll() {
return objectFromMap(this._metadataMap);
}
has(name) {
return this._metadataMap.has(name);
}
} |
JavaScript | class OptionalContentGroup {
constructor(name, intent) {
this.visible = true;
this.name = name;
this.intent = intent;
}
} |
JavaScript | class PDFDataRangeTransport {
/**
* @param {number} length
* @param {Uint8Array} initialData
* @param {boolean} [progressiveDone]
* @param {string} [contentDispositionFilename]
*/
constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
this.length = length;
this.initialData = initialData;
this.progressiveDone = progressiveDone;
this.contentDispositionFilename = contentDispositionFilename;
this._rangeListeners = [];
this._progressListeners = [];
this._progressiveReadListeners = [];
this._progressiveDoneListeners = [];
this._readyCapability = createPromiseCapability();
}
addRangeListener(listener) {
this._rangeListeners.push(listener);
}
addProgressListener(listener) {
this._progressListeners.push(listener);
}
addProgressiveReadListener(listener) {
this._progressiveReadListeners.push(listener);
}
addProgressiveDoneListener(listener) {
this._progressiveDoneListeners.push(listener);
}
onDataRange(begin, chunk) {
for (const listener of this._rangeListeners) {
listener(begin, chunk);
}
}
onDataProgress(loaded, total) {
this._readyCapability.promise.then(() => {
for (const listener of this._progressListeners) {
listener(loaded, total);
}
});
}
onDataProgressiveRead(chunk) {
this._readyCapability.promise.then(() => {
for (const listener of this._progressiveReadListeners) {
listener(chunk);
}
});
}
onDataProgressiveDone() {
this._readyCapability.promise.then(() => {
for (const listener of this._progressiveDoneListeners) {
listener();
}
});
}
transportReady() {
this._readyCapability.resolve();
}
requestDataRange(begin, end) {
unreachable("Abstract method PDFDataRangeTransport.requestDataRange");
}
abort() {}
} |
JavaScript | class PDFDocumentProxy {
constructor(pdfInfo, transport) {
this._pdfInfo = pdfInfo;
this._transport = transport;
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
Object.defineProperty(this, "fingerprint", {
get() {
deprecated("`PDFDocumentProxy.fingerprint`, " + "please use `PDFDocumentProxy.fingerprints` instead.");
return this.fingerprints[0];
}
});
}
}
/**
* @type {AnnotationStorage} Storage for annotation data in forms.
*/
get annotationStorage() {
return this._transport.annotationStorage;
}
/**
* @type {number} Total number of pages in the PDF file.
*/
get numPages() {
return this._pdfInfo.numPages;
}
/**
* @type {Array<string, string|null>} A (not guaranteed to be) unique ID to
* identify the PDF document.
* NOTE: The first element will always be defined for all PDF documents,
* whereas the second element is only defined for *modified* PDF documents.
*/
get fingerprints() {
return this._pdfInfo.fingerprints;
}
/**
* @type {boolean} True if only XFA form.
*/
get isPureXfa() {
return !!this._transport._htmlForXfa;
}
/**
* NOTE: This is (mostly) intended to support printing of XFA forms.
*
* @type {Object | null} An object representing a HTML tree structure
* to render the XFA, or `null` when no XFA form exists.
*/
get allXfaHtml() {
return this._transport._htmlForXfa;
}
/**
* @param {number} pageNumber - The page number to get. The first page is 1.
* @returns {Promise<PDFPageProxy>} A promise that is resolved with
* a {@link PDFPageProxy} object.
*/
getPage(pageNumber) {
return this._transport.getPage(pageNumber);
}
/**
* @param {RefProxy} ref - The page reference.
* @returns {Promise<number>} A promise that is resolved with the page index,
* starting from zero, that is associated with the reference.
*/
getPageIndex(ref) {
return this._transport.getPageIndex(ref);
}
/**
* @returns {Promise<Object<string, Array<any>>>} A promise that is resolved
* with a mapping from named destinations to references.
*
* This can be slow for large documents. Use `getDestination` instead.
*/
getDestinations() {
return this._transport.getDestinations();
}
/**
* @param {string} id - The named destination to get.
* @returns {Promise<Array<any> | null>} A promise that is resolved with all
* information of the given named destination, or `null` when the named
* destination is not present in the PDF file.
*/
getDestination(id) {
return this._transport.getDestination(id);
}
/**
* @returns {Promise<Array<string> | null>} A promise that is resolved with
* an {Array} containing the page labels that correspond to the page
* indexes, or `null` when no page labels are present in the PDF file.
*/
getPageLabels() {
return this._transport.getPageLabels();
}
/**
* @returns {Promise<string>} A promise that is resolved with a {string}
* containing the page layout name.
*/
getPageLayout() {
return this._transport.getPageLayout();
}
/**
* @returns {Promise<string>} A promise that is resolved with a {string}
* containing the page mode name.
*/
getPageMode() {
return this._transport.getPageMode();
}
/**
* @returns {Promise<Object | null>} A promise that is resolved with an
* {Object} containing the viewer preferences, or `null` when no viewer
* preferences are present in the PDF file.
*/
getViewerPreferences() {
return this._transport.getViewerPreferences();
}
/**
* @returns {Promise<any | null>} A promise that is resolved with an {Array}
* containing the destination, or `null` when no open action is present
* in the PDF.
*/
getOpenAction() {
return this._transport.getOpenAction();
}
/**
* @returns {Promise<any>} A promise that is resolved with a lookup table
* for mapping named attachments to their content.
*/
getAttachments() {
return this._transport.getAttachments();
}
/**
* @returns {Promise<Array<string> | null>} A promise that is resolved with
* an {Array} of all the JavaScript strings in the name tree, or `null`
* if no JavaScript exists.
*/
getJavaScript() {
return this._transport.getJavaScript();
}
/**
* @returns {Promise<Object | null>} A promise that is resolved with
* an {Object} with the JavaScript actions:
* - from the name tree (like getJavaScript);
* - from A or AA entries in the catalog dictionary.
* , or `null` if no JavaScript exists.
*/
getJSActions() {
return this._transport.getDocJSActions();
}
/**
* @typedef {Object} OutlineNode
* @property {string} title
* @property {boolean} bold
* @property {boolean} italic
* @property {Uint8ClampedArray} color - The color in RGB format to use for
* display purposes.
* @property {string | Array<any> | null} dest
* @property {string | null} url
* @property {string | undefined} unsafeUrl
* @property {boolean | undefined} newWindow
* @property {number | undefined} count
* @property {Array<OutlineNode>} items
*/
/**
* @returns {Promise<Array<OutlineNode>>} A promise that is resolved with an
* {Array} that is a tree outline (if it has one) of the PDF file.
*/
getOutline() {
return this._transport.getOutline();
}
/**
* @returns {Promise<OptionalContentConfig>} A promise that is resolved with
* an {@link OptionalContentConfig} that contains all the optional content
* groups (assuming that the document has any).
*/
getOptionalContentConfig() {
return this._transport.getOptionalContentConfig();
}
/**
* @returns {Promise<Array<number> | null>} A promise that is resolved with
* an {Array} that contains the permission flags for the PDF document, or
* `null` when no permissions are present in the PDF file.
*/
getPermissions() {
return this._transport.getPermissions();
}
/**
* @returns {Promise<{ info: Object, metadata: Metadata }>} A promise that is
* resolved with an {Object} that has `info` and `metadata` properties.
* `info` is an {Object} filled with anything available in the information
* dictionary and similarly `metadata` is a {Metadata} object with
* information from the metadata section of the PDF.
*/
getMetadata() {
return this._transport.getMetadata();
}
/**
* @typedef {Object} MarkInfo
* Properties correspond to Table 321 of the PDF 32000-1:2008 spec.
* @property {boolean} Marked
* @property {boolean} UserProperties
* @property {boolean} Suspects
*/
/**
* @returns {Promise<MarkInfo | null>} A promise that is resolved with
* a {MarkInfo} object that contains the MarkInfo flags for the PDF
* document, or `null` when no MarkInfo values are present in the PDF file.
*/
getMarkInfo() {
return this._transport.getMarkInfo();
}
/**
* @returns {Promise<TypedArray>} A promise that is resolved with a
* {TypedArray} that has the raw data from the PDF.
*/
getData() {
return this._transport.getData();
}
/**
* @returns {Promise<{ length: number }>} A promise that is resolved when the
* document's data is loaded. It is resolved with an {Object} that contains
* the `length` property that indicates size of the PDF data in bytes.
*/
getDownloadInfo() {
return this._transport.downloadInfoCapability.promise;
}
/**
* @typedef {Object} PDFDocumentStats
* @property {Object<string, boolean>} streamTypes - Used stream types in the
* document (an item is set to true if specific stream ID was used in the
* document).
* @property {Object<string, boolean>} fontTypes - Used font types in the
* document (an item is set to true if specific font ID was used in the
* document).
*/
/**
* @returns {Promise<PDFDocumentStats>} A promise this is resolved with
* current statistics about document structures (see
* {@link PDFDocumentStats}).
*/
getStats() {
return this._transport.getStats();
}
/**
* Cleans up resources allocated by the document on both the main and worker
* threads.
*
* NOTE: Do not, under any circumstances, call this method when rendering is
* currently ongoing since that may lead to rendering errors.
*
* @param {boolean} [keepLoadedFonts] - Let fonts remain attached to the DOM.
* NOTE: This will increase persistent memory usage, hence don't use this
* option unless absolutely necessary. The default value is `false`.
* @returns {Promise} A promise that is resolved when clean-up has finished.
*/
cleanup(keepLoadedFonts = false) {
return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
}
/**
* Destroys the current document instance and terminates the worker.
*/
destroy() {
return this.loadingTask.destroy();
}
/**
* @type {DocumentInitParameters} A subset of the current
* {DocumentInitParameters}, which are needed in the viewer.
*/
get loadingParams() {
return this._transport.loadingParams;
}
/**
* @type {PDFDocumentLoadingTask} The loadingTask for the current document.
*/
get loadingTask() {
return this._transport.loadingTask;
}
/**
* @returns {Promise<Uint8Array>} A promise that is resolved with a
* {Uint8Array} containing the full data of the saved document.
*/
saveDocument() {
if ((typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) && this._transport.annotationStorage.size <= 0) {
deprecated("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
}
return this._transport.saveDocument();
}
/**
* @returns {Promise<Array<Object> | null>} A promise that is resolved with an
* {Array<Object>} containing /AcroForm field data for the JS sandbox,
* or `null` when no field data is present in the PDF file.
*/
getFieldObjects() {
return this._transport.getFieldObjects();
}
/**
* @returns {Promise<boolean>} A promise that is resolved with `true`
* if some /AcroForm fields have JavaScript actions.
*/
hasJSActions() {
return this._transport.hasJSActions();
}
/**
* @returns {Promise<Array<string> | null>} A promise that is resolved with an
* {Array<string>} containing IDs of annotations that have a calculation
* action, or `null` when no such annotations are present in the PDF file.
*/
getCalculationOrderIds() {
return this._transport.getCalculationOrderIds();
}
} |
JavaScript | class PDFPageProxy {
constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
this._pageIndex = pageIndex;
this._pageInfo = pageInfo;
this._ownerDocument = ownerDocument;
this._transport = transport;
this._stats = pdfBug ? new StatTimer() : null;
this._pdfBug = pdfBug;
this.commonObjs = transport.commonObjs;
this.objs = new PDFObjects();
this.cleanupAfterRender = false;
this.pendingCleanup = false;
this._intentStates = new Map();
this.destroyed = false;
}
/**
* @type {number} Page number of the page. First page is 1.
*/
get pageNumber() {
return this._pageIndex + 1;
}
/**
* @type {number} The number of degrees the page is rotated clockwise.
*/
get rotate() {
return this._pageInfo.rotate;
}
/**
* @type {RefProxy | null} The reference that points to this page.
*/
get ref() {
return this._pageInfo.ref;
}
/**
* @type {number} The default size of units in 1/72nds of an inch.
*/
get userUnit() {
return this._pageInfo.userUnit;
}
/**
* @type {Array<number>} An array of the visible portion of the PDF page in
* user space units [x1, y1, x2, y2].
*/
get view() {
return this._pageInfo.view;
}
/**
* @param {GetViewportParameters} params - Viewport parameters.
* @returns {PageViewport} Contains 'width' and 'height' properties
* along with transforms required for rendering.
*/
getViewport({
scale,
rotation = this.rotate,
offsetX = 0,
offsetY = 0,
dontFlip = false
} = {}) {
return new PageViewport({
viewBox: this.view,
scale,
rotation,
offsetX,
offsetY,
dontFlip
});
}
/**
* @param {GetAnnotationsParameters} params - Annotation parameters.
* @returns {Promise<Array<any>>} A promise that is resolved with an
* {Array} of the annotation objects.
*/
getAnnotations({
intent = null
} = {}) {
const renderingIntent = intent === "display" || intent === "print" ? intent : null;
if (!this._annotationsPromise || this._annotationsIntent !== renderingIntent) {
this._annotationsPromise = this._transport.getAnnotations(this._pageIndex, renderingIntent);
this._annotationsIntent = renderingIntent;
}
return this._annotationsPromise;
}
/**
* @returns {Promise<Object>} A promise that is resolved with an
* {Object} with JS actions.
*/
getJSActions() {
return this._jsActionsPromise || (this._jsActionsPromise = this._transport.getPageJSActions(this._pageIndex));
}
/**
* @returns {Promise<Object | null>} A promise that is resolved with
* an {Object} with a fake DOM object (a tree structure where elements
* are {Object} with a name, attributes (class, style, ...), value and
* children, very similar to a HTML DOM tree), or `null` if no XFA exists.
*/
async getXfa() {
var _this$_transport$_htm;
return ((_this$_transport$_htm = this._transport._htmlForXfa) === null || _this$_transport$_htm === void 0 ? void 0 : _this$_transport$_htm.children[this._pageIndex]) || null;
}
/**
* Begins the process of rendering a page to the desired context.
*
* @param {RenderParameters} params - Page render parameters.
* @returns {RenderTask} An object that contains a promise that is
* resolved when the page finishes rendering.
*/
render({
canvasContext,
viewport,
intent = "display",
renderInteractiveForms = false,
transform = null,
imageLayer = null,
canvasFactory = null,
background = null,
includeAnnotationStorage = false,
optionalContentConfigPromise = null
}) {
var _intentState;
if (this._stats) {
this._stats.time("Overall");
}
const renderingIntent = intent === "print" ? "print" : "display"; // If there was a pending destroy, cancel it so no cleanup happens during
// this call to render.
this.pendingCleanup = false;
if (!optionalContentConfigPromise) {
optionalContentConfigPromise = this._transport.getOptionalContentConfig();
}
let intentState = this._intentStates.get(renderingIntent);
if (!intentState) {
intentState = Object.create(null);
this._intentStates.set(renderingIntent, intentState);
} // Ensure that a pending `streamReader` cancel timeout is always aborted.
if (intentState.streamReaderCancelTimeout) {
clearTimeout(intentState.streamReaderCancelTimeout);
intentState.streamReaderCancelTimeout = null;
}
const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
ownerDocument: this._ownerDocument
});
const annotationStorage = includeAnnotationStorage ? this._transport.annotationStorage.serializable : null; // If there's no displayReadyCapability yet, then the operatorList
// was never requested before. Make the request and create the promise.
if (!intentState.displayReadyCapability) {
intentState.displayReadyCapability = createPromiseCapability();
intentState.operatorList = {
fnArray: [],
argsArray: [],
lastChunk: false
};
if (this._stats) {
this._stats.time("Page Request");
}
this._pumpOperatorList({
pageIndex: this._pageIndex,
intent: renderingIntent,
renderInteractiveForms: renderInteractiveForms === true,
annotationStorage
});
}
const complete = error => {
intentState.renderTasks.delete(internalRenderTask); // Attempt to reduce memory usage during *printing*, by always running
// cleanup once rendering has finished (regardless of cleanupAfterRender).
if (this.cleanupAfterRender || renderingIntent === "print") {
this.pendingCleanup = true;
}
this._tryCleanup();
if (error) {
internalRenderTask.capability.reject(error);
this._abortOperatorList({
intentState,
reason: error
});
} else {
internalRenderTask.capability.resolve();
}
if (this._stats) {
this._stats.timeEnd("Rendering");
this._stats.timeEnd("Overall");
}
};
const internalRenderTask = new InternalRenderTask({
callback: complete,
// Only include the required properties, and *not* the entire object.
params: {
canvasContext,
viewport,
transform,
imageLayer,
background
},
objs: this.objs,
commonObjs: this.commonObjs,
operatorList: intentState.operatorList,
pageIndex: this._pageIndex,
canvasFactory: canvasFactoryInstance,
useRequestAnimationFrame: renderingIntent !== "print",
pdfBug: this._pdfBug
});
((_intentState = intentState).renderTasks || (_intentState.renderTasks = new Set())).add(internalRenderTask);
const renderTask = internalRenderTask.task;
Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
if (this.pendingCleanup) {
complete();
return;
}
if (this._stats) {
this._stats.time("Rendering");
}
internalRenderTask.initializeGraphics({
transparency,
optionalContentConfig
});
internalRenderTask.operatorListChanged();
}).catch(complete);
return renderTask;
}
/**
* @param {GetOperatorListParameters} params - Page getOperatorList
* parameters.
* @returns {Promise<PDFOperatorList>} A promise resolved with an
* {@link PDFOperatorList} object that represents the page's operator list.
*/
getOperatorList({
intent = "display"
} = {}) {
function operatorListChanged() {
if (intentState.operatorList.lastChunk) {
intentState.opListReadCapability.resolve(intentState.operatorList);
intentState.renderTasks.delete(opListTask);
}
}
const renderingIntent = `oplist-${intent === "print" ? "print" : "display"}`;
let intentState = this._intentStates.get(renderingIntent);
if (!intentState) {
intentState = Object.create(null);
this._intentStates.set(renderingIntent, intentState);
}
let opListTask;
if (!intentState.opListReadCapability) {
var _intentState2;
opListTask = Object.create(null);
opListTask.operatorListChanged = operatorListChanged;
intentState.opListReadCapability = createPromiseCapability();
((_intentState2 = intentState).renderTasks || (_intentState2.renderTasks = new Set())).add(opListTask);
intentState.operatorList = {
fnArray: [],
argsArray: [],
lastChunk: false
};
if (this._stats) {
this._stats.time("Page Request");
}
this._pumpOperatorList({
pageIndex: this._pageIndex,
intent: renderingIntent
});
}
return intentState.opListReadCapability.promise;
}
/**
* @param {getTextContentParameters} params - getTextContent parameters.
* @returns {ReadableStream} Stream for reading text content chunks.
*/
streamTextContent({
normalizeWhitespace = false,
disableCombineTextItems = false,
includeMarkedContent = false
} = {}) {
const TEXT_CONTENT_CHUNK_SIZE = 100;
return this._transport.messageHandler.sendWithStream("GetTextContent", {
pageIndex: this._pageIndex,
normalizeWhitespace: normalizeWhitespace === true,
combineTextItems: disableCombineTextItems !== true,
includeMarkedContent: includeMarkedContent === true
}, {
highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
size(textContent) {
return textContent.items.length;
}
});
}
/**
* @param {getTextContentParameters} params - getTextContent parameters.
* @returns {Promise<TextContent>} A promise that is resolved with a
* {@link TextContent} object that represents the page's text content.
*/
getTextContent(params = {}) {
const readableStream = this.streamTextContent(params);
return new Promise(function (resolve, reject) {
function pump() {
reader.read().then(function ({
value,
done
}) {
if (done) {
resolve(textContent);
return;
}
Object.assign(textContent.styles, value.styles);
textContent.items.push(...value.items);
pump();
}, reject);
}
const reader = readableStream.getReader();
const textContent = {
items: [],
styles: Object.create(null)
};
pump();
});
}
/**
* @returns {Promise<StructTreeNode>} A promise that is resolved with a
* {@link StructTreeNode} object that represents the page's structure tree,
* or `null` when no structure tree is present for the current page.
*/
getStructTree() {
return this._structTreePromise || (this._structTreePromise = this._transport.getStructTree(this._pageIndex));
}
/**
* Destroys the page object.
* @private
*/
_destroy() {
this.destroyed = true;
this._transport.pageCache[this._pageIndex] = null;
const waitOn = [];
for (const [intent, intentState] of this._intentStates) {
this._abortOperatorList({
intentState,
reason: new Error("Page was destroyed."),
force: true
});
if (intent.startsWith("oplist-")) {
// Avoid errors below, since the renderTasks are just stubs.
continue;
}
for (const internalRenderTask of intentState.renderTasks) {
waitOn.push(internalRenderTask.completed);
internalRenderTask.cancel();
}
}
this.objs.clear();
this._annotationsPromise = null;
this._jsActionsPromise = null;
this._structTreePromise = null;
this.pendingCleanup = false;
return Promise.all(waitOn);
}
/**
* Cleans up resources allocated by the page.
*
* @param {boolean} [resetStats] - Reset page stats, if enabled.
* The default value is `false`.
* @returns {boolean} Indicates if clean-up was successfully run.
*/
cleanup(resetStats = false) {
this.pendingCleanup = true;
return this._tryCleanup(resetStats);
}
/**
* Attempts to clean up if rendering is in a state where that's possible.
* @private
*/
_tryCleanup(resetStats = false) {
if (!this.pendingCleanup) {
return false;
}
for (const {
renderTasks,
operatorList
} of this._intentStates.values()) {
if (renderTasks.size > 0 || !operatorList.lastChunk) {
return false;
}
}
this._intentStates.clear();
this.objs.clear();
this._annotationsPromise = null;
this._jsActionsPromise = null;
this._structTreePromise = null;
if (resetStats && this._stats) {
this._stats = new StatTimer();
}
this.pendingCleanup = false;
return true;
}
/**
* @private
*/
_startRenderPage(transparency, intent) {
const intentState = this._intentStates.get(intent);
if (!intentState) {
return; // Rendering was cancelled.
}
if (this._stats) {
this._stats.timeEnd("Page Request");
} // TODO Refactor RenderPageRequest to separate rendering
// and operator list logic
if (intentState.displayReadyCapability) {
intentState.displayReadyCapability.resolve(transparency);
}
}
/**
* @private
*/
_renderPageChunk(operatorListChunk, intentState) {
// Add the new chunk to the current operator list.
for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
}
intentState.operatorList.lastChunk = operatorListChunk.lastChunk; // Notify all the rendering tasks there are more operators to be consumed.
for (const internalRenderTask of intentState.renderTasks) {
internalRenderTask.operatorListChanged();
}
if (operatorListChunk.lastChunk) {
this._tryCleanup();
}
}
/**
* @private
*/
_pumpOperatorList(args) {
assert(args.intent, 'PDFPageProxy._pumpOperatorList: Expected "intent" argument.');
const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", args);
const reader = readableStream.getReader();
const intentState = this._intentStates.get(args.intent);
intentState.streamReader = reader;
const pump = () => {
reader.read().then(({
value,
done
}) => {
if (done) {
intentState.streamReader = null;
return;
}
if (this._transport.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
this._renderPageChunk(value, intentState);
pump();
}, reason => {
intentState.streamReader = null;
if (this._transport.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
if (intentState.operatorList) {
// Mark operator list as complete.
intentState.operatorList.lastChunk = true;
for (const internalRenderTask of intentState.renderTasks) {
internalRenderTask.operatorListChanged();
}
this._tryCleanup();
}
if (intentState.displayReadyCapability) {
intentState.displayReadyCapability.reject(reason);
} else if (intentState.opListReadCapability) {
intentState.opListReadCapability.reject(reason);
} else {
throw reason;
}
});
};
pump();
}
/**
* @private
*/
_abortOperatorList({
intentState,
reason,
force = false
}) {
assert(reason instanceof Error || typeof reason === "object" && reason !== null, 'PDFPageProxy._abortOperatorList: Expected "reason" argument.');
if (!intentState.streamReader) {
return;
}
if (!force) {
// Ensure that an Error occurring in *only* one `InternalRenderTask`, e.g.
// multiple render() calls on the same canvas, won't break all rendering.
if (intentState.renderTasks.size > 0) {
return;
} // Don't immediately abort parsing on the worker-thread when rendering is
// cancelled, since that will unnecessarily delay re-rendering when (for
// partially parsed pages) e.g. zooming/rotation occurs in the viewer.
if (reason instanceof RenderingCancelledException) {
intentState.streamReaderCancelTimeout = setTimeout(() => {
this._abortOperatorList({
intentState,
reason,
force: true
});
intentState.streamReaderCancelTimeout = null;
}, RENDERING_CANCELLED_TIMEOUT);
return;
}
}
intentState.streamReader.cancel(new AbortException(reason === null || reason === void 0 ? void 0 : reason.message));
intentState.streamReader = null;
if (this._transport.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
} // Remove the current `intentState`, since a cancelled `getOperatorList`
// call on the worker-thread cannot be re-started...
for (const [intent, curIntentState] of this._intentStates) {
if (curIntentState === intentState) {
this._intentStates.delete(intent);
break;
}
} // ... and force clean-up to ensure that any old state is always removed.
this.cleanup();
}
/**
* @type {Object} Returns page stats, if enabled; returns `null` otherwise.
*/
get stats() {
return this._stats;
}
} |
JavaScript | class WorkerTransport {
constructor(messageHandler, loadingTask, networkStream, params) {
this.messageHandler = messageHandler;
this.loadingTask = loadingTask;
this.commonObjs = new PDFObjects();
this.fontLoader = new FontLoader({
docId: loadingTask.docId,
onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
ownerDocument: params.ownerDocument,
styleElement: params.styleElement
});
this._params = params;
if (!params.useWorkerFetch) {
this.CMapReaderFactory = new params.CMapReaderFactory({
baseUrl: params.cMapUrl,
isCompressed: params.cMapPacked
});
this.StandardFontDataFactory = new params.StandardFontDataFactory({
baseUrl: params.standardFontDataUrl
});
}
this.destroyed = false;
this.destroyCapability = null;
this._passwordCapability = null;
this._networkStream = networkStream;
this._fullReader = null;
this._lastProgress = null;
this.pageCache = [];
this.pagePromises = [];
this.downloadInfoCapability = createPromiseCapability();
this.setupMessageHandler();
}
get annotationStorage() {
return shadow(this, "annotationStorage", new AnnotationStorage());
}
destroy() {
if (this.destroyCapability) {
return this.destroyCapability.promise;
}
this.destroyed = true;
this.destroyCapability = createPromiseCapability();
if (this._passwordCapability) {
this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
}
const waitOn = []; // We need to wait for all renderings to be completed, e.g.
// timeout/rAF can take a long time.
for (const page of this.pageCache) {
if (page) {
waitOn.push(page._destroy());
}
}
this.pageCache.length = 0;
this.pagePromises.length = 0; // Allow `AnnotationStorage`-related clean-up when destroying the document.
if (this.hasOwnProperty("annotationStorage")) {
this.annotationStorage.resetModified();
} // We also need to wait for the worker to finish its long running tasks.
const terminated = this.messageHandler.sendWithPromise("Terminate", null);
waitOn.push(terminated);
Promise.all(waitOn).then(() => {
this.commonObjs.clear();
this.fontLoader.clear();
this._hasJSActionsPromise = null;
if (this._networkStream) {
this._networkStream.cancelAllRequests(new AbortException("Worker was terminated."));
}
if (this.messageHandler) {
this.messageHandler.destroy();
this.messageHandler = null;
}
this.destroyCapability.resolve();
}, this.destroyCapability.reject);
return this.destroyCapability.promise;
}
setupMessageHandler() {
const {
messageHandler,
loadingTask
} = this;
messageHandler.on("GetReader", (data, sink) => {
assert(this._networkStream, "GetReader - no `IPDFStream` instance available.");
this._fullReader = this._networkStream.getFullReader();
this._fullReader.onProgress = evt => {
this._lastProgress = {
loaded: evt.loaded,
total: evt.total
};
};
sink.onPull = () => {
this._fullReader.read().then(function ({
value,
done
}) {
if (done) {
sink.close();
return;
}
assert(isArrayBuffer(value), "GetReader - expected an ArrayBuffer."); // Enqueue data chunk into sink, and transfer it
// to other side as `Transferable` object.
sink.enqueue(new Uint8Array(value), 1, [value]);
}).catch(reason => {
sink.error(reason);
});
};
sink.onCancel = reason => {
this._fullReader.cancel(reason);
sink.ready.catch(readyReason => {
if (this.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
throw readyReason;
});
};
});
messageHandler.on("ReaderHeadersReady", data => {
const headersCapability = createPromiseCapability();
const fullReader = this._fullReader;
fullReader.headersReady.then(() => {
// If stream or range are disabled, it's our only way to report
// loading progress.
if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
if (this._lastProgress && loadingTask.onProgress) {
loadingTask.onProgress(this._lastProgress);
}
fullReader.onProgress = evt => {
if (loadingTask.onProgress) {
loadingTask.onProgress({
loaded: evt.loaded,
total: evt.total
});
}
};
}
headersCapability.resolve({
isStreamingSupported: fullReader.isStreamingSupported,
isRangeSupported: fullReader.isRangeSupported,
contentLength: fullReader.contentLength
});
}, headersCapability.reject);
return headersCapability.promise;
});
messageHandler.on("GetRangeReader", (data, sink) => {
assert(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
const rangeReader = this._networkStream.getRangeReader(data.begin, data.end); // When streaming is enabled, it's possible that the data requested here
// has already been fetched via the `_fullRequestReader` implementation.
// However, given that the PDF data is loaded asynchronously on the
// main-thread and then sent via `postMessage` to the worker-thread,
// it may not have been available during parsing (hence the attempt to
// use range requests here).
//
// To avoid wasting time and resources here, we'll thus *not* dispatch
// range requests if the data was already loaded but has not been sent to
// the worker-thread yet (which will happen via the `_fullRequestReader`).
if (!rangeReader) {
sink.close();
return;
}
sink.onPull = () => {
rangeReader.read().then(function ({
value,
done
}) {
if (done) {
sink.close();
return;
}
assert(isArrayBuffer(value), "GetRangeReader - expected an ArrayBuffer.");
sink.enqueue(new Uint8Array(value), 1, [value]);
}).catch(reason => {
sink.error(reason);
});
};
sink.onCancel = reason => {
rangeReader.cancel(reason);
sink.ready.catch(readyReason => {
if (this.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
throw readyReason;
});
};
});
messageHandler.on("GetDoc", ({
pdfInfo
}) => {
this._numPages = pdfInfo.numPages;
this._htmlForXfa = pdfInfo.htmlForXfa;
delete pdfInfo.htmlForXfa;
loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
});
messageHandler.on("DocException", function (ex) {
let reason;
switch (ex.name) {
case "PasswordException":
reason = new PasswordException(ex.message, ex.code);
break;
case "InvalidPDFException":
reason = new InvalidPDFException(ex.message);
break;
case "MissingPDFException":
reason = new MissingPDFException(ex.message);
break;
case "UnexpectedResponseException":
reason = new UnexpectedResponseException(ex.message, ex.status);
break;
case "UnknownErrorException":
reason = new UnknownErrorException(ex.message, ex.details);
break;
}
if (!(reason instanceof Error)) {
const msg = "DocException - expected a valid Error.";
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("!PRODUCTION || TESTING")) {
unreachable(msg);
} else {
warn(msg);
}
}
loadingTask._capability.reject(reason);
});
messageHandler.on("PasswordRequest", exception => {
this._passwordCapability = createPromiseCapability();
if (loadingTask.onPassword) {
const updatePassword = password => {
this._passwordCapability.resolve({
password
});
};
try {
loadingTask.onPassword(updatePassword, exception.code);
} catch (ex) {
this._passwordCapability.reject(ex);
}
} else {
this._passwordCapability.reject(new PasswordException(exception.message, exception.code));
}
return this._passwordCapability.promise;
});
messageHandler.on("DataLoaded", data => {
// For consistency: Ensure that progress is always reported when the
// entire PDF file has been loaded, regardless of how it was fetched.
if (loadingTask.onProgress) {
loadingTask.onProgress({
loaded: data.length,
total: data.length
});
}
this.downloadInfoCapability.resolve(data);
});
messageHandler.on("StartRenderPage", data => {
if (this.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
const page = this.pageCache[data.pageIndex];
page._startRenderPage(data.transparency, data.intent);
});
messageHandler.on("commonobj", data => {
var _globalThis$FontInspe;
if (this.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
const [id, type, exportedData] = data;
if (this.commonObjs.has(id)) {
return;
}
switch (type) {
case "Font":
const params = this._params;
if ("error" in exportedData) {
const exportedError = exportedData.error;
warn(`Error during font loading: ${exportedError}`);
this.commonObjs.resolve(id, exportedError);
break;
}
let fontRegistry = null;
if (params.pdfBug && (_globalThis$FontInspe = globalThis.FontInspector) !== null && _globalThis$FontInspe !== void 0 && _globalThis$FontInspe.enabled) {
fontRegistry = {
registerFont(font, url) {
globalThis.FontInspector.fontAdded(font, url);
}
};
}
const font = new FontFaceObject(exportedData, {
isEvalSupported: params.isEvalSupported,
disableFontFace: params.disableFontFace,
ignoreErrors: params.ignoreErrors,
onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
fontRegistry
});
this.fontLoader.bind(font).catch(reason => {
return messageHandler.sendWithPromise("FontFallback", {
id
});
}).finally(() => {
if (!params.fontExtraProperties && font.data) {
// Immediately release the `font.data` property once the font
// has been attached to the DOM, since it's no longer needed,
// rather than waiting for a `PDFDocumentProxy.cleanup` call.
// Since `font.data` could be very large, e.g. in some cases
// multiple megabytes, this will help reduce memory usage.
font.data = null;
}
this.commonObjs.resolve(id, font);
});
break;
case "FontPath":
case "Image":
this.commonObjs.resolve(id, exportedData);
break;
default:
throw new Error(`Got unknown common object type ${type}`);
}
});
messageHandler.on("obj", data => {
var _imageData$data;
if (this.destroyed) {
// Ignore any pending requests if the worker was terminated.
return undefined;
}
const [id, pageIndex, type, imageData] = data;
const pageProxy = this.pageCache[pageIndex];
if (pageProxy.objs.has(id)) {
return undefined;
}
switch (type) {
case "Image":
pageProxy.objs.resolve(id, imageData); // Heuristic that will allow us not to store large data.
const MAX_IMAGE_SIZE_TO_STORE = 8000000;
if ((imageData === null || imageData === void 0 ? void 0 : (_imageData$data = imageData.data) === null || _imageData$data === void 0 ? void 0 : _imageData$data.length) > MAX_IMAGE_SIZE_TO_STORE) {
pageProxy.cleanupAfterRender = true;
}
break;
case "Pattern":
pageProxy.objs.resolve(id, imageData);
break;
default:
throw new Error(`Got unknown object type ${type}`);
}
return undefined;
});
messageHandler.on("DocProgress", data => {
if (this.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
if (loadingTask.onProgress) {
loadingTask.onProgress({
loaded: data.loaded,
total: data.total
});
}
});
messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
messageHandler.on("FetchBuiltInCMap", data => {
if (this.destroyed) {
return Promise.reject(new Error("Worker was destroyed."));
}
if (!this.CMapReaderFactory) {
return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
}
return this.CMapReaderFactory.fetch(data);
});
messageHandler.on("FetchStandardFontData", data => {
if (this.destroyed) {
return Promise.reject(new Error("Worker was destroyed."));
}
if (!this.StandardFontDataFactory) {
return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
}
return this.StandardFontDataFactory.fetch(data);
});
}
_onUnsupportedFeature({
featureId
}) {
if (this.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
if (this.loadingTask.onUnsupportedFeature) {
this.loadingTask.onUnsupportedFeature(featureId);
}
}
getData() {
return this.messageHandler.sendWithPromise("GetData", null);
}
getPage(pageNumber) {
if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
return Promise.reject(new Error("Invalid page request"));
}
const pageIndex = pageNumber - 1;
if (pageIndex in this.pagePromises) {
return this.pagePromises[pageIndex];
}
const promise = this.messageHandler.sendWithPromise("GetPage", {
pageIndex
}).then(pageInfo => {
if (this.destroyed) {
throw new Error("Transport destroyed");
}
const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
this.pageCache[pageIndex] = page;
return page;
});
this.pagePromises[pageIndex] = promise;
return promise;
}
getPageIndex(ref) {
return this.messageHandler.sendWithPromise("GetPageIndex", {
ref
}).catch(function (reason) {
return Promise.reject(new Error(reason));
});
}
getAnnotations(pageIndex, intent) {
return this.messageHandler.sendWithPromise("GetAnnotations", {
pageIndex,
intent
});
}
saveDocument() {
var _this$_fullReader$fil, _this$_fullReader;
return this.messageHandler.sendWithPromise("SaveDocument", {
isPureXfa: !!this._htmlForXfa,
numPages: this._numPages,
annotationStorage: this.annotationStorage.serializable,
filename: (_this$_fullReader$fil = (_this$_fullReader = this._fullReader) === null || _this$_fullReader === void 0 ? void 0 : _this$_fullReader.filename) !== null && _this$_fullReader$fil !== void 0 ? _this$_fullReader$fil : null
}).finally(() => {
this.annotationStorage.resetModified();
});
}
getFieldObjects() {
return this.messageHandler.sendWithPromise("GetFieldObjects", null);
}
hasJSActions() {
return this._hasJSActionsPromise || (this._hasJSActionsPromise = this.messageHandler.sendWithPromise("HasJSActions", null));
}
getCalculationOrderIds() {
return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
}
getDestinations() {
return this.messageHandler.sendWithPromise("GetDestinations", null);
}
getDestination(id) {
if (typeof id !== "string") {
return Promise.reject(new Error("Invalid destination request."));
}
return this.messageHandler.sendWithPromise("GetDestination", {
id
});
}
getPageLabels() {
return this.messageHandler.sendWithPromise("GetPageLabels", null);
}
getPageLayout() {
return this.messageHandler.sendWithPromise("GetPageLayout", null);
}
getPageMode() {
return this.messageHandler.sendWithPromise("GetPageMode", null);
}
getViewerPreferences() {
return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
}
getOpenAction() {
return this.messageHandler.sendWithPromise("GetOpenAction", null);
}
getAttachments() {
return this.messageHandler.sendWithPromise("GetAttachments", null);
}
getJavaScript() {
return this.messageHandler.sendWithPromise("GetJavaScript", null);
}
getDocJSActions() {
return this.messageHandler.sendWithPromise("GetDocJSActions", null);
}
getPageJSActions(pageIndex) {
return this.messageHandler.sendWithPromise("GetPageJSActions", {
pageIndex
});
}
getStructTree(pageIndex) {
return this.messageHandler.sendWithPromise("GetStructTree", {
pageIndex
});
}
getOutline() {
return this.messageHandler.sendWithPromise("GetOutline", null);
}
getOptionalContentConfig() {
return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
return new OptionalContentConfig(results);
});
}
getPermissions() {
return this.messageHandler.sendWithPromise("GetPermissions", null);
}
getMetadata() {
return this.messageHandler.sendWithPromise("GetMetadata", null).then(results => {
var _this$_fullReader$fil2, _this$_fullReader2, _this$_fullReader$con, _this$_fullReader3;
return {
info: results[0],
metadata: results[1] ? new Metadata(results[1]) : null,
contentDispositionFilename: (_this$_fullReader$fil2 = (_this$_fullReader2 = this._fullReader) === null || _this$_fullReader2 === void 0 ? void 0 : _this$_fullReader2.filename) !== null && _this$_fullReader$fil2 !== void 0 ? _this$_fullReader$fil2 : null,
contentLength: (_this$_fullReader$con = (_this$_fullReader3 = this._fullReader) === null || _this$_fullReader3 === void 0 ? void 0 : _this$_fullReader3.contentLength) !== null && _this$_fullReader$con !== void 0 ? _this$_fullReader$con : null
};
});
}
getMarkInfo() {
return this.messageHandler.sendWithPromise("GetMarkInfo", null);
}
getStats() {
return this.messageHandler.sendWithPromise("GetStats", null);
}
async startCleanup(keepLoadedFonts = false) {
await this.messageHandler.sendWithPromise("Cleanup", null);
if (this.destroyed) {
return; // No need to manually clean-up when destruction has started.
}
for (let i = 0, ii = this.pageCache.length; i < ii; i++) {
const page = this.pageCache[i];
if (!page) {
continue;
}
const cleanupSuccessful = page.cleanup();
if (!cleanupSuccessful) {
throw new Error(`startCleanup: Page ${i + 1} is currently rendering.`);
}
}
this.commonObjs.clear();
if (!keepLoadedFonts) {
this.fontLoader.clear();
}
this._hasJSActionsPromise = null;
}
get loadingParams() {
const params = this._params;
return shadow(this, "loadingParams", {
disableAutoFetch: params.disableAutoFetch
});
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.