language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class TcbClient extends AbstractClient {
constructor(credential, region, profile) {
super("tcb.tencentcloudapi.com", "2018-06-08", credential, region, profile);
}
/**
* 修改数据库权限
* @param {ModifyDatabaseACLRequest} req
* @param {function(string, ModifyDatabaseACLResponse):void} cb
* @public
*/
ModifyDatabaseACL(req, cb) {
let resp = new ModifyDatabaseACLResponse();
this.request("ModifyDatabaseACL", req, resp, cb);
}
/**
* 获取数据库权限
* @param {DescribeDatabaseACLRequest} req
* @param {function(string, DescribeDatabaseACLResponse):void} cb
* @public
*/
DescribeDatabaseACL(req, cb) {
let resp = new DescribeDatabaseACLResponse();
this.request("DescribeDatabaseACL", req, resp, cb);
}
/**
* 更新环境信息
* @param {ModifyEnvRequest} req
* @param {function(string, ModifyEnvResponse):void} cb
* @public
*/
ModifyEnv(req, cb) {
let resp = new ModifyEnvResponse();
this.request("ModifyEnv", req, resp, cb);
}
/**
* 获取环境列表,含环境下的各个资源信息。尤其是各资源的唯一标识,是请求各资源的关键参数
* @param {DescribeEnvsRequest} req
* @param {function(string, DescribeEnvsResponse):void} cb
* @public
*/
DescribeEnvs(req, cb) {
let resp = new DescribeEnvsResponse();
this.request("DescribeEnvs", req, resp, cb);
}
} |
JavaScript | class JsonYamlGenerator extends BaseGenerator {
constructor() { super('yml'); }
invoke( rez/*, themeMarkup, cssInfo, opts*/ ) {
return YAML.stringify(JSON.parse( rez.stringify() ), Infinity, 2);
}
generate( rez, f/*, opts */) {
const data = YAML.stringify(JSON.parse( rez.stringify() ), Infinity, 2);
FS.writeFileSync(f, data, 'utf8');
return data;
}
} |
JavaScript | class ZigUtils {
/**
* Determines the days, hours, minutes, and seconds represented in a provided string (e.g., `'1d2h3m4s'`, `'10h15s'`, `'5m'`)
*
* @static
* @param {String} str
* @returns {Object} object of properties for each unit of time: `day`, `hr`, `min`, and `sec`
* @memberof ZigUtils
*/
static parseIntervalString (str) {
const day = parseInt(str.match(/(\d+)d/g) ? str.match(/(\d+)d/g)[0].slice(0, -1) : 0)
const hr = parseInt(str.match(/(\d+)h/g) ? str.match(/(\d+)h/g)[0].slice(0, -1) : 0)
const min = parseInt(str.match(/(\d+)m/g) ? str.match(/(\d+)m/g)[0].slice(0, -1) : 0)
const sec = parseInt(str.match(/(\d+)s/g) ? str.match(/(\d+)s/g)[0].slice(0, -1) : 0)
return { day, hr, min, sec }
}
/**
* Capitalizes the first character of the provided string
*
* @static
* @param {String} str string to capitalize
* @returns {String} capitalized string
* @memberof ZigUtils
*/
static capitalize (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
} |
JavaScript | class DesktopContainer extends Component {
constructor(props){
super();
let activeItem = ""
window.location.hash.length>2 ? activeItem = window.location.hash.substring(2,window.location.hash.length) : null;
this.state = { activeItem: activeItem}
}
hideFixedMenu = () => this.setState({ fixed: false })
showFixedMenu = () => this.setState({ fixed: true })
handleMenuClick = (e, { name }) => this.setState({ activeItem: name })
render() {
const { children } = this.props
const { fixed } = this.state
const { activeItem } = this.state
return (
<Responsive minWidth={Responsive.onlyTablet.minWidth}>
<Visibility
once={false}
onBottomPassed={this.showFixedMenu}
onBottomPassedReverse={this.hideFixedMenu}
>
<Segment
inverted
textAlign='center'
vertical
>
<Menu
fixed={fixed ? 'top' : null}
inverted={true}
pointing={!fixed}
secondary={!fixed}
size='large'
>
<Container>
<Menu.Item header>
<Icon inverted name="spoon" />
There Is A Spoon
</Menu.Item>
<Menu.Item as='a' href="#" active={ activeItem === "" } name="" onClick={ this.handleMenuClick }>
Home
</Menu.Item>
<Menu.Item as='a' href="#map" active={ activeItem === "map" } name="map" onClick={ this.handleMenuClick }>Map</Menu.Item>
</Container>
</Menu>
</Segment>
</Visibility>
{children}
</Responsive>
)
}
} |
JavaScript | class VulnerabilityAssessmentRecurringScansProperties {
/**
* Create a VulnerabilityAssessmentRecurringScansProperties.
* @member {boolean} [isEnabled] Recurring scans state.
* @member {boolean} [emailSubscriptionAdmins] Specifies that the schedule
* scan notification will be is sent to the subscription administrators.
* Default value: true .
* @member {array} [emails] Specifies an array of e-mail addresses to which
* the scan notification is sent.
*/
constructor() {
}
/**
* Defines the metadata of VulnerabilityAssessmentRecurringScansProperties
*
* @returns {object} metadata of VulnerabilityAssessmentRecurringScansProperties
*
*/
mapper() {
return {
required: false,
serializedName: 'VulnerabilityAssessmentRecurringScansProperties',
type: {
name: 'Composite',
className: 'VulnerabilityAssessmentRecurringScansProperties',
modelProperties: {
isEnabled: {
required: false,
serializedName: 'isEnabled',
type: {
name: 'Boolean'
}
},
emailSubscriptionAdmins: {
required: false,
serializedName: 'emailSubscriptionAdmins',
defaultValue: true,
type: {
name: 'Boolean'
}
},
emails: {
required: false,
serializedName: 'emails',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
}
}
}
};
}
} |
JavaScript | class CelleditGoogleTypeDate extends FuroUi5DataDatePicker {
constructor() {
super();
this.addEventListener('click', e => {
e.stopPropagation();
e.preventDefault();
});
}
} |
JavaScript | class LinkedBag {
constructor() {
this._first = null; // beginning of bag
this._n = 0; // number of elements in bag
}
/**
* Is this bag empty?
*/
isEmpty() {
return this._first == null;
}
/**
* Returns the number of items in this bag.
*/
size() {
return this._n;
}
/**
* Adds the item to this bag.
*
* @param {Item} item
*/
add(item) {
const oldFirst = this._first;
this._first = new Node();
this._first._item = item;
this._first._next = oldFirst;
this._n++;
}
/**
* Returns items in the bag as an array.
*/
entries() {
const array = new Array();
for (let x = this._first; x != null; x = x._next) {
array.push(x._item);
}
return array;
}
} |
JavaScript | class BaseComponent {
constructor(document, elementRef, renderer) {
this.document = document;
this.elementRef = elementRef;
this.renderer = renderer;
this.eventHooks = [];
this.window = { pageXOffset: 0, pageYOffset: 0 };
this.window = document.defaultView;
this.requestAnimationFrame = this.getRequestAnimationFrame();
}
onEventChange(event) {
this.calculate(event);
this.eventHooks.push(this.renderer.listen(this.document, 'mouseup', () => this.removeListeners()));
this.eventHooks.push(this.renderer.listen(this.document, 'touchend', () => this.removeListeners()));
this.eventHooks.push(this.renderer.listen(this.document, 'mousemove', (e) => this.calculate(e)));
this.eventHooks.push(this.renderer.listen(this.document, 'touchmove', (e) => this.calculate(e)));
}
calculateCoordinates(event) {
const { width: elWidth, height: elHeight, top: elTop, left: elLeft } = this.elementRef.nativeElement.getBoundingClientRect();
const pageX = typeof event['pageX'] === 'number' ? event['pageX'] : event['touches'][0].pageX;
const pageY = typeof event['pageY'] === 'number' ? event['pageY'] : event['touches'][0].pageY;
const x = Math.max(0, Math.min(pageX - (elLeft + this.window.pageXOffset), elWidth));
const y = Math.max(0, Math.min(pageY - (elTop + this.window.pageYOffset), elHeight));
this.movePointer({ x, y, height: elHeight, width: elWidth });
}
calculate(event) {
event.preventDefault();
if (!this.requestAnimationFrame) {
return this.calculateCoordinates(event);
}
this.requestAnimationFrame(() => this.calculateCoordinates(event));
}
getRequestAnimationFrame() {
return this.window.requestAnimationFrame ||
this.window.webkitRequestAnimationFrame ||
this.window.mozRequestAnimationFrame ||
this.window.oRequestAnimationFrame ||
this.window.msRequestAnimationFrame;
}
removeListeners() {
this.eventHooks.forEach((cb) => cb());
this.eventHooks.length = 0;
}
ngOnDestroy() {
this.removeListeners();
}
} |
JavaScript | class CustomError extends Error {
constructor(message) {
super(message);
this.message = message;
this.name = "CustomError";
}
} |
JavaScript | class NetworkError extends CustomError {
constructor(message) {
super(message);
this.message = message;
this.name = "NetworkError";
}
} |
JavaScript | class AuthorizationError extends CustomError {
constructor(message) {
super(message);
this.message = message;
this.name = "AuthorizationError";
}
} |
JavaScript | class IllegalArgumentError extends CustomError {
constructor(message) {
super(message);
this.message = message;
this.name = "IllegalArgumentError";
}
} |
JavaScript | class TempInput extends Component {
constructor(props) {
// Expects props for temp, scale, and onChange
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.onChange(e.target.value)
}
render() {
const temp = this.props.temp
const scale = this.props.scale
return (
<div className={'mx-auto md:flex-grow md:ml-6 self-center'}>
<label className={'sr-only'} htmlFor={scaleNames[scale]}>Degrees {scaleNames[scale]}</label>
<input value={temp}
id={scaleNames[scale]}
type={'number'}
onChange={this.handleChange}
className={'h-14 float-left w-10/12 md:w-3/4 text-right text-xl appearance-none drop-shadow border-4 ' +
'border-transparent rounded py-2 px-4 text-primary focus:outline-none bg-primary ' +
'focus:border-primary'} />
<img src={images[scale]} alt={`degrees ${scaleNames[scale]}`} className={'pl-2 h-14 w-2/12 md:w-1/4'}/>
</div>
);
}
} |
JavaScript | class Config {
/**
* Set up a new Configuration
*/
constructor() {
this.reset(DEFAULT_USER_CONFIG);
this.read(DEFAULT_EXTRA_CONFIG);
}
/**
* Reset the RTM Configuration with the specified User config file
* @param {string} file User Config File
*/
reset(file) {
this._CONFIG = {};
this.read(BASE_CONFIG);
this.read(file);
this.USER_CONFIG = file;
}
/**
* Get the Configuration Object
* @returns {object}
*/
get() {
return this.config;
}
/**
* Get the Configuration Object
* @returns {object}
*/
get config() {
if ( this._CONFIG === {} ) {
throw "No Configuration Set";
}
this._parseOptions();
return this._CONFIG;
}
/**
* Get the RTMClient from the configuration
* @returns {RTMClient}
*/
get client() {
if ( !this._CONFIG._client ) {
throw "No Client configuration set";
}
return this._CONFIG._client;
}
/**
* Get the RTMUser from the configuration
*
* If no RTMUser is saved, start the login process
* @param {function} callback callback function
* @param {RTMUser} callback.user The RTM User
*/
user(callback) {
if ( !this._CONFIG._user ) {
return login(callback);
}
return callback(this._CONFIG._user);
}
/**
* Read a configuration file to merge with the existing configuration
* @param {string} file Configuration file path
*/
read(file) {
if ( file && fs.existsSync(file) ) {
// Read the config file
let config = JSON.parse(fs.readFileSync(file, 'utf-8'));
// Merge config into CONFIG
this._CONFIG = merge(this._CONFIG, config, {
arrayMerge: function (d, s) {
return d.concat(s);
}
});
// Parse the Config Object
this._parseConfig();
}
}
/**
* Save the RTM User to the user configuration file
* @param {RTMUser} user RTM User to save
*/
saveUser(user) {
this._CONFIG._user = user;
let config = {};
if ( fs.existsSync(this.USER_CONFIG) ) {
config = JSON.parse(fs.readFileSync(this.USER_CONFIG, 'utf-8'));
}
config.user = this.client.user.export(user);
fs.writeFileSync(this.USER_CONFIG, JSON.stringify(config, null, 2));
}
/**
* Remove any saved RTM User information from the User config file
*/
removeUser() {
if ( fs.existsSync(this.USER_CONFIG) ) {
let config = JSON.parse(fs.readFileSync(this.USER_CONFIG, 'utf-8'));
if ( config.user ) {
delete config.user;
fs.writeFileSync(this.USER_CONFIG, JSON.stringify(config, null, 2));
}
}
if ( this._CONFIG.user ) {
delete this._CONFIG.user;
}
if ( this._CONFIG._user ) {
delete this._CONFIG._user;
}
}
/**
* Parse the command line options (override from config files)
*/
_parseOptions() {
if ( global._program ) {
// Parse plain & styled flags
if ( global._program.color ) {
this._CONFIG.plain = false;
delete global._program.color;
}
if ( global._program.plain ) {
this._CONFIG.plain = true;
delete global._program.plain;
}
// Parse completed
let completed = global._program.completed === undefined ? this._CONFIG.completed : global._program.completed;
if ( completed.toString().toLowerCase() === 'true' ) {
completed = true;
}
else if ( completed.toString().toLowerCase() === 'false' ) {
completed = false;
}
else {
completed = parseInt(completed);
}
this._CONFIG.completed = completed;
// Parse hide due
let hideDue = global._program.hideDue === undefined ? this._CONFIG.hideDue : global._program.hideDue;
if ( hideDue.toString().toLowerCase() === 'false' ) {
hideDue = false;
}
else {
hideDue = parseInt(hideDue);
}
this._CONFIG.hideDue = hideDue;
// Parse status
if ( global._program.status ) {
this._CONFIG.status = !this._CONFIG.status;
delete global._program.status;
}
}
}
/**
* Parse the Configuration properties
* @private
*/
_parseConfig() {
// Reset CONFIG client and user
delete this._CONFIG._client;
delete this._CONFIG._user;
// Set the RTM Client
if ( this._CONFIG.client ) {
this._CONFIG._client = new api(
this._CONFIG.client.key,
this._CONFIG.client.secret,
this._CONFIG.client.perms
);
}
// Set the RTM User, if present
if ( this._CONFIG.user ) {
try {
this._CONFIG._user = this._CONFIG._client.user.import(this._CONFIG.user);
}
catch(exception) {}
}
}
} |
JavaScript | class Search extends Component {
state = {
search: "",
books: [],
results: [],
savedBooks: [],
error: ""
};
handleInputChange = event => {
this.setState({ search: event.target.value });
};
handleFormSubmit = event => {
event.preventDefault();
API.getBooks(this.state.search)
.then(res => {
this.setState({ results: res.data.items, error: "" });
// console.log(res.data.items)
})
.catch(err => this.setState({ error: err.message }));
};
handleSave = book => {
console.log(book)
let bookData = {
image: book.volumeInfo.imageLinks.thumbnail,
title: book.volumeInfo.title,
author: book.volumeInfo.authors.join(", "),
description: book.volumeInfo.description,
link: book.volumeInfo.previewLink
};
API.saveBook(bookData)
.then(savedBook => this.setState({ savedBooks: this.state.savedBooks.concat([savedBook]) }))
.catch(err => console.error(err));
// if (this.state.savedBooks.map(book => book._id).includes(book._id)) {
// API.deleteBook(book._id)
// .then(deletedBook => this.setState({ savedBooks: this.state.savedBooks.filter(book => book._id !== deletedBook._id) }))
// .catch(err => console.error(err));
// } else {
// API.saveBook(book)
// .then(savedBook => this.setState({ savedBooks: this.state.savedBooks.concat([savedBook]) }))
// .catch(err => console.error(err));
// }
}
render() {
console.log(this.state.results)
return (
<div>
<h1>Google Books Search:</h1>
<form>
<input
placeholder="Enter title here"
value={this.search}
name="book"
type="text"
onChange={this.handleInputChange}
>
</input>
<button
type="submit"
onClick={this.handleFormSubmit}
>Search</button>
</form>
<h3>Results:</h3>
<Container>
<Row>
<CardColumns>
{this.state.results.map(result => (
// console.log(result.volumeInfo.imageLinks.thumbnail),
<Col>
<Card style={{ width: '190px' }}>
<Card.Img variant="top" src={result.volumeInfo.imageLinks.thumbnail} />
<Card.Body>
<Card.Title>{result.volumeInfo.title} by {result.volumeInfo.authors}</Card.Title>
<Card.Text style={{ fontSize: 13 }}>{result.volumeInfo.description}</Card.Text>
<Button variant="primary" href={result.volumeInfo.previewLink} target="_blank" style={{margin: '10px'}}>Preview Book</Button>
<Button variant="primary" onClick={() => this.handleSave(result)}>Save Book</Button>
</Card.Body>
</Card>
</Col>
))}
</CardColumns>
</Row>
</Container>
</div>
);
}
} |
JavaScript | class UriComponentToString extends expressionEvaluator_1.ExpressionEvaluator {
/**
* Initializes a new instance of the [UriComponentToString](xref:adaptive-expressions.UriComponentToString) class.
*/
constructor() {
super(expressionType_1.ExpressionType.UriComponentToString, UriComponentToString.evaluator(), returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary);
}
/**
* @private
*/
static evaluator() {
return functionUtils_1.FunctionUtils.apply((args) => decodeURIComponent(args[0]), functionUtils_1.FunctionUtils.verifyString);
}
} |
JavaScript | class Notification extends Widget{
constructor() {
super();
/**
* Notification container element.
*
* @property container
* @type {HTMLElement}
* @since 1.0.0
* @default HTMLDivElement
*/
this.container = document.createElement('div');
this.addClass('skyflow-notification-container');
Helper.addEvent(this.container, 'mouseover', ()=>{
clearTimeout(this.setTimeoutId);
});
Helper.addEvent(this.container, 'mouseout', ()=>{
this.autoHide(this.config.autoHide);
});
document.body.appendChild(this.container);
/**
* Notification close button part.
*
* @property CloseButton
* @type {WidgetPart}
* @since 1.0.0
*/
this.CloseButton = new WidgetPart(document.createElement('span'));
this.CloseButton.show().addClass('skyflow-notification-close-button');
this.CloseButton.addEvent('click', ()=>{
this.hide();
});
this.container.appendChild(this.CloseButton.this);
/**
* Notification header part.
*
* @property Header
* @type {WidgetPart}
* @since 1.0.0
*/
this.Header = new WidgetPart(document.createElement('div'));
this.Header.show().addClass('skyflow-notification-header');
this.container.appendChild(this.Header.this);
/**
* Notification body part.
*
* @property Body
* @type {WidgetPart}
* @since 1.0.0
*/
this.Body = new WidgetPart(document.createElement('div'));
this.Body.show().addClass('skyflow-notification-body');
this.container.appendChild(this.Body.this);
/**
* Notification configuration array.
*
* @property config
* @type {Object}
* @since 1.0.0
*/
this.config = {
/**
* Set if notification must be auto hide.
*
* @property config.autoHide
* @type {Boolean}
* @since 1.0.0
*/
autoHide: true,
/**
* Notification show duration time in ms.
*
* @property config.showDuration
* @type {Number}
* @since 1.0.0
*/
showDuration: 5000,
/**
* Notification events array.
*
* @property config.events
* @type {Object}
* @since 1.0.0
*/
events: {
/**
* Notification show event.
*
* @property config.events.show
* @type {Function}
* @since 1.0.0
* @default null
*/
show: null,
/**
* Notification hide event.
*
* @property config.events.hide
* @type {Function}
* @since 1.0.0
* @default null
*/
hide: null,
/**
* Notification success event.
*
* @property config.events.success
* @type {Function}
* @since 1.0.0
* @default null
*/
success: null,
/**
* Notification warning event.
*
* @property config.events.warning
* @type {Function}
* @since 1.0.0
* @default null
*/
warning: null,
/**
* Notification info event.
*
* @property config.events.info
* @type {Function}
* @since 1.0.0
* @default null
*/
info: null,
/**
* Notification error event.
*
* @property config.events.error
* @type {Function}
* @since 1.0.0
* @default null
*/
error: null,
},
};
this.setTimeoutId = null;
}
/**
* Triggers Notification auto hide feature.
*
* @method autoHide
* @param {Boolean} auto
* @since 1.0.0
* @return {Notification} Returns the current Notification object.
*/
autoHide(auto){
this.config.autoHide = auto;
if(!this.config.autoHide){
return this;
}
clearTimeout(this.setTimeoutId);
this.setTimeoutId = setTimeout(()=>{
this.hide();
}, this.config.showDuration);
return this;
}
/**
* Sets Notification show duration.
*
* @method showDuration
* @param {Number} duration Duration in ms.
* @since 1.0.0
* @return {Notification} Returns the current Notification object.
*/
showDuration(duration){
this.config.showDuration = duration;
return this;
}
/**
* Displays notification message.
*
* @method notify
* @param {String} type Type of notification like 'notify', 'success', 'error', ...
* @param {HTMLElement|String} header Notification header content.
* @param {HTMLElement|String} body Notification body content.
* @since 1.0.0
* @return {Notification} Returns the current Notification object.
*/
notify(type, header, body){
setTimeout(()=>{
this.addClass('skyflow-notification-is-shown');
this.addClass('skyflow-notification-'+type+'-state');
this.autoHide(this.config.autoHide);
}, 100);
if(Helper.isString(header)){
this.Header.html(header);
}
if(Helper.isElement(header)){
this.Header.addChild(header);
}
if(Helper.isString(body)){
this.Body.html(body);
}
if(Helper.isElement(body)){
this.Body.addChild(body);
}
if (this.config.events.show) {
this.config.events.show.apply(null, [this]);
}
if (this.config.events[type]) {
this.config.events[type].apply(null, [this]);
}
return this;
}
/**
* Displays success notification message.
*
* @method success
* @param {HTMLElement|String} body Notification body content.
* @param {HTMLElement|String} header Notification header content.
* @since 1.0.0
* @return {Notification} Returns the current Notification object.
*/
success(body, header = 'Success'){
return this.notify('success', header, body);
}
/**
* Displays warning notification message.
*
* @method warning
* @param {HTMLElement|String} body Notification body content.
* @param {HTMLElement|String} header Notification header content.
* @since 1.0.0
* @return {Notification} Returns the current Notification object.
*/
warning(body, header = 'Warning'){
return this.notify('warning', header, body);
}
/**
* Displays info notification message.
*
* @method info
* @param {HTMLElement|String} body Notification body content.
* @param {HTMLElement|String} header Notification header content.
* @since 1.0.0
* @return {Notification} Returns the current Notification object.
*/
info(body, header = 'Info'){
return this.notify('info', header, body);
}
/**
* Displays error notification message.
*
* @method error
* @param {HTMLElement|String} body Notification body content.
* @param {HTMLElement|String} header Notification header content.
* @since 1.0.0
* @return {Notification} Returns the current Notification object.
*/
error(body, header = 'Error'){
return this.notify('error', header, body);
}
/**
* Hides Notification.
*
* @method hide
* @since 1.0.0
* @return {Notification} Returns the current Notification object.
*/
hide(){
clearTimeout(this.setTimeoutId);
this.removeClass('skyflow-notification-is-shown');
if (this.config.events.hide) {
this.config.events.hide.apply(null, [this]);
}
return this;
}
/**
* Removes Tooltip container from DOM.
*
* @method destroy
* @since 1.0.0
* @return {Notification} Returns the current Notification object.
*/
destroy() {
if(this.container.parentNode){
this.container.parentNode.removeChild(this.container);
}
return this;
}
} |
JavaScript | class AjaxHelper {
/**
* Emulate the beginning of an AJAX request
*
* @function
* @static
* @param {String} [endpoint]
* @returns {undefined}
*/
static begin( endpoint ) {
Ember.run( () => {
if ( endpoint ) {
Ember.$( document ).trigger( 'ajaxSend', [ null, { url: endpoint } ] );
} else {
Ember.$( document ).trigger( 'ajaxStart' );
}
});
}
/**
* Emulate the conclusion of an AJAX request
*
* @function
* @static
* @param {String} [endpoint]
* @returns {undefined}
*/
static end( endpoint ) {
Ember.run( () => {
if ( endpoint ) {
Ember.$( document ).trigger( 'ajaxComplete', [ null, { url: endpoint } ] );
} else {
Ember.$( document ).trigger( 'ajaxStop' );
}
});
}
} |
JavaScript | class Client extends EventEmitter {
/**
* @param {ClientOptions} args Client options
*/
constructor(args = {}) {
super();
/**
* The config of the client
* @type {ClientOptions}
*/
this.config = Client.mergeDefault(ClientOptions, args);
/**
* Whether the client is ready or not
* @type {boolean}
*/
this.isReady = false;
/**
* The default party member meta of the client
* @type {?Object}
* @private
*/
this.lastMemberMeta = this.config.memberMeta;
/**
* The user of the client
* @type {?ClientUser}
*/
this.user = undefined;
/**
* The party that the client is currently in
* @type {?Party}
*/
this.party = undefined;
/**
* The authentication manager of the client
* @type {Authenticator}
* @private
*/
this.Auth = new Authenticator(this);
/**
* The HTTP manager of the client
* @type {Http}
* @private
*/
this.Http = new Http(this);
/**
* The XMPP manager of the client
* @type {Xmpp}
* @private
*/
this.Xmpp = new Xmpp(this);
/**
* The friends cache of the client's user
* @type {List}
*/
this.friends = new List();
/**
* The pending friends cache of the client's user
* @type {List}
*/
this.pendingFriends = new List();
/**
* The blocked friends cache of the client's user
* @type {List}
*/
this.blockedFriends = new List();
/**
* The client's party lock
* Used for delaying all party-related xmpp events while changes to client's party are made
* @typedef {Object} PartyLock
* @property {boolean} active Indicates if the party lock is active
* @property {function} wait Sleep until party lock is no longer active
* @private
*/
this.partyLock = {
active: false,
wait: () =>
new Promise((res) => {
if (!this.partyLock.active) res();
const waitInterval = setInterval(() => {
if (!this.partyLock.active) {
clearInterval(waitInterval);
res();
}
}, 100);
}),
};
/**
* The client's reauthentication lock
* Used for delaying all Http requests while the client is reauthenticating
* @typedef {Object} ReauthLock
* @property {boolean} active Indicates if the reauthentication lock is active
* @property {function} wait Sleep until reauthentication lock is no longer active
* @private
*/
this.reauthLock = {
active: false,
wait: () =>
new Promise((res) => {
if (!this.reauthLock.active) res();
const waitInterval = setInterval(() => {
if (!this.reauthLock.active) {
clearInterval(waitInterval);
res();
}
}, 100);
}),
};
/**
* Parses an error
* @param {Object|string} error The error to be parsed
* @private
*/
this.parseError = (error) =>
typeof error === "object" ? JSON.stringify(error) : error;
/**
* Converts an object's keys to camel case
* @param {Object} obj The object to be converted
* @private
*/
this.makeCamelCase = Client.makeCamelCase;
onExit(async (callback) => {
await this.logout();
callback();
});
}
// -------------------------------------GENERAL-------------------------------------
/**
* Initiates client's login process
* @returns {Promise<void>}
*/
async login() {
const auth = await this.Auth.authenticate();
if (!auth.success)
throw new Error(
`Authentification failed: ${this.parseError(auth.response)}`
);
this.tokenCheckInterval = setInterval(
() => this.Auth.refreshToken(true),
10 * 60000
);
const clientInfo = await this.Http.send(
false,
"GET",
`${Endpoints.ACCOUNT_ID}/${this.Auth.account.id}`,
`bearer ${this.Auth.auths.token}`
);
if (!clientInfo.success)
throw new Error(
`Client account lookup failed: ${this.parseError(
clientInfo.response
)}`
);
this.user = new ClientUser(this, clientInfo.response);
await this.updateCache();
this.Xmpp.setup();
const xmpp = await this.Xmpp.connect();
if (!xmpp.success)
throw new Error(
`XMPP-client connecting failed: ${this.parseError(
xmpp.response
)}`
);
await this.initParty();
this.isReady = true;
this.emit("ready");
}
/**
* Disconnects the client
* @returns {Promise<void>}
*/
async logout() {
if (this.tokenCheckInterval) clearInterval(this.tokenCheckInterval);
if (this.Xmpp.connected) await this.Xmpp.disconnect();
if (this.party) await this.party.leave(false);
if (this.Auth.auths.token)
await this.Http.send(
false,
"DELETE",
`${Endpoints.OAUTH_TOKEN_KILL}/${this.Auth.auths.token}`,
`bearer ${this.Auth.auths.token}`
);
this.Auth.auths.token = undefined;
this.Auth.auths.expires_at = undefined;
this.isReady = false;
}
/**
* Restarts the client
* @returns {Promise<void>}
*/
async restart() {
await this.logout();
await this.login();
}
/**
* Refreshes the client's friends (including pending and blocked)
* @returns {Promise<void>}
* @private
*/
async updateCache() {
const [rawFriends, friendsSummary] = await Promise.all([
this.Http.send(
true,
"GET",
`${Endpoints.FRIENDS}/public/friends/${this.user.id}?includePending=true`,
`bearer ${this.Auth.auths.token}`
),
this.Http.send(
true,
"GET",
`${Endpoints.FRIENDS}/v1/${this.user.id}/summary?displayNames=true`,
`bearer ${this.Auth.auths.token}`
),
]);
if (!rawFriends.success)
throw new Error(
`Cannot update friend cache: ${this.parseError(
rawFriends.response
)}`
);
if (!friendsSummary.success)
throw new Error(
`Cannot update friend cache: ${this.parseError(
friendsSummary.response
)}`
);
this.friends.clear();
this.blockedFriends.clear();
this.pendingFriends.clear();
for (const rawFriend of rawFriends.response) {
if (rawFriend.status === "ACCEPTED")
this.friends.set(rawFriend.accountId, rawFriend);
else if (rawFriend.status === "PENDING")
this.pendingFriends.set(rawFriend.accountId, rawFriend);
else if (rawFriend.status === "BLOCKED")
this.blockedFriends.set(rawFriend.accountId, rawFriend);
}
for (const friendedFriend of friendsSummary.response.friends) {
const friend = this.friends.get(friendedFriend.accountId);
this.friends.set(
friendedFriend.accountId,
new Friend(this, { ...friend, ...friendedFriend })
);
}
for (const blockedFriend of friendsSummary.response.blocklist) {
const friend = this.blockedFriends.get(blockedFriend.accountId);
this.blockedFriends.set(
blockedFriend.accountId,
new Friend(this, { ...friend, ...blockedFriend, blocked: true })
);
}
for (const incomingFriend of friendsSummary.response.incoming) {
const friend = this.pendingFriends.get(incomingFriend.accountId);
this.pendingFriends.set(
incomingFriend.accountId,
new PendingFriend(this, {
...friend,
...incomingFriend,
direction: "INCOMING",
})
);
}
for (const outgoingFriend of friendsSummary.response.outgoing) {
const friend = this.pendingFriends.get(outgoingFriend.accountId);
this.pendingFriends.set(
outgoingFriend.accountId,
new PendingFriend(this, {
...friend,
...outgoingFriend,
direction: "OUTGOING",
})
);
}
}
/**
* Initiates a party
* @param {boolean} create Whether to create a new one after leaving the current one
* @returns {Promise<void>}
* @private
*/
async initParty(create = true) {
const party = await Party.LookupSelf(this);
if (!create) this.party = party;
else if (party) await party.leave(false);
if (create) await Party.Create(this);
}
// -------------------------------------UTIL-------------------------------------
/**
* Debug a message via the debug function provided in the client's config (if provided)
* @param {string} message The message that will be debugged
* @returns {void}
* @private
*/
debug(message) {
if (this.config.debug) this.config.debug(message);
}
/**
* Convert an object's keys to camel case
* @param {Object} obj The object that will be converted
* @returns {Object} The converted object
* @private
*/
static makeCamelCase(obj) {
const returnObj = {};
for (const key of Object.keys(obj)) {
returnObj[
key
.split("_")
.map((s, i) => {
if (i > 0)
return `${s.charAt(0).toUpperCase()}${s.slice(1)}`;
return s;
})
.join("")
] = obj[key];
}
return returnObj;
}
/**
* Sleep until an event is emitted
* @param {string|symbol} event The event will be waited for
* @param {number} [timeout=5000] The timeout (in milliseconds)
* @param {function} [filter] The filter for the event
* @returns {Promise<Object>}
*/
waitForEvent(event, timeout = 5000, filter) {
return new Promise((res, rej) => {
this.once(event, (eventData) => {
if (!filter || filter(eventData)) res(eventData);
});
setTimeout(() => rej(new Error("Event timeout exceed")), timeout);
});
}
/**
* Sleep for the provided milliseconds
* @param {number} timeout The timeout (in milliseconds)
* @returns {Promise<void>}
* @private
*/
static sleep(timeout) {
return new Promise((res) => setTimeout(() => res(), timeout));
}
/**
* Display a console prompt
* @param {string} question The text that will be prompted
* @returns {Promise<string>} The received answer
* @private
*/
static consoleQuestion(question) {
const itf = createInterface(process.stdin, process.stdout);
return new Promise((res) =>
itf.question(question, (answer) => {
itf.close();
res(answer);
})
);
}
/**
* Sleep until the client is ready
* @param {number} [timeout=20000] The timeout (in milliseconds)
*/
waitUntilReady(timeout = 20000) {
return new Promise((res, rej) => {
if (this.isReady) res();
const waitInterval = setInterval(() => {
if (this.isReady) {
clearInterval(waitInterval);
res();
}
}, 250);
setTimeout(
() => rej(new Error("Waiting for ready timeout exceed")),
timeout
);
});
}
/**
* Merges a default object with a given one
* @param {Object} def The default object
* @param {Object} given The given object
* @returns {Object} The merged objects
* @private
*/
static mergeDefault(def, given) {
if (!given) return def;
for (const key in def) {
if (
!Object.prototype.hasOwnProperty.call(given, key) ||
given[key] === undefined
) {
given[key] = def[key];
} else if (given[key] === Object(given[key])) {
given[key] = Client.mergeDefault(def[key], given[key]);
}
}
return given;
}
/**
* Merges a default object with a given one
* @param {Object} def The default object
* @param {Object} given The given object
* @returns {Object} The merged objects
* @private
*/
mergeDefault(def, given) {
return Client.mergeDefault(def, given);
}
// -------------------------------------ACCOUNT-------------------------------------
/**
* Fetches an Epic Games account
* @param {string|Array<string>} query The id, name or email of the account(s) you want to fetch
* @returns {Promise<User>|Promise<Array<User>>} The fetched account(s)
* @example
* client.getProfile('aabbccddeeff00112233445566778899');
*/
async getProfile(query) {
let user;
if (typeof query === "string") {
if (query.length === 32)
user = await this.Http.send(
true,
"GET",
`${Endpoints.ACCOUNT_ID}/${query}`,
`bearer ${this.Auth.auths.token}`
);
else if (/.*@.*\..*/.test(query))
user = await this.Http.send(
true,
"GET",
`${Endpoints.ACCOUNT_EMAIL}/${encodeURI(query)}`,
`bearer ${this.Auth.auths.token}`
);
else
user = await this.Http.send(
true,
"GET",
`${Endpoints.ACCOUNT_DISPLAYNAME}/${encodeURI(query)}`,
`bearer ${this.Auth.auths.token}`
);
return user.success ? new User(this, user.response) : undefined;
}
if (query instanceof Array) {
const ids = [];
const names = [];
const emails = [];
for (const userQuery of query) {
if (userQuery.length === 32) ids.push(userQuery);
else if (/.*@.*\..*/.test(userQuery)) emails.push(userQuery);
else names.push(userQuery);
}
const nameResults = (
await Promise.all(
names.map((name) =>
this.Http.send(
true,
"GET",
`${Endpoints.ACCOUNT_DISPLAYNAME}/${encodeURI(
name
)}`,
`bearer ${this.Auth.auths.token}`
)
)
)
)
.filter((name) => name.success)
.map((name) => new User(this, name.response));
const emailResults = (
await Promise.all(
emails.map((email) =>
this.Http.send(
true,
"GET",
`${Endpoints.ACCOUNT_EMAIL}/${encodeURI(email)}`,
`bearer ${this.Auth.auths.token}`
)
)
)
)
.filter((email) => email.success)
.map((email) => new User(this, email.response));
let idResults = await this.Http.send(
true,
"GET",
`${Endpoints.ACCOUNT_MULTIPLE}?accountId=${ids.join(
"&accountId="
)}`,
`bearer ${this.Auth.auths.token}`
);
if (idResults.success)
idResults = idResults.response.map(
(idr) => new User(this, idr)
);
else idResults = [];
const results = [];
nameResults.forEach((nr) => results.push(nr));
emailResults.forEach((er) => results.push(er));
idResults.forEach((ir) => results.push(ir));
return results;
}
throw new TypeError(
`${typeof query} is not a valid account query type`
);
}
/**
* Changes the presence status
* @param {string} [status] The status message; can be null/undefined if you want to reset it
* @param {string} [to] The display name or the id of the friend; can be undefined if you want to update the presence status for all friends
* @returns {Promise<void>}
*/
setStatus(status, to) {
let id;
if (to) {
const cachedFriend = this.friends.find(
(f) => f.id === to || f.displayName === to
);
if (!cachedFriend)
throw new Error(
`Failed sending a status to ${to}: Friend not existing`
);
id = this.Xmpp.sendStatus(
status,
`${cachedFriend.id}@${Endpoints.EPIC_PROD_ENV}`
);
} else {
this.config.status = status;
id = this.Xmpp.sendStatus(status);
}
return new Promise((res, rej) => {
this.Xmpp.stream.on(`presence#${id}:sent`, () => res());
setTimeout(
() =>
rej(
new Error(
"Failed sending a status: Status timeout of 20000ms exceeded"
)
),
20000
);
});
}
// -------------------------------------FRIENDS-------------------------------------
/**
* Sends / accepts a friend request to an Epic Games user
* @param {string} user The id, name or email of the user
* @returns {Promise<void>}
*/
async addFriend(user) {
let userId;
if (user.length === 32 && !user.includes("@")) userId = user;
else {
const lookedUpUser = await this.getProfile(user);
if (!lookedUpUser)
throw new Error(
`Adding ${user} as a friend failed: Account not found`
);
userId = lookedUpUser.id;
}
const userRequest = await this.Http.send(
true,
"POST",
`${Endpoints.FRIEND_ADD}/${this.user.id}/${userId}`,
`bearer ${this.Auth.auths.token}`
);
if (!userRequest.success)
throw new Error(
`Adding ${userId} as a friend failed: ${this.parseError(
userRequest.response
)}`
);
}
/**
* Removes a friend or reject an user's friend request
* @param {string} user The id, name or email of the user
* @returns {Promise<void>}
*/
async removeFriend(user) {
let userId;
if (user.length === 32 && !user.includes("@")) userId = user;
else {
const lookedUpUser = await this.getProfile(user);
if (!lookedUpUser)
throw new Error(
`Removing ${user} as a friend failed: Account not found`
);
userId = lookedUpUser.id;
}
const userRequest = await this.Http.send(
true,
"DELETE",
`${Endpoints.FRIEND_DELETE}/${this.user.id}/friends/${userId}`,
`bearer ${this.Auth.auths.token}`
);
if (!userRequest.success)
throw new Error(
`Removing ${user} as a friend failed: ${this.parseError(
userRequest.response
)}`
);
}
/**
* Blocks a friend
* @param {string} friend The id, name or email of the friend
* @returns {Promise<void>}
*/
async blockFriend(friend) {
const cachedFriend = this.friends.find(
(f) => f.id === friend || f.displayName === friend
);
if (!cachedFriend)
throw new Error(`Blocking ${friend} failed: Friend not existing`);
const blockListUpdate = await this.Http.send(
true,
"POST",
`${Endpoints.FRIEND_BLOCK}/${this.user.id}/${cachedFriend.id}`,
`bearer ${this.Auth.auths.token}`
);
if (!blockListUpdate.success)
throw new Error(
`Blocking ${friend} failed: ${this.parseError(
blockListUpdate.response
)}`
);
}
/**
* Unblocks a friend
* @param {string} friend The id, name or email of the friend
* @returns {Promise<void>}
*/
async unblockFriend(friend) {
const cachedBlockedFriend = this.blockedFriends.find(
(f) => f.id === friend || f.displayName === friend
);
if (!cachedBlockedFriend)
throw new Error(
`Unblocking ${friend} failed: User not in the blocklist`
);
const blockListUpdate = await this.Http.send(
true,
"DELETE",
`${Endpoints.FRIEND_BLOCK}/${this.user.id}/${cachedBlockedFriend.id}`,
`bearer ${this.Auth.auths.token}`
);
if (!blockListUpdate.success)
throw new Error(
`Unblocking ${friend} failed: ${this.parseError(
blockListUpdate.response
)}`
);
}
/**
* Sends a message to a friend
* @param {string} friend The id or name of the friend
* @param {string} message The message
* @returns {Promise<FriendMessage>} The sent friend message
*/
async sendFriendMessage(friend, message) {
if (!message)
throw new Error(
`Failed sending a friend message to ${friend}: Cannot send an empty message`
);
const cachedFriend = this.friends.find(
(f) => f.id === friend || f.displayName === friend
);
if (!cachedFriend)
throw new Error(
`Failed sending a friend message to ${friend}: Friend not existing`
);
const id = this.Xmpp.stream.sendMessage({
to: `${cachedFriend.id}@${Endpoints.EPIC_PROD_ENV}`,
type: "chat",
body: message,
});
return new Promise((res, rej) => {
this.Xmpp.stream.once(`message#${id}:sent`, () =>
res(
new FriendMessage(this, {
body: message,
author: this.user,
})
)
);
setTimeout(
() =>
rej(
new Error(
`Failed sending a friend message to ${friend}: Message timeout of 20000ms exceeded`
)
),
20000
);
});
}
/**
* Sends a party invitation to a friend
* @param {string} friend The id or name of the friend
* @returns {Promise<SentPartyInvitation>}
*/
async invite(friend) {
return this.party.invite(friend);
}
// -------------------------------------BATTLE ROYALE-------------------------------------
/**
* Fetches news for a gamemode
* @param {Gamemode} mode The gamemode
* @param {Language} language The language
* @returns {Promise<Array>}
*/
async getNews(
mode = Enums.Gamemode.BATTLE_ROYALE,
language = Enums.Language.ENGLISH
) {
if (!Object.values(Enums.Gamemode).includes(mode))
throw new Error(
`Fetching news failed: ${mode} is not a valid gamemode! Use the enum`
);
const news = await this.Http.send(
false,
"GET",
`${Endpoints.BR_NEWS}?lang=${language}`
);
if (!news.success)
throw new Error(
`Fetching news failed: ${this.parseError(news.response)}`
);
if (mode === Enums.Gamemode.BATTLE_ROYALE)
return news.response[`${mode}news`].news.motds;
return news.response[`${mode}news`].news.messages;
}
/**@param {Gamemode} platform The gamemode
* @param {Language} type The language
* @returns {Promise<Array>}*/
async leaderboard(platform, type = Enums.Gamemode.BATTLE_ROYALE) {
if (!Object.values(Enums.Gamemode.BATTLE_ROYALE).includes(type))
throw new Error(
`Fetching news failed: ${type} is not a valid gamemode! Use the enum`
);
if (!(type == SOLO || type == DUO || type == SQUAD)) {
reject({
message:
"Please precise a good type FortniteApi.SOLO/FortniteApi.DUO/FortniteApi.SQUAD",
});
return;
}
const leaderboard = await this.Http.send(
false,
"GET",
` https://fortnite-public-service-prod11.ol.epicgames.com/fortnite/api/leaderboards/type/global/stat/br_placetop1_${platform}_m0${type}/window/weekly?ownertype=1&pageNumber=0&itemsPerPage=50`
);
return leaderboard;
// https://fortnite-public-service-prod11.ol.epicgames.com/fortnite/api/leaderboards/type/global/stat/br_placetop1_${plat}_m0${groupType}/window/weekly?ownertype=1&pageNumber=0&itemsPerPage=50
}
/**
* Fetches v2 stats for one or multiple players
* @param {string} user The id, name or email of the user(s)
* @param {number} [startTime] The timestamp to start fetching stats from; can be null/undefined for lifetime
* @param {number} [endTime] The timestamp to stop fetching stats from; can be undefined for lifetime
* @returns {Promise<Object>}
*/
async getBRStats(user, startTime, endTime) {
let userId;
if (user.length === 32 && !user.includes("@")) userId = user;
else {
const lookedUpUser = await this.getProfile(user);
if (!lookedUpUser)
throw new Error(
`Fetching ${user}'s stats failed: Account not found`
);
userId = lookedUpUser.id;
}
const params = [];
if (startTime) params.push(`startTime=${startTime}`);
if (endTime) params.push(`startTime=${endTime}`);
const stats = await this.Http.send(
true,
"GET",
`${Endpoints.BR_STATS_V2}/account/${userId}${
params[0] ? `?${params.join("&")}` : ""
}`,
`bearer ${this.Auth.auths.token}`
);
if (!stats.success)
throw new Error(
`Fetching ${user}'s stats failed: ${this.parseError(
stats.response
)}`
);
return stats.response;
}
/**
* Lookups for a creator code
* @param {string} code The creator code
* @param {boolean} showSimilar Whether an array with similar creator codes should be returned
* @returns {Promise<CreatorCode>|Promise<Array<CreatorCode>>}
*/
async getCreatorCode(code, showSimilar = false) {
const codeRes = await this.Http.send(
false,
"GET",
`${Endpoints.BR_SAC_SEARCH}?slug=${code}`
);
if (!codeRes.success)
throw new Error(
`Fetching the creator code ${code} failed: ${this.parseError(
codeRes.response
)}`
);
const codes = codeRes.response.filter((c) =>
showSimilar ? c : c.slug === code
);
const parsedCodes = [];
for (const ccode of codes) {
const owner = await this.getProfile(ccode.id);
parsedCodes.push(new CreatorCode(this, { ...ccode, owner }));
}
return showSimilar ? parsedCodes : parsedCodes[0];
}
/**
* Fetches the current Battle Royale store
* @param {Language} language The language
* @returns {Promise<Object>} The Battle Royale store
*/
async getBRStore(language = Enums.Language.ENGLISH) {
const shop = await this.Http.send(
true,
"GET",
`${Endpoints.BR_STORE}?lang=${language}`,
`bearer ${this.Auth.auths.token}`
);
if (!shop.success)
throw new Error(
`Fetching shop failed: ${this.parseError(shop.response)}`
);
return shop.response;
}
/**
* Fetch the current Battle Royale event flags
* @param {Language} language The language
* @returns {Promise<Object>} The Battle Royale event flags
*/
async getBREventFlags(language = Enums.Language.ENGLISH) {
const eventFlags = await this.Http.send(
true,
"GET",
`${Endpoints.BR_EVENT_FLAGS}?lang=${language}`,
`bearer ${this.Auth.auths.token}`
);
if (!eventFlags.success)
throw new Error(
`Fetching challenges failed: ${this.parseError(
eventFlags.response
)}`
);
return eventFlags.response;
}
/**
* Fetch the current Fortnite server status
* @returns {Promise<Object>} The server status
*/
async getFortniteServerStatus() {
const serverStatus = await this.Http.send(
true,
"GET",
Endpoints.BR_SERVER_STATUS,
`bearer ${this.Auth.auths.token}`
);
if (!serverStatus.success)
throw new Error(
`Fetching server status failed: ${this.parseError(
serverStatus.response
)}`
);
return serverStatus.response;
}
/**
* Fetch the current Fortnite tournaments
* @param {string} region The region eg. EU, ASIA, NAE
* @param {boolean} showPastEvents Whether to return past events
* @returns {Promise<Object>} The tournaments
*/
async getTournaments(region = "EU", showPastEvents = false) {
const events = await this.Http.send(
true,
"GET",
`${Endpoints.BR_TOURNAMENTS}api/v1/events/Fortnite/data/${this.user.id}?region=${region}&showPastEvents=${showPastEvents}`,
`bearer ${this.Auth.auths.token}`
);
if (!events.success)
throw new Error(
`Fetching events failed: ${this.parseError(events.response)}`
);
return events.response.events;
}
/**
* Fetch a Fortnite tournament window by id
* @param {string} eventId The event id (eg epicgames_OnlineOpen_Week2_ASIA)
* @param {string} windowId The window id (eg OnlineOpen_Week2_ASIA_Event2)
* @param {boolean} showLiveSessions Whether to show live sessions
* @param {number} page The starting page
* @returns {Promise<Object>} The tournament window
*/
async getTournamentWindow(
eventId,
windowId,
showLiveSessions = false,
page = 0
) {
const window = await this.Http.send(
true,
"GET",
`${Endpoints.BR_TOURNAMENTS}api/v1/leaderboards/Fortnite/${eventId}/${windowId}/${this.user.id}?page=${page}&showLiveSessions=${showLiveSessions}`,
`bearer ${this.Auth.auths.token}`
);
if (!window.success)
throw new Error(
`Fetching events failed: ${this.parseError(window.response)}`
);
return window.response;
}
} |
JavaScript | class Dropdown extends React.PureComponent {
constructor() {
super(...arguments);
_defineProperty(this, "ref", React.createRef());
_defineProperty(this, "handleClick", event => {
const {
current
} = this.ref;
if (current && current.contains(event.target)) {
if (this.props.onClickInside) {
this.props.onClickInside(event);
}
return;
}
if (this.props.onClickOutside) {
this.props.onClickOutside(event);
}
});
}
componentDidMount() {
if (this.props.visible) {
document.addEventListener('click', this.handleClick, true);
}
}
componentDidUpdate(prevProps) {
if (prevProps.visible !== this.props.visible) {
if (this.props.visible) {
document.addEventListener('click', this.handleClick, true);
} else {
document.removeEventListener('click', this.handleClick, true);
}
}
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClick, true);
}
render() {
const _this$props = this.props,
{
cx,
children,
fixed,
onBlur,
onFocus,
tabIndex,
zIndex
} = _this$props,
props = _objectWithoutPropertiesLoose(_this$props, ["cx", "children", "fixed", "onBlur", "onFocus", "tabIndex", "zIndex", "visible", "onClickOutside", "styles"]);
const style = _extends({
position: fixed ? 'fixed' : 'absolute',
zIndex: zIndex || 'auto'
}, props); // Set top by default if neither are defined
if (!('bottom' in props) && !('top' in props)) {
style.top = '100%';
} // Set left by default if neither are defined
if (!('left' in props) && !('right' in props)) {
style.left = 0;
}
return React.createElement("div", {
ref: this.ref,
className: cx(style),
tabIndex: tabIndex,
onBlur: onBlur,
onFocus: onFocus
}, children);
}
} |
JavaScript | class StdoutIterator extends output_iterator_1.default {
constructor(writeCallback) {
super();
this.writeCallback = writeCallback;
this.pretty = false;
}
/**
* Whether to output the JSON with pretty indentation and newlines.
*
* @param polarity boolean
*/
setPretty(polarity) {
this.pretty = polarity;
}
/**
* Write message to STDOUT.
*
* @param message TapjawMessage
*/
async outputMessage(message) {
const json = JSON.stringify(message, null, this.pretty ? 2 : undefined);
if (!json) {
throw new tapjaw_iterator_1.TapjawIteratorError('message could not be parsed into JSON.');
}
/**
* Write JSON to stdout buffer.
*/
this.writeCallback.write(`${json}\n`);
}
} |
JavaScript | class MetaDataContract extends models['NameAndUserDataContract'] {
/**
* Create a MetaDataContract.
* @property {string} [recognitionModel] Possible values include:
* 'recognition_01', 'recognition_02'. Default value: 'recognition_01' .
*/
constructor() {
super();
}
/**
* Defines the metadata of MetaDataContract
*
* @returns {object} metadata of MetaDataContract
*
*/
mapper() {
return {
required: false,
serializedName: 'MetaDataContract',
type: {
name: 'Composite',
className: 'MetaDataContract',
modelProperties: {
name: {
required: false,
serializedName: 'name',
constraints: {
MaxLength: 128
},
type: {
name: 'String'
}
},
userData: {
required: false,
serializedName: 'userData',
constraints: {
MaxLength: 16384
},
type: {
name: 'String'
}
},
recognitionModel: {
required: false,
nullable: false,
serializedName: 'recognitionModel',
defaultValue: 'recognition_01',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class Animator
{
/**
* Create the animator.
* @param {*} target Any object you want to animate.
*/
constructor(target)
{
this._target = target;
this._fromValues = {};
this._toValues = {};
this._progress = 0;
this._onFinish = null;
this._smoothDamp = false;
this._repeats = false;
this._repeatsWithReverseAnimation = false;
this._isInAutoUpdate = false;
this._originalFrom = null;
this._originalTo = null;
this._originalRepeats = null;
/**
* Speed factor to multiply with delta every time this animator updates.
*/
this.speedFactor = 1;
}
/**
* Update this animator with a given delta time.
* @param {Number} delta Delta time to progress this animator by.
*/
update(delta)
{
// if already done, skip
if (this._progress >= 1) {
return;
}
// apply speed factor and update progress
delta *= this.speedFactor;
this._progress += delta;
// did finish?
if (this._progress >= 1) {
// make sure don't overflow
this._progress = 1;
// trigger finish method
if (this._onFinish) {
this._onFinish();
}
}
// update values
for (let key in this._toValues) {
// get key as parts and to-value
let keyParts = this._toValues[key].keyParts;
let toValue = this._toValues[key].value;
// get from value
let fromValue = this._fromValues[key];
// if from not set, get default
if (fromValue === undefined) {
this._fromValues[key] = fromValue = this._getValueFromTarget(keyParts);
if (fromValue === undefined) {
throw new Error(`Animator issue: missing origin value for key '${key}' and property not found in target object.`);
}
}
// get lerp factor
let a = (this._smoothDamp && this._progress < 1) ? (this._progress * (1 + 1 - this._progress)) : this._progress;
// calculate new value
let newValue = null;
if (typeof fromValue === 'number') {
newValue = lerp(fromValue, toValue, a);
}
else if (fromValue.constructor.lerp) {
newValue = fromValue.constructor.lerp(fromValue, toValue, a);
}
else {
throw new Error(`Animator issue: from-value for key '${key}' is not a number, and its class type don't implement a 'lerp()' method!`);
}
// set new value
this._setValueToTarget(keyParts, newValue);
}
// if repeating, reset progress
if (this._repeats && this._progress >= 1) {
if (typeof this._repeats === 'number') { this._repeats--; }
this._progress = 0;
if (this._repeatsWithReverseAnimation ) {
this.flipFromAndTo();
}
}
}
/**
* Get value from target object.
* @private
* @param {Array<String>} keyParts Key parts broken by dots.
*/
_getValueFromTarget(keyParts)
{
// easy case - get value when key parts is just one component
if (keyParts.length === 1) {
return this._target[keyParts[0]];
}
// get value for path with parts
function index(obj,i) {return obj[i]}
return keyParts.reduce(index, this._target);
}
/**
* Set value in target object.
* @private
* @param {Array<String>} keyParts Key parts broken by dots.
*/
_setValueToTarget(keyParts, value)
{
// easy case - set value when key parts is just one component
if (keyParts.length === 1) {
this._target[keyParts[0]] = value;
return;
}
// set value for path with parts
function index(obj,i) {return obj[i]}
let parent = keyParts.slice(0, keyParts.length - 1).reduce(index, this._target);
parent[keyParts[keyParts.length - 1]] = value;
}
/**
* Make sure a given value is legal for the animator.
* @private
*/
_validateValueType(value)
{
return (typeof value === 'number') || (value && value.constructor && value.constructor.lerp);
}
/**
* Set a method to run when animation ends.
* @param {Function} callback Callback to invoke when done.
* @returns {Animator} this.
*/
then(callback)
{
this._onFinish = callback;
return this;
}
/**
* Set smooth damp.
* If true, lerping will go slower as the animation reach its ending.
* @param {Boolean} enable set smooth damp mode.
* @returns {Animator} this.
*/
smoothDamp(enable)
{
this._smoothDamp = enable;
return this;
}
/**
* Set if the animator should repeat itself.
* @param {Boolean|Number} enable false to disable repeating, true for endless repeats, or a number for limited number of repeats.
* @param {Boolean} reverseAnimation if true, it will reverse animation to repeat it instead of just "jumping" back to starting state.
* @returns {Animator} this.
*/
repeats(enable, reverseAnimation)
{
this._originalRepeats = this._repeats = enable;
this._repeatsWithReverseAnimation = Boolean(reverseAnimation);
return this;
}
/**
* Set 'from' values.
* You don't have to provide 'from' values, when a value is not set the animator will just take whatever was set in target when first update is called.
* @param {*} values Values to set as 'from' values.
* Key = property name in target (can contain dots for nested), value = value to start animation from.
* @returns {Animator} this.
*/
from(values)
{
for (let key in values) {
if (!this._validateValueType(values[key])) {
throw new Error("Illegal value type to use with Animator! All values must be either numbers, or a class instance that has a static lerp() method.");
}
this._fromValues[key] = values[key];
}
this._originalFrom = null;
return this;
}
/**
* Set 'to' values, ie the result when animation ends.
* @param {*} values Values to set as 'to' values.
* Key = property name in target (can contain dots for nested), value = value to start animation from.
* @returns {Animator} this.
*/
to(values)
{
for (let key in values) {
if (!this._validateValueType(values[key])) {
throw new Error("Illegal value type to use with Animator! All values must be either numbers, or a class instance that has a static lerp() method.");
}
this._toValues[key] = {keyParts: key.split('.'), value: values[key]};
}
this._originalTo = null;
return this;
}
/**
* Flip between the 'from' and the 'to' states.
*/
flipFromAndTo()
{
let newFrom = {};
let newTo = {};
if (!this._originalFrom) { this._originalFrom = this._fromValues; }
if (!this._originalTo) { this._originalTo = this._toValues; }
for (let key in this._toValues) {
newFrom[key] = this._toValues[key].value;
newTo[key] = {keyParts: key.split('.'), value: this._fromValues[key]};
}
this._fromValues = newFrom;
this._toValues = newTo;
}
/**
* Make this Animator update automatically with the gameTime delta time.
* Note: this will change the speedFactor property.
* @param {Number} seconds Animator duration time in seconds.
* @returns {Animator} this.
*/
duration(seconds)
{
this.speedFactor = 1 / seconds;
return this;
}
/**
* Reset animator progress.
* @returns {Animator} this.
*/
reset()
{
if (this._originalFrom) { this._fromValues = this._originalFrom; }
if (this._originalTo) { this._toValues = this._originalTo; }
if (this._originalRepeats !== null) { this._repeats = this._originalRepeats; }
this._progress = 0;
return this;
}
/**
* Make this Animator update automatically with the gameTime delta time, until its done.
* @returns {Animator} this.
*/
play()
{
if (this._isInAutoUpdate) {
return;
}
_autoAnimators.push(this);
this._isInAutoUpdate = true;
return this;
}
/**
* Get if this animator finished.
* @returns {Boolean} True if animator finished.
*/
get ended()
{
return this._progress >= 1;
}
/**
* Update all auto animators.
* @private
* @param {Number} delta Delta time in seconds.
*/
static updateAutos(delta)
{
for (let i = _autoAnimators.length - 1; i >= 0; --i) {
_autoAnimators[i].update(delta);
if (_autoAnimators[i].ended) {
_autoAnimators[i]._isInAutoUpdate = false;
_autoAnimators.splice(i, 1);
}
}
}
} |
JavaScript | class BaseStore extends BaseClass {
constructor() {
this.data = {};
this.listViewComponent = null;
this.formViewComponent = null;
var service = this.getService();
if(!service){
this.initialized = true;
return;
}
if (service instanceof ApiService) {
this.api = service;
} else {
this.api = new ApiService(service);
}
}
emitChange(delay = false) {
setTimeout(() => {
this.getData().then(data => {
EventManager.emit(this.getFqn(), data);
});
}, delay);
}
getService() {
// Override to implement
// return '/App/Module/Service'
return null;
}
setInitialData(data) {
// Unset all object properties but keep an object reference
Object.keys(this.data).map((key) => {
delete this.data[key];
});
// Assign response data to the original object reference
Object.assign(this.data, data);
this.emitChange();
return this;
}
getInitialData() {
return Q.when(null);
}
onAction(action, callback) {
var meta = {
listenerType: 'store',
listeningTo: 'action',
listenerName: this.getFqn()
};
EventManager.addListener(action, callback.bind(this), meta);
}
onStore(store, callback) {
var meta = {
listenerType: 'store',
listeningTo: 'store',
listenerName: this.getFqn()
};
EventManager.addListener(store, callback, meta);
}
init() {
// Override to implement initial setup code
}
getData(conditions = null) {
if (!conditions) {
return Tools.createPromise(this.data);
}
if (!conditions instanceof Object) {
throw new Error('Conditions must be in form of an Object! ' + typeof conditions + ' given.');
}
if (this.data instanceof Array) {
return Tools.createPromise(DataFilter.filter(this.data, conditions));
}
return Tools.createPromise(null);
}
/**
* Get router parameter
* @param name
* @returns String|null
*/
getParam(name) {
return Router.getParam(name);
}
/**
* @param Object options filters, sorters, limit, page
* @returns {*}
*/
crudList(options = {}) {
var defaultOptions = {
filters: {},
sorters: {},
limit: 100,
page: 1,
emit: true,
push: true
};
// Final config
var config = {};
// Merge default options with options from arguments
Object.assign(config, defaultOptions, options);
return this.api.crudList(config).then(apiResponse => {
if (!apiResponse.isError()) {
if (config.push) {
// Unset all object properties but keep an object reference
Object.keys(this.data).map((key) => {
delete this.data[key];
});
// Assign response data to the original object reference
Object.assign(this.data, apiResponse.getData());
}
if (config.emit) {
this.emitChange();
}
}
return apiResponse;
});
}
/**
* Create record from given Object
*
* Creates a record by calling the API, and pushes the new record to this.data
* on success. This method also calls this.emitChange() for you.
*
* @param Object data Object data to create
* @returns Promise
*/
crudCreate(data, options = {}) {
var defaultOptions = {
prePush: true,
postPush: false,
emit: true
};
// Final config
var config = {};
// Merge default options with options from arguments
Object.assign(config, defaultOptions, options);
// Disable prePush if postPush is set in the options
if(options.postPush){
config.prePush = false;
}
if (config.prePush) {
config.postPush = false;
this.data.push(data);
this.emitChange();
}
return this.api.crudCreate(data).then(apiResponse => {
if(apiResponse.isError()){
return apiResponse;
}
// Unset all object properties but keep an object reference
Object.keys(data).map((key) => {
delete data[key];
});
// Assign response data to the original object reference
Object.assign(data, apiResponse.getData());
if (config.postPush) {
this.data.push(data);
}
if (config.emit) {
this.emitChange();
}
return apiResponse;
});
}
/**
* TODO: delete by ID, not index
* Delete record by given record object or ID
* @param Object|number item Object or index to delete
* @returns Promise
*/
crudDelete(item, options = {}) {
var item = item instanceof Object ? item : this.data[item];
var itemIndex = this.data.indexOf(item);
var defaultOptions = {
remove: true,
emit: true
};
// Final config
var config = {};
// Merge default options with options from arguments
Object.assign(config, defaultOptions, options);
if (config.remove) {
this.data.splice(itemIndex, 1);
}
if (config.emit) {
this.emitChange();
}
return this.api.crudDelete(item.id);
}
crudGet(id) {
var id = id instanceof Object ? id.id : id;
return this.api.crudGet(id);
}
crudRestore(id){
return this.api.crudRestore(id).then(apiResponse => {
if (!apiResponse.isError()) {
this.data.push(apiResponse.getData());
this.emitChange();
}
return apiResponse;
});
}
crudReplace() {
// Not yet implemented
}
crudUpdate(id, data) {
if (id instanceof Object) {
data = id;
id = id.id;
}
return this.api.crudUpdate(id, data).then(apiResponse => {
if (!apiResponse.isError()) {
this.getData().then(storeData => {
storeData.forEach((item, index) => {
if (item.id == id) {
Object.assign(this.data[index], data);
this.emitChange();
}
});
});
}
return apiResponse;
});
}
setListView(component){
this.listViewComponent = component;
return this;
}
setFormView(component){
this.formViewComponent = component;
return this;
}
getListView(){
return this.listViewComponent;
}
getFormView(){
return this.formViewComponent;
}
} |
JavaScript | class DataFilter {
filter(data, conditions) {
var results = [];
data.forEach((item) => {
var matches = 0;
Object.keys(conditions).forEach((key) => {
if (item[key] == conditions[value]) {
matches++;
}
});
if (matches == Object.keys(conditions).length) {
results.push(item);
}
});
return results;
}
} |
JavaScript | class CodeMirrorOptions extends Component {
static propTypes = {
language : PropTypes.string.isRequired,
theme : PropTypes.string.isRequired,
runnable : PropTypes.bool,
judge : PropTypes.bool,
allowDownload : PropTypes.bool,
treatOutputAsHTML : PropTypes.bool,
enableHiddenCode : PropTypes.bool,
enableStdin : PropTypes.bool,
showSolution : PropTypes.bool,
evaluateWithoutExecution : PropTypes.bool,
onRunnableChange : PropTypes.func.isRequired,
onJudgeChange : PropTypes.func.isRequired,
onThemeSelect : PropTypes.func.isRequired,
onLanguageSelect : PropTypes.func.isRequired,
onMultiChange : PropTypes.func.isRequired,
onAllowDownloadChange : PropTypes.func.isRequired,
onTreatOutputAsHTMLChange : PropTypes.func.isRequired,
onEnableHiddenCodeChange : PropTypes.func.isRequired,
onEnableStdinChange : PropTypes.func.isRequired,
onEvaluateWithoutExecutionChange : PropTypes.func.isRequired,
onShowSolutionChange : PropTypes.func.isRequired,
onHighlightedLinesChange : PropTypes.func.isRequired,
highlightedLines : PropTypes.string
};
constructor(props, context) {
super(props, context);
this.handleSelectLanguage = this.handleSelectLanguage.bind(this);
this.handleSelectTheme = this.handleSelectTheme.bind(this);
this.handleRunnableChange = this.handleRunnableChange.bind(this);
this.handleJudgeChange = this.handleJudgeChange.bind(this);
this.handleAllowDownloadChange = this.handleAllowDownloadChange.bind(this);
this.handleTreatOutputAsHTMLChange = this.handleTreatOutputAsHTMLChange.bind(this);
this.handleEnableHiddenCodeChange = this.handleEnableHiddenCodeChange.bind(this);
this.handleEnableStdinChange = this.handleEnableStdinChange.bind(this);
this.handleShowSolutionChange = this.handleShowSolutionChange.bind(this);
this.handleEvaluateWithoutExecutionChange = this.handleEvaluateWithoutExecutionChange.bind(this);
this.handleHighlighedLinesChange = this.handleHighlighedLinesChange.bind(this);
}
handleSelectLanguage(event) {
if (this.props.judge) {
if (!CodeMirrorModes[event.target.value].judge) {
this.props.onJudgeChange(false);
}
}
if (this.props.runnable) {
if (!CodeMirrorModes[event.target.value].runnable) {
this.props.onRunnableChange(false);
}
}
this.props.onLanguageSelect(event.target.value);
}
handleSelectTheme(event) {
this.props.onThemeSelect(event.target.value);
}
handleShowSolutionChange(event) {
this.props.onShowSolutionChange(event.target.checked ? true : false);
}
handleEvaluateWithoutExecutionChange(event) {
this.props.onEvaluateWithoutExecutionChange(event.target.checked ? true : false);
}
handleAllowDownloadChange(event) {
this.props.onAllowDownloadChange(event.target.checked);
}
handleTreatOutputAsHTMLChange(event) {
this.props.onTreatOutputAsHTMLChange(event.target.checked);
}
handleEnableHiddenCodeChange(event) {
this.props.onEnableHiddenCodeChange(event.target.checked);
}
handleEnableStdinChange(event) {
this.props.onEnableStdinChange(event.target.checked);
}
handleRunnableChange(event) {
if (event.target.checked) {
this.props.onMultiChange({
judge : false,
runnable : true,
});
} else {
this.props.onRunnableChange(false);
}
}
handleJudgeChange(event) {
if (event.target.checked) {
this.props.onMultiChange({
judge : true,
runnable : false,
});
} else {
if (this.props.onJudgeChange) {
this.props.onJudgeChange(false);
}
}
}
handleHighlighedLinesChange(event) {
this.props.onHighlightedLinesChange(event.target.value);
}
render() {
return (
<div className="edcomp-toolbar" style={{ border:'none' }}>
<div>
<div style={{ display: 'inline-flex', alignItems: 'center', paddingLeft:15, paddingTop:2, paddingBottom:2, marginTop:5, marginBottom:3, border:'1px solid #ddd', borderRadius:3}}>
<label className={`${styles.label} ${styles.alignCenter} form-label`}>
Language
<FormControl componentClass="select" style={{ marginLeft:5 }}
value={this.props.language}
onChange={this.handleSelectLanguage}
>
{
keys(CodeMirrorModes).map(function codeMirrorModesMapper(key) {
return (
<option key={key} value={key}>{CodeMirrorModes[key].title}</option>
);
})
}
</FormControl>
</label>
<label className={`${styles.label} ${styles.alignCenter} form-label`}>
Theme
<FormControl componentClass="select" style={{ marginLeft:5 }}
value={this.props.theme}
onChange={this.handleSelectTheme}
>
{
keys(CodeMirrorThemes).map(function codeMirrorThemesMapper(key) {
return (
<option key={key} value={key}>{CodeMirrorThemes[key]}</option>
);
})
}
</FormControl>
</label>
<HighlightLines
value={this.props.highlightedLines}
onChangeLines={this.handleHighlighedLinesChange}
/>
</div>
</div>
<div style={{ border:'1px solid #ddd', padding:5, paddingLeft:15, marginRight:10, marginTop:5, marginBottom:5, borderRadius:3, display:'inline-block' }}>
<label className={`${styles.label} form-label ${styles.downloadLabel}`}>
<span>Execute</span>
<Checkbox inline disabled={!CodeMirrorModes[this.props.language].runnable} checked={this.props.runnable} onChange={this.handleRunnableChange}/>
</label>
<label className={`${styles.label} form-label ${styles.downloadLabel}`}>
<span>Exercise</span>
<Checkbox inline disabled={!CodeMirrorModes[this.props.language].judge} checked={this.props.judge} onChange={this.handleJudgeChange}/>
</label>
</div>
<div style={{ border:'1px solid #ddd', padding:5, paddingLeft:15, marginRight:5, marginTop:5, marginBottom:5, borderRadius:3, display:'inline-block' }}>
{this.props.runnable ? <label className={`${styles.label} form-label ${styles.downloadLabel}`}>
<span>Hidden Code</span>
<Checkbox inline checked={this.props.enableHiddenCode} onChange={this.handleEnableHiddenCodeChange}/>
</label> : null}
{this.props.runnable ? <label className={`${styles.label} form-label ${styles.downloadLabel}`}>
<span>Stdin</span>
<Checkbox inline checked={this.props.enableStdin} onChange={this.handleEnableStdinChange}/>
</label> : null}
{this.props.runnable ? <label className={`${styles.label} form-label ${styles.downloadLabel}`}>
<span>Treat Output as HTML</span>
<Checkbox inline checked={this.props.treatOutputAsHTML} onChange={this.handleTreatOutputAsHTMLChange}/>
</label> : null}
{this.props.judge ? <label className={`${styles.label} form-label ${styles.downloadLabel}`}>
<span>Solution</span>
<Checkbox inline checked={this.props.showSolution} onChange={this.handleShowSolutionChange}/>
</label> : null}
{this.props.judge ? <label className={`${styles.label} form-label ${styles.downloadLabel}`}>
<span>Evaluate without Execution</span>
<Checkbox inline checked={this.props.evaluateWithoutExecution} onChange={this.handleEvaluateWithoutExecutionChange}/>
</label> : null}
<label className={`${styles.label} form-label ${styles.downloadLabel}`}>
<span>Downloadable</span>
<Checkbox inline checked={this.props.allowDownload} onChange={this.handleAllowDownloadChange}/>
</label>
</div>
</div>
);
}
} |
JavaScript | class ImageGallery extends React.Component {
constructor(props){
super(props);
this.state = {
links: props.links
}
}
remove(event){
event.target.closest('div.image').remove();
}
render() {
return (
<div>
{this.state.links.map((link, index) => <div key={index} class="image">
<img src={link} />
<button class="remove" onClick={event => this.remove(event)}>X</button>
</div>
)}
</div>
)
}
} |
JavaScript | class Node {
constructor(val) {
this.val = val;
}
addNext(n) {
this.next = n;
}
} |
JavaScript | class Nonogram extends React.Component {
constructor(props) {
super(props);
this.initGame();
}
render() {
this.puzzleBitCount = this.state.puzzleBitmap.getBitCount(Cell.BIT_VALUE_CHECKED);
this.indicators = {
rows: this.state.puzzleBitmap.snappedData,
cols: this.state.puzzleBitmap.transposedSnappedData
};
let userBitCount = this.state.userBitmap.getBitCount(Cell.BIT_VALUE_CHECKED);
let userBitCountErrorClass = this.state.puzzleStatus === PUZZLE_STATUS_ERROR
? 'error' : '';
return (
<div className="nonogram"
onContextMenu={this.preventContextMenu}
>
<div className="nonogram-game">
<IndicatorPanel type="row" data={this.indicators.rows} />
<div>
<div className="nonogram-action">
<button type="button" onClick={this.resetUserBitmap}>Restart</button>
<button type="button" onClick={this.initGame}>New Game</button>
</div>
<div className="nonogram-counter">
<span className={userBitCountErrorClass}>{userBitCount} </span>
/ {this.puzzleBitCount}
</div>
<IndicatorPanel type="col" data={this.indicators.cols} />
<Board
rowLength={this.state.puzzleBitmap.rowLength}
colLength={this.state.puzzleBitmap.colLength}
userBitmap={this.state.userBitmap}
getUserBitmapBit={this.getUserBitmapBit}
updateUserBitmapByBit={this.updateUserBitmapByBit}
checkPuzzleSolved={this.checkPuzzleSolved}
/>
</div>
</div>
{this.renderLightbox()}
</div>
);
}
componentDidUpdate() {
if(typeof this.props.solvedCallback === 'function'
&& this.state.puzzleStatus === PUZZLE_STATUS_SOLVED) {
this.props.solvedCallback();
return;
}
if(typeof this.props.errorCallback === 'function'
&& this.state.puzzleStatus === PUZZLE_STATUS_ERROR) {
this.props.errorCallback();
}
}
/* -------------------------------------------------------------------------
^Event Handlers
------------------------------------------------------------------------- */
checkPuzzleSolved = (userBitmap = this.state.userBitmap) => {
for(let i = 0; i < userBitmap.rowLength; i++) {
if(this.checkPuzzleRowSolved(userBitmap, i) !== true) { return false; }
}
for(let i = 0; i < userBitmap.colLength; i++) {
if(this.checkPuzzleColumnSolved(userBitmap, i) !== true) { return false; }
}
return true;
};
getUserBitmapBit = position => this.state.userBitmap.getBit(position);
hideLightbox = () => {
document.querySelector('.nonogram-lightbox').classList.add('hide');
}
initGame = () => {
let puzzleBitmap = this.createPuzzle();
let status = {
puzzleBitmap,
userBitmap: new UserBitmap({
rowLength: puzzleBitmap.rowLength,
colLength: puzzleBitmap.colLength
}),
puzzleStatus: PUZZLE_STATUS_UNSOLVED
};
if(this.state && typeof this.state === 'object') {
this.setState(() => status);
} else {
this.state = status;
}
};
preventContextMenu = e => e.preventDefault();
resetUserBitmap = () => {
this.setState(() => {
return {
userBitmap: new UserBitmap({
rowLength: this.state.puzzleBitmap.rowLength,
colLength: this.state.puzzleBitmap.colLength
}),
puzzleStatus: PUZZLE_STATUS_UNSOLVED
}
});
};
updateUserBitmapByBit = (position, value) => {
this.setState(state => {
let userBitmap = state.userBitmap.clone();
userBitmap.setBit(position, value);
return {
userBitmap,
puzzleStatus: this.getPuzzleStatus(userBitmap)
};
});
};
/* -------------------------------------------------------------------------
^Methods
------------------------------------------------------------------------- */
checkPuzzleRowSolved(userBitmap, rowIndex) {
return this.indicators.rows[rowIndex].toString()
=== userBitmap.getRowSnappedData(rowIndex).toString()
}
checkPuzzleColumnSolved(userBitmap, colIndex) {
return this.indicators.cols[colIndex].toString()
=== userBitmap.getColumnSnappedData(colIndex).toString()
}
createPuzzle() {
return PuzzleBitmap.createRandom(
Number(this.props.rowLength), Number(this.props.colLength)
);
};
getPuzzleStatus(userBitmap) {
let userBitCount = userBitmap.getBitCount(Cell.BIT_VALUE_CHECKED);
if(this.puzzleBitCount <= userBitCount) {
if(this.checkPuzzleSolved(userBitmap) === true) {
// Puzzle solved.
return PUZZLE_STATUS_SOLVED;
}
// Wrong answer.
return PUZZLE_STATUS_ERROR;
}
if(this.puzzleBitCount > userBitCount) {
if(userBitmap.getBitCount(Cell.BIT_VALUE_UNCHECKED) === 0) {
// All cell marked but wrong answer.
return PUZZLE_STATUS_ERROR;
}
}
return PUZZLE_STATUS_UNSOLVED;
}
getPuzzleStatusMessage() {
if(this.state.puzzleStatus === PUZZLE_STATUS_SOLVED) {
return PUZZLE_ALERT_MESSAGE_SOLVED;
}
if(this.state.puzzleStatus === PUZZLE_STATUS_ERROR) {
return PUZZLE_ALERT_MESSAGE_ERROR;
}
return '';
}
renderLightbox() {
if(this.props.preventDefaultSolvedHandler === 'true') { return null; }
if(this.state.puzzleStatus !== PUZZLE_STATUS_SOLVED) { return null; }
return (
<div className={`nonogram-lightbox`}>
<div>{this.getPuzzleStatusMessage()}</div>
<button type="button" onClick={this.hideLightbox}>OK</button>
</div>
);
}
} |
JavaScript | class App extends Component {
constructor(props) {
super(props);
this.state = {
gameReady: false,
playersData: [],
};
this.submitPlayers = this.submitPlayers.bind(this);
}
submitPlayers(playersArray) {
const playersData = playersArray;
this.setState({ playersData: playersData });
this.setState({ gameReady: true });
}
render() {
return (
<div className="App">
<header className="App-header">
{!this.state.gameReady ? (
<GameInput submitPlayers={this.submitPlayers} />
) : (
<Game
numofTotalPlayers={this.state.playersData.length}
playersData={this.state.playersData}
/>
)}
</header>
</div>
);
}
} |
JavaScript | class HttpRequest {
/**
* The index of the host in this.hosts which will be tried
* first before attempting other hosts
* @type {Number}
*/
activeHostIndex = 0
/**
* Whether or not the setNextActiveHostIndex() should
* perform a round robin strategy
*/
activeHostRoundRobin = true
/**
* The regex pattern to check if a uri is absolute or relative,
* if it is absolute the host is not appended
*/
absoluteUriPattern = /^https?:\/\//
/**
* A list of hosts that are tried in round robin fashion
* when certain HTTP responses are received
* @type {String[]}
*/
hosts = []
/**
* Construtor for HttpRequest
* @param {String[]|String} hosts An array of RQLite hosts or a string
* that will be split on "," to create an array of hosts, the first
* host will be tried first when there are multiple hosts
* @param {Object} [options={}] Additional options
* @param {Boolean} [options.activeHostRoundRobin=true] If true this.setNextActiveHostIndex()
* will perform a round robin when called
*/
constructor (hosts, options = {}) {
this.setHosts(hosts)
if (this.getTotalHosts() === 0) {
throw new Error('At least one host must be provided')
}
const { activeHostRoundRobin = true } = options
if (typeof activeHostRoundRobin !== 'undefined') {
this.setActiveHostRoundRobin(activeHostRoundRobin)
}
}
/**
* Set the list of hosts
* @param {String[]|String} hosts An array of RQLite hosts or a string
* that will be split on "," to create an array of hosts, the first
* host will be tried first when there are multiple hosts
*/
setHosts (hosts) {
this.hosts = !Array.isArray(hosts) ? String(hosts).split(',') : hosts
// Remove trailing slashed from hosts
this.hosts = this.hosts.map(host => host.replace(/\/$/, ''))
}
/**
* Get the list of hosts
* @returns {String[]} The list of hosts
*/
getHosts () {
return this.hosts
}
/**
* Get the current active host from the hosts array
* @param {Boolean} useLeader If true use the first host which is always
* the master, this is prefered for write operations
* @returns {String} The active host
*/
getActiveHost (useLeader) {
// When useLeader is true we should just use the first host
const activeHostIndex = useLeader ? 0 : this.activeHostIndex
return this.getHosts()[activeHostIndex]
}
/**
* Set the active host index with check based on this.hosts
* @param {Number} activeHostIndex The index
*/
setActiveHostIndex (activeHostIndex) {
if (!Number.isFinite(activeHostIndex)) {
throw new Error('The activeHostIndex should be a finite number')
}
const totalHosts = this.getTotalHosts()
if (activeHostIndex < 0) {
// Don't allow an index less then zero
this.activeHostIndex = 0
} else if (activeHostIndex >= totalHosts) {
// Don't allow an index greater then the length of the hosts
this.activeHostIndex = totalHosts - 1
} else {
this.activeHostIndex = activeHostIndex
}
}
/**
* Get the active host index
* @returns {Number} The active host index
*/
getActiveHostIndex () {
return this.activeHostIndex
}
/**
* Set active host round robin value
* @param {Boolean} activeHostRoundRobin If true setActiveHostIndex() will
* perform a round robin
*/
setActiveHostRoundRobin (activeHostRoundRobin) {
if (typeof activeHostRoundRobin !== 'boolean') {
throw new Error('The activeHostRoundRobin argument must be boolean')
}
this.activeHostRoundRobin = activeHostRoundRobin
}
/**
* Get active host round robin value
* @returns {Boolean} The value of activeHostRoundRobin
*/
getActiveHostRoundRobin () {
return this.activeHostRoundRobin
}
/**
* Set the active host index to the next host using a
* round robin strategy
*/
setNextActiveHostIndex () {
// Don't bother if we only have one host
if (this.activeHostRoundRobin && this.getHosts().length === 0) {
return
}
let nextIndex = this.activeHostIndex + 1
// If we are past the last index start back over at 1
if (this.getTotalHosts() === nextIndex) {
nextIndex = 0
}
this.setActiveHostIndex(nextIndex)
}
/**
* Get the total number of hosts
* @returns {Number} The total number of hosts
*/
getTotalHosts () {
return this.getHosts().length
}
/**
* Returns whether or not the uri passes a test for this.absoluteUriPattern
* @returns {Boolean} True if the path is absolute
*/
uriIsAbsolute (uri) {
return this.absoluteUriPattern.test(uri)
}
/**
* Perform an HTTP request using the provided options
* @param {Object} [options={}] Options for the HTTP client
* @param {Object} [options.activeHostIndex] A manually provde active host index
* or falls back to select logic honoring useLeader
* @param {Object} [options.auth] A object for user authentication
* i.e. { username: 'test', password: "password" }
* @param {Object} [options.body] The body of the HTTP request
* @param {Boolean} [options.forever=true] When true use the forever keepalive agent
* @param {Boolean|Function} [options.gzip=true] If true add accept deflate headers and
* uncompress the response body
* @param {Object} [options.headers={}] HTTP headers to send with the request
* @param {String} [options.httpMethod=HTTP_METHOD_GET] The HTTP method for the request
* i.e. GET or POST
* @param {Boolean} [options.json=true] When true automatically parse JSON in the response body
* and stringify the request body
* @param {Object} [options.query] An object with the query to send with the HTTP request
* @param {Boolean} [options.stream=false] When true the returned value is a request object with
* stream support instead of a request-promise result
* @param {Object} [options.timeout=DEAULT_TIMEOUT] Optional timeout to override default
* @param {String} options.uri The uri for the request which can be a relative path to use
* the currently active host or a full i.e. http://localhost:4001/db/query which is used
* literally
* @param {String} options.useLeader When true the request will use the master host, the
* first host in this.hosts, this is ideal for write operations to skip the redirect
* @returns {Object} A request-promise result when stream is false and a request object
* with stream support when stream is true
*/
async fetch (options = {}) {
const {
auth,
body,
forever = true,
gzip = true,
headers = {},
httpMethod = HTTP_METHOD_GET,
json = true,
query,
stream = false,
timeout = DEAULT_TIMEOUT,
useLeader = false,
} = options
// Honor the supplied activeHostIndex or get the active host
const { activeHostIndex = this.getActiveHost(useLeader) } = options
let { uri } = options
if (!uri) {
throw new Error('The uri option is required')
}
uri = this.uriIsAbsolute(uri) ? uri : `${activeHostIndex}/${cleanPath(uri)}`
// If a stream is request use the request library directly
if (stream) {
return r({
auth,
body,
forever,
gzip,
followAllRedirects: true,
followOriginalHttpMethod: true,
followRedirect: true,
headers: createDefaultHeaders(headers),
json,
method: httpMethod,
qs: query,
timeout,
uri,
})
}
const requestPromiseOptions = {
auth,
body,
followAllRedirects: false,
followOriginalHttpMethod: false,
followRedirect: false,
forever,
gzip,
headers: createDefaultHeaders(headers),
json,
method: httpMethod,
qs: query,
resolveWithFullResponse: true,
simple: false,
timeout,
transform (responseBody, response, resolveWithFullResponse) {
// Handle 301 and 302 redirects
const { statusCode: responseStatusCode, headers: responseHeaders = {} } = response
if (responseStatusCode === 301 || responseStatusCode === 302) {
const { location: redirectUri } = responseHeaders
this.uri = redirectUri
this.qs = undefined
return rp({ ...requestPromiseOptions, uri: redirectUri })
}
return resolveWithFullResponse ? response : responseBody
},
uri,
}
return rp(requestPromiseOptions)
}
/**
* Perform an HTTP GET request
* @param {Object} [options={}] The options
* @see this.fetch() for options
*/
async get (options = {}) {
return this.fetch({ ...options, httpMethod: HTTP_METHOD_GET })
}
/**
* Perform an HTTP POST request
* @param {Object} [options={}] The options
* @see this.fetch() for options
*/
async post (options = {}) {
return this.fetch({ ...options, httpMethod: HTTP_METHOD_POST })
}
} |
JavaScript | class Sock {
/**
* @param {String} proto - SP protocol string. Could be "bus", "pair", etc.
* @param {Endpoint} ep - Owning endpoint.
* @param {Object} opts={} - Options for the socket. e.g. `{raw: true}`
* @return {Sock}
*/
constructor(proto, ep, opts={}) {
/**
* @callback Sock.Handler
* @param {Msg} msg
* @return {Void}
*/
/**
* A copy of the installed handler.
* @type {Sock.Handler}
*/
this.handler = null
/**
* @type {Endpoint}
*/
this.endpoint = ep
/**
* @type {nanomsg.Socket}
*/
this.sock = nanomsg.socket(proto, opts)
this.sock.setEncoding("utf8")
this.sock.on("error", e => {
this.sock.close()
console.error(e, "\n", e.stack.split("\n"))
})
}
/**
* Bind the address.
* @param {String} addr
* @return {Int} A nanomsg endpoint id. Returns -1 on error.
*/
bind(addr) {
try {
const eid = this.sock.bind(addr)
assert(this.sock.bound[addr] >= 0)
return eid
} catch(e) {
this.sock.close()
console.error(e, e.stack.split("\n"))
return -1
}
}
/**
* Connect to an address.
* @param {String} addr
* @return {Int} A nanomsg endpoint id. Returns -1 on error.
*/
connect(addr) {
try {
const eid = this.sock.connect(addr)
assert(this.sock.connected[addr] >= 0)
return eid
} catch(e) {
this.sock.close()
console.error(e, e.stack.split("\n"))
return -1
}
}
/**
* Disconnect from an address.
* @param {String} addr
* @return {Int} A nanomsg endpoint id. Returns -1 if the address is not previously connected.
*/
disconnect(addr) {
if (addr in this.sock.connected) {
const eid = this.sock.connected[addr]
this.sock.shutdown(eid)
return eid
}
return -1
}
/**
* Close the socket.
* @return {Void}
*/
close() {
return this.sock.close()
}
/**
* Set/Get the message handler.
*
* When installing, all previously installed handler will be replaced.
*
* @param {Sock.Handler} handler
* @return {Void}
*/
set onmessage(handler) {
this.sock.removeAllListeners("data")
this.handler = handler
this.sock.on("data", msg => {
this.handler(JSON.parse(msg))
})
}
get onmessage() {
return this.handler
}
/**
* Send a payload via the sokcet.
*
* @param {Object} payload - A JSON-serializable payload.
* @return {Int} Actual bytes sent.
*/
send(payload) {
const sent = this.sock.send(JSON.stringify(payload))
assert(sent > 0)
return sent
}
} |
JavaScript | class NotFoundError extends Error {
constructor(entityId, message) {
message = message || `Entity with id ${entityId} does not exist`;
super(message);
}
} |
JavaScript | class Playground extends Component {
constructor( props, context ) {
super( props );
const wrappedScope = {};
for ( let key in props.scope ) {
if ( hasOwnProp( props.scope, key ) ) {
let Comp = props.scope[ key ];
wrappedScope[ key ] = class Wrapper extends Component {
render() {
return ( <Provider session={context} >
<Comp {...this.props} />
</Provider> );
}
};
Object.defineProperty( wrappedScope[ key ], 'name', {
value: Comp.name
});
}
}
this.wrappedScope = wrappedScope;
}
componentDidMount() {
this.forceUpdate();
}
componentDidUpdate() {
const node = ReactDom.findDOMNode( this );
// Undo Spectacle scaling as it messes up the rendering of the ACE editor:
let slide = node.closest( '.spectacle-content' );
if ( slide ) {
let computedStyle = window.getComputedStyle( slide );
let transform = computedStyle.getPropertyValue( 'transform' );
let match = /matrix\(([0-9.]*)/.exec( transform );
if ( isArray( match ) && match.length > 1 ) {
let scaleFactor = match[ 1 ];
node.style.transform = `scale(${1/scaleFactor})`;
}
}
}
render() {
const scope = {
React,
...this.wrappedScope
};
return (
<div className="component-documentation" style={this.props.style}>
<div className="playground-editable unselectable">EDITABLE SOURCE</div>
<ComponentPlayground codeText={this.props.code} scope={scope} />
</div>
);
}
} |
JavaScript | class HTTPRequestWrapper {
// these codes are the only ones returned when a request has been
// successfully handled.
static goodResponses = [
{ statusCode: 200, description: "OK" },
{ statusCode: 201, description: "Created" },
{ statusCode: 202, description: "Accepted" },
{ statusCode: 204, description: "No Content" },
{ statusCode: 205, description: "Reset Content" }
];
// used when a content type is not set
static defaultContentType = "application/json";
/**
* Sets up the HTTP request. Not sent yet.
* @param {any} url
* @param {any} type
*/
constructor(url, method, contentType = null, authToken = null) {
this.url = url;
if (!this._isValidURL(url)) {
throw new Error("\"" + url + "\" is not a valid URL.");
}
this.method = method;
this.contentType = contentType;
this.authToken = authToken;
this.content = null;
}
/**
* Sets the authorisation token. Default is set in constructor.
* @param {any} authToken
*/
setAuthToken(authToken) {
this.authToken = authToken;
}
/**
* Sets the content type. Default is defaultContentType
* @param {any} contentType
*/
setContentType(contentType) {
this.content = contentType;
}
/**
* Sets the content. Default is set in constructor.
* @param {any} content
*/
setContent(content) {
this.content = content;
}
/**
* Gives a callback to the request.
*
* Callbacks receive one variable which is the unedited server response.
* @param {any} callback
*/
setCallback(callback) {
if (callback instanceof Function) {
this.callback = callback;
} else {
throw new Error("setCallback(callback) requires a Function parameter. Passed a " + typeof callback);
}
}
/**
* Gives an error callback to the request.
*
* Callbacks receive no variables and are used to do necessary processing.
* @param {any} callback
*/
setErrorCallback(callback) {
if (callback instanceof Function) {
this.errorCallback = callback;
} else {
throw new Error("setErrorCallback(callback) requires a Function parameter. Passed a " + typeof callback);
}
}
/**
* Sends a request with the given information.
* @param {Function} callback Optional. Can be provided earlier using
* setCallback(). Will override the callback.
* @param {Function} errorCallback Optional. Used when an error occurs.
Intended to perform page-specific functionality upon failing a
request, such as exiting a page. Can also be set using
setErrorCallback().
*/
send(callback = null, errorCallback = null) {
// set callbacks
if (callback) {
this.setCallback(callback);
}
if (errorCallback) {
this.setErrorCallback(errorCallback);
}
// set up request object.
var headers = {};
var content = this.content ? this.content : null;
var request = {
url: this.url,
method: this.method,
};
if (this.contentType) {
headers["Content-Type"] = this.contentType;
} else {
headers["Content-Type"] = HTTPRequestWrapper.defaultContentType;
}
if (this.authToken) {
headers["Authorization"] = "Bearer " + this.authToken;
}
request.headers = headers;
if (content) {
if (headers["Content-Type"] == HTTPRequestWrapper.defaultContentType) {
if (typeof content !== "string") {
request.content = JSON.stringify(content);
} else {
request.content = content;
}
} else {
request.content = content;
}
}
// set callbacks using lexical scoping
var lexicalCallback = this.callback ? this.callback : this._defaultCallback;
var lexicalErrorCallback = this.errorCallback ? this.errorCallback : null;
// run request
http.request(request).then(
// do reponse
function (response) {
// has a status code that is valid
if (HTTPRequestWrapper.goodResponses.some(obj => obj.statusCode == response.statusCode)) {
// do callback
try {
lexicalCallback(response);
} catch (err) {
// console logging handled here
console.error("HTTP response error: " + err + "\n" + err.stack);
console.error(response.content.toString());
// other functions handled in error callback
if (lexicalErrorCallback) {
lexicalErrorCallback(err);
}
// if no error callback, we show a dialog
else {
dialogs.alert({
title: "Response to HTTP request could not be handled.",
message: err.message,
okButtonText: "Okay"
}).then(function () { });
}
}
}
// otherwise throw error for bad status code
else {
// console logging handled here
var err = new Error("Bad response code: " + response.statusCode);
console.error(err.message + "\n" + err.stack);
// other functions handled in error callback
if (lexicalErrorCallback) {
lexicalErrorCallback(err);
}
// if no error callback, we show a dialog
else {
dialogs.alert({
title: "HTTP request could not be handled.",
message: err.message,
okButtonText: "Okay"
}).then(function () { });
}
}
},
// do general error
function (err) {
// console logging handled here
console.error(err.message);
// other functions handled in error callback
if (lexicalCallbackError) {
lexicalErrorCallback(err);
}
// if no error callback, we show a dialog
else {
dialogs.alert({
title: "HTTP request failed",
message: err.message,
okButtonText: "Okay"
}).then(function () { });
}
}
);
}
/**
* A default callback used when one isn't given. Logs to console.
* @param {any} response
*/
_defaultCallback(response) {
console.log("Recieved response.");
}
/**
* Checks if valid url.
* Found on: https://stackoverflow.com/a/49849482
* @param {any} string
* @returns {boolean}
*/
_isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
if (res == null)
return false;
else
return true;
}
} |
JavaScript | class CouchDbReadStream extends stream.Readable {
/**
* Creates a new CouchDbReadStream.
*
* @param {object} db - PouchDb instance.
*/
constructor(db) {
super({
objectMode: true
});
this._db = db;
this._key = null;
}
/** Emits chunks. */
_read(size) {
// Avoid double-calling before we know the keys to process docs in
// sequence.
if (this.reading) return;
this.reading = true;
Promise.resolve({
include_docs: true,
startkey: this._key,
skip: (this._key == null ? 0 : 1),
limit: size || 10
}).then(opts => {
return this._db.allDocs(opts)
}).then(result => {
this.emit("total", result.total_rows);
this.reading = false;
if (result.rows.length === 0) {
this.push(null);
} else {
var lastPushResult = false;
this._key = result.rows[result.rows.length - 1].id;
result.rows.forEach(row => {
lastPushResult = this.push(row.doc);
});
// If the reader is still calling for more, continue.
if (lastPushResult) {
process.nextTick(() => this._read(10));
}
}
}).catch(err => this.emit("error", err));
}
} |
JavaScript | class UserDetailsDirective {
constructor() {
angular.extend(this, {
restrict : 'E',
scope : { selected: '=' },
templateUrl : 'src/users/components/details/UserDetails.html',
bindToController : true,
controllerAs : '$ctrl',
controller : ['$mdBottomSheet', '$log', UserDetailsController]
});
}
} |
JavaScript | class MyClass extends OtherComponent {
state = {
test: 1
}
constructor() {
test();
}
otherfunction = (a, b = {
default: false
}) => {
more();
}
} |
JavaScript | class Intern extends Employee {
constructor(name, email, id, school) {
// calls properties of Employee class
super (name, email, id)
// creates new property of Intern class and assigns it to this instance
this.school = school;
}
// creates new methods for Intern class
getSchool() {
return this.school;
}
getRole() {
return "Intern";
}
} |
JavaScript | class InlineResponse20015Data {
/**
* Constructs a new <code>InlineResponse20015Data</code>.
* Details of a region.
* @alias module:model/InlineResponse20015Data
*/
constructor() {
InlineResponse20015Data.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>InlineResponse20015Data</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/InlineResponse20015Data} obj Optional instance to populate.
* @return {module:model/InlineResponse20015Data} The populated <code>InlineResponse20015Data</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new InlineResponse20015Data();
if (data.hasOwnProperty('code')) {
obj['code'] = ApiClient.convertToType(data['code'], 'String');
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data.hasOwnProperty('type')) {
obj['type'] = ApiClient.convertToType(data['type'], 'String');
}
if (data.hasOwnProperty('nestedRegions')) {
obj['nestedRegions'] = ApiClient.convertToType(data['nestedRegions'], [InlineResponse20015DataNestedRegions]);
}
}
return obj;
}
} |
JavaScript | class OutMessage extends OutgoingMessage {
/**
* Entry point for a response from the server
* @param {Buffer} payload A buffer-like object containing data to send back to the client.
*/
end (payload) {
// removeOption(this._request.options, 'Block1');
// add logic for Block1 sending
const block2Buff = getOption(this._request.options, 'Block2')
let requestedBlockOption = null
// if we got blockwise (2) request
if (block2Buff != null) {
if (block2Buff instanceof Buffer) {
requestedBlockOption = parseBlock2(block2Buff)
}
// bad option
if (requestedBlockOption == null) {
this.statusCode = '4.02'
return super.end()
}
}
// if payload is suitable for ONE message, shoot it out
if (
payload == null ||
(requestedBlockOption == null && payload.length < parameters.maxPacketSize)
) {
return super.end(payload)
}
// for the first request, block2 option may be missed
if (requestedBlockOption == null) {
requestedBlockOption = {
size: maxBlock2,
more: 1,
num: 0
}
}
// block2 size should not bigger than maxBlock2
if (requestedBlockOption.size > maxBlock2) { requestedBlockOption.size = maxBlock2 }
// block number should have limit
const lastBlockNum =
Math.ceil(payload.length / requestedBlockOption.size) - 1
if (requestedBlockOption.num > lastBlockNum) {
// precondition fail, may request for out of range block
this.statusCode = '4.02'
return super.end()
}
// check if requested block is the last
const more = requestedBlockOption.num < lastBlockNum ? 1 : 0
const block2 = createBlock2({
more,
num: requestedBlockOption.num,
size: requestedBlockOption.size
})
if (block2 == null) {
// this catch never be match,
// since we're gentleman, just handle it
this.statusCode = '4.02'
return super.end()
}
this.setOption('Block2', block2)
this.setOption('ETag', _toETag(payload))
// cache it
if (this._request.token != null && this._request.token.length > 0) {
this._addCacheEntry(this._cachekey, payload)
}
super.end(
payload.slice(
requestedBlockOption.num * requestedBlockOption.size,
(requestedBlockOption.num + 1) * requestedBlockOption.size
)
)
return this
}
} |
JavaScript | class Engine {
/**
* Instantiates a new Engine
* @constructor
* @param {ScriptProvider} scriptProvider
* @param {ContextProvider} contextProvider
* @param {Object} options
*/
constructor(scriptProvider, contextProvider, options=null) {
this.scriptProvider = scriptProvider;
this.contextProvider = contextProvider;
this.options = options;
}
/**
* Evaluates a script in context
* @static
* @param {string} js The script to execute
* @param {Object} context The context to apply
* @return {boolean} The result
* @throws {Error}
*/
static evalInContext(js, context) {
return new Promise((resolve, reject) => {
try {
resolve(function() {return eval(js);}.call(context));
} catch (err) {
reject(err);
}
});
}
/**
* Handles a script execute request asynchronously
* @param {Object} request
* @return {boolean} Th result
* @throws {Error}
*/
async handleRequest(request) {
const parsedRequest = request;
try {
const script = await this.scriptProvider.getScript(parsedRequest);
const context = this.contextProvider.getContext(parsedRequest).build();
await Engine.evalInContext(script, context);
return true;
} catch (err) {
throw err;
}
}
} |
JavaScript | class Context {
async _init() {
LOG('init context')
const auth = process.env.PROD ? '.auth.json' : '.auth-sandbox.json'
const { username, password } = await bosom(auth)
this.username = username
this.password = password
this.sandbox = !process.env.PROD
}
/**
* Example method.
*/
example() {
return 'OK'
}
/**
* Path to the fixture file.
*/
get FIXTURE() {
return resolve(FIXTURE, 'test.txt')
}
get SNAPSHOT_DIR() {
return resolve(__dirname, '../snapshot')
}
async _destroy() {
LOG('destroy context')
}
async readCredentials() {
}
} |
JavaScript | class SteeringManager {
/**
* Constructs a new steering manager.
*
* @param {Vehicle} vehicle - The vehicle that owns this steering manager.
*/
constructor( vehicle ) {
/**
* The vehicle that owns this steering manager.
* @type {Vehicle}
*/
this.vehicle = vehicle;
/**
* A list of all steering behaviors.
* @type {Array<SteeringBehavior>}
* @readonly
*/
this.behaviors = new Array();
this._steeringForce = new Vector3(); // the calculated steering force per simulation step
this._typesMap = new Map(); // used for deserialization of custom behaviors
}
/**
* Adds the given steering behavior to this steering manager.
*
* @param {SteeringBehavior} behavior - The steering behavior to add.
* @return {SteeringManager} A reference to this steering manager.
*/
add( behavior ) {
this.behaviors.push( behavior );
return this;
}
/**
* Removes the given steering behavior from this steering manager.
*
* @param {SteeringBehavior} behavior - The steering behavior to remove.
* @return {SteeringManager} A reference to this steering manager.
*/
remove( behavior ) {
const index = this.behaviors.indexOf( behavior );
this.behaviors.splice( index, 1 );
return this;
}
/**
* Clears the internal state of this steering manager.
*
* @return {SteeringManager} A reference to this steering manager.
*/
clear() {
this.behaviors.length = 0;
return this;
}
/**
* Calculates the steering forces for all active steering behaviors and
* combines it into a single result force. This method is called in
* {@link Vehicle#update}.
*
* @param {Number} delta - The time delta.
* @param {Vector3} result - The force/result vector.
* @return {Vector3} The force/result vector.
*/
calculate( delta, result ) {
this._calculateByOrder( delta );
return result.copy( this._steeringForce );
}
// this method calculates how much of its max steering force the vehicle has
// left to apply and then applies that amount of the force to add
_accumulate( forceToAdd ) {
// calculate how much steering force the vehicle has used so far
const magnitudeSoFar = this._steeringForce.length();
// calculate how much steering force remains to be used by this vehicle
const magnitudeRemaining = this.vehicle.maxForce - magnitudeSoFar;
// return false if there is no more force left to use
if ( magnitudeRemaining <= 0 ) return false;
// calculate the magnitude of the force we want to add
const magnitudeToAdd = forceToAdd.length();
// restrict the magnitude of forceToAdd, so we don't exceed the max force of the vehicle
if ( magnitudeToAdd > magnitudeRemaining ) {
forceToAdd.normalize().multiplyScalar( magnitudeRemaining );
}
// add force
this._steeringForce.add( forceToAdd );
return true;
}
_calculateByOrder( delta ) {
const behaviors = this.behaviors;
// reset steering force
this._steeringForce.set( 0, 0, 0 );
// calculate for each behavior the respective force
for ( let i = 0, l = behaviors.length; i < l; i ++ ) {
const behavior = behaviors[ i ];
if ( behavior.active === true ) {
force.set( 0, 0, 0 );
behavior.calculate( this.vehicle, force, delta );
force.multiplyScalar( behavior.weight );
if ( this._accumulate( force ) === false ) return;
}
}
}
/**
* Transforms this instance into a JSON object.
*
* @return {Object} The JSON object.
*/
toJSON() {
const data = {
type: 'SteeringManager',
behaviors: new Array()
};
const behaviors = this.behaviors;
for ( let i = 0, l = behaviors.length; i < l; i ++ ) {
const behavior = behaviors[ i ];
data.behaviors.push( behavior.toJSON() );
}
return data;
}
/**
* Restores this instance from the given JSON object.
*
* @param {Object} json - The JSON object.
* @return {SteeringManager} A reference to this steering manager.
*/
fromJSON( json ) {
this.clear();
const behaviorsJSON = json.behaviors;
for ( let i = 0, l = behaviorsJSON.length; i < l; i ++ ) {
const behaviorJSON = behaviorsJSON[ i ];
const type = behaviorJSON.type;
let behavior;
switch ( type ) {
case 'SteeringBehavior':
behavior = new SteeringBehavior().fromJSON( behaviorJSON );
break;
case 'AlignmentBehavior':
behavior = new AlignmentBehavior().fromJSON( behaviorJSON );
break;
case 'ArriveBehavior':
behavior = new ArriveBehavior().fromJSON( behaviorJSON );
break;
case 'CohesionBehavior':
behavior = new CohesionBehavior().fromJSON( behaviorJSON );
break;
case 'EvadeBehavior':
behavior = new EvadeBehavior().fromJSON( behaviorJSON );
break;
case 'FleeBehavior':
behavior = new FleeBehavior().fromJSON( behaviorJSON );
break;
case 'FollowPathBehavior':
behavior = new FollowPathBehavior().fromJSON( behaviorJSON );
break;
case 'InterposeBehavior':
behavior = new InterposeBehavior().fromJSON( behaviorJSON );
break;
case 'ObstacleAvoidanceBehavior':
behavior = new ObstacleAvoidanceBehavior().fromJSON( behaviorJSON );
break;
case 'OffsetPursuitBehavior':
behavior = new OffsetPursuitBehavior().fromJSON( behaviorJSON );
break;
case 'PursuitBehavior':
behavior = new PursuitBehavior().fromJSON( behaviorJSON );
break;
case 'SeekBehavior':
behavior = new SeekBehavior().fromJSON( behaviorJSON );
break;
case 'SeparationBehavior':
behavior = new SeparationBehavior().fromJSON( behaviorJSON );
break;
case 'WanderBehavior':
behavior = new WanderBehavior().fromJSON( behaviorJSON );
break;
default:
// handle custom type
const ctor = this._typesMap.get( type );
if ( ctor !== undefined ) {
behavior = new ctor().fromJSON( behaviorJSON );
} else {
Logger.warn( 'YUKA.SteeringManager: Unsupported steering behavior type:', type );
continue;
}
}
this.add( behavior );
}
return this;
}
/**
* Registers a custom type for deserialization. When calling {@link SteeringManager#fromJSON}
* the steering manager is able to pick the correct constructor in order to create custom
* steering behavior.
*
* @param {String} type - The name of the behavior type.
* @param {Function} constructor - The constructor function.
* @return {SteeringManager} A reference to this steering manager.
*/
registerType( type, constructor ) {
this._typesMap.set( type, constructor );
return this;
}
/**
* Restores UUIDs with references to GameEntity objects.
*
* @param {Map<String,GameEntity>} entities - Maps game entities to UUIDs.
* @return {SteeringManager} A reference to this steering manager.
*/
resolveReferences( entities ) {
const behaviors = this.behaviors;
for ( let i = 0, l = behaviors.length; i < l; i ++ ) {
const behavior = behaviors[ i ];
behavior.resolveReferences( entities );
}
return this;
}
} |
JavaScript | class OrganizationCountAndAddressInfo {
/**
* Constructs a new <code>OrganizationCountAndAddressInfo</code>.
* @alias module:model/OrganizationCountAndAddressInfo
* @implements module:model/OrganizationCountInfo
* @implements module:model/OrganizationAddressInfo
*/
constructor() {
OrganizationCountInfo.initialize(this);OrganizationAddressInfo.initialize(this);
OrganizationCountAndAddressInfo.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>OrganizationCountAndAddressInfo</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/OrganizationCountAndAddressInfo} obj Optional instance to populate.
* @return {module:model/OrganizationCountAndAddressInfo} The populated <code>OrganizationCountAndAddressInfo</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new OrganizationCountAndAddressInfo();
OrganizationCountInfo.constructFromObject(data, obj);
OrganizationAddressInfo.constructFromObject(data, obj);
if (data.hasOwnProperty('email_messages_count')) {
obj['email_messages_count'] = ApiClient.convertToType(data['email_messages_count'], 'Number');
delete data['email_messages_count'];
}
if (data.hasOwnProperty('people_count')) {
obj['people_count'] = ApiClient.convertToType(data['people_count'], 'Number');
delete data['people_count'];
}
if (data.hasOwnProperty('activities_count')) {
obj['activities_count'] = ApiClient.convertToType(data['activities_count'], 'Number');
delete data['activities_count'];
}
if (data.hasOwnProperty('done_activities_count')) {
obj['done_activities_count'] = ApiClient.convertToType(data['done_activities_count'], 'Number');
delete data['done_activities_count'];
}
if (data.hasOwnProperty('undone_activities_count')) {
obj['undone_activities_count'] = ApiClient.convertToType(data['undone_activities_count'], 'Number');
delete data['undone_activities_count'];
}
if (data.hasOwnProperty('files_count')) {
obj['files_count'] = ApiClient.convertToType(data['files_count'], 'Number');
delete data['files_count'];
}
if (data.hasOwnProperty('notes_count')) {
obj['notes_count'] = ApiClient.convertToType(data['notes_count'], 'Number');
delete data['notes_count'];
}
if (data.hasOwnProperty('followers_count')) {
obj['followers_count'] = ApiClient.convertToType(data['followers_count'], 'Number');
delete data['followers_count'];
}
if (data.hasOwnProperty('address')) {
obj['address'] = ApiClient.convertToType(data['address'], 'String');
delete data['address'];
}
if (data.hasOwnProperty('address_subpremise')) {
obj['address_subpremise'] = ApiClient.convertToType(data['address_subpremise'], 'String');
delete data['address_subpremise'];
}
if (data.hasOwnProperty('address_street_number')) {
obj['address_street_number'] = ApiClient.convertToType(data['address_street_number'], 'String');
delete data['address_street_number'];
}
if (data.hasOwnProperty('address_route')) {
obj['address_route'] = ApiClient.convertToType(data['address_route'], 'String');
delete data['address_route'];
}
if (data.hasOwnProperty('address_sublocality')) {
obj['address_sublocality'] = ApiClient.convertToType(data['address_sublocality'], 'String');
delete data['address_sublocality'];
}
if (data.hasOwnProperty('address_locality')) {
obj['address_locality'] = ApiClient.convertToType(data['address_locality'], 'String');
delete data['address_locality'];
}
if (data.hasOwnProperty('address_admin_area_level_1')) {
obj['address_admin_area_level_1'] = ApiClient.convertToType(data['address_admin_area_level_1'], 'String');
delete data['address_admin_area_level_1'];
}
if (data.hasOwnProperty('address_admin_area_level_2')) {
obj['address_admin_area_level_2'] = ApiClient.convertToType(data['address_admin_area_level_2'], 'String');
delete data['address_admin_area_level_2'];
}
if (data.hasOwnProperty('address_country')) {
obj['address_country'] = ApiClient.convertToType(data['address_country'], 'String');
delete data['address_country'];
}
if (data.hasOwnProperty('address_postal_code')) {
obj['address_postal_code'] = ApiClient.convertToType(data['address_postal_code'], 'String');
delete data['address_postal_code'];
}
if (data.hasOwnProperty('address_formatted_address')) {
obj['address_formatted_address'] = ApiClient.convertToType(data['address_formatted_address'], 'String');
delete data['address_formatted_address'];
}
if (Object.keys(data).length > 0) {
Object.assign(obj, data);
}
}
return obj;
}
} |
JavaScript | class ElementHandler {
/**
* Constructor
* @param {variant} page variant that is fetched
*/
constructor(variant) {
this.title;
this.url;
if(variant == 1){
this.title = "Chen Meng's LinkedIn page";
this.url = "https://www.linkedin.com/in/chenmeng98/"; //Chen Meng's linkedin profile url
}
else{
this.title = "Chen Meng's Github page";
this.url = "https://github.com/MCharming98"; //Chen Meng's Github profile url
}
}
element(element) {
// An incoming element, such as `div`
let tag = element.tagName;
let id = element.getAttribute('id');
if(tag == 'title' || (tag == 'h1' && id == 'title')){ //Modify page title and title header
element.setInnerContent(this.title);
}
else if(tag == 'p' && id == 'description'){ //Modify the description text
element.append(" And you can visit " + this.title + "!");
}
else if(tag == 'a' && id == 'url'){ //Modify the url and its text
element.setAttribute('href', this.url);
element.setAttribute('target', '_blank'); //Open in new window
element.setInnerContent("Visit " + this.title);
}
}
comments(comment) {}
text(text) {}
} |
JavaScript | class PlaylistPicker extends React.Component {
constructor(props) {
super(props);
this.state = {
playlists: [],
value: null
};
this.choosePlaylist = this.choosePlaylist.bind(this);
this.getUserPlaylists = this.getUserPlaylists.bind(this);
this.getPlaylistFromLink = this.getPlaylistFromLink.bind(this);
}
componentDidMount() {
this.getUserPlaylists();
}
/**
* Get playlists of a user
*/
getUserPlaylists() {
SpotifyAPI.getUserPlaylists(json => {
this.setState({
playlists: json.items,
})
})
}
/**
* Set chosen playlist from the search field
*/
choosePlaylist(playlist) {
this.setState({
value: playlist
});
this.props.displayPlaylist(playlist);
}
/**
* Set chosen playlist or album from the paste link
*/
getPlaylistFromLink(e) {
// Get value from input
let input = e.target.value;
let context = '';
// Check if input is valid Spotify link for retrieving a playlist
if (PlaylistPicker.isUrl(input)) {
// Get user id and playlist id from link
context = PlaylistPicker.isUrl(input);
} else if(PlaylistPicker.isUri(input)) {
context = PlaylistPicker.isUri(input);
} else if(input.length < 1){
this.props.displayPlaylist('');
return;
} else {
this.props.displayPlaylist('');
return;
}
let playlist_id = context.playlist;
let album = context.album;
// Get playlist data from backend
if(album) {
this.fetchAlbum(album);
} else {
this.fetchPlaylist(playlist_id);
}
}
/**
* Fetch a playlist from the backend.
* @param playlist_id Spotify ID for a playlist.
*/
fetchPlaylist(playlist_id) {
SpotifyAPI.getPlaylist(playlist_id, json => {
if (json) {
this.props.displayPlaylist(json);
} else {
this.choosePlaylist('');
}
})
}
/**
* Fetches an album from backend
* @param album_id album id from Spotify
*/
fetchAlbum(album_id) {
SpotifyAPI.getAlbum(album_id, json => {
if (json) {
this.props.displayPlaylist(json);
} else {
this.choosePlaylist('');
}
})
}
/**
* Checks if the input is a valid Spotify URL for a playlist or album.
*/
static isUrl(url) {
let regexp = /https:\/\/open.spotify.com\/user\/\w+\/playlist\/(\w+)/g;
let match = regexp.exec(url);
if (match === null) {
return false;
}
return {playlist: match[1]}
}
/**
* Checks if the input is a valid Spotify URI for a playlist or album.
*/
static isUri(uri) {
let maybePlaylist = /spotify:user:\w*:playlist:(\w+)/g.exec(uri);
let maybeAlbum = /spotify:album:(\w*)/g.exec(uri);
if (maybeAlbum !== null) {
return {album: maybeAlbum[1]}
}
if (maybePlaylist !== null) {
return {playlist: maybePlaylist[1]}
}
return false;
}
render () {
return (
<Row className="show-grid" >
<Col xs={12} sm={12} md={12} >
<h1>Choose a playlist</h1>
</Col>
<Col xs={12} sm={6} md={6} >
<h2>Your playlists</h2>
<p>Choose from the playlist you created or which you follow</p>
<Select
id="selectPlaylist"
options={this.state.playlists}
value={this.state.value}
onChange={this.choosePlaylist}
valueKey="id"
labelKey="name"
/>
</Col>
<Col xs={12} sm={6} md={6} >
<h2>Paste link</h2>
<p>Paste url to any public playlist</p>
<form>
<FormGroup controlId="formBasicText" >
<FormControl
type="text"
onChange={this.getPlaylistFromLink}
placeholder="Paste URL or URI from Spotify"
/>
</FormGroup>
</form>
</Col>
</Row>
)
}
} |
JavaScript | class Tetromino {
/**
* @param {Shapes} shapes - The shapes that the tetromino can have
* @param {Point} pos - The pos of the tetromino
* @param {Game} game - The game the tetromino is in
*/
constructor(shapes, pos, game) {
this.shapeIndex = 0;
this.shapes = shapes;
this.pos = pos;
this.game = game;
}
/**
* Updates the tetromino
* @returns {Boolean} If it couldn't move down
*/
update() {
return !this.moveY(1);
}
/**
* Calculates the distance between itself and a collision that's underneath it and returns it
* @returns {Number} The distance between itself and a collision that's underneath it
*/
castDown() {
for (let y = this.pos.y; y < this.game.height; y++) {
if (!this.game.tetrominoFits(this, undefined, y)) {
return y - this.pos.y - 1;
}
}
}
/**
* Draws the tetromino
* @param {wCanvas} canvas - The canvas to draw the tetromino on
*/
draw(canvas) {
drawShape(canvas, this.game.pos.x + this.pos.x * CELL_SIZE, this.game.pos.y + this.pos.y * CELL_SIZE, this.getCurrentShape());
}
/**
* Draws Tetromino's shadow showing where it's dropping
* @param {wCanvas} canvas - The canvas to draw the shadow on
*/
drawShadow(canvas) {
const shape = this.getCurrentShape();
drawShape(
canvas,
this.game.pos.x + this.pos.x * CELL_SIZE,
this.game.pos.y + (this.pos.y + this.castDown()) * CELL_SIZE,
shape,
settings.shadow_color
);
}
/**
* Goes back to the previous shape
* @returns {Boolean} If it was able to change shape
*/
previousShape() {
if (this.game.paused) { return false; }
const oldIndex = this.shapeIndex;
if (--this.shapeIndex < 0) {
this.shapeIndex = this.shapes.length - 1;
}
if (this.game.tetrominoFits(this)) {
return true;
}
this.shapeIndex = oldIndex;
return false;
}
/**
* Goes forward to the next shape
* @returns {Boolean} If it was able to change shape
*/
nextShape() {
if (this.game.paused) { return false; }
const oldIndex = this.shapeIndex;
if (++this.shapeIndex >= this.shapes.length) {
this.shapeIndex = 0;
}
if (this.game.tetrominoFits(this)) {
return true;
}
this.shapeIndex = oldIndex;
return false;
}
/**
* Returns the shape that is being used by the tetromino
* @returns {Shape} The current shape of the tetromino
*/
getCurrentShape() {
return this.shapes[this.shapeIndex];
}
/**
* Moves the tetromino on the X axis
* @param {Number} ammount - How many cells the tetromino should move
* @returns {Boolean} Whether or not it could move into the specified pos
*/
moveX(ammount) {
if (this.game.paused) { return false; }
if (this.game.tetrominoFits(this, this.pos.x + ammount)) {
this.pos.x += ammount;
return true;
}
return false;
}
/**
* Moves the tetromino on the Y axis
* @param {Number} ammount - How many cells the tetromino should move
* @returns {Boolean} Whether or not it could move into the specified pos
*/
moveY(ammount) {
if (this.game.paused) { return false; }
if (this.game.tetrominoFits(this, undefined, this.pos.y + ammount)) {
this.pos.y += ammount;
return true;
}
return false;
}
} |
JavaScript | class ProductListItemReference {
/**
* Constructs a new <code>ProductListItemReference</code>.
* @alias module:models/ProductListItemReference
* @class
* @param id {String} The id of the product list item.
*/
constructor(id) {
/**
* The id of the product list item.
* @member {String} id
*/
this.id = id
/**
* @member {Number} priority
*/
this.priority = undefined
/**
* @member {module:models/ProductDetailsLink} product_details_link
*/
this.product_details_link = undefined
/**
* The link of the product list, the item is assigned
* @member {module:models/ProductListLink} product_list
*/
this.product_list = undefined
/**
* @member {Boolean} public
*/
this.public = undefined
/**
* @member {Number} purchased_quantity
*/
this.purchased_quantity = undefined
/**
* @member {Number} quantity
*/
this.quantity = undefined
/**
* @member {module:models/ProductListItemReference.TypeEnum} type
*/
this.type = undefined
}
/**
* Constructs a <code>ProductListItemReference</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:models/ProductListItemReference} obj Optional instance to populate.
* @return {module:models/ProductListItemReference} The populated <code>ProductListItemReference</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ProductListItemReference()
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'String')
}
if (data.hasOwnProperty('priority')) {
obj['priority'] = ApiClient.convertToType(data['priority'], 'Number')
}
if (data.hasOwnProperty('product_details_link')) {
obj['product_details_link'] = ProductDetailsLink.constructFromObject(data['product_details_link'])
}
if (data.hasOwnProperty('product_list')) {
obj['product_list'] = ProductListLink.constructFromObject(data['product_list'])
}
if (data.hasOwnProperty('public')) {
obj['public'] = ApiClient.convertToType(data['public'], 'Boolean')
}
if (data.hasOwnProperty('purchased_quantity')) {
obj['purchased_quantity'] = ApiClient.convertToType(data['purchased_quantity'], 'Number')
}
if (data.hasOwnProperty('quantity')) {
obj['quantity'] = ApiClient.convertToType(data['quantity'], 'Number')
}
if (data.hasOwnProperty('type')) {
obj['type'] = ApiClient.convertToType(data['type'], 'String')
}
}
return obj
}
} |
JavaScript | class Gain extends ToneAudioNode {
constructor() {
super(optionsFromArguments(Gain.getDefaults(), arguments, ["gain", "units"]));
this.name = "Gain";
/**
* The wrapped GainNode.
*/
this._gainNode = this.context.createGain();
// input = output
this.input = this._gainNode;
this.output = this._gainNode;
const options = optionsFromArguments(Gain.getDefaults(), arguments, ["gain", "units"]);
this.gain = new Param({
context: this.context,
convert: options.convert,
param: this._gainNode.gain,
units: options.units,
value: options.gain,
minValue: options.minValue,
maxValue: options.maxValue,
});
readOnly(this, "gain");
}
static getDefaults() {
return Object.assign(ToneAudioNode.getDefaults(), {
convert: true,
gain: 1,
units: "gain",
});
}
/**
* Clean up.
*/
dispose() {
super.dispose();
this._gainNode.disconnect();
this.gain.dispose();
return this;
}
} |
JavaScript | class MaskInput {
constructor(
element,
{
mask = defaults.mask,
value = '',
reformat,
maskString,
maskChar = defaults.maskChar,
maskFormat = defaults.maskFormat,
showMask,
alwaysShowMask,
onChange,
}
) {
this.input = this.input = createInput({
value: value,
reformat: reformat,
maskString: maskString,
maskChar: maskChar,
mask: mask,
maskFormat: maskFormat,
});
this.props = {
mask,
value,
reformat,
maskChar,
maskFormat,
maskString,
showMask,
alwaysShowMask,
onChange,
};
this.showMask = alwaysShowMask || showMask;
this.element = element;
this.showValue();
this.subscribe();
}
showValue = () => {
if (this.showMask && (this.canSetSelection || this.props.alwaysShowMask)) {
this.element.value = this.input.getMaskedValue();
return;
}
this.element.value = this.input.getVisibleValue();
};
setSelection = () => {
if (!this.canSetSelection) {
return;
}
const selection = this.input.getSelection();
this.element.setSelectionRange(selection.start, selection.end);
const raf =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
(fn => setTimeout(fn, 0));
// For android
raf(() => this.element.setSelectionRange(selection.start, selection.end));
};
getSelection() {
this.input.setSelection({
start: this.element.selectionStart,
end: this.element.selectionEnd,
});
}
subscribe() {
this.unsubscribe = {
onPaste: subscribe(this.element, 'paste', this.onPaste),
onKeyDown: subscribe(this.element, 'keydown', this.onKeyDown),
onKeyPress: subscribe(this.element, this.keyPressPropName(), this.onKeyPress),
onChange: subscribe(this.element, 'change', this.onChange),
onFocus: subscribe(this.element, 'focus', this.onFocus),
onBlur: subscribe(this.element, 'blur', this.onBlur),
};
}
onPaste = e => {
e.preventDefault();
this.getSelection();
// getData value needed for IE also works in FF & Chrome
this.input.paste(e.clipboardData.getData('Text'));
this.showValue();
// Timeout needed for IE
setTimeout(this.setSelection, 0);
this.props.onChange && this.props.onChange(e);
};
onChange = e => {
let currentValue;
if (this.showMask && (this.canSetSelection || this.props.alwaysShowMask)) {
currentValue = this.input.getMaskedValue();
} else {
currentValue = this.input.getVisibleValue();
}
// fix conflict by update value in mask model
if (e.target.value !== currentValue) {
this.getSelection();
this.input.setValue(e.target.value);
this.showValue();
setTimeout(this.setSelection, 0);
}
this.props.onChange && this.props.onChange(e);
};
onKeyPress = e => {
if (e.metaKey || e.altKey || e.ctrlKey || e.key === 'Enter') {
return;
}
e.preventDefault();
this.getSelection();
this.input.input(e.key || e.data || String.fromCharCode(e.which));
this.showValue();
this.setSelection();
this.props.onChange && this.props.onChange(e);
};
onKeyDown = e => {
if (e.which === KEYBOARD.BACKSPACE) {
e.preventDefault();
this.getSelection();
this.input.removePreviosOrSelected();
this.showValue();
this.setSelection();
this.props.onChange && this.props.onChange(e);
}
if (e.which === KEYBOARD.DELETE) {
e.preventDefault();
this.getSelection();
this.input.removeNextOrSelected();
this.showValue();
this.setSelection();
this.props.onChange && this.props.onChange(e);
}
};
onFocus = () => {
this.canSetSelection = true;
};
onBlur = () => {
this.canSetSelection = false;
};
keyPressPropName() {
if (typeof navigator !== 'undefined' && navigator.userAgent.match(/Android/i)) {
return 'beforeinput';
}
return 'keypress';
}
setProps({ mask, value, reformat, maskString, maskChar, maskFormat, showMask, alwaysShowMask, onChange }) {
let updated = false;
if (this.props.onChange !== onChange) {
this.props.onChange = onChange;
}
if (this.props.alwaysShowMask !== alwaysShowMask || this.props.showMask !== showMask) {
this.showMask = alwaysShowMask || showMask;
this.props.alwaysShowMask = alwaysShowMask;
this.props.showMask = showMask;
updated = true;
}
if (maskFormat && maskFormat !== this.props.maskFormat) {
this.input.setMaskFormat(maskFormat);
this.props.maskFormat = maskFormat;
updated = true;
}
if (mask !== this.props.mask) {
this.input.setMask(mask);
this.props.mask = mask;
updated = true;
}
if (maskString !== this.props.maskString) {
this.input.setMaskString(maskString);
this.props.maskString = maskString;
updated = true;
}
if (maskChar !== this.props.maskChar) {
this.input.setMaskChar(maskChar);
this.props.maskChar = maskChar;
updated = true;
}
if (reformat !== this.props.reformat) {
this.input.setReformat(reformat);
this.props.reformat = reformat;
updated = true;
}
if (value !== this.props.value) {
this.input.setValue(value);
this.props.value = value;
updated = true;
}
if (updated) {
this.showValue();
this.setSelection();
}
}
destroy() {
this.unsubscribe.onPaste();
this.unsubscribe.onKeyDown();
this.unsubscribe.onKeyPress();
this.unsubscribe.onChange();
this.unsubscribe.onFocus();
this.unsubscribe.onBlur();
}
} |
JavaScript | class MockPanel extends React.PureComponent {
render() {
return (<div>{this.props.children}</div>);
}
} |
JavaScript | class KernelManager {
/**
* Construct a new kernel manager.
*
* @param options - The default options for kernel.
*/
constructor(options = {}) {
this._models = [];
this._kernels = new Set();
this._specs = null;
this._isDisposed = false;
this._modelsTimer = -1;
this._specsTimer = -1;
this._isReady = false;
this._specsChanged = new signaling_1.Signal(this);
this._runningChanged = new signaling_1.Signal(this);
this.serverSettings =
options.serverSettings || __1.ServerConnection.makeSettings();
// Initialize internal data.
this._readyPromise = this._refreshSpecs().then(() => {
return this._refreshRunning();
});
// Set up polling.
this._modelsTimer = setInterval(() => {
if (typeof document !== 'undefined' && document.hidden) {
// Don't poll when nobody's looking.
return;
}
this._refreshRunning();
}, 10000);
this._specsTimer = setInterval(() => {
if (typeof document !== 'undefined' && document.hidden) {
// Don't poll when nobody's looking.
return;
}
this._refreshSpecs();
}, 61000);
}
/**
* A signal emitted when the specs change.
*/
get specsChanged() {
return this._specsChanged;
}
/**
* A signal emitted when the running kernels change.
*/
get runningChanged() {
return this._runningChanged;
}
/**
* Test whether the terminal manager is disposed.
*/
get isDisposed() {
return this._isDisposed;
}
/**
* Dispose of the resources used by the manager.
*/
dispose() {
if (this.isDisposed) {
return;
}
this._isDisposed = true;
clearInterval(this._modelsTimer);
clearInterval(this._specsTimer);
signaling_1.Signal.clearData(this);
this._models = [];
}
/**
* Get the most recently fetched kernel specs.
*/
get specs() {
return this._specs;
}
/**
* Test whether the manager is ready.
*/
get isReady() {
return this._isReady;
}
/**
* A promise that fulfills when the manager is ready.
*/
get ready() {
return this._readyPromise;
}
/**
* Create an iterator over the most recent running kernels.
*
* @returns A new iterator over the running kernels.
*/
running() {
return algorithm_1.iter(this._models);
}
/**
* Force a refresh of the specs from the server.
*
* @returns A promise that resolves when the specs are fetched.
*
* #### Notes
* This is intended to be called only in response to a user action,
* since the manager maintains its internal state.
*/
refreshSpecs() {
return this._refreshSpecs();
}
/**
* Force a refresh of the running kernels.
*
* @returns A promise that with the list of running sessions.
*
* #### Notes
* This is not typically meant to be called by the user, since the
* manager maintains its own internal state.
*/
refreshRunning() {
return this._refreshRunning();
}
/**
* Start a new kernel.
*
* @param options - The kernel options to use.
*
* @returns A promise that resolves with the kernel instance.
*
* #### Notes
* The manager `serverSettings` will be always be used.
*/
startNew(options = {}) {
let newOptions = Object.assign({}, options, { serverSettings: this.serverSettings });
return kernel_1.Kernel.startNew(newOptions).then(kernel => {
this._onStarted(kernel);
return kernel;
});
}
/**
* Find a kernel by id.
*
* @param id - The id of the target kernel.
*
* @returns A promise that resolves with the kernel's model.
*/
findById(id) {
return kernel_1.Kernel.findById(id, this.serverSettings);
}
/**
* Connect to an existing kernel.
*
* @param model - The model of the target kernel.
*
* @returns A promise that resolves with the new kernel instance.
*/
connectTo(model) {
let kernel = kernel_1.Kernel.connectTo(model, this.serverSettings);
this._onStarted(kernel);
return kernel;
}
/**
* Shut down a kernel by id.
*
* @param id - The id of the target kernel.
*
* @returns A promise that resolves when the operation is complete.
*
* #### Notes
* This will emit [[runningChanged]] if the running kernels list
* changes.
*/
shutdown(id) {
let index = algorithm_1.ArrayExt.findFirstIndex(this._models, value => value.id === id);
if (index === -1) {
return;
}
// Proactively remove the model.
this._models.splice(index, 1);
this._runningChanged.emit(this._models.slice());
return kernel_1.Kernel.shutdown(id, this.serverSettings).then(() => {
let toRemove = [];
this._kernels.forEach(k => {
if (k.id === id) {
k.dispose();
toRemove.push(k);
}
});
toRemove.forEach(k => {
this._kernels.delete(k);
});
});
}
/**
* Shut down all kernels.
*
* @returns A promise that resolves when all of the kernels are shut down.
*/
shutdownAll() {
// Proactively remove all models.
let models = this._models;
if (models.length > 0) {
this._models = [];
this._runningChanged.emit([]);
}
return this._refreshRunning().then(() => {
return Promise.all(models.map(model => {
return kernel_1.Kernel.shutdown(model.id, this.serverSettings).then(() => {
let toRemove = [];
this._kernels.forEach(k => {
k.dispose();
toRemove.push(k);
});
toRemove.forEach(k => {
this._kernels.delete(k);
});
});
})).then(() => {
return undefined;
});
});
}
/**
* Handle a kernel terminating.
*/
_onTerminated(id) {
let index = algorithm_1.ArrayExt.findFirstIndex(this._models, value => value.id === id);
if (index !== -1) {
this._models.splice(index, 1);
this._runningChanged.emit(this._models.slice());
}
}
/**
* Handle a kernel starting.
*/
_onStarted(kernel) {
let id = kernel.id;
this._kernels.add(kernel);
let index = algorithm_1.ArrayExt.findFirstIndex(this._models, value => value.id === id);
if (index === -1) {
this._models.push(kernel.model);
this._runningChanged.emit(this._models.slice());
}
kernel.terminated.connect(() => {
this._onTerminated(id);
});
}
/**
* Refresh the specs.
*/
_refreshSpecs() {
return kernel_1.Kernel.getSpecs(this.serverSettings).then(specs => {
if (!coreutils_1.JSONExt.deepEqual(specs, this._specs)) {
this._specs = specs;
this._specsChanged.emit(specs);
}
});
}
/**
* Refresh the running sessions.
*/
_refreshRunning() {
return kernel_1.Kernel.listRunning(this.serverSettings).then(models => {
this._isReady = true;
if (!coreutils_1.JSONExt.deepEqual(models, this._models)) {
let ids = models.map(r => r.id);
let toRemove = [];
this._kernels.forEach(k => {
if (ids.indexOf(k.id) === -1) {
k.dispose();
toRemove.push(k);
}
});
toRemove.forEach(s => {
this._kernels.delete(s);
});
this._models = models.slice();
this._runningChanged.emit(models);
}
});
}
} |
JavaScript | class CommandBuilder {
constructor(command, args = []) {
this.command = command;
this.args = [...args];
return this;
}
// Adds an argument to the list of arguments. Optionally, pass a truthy/falsy
// value for `condition` to conditionally add the argument. Example:
//
// const watch = false;
// const command = new CommandBuilder("ava", [ "--verbose" ]);
// command.arg("--watch", watch); // argument won't be added
arg(value, condition = true) {
if (Boolean(condition)) {
// FIXME: escape or quote value if necessary
this.args.push(value);
}
return this;
}
// Returns a string representation of the shell command ready to execute
toString() {
const { command, args } = this;
return `${command} ${args.join(" ")}`;
}
// Execute current command and asynchronously return output
async run(options = {}) {
const command = this.toString();
return run(command, options);
}
// Execute current command interactively
async interactive(options = {}) {
const command = this.toString();
return interactive(command, options);
}
} |
JavaScript | class EventDetailError extends Error {
/**
*
* @param {String} event
* @param {String} property
* @param {String} expected
*/
constructor (event, property, expected) {
super()
this.message = [
`When dispatching the '${event}' event,`,
`you need to pass a 'detail' object that has a '${property}' property (typeof ${expected}).`,
'Read about event data here: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail'
].join(' ')
}
} |
JavaScript | class SimpleAppService extends AppService {
/**
* @param {TaskManager} taskManager - TaskManager is used to orchestrate changes to the system.
* @param {AppStore} store - Store is used for loading persisted state.
* @param {Config} config - The runtime config
* @param {Logger} logger - optional passed in Logger instance
*/
constructor({
taskManager,
store,
config = new Config(),
logger = new Logger(config)
} = {}) {
super(taskManager, store, config, logger);
this.logger = logger.child({ config: { "service.name": "AppService" } });
this._running = false;
}
/**
* @description Return if the AppStore is currently running or not
* @returns {Boolean} true if the appStore is running or false if not
*/
isRunning() {
return this._running;
}
/**
* @async
* @description Initialize and start the AppService (and if necessary required services)
* @returns {Promise} Promise which resolves once started
*/
start() {
return new Promise(async (resolve, reject) => {
this._running = true;
this.logger.info("App Service has started");
this.emit(AppService.SERVICE_STARTED_EVENT);
resolve();
});
}
/**
* @description shutdown AppService gracefully
*/
shutdown() {
return new Promise(async (resolve, reject) => {
this._running = false;
this.emit(AppService.SERVICE_SHUTDOWN_EVENT);
resolve();
});
}
/**
* @description Load a single App from remote source (delegates to TaskManager for async operation)
* @argument {String} url URL of App descriptor
* @argument {String} permission Permission to grant the new App
* @returns {Promise} Promise which resolves with new App() throws Error()
*/
loadApp(url, permission) {
// Use TaskManager to schedule loading the App
return new Promise(async (resolve, reject) => {
let task;
this.logger.info(
"APP LOAD has been requested, creating a task for it (url=%s, permission=%s)",
url,
permission
);
try {
task = await this.taskManager.create(Task.types.APP_LOAD, {
url: url,
permission: permission
});
} catch (err) {
this.logger.error("Error creating task %o", err);
return reject(err);
}
// Schedule it immediately
try {
task
.on(Task.events.ERROR_EVENT, error => {
this.logger.error("App Load failed with error: %o", error);
reject(error);
})
.on(Task.events.SUCCESS_EVENT, data => {
this.logger.info(
"App Loaded successfully with App (id=%s, key=%s)",
data.getId(),
data.getKey()
);
resolve(data);
})
.commit();
} catch (err) {
this.logger.error("Error could not commit task %o", err);
return reject(new Error("Error commiting task"));
}
});
}
/**
* @description ReLoad an existing App (delegates to TaskManager for async operation)
* - Loads the App as if it was new, but maintains the same id in the DB
* - Optionally modify the Permission granted to the App
* @argument {App} app The existing App to reload
* @optional @argument {String} permission Permission to override when the App is reloaded
* @returns {Promise} Promise which resolves with new App() throws Error()
*/
reloadApp(app, permission) {
// Use TaskManager to schedule loading the App
return new Promise(async (resolve, reject) => {
let task;
this.logger.info(
"APP RELOAD has been requested, creating a task for it (app=%s, permission=%s)",
app.getId(),
permission
);
try {
task = await this.taskManager.create(Task.types.APP_RELOAD, {
app: app,
permission: permission
});
} catch (err) {
this.logger.error("Error creating task %o", err);
return reject(err);
}
// Schedule it immediately
try {
task
.on(Task.events.ERROR_EVENT, error => {
this.logger.error("App ReLoad failed with error: %o", error);
reject(error);
})
.on(Task.events.SUCCESS_EVENT, data => {
this.logger.info(
"App ReLoaded successfully with App (id=%s, key=%s)",
data.getId(),
data.getKey()
);
resolve(data);
})
.commit();
} catch (err) {
this.logger.error("Error could not commit task %o", err);
return reject(new Error("Error commiting task"));
}
});
}
/**
* @description Unload an already loaded App (delegates to TaskManager for async operation)
* @argument {App} app The App to unload
* @returns {Promise} Promise which resolves when app has been loaded.
*/
unloadApp(app) {
// Use TaskManager to schedule unloading the App
return new Promise(async (resolve, reject) => {
let task;
this.logger.info(
"APP UNLOAD has been requested, creating a task for it (id=%s)",
app.getId()
);
try {
task = await this.taskManager.create(Task.types.APP_UNLOAD, {
app: app
});
} catch (err) {
this.logger.error("Error creating task %o", err);
return reject(err);
}
// Schedule it immediately
try {
task
.on(Task.events.ERROR_EVENT, error => {
this.logger.error("App UnLoad failed with error: %o", error);
reject(error);
})
.on(Task.events.SUCCESS_EVENT, data => {
this.logger.info(
"App UnLoaded successfully (id=%s, key=%s)",
data.getId(),
data.getKey()
);
resolve(data);
})
.commit();
} catch (err) {
this.logger.error("Error could not commit task %o", err);
return reject(new Error("Error commiting task"));
}
});
}
/**
* @description Enable an already loaded App (delegates to TaskManager for async operation)
* @argument {App} app The App to enable
* @returns {Promise} promise which resolves when app has been enabled
*/
enableApp(app) {
// Resolve immediately if App is enabled
if (app.isEnabled()) {
return Promise.resolve(app);
}
// Use TaskManager to schedule enabling the App
return new Promise(async (resolve, reject) => {
let task;
try {
task = await this.taskManager.create(Task.types.APP_ENABLE, {
app: app
});
} catch (err) {
this.logger.error("Error creating task %o", err);
return reject(err);
}
// Schedule it immediately
try {
task
.on(Task.events.ERROR_EVENT, error => {
reject(error);
})
.on(Task.events.SUCCESS_EVENT, data => {
resolve(data);
})
.commit();
} catch (err) {
this.logger.error("Error could not commit task %o", err);
return reject(new Error("Error commiting task"));
}
});
}
/**
* @description Disable an already loaded/enabled App (delegates to TaskManager for async operation)
* @argument {App} app The App to disable
* @returns {Promise} Promise which resolves when app has been disabled.
*/
disableApp(app) {
// Resolve immediately if App is enabled
if (!app.isEnabled()) {
return Promise.resolve(app);
}
// Use TaskManager to schedule enabling the App
return new Promise(async (resolve, reject) => {
let task;
try {
task = await this.taskManager.create(Task.types.APP_DISABLE, {
app: app
});
} catch (err) {
this.logger.error("Error creating task %o", err);
return reject(err);
}
// Schedule it immediately
try {
task
.on(Task.events.ERROR_EVENT, error => {
reject(error);
})
.on(Task.events.SUCCESS_EVENT, data => {
resolve(data);
})
.commit();
} catch (err) {
this.logger.error("Error could not commit task %o", err);
return reject(new Error("Error commiting task"));
}
});
}
/**
* @description Get all Apps that match the predicate
* @argument {Function} predicate : filter the list of Apps using this test
* @returns {Array} Array of Apps matching predicate
*/
async getApps(predicate) {
// Search Store for all known Apps
return new Promise((resolve, reject) => {
let raw = [],
apps = [],
filtered = [];
try {
raw = this.store.find(doc => doc.docType === App.DOCTYPE);
raw.forEach(app => {
apps.push(new App(app));
});
if (predicate && typeof predicate === "function") {
filtered = apps.filter(predicate);
} else {
filtered = apps;
}
resolve(filtered);
} catch (e) {
reject(e);
}
});
}
/**
* @description Get a single known App
* @argument {Object} id The ID of the App (12 char shortform or 64 char longform)
* @returns {App} Requested App
*/
async getApp(id) {
return new Promise((resolve, reject) => {
let doc, app;
try {
// Find the app in the store
doc = this.store.read(id);
if (!doc || (doc.docType && doc.docType !== App.DOCTYPE))
throw new Error("App (id=" + id + ") doesnt exist in the store");
// Hydrate the module data from their individual stored instances as that is the information which
// is updated on a per module basis etc.
if (doc.modules && doc.modules.length) {
doc.modules = doc.modules.map((cur, idx, arr) => {
return this.store.read(cur.id);
});
}
// Return a new Instance of App from the data
app = new App(doc);
resolve(app);
} catch (e) {
reject(e);
}
});
}
/**
* @description Return array of modules matching a filter object
* @argument {Function} predicate Function returning truthy value to test objects in the store against
* @returns {Array} Array of Modules matching filter
*/
getModules(predicate) {
// Search Store for all known Apps
return new Promise((resolve, reject) => {
let raw = [],
modules = [];
try {
raw = this.store.find(doc => doc.docType === Module.DOCTYPE);
raw.forEach(module => {
modules.push(ModuleFactory.create({ module }));
});
if (predicate && typeof predicate === "function") {
modules = modules.filter(predicate);
}
resolve(modules);
} catch (e) {
reject(e);
}
});
}
/**
* @description Return array of modules matching a filter object
* (but only if the module and its parent App are both enabled)
* @argument {Function} predicate Function returning truthy value to test objects in the store against
* @returns {Array} Array of Modules matching filter
*/
getEnabledModules(predicate) {
return new Promise((resolve, reject) => {
let raw = [],
modules = [];
try {
raw = this.store.find(
doc => doc.docType === Module.DOCTYPE && doc.enabled === true
);
raw.forEach(module => {
const app = this.store.read(module.appId);
// only if both app and module are enabled
if (app.enabled === true) {
modules.push(ModuleFactory.create({ module }));
}
});
if (predicate && typeof predicate === "function") {
modules = modules.filter(predicate);
}
resolve(modules);
} catch (e) {
reject(e);
}
});
}
/**
* @description Return a single App(s) module(s)
* @argument {String} id The unique id of the Module
* @returns {Module} Requested Module
*/
getModule(id) {
return new Promise((resolve, reject) => {
let json, module;
try {
json = this.store.read(id);
if (!json || (json.docType && json.docType !== Module.DOCTYPE))
throw new Error("Module (id=" + id + ") doesnt exist");
module = ModuleFactory.create({ module: json });
resolve(module);
} catch (e) {
reject(e);
}
});
}
/**
* @description Enable an already loaded Module by an App UUID and module Key
* @argument {Module} module
* @returns {Promise} Promise which resolves when module has been enabled.
*/
enableModule(module) {
// Resolve immediately if App is enabled
if (module.isEnabled()) {
return Promise.resolve(module);
}
// Use TaskManager to schedule enabling the App
return new Promise(async (resolve, reject) => {
let task;
try {
task = await this.taskManager.create(Task.types.MODULE_ENABLE, {
module: module
});
} catch (err) {
this.logger.error("Error creating task %o", err);
return reject(err);
}
// Schedule it immediately
try {
task
.on(Task.events.ERROR_EVENT, error => {
reject(error);
})
.on(Task.events.SUCCESS_EVENT, data => {
resolve(data);
})
.commit();
} catch (err) {
this.logger.error("Error could not commit task %o", err);
return reject(new Error("Error commiting task"));
}
});
}
/**
* @description Disable an already enabled Module by an App UUID and module Key
* @argument {Module} module
* @returns {Promise} Promise which resolves when module has been disabled.
*/
disableModule(module) {
// Resolve immediately if App is enabled
if (!module.isEnabled()) {
return Promise.resolve(module);
}
// Use TaskManager to schedule enabling the App
return new Promise(async (resolve, reject) => {
let task;
try {
task = await this.taskManager.create(Task.types.MODULE_DISABLE, {
module: module
});
} catch (err) {
this.logger.error("Error creating task %o", err);
return reject(err);
}
// Schedule it immediately
try {
task
.on(Task.events.ERROR_EVENT, error => {
reject(error);
})
.on(Task.events.SUCCESS_EVENT, data => {
resolve(data);
})
.commit();
} catch (err) {
this.logger.error("Error could not commit task %o", err);
return reject(new Error("Error commiting task"));
}
});
}
} |
JavaScript | class Autocomplete extends Component {
constructor(props) {
super(props);
this.list = this.props.list;
this.state = {
items: [],
query: '',
focused: false,
};
}
//TODO: shouldn't set state in componentDidMount()
componentDidMount() {
const items = this.props.list;
this.setState({ items });
}
findItem(query) {
if (query === '') {
return [];
}
const { items } = this.state;
const regex = new RegExp(`${query.trim()}`, 'i');
return items.filter(item => item.displayName.search(regex) >= 0);
}
render() {
const { query } = this.state;
const items = this.findItem(query);
const comp = (a, b) => a.toLowerCase().trim() === b.displayName.toLowerCase().trim();
return (
<View containerStyle={styles.container}>
<AutocompleteJS
autoCapitalize="none"
autoCorrect={false}
listStyle={this.props.listStyle}
containerStyle={this.props.containerStyle}
data={items.length === 1 && comp(query, items[0]) ? [] : items}
defaultValue={query}
onChangeText={text => {
this.setState({ query: text });
this.props.onChangeText(text);
}}
keyExtractor = { (item, index) => index.toString() }
onFocus={() => this.setState({focused: true})}
onBlur={() => this.setState({focused: false})}
placeholder="First Name"
renderItem={(n) => (
this.state.focused ?
<View>
<TouchableOpacity
id={n.id}
style={styles.dropdown}
onPress={() => {
this.setState({ query: n.item.displayName });
this.props.onChangeText(n.item.displayName);
}}>
<Text style={styles.itemText}>
{n.item.displayName}
</Text>
</TouchableOpacity>
</View>
: <View />
)}
/>
</View>
);
}
} |
JavaScript | class AI { // eslint-disable-line no-unused-vars
/**
* AI constructor
* @constructor
*/
constructor() {
/**
* Entity to which AI is attached
* @type {AutonomyEntity}
*/
this.entity = null;
}
/**
* Set autonomy entity
* @param {AutonomyEntity} entity Autonomy entity
*/
setEntity(entity) {
this.entity = entity;
}
/**
* Initialize AI
* @abstract
*/
init() {}
/**
* Update AI
* @abstract
* @param {number} dt Delta time
*/
update(dt) {}
/**
* Apply AI and decide action
* @abstract
* @param {number} dt Delta time
* @return {boolean} Whether decided on action
*/
apply(dt) {}
} |
JavaScript | class NodeIdentityService extends IdentityService {
/**
* Constructor.
* @param {any} stub the stub for this invocation
*/
constructor(stub) {
super();
const method = 'constructor';
LOG.entry(method, stub);
this.stub = stub;
LOG.exit(method);
}
/**
* Load and process a certificate.
*/
_loadCertificate() {
const method = '_loadCertificate';
LOG.entry(method);
let creator = this.stub.getCreator();
this.pem = creator.getIdBytes().toString('utf8');
if (this.pem && this.pem.startsWith('-----BEGIN CERTIFICATE-----')) {
this.certificate = new Certificate(this.pem);
this.identifier = this.certificate.getIdentifier();
this.issuer = this.certificate.getIssuer();
this.name = this.certificate.getName();
}
else {
const newErr = new Error('No creator certificate provided or not a valid x509 certificate');
LOG.error(method, newErr);
throw newErr;
}
LOG.exit(method);
}
/**
* Get a unique identifier for the identity used to submit the transaction.
* @return {string} A unique identifier for the identity used to submit the transaction.
*/
getIdentifier() {
const method = 'getIdentifier';
LOG.entry(method);
if (!this.identifier) {
this._loadCertificate();
}
LOG.exit(method, this.identifier);
return this.identifier; // this.Certificate.raw, hashed using sha256 and sum result
}
/**
* Get the name of the identity used to submit the transaction.
* @return {string} The name of the identity used to submit the transaction.
*/
getName() {
const method = 'getName';
LOG.entry(method);
if (!this.name) {
this._loadCertificate();
}
LOG.exit(method, this.name);
return this.name;
}
/**
* Get the issuer of the identity used to submit the transaction.
* @return {string} The issuer of the identity used to submit the transaction.
*/
getIssuer() {
const method = 'getIssuer';
LOG.entry(method);
if (!this.issuer) {
this._loadCertificate();
}
LOG.exit(method, this.issuer);
return this.issuer; // this.Certificate.Issuer.raw, hashed using sha256 and sum result
}
/**
* Get the certificate for the identity used to submit the transaction.
* @return {string} The certificate for the identity used to submit the transaction.
*/
getCertificate() {
const method = 'getCertificate';
LOG.entry(method);
if (!this.pem) {
this._loadCertificate();
}
LOG.exit(method, this.pem);
return this.pem;
}
} |
JavaScript | class ClassMetadata extends mix(BaseClassMetadata, ClassMetadataInterface, GenericMetadataTrait) {
/**
* Constructs a metadata for the given class.
*
* @param {ReflectionClass} reflectionClass
*/
__construct(reflectionClass) {
super.__construct(reflectionClass);
/**
* @type {string}
*
* @private
*/
this._defaultGroup = this.reflectionClass.shortName;
/**
* @type {string[]}
*
* @private
*/
this._groupSequence = null;
/**
* @type {boolean}
*
* @private
*/
this._groupSequenceProvider = false;
/**
* The strategy for traversing traversable objects.
* By default, only arrays and object literal are traversed.
*
* @type {int}
*
* @private
*/
this._traversalStrategy = TraversalStrategy.IMPLICIT;
}
/**
* @inheritdoc
*/
__sleep() {
const parentProperties = new Set(super.__sleep());
// Don't store the cascading strategy. Classes never cascade.
parentProperties.delete('_cascadingStrategy');
return [
...parentProperties,
'_groupSequence',
'_groupSequenceProvider',
'_defaultGroup',
];
}
/**
* Returns the name of the default group for this class.
*
* For each class, the group "Default" is an alias for the group
* "<ClassName>", where <ClassName> is the non-namespaced name of the
* class. All constraints implicitly or explicitly assigned to group
* "Default" belong to both of these groups, unless the class defines
* a group sequence.
*
* If a class defines a group sequence, validating the class in "Default"
* will validate the group sequence. The constraints assigned to "Default"
* can still be validated by validating the class in "<ClassName>".
*
* @returns {string} The name of the default group
*/
get defaultGroup() {
return this._defaultGroup;
}
/**
* @inheritdoc
*/
addConstraint(constraint) {
const targets = isArray(constraint.targets) ? constraint.targets : [ constraint.targets ];
if (! targets.includes(Constraint.CLASS_CONSTRAINT)) {
throw new ConstraintDefinitionException(__jymfony.sprintf('The constraint "%s" cannot be put on classes.', ReflectionClass.getClassName(constraint)));
}
if (constraint instanceof Valid) {
throw new ConstraintDefinitionException(__jymfony.sprintf('The constraint "%s" cannot be put on classes.', ReflectionClass.getClassName(constraint)));
}
if (constraint instanceof Traverse) {
if (constraint.traverse) {
// If traverse is true, traversal should be explicitly enabled
this._traversalStrategy = TraversalStrategy.TRAVERSE;
} else {
// If traverse is false, traversal should be explicitly disabled
this._traversalStrategy = TraversalStrategy.NONE;
}
// The constraint is not added
return this;
}
constraint.addImplicitGroupName(this.defaultGroup);
super.addConstraint(constraint);
return this;
}
/**
* @inheritdoc
*/
addAttributeMetadata(metadata) {
const name = metadata instanceof PropertyMetadataInterface ? metadata.propertyName : metadata.name;
this._attributesMetadata[name] = metadata;
this._attributesNames.set(name.toLowerCase(), name);
}
/**
* Adds a constraint to the given property.
*
* @param {string} property The name of the property
* @param {Jymfony.Component.Validator.Constraint} constraint The constraint
*
* @returns {Jymfony.Component.Validator.Mapping.ClassMetadata}
*/
addFieldConstraint(property, constraint) {
if (undefined === this._attributesMetadata[property]) {
const memberMetadata = new FieldMetadata(this._reflectionClass.name, property);
this.addAttributeMetadata(memberMetadata);
}
constraint.addImplicitGroupName(this.defaultGroup);
this._attributesMetadata[property].addConstraint(constraint);
return this;
}
/**
* @param {string} property
* @param {Jymfony.Component.Validator.Constraint[]} constraints
*
* @returns {Jymfony.Component.Validator.Mapping.ClassMetadata}
*/
addFieldConstraints(property, constraints) {
for (const constraint of constraints) {
this.addFieldConstraint(property, constraint);
}
return this;
}
/**
* Adds a constraint to the getter of the given property.
*
* @param {string} property The name of the property
* @param {Jymfony.Component.Validator.Constraint} constraint The constraint
*
* @returns {Jymfony.Component.Validator.Mapping.ClassMetadata}
*/
addPropertyGetterConstraint(property, constraint) {
if (undefined === this._attributesMetadata[property]) {
this.addAttributeMetadata(new GetterMetadata(this._reflectionClass.name, property));
}
constraint.addImplicitGroupName(this.defaultGroup);
this._attributesMetadata[property].addConstraint(constraint);
return this;
}
/**
* Adds a constraint to the getter of the given property.
*
* @param {string} property The name of the property
* @param {Jymfony.Component.Validator.Constraint} constraint The constraint
*
* @returns {Jymfony.Component.Validator.Mapping.ClassMetadata}
*/
addGetterConstraint(property, constraint) {
if (undefined === this._attributesMetadata[property]) {
this.addAttributeMetadata(new GetterMetadata(this._reflectionClass.name, property));
}
constraint.addImplicitGroupName(this.defaultGroup);
this._attributesMetadata[property].addConstraint(constraint);
return this;
}
/**
* @param {string} property
* @param {Jymfony.Component.Validator.Constraint[]} constraints
*
* @returns {Jymfony.Component.Validator.Mapping.ClassMetadata}
*/
addPropertyGetterConstraints(property, constraints) {
for (const constraint of constraints) {
this.addPropertyGetterConstraint(property, constraint);
}
return this;
}
/**
* @param {string} property
* @param {Jymfony.Component.Validator.Constraint[]} constraints
*
* @returns {Jymfony.Component.Validator.Mapping.ClassMetadata}
*/
addGetterConstraints(property, constraints) {
for (const constraint of constraints) {
this.addGetterConstraint(property, constraint);
}
return this;
}
/**
* Adds a constraint to the getter of the given property.
*
* @param {string} property
* @param {string} method
* @param {Jymfony.Component.Validator.Constraint} constraint
*
* @returns {Jymfony.Component.Validator.Mapping.ClassMetadata}
*/
addGetterMethodConstraint(property, method, constraint) {
if (undefined === this._attributesMetadata[property]) {
this.addAttributeMetadata(new GetterMetadata(this._reflectionClass.name, property, method));
}
constraint.addImplicitGroupName(this.defaultGroup);
this._attributesMetadata[property].addConstraint(constraint);
return this;
}
/**
* @param {string} property
* @param {string} method
* @param {Jymfony.Component.Validator.Constraint[]} constraints
*
* @returns {Jymfony.Component.Validator.Mapping.ClassMetadata}
*/
addGetterMethodConstraints(property, method, constraints) {
for (const constraint of constraints) {
this.addGetterMethodConstraint(property, method, constraint);
}
return this;
}
/**
* Merges the constraints of the given metadata into this object.
*
* @param {Jymfony.Component.Validator.Mapping.ClassMetadata} source
*/
merge(source) {
if (source.isGroupSequenceProvider) {
this.setGroupSequenceProvider(true);
}
for (const constraint of source.constraints) {
this.addConstraint(__jymfony.clone(constraint));
}
for (let [ , member ] of __jymfony.getEntries(this._attributesMetadata)) {
member = __jymfony.clone(member);
__assert(member instanceof Jymfony.Component.Validator.Mapping.MemberMetadata);
for (const constraint of member.constraints) {
if (constraint.groups.includes(Constraint.DEFAULT_GROUP)) {
member._constraintsByGroup[this.defaultGroup].push(constraint);
}
constraint.addImplicitGroupName(this.defaultGroup);
}
this.addAttributeMetadata(member);
}
}
/**
* @inheritdoc
*/
get constrainedProperties() {
return Object.keys(this._attributesMetadata);
}
/**
* Sets the default group sequence for this class.
*
* @param {string[]|Jymfony.Component.Validator.Constraints.GroupSequence} groupSequence An array of group names
*
* @returns {Jymfony.Component.Validator.Mapping.ClassMetadata}
*
* @throws {Jymfony.Component.Validator.Exception.GroupDefinitionException}
*/
setGroupSequence(groupSequence) {
if (this.isGroupSequenceProvider) {
throw new GroupDefinitionException('Defining a static group sequence is not allowed with a group sequence provider');
}
if (isArray(groupSequence)) {
groupSequence = new GroupSequence(groupSequence);
}
if (groupSequence.groups.includes(Constraint.DEFAULT_GROUP)) {
throw new GroupDefinitionException(__jymfony.sprintf('The group "%s" is not allowed in group sequences', Constraint.DEFAULT_GROUP));
}
if (! groupSequence.groups.includes(this.defaultGroup)) {
throw new GroupDefinitionException(__jymfony.sprintf('The group "%s" is missing in the group sequence', this.defaultGroup));
}
this._groupSequence = groupSequence;
return this;
}
/**
* @inheritdoc
*/
hasGroupSequence() {
return this._groupSequence && 0 < this._groupSequence.groups.length;
}
/**
* @inheritdoc
*/
get groupSequence() {
return this._groupSequence;
}
/**
* Sets whether a group sequence provider should be used.
*
* @param {boolean} active
*
* @throws {Jymfony.Component.Validator.Exception.GroupDefinitionException}
*/
setGroupSequenceProvider(active) {
if (this.hasGroupSequence()) {
throw new GroupDefinitionException('Defining a group sequence provider is not allowed with a static group sequence');
}
if (! this._reflectionClass.isInstanceOf('Jymfony.Component.Validator.GroupSequenceProviderInterface')) {
throw new GroupDefinitionException(__jymfony.sprintf('Class "%s" must implement GroupSequenceProviderInterface', this.name));
}
this._groupSequenceProvider = active;
}
/**
* @inheritdoc
*/
get isGroupSequenceProvider() {
return this._groupSequenceProvider;
}
/**
* Class nodes are never cascaded.
*
* @inheritdoc
*/
get cascadingStrategy() {
return CascadingStrategy.NONE;
}
/**
* @inheritdoc
*/
_createNullMetadata(name) {
return new NullMetadata(name);
}
} |
JavaScript | class ExportDialog extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Modal show={this.props.show} onHide={this.props.onClose}>
<Modal.Header closeButton>
<Modal.Title>Export current configuration</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form.Control
as="textarea"
readOnly
value={JSON.stringify(this.props.data)}
rows="5" />
</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={this.props.onClose}>
Close
</Button>
</Modal.Footer>
</Modal>
);
}
} |
JavaScript | class Drawable {
/**
* Given a mesh internal name and a program internal name, construct
* a Drawable
* @param {String} programName Program internal name
* @param {String} meshName Mesh internal Name
*/
constructor(programName, meshName) {
this.programName = programName;
this.meshName = meshName;
this.mesh = null;
this.program = null;
this.uniforms = {};
this.drawfn = this._draw.bind(this);
this.elapsed = 0;
this.ready = false;
this.viewProject = mat4.create();
this._translate = vec3.create();
this._rotate = quat.create();
this._scale = vec3.fromValues(1, 1, 1);
this._model = mat4.create();
this._ray = vec3.create();
this.local = mat4.create();
this.world = mat4.create();
this.uniforms.u_modelViewProject = mat4.create();
this.children = [];
this.drawMode = Mesh.MODE_TRIANGLES;
this.animator = new Animator();
}
_loadAssets(manager) {
let promises = [];
if(this.meshName) {
promises.push(
manager.loadMesh(this.meshName).then((mesh) => {
this.mesh = mesh;
return mesh;
}).catch((err) => {
console.warn('missing mesh ' + this.meshName); // eslint-disable-line no-console
return Promise.reject(err);
})
);
}
if(this.programName) {
promises.push(
manager.loadProgram(this.programName).then((program) => {
this.program = program;
return program;
}).catch((err) => {
console.warn('missing program' + this.programName); // eslint-disable-line no-console
return Promise.reject(err);
})
);
}
return promises;
}
/**
* Initializer for the drawable
*
* Hooks up the drawable to all its gl-bound resources
*
* @param {AssetManager} manager AssetManager containing the managed resources for this
* drawable.
* @return {Promise} Resolves if the assets are successfully found and initialized,
* rejects (and generates a warning) otherwise.
*/
init(manager) {
let promises = this._loadAssets(manager);
return Promise.all(promises).then(() => {
this.ready = true;
return this;
});
}
/**
* Sets the specific draw function for this drawable
*
* @chainable
* @param {Function} fn The draw function to use when drawable this object
* @return {this} Returns `this`
*/
setDrawFn(fn) {
this.drawfn = fn;
return this;
}
/**
* Executes a draw call for this object
*
* Issues a warning if the drawable has not yet been initialized with `init`
* @return {void}
*/
draw() {
if(this.ready) {
if(this.program) {
this.program.use(this.drawfn);
}
}
}
/**
* Sets a uniform on the drawable
*
* @chainable
* @param {String} name Name of the drawable to set
* @param {mixed} value Value to set on the drawable.
* @returns {this} Returns `this`
*/
setUniform(name, value) {
this.uniforms[name] = value;
return this;
}
/**
* Updates the elapsed time for this object.
*
* Also executes any periodic updates that have been applied to the drawable
* (i.e. animations). If this function returns a falsey value, it signals that the
* animation has ended, and that the object should be removed from the draw loop.
*
* @param {Number} delta Amount of time that has elapsed since the last draw call
* @return {boolean} Return false if the object should be removed from the
* return loop.
*/
updateTime(delta) {
this.elapsed += delta;
this.animator.runAnimations(delta, this);
return true;
}
/**
* Adds a drawable as a child of this one.
* @param {Drawable} drawable The child drawable.
* @return {void}
*/
addChild(drawable) {
if (!(drawable instanceof Drawable)) {
throw new Error('Child drawable should be an instance of Drawable');
}
drawable.updateWorld(this._model);
this.children.push(drawable);
}
/**
* Update the internal u_modelViewProject uniform
* by applying world and local transforms to the model
* matrix. Then, propagate the new local transform to all the children
* by way of their world transforms.
* @return {void}
*/
updateMatrix() {
var translateRotate = mat4.create();
mat4.fromRotationTranslation(translateRotate, this._rotate, this._translate);
mat4.scale(this.local, translateRotate, this._scale);
mat4.multiply(this._model, this.world, this.local);
mat4.multiply(this.uniforms.u_modelViewProject, this.viewProject, this._model);
this.children.forEach((child) => {
child.updateWorld(this._model);
});
}
/**
* Updates the model's "world" transform.
* @param {mat4} world A world transform
* @return {void}
*/
updateWorld(world) {
this.world = world;
this.updateMatrix();
}
/**
* Update the internal viewProject matrix (projection * view matrices)
* @param {mat4} viewProject Projection matrix multiplied by view matrix
* @return {void}
*/
updateView(viewProject/*, camera*/) {
this.viewProject = viewProject;
this.updateMatrix();
this.updateRay();
}
/**
* Updates the internal representation of the ray from the camera to the
* drawable
* @return {void}
*/
updateRay() {
vec3.copy(this._ray, this._translate);
vec3.transformMat4(this._ray, this._ray, this.world);
vec3.transformMat4(this._ray, this._ray, this.viewProject);
}
/**
* Translate a model along some vector
* @param {vec3} vec The vector
* @return {void}
*/
translate(vec) {
vec3.add(this._translate, this._translate, vec);
this.updateMatrix();
this.updateRay();
}
/**
* Sets the position to some vector
* @param {vec3} vec The new position
* @return {void}
*/
setTranslation(vec) {
this._translate = vec3.create();
this.translate(vec);
}
/**
* Scale a model by some vector
* @param {vec3} vec The vector
* @return {void}
*/
scale(vec) {
vec3.multiply(this._scale, this._scale, vec);
this.updateMatrix();
}
/**
* Sets the scale of the local transform
* @param {vec3} vec The scale to set to.
* @return {void}
*/
setScale(vec) {
this._scale = vec3.fromValues(1, 1, 1);
this.scale(vec);
}
/**
* Rotate a model with a quaternion
* @param {quat} q The quaternion
* @return {void}
*/
rotate(q) {
quat.multiply(this._rotate, this._rotate, q);
this.updateMatrix();
}
/**
* Sets the object's rotation from a quaternion
* @param {quat} q The new rotation
* @return {void}
*/
setRotation(q) {
this._rotate = quat.create();
this.rotate(q);
}
/**
* Translate the model along the X axis
* @param {float} dist Distance to translate
* @return {void}
*/
translateX(dist) {
this.translate(vec3.fromValues(dist, 0, 0));
}
/**
* Translate the model along the Y axis
* @param {float} dist Distance to translate
* @return {void}
*/
translateY(dist) {
this.translate(vec3.fromValues(0, dist, 0));
}
/**
* Translate the model along the Z axis
* @param {float} dist Distance to translate
* @return {void}
*/
translateZ(dist) {
this.translate(vec3.fromValues(0, 0, dist));
}
/**
* Scale all dimensions by the same value
* @param {Number} f The amount to _scale
* @return {void}
*/
scalarScale(f) {
this.scale(vec3.fromValues(f, f, f));
}
/**
* Sets the local scale to some scalar value (for x, y, and z)
* @param {Number} f Amount to set the scale to.
* @return {void}
*/
setScalarScale(f) {
this.setScale(vec3.fromValues(f, f, f));
}
/**
* Sets the drawing mode for this drawable. Should be one of the modes
* found on Mesh
*
* @see Mesh
* @param {enum} mode One of the Mesh.MODE_* constants
* @return {void}
*/
setDrawMode(mode) {
let modes = [Mesh.MODE_TRIANGLES, Mesh.MODE_LINES];
if(modes.indexOf(mode) === -1) {
throw new Error('mode should be one of ' + modes.join(', '));
}
this.drawMode = mode;
}
/**
* Sets the draw mode to draw lines
* @return {void}
*/
drawLines() {
this.setDrawMode(Mesh.MODE_LINES);
}
/**
* Sets the draw mode to draw triangles
* @return {void}
*/
drawFaces() {
this.setDrawMode(Mesh.MODE_TRIANGLES);
}
/**
* NYI
* @return {void}
*/
dispose() {
// noop;
}
/**
* Adds an animation
*
* @chainable
* @param {Animation} animation The animation to be run.
* This will need to be started independently, or prior to being added.
* @return {this} Returns `this`
*/
addAnimation(animation) {
this.animator.addAnimation(animation);
return this;
}
_draw(locations, uniforms) {
for(var i in this.uniforms)
{
if(this.uniforms.hasOwnProperty(i) && (i in uniforms))
{
uniforms[i](this.uniforms[i]);
}
}
this.mesh.draw(locations, this.drawMode);
}
} |
JavaScript | class Serializer {
static encode(value, encoders = [encodeJson]) {
return encoders.reduce((p, c) => c(p), value);
}
static decode(value, decoders = [decodeJson]) {
return decoders.reduce((p, c) => c(p), value);
}
static encodeJson(value) {
return this.encode(value, [encodeJson]);
}
static decodeJson(value) {
return this.decode(value, [decodeJson]);
}
static encodeBase64(value) {
return this.encode(value, [encodeJson, encodeBase64]);
}
static decodeBase64(value) {
return this.decode(value, [decodeBase64, decodeJson]);
}
} |
JavaScript | class NeoFooter extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div/>
}
} |
JavaScript | class HandlerGenerator {
login (req, res) {
console.log(req, res);
let username = req.body.username;
let password = req.body.password;
// For the given username fetch user from DB
let mockedUsername = "admin";
let mockedPassword = "password";
if (username && password) {
if (username === mockedUsername && password === mockedPassword) {
let token = jwt.sign({ username: username }, config.secret, {
expiresIn : "24h" // expires in 24 hours
});
// return the JWT token for the future API calls
res.json({
success : true,
message : "Authentication successful!",
token : token
});
}
else {
res.send(403).json({
success : false,
message : "Incorrect username or password"
});
}
}
else {
res.send(400).json({
success : false,
message : "Authentication failed! Please check the request"
});
}
}
index (req, res) {
res.json({
success : true,
message : "Index page"
});
}
} |
JavaScript | class Headline {
constructor(theTag){
this.type = 'Headline';
this.tag = theTag;
this.content;
}
setTag(newTag){ this.tag = newTag; }
setContent(theContent){ this.content = theContent; }
returnMarkup(){
let newHeadline = document.createElement(this.tag);
newHeadline.innerText = this.content;
return newHeadline;
}
} |
JavaScript | class Paragraph {
constructor(){
this.type = 'Paragraph';
this.content;
}
setContent(theContent){ this.content = theContent; }
returnMarkup(){
let newCopy = document.createElement('p');
newCopy.innerText = this.content;
return newCopy;
}
} |
JavaScript | class Container {
constructor(){
// Set main attributes
this.type = 'Container';
this.id;
this.classList = [];
this.attributes = [];
this.elements = [];
}
setType(theType){ this.type = theType }
setID(newID){ if(newID != undefined){ this.id = newID } }
addID(){
let newDate = Date.now();
let newID = 'container_';
let randomNumber = 1 + Math.floor(Math.random() * 100);
let uniqueNum = newDate * randomNumber;
newID += uniqueNum;
this.id = newID;
}
addClass(newClass){ if (newClass != undefined){ this.classList.push(newClass.toString()) } }
removeClass(theClass){
if(this.classList.includes(theClass)){
let myIndex = this.classList.indexOf(theClass);
this.classList.splice(myIndex, 1);
}
}
addAttribute(theAttr){ if (theAttr != undefined){ this.attributes.push(theAttr.toString()) } }
removeAttribute(theAttr){
if(this.attributes.includes(theAttr)){
let myIndex = this.attributes.indexOf(theAttr);
this.attributes.splice(myIndex, 1);
}
}
addElement(theEl){
if (theEl != undefined){ this.elements.push(theEl) }
}
setClasses(theElement){
if(this.classList.length > 0){
for (let i=0; i < this.classList.length; i++){ theElement.classList.add(this.classList[i]) }
}
}
setAttributes(theElement){
if(this.attributes.length > 0){
for (let j = 0; j < this.attributes.length; j++) { theElement.setAttribute(this.attributes[j], true); }
}
}
setElements(theElement){
if(this.elements.length > 0){
for (let k = 0; k < this.elements.length; k++){ theElement.append(this.elements[k]); }
}
}
returnMarkup(){
let newContainer = document.createElement('div');
if(this.id != undefined){newContainer.setAttribute('id', this.id)}
this.setClasses(newContainer);
this.setAttributes(newContainer);
this.setElements(newContainer);
return newContainer;
}
returnJSON(){
return JSON.stringify(this);
}
} |
JavaScript | class Button extends Container {
constructor(theText){
super();
if (theText != undefined){ this.innerText = theText ; }
else { this.innerText = 'Button'; }
}
setText(theText){ this.innerText = theText; }
returnMarkup(){
let newButton = document.createElement('button');
newButton.appendChild(document.createTextNode(this.innerText));
if(this.id != undefined){newButton.setAttribute('id', this.id)}
this.setClasses(newButton);
this.setAttributes(newButton);
this.setElements(newButton);
return newButton;
}
} |
JavaScript | class Link extends Button {
constructor(theHref, theText){
super(theText);
if (theHref != undefined){ this.href = theHref; }
else { this.href = '#' }
this.tabindex = 0;
this.target = '_blank';
this.aria = {};
this.aria.label;
}
setHref(theHref){
if (theHref != undefined){ this.href = theHref; }
}
setTabIndex(theIndex){
if (theIndex != undefined){ this.tabindex = theIndex; }
}
setTarget(theTarget){
if (theTarget != undefined){ this.target = theTarget; }
}
returnMarkup(){
let newLink = document.createElement('a');
newLink.appendChild(document.createTextNode(this.innerText));
if(this.id != undefined){newLink.setAttribute('id', this.id)}
if(this.href != undefined){newLink.setAttribute('href', this.href)}
if(this.aria.label != undefined){newLink.setAttribute('href', this.aria.label)}
newLink.setAttribute('tabindex', this.tabindex.toString());
newLink.setAttribute('target', this.target);
this.setClasses(newLink);
this.setAttributes(newLink);
this.setElements(newLink);
return newLink;
}
} |
JavaScript | class ArgumentList extends Array {
/**
* Declares the class name.
*
* @access public
*/
constructor() {
super();
declareCLIKitClass(this, 'ArgumentList');
}
/**
* Adds an argument to the list.
*
* @param {Object|String|Argument|ArgumentList|Array<Object|String|Argument>} arg - An object
* of argument names to argument descriptors, an argument name, an `Argument` instance, an
* `ArgumentList` instance, or array of object descriptors, argument names, and `Argument`
* instances.
* @access public
*/
add(arg) {
const args = Array.isArray(arg) ? arg : [ arg ];
this.push.apply(this, args.map(a => new Argument(a)));
}
/**
* Returns the number of arguments.
*
* @returns {Number}
* @access public
*/
get count() {
return this.args.length;
}
/**
* Generates an object containing the arguments for the help screen.
*
* @returns {Object}
* @access public
*/
generateHelp() {
const entries = [];
for (const { desc, hidden, hint, multiple, name, required } of this) {
if (!hidden) {
entries.push({
desc,
hint,
multiple,
name,
required
});
}
}
return {
count: entries.length,
entries
};
}
} |
JavaScript | class SegmentRowsetStat {
/**
* Create a SegmentRowsetStat.
* @property {uuid} [rowsetId] Gets a Rowset Id for the Rowset Stat.
* @property {number} [rowsetCount] Gets a Rowset Count for the Rowset Id.
*/
constructor() {
}
/**
* Defines the metadata of SegmentRowsetStat
*
* @returns {object} metadata of SegmentRowsetStat
*
*/
mapper() {
return {
required: false,
serializedName: 'SegmentRowsetStat',
type: {
name: 'Composite',
className: 'SegmentRowsetStat',
modelProperties: {
rowsetId: {
required: false,
serializedName: 'rowsetId',
type: {
name: 'String'
}
},
rowsetCount: {
required: false,
serializedName: 'rowsetCount',
type: {
name: 'Number'
}
}
}
}
};
}
} |
JavaScript | class LineItemList extends Resource {
static getSchema () {
return {
data: ['LineItem'],
hasMore: Boolean,
next: String,
object: String
}
}
} |
JavaScript | class ObserverAdmin extends Service {
/**
* adds element to observe entries of IntersectionObserver
*
* @method add
* @param {Node} element
* @param {Function} enterCallback
* @param {Function} exitCallback
* @param {Object} options
*/
add(element, enterCallback, exitCallback, options) {
let { root = window } = options;
let { elements, intersectionObserver } = this._findRoot(root);
if (elements && elements.length > 0) {
elements.push({ element, enterCallback, exitCallback });
intersectionObserver.observe(element, options);
} else {
let newIO = new IntersectionObserver(bind(this, this._setupOnIntersection(root)), options);
newIO.observe(element);
DOMRef.set(root, { elements: [{ element, enterCallback, exitCallback }], intersectionObserver: newIO });
}
}
/**
* @method unobserve
* @param {Node} element
* @param {Node|window} root
*/
unobserve(element, root) {
let { intersectionObserver } = this._findRoot(root);
if (intersectionObserver) {
intersectionObserver.unobserve(element);
}
}
/**
* to unobserver multiple elements
*
* @method disconnect
* @param {Node|window} root
*/
disconnect(root) {
let { intersectionObserver } = this._findRoot(root);
if (intersectionObserver) {
intersectionObserver.disconnect();
}
}
_setupOnIntersection(root) {
return function(entries) {
return this._onAdminIntersection(root, entries);
}
}
_onAdminIntersection(root, ioEntries) {
ioEntries.forEach((entry) => {
let { isIntersecting, intersectionRatio } = entry;
// first determine if entry intersecting
if (isIntersecting) {
// then find entry's callback in static administration
let { elements = [] } = this._findRoot(root);
elements.some(({ element, enterCallback }) => {
if (element === entry.target) {
// call entry's enter callback
enterCallback();
return true;
}
});
} else if (intersectionRatio <= 0) { // exiting viewport
// then find entry's callback in static administration
let { elements = [] } = this._findRoot(root);
elements.some(({ element, exitCallback }) => {
if (element === entry.target) {
// call entry's exit callback
exitCallback();
return true;
}
});
}
});
}
_findRoot(root) {
return DOMRef.get(root) || {};
}
} |
JavaScript | class BlinkDiff {
/*
* @param {object} options
* @param {PNGImage|Buffer} options.imageA Image object of first image
* @param {string} options.imageAPath Path to first image
* @param {PNGImage|Buffer} options.imageB Image object of second image
* @param {string} options.imageBPath Path to second image
* @param {string} [options.imageOutputPath=undefined] Path to output image file
* @param {int} [options.imageOutputLimit=BlinkDiff.OUTPUT_ALL] Determines when an image output is created
* @param {string} [options.thresholdType=BlinkDiff.THRESHOLD_PIXEL] Defines the threshold of the comparison
* @param {int} [options.threshold=500] Threshold limit according to the comparison limit.
* @param {number} [options.delta=20] Distance between the color coordinates in the 4 dimensional color-space that will not trigger a difference.
* @param {int} [options.outputMaskRed=255] Value to set for red on difference pixel. 'Undefined' will not change the value.
* @param {int} [options.outputMaskGreen=0] Value to set for green on difference pixel. 'Undefined' will not change the value.
* @param {int} [options.outputMaskBlue=0] Value to set for blue on difference pixel. 'Undefined' will not change the value.
* @param {int} [options.outputMaskAlpha=255] Value to set for the alpha channel on difference pixel. 'Undefined' will not change the value.
* @param {float} [options.outputMaskOpacity=0.7] Strength of masking the pixel. 1.0 means that the full color will be used; anything less will mix-in the original pixel.
* @param {int} [options.outputShiftRed=255] Value to set for red on shifted pixel. 'Undefined' will not change the value.
* @param {int} [options.outputShiftGreen=165] Value to set for green on shifted pixel. 'Undefined' will not change the value.
* @param {int} [options.outputShiftBlue=0] Value to set for blue on shifted pixel. 'Undefined' will not change the value.
* @param {int} [options.outputShiftAlpha=255] Value to set for the alpha channel on shifted pixel. 'Undefined' will not change the value.
* @param {float} [options.outputShiftOpacity=0.7] Strength of masking the shifted pixel. 1.0 means that the full color will be used; anything less will mix-in the original pixel.
* @param {int} [options.outputBackgroundRed=0] Value to set for red as background. 'Undefined' will not change the value.
* @param {int} [options.outputBackgroundGreen=0] Value to set for green as background. 'Undefined' will not change the value.
* @param {int} [options.outputBackgroundBlue=0] Value to set for blue as background. 'Undefined' will not change the value.
* @param {int} [options.outputBackgroundAlpha=undefined] Value to set for the alpha channel as background. 'Undefined' will not change the value.
* @param {float} [options.outputBackgroundOpacity=0.6] Strength of masking the pixel. 1.0 means that the full color will be used; anything less will mix-in the original pixel.
* @param {object|object[]} [options.blockOut] Object or list of objects with coordinates of blocked-out areas.
* @param {int} [options.blockOutRed=0] Value to set for red on blocked-out pixel. 'Undefined' will not change the value.
* @param {int} [options.blockOutGreen=0] Value to set for green on blocked-out pixel. 'Undefined' will not change the value.
* @param {int} [options.blockOutBlue=0] Value to set for blue on blocked-out pixel. 'Undefined' will not change the value.
* @param {int} [options.blockOutAlpha=255] Value to set for the alpha channel on blocked-out pixel. 'Undefined' will not change the value.
* @param {float} [options.blockOutOpacity=1.0] Strength of masking the blocked-out pixel. 1.0 means that the full color will be used; anything less will mix-in the original pixel.
* @param {boolean} [options.copyImageAToOutput=true] Copies the first image to the output image before the comparison begins. This will make sure that the output image will highlight the differences on the first image.
* @param {boolean} [options.copyImageBToOutput=false] Copies the second image to the output image before the comparison begins. This will make sure that the output image will highlight the differences on the second image.
* @param {string[]} [options.filter=[]] Filters that will be applied before the comparison. Available filters are: blur, grayScale, lightness, luma, luminosity, sepia
* @param {boolean} [options.debug=false] When set, then the applied filters will be shown on the output image.
* @param {boolean} [options.composition=true] Should a composition be created to compare?
* @param {boolean} [options.composeLeftToRight=false] Create composition from left to right, otherwise let it decide on its own whats best
* @param {boolean} [options.composeTopToBottom=false] Create composition from top to bottom, otherwise let it decide on its own whats best
* @param {boolean} [options.hideShift=false] Hides shift highlighting by using the background color instead
* @param {int} [options.hShift=2] Horizontal shift for possible antialiasing
* @param {int} [options.vShift=2] Vertical shift for possible antialiasing
* @param {object} [options.cropImageA=null] Cropping for first image (default: no cropping)
* @param {int} [options.cropImageA.x=0] Coordinate for left corner of cropping region
* @param {int} [options.cropImageA.y=0] Coordinate for top corner of cropping region
* @param {int} [options.cropImageA.width] Width of cropping region (default: Width that is left)
* @param {int} [options.cropImageA.height] Height of cropping region (default: Height that is left)
* @param {object} [options.cropImageB=null] Cropping for second image (default: no cropping)
* @param {int} [options.cropImageB.x=0] Coordinate for left corner of cropping region
* @param {int} [options.cropImageB.y=0] Coordinate for top corner of cropping region
* @param {int} [options.cropImageB.width] Width of cropping region (default: Width that is left)
* @param {int} [options.cropImageB.height] Height of cropping region (default: Height that is left)
* @param {boolean} [options.perceptual=false] Turns perceptual comparison on
* @param {float} [options.gamma] Gamma correction for all colors
* @param {float} [options.gammaR] Gamma correction for red
* @param {float} [options.gammaG] Gamma correction for green
* @param {float} [options.gammaB] Gamma correction for blue
*
* @property {PNGImage} _imageA
* @property {PNGImage} _imageACompare
* @property {string} _imageAPath
* @property {PNGImage} _imageB
* @property {PNGImage} _imageBCompare
* @property {string} _imageBPath
* @property {PNGImage} _imageOutput
* @property {string} _imageOutputPath
* @property {int} _imageOutputLimit
* @property {string} _thresholdType
* @property {int} _threshold
* @property {number} _delta
* @property {int} _outputMaskRed
* @property {int} _outputMaskGreen
* @property {int} _outputMaskBlue
* @property {int} _outputMaskAlpha
* @property {float} _outputMaskOpacity
* @property {int} _outputShiftRed
* @property {int} _outputShiftGreen
* @property {int} _outputShiftBlue
* @property {int} _outputShiftAlpha
* @property {float} _outputShiftOpacity
* @property {int} _outputBackgroundRed
* @property {int} _outputBackgroundGreen
* @property {int} _outputBackgroundBlue
* @property {int} _outputBackgroundAlpha
* @property {float} _outputBackgroundOpacity
* @property {object[]} _blockOut
* @property {int} _blockOutRed
* @property {int} _blockOutGreen
* @property {int} _blockOutBlue
* @property {int} _blockOutAlpha
* @property {float} _blockOutOpacity
* @property {boolean} _copyImageAToOutput
* @property {boolean} _copyImageBToOutput
* @property {string[]} _filter
* @property {boolean} _debug
* @property {boolean} _composition
* @property {boolean} _composeLeftToRight
* @property {boolean} _composeTopToBottom
* @property {int} _hShift
* @property {int} _vShift
* @property {object} _cropImageA
* @property {int} _cropImageA.x
* @property {int} _cropImageA.y
* @property {int} _cropImageA.width
* @property {int} _cropImageA.height
* @property {object} _cropImageB
* @property {int} _cropImageB.x
* @property {int} _cropImageB.y
* @property {int} _cropImageB.width
* @property {int} _cropImageB.height
* @property {object} _refWhite
* @property {boolean} _perceptual
* @property {float} _gamma
* @property {float} _gammaR
* @property {float} _gammaG
* @property {float} _gammaB
*/
/**
* @param {Options} options
*/
constructor(options) {
this._imageA = options.imageA;
this._imageAPath = options.imageAPath;
assert.ok(options.imageAPath || options.imageA, "Image A not given.");
this._imageB = options.imageB;
this._imageBPath = options.imageBPath;
assert.ok(options.imageBPath || options.imageB, "Image B not given.");
this._imageOutput = null;
this._imageOutputPath = options.imageOutputPath;
this._imageOutputLimit = load(options.imageOutputLimit, BlinkDiff.OUTPUT_ALL);
// Pixel or Percent
this._thresholdType = load(options.thresholdType, BlinkDiff.THRESHOLD_PIXEL);
// How many pixels different to ignore.
this._threshold = load(options.threshold, 500);
this._delta = load(options.delta, 20);
this._outputMaskRed = load(options.outputMaskRed, 255);
this._outputMaskGreen = load(options.outputMaskGreen, 0);
this._outputMaskBlue = load(options.outputMaskBlue, 0);
this._outputMaskAlpha = load(options.outputMaskAlpha, 255);
this._outputMaskOpacity = load(options.outputMaskOpacity, 0.7);
this._outputBackgroundRed = load(options.outputBackgroundRed, 0);
this._outputBackgroundGreen = load(options.outputBackgroundGreen, 0);
this._outputBackgroundBlue = load(options.outputBackgroundBlue, 0);
this._outputBackgroundAlpha = options.outputBackgroundAlpha;
this._outputBackgroundOpacity = load(options.outputBackgroundOpacity, 0.6);
if (options.hideShift) {
this._outputShiftRed = this._outputBackgroundRed;
this._outputShiftGreen = this._outputBackgroundGreen;
this._outputShiftBlue = this._outputBackgroundBlue;
this._outputShiftAlpha = this._outputBackgroundAlpha;
this._outputShiftOpacity = this._outputBackgroundOpacity;
} else {
this._outputShiftRed = load(options.outputShiftRed, 200);
this._outputShiftGreen = load(options.outputShiftGreen, 100);
this._outputShiftBlue = load(options.outputShiftBlue, 0);
this._outputShiftAlpha = load(options.outputShiftAlpha, 255);
this._outputShiftOpacity = load(options.outputShiftOpacity, 0.7);
}
const blockOut = /** @type {Rect[]|Rect}*/ (load(options.blockOut, []));
/** @type {Rect[]}*/
this._blockOut = Array.isArray(blockOut) ? blockOut : [blockOut];
this._blockOutRed = load(options.blockOutRed, 0);
this._blockOutGreen = load(options.blockOutGreen, 0);
this._blockOutBlue = load(options.blockOutBlue, 0);
this._blockOutAlpha = load(options.blockOutAlpha, 255);
this._blockOutOpacity = load(options.blockOutOpacity, 1.0);
this._copyImageAToOutput = load(options.copyImageAToOutput, true);
this._copyImageBToOutput = load(options.copyImageBToOutput, false);
this._filter = load(options.filter, []);
this._debug = load(options.debug, false);
this._composition = load(options.composition, true);
this._composeLeftToRight = load(options.composeLeftToRight, false);
this._composeTopToBottom = load(options.composeTopToBottom, false);
this._hShift = load(options.hShift, 2);
this._vShift = load(options.vShift, 2);
this._cropImageA = options.cropImageA;
this._cropImageB = options.cropImageB;
// Prepare reference white
this._refWhite = this._convertRgbToXyz({c1: 1, c2: 1, c3: 1, c4: 1});
this._perceptual = load(options.perceptual, false);
this._gamma = options.gamma;
this._gammaR = options.gammaR;
this._gammaG = options.gammaG;
this._gammaB = options.gammaB;
}
/**
* Runs the comparison synchronously
*
* @method runSync
* @return {Result} Result of comparison { code, differences, dimension, width, height }
*/
runSync() {
var i, len, rect, color;
try {
this._imageA = this._loadImageSync(this._imageAPath, this._imageA);
this._imageB = this._loadImageSync(this._imageBPath, this._imageB);
// Crop images if requested
if (this._cropImageA) {
this._correctDimensions(this._imageA.getWidth(), this._imageA.getHeight(), this._cropImageA);
this._crop("Image-A", this._imageA, this._cropImageA);
}
if (this._cropImageB) {
this._correctDimensions(this._imageB.getWidth(), this._imageB.getHeight(), this._cropImageB);
this._crop("Image-B", this._imageB, this._cropImageB);
}
// Always clip
this._clip(this._imageA, this._imageB);
this._imageOutput = PNGImage.createImage(this._imageA.getWidth(), this._imageA.getHeight());
// Make a copy when not in debug mode
if (this._debug) {
this._imageACompare = this._imageA;
this._imageBCompare = this._imageB;
} else {
this._imageACompare = PNGImage.copyImage(this._imageA);
this._imageBCompare = PNGImage.copyImage(this._imageB);
}
// Block-out
color = {
red: this._blockOutRed,
green: this._blockOutGreen,
blue: this._blockOutBlue,
alpha: this._blockOutAlpha,
opacity: this._blockOutOpacity
};
for (i = 0, len = this._blockOut.length; i < len; i++) {
rect = this._blockOut[i];
// Make sure the block-out parameters fit
this._correctDimensions(this._imageACompare.getWidth(), this._imageACompare.getHeight(), rect);
this._imageACompare.fillRect(rect.x, rect.y, rect.width, rect.height, color);
this._imageBCompare.fillRect(rect.x, rect.y, rect.width, rect.height, color);
}
// Copy image to composition
if (this._copyImageAToOutput) {
this._copyImage(this._debug ? this._imageACompare : this._imageA, this._imageOutput);
} else if (this._copyImageBToOutput) {
this._copyImage(this._debug ? this._imageBCompare : this._imageB, this._imageOutput);
}
// Gamma correction
var gamma = undefined;
if (this._gamma || this._gammaR || this._gammaG || this._gammaB) {
gamma = {
R: this._gammaR || this._gamma, G: this._gammaG || this._gamma, B: this._gammaB || this._gamma
};
}
// Comparison
var result = this._compare(this._imageACompare, this._imageBCompare, this._imageOutput, this._delta,
{ // Output-Mask color
red: this._outputMaskRed,
green: this._outputMaskGreen,
blue: this._outputMaskBlue,
alpha: this._outputMaskAlpha,
opacity: this._outputMaskOpacity
}, { // Output-Shift color
red: this._outputShiftRed,
green: this._outputShiftGreen,
blue: this._outputShiftBlue,
alpha: this._outputShiftAlpha,
opacity: this._outputShiftOpacity
}, { // Background color
red: this._outputBackgroundRed,
green: this._outputBackgroundGreen,
blue: this._outputBackgroundBlue,
alpha: this._outputBackgroundAlpha,
opacity: this._outputBackgroundOpacity
},
this._hShift, this._vShift,
this._perceptual,
gamma
);
// Create composition if requested
if (this._debug) {
this._imageOutput = this._createComposition(this._imageACompare, this._imageBCompare, this._imageOutput);
} else {
this._imageOutput = this._createComposition(this._imageA, this._imageB, this._imageOutput);
}
// Need to write to the filesystem?
if (this._imageOutputPath && this._withinOutputLimit(result.code, this._imageOutputLimit)) {
this._imageOutput.writeImageSync(this._imageOutputPath);
this.log("Wrote differences to " + this._imageOutputPath);
}
return result;
} catch (err) {
console.error(err.stack);
throw err;
}
}
/**
* Determines if result is within the output limit
*
* @method _withinOutputLimit
* @param {int} resultCode
* @param {int} outputLimit
* @return {boolean}
*/
_withinOutputLimit(resultCode, outputLimit) {
return this._convertResultCodeToRelativeValue(resultCode) <= outputLimit;
}
/**
* Converts the result-code to a relative value
*
* @method _convertResultCodeToRelativeValue
* @param {int} resultCode
* @return {int}
*/
_convertResultCodeToRelativeValue(resultCode) {
/** @type {any} */
var valueMap = {
0: 0, 1: 10, 7: 20, 5: 30
};
return valueMap[resultCode] !== undefined ? valueMap[resultCode] : 0;
}
/**
* Creates a comparison image
*
* @method _createComposition
* @param {PNGImage} imageA
* @param {PNGImage} imageB
* @param {PNGImage} imageOutput
* @return {PNGImage}
*/
_createComposition(imageA, imageB, imageOutput) {
var width, height, image = imageOutput;
if (this._composition) {
width = Math.max(imageA.getWidth(), imageB.getWidth());
height = Math.max(imageA.getHeight(), imageB.getHeight());
if (((width > height) && !this._composeLeftToRight) || this._composeTopToBottom) {
image = PNGImage.createImage(width, height * 3);
PNG.bitblt(imageA.getImage(), image.getImage(), 0, 0, imageA.getWidth(), imageA.getHeight(), 0, 0);
PNG.bitblt(imageOutput.getImage(), image.getImage(), 0, 0, imageOutput.getWidth(), imageOutput.getHeight(), 0, height);
PNG.bitblt(imageB.getImage(), image.getImage(), 0, 0, imageB.getWidth(), imageB.getHeight(), 0, height * 2);
} else {
image = PNGImage.createImage(width * 3, height);
PNG.bitblt(imageA.getImage(), image.getImage(), 0, 0, imageA.getWidth(), imageA.getHeight(), 0, 0);
PNG.bitblt(imageOutput.getImage(), image.getImage(), 0, 0, imageOutput.getWidth(), imageOutput.getHeight(), width, 0);
PNG.bitblt(imageB.getImage(), image.getImage(), 0, 0, imageB.getWidth(), imageB.getHeight(), width * 2, 0);
}
}
return image;
}
/**
* Loads the image or uses the already available image
*
* @method _loadImageSync
* @param {string|undefined} path
* @param {PNGImage|Buffer=} image
* @return {PNGImage}
*/
_loadImageSync(path, image) {
if (image instanceof Buffer) {
return PNGImage.loadImageSync(image);
} else if ((typeof path === 'string') && !image) {
return PNGImage.readImageSync(path);
} else {
return /** @type {PNGImage} */ (image);
}
}
/**
* Copies one image into another image
*
* @method _copyImage
* @param {PNGImage} imageSrc
* @param {PNGImage} imageDst
*/
_copyImage(imageSrc, imageDst) {
PNG.bitblt(imageSrc.getImage(), imageDst.getImage(), 0, 0, imageSrc.getWidth(), imageSrc.getHeight(), 0, 0);
}
/**
* Is the difference above the set threshold?
*
* @method isAboveThreshold
* @param {int} items
* @param {int} total
* @return {boolean}
*/
isAboveThreshold(items, total) {
if ((this._thresholdType === BlinkDiff.THRESHOLD_PIXEL) && (this._threshold <= items)) {
return true;
} else if (this._threshold <= (items / total)) {
return true;
}
return false;
}
/**
* Log method that can be overwritten to modify the logging behavior.
*
* @method log
* @param {string} text
*/
log(text) {
// Nothing here; Overwrite this to add some functionality
}
/**
* Has comparison passed?
*
* @method hasPassed
* @param {int} result Comparison result-code
* @return {boolean}
*/
hasPassed(result) {
return ((result !== BlinkDiff.RESULT_DIFFERENT) && (result !== BlinkDiff.RESULT_UNKNOWN));
}
/**
* Clips the images to the lower resolution of both
*
* @method _clip
* @param {PNGImage} imageA Source image
* @param {PNGImage} imageB Destination image
*/
_clip(imageA, imageB) {
var minWidth, minHeight;
if ((imageA.getWidth() != imageB.getWidth()) || (imageA.getHeight() != imageB.getHeight())) {
minWidth = imageA.getWidth();
if (imageB.getWidth() < minWidth) {
minWidth = imageB.getWidth();
}
minHeight = imageA.getHeight();
if (imageB.getHeight() < minHeight) {
minHeight = imageB.getHeight();
}
this.log("Clipping to " + minWidth + " x " + minHeight);
imageA.clip(0, 0, minWidth, minHeight);
imageB.clip(0, 0, minWidth, minHeight);
}
}
/**
* Crops the source image to the bounds of rect
*
* @method _crop
* @param {string} which Title of image to crop
* @param {PNGImage} image Source image
* @param {object} rect Values for rect
* @param {int} rect.x X value of rect
* @param {int} rect.y Y value of rect
* @param {int} rect.width Width value of rect
* @param {int} rect.height Height value of rect
*/
_crop(which, image, rect) {
this.log("Cropping " + which + " from " + rect.x + "," + rect.y + " by " + rect.width + " x " + rect.height);
image.clip(rect.x, rect.y, rect.width, rect.height);
}
/**
* Correcting area dimensions if necessary
*
* Note:
* Priority is on the x/y coordinates, and not on the size since the size will then be removed anyways.
*
* @method _correctDimensions
* @param {int} width
* @param {int} height
* @param {object} rect Values for rect
* @param {int} rect.x X value of rect
* @param {int} rect.y Y value of rect
* @param {int} rect.width Width value of rect
* @param {int} rect.height Height value of rect
*/
_correctDimensions(width, height, rect) {
// Set values if none given
rect.x = rect.x || 0;
rect.y = rect.y || 0;
rect.width = rect.width || width;
rect.height = rect.height || height;
// Check negative values
rect.x = Math.max(0, rect.x);
rect.y = Math.max(0, rect.y);
rect.width = Math.max(0, rect.width);
rect.height = Math.max(0, rect.height);
// Check dimensions
rect.x = Math.min(rect.x, width - 1); // -1 to make sure that there is an image
rect.y = Math.min(rect.y, height - 1);
rect.width = Math.min(rect.width, width - rect.x);
rect.height = Math.min(rect.height, height - rect.y);
}
/**
* Calculates the distance of colors in the 4 dimensional color space
*
* @method _colorDelta
* @param {Color} color1 Values for color 1
* @param {Color} color2 Values for color 2
* @return {number} Distance
*/
_colorDelta(color1, color2) {
var c1, c2, c3, c4;
c1 = Math.pow(color1.c1 - color2.c1, 2);
c2 = Math.pow(color1.c2 - color2.c2, 2);
c3 = Math.pow(color1.c3 - color2.c3, 2);
c4 = Math.pow(color1.c4 - color2.c4, 2);
return Math.sqrt(c1 + c2 + c3 + c4);
}
/**
* Gets the color of an image by the index
*
* @method _getColor
* @param {PNGImage} image Image
* @param {int} idx Index of pixel in image
* @param {boolean=} perceptual
* @param {Gamma=} gamma
* @return {Color}
*/
_getColor(image, idx, perceptual, gamma) {
var color = {
c1: image.getRed(idx), c2: image.getGreen(idx), c3: image.getBlue(idx), c4: image.getAlpha(idx)
};
if (perceptual || gamma) {
color = this._correctGamma(color, gamma);
color = this._convertRgbToXyz(color);
color = this._convertXyzToCieLab(color);
}
return color;
}
/**
* Correct gamma and return color in [0, 1] range
*
* @method _correctGamma
* @param {Color} color
* @param {Gamma=} gamma
* @return {Color}
*/
_correctGamma(color, gamma) {
// Convert to range [0, 1]
var result = {
c1: color.c1 / 255, c2: color.c2 / 255, c3: color.c3 / 255, c4: color.c4
};
if (gamma && (gamma.R !== undefined || gamma.G !== undefined || gamma.B !== undefined)) {
if (gamma.R !== undefined) {
result.c1 = Math.pow(result.c1, gamma.R);
}
if (gamma.G !== undefined) {
result.c2 = Math.pow(result.c2, gamma.G);
}
if (gamma.B !== undefined) {
result.c3 = Math.pow(result.c3, gamma.B);
}
}
return result;
}
/**
* Converts the color from RGB to XYZ
*
* @method _convertRgbToXyz
* @param {Color} color
* @return {Color}
*/
_convertRgbToXyz(color) {
var result = {};
result.c1 = color.c1 * 0.4887180 + color.c2 * 0.3106803 + color.c3 * 0.2006017;
result.c2 = color.c1 * 0.1762044 + color.c2 * 0.8129847 + color.c3 * 0.0108109;
result.c3 = color.c2 * 0.0102048 + color.c3 * 0.9897952;
result.c4 = color.c4;
return result;
}
/**
* Converts the color from XYZ to CieLab
*
* @method _convertXyzToCieLab
* @param {Color} color
* @return {Color}
*/
_convertXyzToCieLab(color) {
var result = {}, c1, c2, c3;
/**
* @param {number} t
* @returns {number}
*/
function f (t) {
return (t > 0.00885645167904) ? Math.pow(t, 1 / 3) : 70.08333333333263 * t + 0.13793103448276;
}
c1 = f(color.c1 / this._refWhite.c1);
c2 = f(color.c2 / this._refWhite.c2);
c3 = f(color.c3 / this._refWhite.c3);
result.c1 = (116 * c2) - 16;
result.c2 = 500 * (c1 - c2);
result.c3 = 200 * (c2 - c3);
result.c4 = color.c4;
return result;
}
/**
* Calculates the lower limit
*
* @method _calculateLowerLimit
* @param {int} value
* @param {int} min
* @param {int} shift
* @return {int}
*/
_calculateLowerLimit(value, min, shift) {
return (value - shift) < min ? -(shift + (value - shift)) : -shift;
}
/**
* Calculates the upper limit
*
* @method _calculateUpperLimit
* @param {int} value
* @param {int} max
* @param {int} shift
* @return {int}
*/
_calculateUpperLimit(value, max, shift) {
return (value + shift) > max ? (max - value) : shift;
}
/**
* Checks if any pixel in the shift surrounding has a comparable color
*
* @method _shiftCompare
* @param {int} x
* @param {int} y
* @param {Color} color
* @param {number} deltaThreshold
* @param {PNGImage} imageA
* @param {PNGImage} imageB
* @param {int} width
* @param {int} height
* @param {int} hShift
* @param {int} vShift
* @param {boolean=} perceptual
* @param {Gamma=} gamma
* @return {boolean} Is pixel within delta found in surrounding?
*/
_shiftCompare(x, y, color, deltaThreshold, imageA, imageB, width, height, hShift, vShift, perceptual, gamma) {
var i, xOffset, xLow, xHigh, yOffset, yLow, yHigh, delta, localDeltaThreshold;
if ((hShift > 0) || (vShift > 0)) {
xLow = this._calculateLowerLimit(x, 0, hShift);
xHigh = this._calculateUpperLimit(x, width - 1, hShift);
yLow = this._calculateLowerLimit(y, 0, vShift);
yHigh = this._calculateUpperLimit(y, height - 1, vShift);
for (xOffset = xLow; xOffset <= xHigh; xOffset++) {
for (yOffset = yLow; yOffset <= yHigh; yOffset++) {
if ((xOffset != 0) || (yOffset != 0)) {
i = imageB.getIndex(x + xOffset, y + yOffset);
var color1 = this._getColor(imageA, i, perceptual, gamma);
localDeltaThreshold = this._colorDelta(color, color1);
var color2 = this._getColor(imageB, i, perceptual, gamma);
delta = this._colorDelta(color, color2);
if ((Math.abs(delta - localDeltaThreshold) < deltaThreshold) && (localDeltaThreshold > deltaThreshold)) {
return true;
}
}
}
}
}
return false;
}
/**
* Does a quick comparison between the supplied images
*
* @method _pixelCompare
* @param {PNGImage} imageA
* @param {PNGImage} imageB
* @param {PNGImage} imageOutput
* @param {number} deltaThreshold
* @param {int} width Width of image
* @param {int} height Height of image
* @param {RGBAOColor} outputMaskColor
* @param {RGBAOColor} outputShiftColor
* @param {RGBAOColor} backgroundColor
* @param {int=} hShift Horizontal shift
* @param {int=} vShift Vertical shift
* @param {boolean=} perceptual
* @param {Gamma=} gamma
* @return {int} Number of pixel differences
*/
_pixelCompare(imageA, imageB, imageOutput, deltaThreshold, width, height, outputMaskColor, outputShiftColor, backgroundColor, hShift, vShift, perceptual, gamma) {
var difference = 0, i, x, y, delta;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
i = imageA.getIndex(x, y);
var color1 = this._getColor(imageA, i, perceptual, gamma);
var color2 = this._getColor(imageB, i, perceptual, gamma);
delta = this._colorDelta(color1, color2);
if (delta > deltaThreshold) {
if (this._shiftCompare(x, y, color1, deltaThreshold, imageA, imageB, width, height, hShift || 0, vShift || 0, perceptual, gamma) && this._shiftCompare(x, y, color2, deltaThreshold, imageB, imageA, width, height, hShift || 0, vShift || 0, perceptual, gamma)) {
imageOutput.setAtIndex(i, outputShiftColor);
} else {
difference++;
imageOutput.setAtIndex(i, outputMaskColor);
}
} else {
imageOutput.setAtIndex(i, backgroundColor);
}
}
}
return difference;
}
/**
* Compares the two images supplied
*
* @method _compare
* @param {PNGImage} imageA
* @param {PNGImage} imageB
* @param {PNGImage} imageOutput
* @param {number} deltaThreshold
* @param {RGBAOColor} outputMaskColor
* @param {RGBAOColor} outputShiftColor
* @param {RGBAOColor} backgroundColor
* @param {int=} hShift
* @param {int=} vShift
* @param {boolean=} perceptual
* @param {Gamma=} gamma
* @return {Result}
*/
_compare(imageA, imageB, imageOutput, deltaThreshold, outputMaskColor, outputShiftColor, backgroundColor, hShift, vShift, perceptual, gamma) {
/** @type {any} */
var result = {
code: BlinkDiff.RESULT_UNKNOWN,
differences: undefined,
dimension: undefined,
width: undefined,
height: undefined
};
// Get some data needed for comparison
result.width = imageA.getWidth();
result.height = imageA.getHeight();
result.dimension = result.width * result.height;
// Check if identical
result.differences = this._pixelCompare(imageA, imageB, imageOutput, deltaThreshold, result.width, result.height, outputMaskColor, outputShiftColor, backgroundColor, hShift, vShift, perceptual, gamma);
// Result
if (result.differences == 0) {
this.log("Images are identical or near identical");
result.code = BlinkDiff.RESULT_IDENTICAL;
return result;
} else if (this.isAboveThreshold(result.differences, result.dimension)) {
this.log("Images are visibly different");
this.log(result.differences + " pixels are different");
result.code = BlinkDiff.RESULT_DIFFERENT;
return result;
} else {
this.log("Images are similar");
this.log(result.differences + " pixels are different");
result.code = BlinkDiff.RESULT_SIMILAR;
return result;
}
}
} |
JavaScript | class Bokeh2Pass extends Pass {
/**
* Constructs a new bokeh2 pass.
*
* @param {PerspectiveCamera} camera - The main camera. Used to obtain the focal length and the near and far plane settings.
* @param {Object} [options] - Additional parameters.
* @param {Number} [options.rings=3] - The amount of blur rings.
* @param {Number} [options.samples=4] - The amount of samples per ring.
* @param {Boolean} [options.showFocus=false] - Whether the focus point should be highlighted.
* @param {Boolean} [options.manualDoF=false] - Enables manual depth of field blur.
* @param {Boolean} [options.vignette=false] - Enables a vignette effect.
* @param {Boolean} [options.pentagon=false] - Enable to use a pentagonal shape to scale gathered texels.
* @param {Boolean} [options.shaderFocus=true] - Disable if you compute your own focalDepth (in metres!).
* @param {Boolean} [options.noise=true] - Disable if you don't want noise patterns for dithering.
*/
constructor(camera, options = {}) {
super();
/**
* The name of this pass.
*/
this.name = "Bokeh2Pass";
/**
* This pass renders to the write buffer.
*/
this.needsSwap = true;
/**
* A bokeh shader material.
*
* @type {BokehMaterial}
* @private
*/
this.bokehMaterial = new Bokeh2Material(camera, options);
this.quad.material = this.bokehMaterial;
}
/**
* Renders the effect.
*
* @param {WebGLRenderer} renderer - The renderer.
* @param {WebGLRenderTarget} readBuffer - The read buffer.
* @param {WebGLRenderTarget} writeBuffer - The write buffer.
*/
render(renderer, readBuffer, writeBuffer) {
this.bokehMaterial.uniforms.tDiffuse.value = readBuffer.texture;
this.bokehMaterial.uniforms.tDepth.value = readBuffer.depthTexture;
renderer.render(this.scene, this.camera, this.renderToScreen ? null : writeBuffer);
}
/**
* Updates this pass with the renderer's size.
*
* @param {Number} width - The width.
* @param {Number} height - The height.
*/
setSize(width, height) {
this.bokehMaterial.setTexelSize(1.0 / width, 1.0 / height);
}
} |
JavaScript | class App extends React.Component {
constructor() {
super();
this.state = {
showPopup: false
};
}
togglePopup() {
this.setState({
showPopup: !this.state.showPopup
});
}
render (){
return (
<div className="App">
<h1>Añadir Cliente</h1>
<button onClick={this.togglePopup.bind(this)}>show popup</button>
{this.state.showPopup ?
<PopUp
text='Close Me'
closePopup={this.togglePopup.bind(this)}
/>
: null
}
</div>)
}
} |
JavaScript | class Dance extends Component {
constructor(props){
super(props);
this.state = {
danceLevel: 0,
isSubmitted: false,
}
}
componentDidMount(){
/* get last added keyword */
// const usersRef = base.database().ref('keyword');
// usersRef.orderByChild('timestamp').limitToLast(1).on('child_added',function(snapshot) {
// console.log('new record', snapshot.child("keyword").val());
// });
}
handleChange = (value) => {
this.setState({danceLevel: value })
}
handleSubmit = (ev) => {
ev.preventDefault()
// console.log(`Submitted Dance Level: ${this.state.danceLevel}`)
this.setState({isSubmitted: true})
// const usersRef = base.database().ref('users');
// usersRef.child(localStorage.getItem('keyData')).set({
// danceLevel: this.state.danceLevel,
// })
localStorage.setItem("danceData", this.state.danceLevel/10)
// this.props.history.push(`/dance`)
}
render(){
// console.log(`${this.props.location.keyword}`)
// console.log(`Keyword from "Keyword": ${this.props.location.keyword}`)
const danceLabels = {
0: 'Nah don\'t feel like dancing',
10: 'Get me on my feet!'
}
const sliderStyle = {
width: '70%',
marginTop:'45px',
marginLeft: 'auto',
marginRight: 'auto'
}
const btn = {
marginTop: '60px',
fontSize: '35px',
color: 'rgb(30, 182, 65)',
border: 'none',
backgroundColor: '#F2F2F2'
}
return(
<div className="Dance">
<div className="outer">
<h3>How <b>"danceable"</b> do you want the songs?
</h3>
<div className="slider orientation-reversed custom-labels" >
<div className = "slider-group" style={sliderStyle}>
<div className = "slider-horizontal">
<Slider
min = {0}
max = {10}
value = {this.state.danceLevel}
labels = {danceLabels}
orientation = 'horizontal'
onChange = {this.handleChange}
/>
<div className = 'value'>{this.state.danceLevel}</div>
</div>
</div>
</div>
<form onSubmit= {this.handleSubmit} >
<button type="submit" style={btn}><i className="fas fa-forward"></i></button>
</form>
{/* <li><NavLink to="/energy">move to energy</NavLink></li>
<Route path="/energy" component={Energy}/> */}
{/* <Data danceLevel={this.state.danceLevel} /> */}
{this.state.isSubmitted && <Redirect to={{
pathname: '/energy',
danceLevel: this.state.danceLevel,
}}/>}
</div>
</div>
)
}
} |
JavaScript | class ValueToState extends AdjustFunction {
/**
* Constructor
*/
constructor() {
super();
this.setInput("input", SourceData.create("prop", "input"));
this.setInput("states", {"default": "none", "states": []});
this.setInput("outputName", "output");
}
setDefaultState(aState) {
let statesObject = this.getRawInput("states");
statesObject["default"] = aState;
return this;
}
addState(aAtValue, aState) {
let statesObject = this.getRawInput("states");
statesObject["states"].push({"minValue": aAtValue, "state": aState});
//METODO: sort array
return this;
}
/**
* Function that removes the used props
*
* @param aProps Object The props object that should be adjusted
*/
removeUsedProps(aProps) {
//METODO: change this to actual source cleanup
delete aProps["input"];
delete aProps["states"];
delete aProps["outputName"];
}
/**
* Sets the class based on the prop.
*
* @param aData * The data to adjust
* @param aManipulationObject WprrBaseObject The manipulation object that is performing the adjustment. Used to resolve sourcing.
*
* @return * The modified data
*/
adjust(aData, aManipulationObject) {
//console.log("wprr/manipulation/adjustfunctions/logic/ValueToState::adjust");
let input = this.getInput("input", aData, aManipulationObject);
let states = this.getInput("states", aData, aManipulationObject);
let outputName = this.getInput("outputName", aData, aManipulationObject);
this.removeUsedProps(aData);
let returnState = states["default"];
let currentArray = states["states"];
let currentArrayLength = currentArray.length;
for(let i = 0; i < currentArrayLength; i++) {
let currentData = currentArray[i];
if(currentData["minValue"] <= input) {
returnState = currentData["state"];
}
else {
break;
}
}
aData[outputName] = returnState;
return aData;
}
/**
* Creates a new instance of this class.
*
* @param aInput * | SourceData The value input.
* @param aOutputName String | SourceData The name of the prop to set the data to.
*
* @return ValueToState The new instance.
*/
static create(aInput = null, aOutputName = null) {
let newValueToState = new ValueToState();
newValueToState.setInputWithoutNull("input", aInput);
newValueToState.setInputWithoutNull("outputName", aOutputName);
return newValueToState;
}
} |
JavaScript | class Map extends React.Component {
render() {
return (
<div id="map-container">
<Boundaries />
<Buffs />
<Car {...this.props.car} />
</div>
);
}
} |
JavaScript | class IssueService extends Issue {
/**
* @param {Object} [obj = {}]
* @return {Issue}
*/
static new(obj = {}) {
return new Issue(obj);
}
/**
* @param {Object} [obj = {}]
* @return {IssueEvent}
*/
static newEvent(obj = {}) {
return new IssueEvent(obj);
}
/**
* @param issue
* @return {Promise<Issue>}
*/
static async saveOrUpdate(issue) {
if (!issue) throw new Error('Trying to save an empty entity');
debug('saving', JSON.stringify(issue));
if (issue.labels && issue.labels.length) {
await Promise.all(issue.labels.map(label => LabelService.saveFromUrl(label.url)));
}
return new Issue(issue).save();
}
/**
* @param {Object} event
* @return {Promise.<IssueEvent>}
*/
static async saveEvent(event) {
if (!event) throw new Error('Trying to save an empty entity');
debug('saving event', JSON.stringify(event));
const { issue, action } = event;
if (action === 'deleted') await IssueService.delete(issue.id);
await IssueService.saveFromUrl(issue.url);
return IssueEvent(event).save();
}
/**
* @param {Number} id
* @return {Promise<void>}
*/
static async delete(id) {
debug('marking as deleted', id);
const issue = await IssueService.findOne({ id }).exec();
if (issue) {
issue.deleted = true;
await issue.save();
}
}
/**
* @param {String} url
* @return {Promise<Issue>}
*/
static async saveFromUrl(url) {
if (!url) throw new Error('Trying to resolve a reference without url');
debug('saving from url', url);
const old = await Issue.findOne({ url }).exec() || {};
try {
const request = await AuthService.buildGitHubRequest();
const req = await request.get(url);
const ref = req.data;
return IssueService.saveOrUpdate(Object.assign(old, ref));
} catch (ignore) {
return old;
}
}
} |
JavaScript | class SafetyRatedLocation {
constructor(client, locationId) {
this.client = client;
this.locationId = locationId;
}
/**
* Retieve safety information of a location by its Id.
*
* What is the safety information of a location with Id Q930400801?
* ```js
* amadeus.safety.safetyRatedLocation('Q930400801').get();
* ```
*/
get() {
return this.client.get(`/v1/safety/safety-rated-locations/${this.locationId}`);
}
} |
JavaScript | class VectorMap extends Component {
static propTypes = {
/** series entry of options object */
series: PropTypes.object.isRequired,
/** markers entry of options object */
markers: PropTypes.array.isRequired,
/** jvectormap options object */
options: PropTypes.object.isRequired,
/** height of the container element */
height: PropTypes.string
}
static defaultProps = {
height: '300px'
}
componentDidMount() {
this.props.options.markers = this.props.markers;
this.props.options.series = this.props.series;
$(this.mapElement).vectorMap(this.props.options);
}
setRef = node => this.mapElement = node
render() {
return (
<div ref={this.setRef} style={{height: this.props.height}}/>
)
}
} |
JavaScript | class DonationPaper extends State {
constructor(obj) {
super(DonationPaper.getClass(), obj.paperID);
Object.assign(this, obj);
}
/**
* Basic getters and setters
*/
getIssuer() {
return this.issuer;
}
setIssuer(newIssuer) {
this.issuer = newIssuer;
}
/**
* Useful methods to encapsulate donation paper states
*/
setIssued() {
this.currentState = cpState.ISSUED;
}
setRedeemed() {
this.currentState = cpState.REDEEMED;
}
/**
*
* @param {String} date time paper was redeemed
*/
setRedeemedDate(date) {
this.redeemDate = date;
}
getRedeemedDate() {
if (this.currentState !== cpState.REDEEMED) {
throw new Error("Donation paper is not redeemed yet!");
}
return this.redeemDate;
}
/**
*
* @param {String} redeemer
*/
setRedeemer(redeemer) {
this.redeemer = redeemer;
}
getRedeemer() {
return this.redeemer;
}
isIssued() {
return this.currentState === cpState.ISSUED;
}
isRedeemed() {
return this.currentState === cpState.REDEEMED;
}
static fromBuffer(buffer) {
return DonationPaper.deserialize(buffer);
}
toBuffer() {
return Buffer.from(JSON.stringify(this));
}
/**
* Deserialize a state data to donation paper
* @param {Buffer} data to form back into the object
*/
static deserialize(data) {
return State.deserializeClass(data, DonationPaper);
}
/**
* Factory method to create a donation paper object
*/
static createInstance(issuer, paperID, issueDateTime, amount) {
return new DonationPaper({ issuer, paperID, issueDateTime, amount });
}
static getClass() {
return 'org.papernet.donationpaper';
}
} |
JavaScript | class ConfirmPrompt {
/**
* Creates a new instance of the prompt.
*
* **Example usage:**
*
* ```JavaScript
* dialogs.add('confirmPrompt', new ConfirmPrompt((context, value) => {
* if (value === undefined) {
* context.reply(`Please answer with "yes" or "no".`);
* return Prompts.resolve();
* } else {
* return dialogs.end(context, values);
* }
* }));
* ```
* @param validator (Optional) validator that will be called each time the user responds to the prompt.
*/
constructor(validator) {
this.validator = validator;
this.stylerOptions = { includeNumbers: false };
}
begin(context, dialogs, options) {
// Persist options
const instance = dialogs.getInstance(context);
instance.state = options || {};
// Send initial prompt
if (instance.state.prompt) {
return this.sendChoicePrompt(context, dialogs, instance.state.prompt, instance.state.speak);
}
else {
return Promise.resolve();
}
}
continue(context, dialogs) {
// Recognize value
const options = dialogs.getInstance(context).state;
const utterance = context.request && context.request.text ? context.request.text : '';
const results = booleanModel.parse(utterance);
const value = results.length > 0 && results[0].resolution ? results[0].resolution.value : undefined;
if (this.validator) {
// Call validator for further processing
return Promise.resolve(this.validator(context, value, dialogs));
}
else if (typeof value === 'boolean') {
// Return recognized value
return dialogs.end(context, value);
}
else if (options.retryPrompt) {
// Send retry prompt to user
return this.sendChoicePrompt(context, dialogs, options.retryPrompt, options.retrySpeak);
}
else if (options.prompt) {
// Send original prompt to user
return this.sendChoicePrompt(context, dialogs, options.prompt, options.speak);
}
else {
return Promise.resolve();
}
}
sendChoicePrompt(context, dialogs, prompt, speak) {
if (typeof prompt === 'string') {
// Get locale specific choices
let locale = context.request && context.request.locale ? context.request.locale.toLowerCase() : '*';
if (!ConfirmPrompt.choices.hasOwnProperty(locale)) {
locale = '*';
}
const choices = ConfirmPrompt.choices[locale];
// Reply with formatted prompt
const style = dialogs.getInstance(context).state.style;
context.reply(choicePrompt_1.formatChoicePrompt(context, choices, prompt, speak, this.stylerOptions, style));
}
else {
context.reply(prompt);
}
return Promise.resolve();
}
} |
JavaScript | class Matrix {
constructor(m, type) {
this.dim = 3;
this.value = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]];
if (m) {
this.set(m, type);
}
}
set (m, type) {
if (m.value[0][0]) {
this.value = m.value;
this.dim = m.dim;
}
else if (m[0][0]) {
this.value = m;
}
}
rotateX (theta) {
let c = Math.cos(theta);
let s = Math.sin(theta);
let T = [
[1, 0, 0],
[0, c, -s],
[0, s, c]];
this.value = this.getTransform(T);
}
rotateY (theta) {
let c = Math.cos(theta);
let s = Math.sin(theta);
let T = [
[ c, 0, s],
[ 0, 1, 0],
[ -s, 0, c]];
this.value = this.getTransform(T);
}
getMult (v) {
if (v[0][0] || (v.value && v.value[0][0])) {
// TODO: what If v is a matrix
console.log('TODO: what If v is a matrix');
}
else {
// If v is a vector
let A = new Vector(v);
let B = [];
for (let i = 0; i < A.dim; i++) {
B.push(A.value[0] * this.value[i][0] + A.value[1] * this.value[i][1] + A.value[2] * this.value[i][2]);
}
return new Vector(B);
}
}
getTransform (m) {
let newMatrix = [];
for (let row in m) {
let t = m[row];
let newRow = [];
newRow.push(t[0] * this.value[0][0] + t[1] * this.value[1][0] + t[2] * this.value[2][0]);
newRow.push(t[0] * this.value[0][1] + t[1] * this.value[1][1] + t[2] * this.value[2][1]);
newRow.push(t[0] * this.value[0][2] + t[1] * this.value[1][2] + t[2] * this.value[2][2]);
newMatrix.push(newRow);
}
return newMatrix;
}
getInv() {
let M = new Matrix();
let determinant = this.value[0][0] * (this.value[1][1] * this.value[2][2] - this.value[2][1] * this.value[1][2]) -
this.value[0][1] * (this.value[1][0] * this.value[2][2] - this.value[1][2] * this.value[2][0]) +
this.value[0][2] * (this.value[1][0] * this.value[2][1] - this.value[1][1] * this.value[2][0]);
let invdet = 1 / determinant;
M.value[0][0] = (this.value[1][1] * this.value[2][2] - this.value[2][1] * this.value[1][2]) * invdet;
M.value[0][1] = -(this.value[0][1] * this.value[2][2] - this.value[0][2] * this.value[2][1]) * invdet;
M.value[0][2] = (this.value[0][1] * this.value[1][2] - this.value[0][2] * this.value[1][1]) * invdet;
M.value[1][0] = -(this.value[1][0] * this.value[2][2] - this.value[1][2] * this.value[2][0]) * invdet;
M.value[1][1] = (this.value[0][0] * this.value[2][2] - this.value[0][2] * this.value[2][0]) * invdet;
M.value[1][2] = -(this.value[0][0] * this.value[1][2] - this.value[1][0] * this.value[0][2]) * invdet;
M.value[2][0] = (this.value[1][0] * this.value[2][1] - this.value[2][0] * this.value[1][1]) * invdet;
M.value[2][1] = -(this.value[0][0] * this.value[2][1] - this.value[2][0] * this.value[0][1]) * invdet;
M.value[2][2] = (this.value[0][0] * this.value[1][1] - this.value[1][0] * this.value[0][1]) * invdet;
return M;
}
} |
JavaScript | class QuoteComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
color: props.color,
dataItem: props.dataItem,
update: props.update,
};
}
// Updates the state before rendering the component
static getDerivedStateFromProps(props, state) {
return {
color: props.color,
dataItem: props.dataItem,
};
}
componentDidMount() {}
render() {
let style = {
backgroundColor: this.state.color,
outline: "none",
};
let quoteStyle = {
color: this.state.color,
};
let url =
'https://twitter.com/intent/tweet?text="' +
encodeURIComponent(
this.state.dataItem.quote + '" - ' + this.state.dataItem.author
);
return (
<div id="quote-container">
<div id="title" class="text-center">
Random Quote Machine
</div>
<div id="quote-box">
<div id="text">
<i
class="fa fa-quote-left"
aria-hidden="true"
style={quoteStyle}
></i>
<span id="text-content" style={quoteStyle}>
{" "}
{this.state.dataItem.quote}{" "}
</span>
<i
class="fa fa-quote-right"
aria-hidden="true"
style={quoteStyle}
></i>
</div>
<div id="author">
<p class="text-right">
<span>- </span>
<span id="author-content">{this.state.dataItem.author}</span>
</p>
</div>
<div
id="controls"
class="d-flex flex-row justify-content-between align-items-center"
>
<div class="control-item">
<a
href={url}
target="_blank"
id="tweet-quote"
class="button"
style={style}
>
<i class="fa fa-twitter" aria-hidden="true"></i>
</a>
</div>
<div class="control-item">
<button
id="new-quote"
class="button"
style={style}
onClick={this.state.update}
>
New Quote
</button>
</div>
</div>
</div>
<div id="creator" class="text-center">
by Peter Huang
</div>
</div>
);
}
} |
JavaScript | class RequestErrorDetailsExtractor {
/** @inheritDoc */
target = _error.default;
/**
* Settings that define which header makes its way to the result
*/
constructor(settings) {
this.headerSettings = {
include: new Set(settings?.headers.include),
exclude: new Set(settings?.headers.exclude)
};
}
/** @inheritDoc */
extract(error) {
return {
url: error.details.request?.url,
type: error.type,
status: error.details.response?.status,
method: error.details.request?.method,
query: error.details.request?.query,
contentType: error.details.request?.contentType,
withCredentials: error.details.request?.credentials,
requestHeaders: this.prepareHeaders(error.details.request?.headers),
requestBody: error.details.request?.body,
responseHeaders: this.prepareHeaders(error.details.response?.headers),
responseBody: error.details.response?.body
};
}
/**
* Filters the specified headers according to settings {@see headerSettings}
* @param headers - headers that need to be filtered
*/
prepareHeaders(headers) {
let filteredHeaders = headers;
const filterHeaders = (originalHeaders, filter) => Object.keys(originalHeaders).filter(filter).reduce((headers, headerName) => {
headers[headerName] = originalHeaders[headerName];
return headers;
}, {});
if (headers) {
if (this.headerSettings.include.size > 0) {
filteredHeaders = filterHeaders(headers, headerName => this.headerSettings.include.has(headerName));
} else if (this.headerSettings.exclude.size > 0) {
filteredHeaders = filterHeaders(headers, headerName => !this.headerSettings.exclude.has(headerName));
}
}
return filteredHeaders;
}
} |
JavaScript | class Tree {
constructor(data, eid) {
self = this;
this.data = data;
this.root = this.branching();
let el = document.getElementById(eid);
if(el) {
this.clear(el);
el.appendChild(this.root);
this.root.addEventListener('click', function(event) {
let target = event.target;
if(target.tagName == 'SPAN') {
let parent = target.parentNode;
if(!parent.previousSibling && !parent.nextSibling) {
self.deleteElement(parent.parentNode);
} else {
self.deleteElement(parent);
}
}
}, false);
}
}
clear(el) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
}
parent(id) {
let rows = [];
if(!this.data) return rows;
for(let i of this.data) {
if(i.parent === id) rows.push(i);
}
return rows;
}
makeElement(name, cls = []) {
let el = document.createElement(name);
if(cls.length) element.classList.add(...cls);
return el;
}
deleteElement(el) {
if(!el) return false;
el.parentNode.removeChild(el);
return true;
}
branching(id = null) {
let items = this.parent(id);
if(!items.length) return undefined;
let ul = this.makeElement('ul');
for(let i of items) {
if(!i.id) continue
let sub = this.branching(i.id);
let span = this.makeElement('span');
let li = this.makeElement('li');
span.innerText = i.id
li.appendChild(span);
ul.appendChild(li);
if(sub) li.appendChild(sub);
}
return ul;
}
} |
JavaScript | class LoginBlock extends Component {
constructor(props){
super(props);
this.state = {
User: {},
emailState: STATUS.NO_INPUT,
passwordState: STATUS.NO_INPUT,
confirmState: STATUS.NO_INPUT,
rememberMe: false,
email: "",
password: ""
}
this.login = this.login.bind(this);
this.updateEmail = this.updateEmail.bind(this);
this.updatePassword = this.updatePassword.bind(this);
this.updateRememberMe = this.updateRememberMe.bind(this);
}
login(){
this.props.accountLogin(this.state.email, this.state.password, { rememberMe: this.state.rememberMe })
}
updateEmail(event){
let new_email = event.target.value
let isEmail = validator.isEmail(new_email);
let newState = isEmail ? STATUS.VALID : STATUS.INVALID;
if (new_email === "")
newState = STATUS.NO_INPUT;
this.setState({email: new_email, emailState: newState});
// If we have an error set, clear it since we are changing something
if (this.props.Account.loginFailure){
this.props.clearAccountErrors()
}
}
updatePassword(event){
let new_password = event.target.value
let newState = STATUS.VALID;
if (new_password === "")
newState = STATUS.NO_INPUT;
this.setState({password: new_password, passwordState: newState});
// If we have an error set, clear it since we are changing something
if (this.props.Account.loginFailure){
this.props.clearAccountErrors()
}
}
updateRememberMe(remember_me_status){
this.setState({rememberMe: remember_me_status });
}
render() {
// Build the Email Validation State
let email_classes = "form-control input-lg"
let email_extra_class = ""
let email_feedback
switch(this.state.emailState){
case STATUS.INVALID:
email_extra_class += "is-invalid"
email_feedback = <div className="invalid-feedback" id="feedback_email">Email/Identifier is invalid. Please provide your identifier or your account Email.</div>
break;
case STATUS.VALID:
email_extra_class += "is-valid"
break;
}
// Build the Password Validation State
let password_classes = "form-control input-lg"
let password_extra_class = ""
let password_feedback
switch(this.state.passwordState){
case STATUS.VALID:
password_extra_class += "is-valid"
break;
}
// Build the Login Text
let login_classes = "btn btn-lg btn-block"
let login_extra_class = "btn-success"
let login_text = "Login"
let login_feedback
if (this.props.Account.loginFetching) {
login_text = "Logging in..."
}
if (this.props.Account.loginFailure) {
switch(this.props.Account.loginErrorType){
case "InvalidPassword":
password_extra_class = "is-invalid"
password_feedback = <div className="invalid-feedback" id="feedback_password">Invalid Password</div>
break;
case "AccountNotFoundError":
email_extra_class = "is-invalid"
email_feedback = <div className="invalid-feedback" id="feedback_email">No Account for Email/Identifier found</div>
break;
default:
login_feedback = <div className="alert alert-danger col-12">{this.props.Account.loginErrorMessage}</div>
login_extra_class = "btn-danger"
login_text = "Login Error"
break;
}
}
if (this.props.Account.isLoggedIn)
login_text = "Logged In"
// Build all the strings using the selected options
// Add the class that was selected for use
email_classes = email_classes + " " + email_extra_class
password_classes = password_classes + " " + password_extra_class
login_classes = login_classes + " " + login_extra_class
return (
<div style={{width: "100%", textAlign: "center"}} id="login-block">
<h2>Please Login</h2>
<hr className="" />
{/* Email Input */}
<div className="form-group">
<input
type="text"
name="email" id="email"
className={email_classes}
onChange={this.updateEmail}
value={this.state.email}
placeholder="Email/Identifier"
/>
{email_feedback}
</div>
{/* Password Input */}
<div className="form-group">
<input
type="password"
id="password" name="password"
className={password_classes}
onChange={this.updatePassword}
value={this.state.password}
placeholder="Password"
/>
{password_feedback}
</div>
{/* Remember Me Checkbox */}
<ButtonCheckbox onChange={this.updateRememberMe} text={"Remember Me"} />
<hr className="" />
{/* Login/Register Buttons */}
<div className="row">
{login_feedback}
<div className="col-12 col-sm-5 col-md-5 order-2 order-sm-1">
<button className="btn btn-lg btn-outline-secondary btn-block" onClick={this.props.onRegisterClick}>Register</button>
</div>
<div className="col-12 col-sm-7 col-md-7 order-1 order-sm-2">
<button id="login_button" className={login_classes} onClick={this.login}>{login_text}</button>
</div>
</div>
</div>
);
}
} |
JavaScript | class NextButton {
constructor (container) {
this.container = container
this.button = container.querySelector('.next__button')
this.svg = container.querySelector('.next__svg')
this.line = container.querySelector('.next__svg-line')
this.init()
this.render()
}
/**
* Add listeners on the button to detect mouseover on the container
*/
init () {
this.container.addEventListener('mouseenter', () => {
this.isOver = true
this.ease = 1.5
})
this.container.addEventListener('mouseleave', () => {
this.isOver = false
this.ease = 0.75
})
this.button.addEventListener('click', () => {
this.isCliked = true
setTimeout(() => {
this.isCliked = false
}, 850)
})
this.mouse = {
x: 0,
y: 0
}
this.container.addEventListener('mousemove', (e) => {
this.mouse.x = e.pageX - this.positions.left
this.mouse.y = e.pageY - this.positions.top
})
this.button.x = 0
this.button.y = 0
window.addEventListener('resize', () => {
this.positions.left = this.container.offsetLeft
this.positions.top = this.container.offsetTop
})
this.positions = {
left: this.container.offsetLeft,
top: this.container.offsetTop,
width: this.container.offsetWidth,
height: this.container.offsetHeight
}
this.svg.setAttribute('width', this.positions.width)
this.svg.setAttribute('height', this.positions.height)
this.svg.setAttribute('viewBox', `0 0 ${this.positions.width} ${this.positions.height} `)
this.ease = 0.75
}
/**
* Add css to the element to show the animation
*/
render () {
let translateX = 0
let translateY = 0
if (this.isCliked) {
translateX = 0
translateY = this.positions.height / 1.5
} else if (this.isOver) {
translateX = ((this.mouse.x - this.positions.width / 2) / (this.positions.width / 2) * (this.positions.width - 50) / 2)
translateY = ((this.mouse.y - this.positions.height / 2) / (this.positions.height / 2) * (this.positions.width - 50) / 2)
}
this.button.x += Math.round(((translateX - this.button.x)) * this.ease) / 10
this.button.y += Math.round(((translateY - this.button.y)) * this.ease) / 10
this.button.style.transform = `translateX(${this.button.x}px) translateY(${this.button.y}px)`
this.line.setAttribute('x1', this.button.x + this.positions.width / 2)
this.line.setAttribute('y1', this.button.y + this.positions.height / 2 + 25)
this.line.setAttribute('x2', this.positions.width / 2)
this.line.setAttribute('y2', this.positions.height + 50)
let ratio = 1 - (this.button.y + this.positions.height / 2) / (this.positions.height)
this.line.setAttribute('opacity', ratio)
window.requestAnimationFrame(this.render.bind(this))
}
} |
JavaScript | class CategoryView {
/**
* Constructor
* @param {string} view The block name of the view.
*/
constructor(view) {
/** {ArticleConsumer} for loading articles. */
this.articleConsumer = new ArticleConsumer();
/** {number} Id of the initial category. */
this.initialCategory = this.getCategory();
/** {boolean} whether the view is loading extra articles. */
this.isLoading = false;
/** {boolean} Determines whether to load regular pages or search queries. */
this.searchMode = false;
this.searchTimeout = null;
this.setUpInfiniteScroll();
this.setUpSearch();
}
/**
* Configures the view for infinite scrolling.
*/
setUpInfiniteScroll() {
this.disablePaginator();
this.updateView();
window.addEventListener('scroll', this.updateView.bind(this));
}
/**
* Disables the paginator.
*/
disablePaginator() {
BEM.addModifier(PAGINATOR, MODIFIER_HIDDEN);
}
/**
* Loads next page if required.
*/
updateView() {
if (this.shouldLoadNextPage()) {
this.loadNextPage();
}
}
/**
* Checks if the next page should be loaded.
* @returns {boolean}
*/
shouldLoadNextPage() {
if (this.isLoading) {
return false;
}
let windowHeight = window.innerHeight;
let scrollTop = document.body.scrollTop;
let position = windowHeight + scrollTop;
let threshold = document.body.scrollHeight;
return position >= threshold;
}
/**
* Loads next page, either for regular view or search.
*/
loadNextPage() {
if (!this.searchMode) {
return this.loadNextCategoryPage();
}
return this.loadNextSearchPage();
}
/**
* Load next page for categories.
* @param {number} [categoryId]
* @param {number} [page]
*/
loadNextCategoryPage(categoryId=this.initialCategory, page=this.getPage() + 1) {
this.isLoading = true;
this.articleConsumer.getArticles(categoryId, page)
.then(this.addPage.bind(this))
.catch(this.handleError.bind(this))
.then(() => this.isLoading = false);
}
/**
* Load next page for search.
*/
loadNextSearchPage(page=this.getPage() + 1) {
this.isLoading = true;
this.articleConsumer.search(INPUT.value, this.getPage() + 1)
.then(this.addPage.bind(this))
.catch(this.handleError.bind(this))
.then(() => this.isLoading = false);
}
/**
* Returns the id of the current caegory.
* @returns {number}
*/
getCategory() {
return parseInt(MAIN.dataset.category);
}
/**
* Returns the current page number.
* @returns {number}
*/
getPage() {
let nodes = BEM.getBEMNodes(BLOCK_VIEW, ELEMENT_MAIN);
let length = nodes.length;
let last = nodes[length - 1];
return parseInt(last.dataset.page);
}
/**
* Adds html as page to the DOM.
* @param {string} html
*/
addPage(html) {
let parser = new DOMParser();
let document = parser.parseFromString(html, 'text/html');
let node = BEM.getChildBEMNode(document, BLOCK_VIEW, ELEMENT_MAIN)
VIEW.appendChild(node);
}
/**
* Handles API errors.
* 404 is ignored as it's considered a valid response.
* If all other cases user is notified and response is thrown.
* @param {HttpResponseMessage} response
*/
handleError(response) {
// 404 is ignored as it's considered a valid response.
if (response.statusCode === 404) {
// TODO: loading may now optionally be disabled since there are no more pages...
return;
}
// If all other cases user is notified and response is thrown.
// TODO: Proper modal/notification...
alert("Oops! Something went wrong!\n\nPlease reload the page and try again...");
throw response
}
/**
* Configures the search input.
*/
setUpSearch() {
INPUT.addEventListener('focus', BEM.addModifier.bind(BEM, NAVBAR, MODIFIER_SEARCH));
INPUT.addEventListener('blur', BEM.removeModifier.bind(BEM, NAVBAR, MODIFIER_SEARCH));
INPUT.addEventListener('input', this.search.bind(this));
}
/**
* Performs search or resets view.
*/
search() {
setTimeout(() => {
clearTimeout(this.searchTimeout);
this.searchTimeout = setTimeout(() => { // Abuse scheduler to make sure we have the updated input value.
if (this.searchMode && !INPUT.value) {
this.setCategory();
return;
}
this.articleConsumer.search(INPUT.value)
.then(this.setSearch.bind(this))
.catch(this.handleError.bind(this))
.then(() => this.isLoading = false);
}, 300);
}, 0)
}
/**
* Set the search results.
*/
setSearch(html) {
this.searchMode = true;
this.removeAllPages();
this.addPage(html);
}
/**
* Reset the view.
*/
setCategory() {
this.searchMode = false;
this.removeAllPages();
this.loadNextCategoryPage(this.initialCategory, 1);
}
/**
* Removes all pages from DOM.
*/
removeAllPages() {
let nodes = BEM.getBEMNodes(BLOCK_VIEW, ELEMENT_MAIN)
if (nodes.length) {
nodes.forEach(node => node.remove())
}
}
} |
JavaScript | class App1 extends React.Component{
render(){
return(
<Router>
<Switch>
<Route path="/admin" component={App} />
<Route path="/" component={Main} />
</Switch>
</Router>
)
}
} |
JavaScript | class DeleteForEntityIdAndKind extends ServiceBase {
/**
* Constructor to delete specific curated entity row.
*
* @param {object} params
* @param {object} params.current_admin
* @param {number} params.current_admin.id
* @param {string} params.entity_kind
* @param {number} params.entity_id
*
* @augments ServiceBase
*
* @constructor
*/
constructor(params) {
super();
const oThis = this;
oThis.currentAdminId = params.current_admin.id;
oThis.entityKind = params.entity_kind;
oThis.entityId = +params.entity_id;
oThis.entityKindInt = 0;
}
/**
* Async perform.
*
* @returns {Promise<result>}
* @private
*/
async _asyncPerform() {
const oThis = this;
await oThis.validateAndSanitize();
await oThis.fetchAndValidateExistingEntity();
await oThis.deleteEntity();
await oThis.logAdminActivity();
return responseHelper.successWithData({});
}
/**
* Validate and sanitize input parameters.
*
* @sets oThis.entityKindInt
*
* @returns {Promise<never>}
*/
async validateAndSanitize() {
const oThis = this;
oThis.entityKindInt = curatedEntitiesConstants.invertedEntityKinds[oThis.entityKind];
if (!oThis.entityKindInt) {
return Promise.reject(
responseHelper.paramValidationError({
internal_error_identifier: 'a_s_a_c_d_1',
api_error_identifier: 'invalid_api_params',
params_error_identifiers: ['invalid_entity_kind'],
debug_options: { entityKind: oThis.entityKind }
})
);
}
}
/**
* Fetch existing entry for the entity kind and validate if present.
*
* @sets oThis.entityDetails
*
* @returns {Promise<void>}
*/
async fetchAndValidateExistingEntity() {
const oThis = this;
const curatedEntityIdsByKindCacheRsp = await new CuratedEntityIdsByKindCache({
entityKind: oThis.entityKind
}).fetch();
if (!curatedEntityIdsByKindCacheRsp || curatedEntityIdsByKindCacheRsp.isFailure()) {
return Promise.reject(curatedEntityIdsByKindCacheRsp);
}
const curatedEntityIds = curatedEntityIdsByKindCacheRsp.data.entityIds;
if (curatedEntityIds.indexOf(oThis.entityId) === -1) {
return Promise.reject(
responseHelper.error({
internal_error_identifier: 'a_s_a_c_d_2',
api_error_identifier: 'entity_not_found',
debug_options: {
entity_kind: oThis.entityKind,
entity_id: oThis.entityId
}
})
);
}
}
/**
* Delete curated entity from table.
*
* @returns {Promise<*>}
*/
async deleteEntity() {
const oThis = this;
await new CuratedEntityModel().deleteForEntityIdAndKind(oThis.entityId, oThis.entityKind);
}
/**
* Log admin activity.
*
* @returns {Promise<void>}
* @private
*/
async logAdminActivity() {
const oThis = this;
await new AdminActivityLogModel().insertAction({
adminId: oThis.currentAdminId,
actionOn: oThis.entityId,
extraData: JSON.stringify({ eids: [oThis.entityId], enk: oThis.entityKind }),
action: adminActivityLogConstants.deleteCuratedEntity
});
}
} |
JavaScript | class TodoModel {
/**
* @param {Object} todoObject - title, description
* @return {Object} json
* @description constructor method for the todo model
*/
constructor({ todoId='', title, description, userId }) {
this.title = title;
this.description = description;
this.userId = userId;
this.todoId = todoId;
}
/**
* @param {Object} todoObject
* @return {Object} json
* @description method to create a new todo
*/
async create() {
try {
const query = {
text: ADD_TODO_QUERY,
values: [this.userId, this.title, this.description]
};
return await pool.query(query);
} catch (error) {
throw new Error(error);
}
}
/**
* @param {Object} todoObject
* @return {Object} json
* @description method to update a todo
*/
async update() {
try {
// eslint-disable-next-line max-len
const query = `update todos set title='${this.title}', description='${this.description}' where id=${this.todoId} AND userId=${this.userId} returning *`;
return await pool.query(query);
} catch (error) {
throw new Error(error);
}
}
/**
* @param {Object} todoId
* @return {Object} json
* @description method to delete a todo
*/
static async delete({ todoId, userId }) {
try {
// eslint-disable-next-line max-len
const query = `delete from todos Where id=${todoId} AND userid=${userId} returning *;`;
return await pool.query(query);
} catch (error) {
throw new Error(error);
}
}
/**
* @param {Integer} todoId
* @return {Object} json
* @description method to find a todo by id
*/
static async findById(todoId) {
try {
const query = `SELECT * FROM todos WHERE id = '${todoId}';`;
return await pool.query(query);
} catch (error) {
throw new Error(error);
}
}
/**
* @param {Integer} todoId
* @return {Object} json
* @description method to find a todo by id
*/
static async findUserTodoById({ todoId, userId }) {
try {
// eslint-disable-next-line max-len
const query = `select * from todos Where id=${todoId} AND userId=${userId};`;
return await pool.query(query);
} catch (error) {
throw new Error(error);
}
}
/**
* @param {Integer} userId - the userID
* @return {Object} json
* @description method to find all todos for a specific user
*/
static async findAllUserTodos(userId) {
try {
const query = `select * from todos where userId=${userId}`;
return await pool.query(query);
} catch (error) {
throw new Error(error);
}
}
} |
JavaScript | class AddChatMessage extends React.Component {
constructor(props) {
super(props)
this.state = {message: ''}
}
onChangeMessage = (e) => {
this.setState({message: e.target.value})
}
onSendCick = () => {
this.props.onClick({message: this.state.message})
this.setState({message:''})
this.textInput.focus()
}
handleKeyPress = (e) => {
if (e.key === 'Enter'){
e.preventDefault()
this.onSendCick()
return false
}
}
render() {
return (
<div>
<textarea ref={(e) => { this.textInput = e }} onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
<button onClick={this.onSendCick} disabled={(this.state.message.trim()=='')}>Send</button>
</div>
)
}
} |
JavaScript | class ThemeProvider extends Component {
static propTypes = {
theme: PropTypes.object.isRequired,
};
getChildContext() {
let { children, ...context } = this.props;
if (context && context.theme) {
context.theme = Object.assign(defaultTheme, context.theme || {});
}
return context;
}
render({ children }) {
return (children && children[0]) || null;
}
} |
JavaScript | class RoutingAPI extends API {
/**
* Constructor
*
* @param {Object} options Options.
* @param {string} [options.url='https://api.geops.io/routing/v1/'] Service url.
* @param {string} options.apiKey Access key for [geOps services](https://developer.geops.io/).
* @param {string} options.mot Mean of transport on load.
*/
constructor(options = {}) {
super({
...options,
url: options.url || 'https://api.geops.io/routing/v1/',
});
}
/**
* Route.
*
* @param {RoutingSearchParams} params Request parameters. See [Routing service documentation](https://developer.geops.io/apis/routing/).
* @param {AbortController} abortController Abort controller used to cancel the request.
* @returns {Promise<GeoJSONFeatureCollection>} An GeoJSON feature collection with coordinates in [EPSG:4326](http://epsg.io/4326).
*/
route(params, abortController = new AbortController()) {
return this.fetch('', params, {
signal: abortController.signal,
});
}
} |
JavaScript | class HeartbeatController extends _json.default {
constructor(client, sourceId, destinationId) {
super(client, sourceId, destinationId, 'urn:x-cast:com.google.cast.tp.heartbeat');
this.intervalValue = void 0;
this.pingTimer = void 0;
this.timeout = void 0;
this.pingTimer = null;
this.timeout = null;
this.intervalValue = DEFAULT_INTERVAL;
const self = this;
function onMessage(data) {
if (data.type === 'PONG') self.emit('pong');
}
function onClose() {
self.removeListener('message', onMessage);
self.stop();
}
this.on('message', onMessage);
this.once('close', onClose);
}
ping() {
debug('Received a .ping() before checking timeout');
if (this.timeout) return; // We already have a ping in progress.
debug('We do not have a timeout, so we are continuing');
this.timeout = setTimeout(() => {
this.emit('timeout');
}, this.intervalValue * 1000 * TIMEOUT_FACTOR);
this.once('pong', () => {
clearTimeout(this.timeout);
this.timeout = null;
this.pingTimer = setTimeout(() => {
this.pingTimer = null;
this.ping();
}, this.intervalValue * 1000);
});
this.send({
type: 'PING'
});
}
start(intervalValue) {
this.intervalValue = intervalValue || this.intervalValue;
this.ping();
}
stop() {
if (this.pingTimer) clearTimeout(this.pingTimer);
if (this.timeout) clearTimeout(this.timeout);
this.removeAllListeners('pong');
}
} |
JavaScript | class TypingResult {
constructor(elm_root, text) {
this.text_length = text.length;
this.elm_root = elm_root;
this.elm_info_terms_number = elm_root.querySelector(".modalbox__infotermsnumber");
this.elm_info_duration = elm_root.querySelector(".modalbox__infoduration");
this.elm_info_speed = elm_root.querySelector(".modalbox__infospeed");
this.elm_info_errors = elm_root.querySelector(".modalbox__infoerrors");
this.total_terms = window.localStorage.getItem('terms_number') ?? text.split(' ').length;
this.elm_info_terms_number.innerHTML = this.total_terms;
this.duration = 0;
this.duration_interval = null;
this.startDuration();
// this.debugProperties()
}
// DEV only
debugProperties() {
let array = Object.getOwnPropertyNames(this);
array.forEach( (entry) => {
console.log( entry + " :", this[entry]);
});
}
/**
* Count the number of seconds since the typing session start
* @private
* @returns {void}
*/
startDuration() {
this.duration_interval = setInterval( ()=>{ this.duration += 1 }, 1000 );
}
/**
* Put the statistic informations in the modal box
* @returns {void}
* @param {number} errors_number
*/
terminate(errors_number) {
if (this.duration_interval) {
// Info - duration
clearInterval(this.duration_interval);
this.elm_info_duration.innerHTML = getTime(this.duration);
// Info - Words typed / mn
const words_per_mn = getWordsByMinute(this.total_terms, this.duration);
const string_end = words_per_mn === 1 ? " mot / mn" : " mots / mn"
this.elm_info_speed.innerHTML = words_per_mn + string_end;
// Info - Errors
this.elm_info_errors.innerHTML = getErrorsPercent(errors_number, this.text_length) + " %";
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.