language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class UIList extends UIComponentPrototype {
/**
* @event PhaserComps.UIComponents.UIList.EVENT_ITEM_CHANGE
* @memberOf PhaserComps.UIComponents.UIList
* @description
* Emitted when any item emits such even.
* @param {PhaserComps.UIComponents.UIListBaseItem} item item instance, that emitted change event
*/
static get EVENT_ITEM_CHANGE() { return EVENT_ITEM_CHANGE; }
constructor(parent, key, rendererClass) {
super(parent, key);
this._rendererClass = rendererClass;
this._items = [];
}
/**@return {*[]}*/
get data() {
return this._data;
}
/** @param {*[]} value */
set data(value) {
this._data = value;
this._updateData();
}
/**
* @method PhaserComps.UIComponents.UIList#clean
* @desc Destroy all items renderer instances
*/
clean() {
while(this._items.length !== 0) {
let item = this._items.pop();
item.destroy(true);
}
}
_updateData() {
const len = this._data.length;
for (let index = 0; index < len; index++) {
let dataItem = this._data[index];
let item = this._getRenderer(index);
item.data = dataItem;
}
this.doState();
}
_getRenderer(index) {
if (this._items.length - 1 < index) {
let renderer = new this._rendererClass(this, "item_" + index);
this._items[index] = renderer;
renderer.on(UIList.EVENT_ITEM_CHANGE, this.onItemChange, this);
}
return this._items[index];
}
/**
* @method PhaserComps.UIComponents.UIList#getStateId
* @inheritDoc
* @returns {String}
*/
getStateId() {
return "count_" + (this._data ? this._data.length : "0");
}
/**
* @method PhaserComps.UIComponents.UIList#destroy
* @protected
* @inheritDoc
*/
destroy(fromScene) {
this.clean();
super.destroy(fromScene);
}
onItemChange(item) {
this.emit(UIList.EVENT_ITEM_CHANGE, item);
}
} |
JavaScript | class StateMachine {
constructor(originator, defaultState = null) {
this._originator = originator;
this._defaultState = defaultState;
this.initialize();
}
//current active state
get active() {
return utility_1.default.lastElement(this._states);
}
initialize() {
this._states = [];
//initialize state tracker if default state is given
if (this._defaultState) {
this.push(this._defaultState);
}
}
reset() {
this.initialize();
}
push(state) {
if (this.active !== state) {
this._states.push(state);
}
}
pop() {
return this._states.pop();
}
//replace current active state
swap(state) {
this.pop();
this.push(state);
}
update(timeStep) {
if (this.active) {
this._originator[this.active](timeStep);
}
}
} |
JavaScript | class distanceRGBA_frag{static theWord() {
return "#define DISTANCE\n\
\n\
uniform vec3 referencePosition;\n\
uniform float nearDistance;\n\
uniform float farDistance;\n\
varying vec3 vWorldPosition;\n\
\n\
#include <common>\n\
#include <packing>\n\
#include <uv_pars_fragment>\n\
#include <map_pars_fragment>\n\
#include <alphamap_pars_fragment>\n\
#include <clipping_planes_pars_fragment>\n\
\n\
void main () {\n\
\n\
#include <clipping_planes_fragment>\n\
\n\
vec4 diffuseColor = vec4( 1.0 );\n\
\n\
#include <map_fragment>\n\
#include <alphamap_fragment>\n\
#include <alphatest_fragment>\n\
\n\
float dist = length( vWorldPosition - referencePosition );\n\
dist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\
dist = saturate( dist ); // clamp to [ 0, 1 ]\n\
\n\
gl_FragColor = packDepthToRGBA( dist );\n\
\n\
}\n\
";
}} |
JavaScript | class MemoryRouter extends React.Component {
static propTypes = {
initialEntries: PropTypes.array,
initialIndex: PropTypes.number,
getUserConfirmation: PropTypes.func,
keyLength: PropTypes.number,
children: PropTypes.node
}
history = createHistory(this.props)
render() {
return <Router history={this.history} children={this.props.children}/>
}
} |
JavaScript | class List {
children = [];
constructor(root, props) {
this.root = root;
this.props = props;
}
appendChild(child) {
this.children.push(child);
}
removeChild(child) {
const index = this.children.indexOf(child);
this.children.slice(index, 1);
}
async renderChildren(align, styles) {
// Override the styles and use List component styles
// expected an assignment
styles = this.props.style ? this.props.style : styles;
for (let i = 0; i < this.children.length; i += 1) {
await this.children[i].render(align, styles);
}
}
async render(align, styles) {
await this.renderChildren(align, styles);
}
} |
JavaScript | class ChildMessageRenderer extends Component {
constructor(props) {
super(props);
this.state = {
id:props.value
}
this.invokeParentMethod = this.invokeParentMethod.bind(this);
}
invokeParentMethod(e) {
window.location.href="#/module/workpack";
}
render() {
return (
<NavLink href="#/module/workpack" data-id={this.state.id} className="btn btn-info">View</NavLink>
);
}
} |
JavaScript | class SearchBar extends Component { // see line 3 comments
constructor(props) {
super(props)
this.state = { term: '' }; // only time you use this syntax to set value of state! otherwise, use setState()
}
onInputChange(term) {
this.setState({ term });
this.props.onSearchTermChange(term);
}
render() { // what is run when a component is re-renders
return (
<div className="search-bar">
<input
value={this.state.term}
onChange={event => this.onInputChange(event.target.value)} />
</div>
);
}
} |
JavaScript | class TaskDelayer {
constructor({
delay = 10,
operator = '||',
task = (queue, index) => {}
} = {}) {
this.delay = delay;
this.operator = operator;
this.task = task;
this._init(arguments[0]);
}
_init(options) {
this._queue = [];
this._lastTimestamp = 0;
this._index = 0;
this._checker = null;
if (typeof options === 'object') {
Object.entries(options).forEach(e => this[e[0]] = e[1]);
}
if (this.operator.toLowerCase() === 'or') {
this.operator = '||';
}
if (this.operator.toLowerCase() === 'and') {
this.operator = '&&';
}
}
_check() {
if (+this.delay < 0 && isNaN(+this.delay)) {
throw new Error('The "delay" property must be a number.');
}
this._checker = setTimeout(() => {
this._stamp();
this._ship();
this._clear();
clearTimeout(this._checker);
}, +this.delay);
}
_stock(target) {
this._queue.push(target);
}
_ship() {
if (typeof this.task !== 'function') {
throw new Error('The "task" property must be a function.');
}
this.task(this._queue, this._index);
}
_stamp() {
this._lastTimestamp = Date.now();
}
_clear() {
this._queue.splice(0, this._queue.length);
this._index = 0;
}
_canShip() {
let results = [];
if (typeof this.condition === 'function') {
results.push({ship: this.condition()});
}
if (+this.count > 0) {
results.push({
ship: this._index % this.count === 0 && this._queue.length === 0
});
}
if (+this.interval > 0) {
results.push({
ship: Date.now() - this._lastTimestamp >= this.interval
});
}
if (results.length < 1) {
throw new Error('No specified condition.');
}
let canShip = true;
switch (this.operator) {
case '||':
canShip = false;
results.forEach(e => {
canShip = canShip || e.ship;
});
break;
case '&&':
canShip = true;
results.forEach(e => {
canShip = canShip && e.ship;
});
break;
default:
throw new Error('Operator property must be "or" or "and"');
}
return canShip;
}
spawn(target) {
if (!this._lastTimestamp) {
this._stamp();
}
this._index++;
let check;
if (typeof this.condition === 'function') {
check = this.condition();
} else if (+this.count > 0) {
check = this._index % this.count > 0 && this._queue.length === 0;
} else if (+this.interval > 0) {
check = Date.now() - this._lastTimestamp < this.interval;
} else {
throw new Error('No specified condition.');
}
if (this._canShip()) {
this._stamp();
this._stock(target);
this._ship();
this._clear();
} else {
this._checker && clearTimeout(this._checker);
this._stock(target);
this._check();
}
}
queue() {
return Object.assign({}, this._queue);
}
index() {
return this._index;
}
} |
JavaScript | class KeyboardFuzzer {
constructor( display, seed ) {
// @private
this.display = display;
this.random = new Random( { seed: seed } );
this.numberOfComponentsTested = 10;
this.keyupListeners = [];
// @private {HTMLElement}
this.currentElement = null;
}
/**
* @private
* Randomly decide if we should focus the next element, or stay focused on the current element
*/
chooseNextElement() {
if ( this.currentElement === null ) {
this.currentElement = document.activeElement;
}
else if ( this.random.nextDouble() < NEXT_ELEMENT_THRESHOLD ) {
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.KeyboardFuzzer( 'choosing new element' );
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.push();
// before we change focus to the next item, immediately release all keys that were down on the active element
this.clearListeners();
const nextFocusable = PDOMUtils.getRandomFocusable( this.random );
nextFocusable.focus();
this.currentElement = nextFocusable;
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.pop();
}
}
/**
* @private
*/
clearListeners() {
this.keyupListeners.forEach( listener => {
assert && assert( typeof listener.timeout === 'function', 'should have an attached timeout' );
stepTimer.clearTimeout( listener.timeout );
listener();
assert && assert( !this.keyupListeners.includes( listener ), 'calling listener should remove itself from the keyupListeners.' );
} );
}
/**
* @private
* @param {HTMLElement} element
*/
triggerClickEvent( element ) {
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.KeyboardFuzzer( 'triggering click' );
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.push();
element.click();
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.pop();
}
/**
* Trigger a keydown/keyup pair. The keyup is triggered with a timeout.
* @private
*
* @param {HTMLElement} element
* @param {string} key
*/
triggerKeyDownUpEvents( element, key ) {
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.KeyboardFuzzer( `trigger keydown/up: ${key}` );
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.push();
// TODO: screen readers normally take our keydown events, but may not here, is the discrepancy ok?
this.triggerDOMEvent( KEY_DOWN, element, key );
const randomTimeForKeypress = this.random.nextInt( MAX_MS_KEY_HOLD_DOWN );
const keyupListener = () => {
this.triggerDOMEvent( KEY_UP, element, key );
if ( this.keyupListeners.includes( keyupListener ) ) {
this.keyupListeners.splice( this.keyupListeners.indexOf( keyupListener ), 1 );
}
};
keyupListener.timeout = stepTimer.setTimeout( keyupListener, randomTimeForKeypress === MAX_MS_KEY_HOLD_DOWN ? 2000 : randomTimeForKeypress );
this.keyupListeners.push( keyupListener );
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.pop();
}
/**
* Trigger a keydown/keyup pair with a random key
* @private
* @param {HTMLElement} element
*/
triggerRandomKeyDownUpEvents( element ) {
const randomKey = ALL_KEYS[ Math.floor( this.random.nextDouble() * ( ALL_KEYS.length - 1 ) ) ];
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.KeyboardFuzzer( `trigger random keydown/up: ${randomKey}` );
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.push();
this.triggerKeyDownUpEvents( element, randomKey );
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.pop();
}
/**
* A random event creator that sends keyboard events. Based on the idea of fuzzMouse, but to test/spam accessibility
* related keyboard navigation and alternate input implementation.
*
* @public
* TODO: NOTE: Right now this is a very experimental implementation. Tread wearily
* TODO: @param keyboardPressesPerFocusedItem {number} - basically would be the same as fuzzRate, but handling
* TODO: the keydown events for a focused item
*/
fuzzBoardEvents( fuzzRate ) {
const pdomPointer = this.display._input.pdomPointer;
if ( pdomPointer && !pdomPointer.blockTrustedEvents ) {
pdomPointer.blockTrustedEvents = true;
}
for ( let i = 0; i < this.numberOfComponentsTested; i++ ) {
// find a focus a random element
this.chooseNextElement();
for ( let i = 0; i < fuzzRate / this.numberOfComponentsTested; i++ ) {
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.KeyboardFuzzer( `main loop, i=${i}` );
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.push();
// get active element, focus might have changed in the last press
const elementWithFocus = document.activeElement;
if ( keyboardTestingSchema[ elementWithFocus.tagName.toUpperCase() ] ) {
const randomNumber = this.random.nextDouble();
if ( randomNumber < DO_KNOWN_KEYS_THRESHOLD ) {
const keyValues = keyboardTestingSchema[ elementWithFocus.tagName ];
const key = this.random.sample( keyValues );
this.triggerKeyDownUpEvents( elementWithFocus, key );
}
else if ( randomNumber < CLICK_EVENT_THRESHOLD ) {
this.triggerClickEvent( elementWithFocus );
}
else {
this.triggerRandomKeyDownUpEvents( elementWithFocus );
}
}
else {
this.triggerRandomKeyDownUpEvents( elementWithFocus );
}
// TODO: What about other types of events, not just keydown/keyup??!?!
// TODO: what about application role elements
sceneryLog && sceneryLog.KeyboardFuzzer && sceneryLog.pop();
}
}
}
/**
* Taken from example in http://output.jsbin.com/awenaq/3,
* @param {string} event
* @param {HTMLElement} element
* @param {string} key
* @private
*/
triggerDOMEvent( event, element, key ) {
const eventObj = new KeyboardEvent( event, {
bubbles: true,
key: key,
shiftKey: globalKeyStateTracker.shiftKeyDown,
altKey: globalKeyStateTracker.altKeyDown,
ctrlKey: globalKeyStateTracker.ctrlKeyDown
} );
element.dispatchEvent( eventObj );
}
} |
JavaScript | class MapWrapper extends PureComponent {
/**
* @param {HTMLElement} root The root element for which the component will be rendered.
*/
constructor(root) {
super(root);
this.root = root;
this._elmRoot = super.render(MapWrapperTemplate(), "#map");
document.querySelector("#cyt_root").children[0].classList.add("cyt_container");
}
/**
* @return {HTMLElement} elmRoot Root element for rendering courseItem
*/
get subRoot() {
return this._elmRoot;
}
} |
JavaScript | class GameDb {
/**
* Create a connection with the DB.
* @return {Promise}
*/
static connect() {
return (MongoClient.connect(DB_HOST, CONNECT_OPTIONS));
}
/**
* Add a game with the name passed as parameter in the db.
* @param {String} gameName
*/
static add(gameName) {
let newGame = { name: gameName };
this.connect().then((client) => {
let db = client.db(DB_NAME);
db.collection(DB_COLLECTION).insertOne(newGame, QUERY_NO_OPTIONS,
(err, results) => { if (err) throw err; });
client.close();
});
}
/**
* Edit the name of a game by a new one.
* @param {String} oldName
* @param {String} newName
*/
static edit(oldName, newName) {
this.connect().then((client) => {
let db = client.db(DB_NAME);
db.collection(DB_COLLECTION).updateOne(
{ name: oldName },
{ $set: { name: newName } }
);
client.close();
});
}
/**
* Deletes a game from the database with its id.
* @param {String} id [The ID of the game we want to delete from the DB]
*/
static delete(id) {
let objToDelete = { _id: new MongoObjectID(id) };
this.connect().then((client) => {
let db = client.db(DB_NAME);
db.collection(DB_COLLECTION).deleteOne(objToDelete,
QUERY_NO_OPTIONS, (err, results) => { if (err) throw err; });
client.close();
});
}
} |
JavaScript | class abWeb_Sass extends abWeb.Ext
{
constructor(abWeb, extPath)
{ super(abWeb, extPath);
this._header = this.uses('header');
this.cssDir = path.join(this.buildInfo.front, 'css');
if (!abFS.dir.existsSync(this.cssDir)) {
this.console.warn(`\`${this.cssDir}\` does not exist. Creating...`);
abFS.dir.createRecursiveSync(this.cssDir);
}
let relDir = path.relative(this.buildInfo.index, this.buildInfo.front);
this._sourceDirPath = relDir;
this._sourcePath_Base = path.join(this.cssDir, 'sass');
this._sourcePath = path.join(this.cssDir, 'sass.css');
this._variablesPaths = [];
this._stylesPaths = [];
this._variants = [];
this._substyles = [];
// this._preloads = [];
this._devPath = path.relative(this.cssDir, this.buildInfo.dev)
.replace(/\\/g, '/', '/');
this._distPath = path.relative(this.cssDir, this.buildInfo.dist)
.replace(/\\/g, '/', '/');
}
_createCss(css, sourceAlias)
{
let cssPath = path.join(this.cssDir, sourceAlias === '_default' ?
'sass.css' : `sass-${sourceAlias}.css`);
let relativeCss = '';
let regex = /url\(\s*([\'"])?(\{(.+?)\})+(.*?)([\'"])?\s*\)/gm;
let regexIndex = 0;
while (true) {
let match = regex.exec(css);
if (match === null)
break;
if (match.index <= regexIndex)
continue;
let open = typeof(match[1]) === 'undefined' ? '' : match[1];
let close = typeof(match[5]) === 'undefined' ? '' : match[5];
if (open !== close)
continue;
relativeCss += css.substring(regexIndex, match.index);
if (match[4].match(/^(((https?:)?\/\/)|(data:))/)) {
relativeCss += `url(${open}${match[4]}${close})`;
} else {
let relPath = match[3];
if (this.buildInfo.type('rel')) {
if (match[3].indexOf(this._devPath) === 0) {
relPath = this._distPath +
match[3].substring(this._devPath.length);
}
}
let relation = path.join(relPath, match[4])
.replace(/\\/g, '/');
relativeCss += `url(${open}${relation}${close})`;
// this._preloads.push(relation);
}
regexIndex = match.index + match[0].length;
}
relativeCss += css.substring(regexIndex, css.length);
fs.writeFileSync(cssPath, relativeCss);
}
_getSources(fsPaths)
{
let sources = {
'_default': '',
};
for (let variant of this._variants) {
sources[variant] = '';
}
for (let substyle of this._substyles) {
sources[substyle] = '';
}
this.console.log('Variables:');
for (let fsPath of fsPaths.variables) {
let relativePath = path.relative(this._sourceDirPath, fsPath);
relativePath = relativePath.replace(/\\/g, '/');
sources['_default'] += '@import "{abWeb}' + relativePath + '";\r\n';
for (let variant of this._variants) {
sources[variant] += '@import "{abWeb}' + relativePath + '";\r\n';
}
this.console.log(' - ' + relativePath);
}
for (let variant of this._variants) {
this.console.log('Variant: ' + variant);
for (let fsPath of fsPaths[`variants.${variant}.variables`]) {
let relativePath = path.relative(this._sourceDirPath, fsPath);
relativePath = relativePath.replace(/\\/g, '/');
sources[variant] += '@import "{abWeb}' + relativePath + '";\r\n';
this.console.log(' - ' + relativePath);
}
}
for (let substyle of this._substyles) {
this.console.log('Substyle: ' + substyle);
for (let fsPath of fsPaths[`substyles.${substyle}.variables`]) {
let relativePath = path.relative(this._sourceDirPath, fsPath);
relativePath = relativePath.replace(/\\/g, '/');
sources[substyle] += '@import "{abWeb}' + relativePath + '";\r\n';
this.console.log(' - ' + relativePath);
}
}
// sassSource += '\r\n';
this.console.log('Styles:');
for (let fsPath of fsPaths.styles) {
if (path.basename(fsPath) === 'variables.scss')
continue;
let relativePath = path.relative(this._sourceDirPath, fsPath);
relativePath = relativePath.replace(/\\/g, '/');
if (path.extname(relativePath) === '.css')
relativePath += '-abWeb';
sources['_default'] += '@import "{abWeb}' + relativePath + '";\r\n';
for (let variant of this._variants) {
sources[variant] += '@import "{abWeb}' + relativePath + '";\r\n';
}
this.console.log(' - ' + relativePath);
}
for (let variant of this._variants) {
this.console.log('Variant: ' + variant);
for (let fsPath of fsPaths[`variants.${variant}.styles`]) {
if (path.basename(fsPath) === 'variables.scss')
continue;
let relativePath = path.relative(this._sourceDirPath, fsPath);
relativePath = relativePath.replace(/\\/g, '/');
if (path.extname(relativePath) === '.css')
relativePath += '-abWeb';
sources[variant] += '@import "{abWeb}' + relativePath + '";\r\n';
this.console.log(' - ' + relativePath);
}
}
for (let substyle of this._substyles) {
this.console.log('Variant: ' + substyle);
for (let fsPath of fsPaths[`substyles.${substyle}.styles`]) {
if (path.basename(fsPath) === 'variables.scss')
continue;
let relativePath = path.relative(this._sourceDirPath, fsPath);
relativePath = relativePath.replace(/\\/g, '/');
if (path.extname(relativePath) === '.css')
relativePath += '-abWeb';
sources[substyle] += '@import "{abWeb}' + relativePath + '";\r\n';
this.console.log(' - ' + relativePath);
}
}
return sources;
}
_parseSource(url, prev, done)
{
if (url.indexOf('{abWeb}') === 0) {
url = url.substring('{abWeb}'.length);
}
if (path.extname(url) === '.css-abWeb')
url = url.substring(0, url.length - '-abWeb'.length);
let urlPath = path.join(this._sourceDirPath, url);
if (path.extname(urlPath) !== '.scss' && path.extname(urlPath) !== '.css')
urlPath += '.scss';
let urlPath_Dir = path.dirname(urlPath);
let urlPath_Base = path.basename(urlPath);
if (!fs.existsSync(urlPath))
urlPath = path.join(urlPath_Dir, '_' + urlPath_Base);
if (!fs.existsSync(urlPath)) {
this.console.error(`File '${url}' imported in '${prev}' does not exist.`);
done({ contents: '' });
return;
}
fs.readFile(urlPath, (err, data) => {
if (err) {
this.console.error('Cannot read file: ', url);
done({ contents: '' });
return;
}
let sass = data.toString();
sass = sass.replace(/@import\s*([\'"])\s*/g, '@import $1' +
path.dirname(url) + '/');
let relativeSass = '';
let regex = /url\(\s*([\'"])?(?!(?:https?:)?\/\/)(?!data:)(.*?)([\'"])?\s*\)/gm;
let regexIndex = 0;
while (true) {
let match = regex.exec(sass);
if (match === null)
break;
if (match.index <= regexIndex)
continue;
let open = typeof(match[1]) === 'undefined' ? '' : match[1];
let close = typeof(match[3]) === 'undefined' ? '' : match[3];
if (open !== close)
continue;
relativeSass += sass.substring(regexIndex, match.index);
let relation = path.relative(this.cssDir,
path.dirname(urlPath)).replace(/\\/g, '/');
relativeSass += `url(${open}{${relation}}${match[2]}${close})`;
regexIndex = match.index + match[0].length;
}
relativeSass += sass.substring(regexIndex, sass.length);
done({ contents: relativeSass });
});
}
// _replaceRelativeUrls_ParseUrlPath(urlPaths, url, prev)
// {
// let prevPath = null;
// for (let i = urlPaths.length - 1; i >= 0; i--) {
// if (urlPaths[i].url === prev) {
// prevPath = urlPaths[i].path;
// break;
// }
// }
// if (prevPath === null)
// prevPath = path.resolve(prev);
// let urlPath = path.join(path.dirname(prevPath), url);
// urlPaths.push({
// url: url,
// path: urlPath,
// });
// return urlPath;
// }
/* abWeb.Ext Overrides */
__build(taskName)
{
let promises = [];
for (let sourceAlias in this._sources) {
let sourcePath = sourceAlias === '_default' ?
this._sourcePath : (this._sourcePath_Base + '-' +
sourceAlias + '.css');
promises.push(() => { return new Promise((resolve, reject) => {
let compress = false;
let dumpLineNumbers = 'comments';
if (this.buildInfo.type('rel')) {
compress = true;
dumpLineNumbers = null
}
let urlPaths = [];
dartSass.render({
data: this._sources[sourceAlias],
file: sourcePath,
includePaths: [ this._sourceDirPath ],
importer: (url, prev, done) => {
return this._parseSource(url, prev, done);
},
outputStyle: this.buildInfo.type('rel') ? 'compressed' : 'expanded',
}, (err, result) => {
if (err) {
this.console.error('Error compiling sass.');
this.console.warn(err);
this.console.warn(' File: ' + err.file)
this.console.warn(' Index: ' + err.column)
this.console.warn(' Line: ' + err.line)
resolve(); return;
}
// this._preloads = [];
this._createCss(result.css.toString('utf-8'), sourceAlias);
if (this._header.hasTagsGroup_Header('preloads'))
this._header.clearTagsGroup_Header('preloads');
// for (let preload of this._preloads) {
// let as = null;
// let ext = path.extname(preload).toLowerCase();
// let extRaw = ext.split('?')[0].split('#')[0];
// let preloadUri = preload.substring(0, preload.length - ext.length) +
// extRaw;
// if ([ '.jpg', '.jpeg', '.gif', '.png' ].includes(ext)) {
// as = 'image';
// } else if ([ '.eot', '.eot?#iefix', '.woff', '.woff2', '.ttf', '.svg',
// '.svg#fontawesome' ]
// .includes(ext)) {
// as = 'font';
// } else
// continue;
// this._header.addTag_Header('preloads', 'link', {
// rel: "preload",
// href: preloadUri,
// as: as,
// });
// }
resolve();
});
})});
}
return (async () => {
for (let promise of promises)
await promise();
this._header.build();
this.console.success('Finished.');
})();
}
__onChange(fsPaths, changes)
{
this._sources = this._getSources(fsPaths);
this.build();
}
__parse(config)
{
if (!('paths' in config))
return;
if (config.addToHeader) {
this._header.addTag_Header('sass', 'link', {
id: 'ABWeb_Sass_Styles',
rel: "stylesheet",
href: this.uri(this._sourcePath, true),
type: "text/css"
});
this._header.addTagsGroup_Header('preloads', {
'after': [ 'sass' ],
});
}
this._variablesPaths = [];
this._stylesPaths = [];
this._variantPaths = {};
this._substylePaths = {};
// this._preloads = [];
let watchPaths = [];
for (let fsPath of config.paths) {
if (path.extname(fsPath) === '.scss' || path.extname(fsPath) === '.css') {
this._stylesPaths.push(fsPath);
watchPaths.push(path.join(path.dirname(fsPath), '*.*css'));
} else if (path.extname(fsPath) === '') {
this._variablesPaths.push(path.join(fsPath, 'variables.scss'));
this._stylesPaths.push(path.join(fsPath, 'styles.scss'));
watchPaths.push(path.join(fsPath, '*.*css'));
} else
this.console.error('Unknown extension type: ', fsPath);
}
for (let variant in config.variants) {
this._variants.push(variant);
let variant_VariablePaths = [];
let variant_StylePaths = [];
for (let fsPath of config.variants[variant]) {
if (path.extname(fsPath) === '.scss' ||
path.extname(fsPath) === '.css') {
variant_StylePaths.push(fsPath);
watchPaths.push(path.join(path.dirname(fsPath), '*.*css'));
} else if (path.extname(fsPath) === '') {
variant_VariablePaths.push(path.join(fsPath, 'variables.scss'));
variant_StylePaths.push(path.join(fsPath, 'styles.scss'));
watchPaths.push(path.join(fsPath, '*.*css'));
} else
this.console.error('Unknown extension type: ', fsPath);
}
this.watch(`variants.${variant}.variables`, [ 'add', 'unlink', 'change' ],
variant_VariablePaths);
this.watch(`variants.${variant}.styles`, [ 'add', 'unlink', 'change' ],
variant_StylePaths);
}
for (let substyle in config.substyles) {
this._substyles.push(substyle);
let substyle_VariablePaths = [];
let substyle_StylePaths = [];
for (let fsPath of config.substyles[substyle]) {
if (path.extname(fsPath) === '.scss' ||
path.extname(fsPath) === '.css') {
substyle_StylePaths.push(fsPath);
watchPaths.push(path.join(path.dirname(fsPath), '*.*css'));
} else if (path.extname(fsPath) === '') {
substyle_VariablePaths.push(path.join(fsPath, 'variables.scss'));
substyle_StylePaths.push(path.join(fsPath, 'styles.scss'));
watchPaths.push(path.join(fsPath, '*.*css'));
} else
this.console.error('Unknown extension type: ', fsPath);
}
this.watch(`substyles.${substyle}.variables`, [ 'add', 'unlink', 'change' ],
substyle_VariablePaths);
this.watch(`substyles.${substyle}.styles`, [ 'add', 'unlink', 'change' ],
substyle_StylePaths);
}
this.watch('scss', [ 'add', 'unlink', 'change' ], watchPaths);
this.watch('variables', [ 'add', 'unlink', 'change' ], this._variablesPaths);
this.watch('styles', [ 'add', 'unlink', 'change' ], this._stylesPaths);
}
/* / abWeb.Ext Overrides */
} |
JavaScript | class CarsListAux extends React.Component {
constructor(props) {
super(props);
this.gallery = React.createRef();
this.carousel = React.createRef();
this.state = {
slides: 3,
space: 20,
};
}
componentDidMount() {
window.addEventListener("resize", this.updateResolution.bind(this));
this.updateResolution();
}
updateResolution() {
let number = 1;
if (window.innerWidth <= 700) number = 1;
else if (window.innerWidth > 700 && window.innerWidth <= 1024) number = 2;
else if (window.innerWidth > 1024) number = 3;
this.setState(
{
slides: number,
space: number === 1 ? 0 : number === 2 ? 10 : 20
}
)
}
render() {
return (
<Row className="cars-container">
<Col xs="12">
{!this.props.loading &&
<Carousel
ref={this.carousel}
enableKeyboardControls={true}
autoplay={false}
pauseOnHover={true}
slideIndex={0}
slidesToShow={this.state.slides}
cellSpacing={5}
wrapAround={true}
renderCenterLeftControls={({ previousSlide }) => (
<button className="button-carousel" onClick={previousSlide}>{'\u25C4'}</button>
)}
renderCenterRightControls={({ nextSlide }) => (
<button className="button-carousel" onClick={nextSlide}>{'\u25BA'}</button>
)}
renderTopCenterControls={({ currentSlide }) => (
<div>Anuncio {currentSlide + 1} de {this.props.cars.length}</div>
)}
renderBottomCenterControls={() => {}}
>
{ this.props.cars.map((car) => {
return (
<CustomCardLg
key={car.id}
index={car.id}
url={car.url}
image={car.image}
name={car.name}
text={car.text}
oil={car.oil}
shift={car.shift}
kilometers={car.kilometers}
cylinders={car.cylinders}
power={car.power}
year={car.year}
price={car.price}
brand={car.brand}
onGalleryClick={this.openLightbox.bind(this)}
/>
)
})
}
</Carousel>
}
{this.props.loading &&
<div className="spinner">
<img src={logo} alt="loading..." />
<h3>Loading data...</h3>
</div>
}
{ !this.props.loading &&
<PopupGallery ref={this.gallery} images={this.props.cars[0].images} />
}
</Col>
</Row>
);
}
openLightbox(e) {
e.preventDefault();
let index = '' + parseInt(e.currentTarget.dataset.index);
for (let i = 0; i < this.props.cars.length; i++) {
const car = this.props.cars[i];
if (index === car.id) {
this.gallery.current.setImages(car.images);
this.gallery.current.showGallery();
}
}
}
closeLightbox(e) {
e.preventDefault();
this.gallery.current.closeGallery();
}
} |
JavaScript | class Engine {
constructor(scenes, initial) {
this.scenes = scenes
this.active = initial
scenes[initial].load()
}
switchTo(target, ...args) {
const { active, scenes } = this
if (target === active) {
return console.warn(`Tried to switch to active scene ${target}!`)
}
scenes[active].unload()
scenes[target].load(...args)
this.active = target
if ('activeElement' in document) {
document.activeElement.blur()
}
}
} |
JavaScript | class Scene {
constructor(selector) { this.container = _(selector) }
load(...args) { this.container.classList.add('show') }
unload() { this.container.classList.remove('show') }
} |
JavaScript | class Loading extends Component {
constructor(props) {
super(props);
this.container = React.createRef();
this.fadeOut = this.fadeOut.bind(this);
}
componentDidMount() {
this.fadeOut();
}
fadeOut() {
const { onComplete } = this.props;
const elm = this.container.current;
TweenMax.to(elm, 0.25, { opacity: 0, delay: 0.5, onComplete });
}
render() {
return (
<div className='re-toolkit-loading' ref={this.container}>
<div className='loader' />
</div>
);
}
} |
JavaScript | class PayslipsList extends PureComponent
{
render()
{
return <PayslipsContext.Consumer>
{({payslips}) => {
if (!payslips.length) {
return <p>
No payslips have been calculated.
Please go to the main page and add an employee data to calculate a payslip.
</p>;
}
return <table className="payslipsTable">
<thead>
<tr>
<th>Name</th>
<th>Pay period</th>
<th style={{textAlign: 'right'}}>Gross income</th>
<th style={{textAlign: 'right'}}>Income tax</th>
<th style={{textAlign: 'right'}}>Net income</th>
<th style={{textAlign: 'right'}}>Super amount</th>
</tr>
</thead>
<tbody>
{payslips.map(payslip => (
<PayslipRow key={payslip.id} {...payslip}/>
))}
</tbody>
</table>;
}}
</PayslipsContext.Consumer>;
}
} |
JavaScript | class ThemeQueryManager extends PaginatedQueryManager {
static QueryKey = ThemeQueryKey;
static DefaultQuery = DEFAULT_THEME_QUERY;
/**
* A sorting function that defines the sort order of items under
* consideration of the specified query.
*
* Note that this isn't doing anything so the results are kept in the order they
* are received from the endpoint.
* The themes query REST API endpoint uses ElasticSearch to sort results by
* relevancy, which we cannot easily mimick on the client side.
*/
static sort() {
return; // Leave the keys argument unchanged.
}
} |
JavaScript | class Ring {
constructor(endpoint) {
//console.log("d3 ", d3);
this.endpoint = endpoint;
this.maxWidth= 290;
this.nextLine = 60;
this.fetchData();
}
init() {
this.element = d3
.select('#rings-container')
.append('li')
.attr("class","ring-container")
.append("div")
.attr("id", this.dataset.title)
.attr("class", "ring")
this.width = parseInt(d3.select('#'+this.dataset.title).style('width'))
this.height = 320 ;
console.log("this height ", this.height)
this.radius = this.width / 3.5;
this.thickness = 10;
this.margin = {
top: (this.height - this.radius) / 2,
right: (this.width - this.radius) / 2,
bottom: (this.height - this.radius) / 2,
left: (this.width - this.radius) / 2,
};
this.center = { x: this.width / 2, y: this.height / 2 + 15 };
this.element.innerHTML = '';
this.total = this.dataset.items.reduce((acc, currValue) => {
return acc + currValue.value;
}, 0);
this.domain = this.dataset.items.map(d => d.name);
this.draw();
}
draw() {
//draw pie
this.svgViewport = this.element
.append('svg')
.attr('width', this.width)
.attr('height', this.height + (parseInt((this.dataset.items.length-1)/2)*this.nextLine))
const graph = this.svgViewport
.append('g')
.attr('transform', `translate(${this.center.x},${this.center.y})`);
const ring = d3
.pie()
.sort(null)
.value(d => d.value);
const arcPath = d3
.arc()
.outerRadius(this.radius)
.innerRadius(this.radius - this.thickness);
const itemsColor = this.dataset.items.map( item => item.color);
const itemsName = this.dataset.items.map (item => item.name)
const color = d3.scaleOrdinal( itemsColor);
color.domain = itemsName;
const paths = graph.selectAll('path').data(ring(this.dataset.items));
paths
.enter()
.append('path')
.attr('class', 'arc')
.attr('d', arcPath)
.attr('stroke', '#fff')
.attr('stroke-width', 1)
.attr('fill', d => color(d.data.name));
this.drawTitles();
this.drawItemsText()
}
drawTitles() {
const circle = this.svgViewport
.append('g')
.attr('class', 'circle');
/*circle
.append('circle')
.attr('transform', `translate(${this.center.x},${this.center.y})`)
.attr('r', this.radius - this.thickness - 3)
.attr('class', 'circle-center');*/
//Title in Ring
circle
.append('text')
.attr('text-anchor', 'middle')
.attr('x', this.center.x)
.attr('y', this.center.y - 15)
.attr('class', 'circle-label')
.text(this.dataset.title.toUpperCase());
// Total Value
circle
.append('text')
.attr('text-anchor', 'middle')
.attr('x', this.center.x)
.attr('y', this.center.y + 15)
.attr('class', 'circle-value')
.text(() => {
let string = this.formatThousands(this.total, 'de');
return this.dataset.title == 'Revenue' ? (string += '€') : string;
});
}
drawItemsText() {
const rectangle = this.svgViewport.append('g').attr('class', 'rect');
rectangle
.append('rect')
.attr('x', 0)
.attr('y', 260)
.attr('width', '320')
.attr('height', '120')
.attr('fill', 'none')
.attr('class', 'circle-title');
for(let x=0 ; x<this.dataset.items.length ; x++){
rectangle
.append('text')
.attr('text-anchor',(x % 2 === 0) ? 'start': 'end')
.attr('x', (x % 2 === 0) ? 0 : this.maxWidth)
.attr('y', (275 + (parseInt(x/2))*this.nextLine))
.attr('class', 'details-label')
.attr('fill', this.dataset.items[x].color)
.text(this.capitalizeFirstLetter(this.dataset.items[x].name));
rectangle
.append('text')
.attr('text-anchor', (x % 2 === 0) ? 'start' : 'end')
.attr('x', (x % 2 === 0) ? 0 : 200 )
.attr('y', 305 + (parseInt(x/2)*this.nextLine))
.attr('class', 'details-percent')
.text(this.percent(this.dataset.items[x].value).toFixed(0) + '%');
rectangle
.append('text')
.attr('text-anchor',(x % 2 === 0) ? 'start' : 'end')
.attr('x', (x % 2 === 0) ? 40 : this.maxWidth )
.attr('y', 305 + (parseInt(x/2)*this.nextLine))
.attr('class', 'details-value')
.text(() => {
let string = this.formatThousands(this.dataset.items[x].value);
return this.dataset.title == 'Revenue' ? (string += '€') : string;
});
}
}
fetchData() {
d3.json(this.endpoint)
.then(data => this.setData(data))
}
setData(data) {
this.dataset = data;
this.init();
}
getData() {
return this.dataset;
}
redraw() {
this.init();
}
percent(value) {
if (typeof value == undefined) return;
return (value / this.total) * 100;
}
formatThousands(value, lang) {
if (typeof value == undefined) return;
return value.toLocaleString(lang);
}
capitalizeFirstLetter(value) {
if (typeof value == undefined) return;
let firstLetter = value[0] || value.charAt(0);
return firstLetter ? firstLetter.toUpperCase() + value.slice(1) : '';
}
} |
JavaScript | class CroquisTool {
constructor(mapContext) {
this.mapContext = mapContext;
this.uiElement;
}
getInteraction() {
return this.interaction;
}
setInteraction(interaction) {
this.interaction = interaction;
}
activate() {
if (!this.interaction.getActive()) {
this.interaction.setActive(true);
}
this.mapContext.setInteraction(this.interaction);
}
askForObservation(croquisObject) {
if(configuration.ask4Observation()){
let modal = ModalDialogFactory.buildInputTextModalDialog('Escriba una observación para el elemento');
modal.show();
modal.setOnAcceptAction(() => {
let inputValue = modal.getInputValue();
croquisObject.setObservation(inputValue);
modal.hide();
});
}
}
setUIElement(uiElement) {
this.uiElement = uiElement;
}
showUIElment(obj) {
if (this.uiElement) {
this.uiElement.setData(obj);
this.uiElement.show();
}
}
hideUIElement() {
if (this.uiElement) {
this.uiElement.hide();
}
}
} |
JavaScript | class DimensionsFootprintModel extends PerformanceModel {
constructor(owner, cfg) {
super(owner, cfg);
this.dimensionsEntities = {}; // Maps dimensions to the Entities that represent them in this DimensionsFootprintModel
}
/**
* Creates dimensions for the given axis-aligned bounding box.
*
* @param {String|Number} cfg.id ID for the new dimensions.
* @param {Number[]} cfg.aabb Axis-aligned bounding box to create the dimensions from.
*/
createDimensions(cfg) {
this._createAABBDimensions(cfg.id, cfg.aabb);
}
_createAABBDimensions(id, aabb) {
const lineColor = [0, 0, 0];
const labelColor = [0, 0, 0];
const Z_POS = aabb[1] ;
let offset = 3;
let offset2 = 0.5
let arrowLength = 0.4;
let arrowWidth = 0.15;
let textSize = 0.2;
const dimensionsEntityId = id + "." + "dimensions";
const meshIds = [];
for (let i = 0; i < 4; i++) {
const axisLineMeshId = id + "." + "axisLineMesh." + i;
const axisLabelMeshId = id + "." + "axisLabelMesh." + i;
switch (i) {
case 0:
this.createMesh({
id: axisLineMeshId,
primitive: "lines",
positions: [
aabb[0], Z_POS, aabb[2] - offset, // Line
aabb[3], Z_POS, aabb[2] - offset,
aabb[0] + arrowLength, Z_POS, aabb[2] - arrowWidth - offset, // Arrow heads
aabb[0] + arrowLength, Z_POS, aabb[2] + arrowWidth - offset,
aabb[3] - arrowLength, Z_POS, aabb[2] - arrowWidth - offset,
aabb[3] - arrowLength, Z_POS, aabb[2] + arrowWidth - offset,
aabb[0], Z_POS, (aabb[2] + aabb[5]) * .5, // Limit extents
aabb[0], Z_POS, aabb[2] - offset - offset2,
aabb[3], Z_POS, (aabb[2] + aabb[5]) * .5,
aabb[3], Z_POS, aabb[2] - offset - offset2
],
indices: [0, 1, 0, 2, 0, 3, 1, 4, 1, 5, 6, 7, 8, 9],
color: lineColor
});
this.createMesh(utils.apply(buildVectorTextGeometry({
text: "123.0 mm",
size: textSize
}), {
id: axisLabelMeshId,
position: [(aabb[0] + aabb[3]) * 0.5, Z_POS, aabb[0] - offset - 0.5],
rotation: [-90, 0, 180],
color: labelColor
}));
break;
case 1:
this.createMesh({
id: axisLineMeshId,
primitive: "lines",
positions: [
aabb[0] - offset, Z_POS, aabb[2],
aabb[0] - offset, Z_POS, aabb[5],
aabb[0] + 0.5 - offset, Z_POS, aabb[2] + 0.5,
aabb[0] - 0.5 - offset, Z_POS, aabb[2] + 0.5,
aabb[0] + 0.5 - offset, Z_POS, aabb[5] - 0.5,
aabb[0] - 0.5 - offset, Z_POS, aabb[5] - 0.5,
aabb[0] - offset - offset2, Z_POS, aabb[2],
(aabb[0] + aabb[3]) * 0.5, Z_POS, aabb[2],
aabb[0] - offset - offset2, Z_POS, aabb[5],
(aabb[0] + aabb[3]) * 0.5, Z_POS, aabb[5]
],
indices: [0, 1, 0, 2, 0, 3, 1, 4, 1, 5, 6, 7, 8, 9],
color: lineColor
});
this.createMesh(utils.apply(buildVectorTextGeometry({
text: "123.0 mm",
size: textSize
}), {
id: axisLabelMeshId,
position: [aabb[0] - offset - 0.5, Z_POS, (aabb[2] + aabb[5]) * 0.5],
rotation: [90, 180, 90],
color: labelColor
}));
break;
case 2:
this.createMesh({
id: axisLineMeshId,
primitive: "lines",
positions: [
aabb[0], Z_POS, aabb[5] + offset,
aabb[3], Z_POS, aabb[5] + offset,
aabb[0] + 0.5, Z_POS, aabb[5] - 0.5 + offset,
aabb[0] + 0.5, Z_POS, aabb[5] + 0.5 + offset,
aabb[3] - 0.5, Z_POS, aabb[5] - 0.5 + offset,
aabb[3] - 0.5, Z_POS, aabb[5] + 0.5 + offset,
aabb[0], Z_POS, (aabb[2] + aabb[5]) * .5,
aabb[0], Z_POS, aabb[5] + offset + offset2,
aabb[3], Z_POS, (aabb[2] + aabb[5]) * .5,
aabb[3], Z_POS, aabb[5] + offset + offset2
],
indices: [0, 1, 0, 2, 0, 3, 1, 4, 1, 5, 6, 7, 8, 9],
color: lineColor
});
this.createMesh(utils.apply(buildVectorTextGeometry({
text: "123.0 mm",
size: textSize
}), {
id: axisLabelMeshId,
position: [(aabb[0] + aabb[3]) * 0.5, Z_POS, aabb[5] + offset + 0.5],
rotation: [90, 180, 180],
color: labelColor
}));
break;
case 3:
this.createMesh({
id: axisLineMeshId,
primitive: "lines",
positions: [
aabb[3] + offset, Z_POS, aabb[2],
aabb[3] + offset, Z_POS, aabb[5],
aabb[3] + 0.5 + offset, Z_POS, aabb[2] + 0.5,
aabb[3] - 0.5 + offset, Z_POS, aabb[2] + 0.5,
aabb[3] + 0.5 + offset, Z_POS, aabb[5] - 0.5,
aabb[3] - 0.5 + offset, Z_POS, aabb[5] - 0.5,
aabb[3] + offset + offset2, Z_POS, aabb[2],
(aabb[0] + aabb[3]) * 0.5, Z_POS, aabb[2],
aabb[3] + offset + offset2, Z_POS, aabb[5],
(aabb[0] + aabb[3]) * 0.5, Z_POS, aabb[5]
],
indices: [0, 1, 0, 2, 0, 3, 1, 4, 1, 5, 6, 7, 8, 9],
color: lineColor
});
this.createMesh(utils.apply(buildVectorTextGeometry({
text: "123.0 mm",
size: textSize
}), {
id: axisLabelMeshId,
position: [aabb[3] + offset + 0.5, Z_POS, (aabb[2] + aabb[5]) * 0.5],
rotation: [90, 180, -90],
color: labelColor
}));
break;
}
meshIds.push(axisLineMeshId);
meshIds.push(axisLabelMeshId);
}
const dimensionsEntity = this.createEntity({
id: dimensionsEntityId,
meshIds: meshIds
});
this.dimensionsEntities[id] = dimensionsEntity;
return dimensionsEntity;
}
/**
* Shows or hides the dimensions with the given ID.
*
* The ID should correspond to dimensions that were created earlier with {@link createDimensions}.
*
* @param {String|Number} id ID of the target dimensions.
* @param {Boolean} visible Whether to show or hide the target dimensions.
*/
setDimensionsVisible(id, visible) {
const entity = this.dimensionsEntities[id];
if (!entity) {
return;
}
entity.visible = visible;
}
} |
JavaScript | class Log {
/*
constructor(fn) {
this.fn = fn
this.trace = chalk.bgBlue.black
this.success = chalk.bgGreen.black
this.failure = chalk.bgRed.black
}
trace(msg, obj) {
sails.log(this.trace(`${this.fn}: ${msg}`, obj))
}
success(msg, obj) {
sails.log(this.success(`${this.fn}: ${msg} success! :)`, obj))
}
failure(msg, obj) {
sails.log(this.failure(`${this.fn}: ${msg} failure :(`, obj))
}
criticalFailure(msg) {
sails.log.error(this.failure(`${this.fn}: ${msg} failure :*(`, obj))
}
*/
} |
JavaScript | class Validate {
constructor(obj) {
this.obj = obj
}
/**
* check if object has keys. throw error if it does not.
* @param {object} obj - object to validate
* @param {object[]} keys - keys to check for
* @return {Boolean} return error if keys are not validated
*/
hasKeys(keys, obj) {
obj = obj || this.obj
if (!obj || is.empty(obj)) return new Error('object does not exist or is empty')
// return if no keys to check and obj exists
if (!keys && obj && is.not.empty(obj)) return true
for (const key of keys) {
if (!_.has(obj[key])) {
return new Error(obj.toString() + ' does not have key: ' + key)
}
}
return true
}
/**
* test if array === [String, String]
* @param {object[]} obj - array to test
* @return {Boolean} true if double string array
*/
isDoubleStringArray(obj) {
const array = obj || this.obj
return (
is.array(array)
&& array.length === 2
&& is.string(array[0])
&& is.string(array[1])
)
}
/**
* test if array === [Number, Number]
* @param {object[]} obj - array to test
* @return {Boolean} true if double number array
*/
isDoubleNumberArray(obj) {
const array = obj || this.obj
return (
is.array(array)
&& array.length === 2
&& is.number(array[0])
&& is.number(array[1])
)
}
/** validate if obj is geoPoint with coordinates as double string array (useful for Postman testing) */
/*
isStringGeoPoint(obj) {
const array = obj || this.obj
if (_.has(array, 'coordinates') && this.isDoubleStringArray(array.coordinates)) {
return true
} else {
return false
}
}
*/
/** validate if obj is geoFeature with coordinates as double string array (useful for Postman testing) */
/*
isStringGeoFeature(obj) {
const array = obj || this.obj
if (_.has(array, 'geometry.coordinates') && this.isDoubleStringArray(array.geometry.coordinates)) {
return true
} else {
return false
}
}
*/
/**
* test to see if a key value pair is present in a [potentially] nested object
* @param {object} obj [nested object]
* @param {object} key [nested object representing the unique key]
* @param {value} val [any value to test for]
* @example
* // here is the nested object to do the find on
{
"level1": {
"level2": {
"level2a": "nesting",
"level2b": "nesting again",
"level3": {
"level4": {
"level5": "value"
}
}
}
}
}
// you can pass this and it will return "value"
{
"level4": {
"level5": "value"
}
}
// you can pass this and it will return null
{
"level4": {
"level5": "not the right value"
}
}
// you can pass this and it will return null
{
"level4": {
"notRightKey": "value"
}
}
* @return {Boolean} [whether the key-value pair exists]
*/
hasKeyValuePair(findObj) {
// flatten nested object and key
const flatObj = flatten(this.obj)
const flatFindObj = flatten(findObj)
// create array of keys
const objKeys = Object.keys(flatObj)
const findObjKeys = Object.keys(flatFindObj)
// find where key is in nested obj
const keyTree = _.find(objKeys, nestedKey => {
// return the nestedKey string that includes key
return (_s.include(nestedKey, findObjKeys))
})
// return if no keyTree found
if (!keyTree || is.empty(keyTree)) return false
// find the value of the key
const keyVal = _.get(this.obj, keyTree)
const findVal = _.get(findObj, findObjKeys[0])
// return true if values are equal
return (keyVal === findVal)
}
} |
JavaScript | class Retrieve {
constructor(obj) {
this.obj = obj
}
/**
* find the value of a key in an object within an array
* @param {string} key [key of object to search for]
* @param {value} val [value in key to search for]
* @return {object} [object that has a matching value in key of array]
*
* @example
let obj = {
"long_name": "48",
"short_name": "48",
"types": [
"street_number"
]
}
retrieve.objWithValueInArrayAtKey(obj, 'types', 'street_number') // returns obj
*/
objIfValueIsWithinArrayAtKey(obj, key, val) {
obj = obj || this.obj
// return obj if obj.key has val in it
if (_.includes(obj[key], val)) {
return obj
}
} // valueInArray
/**
* find the value of a key in an object within an array
* @param {string} key [key of object to search for]
* @param {value} val [value in key to search for]
* @return {object} [object that has a matching value in key of array]
*
* @example
let array = [
{
"long_name": "48",
"short_name": "48",
"types": [
"street_number"
]
},
{
"long_name": "Los Angeles",
"short_name": "LA",
"types": [
"city"
]
}
]
retrieve.objWithValueInArrayAtKeyInArray(array, 'types', 'street_number') // returns [array[0]]
*/
objectsWithValueInArrayAtKeyInArray(array, key, val) {
array = array || this.obj
if (is.not.array(array)) return
let matchingObjects = []
let matchingObject
// find the obj if value is within array at key for each obj in passed array
for (const obj of array) {
matchingObject = this.objIfValueIsWithinArrayAtKey(obj, key, val)
// push to matchingObjects array if found
if (matchingObject) {
matchingObjects.push(matchingObject)
}
}
return matchingObjects
}
/**
* returns value at key if the key exists
* @param {string} key [string representation of nested keys]
* @return {value} [value at key]
*/
// TODO: deprecate this and only use _.get
valueAtKey(key) {
if (!_.has(this.object, key)) {
return
} else {
return _.get(this.object, key)
} // if
} // ofValue
} // class |
JavaScript | class VarsField extends React.Component{
render(){
const screen_size = document.documentElement.clientWidth
const xs = screen_size < 576 ? true : false
const {fieldName, fieldLabel, handleBlur, handleChange, append, touched, errors, values, popover}
= this.props;
return(
<Col xs={10} sm={7} md={4} lg={3} xl={3} className="text-center"> {/*here I choose field size*/}
<Form.Group controlId={"form"+ fieldName}>
<Form.Label>{fieldLabel}</Form.Label>
<InputGroup>
<Form.Control size={xs? "lg" : ""} className="text-center" type="number" name={fieldName}
onChange={handleChange} onBlur={handleBlur}
isInvalid={!!errors[fieldName] && touched[fieldName]}
isValid = {!errors[fieldName] && touched[fieldName]}
value={values[fieldName]}
/>
{append &&
<InputGroup.Append>
<InputGroup.Text id={"inputAppend"+fieldName}>{append}</InputGroup.Text>
</InputGroup.Append>
}
<OverlayTrigger trigger="focus" overlay={
<Popover id={"popover"+fieldName}>{popover}</Popover>
}>
<Button variant="secondary" style={xs? {width:'48px', fontSize:'1.4em'}:{}}><i>i</i></Button>
</OverlayTrigger>
<Form.Control.Feedback type="invalid">
{errors[fieldName]}
</Form.Control.Feedback>
</InputGroup>
</Form.Group>
</Col>
)
}
} |
JavaScript | class WalletService extends EventEmitter {
constructor({ providers, unlockAddress } = configure()) {
super()
this.unlockContractAddress = unlockAddress
this.providers = providers
this.ready = false
this.providerName = null
this.web3 = null
this.on('ready', () => {
this.ready = true
})
}
/**
* Expooses gas amount constants to be utilzed when sending relevant transactions
* for the platform.
*/
static gasAmountConstants() {
return {
createLock: 3000000,
updateKeyPrice: 1000000,
purchaseKey: 1000000,
withdrawFromLock: 1000000,
partialWithdrawFromLock: 1000000,
}
}
/**
* This connects to the web3 service and listens to new blocks
* @param {string} providerName
* @return
*/
async connect(providerName) {
if (providerName && providerName === this.providerName) {
// If the provider is set and did not really change, no need to reset it
return
}
// Keep track of the provider
this.providerName = providerName
// And reset the connection
this.ready = false
const provider = this.providers[providerName]
// We fail: it appears that we are trying to connect but do not have a provider available...
if (!provider) {
return this.emit('error', new Error(FATAL_MISSING_PROVIDER))
}
try {
if (provider.enable) {
// this exists for metamask and other modern dapp wallets and must be called,
// see: https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8
await provider.enable()
}
} catch (error) {
return this.emit('error', new Error(FATAL_NOT_ENABLED_IN_PROVIDER))
}
this.web3 = new Web3(provider)
const networkId = await this.web3.eth.net.getId()
if (this.networkId !== networkId) {
this.networkId = networkId
this.emit('network.changed', networkId)
}
}
/**
* Checks if the contract has been deployed at the address.
* Invokes the callback with the result.
* Addresses which do not have a contract attached will return 0x
*/
async isUnlockContractDeployed(callback) {
let opCode = '0x' // Default
try {
opCode = await this.web3.eth.getCode(this.unlockContractAddress)
} catch (error) {
return callback(error)
}
return callback(null, opCode !== '0x')
}
/**
* Function which yields the address of the account on the provider or creates a key pair.
*/
async getAccount(createIfNone = false) {
const accounts = await this.web3.eth.getAccounts()
let address
if (!accounts.length && !createIfNone) {
// We do not have an account and were not asked to create one!
// Not sure how that could happen?
return (this.ready = false)
}
if (accounts.length) {
address = accounts[0] // We have an account.
} else if (createIfNone) {
let newAccount = await this.web3.eth.accounts.create()
address = newAccount.address
}
this.emit('account.changed', address)
this.emit('ready')
return Promise.resolve(address)
}
/**
* This function submits a web3Transaction and will trigger an event as soon as it receives its
* hash. We then use the web3Service to handle the ongoing transaction (watch for conformation
* receipt... etc)
* @private
*/
_sendTransaction({ to, from, data, value, gas }, transactionType, callback) {
const web3TransactionPromise = this.web3.eth.sendTransaction({
to,
from,
value,
data,
gas,
})
this.emit('transaction.pending', transactionType)
return web3TransactionPromise
.once('transactionHash', hash => {
callback(null, hash)
// TODO: consider an object instead of all the fields independently.
this.emit(
'transaction.new',
hash,
from,
to,
data,
transactionType,
'submitted'
)
})
.on('error', error => {
callback(error)
})
}
/**
*
* @param {PropTypes.address} lock : address of the lock for which we update the price
* @param {PropTypes.address} account: account who owns the lock
* @param {string} price : new price for the lock
*/
updateKeyPrice(lock, account, price) {
const lockContract = new this.web3.eth.Contract(PublicLock.abi, lock)
const data = lockContract.methods
.updateKeyPrice(Web3Utils.toWei(price, 'ether'))
.encodeABI()
return this._sendTransaction(
{
to: lock,
from: account,
data,
gas: WalletService.gasAmountConstants().updateKeyPrice,
contract: PublicLock,
},
TransactionType.UPDATE_KEY_PRICE,
error => {
if (error) {
return this.emit('error', new Error(FAILED_TO_UPDATE_KEY_PRICE))
}
}
)
}
/**
* Creates a lock on behalf of the user.
* @param {PropTypes.lock} lock
* @param {PropTypes.address} owner
*/
createLock(lock, owner) {
const unlock = new this.web3.eth.Contract(
Unlock.abi,
this.unlockContractAddress
)
const data = unlock.methods
.createLock(
lock.expirationDuration,
Web3Utils.toWei(lock.keyPrice, 'ether'),
lock.maxNumberOfKeys
)
.encodeABI()
return this._sendTransaction(
{
to: this.unlockContractAddress,
from: owner,
data,
gas: WalletService.gasAmountConstants().createLock,
contract: Unlock,
},
TransactionType.LOCK_CREATION,
(error, hash) => {
if (error) {
return this.emit('error', new Error(FAILED_TO_CREATE_LOCK))
}
// Let's update the lock to reflect that it is linked to this
// This is an exception because, until we are able to determine the lock address
// before the transaction is mined, we need to link the lock and transaction.
return this.emit('lock.updated', lock.address, {
expirationDuration: lock.expirationDuration,
keyPrice: lock.keyPrice, // Must be expressed in Eth!
maxNumberOfKeys: lock.maxNumberOfKeys,
owner: owner,
outstandingKeys: 0,
balance: '0',
transaction: hash,
})
}
)
}
/**
* Purchase a key to a lock by account.
* The key object is passed so we can kepe track of it from the application
* The lock object is required to get the price data
* We pass both the owner and the account because at some point, these may be different (someone
* purchases a key for someone else)
* @param {PropTypes.address} lock
* @param {PropTypes.address} owner
* @param {string} keyPrice
* @param {string} data
* @param {string} account
\ */
purchaseKey(lock, owner, keyPrice, account, data = '') {
const lockContract = new this.web3.eth.Contract(PublicLock.abi, lock)
const abi = lockContract.methods
.purchaseFor(owner, Web3Utils.utf8ToHex(data || ''))
.encodeABI()
return this._sendTransaction(
{
to: lock,
from: account,
data: abi,
gas: WalletService.gasAmountConstants().purchaseKey,
value: Web3Utils.toWei(keyPrice, 'ether'),
contract: PublicLock,
},
TransactionType.KEY_PURCHASE,
error => {
if (error) {
return this.emit('error', new Error(FAILED_TO_PURCHASE_KEY))
}
}
)
}
/**
* Triggers a transaction to withdraw some funds from the lock and assign them
* to the owner.
* @param {PropTypes.address} lock
* @param {PropTypes.address} account
* @param {string} ethAmount
* @param {Function} callback
*/
partialWithdrawFromLock(lock, account, ethAmount, callback) {
const lockContract = new this.web3.eth.Contract(PublicLock.abi, lock)
const weiAmount = Web3Utils.toWei(ethAmount)
const data = lockContract.methods.partialWithdraw(weiAmount).encodeABI()
return this._sendTransaction(
{
to: lock,
from: account,
data,
gas: WalletService.gasAmountConstants().partialWithdrawFromLock,
contract: PublicLock,
},
TransactionType.WITHDRAWAL,
error => {
if (error) {
this.emit('error', new Error(FAILED_TO_WITHDRAW_FROM_LOCK))
return callback(error)
}
return callback()
}
)
}
/**
* Triggers a transaction to withdraw funds from the lock and assign them to the owner.
* @param {PropTypes.address} lock
* @param {PropTypes.address} account
* @param {Function} callback TODO: implement...
*/
withdrawFromLock(lock, account) {
const lockContract = new this.web3.eth.Contract(PublicLock.abi, lock)
const data = lockContract.methods.withdraw().encodeABI()
return this._sendTransaction(
{
to: lock,
from: account,
data,
gas: WalletService.gasAmountConstants().withdrawFromLock,
contract: PublicLock,
},
TransactionType.WITHDRAWAL,
error => {
if (error) {
return this.emit('error', new Error(FAILED_TO_WITHDRAW_FROM_LOCK))
}
}
)
}
/**
* Signs data for the given account.
* We favor web3.eth.personal.sign which provides a better UI but is not implemented
* everywhere. If it's failing we use web3.eth.sign
*
* @param {*} account
* @param {*} data
* @param {*} callback
*/
signData(account, data, callback) {
let method
if (this.web3.currentProvider.isMetaMask) {
method = 'eth_signTypedData_v3'
data = JSON.stringify(data)
} else {
method = 'eth_signTypedData'
}
return this.web3.currentProvider.send(
{
method: method,
params: [account, data],
from: account,
},
(err, result) => {
// network failure
if (err) {
return callback(err, null)
}
// signature failure on the node
if (result.error) {
return callback(result.error, null)
}
callback(null, Buffer.from(result.result).toString('base64'))
}
)
}
} |
JavaScript | class BasicUserContentBody extends React.PureComponent {
constructor(props){
super(props);
this.state = { 'hasError' : false, 'errorInfo' : null };
}
componentDidCatch(err, info){
this.setState({ 'hasError' : true, 'errorInfo' : info }, ()=>{
var href = this.props.href;
if (!href){
var storeState = store && store.getState();
href = storeState && storeState.href;
}
logger.error('Client Error - ' + href + ': ' + err);
});
}
/** Determines the item type from the context. */
itemType(){
var { context, itemType } = this.props;
if (itemType && typeof itemType === 'string') return itemType;
if (!Array.isArray(context['@type'])) throw new Error('Expected an @type on context.');
if (context['@type'].indexOf('StaticSection') > -1){
return 'StaticSection';
} else if (isHiglassViewConfigItem(context)){ // Func internally checks context['@type'].indexOf('HiglassViewConfig') > -1 also
return 'HiglassViewConfig';
} else if (isMicroscopeConfigurationItem(context)){ // Func internally checks context['@type'].indexOf('MicroscopeConfiguration') > -1 also
return 'MicroscopeConfiguration';
} else {
// TODO: Case for JupyterNotebook (?) and/or yet-to-be-created ones.
throw new Error('Unsupported Item type.');
}
}
render(){
const { context, markdownCompilerOptions, parentComponentType, windowWidth } = this.props;
const { hasError } = this.state;
const { content, filetype } = context || {};
if (hasError){
return (
<div className="error">
<h4>Error parsing content.</h4>
</div>
);
}
var itemType = this.itemType();
if (itemType === 'StaticSection' || itemType === 'CustomSection') {
return <BasicStaticSectionBody {...{ content, filetype, markdownCompilerOptions, windowWidth, placeholderReplacementFxn }} />;
} else if (itemType === 'HiglassViewConfig') {
return (
<React.Fragment>
<EmbeddedHiglassActions context={context} parentComponentType={parentComponentType || BasicUserContentBody} />
<HiGlassAjaxLoadContainer {..._.omit(this.props, 'context', 'higlassItem')} higlassItem={context} scale1dTopTrack={false} />
</React.Fragment>
);
} else if (itemType === 'MicroscopeConfiguration') {
return (
<React.Fragment>
<MicroMetaAjaxLoadContainer {..._.omit(this.props, 'context', 'microscopeItem')} microscopeItem={context} height={800} />
</React.Fragment>
);
} else {
// TODO handle @type=JupyterHub?
return (
<div className="error">
<h4>Error determining Item type.</h4>
</div>
);
}
}
} |
JavaScript | class H2TableColumn extends mixinBehaviors([Templatizer], PolymerElement) {
static get template() {
return null;
}
static get properties() {
return {
prop: {
type: String
},
props: String,
separator: String,
label: {
type: String
},
width: {
type: Number
},
fixed: {
type: String,
},
type: {
type: String,
value: 'view'
},
tmpl: Object,
modelAs: {
type: String,
value: 'item'
},
sortable: {
type: Boolean,
value: false
},
filterable: {
type: Boolean,
value: false
},
sortType: {
type: String,
value: 'string'
},
sortEnum: Array,
frozen: {
type: Boolean,
value: false
},
formatter: Function,
cellStyle: String,
defaultValue: String,
filterEnum: Array
};
}
static get is() {
return "h2-table-column";
}
constructor() {
super();
this.tmpl = this._findTemplate().pop();
if (this.tmpl) {
// hack for template.__dataHost
this.tmpl.__dataHost = this.parentElement;
this._parentModel = {};
this.templatize(this.tmpl);
}
}
_findTemplate() {
return FlattenedNodesObserver.getFlattenedNodes(this)
.filter(node => node.localName === 'template');
}
stampTemplate(instanceProps, key = this.modelAs) {
if(this.tmpl) return this.stamp({[key]: instanceProps, "global": this.tmpl.__dataHost.global});
return null;
}
} |
JavaScript | class DepthCalculator {
calculateDepth(arr) {
if (!arr || !Array.isArray(arr)) return 0;
let deep = 1;
for (let i = 0; i < arr.length; i++) {
let currentDeep = this.calculateDepth(arr[i]) + 1;
if (currentDeep > deep) {
deep = currentDeep;
}
}
return deep;
// function goDeeper(item, deeper = 1) {
// let currentDeep = deeper;
// for (let i = 0; i < item.length; i++) {
// if (Array.isArray(item[i])) {
// goDeeper(item[i], currentDeep + 1);
// }
// }
// if (currentDeep > deep) {
// deep = currentDeep;
// }
// return currentDeep;
// }
// goDeeper(arr);;
// return deep;
}
} |
JavaScript | class busTime {
constructor() {
this.times = null;
this.days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
//Different ways the blue bus site says "Leave Bryn Mawr" or "Leave Haverford"
this.sources = {
Brynmawr : new Set(["Leaves BMC", "Leave Bryn Mawr", "Bryn Mawr to Haverford"]),
Haverford : new Set(["Leave Haverford", "Haverford to Bryn Mawr", "Leaves Stokes"])
};
this.busUrl = "http://www.brynmawr.edu/transportation/bico.shtml";
}
//Figures out if the time is for Leaving Haverford or Bryn Mawr by comparing to the two
//sets above
getSource(source) {
var trimmedSource = source.replace(/\s+/g, " ").trim();
for (var valid_source in this.sources) {
if (this.sources[valid_source].has(trimmedSource) ) {
return valid_source;
}
}
return null;
}
//Returns a dictionary that maps to two arrays full of times the blue bus leaves each school
getTimes() {
//Turns html tables into arrays
// Adapted from https://gist.github.com/WickyNilliams/9252235
function arrayify(htmlTable) {
return Array.prototype.slice.call(htmlTable);
}
//Figures out what is in the heading of a table
function parseThInTable(table){
var ths = arrayify(table.getElementsByTagName("th"));
return ths;
}
//parses data cell in a table
function parseTdInTable(table) {
var tds = arrayify(table.getElementsByTagName("td"));
return tds;
}
//Parses a row in a table and splits it up into data or header cells that can be parsed
//by the above functions
function parseTrInTable(table) {
// Parses one table objecet
var rows = arrayify(table.getElementsByTagName("tr"));
var finalResult = [];
var ths = rows.slice(0,2).map(parseThInTable);
var tds = rows.slice(2,rows.length).map(parseTdInTable);
finalResult.push(ths);
finalResult.push(tds);
return finalResult;
}
//The actual scraping of the page
function scrapePage(text) {
var parser = new DOMParser();
var parsedHTML = parser.parseFromString(text, "text/html");
var tables = arrayify(parsedHTML.body.getElementsByTagName("table"));
var parsed = tables.map(parseTrInTable);
var timeDictionary = {};
var HaverfordTimes = [];
var BrynMawrTimes = [];
for (var dayOfWeek in parsed){
var HaverfordColumn;
var BrynMawrColumn;
for(var column in parsed[dayOfWeek][0][1]) {
var source = this.getSource(parsed[dayOfWeek][0][1][column].innerText);
if(source == "Haverford"){
HaverfordColumn = column;
}
else if(source == "Brynmawr"){
BrynMawrColumn = column;
}
}
var dayTimes = parsed[dayOfWeek][1];
for (var row in dayTimes){
var HaverfordTime = dayTimes[row][HaverfordColumn].innerText.match((/([0-9]|[0-9][0-9]):[0-9][0-9]/g));
var BrynMawrTime = dayTimes[row][BrynMawrColumn].innerText.match((/([0-9]|[0-9][0-9]):[0-9][0-9]/g));
HaverfordTime.forEach(function(time) {
HaverfordTimes.push(time);
});
BrynMawrTime.forEach(function(time) {
BrynMawrTimes.push(time);
});
}
}
timeDictionary["Haverford"] = HaverfordTimes;
timeDictionary["BrynMawr"] = BrynMawrTimes;
return timeDictionary;
};
return new Promise(function(fulfill, reject) {
try {
$.get(this.busUrl, function(response) {
//fulfill(response);
// see https://stackoverflow.com/questions/10585029/parse-a-html-string-with-js
// for parsing info
// Look at https://gist.github.com/WickyNilliams/9252235
var scraped = scrapePage.call(this, response);
fulfill(scraped);
}.bind(this));
}
catch (e) {
reject(e);
}
}.bind(this));
}
} |
JavaScript | class StateCharacter extends Character { // eslint-disable-line no-unused-vars
/**
* State character constructor
* @constructor
* @param {number} x x position
* @param {number} y y position
* @param {number} width object width
* @param {number} height object height
* @param {number} imageID image ID for rendering (if has not, -1)
*/
constructor(x, y, width, height, imageID = -1) {
super(x, y, width, height, imageID);
/**
* State of character
* @protected
* @type {State}
*/
this.state = null;
}
/**
* Update object
* @override
* @param {number} dt - delta time
*/
update(dt) {
// update AI
for (let it of this.ai) {
it.update(dt);
}
// apply AI
for (let it of this.ai) {
if (it.apply(dt)) {
this.state = it instanceof StateAI ? it.getState() : null;
break;
}
}
}
/**
* Render entity
* @override
* @param {Context} ctx Canvas context
* @param {number} [shiftX = 0] Shift x position
* @param {number} [shiftY = 0] Shift y position
*/
render(ctx, shiftX = 0, shiftY = 0) {
if (this.state != null) {
this.state.render(ctx, shiftX, shiftY);
// For debug to render collider
if (Engine.debug && this.collider !== undefined) {
this.collider.render(ctx, shiftX, shiftY);
}
} else {
super.render(ctx, shiftX, shiftY);
}
}
} |
JavaScript | class HtmlExport extends UtilityClass {
/**
* Converts the snapshot of given revision number to html.
*
* @param {string} documentId The id for the document in question.
* @param {BodySnapshot} bodySnapshot The snapshot to convert
* to html.
*/
static async exportHtml(documentId, bodySnapshot) {
use.HtmlExport.exportHtml(bodySnapshot, documentId);
}
} |
JavaScript | class PortalLauncher extends HTMLElement {
/**
* Store the tag name to make it easier to obtain directly.
* @notice function name must be here for tooling to operate correctly
*/
static get tag() {
return "portal-launcher";
}
/**
* life cycle
*/
constructor(delayRender = false) {
super();
// set tag for later use
this.tag = PortalLauncher.tag;
// ensure there's at least 1 link in here somewhere...
if (this.querySelectorAll("a")) {
this.querySelectorAll("a").forEach(a => {
a.addEventListener("click", this.click.bind(this));
});
}
}
/**
* Basic feature detecting event handler
*/
click(e) {
let target = e.target;
// support walking the path in order to find the link clicked
if (target.tagName !== "A") {
e.path.forEach(item => {
if (item.tagName === "A") {
target = item;
}
});
}
if (target && target.getAttribute("href") != null) {
// progressive enhancement, if this class exists, can the link click
if ("HTMLPortalElement" in window) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
// Adding some styles with transitions
const style = document.createElement("style");
const initialScale = 0.2;
style.innerHTML = `
portal {
position:fixed;
width: 100%;
height: 100%;
opacity: 0;
box-shadow: 0 0 20px 10px #999;
transform: scale(${initialScale});
bottom: calc(20px + 50% * ${initialScale} - 50%);
right: calc(20px + 50% * ${initialScale} - 50%);
z-index: 10000;
}
.portal-transition {
transition:
transform 0.4s,
bottom 0.7s,
left 0.7s,
opacity 1.0s;
}
@media (prefers-reduced-motion: reduce) {
.portal-transition {
transition: all 0.001s;
}
}
.portal-reveal {
transform: scale(1.0);
bottom: 0px;
left: 0px;
}
.fade-in {
opacity: 1.0;
}
`;
const portal = document.createElement("portal");
// Let's navigate into the WICG Portals spec page
portal.src = target.getAttribute("href");
// Add a class that defines the transition. Consider using
// `prefers-reduced-motion` media query to control the animation.
// https://developers.google.com/web/updates/2019/03/prefers-reduced-motion
portal.classList.add("portal-transition");
portal.addEventListener("transitionend", evt => {
if (evt.propertyName == "bottom") {
// Activate the portal once the transition has completed
portal.activate();
}
});
document.body.append(style, portal);
// Waiting for the page to load.
// using setTimeout is a suboptimal way and it's best to fade-in
// when receiving a load complete message from the portal via postMessage
setTimeout(_ => portal.classList.add("fade-in"), 250);
setTimeout(_ => portal.classList.add("portal-reveal"), 500);
}
}
}
} |
JavaScript | class App extends React.Component {
//n,e are from the public key generated by the server for us to encrypt
constructor() {
super();
this.state = {
plainText: "",
summarizedText: "",
serverKey: {
n: 0.0,
e: 0.0
},
clientKey: {
n: 0.0,
d: 0.0,
e: 0.0
},
}
};
//RSA stuff
//As react native does not support BigInteger class we need to encode substrings of a size such that when it
//exponeniates in the m^e%n it doesn't overflow and we lose data.
//converting to uppercase so as to maintain consistency of ASCII lengths, as a is 97 and c is 100
//also because numbers and other symbols are also of width : 2
rsa_encode = () => {
//split the input into word tokens
var words = this.state.plainText.toUpperCase().split(' ');
var cipherText = ""
const SubSubWordTokenSize = 15
console.log("\n\nRSA-ENCODE\nWORD IN ASCII\tENCODED WORD CHAIN")
console.log("----------------------------------------------")
//iterate through each token so as to split then into subtokens of manageable sizes as some tokens are too large
for (let wordToken in words) {
var cipherToken = ""
//split the tokens into subtokens of length 4
var subWordTokens = words[wordToken].match(/.{1,4}/g);
//iterate through the sub-sub-tokens and encode them
for (var subSubWordToken in subWordTokens) {
var collectionOfSubSubWordTokenChars = ""
//iterate through the sub-sub-tokens to encode
for (let subSubWordTokenChars in subWordTokens[subSubWordToken]) {
//get the ASCII value of the character in the sub-sub-token
collectionOfSubSubWordTokenChars += subWordTokens[subSubWordToken][subSubWordTokenChars].charCodeAt()
}
cipherToken = BigInt(collectionOfSubSubWordTokenChars).modPow(this.state.serverKey.e, this.state.serverKey.n).toString()
console.log(collectionOfSubSubWordTokenChars.padEnd(8, ' ') + "\t\t" + cipherToken);
//pad a character at the end to make all the encoded words have the same size of 15
cipherText += cipherToken.padEnd(SubSubWordTokenSize, '~')
}
//add a space bar to the end of the word
cipherText += " "
}
//console.log(cipherText)
return (cipherText)
}
rsa_decode(cipherText) {
var words = cipherText.split(' ');
var plainText = "";
//group together number of integers to convert to ASCII
var subSubWordTokenSize = 2
console.log("\n\nRSA-DECODE\nENCODED WORD CHAIN\tWORD IN ASCII")
console.log("----------------------------------------------")
//iterate through the words
for (var wordToken in words) {
//get the formatted subword list
var subWordTokens = words[wordToken].match(/.{1,15}/g);
//iterate through each subword and decode them
for (var subSubWordTokens in subWordTokens) {
//replace the terminal character with null
var plain_token = subWordTokens[subSubWordTokens].toString().replace('~', '')
var decoded_token = BigInt(parseInt(plain_token)).modPow(this.state.clientKey.d, this.state.clientKey.n).toString()
console.log(plain_token.padEnd(' ', 8) + "\t\t" + decoded_token);
var i = 0
while (i < decoded_token.length) {
//splice the range over 2 integer values and get ASCII character
plainText += String.fromCharCode((decoded_token.substring(i, i + subSubWordTokenSize)));
i += subSubWordTokenSize;
}
}
plainText += " "
}
return plainText
}
rsa_keyGen() {
var bits = 24;
var p = 0;
var q = 0;
//generate two primes of 24 bits
forge.prime.generateProbablePrime(bits, function (err, num) {
p = num.data[0];
});
forge.prime.generateProbablePrime(bits, function (err, num) {
q = num.data[0];
});
//calculate the public key and private key of the server
var n = p * q
var phi_n = (p - 1) * (q - 1)
var e = 65537
var d = BigInt(e).modInv(phi_n)
this.setState({
clientKey: {
n: n,
e: e,
d: d
}
})
}
//sends a HTTP-POST request with the cipherText as json to the server
getSummary = () =>
fetch(url + "/summarize", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ cipher_text: this.rsa_encode(), n: this.state.clientKey.n }),
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
summarizedText: this.rsa_decode(responseJson.summarized_text).toLowerCase()
})
console.log("\nsummarized text : " + this.state.summarizedText)
})
.catch((error) => {
console.error(error);
});
//on loading the program get the public keys from the server
componentDidMount = () =>
fetch(url + '/getKey', {
method: 'GET'
})
.then((response) => response.json())
.then((public_key) => {
console.log("\nPUBLIC KEY OF SERVER :\n", public_key)
this.setState({
serverKey: {
n: public_key.n,
e: public_key.e
}
})
//generate client's public keys
this.rsa_keyGen()
console.log("\KEYS OF CLIENT :\n", this.state.clientKey)
})
.catch((error) => {
console.error(error);
});
//remove any trailing space-bars
updatePlainText = (text) => this.setState({ plainText: text.trim() })
render() {
return (
<View style={styles.container}>
{/* Input text-box that sets the state of plainText */}
<ScrollView showsVerticalScrollIndicator={true}>
<TextInput style={styles.input}
underlineColorAndroid="transparent"
placeholder="Enter the text"
autoCapitalize="none"
multiline={true}
onChangeText={this.updatePlainText} />
</ScrollView>
{/* On button press calls sends the HTTP-POST request*/}
<View style={styles.buttonContainer}>
<Button
onPress={() => { this.getSummary() }}
title="Summarize"
/>
{/* Output text-box that shows the response (i.e the summarized text) */}
<ScrollView>
<TextInput style={styles.input}
underlineColorAndroid="transparent"
placeholder={this.state.summarizedText}
autoCapitalize="none"
multiline={true}
editable={false} />
</ScrollView>
</View>
<StatusBar style="auto" />
</View>
);
}
} |
JavaScript | class HttpManager {
constructor(clientCount, userAgent) {
if (clientCount < 1) {
throw new Error('There must be at least one client');
}
this.userAgent = userAgent;
this.clients = new Array(clientCount).fill(utils_1.createHttpClient(userAgent));
}
getClient(index) {
return this.clients[index];
}
// client disposal is necessary if a keep-alive connection is used to properly close the connection
// for more information see: https://github.com/actions/http-client/blob/04e5ad73cd3fd1f5610a32116b0759eddf6570d2/index.ts#L292
disposeAndReplaceClient(index) {
this.clients[index].dispose();
this.clients[index] = utils_1.createHttpClient(this.userAgent);
}
disposeAndReplaceAllClients() {
for (const [index] of this.clients.entries()) {
this.disposeAndReplaceClient(index);
}
}
} |
JavaScript | class Reader {
constructor(path) {
this.path = path;
this.unzip = new Unzip(path);
}
parseResorceMap(resourceBuffer, callback) {
let res;
try {
res = new ResourceFinder().processResourceTable(resourceBuffer);
} catch (e) {
return callback(e);
}
callback(null, res);
}
/**
*
*
* @param {Array<String>} whatYouNeed Entries' name
* @param {Object} options (Optional)
* @param {String} options.type By default, this function will return an Object of buffers.
* If options.type='blob', it will return blobs in browser.
* It won't do anything in NodeJS.
* @param {Function} callback Will be called like `callback(error, buffers)`
*/
getEntries(whatYouNeed, options, callback) {
if (utils.isFunction(options)) {
callback = options;
options = {};
}
whatYouNeed = whatYouNeed.map(rule => {
if (typeof rule === 'string') rule = rule.split('\u0000').join('');
return rule;
});
this.unzip.getBuffer(whatYouNeed, options, (error, buffers, entryCount) => {
callback(error, buffers, entryCount);
});
}
getEntry(entryName, options, callback) {
if (utils.isFunction(options)) {
callback = options;
options = {};
}
if (typeof entryName === 'string') entryName = entryName.split('\u0000').join('');
this.unzip.getBuffer([entryName], options, (error, buffers) => {
callback(error, buffers[entryName]);
});
}
} |
JavaScript | class Link extends Component {
static displayName = 'Link';
static propTypes = {
href: PropTypes.string.isRequired,
global: PropTypes.bool,
globalHash: PropTypes.bool
};
onClick = (e) => {
if (this.props.onClick) {
this.props.onClick(e);
}
// return if the link target is external
if (this.props.href.match(/^([a-z-]+:|\/\/)/)) return;
// return if the user did a middle-click, right-click, or used a modifier
// key (like ctrl-click, meta-click, shift-click, etc.)
if (e.button !== 0 || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return;
if (!e.defaultPrevented) {
e.preventDefault();
this._navigate(this.props.href, function (err) {
if (err) {
throw err;
}
});
}
};
_navigationParams() {
var params = {};
for (var k in this.props) {
if (!this.constructor.propTypes[k]) {
params[k] = this.props[k];
}
}
return params;
};
_createHref() {
return this.props.global ?
Environment.defaultEnvironment.makeHref(this.props.href) :
this.makeHref(this.props.href);
};
_navigate(path, cb) {
if (this.props.globalHash) {
return Environment.hashEnvironment.navigate(path, cb);
}
if (this.props.global) {
return Environment.defaultEnvironment.navigate(path, cb);
}
return this.navigate(path, this._navigationParams(), cb);
};
render() {
var props = assign({}, this.props, {
onClick: this.onClick,
href: this._createHref()
});
return (
<a {...props}>{this.props.children}</a>
)
}
} |
JavaScript | class Game {
constructor() {
//0 is player1
//1 is player2
this.activePlayers = {}
this.currentTurn = 'player1'
}
//@param is an instance of the Player class
addPlayer(PlayerInstance) {
this.activePlayers[PlayerInstance.playerName] = PlayerInstance
console.log('active players', this.activePlayers)
return PlayerInstance
}
} |
JavaScript | class MYSQLPromiseObjectBuilder {
constructor(/**@type {import("mysql").Pool}*/ pool) {
this.keys = [];
this.values = [];
this.pool = pool;
}
/**Add a promise to the handler.
* @param {string} key Key in the response object
* @param {string} query SQL Query
* @param {*} def Default Value
* @param {string} DBKey Database Key
* @memberof MYSQLPromiseObjectBuilder
* @returns {true} Done
*/
async add(key, query, def = null, DBKey) {
this.keys.push(key);
let response = new Promise((res) => {
this.pool.query(query, (err, result) => {
// Call from Pool, Auto closes connection
if (result && result[0] != null) {
res(DBKey != null ? result[0][DBKey] : result[0]);
} else {
res(def);
}
});
});
this.values.push(response);
return response;
}
/**Build an object based on the responses.
* @param {Object} data is data.memberData (the mongoose Member schema)
* @returns {Object<*>} Object
* @memberof MYSQLPromiseObjectBuilder
*/
async waitForAll(data = {}) {
let values = await Promise.all(this.values);
for (let i = 0; i < values.length; i++) {
data[this.keys[i]] = values[i];
}
return data;
}
} |
JavaScript | class DashboardController {
/**
* Gets dashboard data for the logged in user.
*
* @param {*} req
* @param {*} res
* @returns
*/
static async data(req, res) {
try {
const data = await DashboardService.data(req.user.id);
if (data) {
res.status(200).json(data);
} else {
res.status(404).json(new ClientMessage(true, ['Not found']));
}
} catch (error) {
res.status(500).json(new ClientMessage(true, [error.message]));
}
}
} |
JavaScript | class Bool extends _Variant {
/**
* @param {bool} defaultValue
* @param {string} falseText
* @param {string} trueText
* @param {string} prompt Input prompt text
*/
constructor (key, defaultValue = false, falseText = 'false', trueText = 'true', prompt = '') {
const signature = `new Bool('${key}', '${defaultValue}', '${falseText}', '${trueText}', '${prompt}') `
if (typeof defaultValue !== 'boolean') {
throw new Error(signature + 'arg 2 \'defaultValue\' must be a boolean')
} else if (typeof falseText !== 'string') {
throw new Error(signature + 'arg 3 \'falseText\' must be a string')
} else if (typeof trueText !== 'string') {
throw new Error(signature + 'arg 4 \'trueText\' must be a string')
}
super(key, defaultValue)
this._value._false = falseText
this._value._true = trueText
this._value._prompt = prompt
}
defaultDisplayString () { return this.displayString(this.defaultValue()) }
defaultDisplayValue () { return this.displayValue(this.defaultValue()) }
displayString (bool) { return this.displayValue(bool) }
displayValue (bool) { return bool ? this._value._true : this._value._false }
hasOption (inputText) {
return (inputText === this._value._false || inputText === this._value._true)
}
inputHint () { return `'${this._value._false}' or '${this._value._true}'` }
isValidDisplayValue (inputText) { return this.validateDisplayValue(inputText).valid }
isValidNativeValue (value) {
// For now, allow truthy and falsey
// if (typeof value !== 'boolean') return false
return this.validateNativeValue(value).valid
}
maximumValue () { return true }
maximumDisplayValue () { return this._value._true }
minimumValue () { return false }
minimumDisplayValue () { return this._value._false }
stepValue () { return 1 }
stepDisplayValue () { return '' }
options () { return [false, true] }
optionText (bool) { return bool ? this._value._true : this._value._false }
optionTexts () { return [this._value._false, this._value._true] }
prompt () { return this._value._prompt }
validateDisplayValue (inputText) {
if (!this.hasOption(inputText)) {
return new ValidationResult(false, inputText, 'Invalid option')
}
const bool = (inputText === this._value._true)
return this.validateNativeValue(bool)
}
validateNativeValue (bool) {
const b = !!bool
return new ValidationResult(true, b)
}
} |
JavaScript | class EventsHandler {
constructor(canvasManager, pointsManager) {
var self = this;
this.handleStart = function(e) {
var coord = self.getEventCoordinates(e);
canvasManager.paint = true;
var points = pointsManager.recordPosition(coord.x - this.offsetLeft, coord.y - this.offsetTop);
canvasManager.draw(points);
};
this.handleMove = function(e) {
if(canvasManager.paint) {
var coord = self.getEventCoordinates(e);
var points = pointsManager.recordPosition(coord.x - this.offsetLeft, coord.y - this.offsetTop, true);
canvasManager.draw(points);
}
};
this.handleEnd = function(e) {
if(canvasManager.paint) {
canvasManager.paint = false;
pointsManager.sendPoints();
$('.page-draw').hide();
$('.page-player').show();
// See if we reset the canvas + points here
// this.canvasManager.clear();
}
};
}
getEventCoordinates(e) {
var isTouchEvent = e.touches ? true : false;
var x, y;
if(isTouchEvent) {
x = e.touches.item(0).pageX - this.offsetLeft;
y = e.touches.item(0).pageY - this.offsetTop;
} else {
if(typeof e.offsetX !== 'undefined') {
x = e.offsetX;
y = e.offsetY;
}
else if(e.layerX) {
x = e.layerX;
y = e.layerY;
}
}
return {
x: x,
y: y
};
}
} |
JavaScript | class TextBox extends Control {
/**
* @constructs
* @param {UI} parent
* @param {string} [text = ""]
* @param {string} [theme = ""]
*/
constructor(parent, text = "", theme = "") {
let elmText = document.createElement("input");
super(parent, theme);
this.config(BText, elmText, TextEncoder);
let thisEnabled = Object.getOwnPropertyDescriptor(this, "enabled");
let that = this;
//NOTE Attributes
this.setAttribute("element-type", "TextBox");
this.setAttribute("element-name", "container");
elmText.setAttribute("element-type", "TextBox");
// elmText.setAttribute("element-name", "input");
// elmText.setAttribute("type", "headText");
// if (!instanceOf(text, String)) {
// text = "";
// }
// elmText.value = text;
//NOTE Append Children
this.addControl(elmText);
//NOTE Public Properties
/**
* @member {string}
*/
// this.defineProperty("text", {
// enumerable: true,
// configurable: true,
// get () {
// return elmText.value;
// },
// set (v) {
// if (instanceOf(v, String)) {
// elmText.value = v;
// }
// }
// });
/**
* @member {boolean}
*/
this.defineProperty("enabled", {
get() {
return thisEnabled.get.bind(that)();
},
set(v) {
thisEnabled.set.bind(that)(v);
if (v === false) {
elmText.setAttribute("disabled", "true");
} else {
elmText.removeAttribute("disabled");
}
},
type: Boolean
});
/**
* @member {string}
*/
this.defineProperty("pattern", {
get() {
return elmText.getAttribute("pattern");
},
set(v) {
elmText.setAttribute("pattern", v);
that.checkValidity();
},
type: String
});
/**
* @member {boolean}
*/
this.defineProperty("required", {
get() {
return elmText.hasAttribute("required");
},
set(v) {
if (v === true) {
elmText.setAttribute("required", "true");
} else {
elmText.removeAttribute("required");
}
that.checkValidity();
},
type: Boolean
});
/**
* @member {number}
*/
this.defineProperty("tabIndex", {
enumerable: true,
configerable: true,
get() {
return elmText.hasAttribute("tabindex") ?
elmButton.getAttribute("tabindex") :
0;
},
set(v) {
if (v > 0) {
elmText.setAttribute("tabindex", v);
} else {
elmText.removeAttribute("tabindex");
}
},
type: Number
});
//NOTE Private Functions
function onClick(e) {
elmText.focus();
}
//NOTE Public Functions
this.select = () => {
elmText.select();
};
/**
* @return boolean
*/
this.isValid = () => {
this.setAttribute("validity", elmText.validity.valid);
return elmText.validity.valid;
};
//NOTE Default Event
this.addEvent("click", onClick);
elmText.addEventListener(
"input",
((e) => {
this.isValid();
}).bind(this),
true
);
elmText.addEventListener(
"focus",
((e) => {
this.dispatchEvent(Events.onFocus);
}).bind(this),
true
);
elmText.addEventListener(
"blur",
((e) => {
this.dispatchEvent(Events.onBlur);
}).bind(this),
true
);
delete this.addControl;
}
} |
JavaScript | class calculator {
constructor(){ //desifnamos las variables que van aestar disponibles en un scope global
this.valueA = 0;
this.valueB = 0;
}
sum(valueA, valueB) { //utilizamos el metodo sum, para sumar nuestros valores
this.valueA = valueA;
this.valueB = valueB;
return this.valueA + this.valueB;
}
} |
JavaScript | class ChainOfSpringsSim extends AbstractODESim {
/**
* @param {string=} opt_name name of this as a Subject
*/
constructor(opt_name) {
super(opt_name);
/**
* @type {boolean}
* @private
*/
this.attachRight_ = true;
/** the atom being dragged, or -1 when no drag is happening
* @type {number}
* @private
*/
this.dragAtom_ = -1;
/**
* @type {number}
* @private
*/
this.gravity_ = 4;
/**
* @type {number}
* @private
*/
this.mass_ = 5;
/**
* @type {number}
* @private
*/
this.damping_ = 0.1;
/**
* @type {number}
* @private
*/
this.restLength_ = 0;
/**
* @type {number}
* @private
*/
this.stiffness_ = 6.0;
/**
* @type {number}
* @private
*/
this.springDamping_ = 0.1;
/** potential energy offset
* @type {number}
* @private
*/
this.potentialOffset_ = 0;
/**
* @type {!PointMass}
* @private
*/
this.fixed1_ = PointMass.makeSquare(0.5, 'fixed1');
this.fixed1_.setPosition(new Vector(-6, 4));
/**
* @type {!PointMass}
* @private
*/
this.fixed2_ = PointMass.makeSquare(0.5, 'fixed2');
this.fixed2_.setPosition(new Vector(6, 4));
/**
* @type {!Array<!PointMass>}
* @private
*/
this.atoms_ = [];
/**
* @type {!Array<!Spring>}
* @private
*/
this.springs_ = [];
this.addParameter(new ParameterNumber(this, ChainOfSpringsSim.en.GRAVITY,
ChainOfSpringsSim.i18n.GRAVITY,
() => this.getGravity(), a => this.setGravity(a)));
this.addParameter(new ParameterNumber(this, ChainOfSpringsSim.en.MASS,
ChainOfSpringsSim.i18n.MASS,
() => this.getMass(), a => this.setMass(a)));
this.addParameter(new ParameterNumber(this, ChainOfSpringsSim.en.STIFFNESS,
ChainOfSpringsSim.i18n.STIFFNESS,
() => this.getStiffness(), a => this.setStiffness(a)));
this.addParameter(new ParameterNumber(this, ChainOfSpringsSim.en.DAMPING,
ChainOfSpringsSim.i18n.DAMPING,
() => this.getDamping(), a => this.setDamping(a)));
this.addParameter(new ParameterNumber(this, ChainOfSpringsSim.en.SPRING_DAMPING,
ChainOfSpringsSim.i18n.SPRING_DAMPING,
() => this.getSpringDamping(), a => this.setSpringDamping(a)));
this.addParameter(new ParameterNumber(this, ChainOfSpringsSim.en.LENGTH,
ChainOfSpringsSim.i18n.LENGTH,
() => this.getLength(), a => this.setLength(a)));
this.addParameter(new ParameterNumber(this, EnergySystem.en.PE_OFFSET,
EnergySystem.i18n.PE_OFFSET,
() => this.getPEOffset(), a => this.setPEOffset(a))
.setLowerLimit(Util.NEGATIVE_INFINITY)
.setSignifDigits(5));
};
/** @override */
toString() {
return Util.ADVANCED ? '' : this.toStringShort().slice(0, -1)
+', atoms: '+this.atoms_.length
+', gravity_: '+Util.NF(this.gravity_)
+', damping_: '+Util.NF(this.damping_)
+', mass_: '+Util.NF(this.mass_)
+', springDamping_: '+Util.NF(this.springDamping_)
+', stiffness_: '+Util.NF(this.stiffness_)
+', restLength_: '+Util.NF(this.restLength_)
+', fixed1_: '+this.fixed1_
+', fixed2_: '+this.fixed2_
+', potentialOffset_: '+Util.NF(this.potentialOffset_)
+ super.toString();
};
/** @override */
getClassName() {
return 'ChainOfSpringsSim';
};
/**
* @param {number} numAtoms
* @return {!Array<string>}
* @param {boolean} localized
* @private
*/
static makeVarNames(numAtoms, localized) {
const names = [];
const n = numAtoms*4 + 8;
for (let i=0; i<n; i++) {
names.push(ChainOfSpringsSim.getVariableName(i, numAtoms, localized));
}
return names;
};
/**
* @param {number} idx
* @param {number} numAtoms
* @param {boolean} localized
* @return {string}
* @private
*/
static getVariableName(idx, numAtoms, localized) {
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
// time KE PE TE fix1x fix1y fix2x fix2y U0x U0y V0x V0y U1x U1y V1x V1y U2x ...
if (idx >= 8) {
const j = (idx-8)%4;
const atom = 1 + Math.floor((idx-8)/4);
let nm = localized ? ChainOfSpringsSim.i18n.BALL : ChainOfSpringsSim.en.BALL;
nm = nm + ' ' + atom + ' ';
switch (j) {
case 0:
return nm + (localized ? ChainOfSpringsSim.i18n.X_POSITION :
ChainOfSpringsSim.en.X_POSITION);
case 1:
return nm + (localized ? ChainOfSpringsSim.i18n.Y_POSITION :
ChainOfSpringsSim.en.Y_POSITION);
case 2:
return nm + (localized ? ChainOfSpringsSim.i18n.X_VELOCITY :
ChainOfSpringsSim.en.X_VELOCITY);
case 3:
return nm + (localized ? ChainOfSpringsSim.i18n.Y_VELOCITY :
ChainOfSpringsSim.en.Y_VELOCITY);
}
} else {
switch (idx) {
case 0:
return localized ? VarsList.i18n.TIME :
VarsList.en.TIME;
case 1:
return localized ? EnergySystem.i18n.KINETIC_ENERGY :
EnergySystem.en.KINETIC_ENERGY;
case 2:
return localized ? EnergySystem.i18n.POTENTIAL_ENERGY :
EnergySystem.en.POTENTIAL_ENERGY;
case 3:
return localized ? EnergySystem.i18n.TOTAL_ENERGY :
EnergySystem.en.TOTAL_ENERGY;
case 4:
return localized ? ChainOfSpringsSim.i18n.ANCHOR1_X :
ChainOfSpringsSim.en.ANCHOR1_X;
case 5:
return localized ? ChainOfSpringsSim.i18n.ANCHOR1_Y :
ChainOfSpringsSim.en.ANCHOR1_Y;
case 6:
return localized ? ChainOfSpringsSim.i18n.ANCHOR2_X :
ChainOfSpringsSim.en.ANCHOR2_X;
case 7:
return localized ? ChainOfSpringsSim.i18n.ANCHOR2_Y :
ChainOfSpringsSim.en.ANCHOR2_Y;
}
}
throw '';
};
/** Set number of atoms and set simulation to initial state.
* @param {number} numAtoms number of mass objects in the chain
* @param {boolean} attachRight whether to attach to fixed block on right
* @return {undefined}
*/
makeChain(numAtoms, attachRight) {
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
// time KE PE TE fix1x fix1y fix2x fix2y U0x U0y V0x V0y U1x U1y V1x V1y U2x ...
this.getSimList().removeAll(this.atoms_);
this.atoms_.length = 0;
this.getSimList().removeAll(this.springs_);
this.springs_.length = 0;
const va = this.getVarsList();
va.deleteVariables(0, va.numVariables());
va.addVariables(ChainOfSpringsSim.makeVarNames(numAtoms, /*localized=*/false),
ChainOfSpringsSim.makeVarNames(numAtoms, /*localized=*/true));
va.setComputed(1, 2, 3);
const left = this.fixed1_.getPosition();
const right = this.fixed2_.getPosition();
va.setValue(4, left.getX());
va.setValue(5, left.getY());
va.setValue(6, right.getX());
va.setValue(7, right.getY());
this.getSimList().add(this.fixed1_);
this.getSimList().add(this.fixed2_);
if (numAtoms > 0) {
const len = right.subtract(left).length();
const size = Math.min(0.5, len/(2*(numAtoms+1)));
const mass = this.mass_/numAtoms;
for (let i=0; i<numAtoms; i++) {
const atom = PointMass.makeCircle(size, 'atom'+(i+1)).setMass(mass);
this.atoms_.push(atom);
}
this.getSimList().addAll(this.atoms_);
let spring = new Spring('spring 0',
this.fixed1_, Vector.ORIGIN,
this.atoms_[0], Vector.ORIGIN, this.restLength_, this.stiffness_);
spring.setDamping(this.springDamping_);
this.springs_.push(spring);
for (let i=1; i<numAtoms; i++) {
spring = new Spring('spring '+i,
this.atoms_[i-1], Vector.ORIGIN,
this.atoms_[i], Vector.ORIGIN, this.restLength_, this.stiffness_);
spring.setDamping(this.springDamping_);
this.springs_.push(spring);
}
if (attachRight) {
spring = new Spring('spring '+(numAtoms+1),
this.atoms_[numAtoms-1], Vector.ORIGIN,
this.fixed2_, Vector.ORIGIN, this.restLength_, this.stiffness_);
spring.setDamping(this.springDamping_);
this.springs_.push(spring);
}
this.getSimList().addAll(this.springs_);
this.straightLine();
}
this.saveInitialState();
this.modifyObjects();
};
/** Arranges atoms in a straight line between the fixed points (even if the fixed
* points are not connected to the chain).
* @return {undefined}
*/
straightLine() {
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
// time KE PE TE fix1x fix1y fix2x fix2y U0x U0y V0x V0y U1x U1y V1x V1y U2x ...
const vars = this.getVarsList().getValues();
const left = this.fixed1_.getPosition();
const right = this.fixed2_.getPosition();
const diff = right.subtract(left);
const n = this.atoms_.length;
for (let i=0; i<n; i++) {
const p = left.add(diff.multiply((i+1)/(n+1)));
vars[0 + i*4 + 8] = p.getX();
vars[1 + i*4 + 8] = p.getY();
vars[2 + i*4 + 8] = 0;
vars[3 + i*4 + 8] = 0;
}
this.getVarsList().setValues(vars);
this.modifyObjects();
};
/** @override */
getEnergyInfo() {
let ke = 0;
let pe = 0;
this.springs_.forEach(spr => pe += spr.getPotentialEnergy());
this.atoms_.forEach(atom => {
ke += atom.getKineticEnergy();
// gravity potential = m g (y - floor)
pe += this.gravity_ * atom.getMass() * atom.getPosition().getY();
});
return new EnergyInfo(pe + this.potentialOffset_, ke);
};
/** @override */
getPEOffset() {
return this.potentialOffset_;
}
/** @override */
setPEOffset(value) {
this.potentialOffset_ = value;
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
// time KE PE TE fix1x fix1y fix2x fix2y U0x U0y V0x V0y U1x U1y V1x V1y U2x ...
// discontinuous change in energy
this.getVarsList().incrSequence(2, 3);
this.broadcastParameter(EnergySystem.en.PE_OFFSET);
};
/** @override */
modifyObjects() {
const va = this.getVarsList();
const vars = va.getValues();
this.moveObjects(vars);
const ei = this.getEnergyInfo();
// vars[1] = KE, vars[2] = PE, vars[3] = TE
va.setValue(1, ei.getTranslational(), true);
va.setValue(2, ei.getPotential(), true);
va.setValue(3, ei.getTotalEnergy(), true);
};
/**
@param {!Array<number>} vars
@private
*/
moveObjects(vars) {
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
// time KE PE TE fix1x fix1y fix2x fix2y U0x U0y V0x V0y U1x U1y V1x V1y U2x ...
this.atoms_.forEach((atom, i) => {
const idx = 4*i + 8;
atom.setPosition(new Vector(vars[idx], vars[1 + idx]));
atom.setVelocity(new Vector(vars[2 + idx], vars[3 + idx], 0));
});
this.fixed1_.setPosition(new Vector(vars[4], vars[5]));
this.fixed2_.setPosition(new Vector(vars[6], vars[7]));
};
/** @override */
startDrag(simObject, location, offset, dragBody, mouseEvent) {
if (simObject instanceof PointMass) {
this.dragAtom_ = this.atoms_.indexOf(simObject);
return this.dragAtom_ > -1 || simObject == this.fixed1_ || simObject == this.fixed2_;
} else {
return false;
}
};
/** @override */
mouseDrag(simObject, location, offset, mouseEvent) {
const p = location.subtract(offset);
const va = this.getVarsList();
if (simObject == this.fixed1_) {
va.setValue(4, p.getX());
va.setValue(5, p.getY());
} else if (simObject == this.fixed2_) {
va.setValue(6, p.getX());
va.setValue(7, p.getY());
} else if (this.dragAtom_ > -1) {
const atom = this.atoms_[this.dragAtom_];
if (simObject != atom) {
return;
}
const idx = 4*this.dragAtom_ + 8;
va.setValue(0 + idx, p.getX());
va.setValue(1 + idx, p.getY());
va.setValue(2 + idx, 0);
va.setValue(3 + idx, 0);
}
// derived energy variables are discontinuous
// vars[1] = KE, vars[2] = PE, vars[3] = TE
va.incrSequence(1, 2, 3);
this.moveObjects(va.getValues());
};
/** @override */
finishDrag(simObject, location, offset) {
this.dragAtom_ = -1;
};
/** @override */
handleKeyEvent(keyCode, pressed, keyEvent) {
};
/** @override */
evaluate(vars, change, timeStep) {
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
// time KE PE TE fix1x fix1y fix2x fix2y U0x U0y V0x V0y U1x U1y V1x V1y U2x ...
Util.zeroArray(change);
this.moveObjects(vars);
change[0] = 1; // time
this.atoms_.forEach((atom, listIdx) => {
if (this.dragAtom_ == listIdx) {
return;
}
const idx = 4*listIdx + 8;
change[idx] = vars[idx+2]; // Ux' = Vx
change[idx+1] = vars[idx+3]; // Uy' = Vy
const mass = atom.getMass();
// for each spring, get force from spring,
const force = new MutableVector(0, 0);
this.springs_.forEach(spr => {
if (spr.getBody1() == atom) {
force.add(spr.calculateForces()[0].getVector());
} else if (spr.getBody2() == atom) {
force.add(spr.calculateForces()[1].getVector());
}
});
// add gravity force
force.add(new Vector(0, -this.gravity_*mass));
force.add(new Vector(vars[idx+2], vars[idx+3]).multiply(-this.damping_));
change[idx+2] = force.getX()/mass; // Vx'
change[idx+3] = force.getY()/mass; // Vy'
});
return null;
};
/** Return gravity strength.
@return {number} gravity strength
*/
getGravity() {
return this.gravity_;
};
/** Set gravity strength.
@param {number} value gravity strength
*/
setGravity(value) {
this.gravity_ = value;
// discontinuous change in energy
// vars[1] = KE, vars[2] = PE, vars[3] = TE
this.getVarsList().incrSequence(2, 3);
this.broadcastParameter(ChainOfSpringsSim.en.GRAVITY);
};
/** Return damping
@return {number} damping
*/
getDamping() {
return this.damping_;
};
/** Set damping
@param {number} value damping
*/
setDamping(value) {
this.damping_ = value;
this.broadcastParameter(ChainOfSpringsSim.en.DAMPING);
};
/** Return spring damping
@return {number} spring damping
*/
getSpringDamping() {
return this.springDamping_;
};
/** Set spring damping
@param {number} value spring damping
*/
setSpringDamping(value) {
this.springDamping_ = value;
this.springs_.forEach(spr => spr.setDamping(value));
this.broadcastParameter(ChainOfSpringsSim.en.SPRING_DAMPING);
};
/** Return mass of atoms
@return {number} mass of atoms
*/
getMass() {
return this.mass_;
};
/** Set mass of atoms
@param {number} value mass of atoms
*/
setMass(value) {
this.mass_ = value;
const mass = this.mass_/this.atoms_.length;
this.atoms_.forEach(atom => atom.setMass(mass));
// discontinuous change in energy
// vars[1] = KE, vars[2] = PE, vars[3] = TE
this.getVarsList().incrSequence(1, 2, 3);
this.broadcastParameter(ChainOfSpringsSim.en.MASS);
};
/** Return spring resting length
@return {number} spring resting length
*/
getLength() {
return this.restLength_;
};
/** Set spring resting length
@param {number} value spring resting length
*/
setLength(value) {
this.restLength_ = value;
for (let i=0; i<this.springs_.length; i++) {
this.springs_[i].setRestLength(value);
}
// discontinuous change in energy
// vars[1] = KE, vars[2] = PE, vars[3] = TE
this.getVarsList().incrSequence(2, 3);
this.broadcastParameter(ChainOfSpringsSim.en.LENGTH);
};
/** Returns spring stiffness
@return {number} spring stiffness
*/
getStiffness() {
return this.stiffness_;
};
/** Sets spring stiffness
@param {number} value spring stiffness
*/
setStiffness(value) {
this.stiffness_ = value;
for (let i=0; i<this.springs_.length; i++) {
this.springs_[i].setStiffness(value);
}
// discontinuous change in energy
// vars[1] = KE, vars[2] = PE, vars[3] = TE
this.getVarsList().incrSequence(2, 3);
this.broadcastParameter(ChainOfSpringsSim.en.STIFFNESS);
};
} // end class |
JavaScript | class VideoDetailPage extends Component {
constructor(props) {
super(props);
this.itemData = props.navigation.state.params.data;
this.state = {
isFullScreen: false,
}
}
componentDidMount() {
Orientation.addOrientationListener(this._orientationDidChange);
}
_orientationDidChange = (orientation) => {
this.setState({
isFullScreen: orientation === 'LANDSCAPE',
});
};
componentWillUnmount() {
Orientation.removeOrientationListener(this._orientationDidChange);
}
_renderTAg = (tag) => {
return (
<ImageBackground
key={tag.id}
style={{borderRadius: 5, flex: 1, marginLeft: 4, marginRight: 4,}}
source={{uri: tag.headerImage}}>
<Text style={{
color: '#fff',
fontSize: 10,
paddingTop: 8,
paddingBottom: 8,
textAlign: 'center'
}}>{'#' + tag.name + '#'}</Text>
</ImageBackground>);
};
render() {
return (<View style={styles.container}>
<VideoPlayer data={{
title: this.itemData.data.title,
playUrl: this.itemData.data.playUrl,
showCover: true,
coverUrl: this.itemData.data.cover.feed,
duration: this.itemData.data.duration,
}}{...this.props}/>
{this.state.isFullScreen ? null : <ImageBackground style={[styles.container, {padding: 16}]}
source={{uri: this.itemData.data.cover.blurred}}>
<Text style={{
color: '#fff',
fontSize: 15,
fontWeight: 'bold',
flexWrap: 'wrap'
}}>{this.itemData.data.title}</Text>
<Text style={{
color: '#fff',
fontSize: 12,
}}
numberOfLines={1}>{'# ' + this.itemData.data.category + ' / ' + this.itemData.data.duration}</Text>
<Text style={{
color: '#fff',
fontSize: 13,
flexWrap: 'wrap',
paddingTop: 16,
paddingBottom: 16
}}>{this.itemData.data.description}</Text>
<View style={[styles.horizontal, {alignItems: 'center',}]}>
<View style={[styles.horizontal, {alignItems: 'center', paddingRight: 20,}]}>
<Image style={styles.consumptionImage}
source={require('../../../../img/ic_action_favorites_without_padding.png')}/>
<Text style={{
color: '#fff',
fontSize: 12,
flexWrap: 'wrap',
textAlign: 'center',
paddingLeft: 8,
}}>{this.itemData.data.consumption.collectionCount}</Text>
</View>
<View style={[styles.horizontal, {alignItems: 'center', paddingRight: 20,}]}>
<Image style={styles.consumptionImage}
source={require('../../../../img/ic_action_share_without_padding.png')}/>
<Text style={{
color: '#fff',
fontSize: 12,
flexWrap: 'wrap',
textAlign: 'center',
paddingLeft: 8,
}}>{this.itemData.data.consumption.shareCount}</Text>
</View>
<View style={[styles.horizontal, {alignItems: 'center', paddingRight: 20,}]}>
<Image style={styles.consumptionImage}
source={require('../../../../img/ic_action_reply_without_padding.png')}/>
<Text style={{
color: '#fff',
fontSize: 12,
flexWrap: 'wrap',
textAlign: 'center',
paddingLeft: 8,
}}>{this.itemData.data.consumption.replyCount}</Text>
</View>
<View style={[styles.horizontal, {alignItems: 'center', paddingRight: 20,}]}>
<Image style={styles.consumptionImage}
source={require('../../../../img/ic_action_offline_without_padding.png')}/>
<Text style={{
color: '#fff',
fontSize: 12,
flexWrap: 'wrap',
textAlign: 'center',
paddingLeft: 8,
}}>缓存</Text>
</View>
</View>
<View style={{height: 0.5, backgroundColor: '#999', marginTop: 16, marginBottom: 16}}/>
<View
style={[styles.horizontal, {justifyContent: 'space-between',}]}>
{this.itemData.data.tags.map(this._renderTAg)}
</View>
<View style={{height: 0.5, backgroundColor: '#999', marginTop: 16, marginBottom: 16}}/>
<View style={{
flexDirection: 'row',
alignItems: 'center',
paddingTop: 8,
}}>
<Image style={styles.avatar} source={{uri: this.itemData.data.author.icon}}/>
<View style={{alignItems: 'flex-start', flex: 1, paddingLeft: 6,}}>
<Text style={{
fontSize: 13,
color: '#fff',
fontWeight: 'bold',
textAlign: 'center'
}}>{this.itemData.data.author.name}</Text>
<Text style={{
fontSize: 10,
color: '#fff',
flexWrap: 'wrap',
}}>{this.itemData.data.author.description}</Text>
</View>
<View style={{
alignSelf: 'flex-end',
borderRadius: 3,
borderWidth: 1,
borderColor: '#fff',
marginLeft: 5,
marginBottom: 12
}}>
<Text style={{
color: '#fff',
fontSize: 10,
paddingLeft: 6,
paddingRight: 6,
paddingTop: 3,
paddingBottom: 3,
}}>{'+关注'}</Text>
</View>
</View>
<View style={{height: 0.5, backgroundColor: '#999', marginTop: 16, marginBottom: 16}}/>
</ImageBackground>}
</View>);
}
} |
JavaScript | class GetBucketAccelerateConfigurationCommand extends smithy_client_1.Command {
// Start section: command_properties
// End section: command_properties
constructor(input) {
// Start section: command_constructor
super();
this.input = input;
// End section: command_constructor
}
/**
* @internal
*/
resolveMiddleware(clientStack, configuration, options) {
this.middlewareStack.use(middleware_serde_1.getSerdePlugin(configuration, this.serialize, this.deserialize));
this.middlewareStack.use(middleware_bucket_endpoint_1.getBucketEndpointPlugin(configuration));
const stack = clientStack.concat(this.middlewareStack);
const { logger } = configuration;
const clientName = "S3Client";
const commandName = "GetBucketAccelerateConfigurationCommand";
const handlerExecutionContext = {
logger,
clientName,
commandName,
inputFilterSensitiveLog: models_0_1.GetBucketAccelerateConfigurationRequest.filterSensitiveLog,
outputFilterSensitiveLog: models_0_1.GetBucketAccelerateConfigurationOutput.filterSensitiveLog,
};
const { requestHandler } = configuration;
return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext);
}
serialize(input, context) {
return Aws_restXml_1.serializeAws_restXmlGetBucketAccelerateConfigurationCommand(input, context);
}
deserialize(output, context) {
return Aws_restXml_1.deserializeAws_restXmlGetBucketAccelerateConfigurationCommand(output, context);
}
} |
JavaScript | class EzModal extends React.Component {
constructor(props) {
super(props);
this._modalClosePromise = null;
this.CloseConfirm = () => {
//log.assert(false);
this.setState({ isOpen: false });
if (this._modalClosePromise != null) {
let tempPromise = this._modalClosePromise;
this._modalClosePromise = null;
tempPromise.resolve(undefined);
}
};
this.CloseCancel = () => {
//log.assert(false);
this.setState({ isOpen: false });
if (this._modalClosePromise != null) {
let tempPromise = this._modalClosePromise;
this._modalClosePromise = null;
tempPromise.reject(undefined);
}
};
this.state = { isOpen: false, title: undefined, message: undefined, details: undefined, showOptions: {} };
log.deprecated(`${xlib.reflection.getTypeName(this)} is deprecated due to poor design. use EzPopup instead`);
}
//componentDidMount() {
// //look for querystrings
// log.info("EzModal props", this.props);
//}
render() {
//const Modal = ReactBootstrap.Modal;
//const Button = ReactBootstrap.Button;
let buttonJsx;
if (this.state.showOptions == null) {
throw log.error("showOptions null", { state: this.state });
}
if (this.state.showOptions.confirmButtonText == null) {
buttonJsx = React.createElement(ReactStrap.Button, { className: "btn-primary", onClick: this.CloseConfirm }, " Close ");
}
else {
buttonJsx = React.createElement("span", null,
React.createElement(ReactStrap.Button, { onClick: this.CloseCancel }, "Cancel "),
React.createElement(ReactStrap.Button, { className: "btn-primary", onClick: this.CloseConfirm },
" ",
this.state.showOptions.confirmButtonText,
" "));
}
//TODO: how to pass args to function?
return (React.createElement("div", null,
React.createElement(ReactStrap.Modal, { isOpen: this.state.isOpen, toggle: this.CloseConfirm, backdrop: this.state.showOptions.nonModal === true ? true : "static" },
React.createElement(ReactStrap.ModalHeader, { toggle: this.CloseConfirm },
this.state.title,
"\t\t\t\t\t"),
React.createElement(ReactStrap.ModalBody, null,
React.createElement("div", { className: "row" },
React.createElement("div", { className: "col-sm-12" },
" ",
this.state.message,
" "),
React.createElement("div", { className: "col-sm-12" },
" ",
React.createElement("pre", null,
this.state.details,
" ")))),
React.createElement(ReactStrap.ModalFooter, null, buttonJsx))));
}
Show(title, message, details, options) {
//log.assert(false);
if (options == null) {
options = {};
}
if (this._modalClosePromise == null) {
this._modalClosePromise = xlib.promise._deprecated.CreateExposedPromise();
}
this.setState({ isOpen: true, title, message, details, showOptions: options });
return this._modalClosePromise;
}
} |
JavaScript | class EzStripeCheckout extends React.Component {
constructor() {
super();
this.state = { showOptions: _.clone(_defaultStripeCheckoutOptions) };
}
/**
* shows the stripe checkout modal using your options. returns the stripeToken via promise.
* @param showOptions
*/
showStripe(showOptions) {
blib.googleAnalytics("send", "event", "stripeCheckout", "start");
if (this._showPromise != null && this._showPromise.isResolved() !== true) {
return Promise.reject(new Error("StripeCheckout.showStripe() already in progress"));
}
this._showPromise = xlib.promise._deprecated.CreateExposedPromise((resolve, reject) => {
this.setState({ showOptions }, () => {
//callback
var stripeCheckout = this.refs["reactStripeCheckout"];
//log.assert(false, "inspect", stripeCheckout);
stripeCheckout.showStripeDialog();
});
});
return this._showPromise;
}
render() {
let showOptions = this.state.showOptions;
return (React.createElement(StripeCheckout, { ref: "reactStripeCheckout", token: this._onToken.bind(this), stripeKey: this.props.configOptions.stripeKey, billingAddress: showOptions.billingAddressCheck, shippingAddress: showOptions.shippingAddressCheck, currency: "USD", email: showOptions.email, zipCode: showOptions.zipCodeCheck, alipay: showOptions.allowAlipay, alipayReusable: showOptions.allowAlipayReusable, bitcoin: showOptions.allowBitcoin, name: showOptions.name, description: showOptions.description, panelLabel: showOptions.payButtonLabel, image: showOptions.imageUrl, allowRememberMe: showOptions.allowRememberMe, reconfigureOnUpdates: true, reconfigureOnUpdate: true, amount: showOptions.amount, closed: this._checkoutClosed.bind(this) },
" ",
React.createElement("button", { style: { display: "none" } })));
}
/**
* called if manually closed by user, or after onToken() is called
*/
_checkoutClosed() {
//log.debug("EzStrieCheckout._checkoutClosed()", { arguments });
//need to put in timeout otherwise source-map-support barfs with xss security errors
setTimeout(() => {
//log.debug("EzStrieCheckout._checkoutClosed().timeout");
if (this._showPromise != null && this._showPromise.isResolved() !== true) {
this._showPromise.reject(new Error("aborted by user"));
blib.googleAnalytics("send", "event", "stripeCheckout", "cancel");
return;
}
});
}
_onToken(stripeToken) {
//log.debug("EzStrieCheckout.onToken()", { stripeToken, arguments });
//setTimeout(() => {
//log.debug("EzStrieCheckout.onToken().timeout");
if (this._showPromise != null && this._showPromise.isResolved() !== true) {
this._showPromise.resolve({ stripeToken });
blib.googleAnalytics("send", "event", "stripeCheckout", "finish");
return;
}
log.assert(false, "promise isn't ready, why?");
//});
//this.componentDidMount
}
} |
JavaScript | class SpinnerButton extends React.Component {
constructor(props) {
super(props);
this._onClick = (event) => {
event.preventDefault();
let clickPromise = this.props.onClick(event)
.catch((err) => {
//log.warn( "in on click catch", { currentTarget: event.currentTarget, } );
let errDetails = this.props.customError == null ? {
title: (React.createElement("div", null, "An Error Occured")),
content: (React.createElement("div", null, err.message))
} : this.props.customError(err);
if (errDetails != null) {
this.setState({ popoverOpen: !this.state.popoverOpen, errDetails });
}
else {
//silently eat the error.
}
});
let onClickPromise = this._instrumentMountInfo(clickPromise, this.state.onClickPromise.isMounted); //re-store the current isMounted state
this.setState({ onClickPromise });
onClickPromise.finally(() => {
if (this.state.onClickPromise.isMounted === true) {
//notify that our promise state has changed internally
this.setState({ onClickPromise });
}
});
};
let onClickPromise = this._instrumentMountInfo(Promise.resolve(), false);
this.state = {
onClickPromise,
popoverOpen: false,
buttonId: `spinner_${xlib.security.randomAsciiStringCrypto(10)}`,
errDetails: { title: "", content: "" },
};
}
/** inject the isMounted property onto the Promise */
_instrumentMountInfo(promise, isMounted) {
//let promiseTypeProxy = this.state.onClickPromise;
let toReturn = promise;
toReturn.isMounted = isMounted;
return toReturn;
}
componentDidMount() {
this.state.onClickPromise.isMounted = true;
}
componentWillUnmount() {
this.state.onClickPromise.isMounted = false;
}
render() {
const _a = this.props, { isLoaded, onClick, customError } = _a, otherProps = __rest(_a, ["isLoaded", "onClick", "customError"]);
return (React.createElement("button", Object.assign({ id: this.state.buttonId, onClick: this._onClick, disabled: this.state.onClickPromise.isResolved() === false || this.props.disabled === true || this.props.isLoaded === false }, otherProps),
React.createElement(reactEco.ReactLoader, { loaded: (this.state.onClickPromise.isResolved() && this.props.isLoaded !== false) }),
this.props.children,
React.createElement(ReactStrap.Popover, { placement: "bottom", isOpen: this.state.popoverOpen, toggle: () => { this.setState({ popoverOpen: !this.state.popoverOpen }); }, target: this.state.buttonId },
React.createElement(ReactStrap.PopoverTitle, null,
React.createElement("span", { className: "badge badge-danger" }, this.state.errDetails.title)),
React.createElement(ReactStrap.PopoverContent, null,
React.createElement("div", { className: "alert alert-danger", role: "alert" },
this.state.errDetails.content,
"}")))));
}
} |
JavaScript | class LrndesignImagemapHotspot extends LitElement {
/**
* LitElement constructable styles enhancement
*/
static get styles() {
return [
css`
:host {
display: none;
}
@media print {
:host {
display: block;
}
}
`,
];
}
/**
* LitElement render
*/
render() {
return html`
<figure class="hotspot-print">
<figcaption>
<relative-heading disable-link id="sub-heading" parent="heading">
<h2>${this.label}</h2>
</relative-heading>
<div id="desc"><slot></slot></div>
</figcaption>
<slot id="svg" name="svg"></slot>
</figure>
`;
}
/**
* HTMLElement
*/
constructor() {
super();
import("@lrnwebcomponents/relative-heading/relative-heading.js");
}
static get tag() {
return "lrndesign-imagemap-hotspot";
}
static get properties() {
return {
/**
* Label for the hotspot
*/
label: {
type: String,
},
/**
* Id of hotspot element inside the SVG
*/
hotspotId: {
type: String,
attribute: "hotspot-id",
reflect: true,
},
position: {
type: String,
},
__hotspots: {
type: Array,
},
};
}
loadSvg(svg, hotspots) {
let div = document.createElement("div");
div.innerHTML = svg;
let slot = div.children[0];
slot.slot = svg;
slot.setAttribute("aria-labelledBy", "sub-heading");
slot.setAttribute("aria-describedBy", "sub-heading desc");
(hotspots || []).forEach((hotspot) => {
let svgHotspot = slot.querySelector(`#${hotspot}`);
svgHotspot.classList.add("hotspot");
if (hotspot === this.hotspotId) {
svgHotspot.classList.add("selected");
}
});
this.appendChild(slot);
div.remove();
}
setParentHeading(parent) {
this.shadowRoot.querySelector("#heading").parent = parent;
}
} |
JavaScript | class OptimizerInputsQuantRiskModelRawData {
/**
* Constructs a new <code>OptimizerInputsQuantRiskModelRawData</code>.
* @alias module:model/OptimizerInputsQuantRiskModelRawData
*/
constructor() {
OptimizerInputsQuantRiskModelRawData.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>OptimizerInputsQuantRiskModelRawData</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/OptimizerInputsQuantRiskModelRawData} obj Optional instance to populate.
* @return {module:model/OptimizerInputsQuantRiskModelRawData} The populated <code>OptimizerInputsQuantRiskModelRawData</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new OptimizerInputsQuantRiskModelRawData();
if (data.hasOwnProperty('labels')) {
obj['labels'] = OptimizerInputsLabels.constructFromObject(data['labels']);
}
if (data.hasOwnProperty('RawAssetCovarianceMatrix')) {
obj['RawAssetCovarianceMatrix'] = OptimizerInputsSparseMatrix.constructFromObject(data['RawAssetCovarianceMatrix']);
}
if (data.hasOwnProperty('RawFactorExposure')) {
obj['RawFactorExposure'] = OptimizerInputsSparseMatrix.constructFromObject(data['RawFactorExposure']);
}
if (data.hasOwnProperty('RawFactorCovarianceMatrix')) {
obj['RawFactorCovarianceMatrix'] = OptimizerInputsDenseMatrix.constructFromObject(data['RawFactorCovarianceMatrix']);
}
if (data.hasOwnProperty('RiskModelCoverageFlag')) {
obj['RiskModelCoverageFlag'] = ApiClient.convertToType(data['RiskModelCoverageFlag'], ['Number']);
}
}
return obj;
}
} |
JavaScript | class Manager extends Employee {
constructor(name, id, email, special) {
super(name, id, email);
this.special= special;
}
getSpecial() {
return this.special;
}
getRole() {
return `Manager`;
}
} |
JavaScript | class EventManager {
/**
* Constructor
*/
constructor() {
this._events = {};
}
/**
* Define an event, with a name associated with a function
* @param {String} eventName - Name to give to the event
* @param {Function} callback - function associated to the even
*/
on(eventName, callback) {
if (typeof callback === 'function') {
if (!(eventName in this._events)) {
this._events[eventName] = [];
}
this._events[eventName].push(callback);
} else {
console.warn('The callback must be of type Function');
}
}
emit(eventName, args = []) {
// the event must exist and be non null
if ((eventName in this._events) && (this._events[eventName].length > 0)) {
const events = this._events[eventName];
for (let i = 0; i < events.length; i += 1) {
events[i](...args);
}
} else {
console.warn(`No function associated to the event ${eventName}`);
}
}
} |
JavaScript | class Rigidbody {
constructor(pos, scale, density = 1.0) {
this.pos = pos;
this.rot = 0.0;
this.linVel = new Vec2();
this.angVel = 0.0;
//Vector from center to top right corner
this.scale = scale;
//Scale is half, get the whole size
this.gravity = 20;
this.linDamp = 0.995;
this.angDamp = 0.99;
this.mass = 0;
this.inertia = 0;
this.resetMass(density);
}
integrateVelocity(dt) {
if(this.mass != 0.0)
this.linVel.y += dt*this.gravity;
}
integratePosition(dt) {
//Integrate and apply some fake damping
if(this.mass != 0.0) {
this.pos = this.pos.add(this.linVel.mul(dt));
this.linVel = this.linVel.mul(this.linDamp);
}
if(this.inertia != 0.0) {
this.rot += this.angVel*dt;
this.angVel *= this.angDamp;
}
}
resetMass(density) {
let width = this.scale.x*2.0;
let height = this.scale.y*2.0;
this.mass = width*height*density;
this.inertia = this.mass*(width*width + height*height)/12.0;
this.mass = safeDivide(1.0, this.mass);
this.inertia = safeDivide(1.0, this.inertia);
}
//Inefficient, would be better to store right vector so you can cross to get up
getUp(scaled) {
let result = new Vec2(-Math.sin(this.rot), Math.cos(this.rot));
return scaled ? result.mul(this.scale.y) : result;
}
getRight(scaled) {
let result = new Vec2(Math.cos(this.rot), Math.sin(this.rot));
return scaled ? result.mul(this.scale.x) : result;
}
modelToWorld(model) {
return model.mulVec(this.scale).rotate(this.rot).add(this.pos);
}
worldToModel(world) {
return world.sub(this.pos).rotate(-this.rot).mulVec(this.scale.recip());
}
isMobile() {
return this.mass != 0 || this.inertia != 0;
}
} |
JavaScript | class RecoveryAPI {
constructor (state, transport, execUserCommand, instanceUID) {
this.state = state
this.transport = transport
this.instanceUID = instanceUID
this.execUserCommand = execUserCommand
}
checkUserSockets (user) {
const { userName } = user
return run(this, function * () {
const sockets = yield user.userState.getSocketsToInstance()
yield Promise.each(_.toPairs(sockets), ([socket, instance]) => {
if (instance === this.instanceUID) {
if (!this.transport.getSocket(socket)) {
return user.userState.removeSocket(socket)
}
}
})
const data = yield user.userState.getSocketsToRooms()
const args = _.values(data)
const rooms = _.intersection(...args)
return Promise.each(rooms, roomName => {
return this.state.getRoom(roomName)
.then(room => room.roomState.hasInList('userlist', userName))
.then(isPresent => isPresent ? null : user.removeFromRoom(roomName))
.catchReturn()
})
})
}
checkRoomJoined (room) {
const { roomName } = room
return room.getList(null, 'userlist', true).then(userlist => {
return Promise.each(userlist, userName => {
return this.state.getUser(userName).then(user => {
return user.userState.getRoomToSockets(roomName).then(sockets => {
if (!sockets || !sockets.length) {
return user.removeFromRoom(roomName)
}
}).catchReturn()
.then(() => room.checkAcess(userName))
.catch(() => user.removeFromRoom(roomName))
}).catchReturn()
})
})
}
/**
* Sync user to sockets associations.
*
* @param {string} userName User name.
* @param {callback} [cb] Optional callback.
*
* @return {Promise<undefined>} Promise that resolves without any data.
*/
userStateSync (userName, cb) {
return this.state.getUser(userName)
.then(user => this.checkUserSockets(user))
.asCallback(cb)
}
/**
* Sync room to users associations.
*
* @param {string} roomName Room name.
* @param {callback} [cb] Optional callback.
*
* @return {Promise<undefined>} Promise that resolves without any data.
*/
roomStateSync (roomName, cb) {
return this.state.getRoom(roomName)
.then(room => this.checkRoomJoined(room))
.asCallback(cb)
}
/**
* Fixes an instance data after an incorrect service shutdown.
*
* @param {string} id Instance id.
* @param {callback} [cb] Optional callback.
*
* @return {Promise<undefined>} Promise that resolves without any data.
*/
instanceRecovery (id, cb) {
return this.state.getInstanceSockets(id).then(sockets => {
return Promise.each(_.toPairs(sockets), ([id, userName]) => {
return this.state.getUser(userName)
.then(user => user.removeSocket(id))
.catchReturn()
})
}).asCallback(cb)
}
/**
* Gets an instance heartbeat.
*
* @param {string} id Instance id.
* @param {callback} [cb] Optional callback.
*
* @return {Promise<number>} Heartbeat timestamp.
*/
getInstanceHeartbeat (id, cb) {
return this.state.getInstanceHeartbeat(id).asCallback(cb)
}
} |
JavaScript | class SharingManager {
/**
* @param inventory {DeployInventory} the deploy inventory object
* @param base initial base snapshot
* @param monitor {EntityChangeMonitor} monitor for the changes
* @param serviceObject {Object} an object used to involve with server
* @param currentUser {String} the jenkins user by whom this page is requested
*/
constructor(inventory, base, monitor, serviceObject, currentUser) {
this.serviceObject = serviceObject;
this.currentUser = currentUser;
/**
* the target deploy inventory object
* @type {DeployInventory}
*/
this.inventory = inventory;
/**
* thread for fetching latest versions
* @type {TimerThread}
*/
this.fetchingThread = new TimerThread(this, this.fetch, this.fetched, 500, 30000);
/**
* thread for pushing local snapshots
* @type {TimerThread}
*/
this.pushingThread = new TimerThread(this, this.push, this.pushed, 500, 30000);
/**
* base snapshot, the latest version fetched from server
* @type {Object}
*/
this.base = base;
/**
* outgoing snapshot, stores what we just sent to server but no received the reply
* equal to base means no snapshot are sent after received the reply last time.
*/
this.outgoing = base;
/**
* the id of the changes made on current version of base
*/
this.changeId = null;
/**
* notify the UI whether we are pushing now
*/
this.pushing = ko.observable(false);
/**
* a text describing what we are doing now
*/
this.lastLog = ko.observable("");
this.running = ko.observable(false);
/**
* represents if there is any changes in the draft after last push
* @type {boolean}
*/
this.draftHasChanges = false;
// monitor the changes in draft
monitor.listeners.push(() => this.draftHasChanges = true);
}
resetBase(base) {
let running = this.running();
if (running) this.stop();
// keep the changes before resetting the outgoing
this.draftHasChanges |= this.outgoing !== this.base;
this.base = this.outgoing = base;
if (running) this.start();
}
/**
* return the draft snapshot
* @return {Object}
*/
get draft() {
return this.inventory.toJson();
}
set draft(draft) {
this.inventory.fromJson(draft);
}
/**
* start the whole sharing process
*/
start() {
if (this.running()) {
return;
}
this.log("sharing");
this.fetchingThread.start();
this.pushingThread.start();
this.running(true);
}
fetch(callback) {
this.serviceObject.httpPollDeployInventory(this.inventory.name(), this.base.version + 1, 30000, callback);
}
fetched(response) {
/**
* @type {{changes: {id: String}[], version: String, sharedBy: String}}
*/
let latest = response.responseJSON;
if (!latest) {
throw "invalid response from server"
}
if (latest.version <= this.base.version) {
// timed out or got an old version, just ignore it
return;
}
/**
* if the draft has changed after merge:
* 1. there are changes before merge
* 2. the outgoing is merged into draft, which has changes
*/
let draftHasChanges = this.draftHasChanges;
/**
* The snapshot of the draft.
* Since all changes are made based on the outgoing and if any changes are made,
* the draftHashChanges must be true, so we can reuse outgoing if draftHasChanges is false.
* This can also solve another problem:
* Since some changes on draft will not change the draftHasChanges, so in this case, after we got a new version
* the invisible changes will be reset to the latest, to eventually let the draft be in sync.
*/
let draft = draftHasChanges ? this.draft : this.outgoing;
let newDraft;
if (this.outgoing === this.base) { // success case #1, #5, #6
// We have just successfully pushed a change to server,
// and the it is the first time after that push,
// and we got the next version of the local version from server,
// and our change is included in that version,
// so it can be proved that this version is just what we have pushed.
// In this case, ignore it is safe.
if (latest.version === this.base.version + 1 && this.changeId && this.findChangeById(latest, this.changeId)) {
newDraft = null; // no merge, no update
} else {
newDraft = this.merge(latest, draft, this.base);
this.log("new changes received");
}
} else if (this.findChangeById(latest, this.changeId)) { // success case #2
// This is the second case where we can skip merge:
// The latest version is the next version of local version, and it contains the last pushed change.
if (latest.version === this.outgoing.version + 1) {
newDraft = null; // no merge, no update
} else {
newDraft = this.merge(latest, draft, this.outgoing);
draftHasChanges = true;
this.log("new changes merged");
}
} else { // rejected case #3, #4
newDraft = this.merge(latest, draft, this.base);
draftHasChanges = true;
this.log("conflict resolved");
}
// since the version is changed, so the change id for the previous version is not valid.
this.changeId = null;
this.base = this.outgoing = latest;
// this is the only place to upgrade local version
this.inventory.version = latest.version;
if (newDraft != null) {
this.draft = newDraft;
}
this.pushing(false);
this.draftHasChanges = draftHasChanges;
if (!latest.sharedBy) {
this.stop();
}
}
push(callback) {
if (!this.draftHasChanges && this.outgoing === this.base) return true;
this.outgoing = this.draft;
// set to true since we have made a snapshot of the draft
// this is the only place we clear this mark
// if some time later, the push request failed, this mark must be set
this.draftHasChanges = false;
this.changeId = generateUUID();
this.pushing(true);
this.serviceObject.httpSaveDeployInventory(JSON.stringify(this.outgoing), this.changeId, callback);
}
pushed(response) {
if (this.outgoing === this.base) { // case #2, #3, #4
return; // do nothing
}
let result = response.responseJSON;
if (!result) {
throw "invalid response from server"
}
if (result.status.code === 200) { // case #1, #6. actually case #6 is not concerned at this time
this.base = this.outgoing;
this.log("pushed");
if (result.data) this.inventory.changes(result.data);
console.info("snapshot pushed. version = " + this.outgoing.version);
} else { // case #5
this.outgoing = this.base;
// what we have tried to push is given up, so this mark is set to enable next retrying
this.draftHasChanges = true;
if (result.status.code === 410) {
this.log("retry pushing deal to conflict");
console.info("conflict occurred on server while pushing snapshot");
} else {
this.log("error occurred while pushing!");
throw "failed to push snapshot to server: " + result.status.code + " " + result.status.message;
}
}
this.pushing(false);
}
stop() {
if (!this.running()) {
return;
}
this.pushingThread.stop();
this.fetchingThread.stop();
if (this.outgoing !== this.base) {
this.outgoing = this.base;
}
this.log("");
this.running(false);
}
findChangeById(snapshot, changeId) {
for (let i = 0; i < snapshot.changes.length; i++) {
let change = snapshot.changes[i];
if (change.id === changeId) return change;
}
}
/**
* Apply what we changed from origin snapshot to draft snapshot on latest snapshot
* This is the implementation of the formula described above:
*
* result = latest + (draft - origin)
*
* @param latest changes will be applied on latest
* @param draft draft snapshot
* @param origin origin snapshot
* @return {Object}
*/
merge(latest, draft, origin) {
// nothing changed
if (draft === origin) {
return latest;
}
// draft or origin is null
if (draft === null || draft === undefined) {
if (origin === null || origin === undefined) {
return latest;
} else {
return draft;
}
} else if (origin === null || origin === undefined) {
return draft;
} if (latest === null || latest === undefined) {
return latest;
}
// type unmatched
if (typeof draft !== typeof origin || typeof draft !== typeof latest) {
return draft;
}
if (typeof draft !== "object") {
return draft;
}
// one is array but another is not
if (Array.isArray(draft) !== Array.isArray(origin) || Array.isArray(draft) !== Array.isArray(latest)) {
return draft;
}
let snapshot, p;
// both are not array
if (!Array.isArray(draft)) {
snapshot = {};
for (p in draft) {
if (draft.hasOwnProperty(p)) {
snapshot[p] = this.merge(latest[p], draft[p], origin[p]);
}
}
for (p in latest) {
if (latest.hasOwnProperty(p) && !draft.hasOwnProperty(p)) {
snapshot[p] = this.merge(latest[p], undefined, origin[p]);
}
}
return snapshot;
}
// the last case, both are arrays
let i, s;
let originJoin = draft.arrayInnerJoin(origin);
let latestJoin = draft.arrayInnerJoin(latest);
let originMatch = originJoin.left, latestMatch = latestJoin.left, matchLatest = latestJoin.right, pairs = [];
for (i = 0; i < draft.length; i++) {
if (latestMatch[i] === undefined) {
if (originMatch[i] === undefined) { // created by local
s = draft[i];
} else { // dropped by server
s = undefined;
}
} else {
if (originMatch[i] === undefined) { // created both by local and server
s = this.merge(latest[latestMatch[i]], draft[i], undefined);
} else { // normal case
s = this.merge(latest[latestMatch[i]], draft[i], origin[originMatch[i]]);
}
}
if (s !== undefined && s !== null) {
pairs.push({i: i, s: s});
}
}
for (i = 0; i < latest.length; i++) {
if (matchLatest[i] === undefined) { // created by server
pairs.push({j: i, s: latest[i]});
}
}
// do our best to keep the order of array made by remote server as well as local's
pairs.sort(function (a, b) {
if (a.i !== undefined && b.i !== undefined) {
if (originMatch[a.i] !== undefined && originMatch[b.i] !== undefined) {
if (latestMatch[a.i] !== undefined && latestMatch[b.i] !== undefined) { // both exists
// if we do not change the order, use the order of made by server
if (a.i < b.i === originMatch[a.i] < originMatch[b.i]) {
return latestMatch[a.i] < latestMatch[b.i] ? -1 : 1;
}
}
}
return a.i < b.i ? -1 : 1;
} else if (a.j !== undefined && b.j !== undefined) {
// both created by server
return a.j < b.j ? -1 : 1;
} else if (a.i !== undefined && b.j !== undefined && latestMatch[a.i] !== undefined) {
// one in latest with one crated by server
return latestMatch[a.i] < b.j ? -1 : 1;
} else if (a.j !== undefined && b.i !== undefined && latestMatch[b.i] !== undefined) {
// one crated by server with one in latest
return a.j < latestMatch[b.i] ? -1 : 1;
} else {
// one created by local with one created by server
return 0;
}
});
snapshot = [];
for (i = 0; i < pairs.length; i++) {
snapshot.push(pairs[i].s);
}
return snapshot;
}
log(s) {
this.lastLog(s);
}
} |
JavaScript | class TimerThread {
/**
* @param instance {Object} the instance of this while calling runnable and callback
* @param runnable {Function} the function to run in the thread, the sole argument of this function
* is a callback used in timer thread and should be passed as the callback of your real function.
* returning true means you want to use sync mode, the callback will not be called in this case.
* @param callback {Function} callback called after the runnable's callback is called
* @param interval {Number} interval of the time after a callback is called before another runnable is launched.
* @param timeout {Number} how long before a call is treated as timeout
*/
constructor(instance, runnable, callback, interval, timeout) {
this.instance = instance;
this.runnable = runnable;
this.callback = callback;
this.interval = interval === undefined || interval < 0 ? 0 : interval;
this.tickInverval = 100;
this.timeoutInterval = timeout === undefined ? -1 : timeout;
this.timer = null;
this.processing = false;
let now = new Date().getTime();
this.processBeginTime = now;
this.idleBeginTime = now;
this.loops = 0;
}
start() {
if (this.timer) {
this.stop();
}
this.idleBeginTime = new Date().getTime() - this.interval; // avoid first wait
this.timer = setInterval(this.tick.bind(this), this.tickInverval);
}
stop() {
if (!this.timer) return;
clearInterval(this.timer);
this.processing = false;
this.loops++; // avoid future callbacks
}
tick() {
this.loop();
}
loop() {
const now = new Date().getTime();
if (this.processing) { // runnable is already started
if (this.timeoutInterval < 0 || now - this.processBeginTime < this.timeoutInterval) {
return; // do not timeout, continue waiting
}
this.processing = false; // timeout
}
if (now - this.idleBeginTime < this.interval) {
return; // wait the entire interval
}
let loops = ++this.loops;
this.processBeginTime = new Date().getTime();
let sync = false;
try {
sync = this.runnable.call(this.instance, (... args) => {
if (this.loops !== loops) return; // avoid to call older callbacks
try {
this.callback.apply(this.instance, args);
this.processing = false;
this.idleBeginTime = new Date().getTime();
this.loop();
} catch (e) {
console.error(e);
}
});
if (sync) {
this.processing = false;
this.idleBeginTime = new Date().getTime();
} else {
this.processing = true;
}
} catch (e) {
console.error(e);
// exception is treated as async
// so next retry will come after timeout
}
}
} |
JavaScript | class ViewModel {
/**
* @param {EntityChangeMonitor} monitor
*/
constructor(monitor) {
this.monitor = monitor;
}
/**
* add extenders to
* @param observable
* @return {Function}
*/
withMonitor(observable) {
if (this.monitor) {
observable = observable.extend({audit: value => this.monitor.onchange(this, name, value)});
}
return observable;
}
showElement(e) {
jQuery(e).hide().fadeIn();
}
hideElement(e) {
jQuery(e).fadeOut(() => jQuery(e).remove());
}
} |
JavaScript | class Settings {
constructor() {
this.bindEvents();
}
/**
* Attaches events to various controls
*/
bindEvents() {
// Mute setting
document.getElementById('mute').addEventListener('change', e => {this.mute(e.target.checked)});
// Axes setting
document.getElementById('axes').addEventListener('change', e => {this.showAxes(e.target.checked)});
}
/**
* Sets the mute setting of the config
* @param boolean true or false
*/
mute(boolean) {
Config.settings.mute = boolean;
}
/**
* Creates or deletes the assist axes in the scene
* @param boolean true or false
*/
showAxes(boolean) {
if (boolean) {
Config.createAxes();
} else {
for (let axis of Config.axes)
axis.dispose();
}
}
} |
JavaScript | class LinesGeometry extends BaseLinesGeometry {
startUpdate() {
return true;
}
computeBoundingSphere() {
const { boundingBox } = this;
// Build bounding sphere
let radiusSquared = 0.0;
const center = new THREE.Vector3();
if (boundingBox) {
boundingBox.getCenter(center);
}
const positions = this._positions;
const sphere = this.boundingSphere || new THREE.Sphere();
const size = this._positions.length;
const pos = new THREE.Vector3();
const posSize = this.getPositionSize();
for (let i = 0; i < size; i += posSize) {
pos.set(positions[i], positions[i + 1], positions[i + 2]);
const lengthSquared = center.distanceToSquared(pos);
if (radiusSquared < lengthSquared) {
radiusSquared = lengthSquared;
}
}
sphere.set(center, Math.sqrt(radiusSquared));
this.boundingSphere = sphere;
}
computeBoundingBox() {
const positions = this._positions;
const box = new THREE.Box3();
const size = this._positions.length;
const tmpVec = new THREE.Vector3();
const posSize = this.getPositionSize();
for (let i = 0; i < size; i += posSize) {
tmpVec.set(positions[i], positions[i + 1], positions[i + 2]);
box.expandByPoint(tmpVec);
}
this.boundingBox = box;
}
finalize() {
this.finishUpdate();
// TODO compute bounding box?
this.computeBoundingSphere();
}
} |
JavaScript | class Service
{
constructor(id, name, socket)
{
this.id = id;
this.name = name;
this.socket = socket;
this.maxRetries = 3;
this.detach = false;
}
set lastcheck(check){
this.maxRetries = 3; //resets the retries as well. Because it's alive :)
this.lastchecktime = check;
}
get lastcheck(){return this.lastchecktime;}
//give the client 3 tries before it's considered as crashed.
get crashed(){
this.maxRetries--;
return !(this.maxRetries>0)
}
} |
JavaScript | class BackgroundHandler extends CustomEventTarget {
/**
* Creates a new Background Handler and starts listening to new connections.
*
* @param {object} exposedData An object containing all properties and methods to be exposed to the content scripts
* @param {object} options Currently unused. An object that will customize how this class works.
*/
constructor(exposedData = {}, options = {}) {
super();
this.scriptConnections = new Map(); // script-id --> connection
this.exposedData = exposedData;
this.errorCallback = options.errorCallback ?? null;
chrome.runtime.onConnect.addListener( (port) => this.handleNewConnection(port) );
}
/**
* Handle a new incoming connection
*
* @param {chrome.runtime.Port} port The newly created connection to a content script
*/
handleNewConnection(port) {
if (!this.isInternalConnection(port)) return;
let [name, scriptId] = this.parsePortName(port);
let tabId = port.sender?.tab?.id ?? null;
if (tabId == -1) tabId = null;
// If the script id is already taken, terminate the connection and send an error
if (this.scriptConnections.get(scriptId)) {
port.disconnect();
return this.handleError(ERRORS.ID_TAKEN, scriptId);
}
// In the background script, there is no tab-id associated
let connectionOptions = { hasTabId: false };
let connection = new Connection(port, this.exposedData, connectionOptions);
connection.addListener("disconnect", () => this.disconnectScript(name, tabId) );
this.scriptConnections.set(scriptId, connection);
// Fire the connection event
this.fireEvent("connectionreceived", {
scriptId: name,
tabId
});
}
/**
* Checks if the connection was initialized from this library
*
* @param {chrome.runtime.Port} port The connection
*/
isInternalConnection(port) {
return port.name.startsWith(CONNECTION_PREFIX) ||
port.name.startsWith(CONNECTION_PREFIX_NOTAB);
}
/**
* Check if the connection should not be related to any chrome tab
*
* @param {chrome.runtime.Port} port The connection
*/
isTabAgnostic(port) {
return port.name.startsWith(CONNECTION_PREFIX_NOTAB);
}
/**
* Parse the port name and extracts a unique identifier (the script id).
*
* @param {chrome.runtime.Port} port The connection
* @returns {string} The script id
*/
parsePortName(port) {
let scriptId, tabId, completeScriptId;
if (this.isTabAgnostic(port)) {
scriptId = port.name.substr(CONNECTION_PREFIX_NOTAB.length);
}
else {
scriptId = port.name.substr(CONNECTION_PREFIX.length);
tabId = port.sender.tab.id;
}
completeScriptId = this.generateScriptId(scriptId, tabId);
return [scriptId, completeScriptId];
}
/**
* Generate a script id to be used within the connections map
*
* @param {string} name
* @param {number} tabId
* @returns {string} The generated script id
*/
generateScriptId(name, tabId) {
let scriptId = name;
if (tabId) {
scriptId += `-${tabId}`;
}
return scriptId;
}
/**
* Disconnect a script based on its id
*
* @param {string} id
*/
disconnectScript(name, tabId) {
let id = this.generateScriptId(name, tabId);
let conn = this.scriptConnections.get(id);
// Disconnect the script if it hasn't disconnected yet
if (conn) {
conn.disconnect();
}
// Remove the script in the connections map
this.scriptConnections.delete(id);
// Fire the disconnection event
this.fireEvent("connectionended", {
scriptId: name,
tabId
});
}
/**
* Get the connection to a script based on its id and the chrome tab that it's associated with.
*
* @async
* @param {string} scriptId The id of the script to which you want to get a connection
* @param {string} tabId The id of the chrome tab this scripts relates to
* @return {Promise<Proxy>} The connection proxy
*/
async getScriptConnection(scriptId, tabId) {
let specificScriptId = scriptId;
if (tabId) specificScriptId += `-${tabId}`;
let connection = this.scriptConnections.get(specificScriptId);
if (!connection) {
this.handleError(ERRORS.NO_CONNECTION, scriptId, tabId);
return null;
}
let proxy = await connection.getProxy();
return proxy;
}
/**
* Check if a script with a specific id associated to a specific tab has made a connection to the background page.
*
* @param {string} scriptId
* @param {string} tabId
* @returns Whether the script is connected
*/
hasConnectedScript(scriptId, tabId) {
let specificScriptId = scriptId;
if (tabId) specificScriptId += `-${tabId}`;
return this.scriptConnections.has(specificScriptId);
}
/**
* Handle the errors thrown within the class
*
* @param {Error} error
* @param {...any} args
* @returns
*/
handleError(error, ...args) {
if (this.errorCallback) {
this.errorCallback({
errorId: error.id,
error: error.getText(...args)
});
return;
}
console.error(error.getText(...args));
}
} |
JavaScript | class YQt extends YSensor
{
constructor(obj_yapi,str_func)
{
//--- (generated code: YQt constructor)
super(obj_yapi, str_func);
/** @member {string} **/
this._className = 'Qt';
//--- (end of generated code: YQt constructor)
}
//--- (generated code: YQt implementation)
/**
* Retrieves a quaternion component for a given identifier.
* The identifier can be specified using several formats:
* <ul>
* <li>FunctionLogicalName</li>
* <li>ModuleSerialNumber.FunctionIdentifier</li>
* <li>ModuleSerialNumber.FunctionLogicalName</li>
* <li>ModuleLogicalName.FunctionIdentifier</li>
* <li>ModuleLogicalName.FunctionLogicalName</li>
* </ul>
*
* This function does not require that the quaternion component is online at the time
* it is invoked. The returned object is nevertheless valid.
* Use the method YQt.isOnline() to test if the quaternion component is
* indeed online at a given time. In case of ambiguity when looking for
* a quaternion component by logical name, no error is notified: the first instance
* found is returned. The search is performed first by hardware name,
* then by logical name.
*
* If a call to this object's is_online() method returns FALSE although
* you are certain that the matching device is plugged, make sure that you did
* call registerHub() at application initialization time.
*
* @param func {string} : a string that uniquely characterizes the quaternion component
*
* @return {YQt} a YQt object allowing you to drive the quaternion component.
*/
static FindQt(func)
{
/** @type {YFunction} **/
let obj;
obj = YFunction._FindFromCache('Qt', func);
if (obj == null) {
obj = new YQt(YAPI, func);
YFunction._AddToCache('Qt', func, obj);
}
return obj;
}
/**
* Retrieves a quaternion component for a given identifier in a YAPI context.
* The identifier can be specified using several formats:
* <ul>
* <li>FunctionLogicalName</li>
* <li>ModuleSerialNumber.FunctionIdentifier</li>
* <li>ModuleSerialNumber.FunctionLogicalName</li>
* <li>ModuleLogicalName.FunctionIdentifier</li>
* <li>ModuleLogicalName.FunctionLogicalName</li>
* </ul>
*
* This function does not require that the quaternion component is online at the time
* it is invoked. The returned object is nevertheless valid.
* Use the method YQt.isOnline() to test if the quaternion component is
* indeed online at a given time. In case of ambiguity when looking for
* a quaternion component by logical name, no error is notified: the first instance
* found is returned. The search is performed first by hardware name,
* then by logical name.
*
* @param yctx {YAPIContext} : a YAPI context
* @param func {string} : a string that uniquely characterizes the quaternion component
*
* @return {YQt} a YQt object allowing you to drive the quaternion component.
*/
static FindQtInContext(yctx,func)
{
/** @type {YFunction} **/
let obj;
obj = YFunction._FindFromCacheInContext(yctx, 'Qt', func);
if (obj == null) {
obj = new YQt(yctx, func);
YFunction._AddToCache('Qt', func, obj);
}
return obj;
}
/**
* Continues the enumeration of quaternion components started using yFirstQt().
*
* @return {YQt} a pointer to a YQt object, corresponding to
* a quaternion component currently online, or a null pointer
* if there are no more quaternion components to enumerate.
*/
nextQt()
{
/** @type {object} **/
let resolve = this._yapi.imm_resolveFunction(this._className, this._func);
if(resolve.errorType != YAPI.SUCCESS) return null;
/** @type {string|null} **/
let next_hwid = this._yapi.imm_getNextHardwareId(this._className, resolve.result);
if(next_hwid == null) return null;
return YQt.FindQtInContext(this._yapi, next_hwid);
}
/**
* Starts the enumeration of quaternion components currently accessible.
* Use the method YQt.nextQt() to iterate on
* next quaternion components.
*
* @return {YQt} a pointer to a YQt object, corresponding to
* the first quaternion component currently online, or a null pointer
* if there are none.
*/
static FirstQt()
{
/** @type {string|null} **/
let next_hwid = YAPI.imm_getFirstHardwareId('Qt');
if(next_hwid == null) return null;
return YQt.FindQt(next_hwid);
}
/**
* Starts the enumeration of quaternion components currently accessible.
* Use the method YQt.nextQt() to iterate on
* next quaternion components.
*
* @param yctx {YAPIContext} : a YAPI context.
*
* @return {YQt} a pointer to a YQt object, corresponding to
* the first quaternion component currently online, or a null pointer
* if there are none.
*/
static FirstQtInContext(yctx)
{
/** @type {string|null} **/
let next_hwid = yctx.imm_getFirstHardwareId('Qt');
if(next_hwid == null) return null;
return YQt.FindQtInContext(yctx, next_hwid);
}
//--- (end of generated code: YQt implementation)
} |
JavaScript | class YGyro extends YSensor
{
constructor(obj_yapi,str_func)
{
//--- (generated code: YGyro constructor)
super(obj_yapi, str_func);
/** @member {string} **/
this._className = 'Gyro';
/** @member {number} **/
this._bandwidth = YGyro.BANDWIDTH_INVALID;
/** @member {number} **/
this._xValue = YGyro.XVALUE_INVALID;
/** @member {number} **/
this._yValue = YGyro.YVALUE_INVALID;
/** @member {number} **/
this._zValue = YGyro.ZVALUE_INVALID;
/** @member {number} **/
this._qt_stamp = 0;
/** @member {YQt} **/
this._qt_w = null;
/** @member {YQt} **/
this._qt_x = null;
/** @member {YQt} **/
this._qt_y = null;
/** @member {YQt} **/
this._qt_z = null;
/** @member {number} **/
this._w = 0;
/** @member {number} **/
this._x = 0;
/** @member {number} **/
this._y = 0;
/** @member {number} **/
this._z = 0;
/** @member {number} **/
this._angles_stamp = 0;
/** @member {number} **/
this._head = 0;
/** @member {number} **/
this._pitch = 0;
/** @member {number} **/
this._roll = 0;
/** @member {function} **/
this._quatCallback = null;
/** @member {function} **/
this._anglesCallback = null;
//--- (end of generated code: YGyro constructor)
}
//--- (generated code: YGyro implementation)
imm_parseAttr(name, val)
{
switch(name) {
case 'bandwidth':
this._bandwidth = parseInt(val);
return 1;
case 'xValue':
this._xValue = Math.round(val * 1000.0 / 65536.0) / 1000.0;
return 1;
case 'yValue':
this._yValue = Math.round(val * 1000.0 / 65536.0) / 1000.0;
return 1;
case 'zValue':
this._zValue = Math.round(val * 1000.0 / 65536.0) / 1000.0;
return 1;
}
return super.imm_parseAttr(name, val);
}
/**
* Returns the measure update frequency, measured in Hz (Yocto-3D-V2 only).
*
* @return {number} an integer corresponding to the measure update frequency, measured in Hz (Yocto-3D-V2 only)
*
* On failure, throws an exception or returns YGyro.BANDWIDTH_INVALID.
*/
async get_bandwidth()
{
/** @type {number} **/
let res;
if (this._cacheExpiration <= this._yapi.GetTickCount()) {
if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) {
return YGyro.BANDWIDTH_INVALID;
}
}
res = this._bandwidth;
return res;
}
/**
* Changes the measure update frequency, measured in Hz (Yocto-3D-V2 only). When the
* frequency is lower, the device performs averaging.
*
* @param newval {number} : an integer corresponding to the measure update frequency, measured in Hz
* (Yocto-3D-V2 only)
*
* @return {number} YAPI.SUCCESS if the call succeeds.
*
* On failure, throws an exception or returns a negative error code.
*/
async set_bandwidth(newval)
{
/** @type {string} **/
let rest_val;
rest_val = String(newval);
return await this._setAttr('bandwidth',rest_val);
}
/**
* Returns the angular velocity around the X axis of the device, as a floating point number.
*
* @return {number} a floating point number corresponding to the angular velocity around the X axis of
* the device, as a floating point number
*
* On failure, throws an exception or returns YGyro.XVALUE_INVALID.
*/
async get_xValue()
{
/** @type {number} **/
let res;
if (this._cacheExpiration <= this._yapi.GetTickCount()) {
if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) {
return YGyro.XVALUE_INVALID;
}
}
res = this._xValue;
return res;
}
/**
* Returns the angular velocity around the Y axis of the device, as a floating point number.
*
* @return {number} a floating point number corresponding to the angular velocity around the Y axis of
* the device, as a floating point number
*
* On failure, throws an exception or returns YGyro.YVALUE_INVALID.
*/
async get_yValue()
{
/** @type {number} **/
let res;
if (this._cacheExpiration <= this._yapi.GetTickCount()) {
if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) {
return YGyro.YVALUE_INVALID;
}
}
res = this._yValue;
return res;
}
/**
* Returns the angular velocity around the Z axis of the device, as a floating point number.
*
* @return {number} a floating point number corresponding to the angular velocity around the Z axis of
* the device, as a floating point number
*
* On failure, throws an exception or returns YGyro.ZVALUE_INVALID.
*/
async get_zValue()
{
/** @type {number} **/
let res;
if (this._cacheExpiration <= this._yapi.GetTickCount()) {
if (await this.load(this._yapi.defaultCacheValidity) != this._yapi.SUCCESS) {
return YGyro.ZVALUE_INVALID;
}
}
res = this._zValue;
return res;
}
/**
* Retrieves a gyroscope for a given identifier.
* The identifier can be specified using several formats:
* <ul>
* <li>FunctionLogicalName</li>
* <li>ModuleSerialNumber.FunctionIdentifier</li>
* <li>ModuleSerialNumber.FunctionLogicalName</li>
* <li>ModuleLogicalName.FunctionIdentifier</li>
* <li>ModuleLogicalName.FunctionLogicalName</li>
* </ul>
*
* This function does not require that the gyroscope is online at the time
* it is invoked. The returned object is nevertheless valid.
* Use the method YGyro.isOnline() to test if the gyroscope is
* indeed online at a given time. In case of ambiguity when looking for
* a gyroscope by logical name, no error is notified: the first instance
* found is returned. The search is performed first by hardware name,
* then by logical name.
*
* If a call to this object's is_online() method returns FALSE although
* you are certain that the matching device is plugged, make sure that you did
* call registerHub() at application initialization time.
*
* @param func {string} : a string that uniquely characterizes the gyroscope
*
* @return {YGyro} a YGyro object allowing you to drive the gyroscope.
*/
static FindGyro(func)
{
/** @type {YFunction} **/
let obj;
obj = YFunction._FindFromCache('Gyro', func);
if (obj == null) {
obj = new YGyro(YAPI, func);
YFunction._AddToCache('Gyro', func, obj);
}
return obj;
}
/**
* Retrieves a gyroscope for a given identifier in a YAPI context.
* The identifier can be specified using several formats:
* <ul>
* <li>FunctionLogicalName</li>
* <li>ModuleSerialNumber.FunctionIdentifier</li>
* <li>ModuleSerialNumber.FunctionLogicalName</li>
* <li>ModuleLogicalName.FunctionIdentifier</li>
* <li>ModuleLogicalName.FunctionLogicalName</li>
* </ul>
*
* This function does not require that the gyroscope is online at the time
* it is invoked. The returned object is nevertheless valid.
* Use the method YGyro.isOnline() to test if the gyroscope is
* indeed online at a given time. In case of ambiguity when looking for
* a gyroscope by logical name, no error is notified: the first instance
* found is returned. The search is performed first by hardware name,
* then by logical name.
*
* @param yctx {YAPIContext} : a YAPI context
* @param func {string} : a string that uniquely characterizes the gyroscope
*
* @return {YGyro} a YGyro object allowing you to drive the gyroscope.
*/
static FindGyroInContext(yctx,func)
{
/** @type {YFunction} **/
let obj;
obj = YFunction._FindFromCacheInContext(yctx, 'Gyro', func);
if (obj == null) {
obj = new YGyro(yctx, func);
YFunction._AddToCache('Gyro', func, obj);
}
return obj;
}
async _loadQuaternion()
{
/** @type {number} **/
let now_stamp;
/** @type {number} **/
let age_ms;
now_stamp = ((this._yapi.GetTickCount()) & (0x7FFFFFFF));
age_ms = (((now_stamp - this._qt_stamp)) & (0x7FFFFFFF));
if ((age_ms >= 10) || (this._qt_stamp == 0)) {
if (await this.load(10) != this._yapi.SUCCESS) {
return this._yapi.DEVICE_NOT_FOUND;
}
if (this._qt_stamp == 0) {
this._qt_w = YQt.FindQtInContext(this._yapi, this._serial+'.qt1');
this._qt_x = YQt.FindQtInContext(this._yapi, this._serial+'.qt2');
this._qt_y = YQt.FindQtInContext(this._yapi, this._serial+'.qt3');
this._qt_z = YQt.FindQtInContext(this._yapi, this._serial+'.qt4');
}
if (await this._qt_w.load(9) != this._yapi.SUCCESS) {
return this._yapi.DEVICE_NOT_FOUND;
}
if (await this._qt_x.load(9) != this._yapi.SUCCESS) {
return this._yapi.DEVICE_NOT_FOUND;
}
if (await this._qt_y.load(9) != this._yapi.SUCCESS) {
return this._yapi.DEVICE_NOT_FOUND;
}
if (await this._qt_z.load(9) != this._yapi.SUCCESS) {
return this._yapi.DEVICE_NOT_FOUND;
}
this._w = await this._qt_w.get_currentValue();
this._x = await this._qt_x.get_currentValue();
this._y = await this._qt_y.get_currentValue();
this._z = await this._qt_z.get_currentValue();
this._qt_stamp = now_stamp;
}
return this._yapi.SUCCESS;
}
async _loadAngles()
{
/** @type {number} **/
let sqw;
/** @type {number} **/
let sqx;
/** @type {number} **/
let sqy;
/** @type {number} **/
let sqz;
/** @type {number} **/
let norm;
/** @type {number} **/
let delta;
if (await this._loadQuaternion() != this._yapi.SUCCESS) {
return this._yapi.DEVICE_NOT_FOUND;
}
if (this._angles_stamp != this._qt_stamp) {
sqw = this._w * this._w;
sqx = this._x * this._x;
sqy = this._y * this._y;
sqz = this._z * this._z;
norm = sqx + sqy + sqz + sqw;
delta = this._y * this._w - this._x * this._z;
if (delta > 0.499 * norm) {
// singularity at north pole
this._pitch = 90.0;
this._head = Math.round(2.0 * 1800.0/Math.PI * Math.atan2(this._x,-this._w)) / 10.0;
} else {
if (delta < -0.499 * norm) {
// singularity at south pole
this._pitch = -90.0;
this._head = Math.round(-2.0 * 1800.0/Math.PI * Math.atan2(this._x,-this._w)) / 10.0;
} else {
this._roll = Math.round(1800.0/Math.PI * Math.atan2(2.0 * (this._w * this._x + this._y * this._z),sqw - sqx - sqy + sqz)) / 10.0;
this._pitch = Math.round(1800.0/Math.PI * Math.asin(2.0 * delta / norm)) / 10.0;
this._head = Math.round(1800.0/Math.PI * Math.atan2(2.0 * (this._x * this._y + this._z * this._w),sqw + sqx - sqy - sqz)) / 10.0;
}
}
this._angles_stamp = this._qt_stamp;
}
return this._yapi.SUCCESS;
}
/**
* Returns the estimated roll angle, based on the integration of
* gyroscopic measures combined with acceleration and
* magnetic field measurements.
* The axis corresponding to the roll angle can be mapped to any
* of the device X, Y or Z physical directions using methods of
* the class YRefFrame.
*
* @return {number} a floating-point number corresponding to roll angle
* in degrees, between -180 and +180.
*/
async get_roll()
{
await this._loadAngles();
return this._roll;
}
/**
* Returns the estimated pitch angle, based on the integration of
* gyroscopic measures combined with acceleration and
* magnetic field measurements.
* The axis corresponding to the pitch angle can be mapped to any
* of the device X, Y or Z physical directions using methods of
* the class YRefFrame.
*
* @return {number} a floating-point number corresponding to pitch angle
* in degrees, between -90 and +90.
*/
async get_pitch()
{
await this._loadAngles();
return this._pitch;
}
/**
* Returns the estimated heading angle, based on the integration of
* gyroscopic measures combined with acceleration and
* magnetic field measurements.
* The axis corresponding to the heading can be mapped to any
* of the device X, Y or Z physical directions using methods of
* the class YRefFrame.
*
* @return {number} a floating-point number corresponding to heading
* in degrees, between 0 and 360.
*/
async get_heading()
{
await this._loadAngles();
return this._head;
}
/**
* Returns the w component (real part) of the quaternion
* describing the device estimated orientation, based on the
* integration of gyroscopic measures combined with acceleration and
* magnetic field measurements.
*
* @return {number} a floating-point number corresponding to the w
* component of the quaternion.
*/
async get_quaternionW()
{
await this._loadQuaternion();
return this._w;
}
/**
* Returns the x component of the quaternion
* describing the device estimated orientation, based on the
* integration of gyroscopic measures combined with acceleration and
* magnetic field measurements. The x component is
* mostly correlated with rotations on the roll axis.
*
* @return {number} a floating-point number corresponding to the x
* component of the quaternion.
*/
async get_quaternionX()
{
await this._loadQuaternion();
return this._x;
}
/**
* Returns the y component of the quaternion
* describing the device estimated orientation, based on the
* integration of gyroscopic measures combined with acceleration and
* magnetic field measurements. The y component is
* mostly correlated with rotations on the pitch axis.
*
* @return {number} a floating-point number corresponding to the y
* component of the quaternion.
*/
async get_quaternionY()
{
await this._loadQuaternion();
return this._y;
}
/**
* Returns the x component of the quaternion
* describing the device estimated orientation, based on the
* integration of gyroscopic measures combined with acceleration and
* magnetic field measurements. The x component is
* mostly correlated with changes of heading.
*
* @return {number} a floating-point number corresponding to the z
* component of the quaternion.
*/
async get_quaternionZ()
{
await this._loadQuaternion();
return this._z;
}
/**
* Registers a callback function that will be invoked each time that the estimated
* device orientation has changed. The call frequency is typically around 95Hz during a move.
* The callback is invoked only during the execution of ySleep or yHandleEvents.
* This provides control over the time when the callback is triggered.
* For good responsiveness, remember to call one of these two functions periodically.
* To unregister a callback, pass a null pointer as argument.
*
* @param callback {function} : the callback function to invoke, or a null pointer.
* The callback function should take five arguments:
* the YGyro object of the turning device, and the floating
* point values of the four components w, x, y and z
* (as floating-point numbers).
* @noreturn
*/
async registerQuaternionCallback(callback)
{
this._quatCallback = callback;
if (callback != null) {
if (await this._loadQuaternion() != this._yapi.SUCCESS) {
return this._yapi.DEVICE_NOT_FOUND;
}
await this._qt_w.set_userData(this);
await this._qt_x.set_userData(this);
await this._qt_y.set_userData(this);
await this._qt_z.set_userData(this);
await this._qt_w.registerValueCallback(yInternalGyroCallback);
await this._qt_x.registerValueCallback(yInternalGyroCallback);
await this._qt_y.registerValueCallback(yInternalGyroCallback);
await this._qt_z.registerValueCallback(yInternalGyroCallback);
} else {
if (!(this._anglesCallback != null)) {
await this._qt_w.registerValueCallback(null);
await this._qt_x.registerValueCallback(null);
await this._qt_y.registerValueCallback(null);
await this._qt_z.registerValueCallback(null);
}
}
return 0;
}
/**
* Registers a callback function that will be invoked each time that the estimated
* device orientation has changed. The call frequency is typically around 95Hz during a move.
* The callback is invoked only during the execution of ySleep or yHandleEvents.
* This provides control over the time when the callback is triggered.
* For good responsiveness, remember to call one of these two functions periodically.
* To unregister a callback, pass a null pointer as argument.
*
* @param callback {function} : the callback function to invoke, or a null pointer.
* The callback function should take four arguments:
* the YGyro object of the turning device, and the floating
* point values of the three angles roll, pitch and heading
* in degrees (as floating-point numbers).
* @noreturn
*/
async registerAnglesCallback(callback)
{
this._anglesCallback = callback;
if (callback != null) {
if (await this._loadQuaternion() != this._yapi.SUCCESS) {
return this._yapi.DEVICE_NOT_FOUND;
}
await this._qt_w.set_userData(this);
await this._qt_x.set_userData(this);
await this._qt_y.set_userData(this);
await this._qt_z.set_userData(this);
await this._qt_w.registerValueCallback(yInternalGyroCallback);
await this._qt_x.registerValueCallback(yInternalGyroCallback);
await this._qt_y.registerValueCallback(yInternalGyroCallback);
await this._qt_z.registerValueCallback(yInternalGyroCallback);
} else {
if (!(this._quatCallback != null)) {
await this._qt_w.registerValueCallback(null);
await this._qt_x.registerValueCallback(null);
await this._qt_y.registerValueCallback(null);
await this._qt_z.registerValueCallback(null);
}
}
return 0;
}
async _invokeGyroCallbacks(qtIndex,qtValue)
{
switch(qtIndex - 1) {
case 0:
this._w = qtValue;
break;
case 1:
this._x = qtValue;
break;
case 2:
this._y = qtValue;
break;
case 3:
this._z = qtValue;
break;
}
if (qtIndex < 4) {
return 0;
}
this._qt_stamp = ((this._yapi.GetTickCount()) & (0x7FFFFFFF));
if (this._quatCallback != null) {
await this._quatCallback(this, this._w, this._x, this._y, this._z);
}
if (this._anglesCallback != null) {
await this._loadAngles();
await this._anglesCallback(this, this._roll, this._pitch, this._head);
}
return 0;
}
/**
* Continues the enumeration of gyroscopes started using yFirstGyro().
*
* @return {YGyro} a pointer to a YGyro object, corresponding to
* a gyroscope currently online, or a null pointer
* if there are no more gyroscopes to enumerate.
*/
nextGyro()
{
/** @type {object} **/
let resolve = this._yapi.imm_resolveFunction(this._className, this._func);
if(resolve.errorType != YAPI.SUCCESS) return null;
/** @type {string|null} **/
let next_hwid = this._yapi.imm_getNextHardwareId(this._className, resolve.result);
if(next_hwid == null) return null;
return YGyro.FindGyroInContext(this._yapi, next_hwid);
}
/**
* Starts the enumeration of gyroscopes currently accessible.
* Use the method YGyro.nextGyro() to iterate on
* next gyroscopes.
*
* @return {YGyro} a pointer to a YGyro object, corresponding to
* the first gyro currently online, or a null pointer
* if there are none.
*/
static FirstGyro()
{
/** @type {string|null} **/
let next_hwid = YAPI.imm_getFirstHardwareId('Gyro');
if(next_hwid == null) return null;
return YGyro.FindGyro(next_hwid);
}
/**
* Starts the enumeration of gyroscopes currently accessible.
* Use the method YGyro.nextGyro() to iterate on
* next gyroscopes.
*
* @param yctx {YAPIContext} : a YAPI context.
*
* @return {YGyro} a pointer to a YGyro object, corresponding to
* the first gyro currently online, or a null pointer
* if there are none.
*/
static FirstGyroInContext(yctx)
{
/** @type {string|null} **/
let next_hwid = yctx.imm_getFirstHardwareId('Gyro');
if(next_hwid == null) return null;
return YGyro.FindGyroInContext(yctx, next_hwid);
}
static imm_Const()
{
return Object.assign(super.imm_Const(), {
BANDWIDTH_INVALID : YAPI.INVALID_INT,
XVALUE_INVALID : YAPI.INVALID_DOUBLE,
YVALUE_INVALID : YAPI.INVALID_DOUBLE,
ZVALUE_INVALID : YAPI.INVALID_DOUBLE
});
}
//--- (end of generated code: YGyro implementation)
} |
JavaScript | class Constraint extends Model {
/**
* get ViewModel class bind with Model
* @return {ViewModel} - ViewModel class
*/
getViewModel() {
return require('../vm/Constraint');
}
} |
JavaScript | class CRX3Stream extends WriteStream {
constructor (path, options) {
if (!options && typeof path === 'object') {
options = path;
path = null;
}
if (path && typeof path === 'string') {
options = options || {};
options.crxPath = path;
}
const cfg = config(options);
super(path || cfg.crxPath, options);
this.setDefaultEncoding('binary');
this.pos = this.pos || 0;
/**
* @name module:crx3/lib/crx3stream.CRX3Stream~crx
* @type {module:crx3/lib/crx3stream.CRX3StreamState}
*/
this.crx = new CRX3StreamState(cfg, this.pos);
}
/* eslint-disable no-underscore-dangle */
_write (chunk, encoding, callback) {
if (this.crx.error) {
process.nextTick(callback, this.crx.error);
return;
}
if (!this.crx.sign) {
this.crxInit(() => this._write(chunk, encoding, callback));
return;
}
this.crx.sign.update(chunk, encoding);
super._write(chunk, encoding, callback);
}
_writev (chunks, callback) {
if (this.crx.error) {
process.nextTick(callback, this.crx.error);
return;
}
if (!this.crx.sign) {
this.crxInit(() => this._writev(chunks, callback));
return;
}
for (var i = 0, max = chunks.length; i < max; i++) {
this.crx.sign.update(chunks[i].chunk, chunks[i].encoding);
}
super._writev(chunks, callback);
}
_final (callback) {
if (this.crx.error) {
process.nextTick(callback, this.crx.error);
return;
}
this.crxFinish(callback);
}
/**
* @private
* @param {Function} callback
*/
crxInit (callback) {
this.crx.keys = keypair(this.crx.cfg.keyPath);
this.crx.appId = createCrxId(this.crx.keys.publicKey);
this.crx.encodedAppId = encodeAppId(this.crx.appId);
this.crx.signedHeaderData = createSignedHeaderData(this.crx.appId);
this.crx.sign = createSign(this.crx.signedHeaderData);
const fauxHeader = createCRXFileHeader(this.crx.keys, this.crx.signedHeaderData, createSign(this.crx.signedHeaderData));
this.pos = this.crx.pos + fauxHeader.length;
callback();
}
/**
* @private
* @param {Function} callback
*/
crxFinish (callback) {
if (!this.crx.sign) {
// Finishing before any write happened, means some error, so we should simply return early.
callback();
return;
}
const final = err => {
callback(err);
process.nextTick(() => this.crx = null); // eslint-disable-line no-return-assign
};
const done2 = typeof super._final === 'function' ? err => super._final(err2 => final(err || err2)) : final;
const done1 = err => fdatasync(this.fd, err2 => done2(err || err2));
this.pos = this.crx.pos;
super._write(createCRXFileHeader(this.crx.keys, this.crx.signedHeaderData, this.crx.sign), 'binary', done1);
}
/* eslint-enable no-underscore-dangle */
} |
JavaScript | class TextTrack extends Track {
constructor(options = {}) {
if (!options.tech) {
throw new Error('A tech was not provided.');
}
const settings = merge(options, {
kind: TextTrackKind[options.kind] || 'subtitles',
language: options.language || options.srclang || ''
});
let mode = TextTrackMode[settings.mode] || 'disabled';
const default_ = settings.default;
if (settings.kind === 'metadata' || settings.kind === 'chapters') {
mode = 'hidden';
}
// on IE8 this will be a document element
// for every other browser this will be a normal object
const tt = super(settings);
tt.tech_ = settings.tech;
if (browser.IS_IE8) {
for (const prop in TextTrack.prototype) {
if (prop !== 'constructor') {
tt[prop] = TextTrack.prototype[prop];
}
}
}
tt.cues_ = [];
tt.activeCues_ = [];
const cues = new TextTrackCueList(tt.cues_);
const activeCues = new TextTrackCueList(tt.activeCues_);
let changed = false;
const timeupdateHandler = Fn.bind(tt, function() {
// Accessing this.activeCues for the side-effects of updating itself
// due to it's nature as a getter function. Do not remove or cues will
// stop updating!
/* eslint-disable no-unused-expressions */
this.activeCues;
/* eslint-enable no-unused-expressions */
if (changed) {
this.trigger('cuechange');
changed = false;
}
});
if (mode !== 'disabled') {
tt.tech_.on('timeupdate', timeupdateHandler);
}
Object.defineProperty(tt, 'default', {
get() {
return default_;
},
set() {}
});
Object.defineProperty(tt, 'mode', {
get() {
return mode;
},
set(newMode) {
if (!TextTrackMode[newMode]) {
return;
}
mode = newMode;
if (mode === 'showing') {
this.tech_.on('timeupdate', timeupdateHandler);
}
this.trigger('modechange');
}
});
Object.defineProperty(tt, 'cues', {
get() {
if (!this.loaded_) {
return null;
}
return cues;
},
set() {}
});
Object.defineProperty(tt, 'activeCues', {
get() {
if (!this.loaded_) {
return null;
}
// nothing to do
if (this.cues.length === 0) {
return activeCues;
}
const ct = this.tech_.currentTime();
const active = [];
for (let i = 0, l = this.cues.length; i < l; i++) {
const cue = this.cues[i];
if (cue.startTime <= ct && cue.endTime >= ct) {
active.push(cue);
} else if (cue.startTime === cue.endTime &&
cue.startTime <= ct &&
cue.startTime + 0.5 >= ct) {
active.push(cue);
}
}
changed = false;
if (active.length !== this.activeCues_.length) {
changed = true;
} else {
for (let i = 0; i < active.length; i++) {
if (this.activeCues_.indexOf(active[i]) === -1) {
changed = true;
}
}
}
this.activeCues_ = active;
activeCues.setCues_(this.activeCues_);
return activeCues;
},
set() {}
});
if (settings.src) {
tt.src = settings.src;
loadTrack(settings.src, tt);
} else {
tt.loaded_ = true;
}
return tt;
}
/**
* add a cue to the internal list of cues
*
* @param {Object} cue the cue to add to our internal list
* @method addCue
*/
addCue(cue) {
const tracks = this.tech_.textTracks();
if (tracks) {
for (let i = 0; i < tracks.length; i++) {
if (tracks[i] !== this) {
tracks[i].removeCue(cue);
}
}
}
this.cues_.push(cue);
this.cues.setCues_(this.cues_);
}
/**
* remvoe a cue from our internal list
*
* @param {Object} removeCue the cue to remove from our internal list
* @method removeCue
*/
removeCue(removeCue) {
let removed = false;
for (let i = 0, l = this.cues_.length; i < l; i++) {
const cue = this.cues_[i];
if (cue === removeCue) {
this.cues_.splice(i, 1);
removed = true;
}
}
if (removed) {
this.cues.setCues_(this.cues_);
}
}
} |
JavaScript | class WalletLinkerClient {
constructor({ httpUrl, wsUrl, web3 }) {
this.httpUrl = httpUrl
this.wsUrl = wsUrl
this.web3 = web3
this.netId = null
this.messagesWS = null
// code for linking via QR code
this.linkCode = null
// provider stuff
this.callbacks = {}
this.pendingCall = null
this.session = new Session()
this.session.load()
if (window) {
window.__linkWallet = (account, notifyWallet) => {
this.notifyWallet = notifyWallet
// TODO perhaps not anything if it's already linked to that account
this.link()
}
}
}
// Initiates linking of web3 provider to mobile wallet.
async link() {
return await this.generateLinkCode()
}
cancelLink() {
debug('cancelling link')
this.pending_call = null
this.linkCode = null
}
async unlink() {
const success = await this.post(`${API_PATH}/unlink`, {})
if (success) {
this.session.clear()
this.session.save()
}
}
// Handles prelinking and streaming of wallet messages.
async start() {
debug('start called')
this.netId = await this.web3.eth.net.getId()
// Handle prelink code from DApp if these is one.
const hash = window.location.hash
const search =
window.location.search || (hash && hash.substr(hash.indexOf('?')))
let prelinked = false
if (this.lastSearch !== search) {
this.lastSearch = search
const params = queryString.parse(search)
const plink = params['plink']
if (plink) {
// We do not handle wait for this promise to resolve, because prelinking
// changes internal state that will trigger a UI refresh anyway.
try {
debug('Trying to plink...')
await this.prelink(plink)
prelinked = true
} catch (e) {
console.error('prelink error:', e)
}
}
}
// If there is no prelink but we have a session, we're ready to stream
// messages from the server.
if (!prelinked && this.session.token) {
this.streamWalletMessages()
} else {
debug('not linked')
}
}
// Verify the prelink token with the linking server and update local link
// state based on server response.
async prelink(plink) {
debug('preLink called')
const [linkId, code, privKey] = plink.split('-')
if (linkId && code && privKey) {
debug(`prelinking: link id ${linkId} code ${code} private key ${privKey}`)
const url = `${API_PATH}/link-prelinked`
const resp = await this.post(url, {
code,
link_id: linkId,
priv_key: privKey
})
debug('prelink response:', resp)
const sessionToken = resp.session_token
this.session.linked = resp.linked
if (this.session.linked && privKey) {
localStorage.setItem(LOCAL_KEY_STORE, privKey)
}
if (this.session.token !== sessionToken) {
this.session.token = sessionToken
this.streamWalletMessages()
}
this.session.save()
} else {
debug('wallet already prelinked')
}
}
// Returns a serialized web3 transaction for the linking server.
createCall(method, params) {
return {
method,
net_id: this.netId,
params
}
}
// web3 provider function: returns linked accounts
getAccounts(callback) {
if (callback) {
callback(undefined, this.session.accounts)
} else {
return new Promise(resolve => {
resolve(this.session.accounts)
})
}
}
// web3 provider function: processes Ethereum transactions. If the wallet
// is unlinked, we generate a request for a QR code and embed the transaction
// in that request. If the wallet is already linked, we submit the transaction
// to the linking server, which forwards it to the mobile wallet for
// confirmation and execution.
processTransaction(txn, callback) {
debug('processTransaction called', txn)
txn.gasLimit = txn.gas
if (txn.from.toLowerCase() === PLACEHOLDER_ADDRESS.toLowerCase()) {
// If we're linking and performing a transaction, we can leave txn.from
// as undefined, and the mobile wallet will fill it in for us.
txn.from =
this.session.accounts.length > 0 ? this.session.accounts[0] : undefined
}
const callId = uuidv1()
this.callbacks[callId] = async data => callback(undefined, data.hash)
const call = this.createCall('processTransaction', { txn_object: txn })
if (!this.session.linked) {
// We're not linked, so the current transaction is pending a successful
// wallet link.
this.pendingCall = { callId, call }
// We let this async call run on its own. It's up to the UI to check for
// updates to linkCode and display it.
this.generateLinkCode()
return
}
// Forward the transaction to the mobile wallet via the linking server.
const callWalletUrl = `${API_PATH}/call-wallet/${this.session.token}`
const body = {
call_id: callId,
accounts: this.session.accounts,
call,
return_url: this.getReturnUrl()
}
debug(`sending transaction from`, call.params.txn_object.from)
const resp = this.post(callWalletUrl, body)
resp
.then(() => {})
.catch(err => {
delete this.callbacks[callId]
callback(err)
})
}
// Returns a web3 provider that forwards requests to the mobile wallet.
getProvider() {
const rpcUrl = this.web3.eth.net.currentProvider.host
const provider = ZeroClientProvider({
rpcUrl,
getAccounts: this.getAccounts.bind(this),
processTransaction: this.processTransaction.bind(this)
})
// Disable transaction validation, which interferes with our work.
const hookedWallet = provider._providers[6]
if (!hookedWallet.validateTransaction) {
console.error('The sub provider at [6] is NOT a hooked wallet.')
} else {
// Pass through validate for now
hookedWallet.validateTransaction = (_, cb) => {
cb()
}
}
// Disable caching subProviders, because they interfere with the provider
// we're returning.
provider._providers.splice(3, 1)
provider._providers.splice(4, 1)
provider.isOrigin = true
debug('getProvider returning', provider)
return provider
}
getLinkPrivKey() {
const localKey = localStorage.getItem(LOCAL_KEY_STORE)
const privKey = localKey || cryptoRandomString(64).toString('hex')
if (privKey != localKey) {
localStorage.setItem(LOCAL_KEY_STORE, privKey)
}
return privKey
}
getLinkPubKey() {
return secp256k1
.publicKeyCreate(new Buffer(this.getLinkPrivKey(), 'hex'), false)
.slice(1)
.toString('hex')
}
ecDecrypt(buffer) {
const privKey = this.getLinkPrivKey()
return ecies
.decrypt(new Buffer(privKey, 'hex'), new Buffer(buffer, 'hex'))
.toString('utf8')
}
// Generates a link code through the linking server, which is an input into
// the QR codes used for linking to a mobile wallet.
async generateLinkCode() {
const body = {
session_token: this.session.token,
returnUrl: this.getReturnUrl(),
pending_call: this.pendingCall && {
call_id: this.pendingCall.callId,
call: this.pendingCall.call
},
pub_key: this.getLinkPubKey(),
notify_wallet: this.notifyWallet
}
debug('generating link code')
const resp = await this.post(`${API_PATH}/generate-code`, body)
debug('got link code response:', resp)
this.linkCode = resp.link_code
this.session.linked = resp.linked
if (this.session.token !== resp.sessionToken) {
this.session.token = resp.session_token
this.streamWalletMessages()
}
this.session.save()
return resp.link_code
}
// Stop streaming linker messages over our websocket.
closeWalletMessages() {
if (
this.messagesWS &&
this.messagesWS.readyState !== this.messagesWS.CLOSED
) {
debug('closing wallet messages web socket')
this.messagesWS.close()
}
}
// Stream mobile wallet messages from the linking server. Not to be confused
// with Origin Messaging.
async streamWalletMessages() {
this.closeWalletMessages()
if (!this.session.token) {
throw new Error('Cannot sync messages without session token')
}
const sessionToken = this.session.token || '-'
const messageId = this.session.lastMessageId || 0
const wsUrl = `${
this.wsUrl
}${API_PATH}/linked-messages/${sessionToken}/${messageId}`
const ws = new WebSocket(wsUrl)
debug('streaming messages from', wsUrl)
ws.onmessage = e => this.processWalletMessage(JSON.parse(e.data))
ws.onclose = e => {
console.log('messages websocket closed:', e)
if (e.code != 1000) {
// If this is an abnormal close, try to reopen soon.
setTimeout(() => {
if (this.messagesWS === ws) {
this.streamWalletMessages()
}
}, 30000)
}
}
this.messagesWS = ws
}
// Process messages pushed from linking server.
processWalletMessage(m) {
const { type, data } = m.msg
const id = m.msgId
switch (type) {
case 'CONTEXT':
this.handleContextMessage(data)
break
case 'CALL_RESPONSE':
this.handleCallResponse(data)
break
default:
console.error('unknown message', type, data)
}
if (id) {
this.session.lastMessageId = id
this.session.save()
}
}
// Handles the CONTEXT message, which allows this client to refresh its state,
// such as wallet link status and linked accounts.
handleContextMessage(msg) {
debug('received context message:', msg)
if (msg.sessionToken) {
this.session.token = msg.sessionToken
}
if (!msg.linked && this.session.linked) {
// We've been logged out, so clear our state.
this.session.clear()
this.session.save()
return
}
this.session.linked = msg.linked
if (this.session.linked) {
this.cancelLink()
}
const device = msg.device
if (!device) {
debug('no device info found')
this.session.accounts = []
return
}
debug('device info found')
this.session.accounts = device.accounts
if (device.priv_data) {
const data = JSON.parse(this.ecDecrypt(device.priv_data))
this.session.privData = data
if (data && data.messaging && this.callbacks['messaging']) {
debug('got messaging data', data.messaging)
this.callbacks['messaging'](data.messaging)
}
}
}
// Called with the results of a web3 transaction that was executed through
// the mobile wallet.
handleCallResponse(msg) {
debug('got call response:', msg)
if (this.callbacks[msg.call_id]) {
debug(`performing callback for ${msg.call_id}`)
this.callbacks[msg.call_id](msg.result)
delete this.callbacks[msg.call_id]
}
}
getReturnUrl() {
if (
typeof window.orientation !== 'undefined' ||
navigator.userAgent.indexOf('IEMobile') !== -1
) {
return window.location.href
} else {
return ''
}
}
// Performs an HTTP request to the linking server and returns the JSON
// response object.
async httpReq(method, path, body) {
const url = `${this.httpUrl}${path}`
const opts = {
method,
credentials: 'include',
body: body && JSON.stringify(body),
headers: { 'content-type': 'application/json' }
}
const resp = await fetch(url, opts)
const json = await resp.json()
if (!resp.ok) {
throw new Error(JSON.stringify(json))
}
return json
}
async post(url, body) {
return await this.httpReq('POST', url, body)
}
registerCallback(callId, cb) {
debug('registering callback for', callId)
this.callbacks[callId] = cb
}
} |
JavaScript | class EventMonitor extends SAMPCACEventObserver {
detectorMonitor_ = null;
manager_ = null;
constructor(manager, detectorMonitor) {
super();
this.detectorMonitor_ = detectorMonitor;
this.manager_ = manager;
server.deferredEventManager.addObserver(this);
}
// ---------------------------------------------------------------------------------------------
// SAMPCACEventObserver implementation:
// ---------------------------------------------------------------------------------------------
// Called when the |player| has been detected to use the given |cheatId|. Additional information
// and specifics could be found in |option1| and |option2|.
onPlayerCheatDetected(player, cheatId, option1, option2) {
if (!server.isTest())
console.log(`[sampcac] Detected ${player.name}: ${cheatId} (${option1}, ${option2})`);
switch (cheatId) {
case SAMPCACNatives.kCheatAdditionalVisibility:
case SAMPCACNatives.kCheatAdditionalVisibilityNameTags:
this.detectorMonitor_.reportExtrasensoryPerception(player, cheatId);
break;
case SAMPCACNatives.kCheatAimbot:
case SAMPCACNatives.kCheatAimbotAlternative:
case SAMPCACNatives.kCheatAimbotAlternative2:
case SAMPCACNatives.kCheatAimbotAlternative3:
case SAMPCACNatives.kCheatAimbotAlternative4:
this.detectorMonitor_.reportAimbot(player, cheatId);
break;
case SAMPCACNatives.kCheatCleo:
this.manager_.reportPlayerHasInstalledCleo(player);
break;
case SAMPCACNatives.kCheatFakePing:
this.detectorMonitor_.reportFakePing(player);
break;
case SAMPCACNatives.kCheatMacro:
this.detectorMonitor_.reportMacro(player, option1);
break;
case SAMPCACNatives.kCheatNoRecoil:
case SAMPCACNatives.kCheatNoRecoilAlternative:
case SAMPCACNatives.kCheatNoRecoilAlternative2:
this.detectorMonitor_.reportNoRecoil(player, cheatId);
break;
case SAMPCACNatives.kCheatTriggerbot:
case SAMPCACNatives.kCheatTriggerbotAlternative:
this.detectorMonitor_.reportTriggerBot(player, cheatId);
break;
case SAMPCACNatives.kCheatUntrustedLibrary:
case SAMPCACNatives.kCheatUntrustedLibraryAlternative:
case SAMPCACNatives.kCheatUntrustedLibraryAlternative2:
case SAMPCACNatives.kCheatUntrustedLibraryAlternative3:
this.detectorMonitor_.reportUntrustedLibrary(player, cheatId);
break;
case SAMPCACNatives.kCheatWeaponDataModified:
this.detectorMonitor_.reportWeaponDataModified(player);
break;
// The following cheat detectors are entirely disabled because they're inaccurate and
// produce invalid results. Just drop the reports entirely.
case SAMPCACNatives.kCheatAimbotAlternative5:
break;
case SAMPCACNatives.kCheatAny:
break;
}
}
// Called when the |modelId| for the |player| has been modified. The |checksum| identifies what
// the actual value is, in case we might want to whitelist it.
onPlayerGameResourceMismatch(player, modelId, componentType, checksum) {
console.log(
`[sampcac] Mismatch for ${player.name} for model ${modelId} (${componentType}, ` +
`${checksum})`)
}
// Called when the |player| has been kicked for the given |reason|.
onPlayerKicked(player, reason) {
console.log(`[sampcac] Kicked ${player.name} for: ${reason}`);
}
// Called when the given |checksum| has been calculated for the |player|. Will be forwarded to
// the detector manager which will resolve the enqueued promise with it.
onPlayerMemoryChecksum(player, address, checksum) {
this.manager_.onMemoryResponse(player, address, checksum);
}
// Called when the memory at the given |address| has been read in their GTA_SA.exe memory space,
// with the actual memory contents being written to |buffer| as an Uint8Buffer.
onPlayerMemoryRead(player, address, buffer) {
this.manager_.onMemoryResponse(player, address, [ ...buffer ]);
}
// Called when the |player| has taken a screenshot.
onPlayerScreenshotTaken(player) {
console.log(`[sampcac] Player ${player.name} took a screenshot.`);
}
// ---------------------------------------------------------------------------------------------
dispose() {
server.deferredEventManager.removeObserver(this);
}
} |
JavaScript | class EURtoUSD extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false,
EURUSD: 0,
changeEURUSD: '',
colorEURUSD: ''
};
}
getCurrencyDataEUR_USD() {
return fetch('https://economia.awesomeapi.com.br/last/EUR-USD')
.then(APIresponse => {
// If request returns anything other than 200 (success), raise error
if (APIresponse.status >= 400) {
throw new Error(`Paint It Black! warns: request failed with status ${APIresponse.status}`);
}
return APIresponse.json()
})
.then(APIdata => {
// console.log(APIdata) // DEBUG data returned from API
var value = [APIdata.EURUSD.ask, APIdata.EURUSD.pctChange]
return value
})
.then(value => {
value[0] = value[0].substring(0,5);
value[1] = value[1].substring(0,4);
// Display the pctChange as green if positive, and add an arrow up. Vice-versa when negative
var color;
if (value[1] >= 0) {
color = config.Dashboard1.EURUSD_upchange_color
value[1] = '▲ ' + value[1]
}
else {
color = config.Dashboard1.EURUSD_downchange_color
value[1] = '▼ ' + value[1]
}
this.setState({
EURUSD: value[0],
changeEURUSD: value[1],
colorEURUSD: color
});
});
}
componentDidMount = async () => {
await this.getCurrencyDataEUR_USD();
// Set an interval of XX seconds to fetch the most recent data. This triggers a render of the component
// without refreshing the page! Yay for React!
setInterval( async() => {
// console.log('Fetching EUR/USD');
await this.getCurrencyDataEUR_USD();
}, config.Dashboard1.EURUSD_repeat_delay*1000)
}
render() {
return (
<div className='element-container' style={{ position: 'absolute', top: '481px', left: '1491px', height: '232px', width: '420px'}}>
<div className='kpi-card-container'>
<p className='kpi-card-title'>💰 EUR/USD:</p>
<p className='kpi-card-content' style={{ left: '34%' }}> {this.state.EURUSD} |</p>
<p className='kpi-card-content' style={{ left: '66%', color: this.state.colorEURUSD }}> {this.state.changeEURUSD}% </p>
</div>
</div>
);
}
} |
JavaScript | class Translate {
/**
* @constructor
* @param {Object} emoji
*/
constructor(emoji) {
this.emoji = emoji;
}
/**
* main method
* @param {string} target
* @return {string}
*/
exec(target) {
let origin = 'ja';
let convt = 'en';
const transRegexp = /^(\S+)\s((?:\s|\S)+)$/;
const option = transRegexp.exec(target)[1];
if (option == origin) {
[origin, convt] = [convt, origin];
};
const text = transRegexp.exec(target)[2];
return this.trans(text, origin, convt);
}
/**
* call translateAPI
* @param {string} text
* @param {string} from
* @param {string} to
*
* @return {string} message
*/
trans(text, from, to) {
const langParam = {'ja': '日本語', 'en': '英語'};
const convertMsg = LanguageApp.translate(text, from, to);
let message = `*${text}* は${langParam[to]}で `;
message += `\`\`\`${convertMsg}\`\`\` って言うらしいですよ ${this.emoji.smile}`;
return message;
}
} |
JavaScript | class SizeLimitedCache extends Map {
constructor(size) {
super();
this.maxSize = size;
this.currentSize = 0;
}
set(key, buffer) {
this.delete(key);
this.currentSize += buffer.length;
this.evict();
super.set(key, buffer);
}
delete(key) {
const buffer = this.get(key);
if (buffer) {
this.currentSize -= buffer.length;
super.delete(key);
}
}
evict() {
// Don't evict _everything_, because we just added something!
const iter = this.keys();
while (this.currentSize > this.maxSize && this.size > 1) {
// Amazingly, maps iterate in key-addition order, so we don't need to
// track anything like LRU or whatever. We'll just toss the oldest thing
// added.
const firstIn = iter.next();
this.delete(firstIn.value);
}
}
} |
JavaScript | class AsyncGlobalPropertiesTelemetryReporter {
constructor(_telemetryReporter) {
this._telemetryReporter = _telemetryReporter;
this._actionsQueue = Promise.resolve();
// We just store the parameter
}
reportEvent(name, data) {
/*
* TODO: Put this code back after VS stops dropping telemetry events that happen after fatal errors, and disconnecting...
* VS has a bug where it drops telemetry events that happen after a fatal error, or after the DA starts disconnecting. Our
* temporary workaround is to make telemetry sync, so it'll likely be sent before we send the fatal errors, etc...
this._actionsQueue = this._actionsQueue.then(() => // We block the report event until all the addCustomGlobalProperty have finished
this._telemetryReporter.reportEvent(name, data));
*/
this._telemetryReporter.reportEvent(name, data);
}
setupEventHandler(_sendEvent) {
this._telemetryReporter.setupEventHandler(_sendEvent);
}
addCustomGlobalProperty(additionalGlobalPropertiesPromise) {
const reportedPropertyP = Promise.resolve(additionalGlobalPropertiesPromise).then(property => this._telemetryReporter.addCustomGlobalProperty(property), rejection => this.reportErrorWhileWaitingForProperty(rejection));
this._actionsQueue = Promise.all([this._actionsQueue, reportedPropertyP]);
}
reportErrorWhileWaitingForProperty(rejection) {
let properties = {};
properties.successful = 'false';
properties.exceptionType = 'firstChance';
utils_1.fillErrorDetails(properties, rejection);
/* __GDPR__
"error-while-adding-custom-global-property" : {
"${include}": [
"${IExecutionResultTelemetryProperties}"
]
}
*/
this._telemetryReporter.reportEvent('error-while-adding-custom-global-property', properties);
}
} |
JavaScript | class ServerlessNestedYml {
constructor(serverless) {
this.serverless = serverless
this.config = {}
this
._setConfig()
._init()
}
/**
* Get config from custom.splittedYml
*
* @returns {ServerlessNestedYml}
* @private
*/
_setConfig() {
const keys = Object.keys(defaults)
const customConfig = pick(this.serverless.service.custom.nestedYml || {}, keys)
keys.forEach(key => {
if (isArray(defaults[key])) {
this.config[key] = !customConfig[key]
? defaults[key]
: isArray(customConfig[key])
? customConfig[key]
: [customConfig[key]]
} else {
this.config[key] = customConfig[key] || defaults[key]
}
})
return this
}
/**
* Initialize commands and hooks
*
* @returns {Bluebird<void>}
* @private
*/
_init() {
this.commands = {
'nested-yml': {
usage: 'Show merged serverless.yml',
lifecycleEvents: ['print']
}
}
this.hooks = {
'nested-yml:print': this.showConfig.bind(this)
}
return this._mergeConfig()
}
/**
* fetch all nested yml config files and merge them in the config
*
* @returns {Bluebird<void>}
* @private
*/
_mergeConfig() {
const globs = this.config.paths.map(path => (
`${path}/**/${this.config.filename}`
.split('/')
.filter(s => s)
.join('/')
))
const excludes = this.config.exclude.map(path => (
'!' + path
.split('/')
.filter(s => s)
.join('/')
))
const files = fg.sync([...globs, ...excludes])
this._showIncludedFiles({ files, excludes })
files
.map(file => {
return {
path: file,
content: this.serverless.utils.readFileSync(file)
}
})
.forEach(({ content, path }) => {
if (this.config.monorepo === true && content.functions) {
const modulePath = dirname(path)
Object.keys(content.functions).forEach(fnName => {
const formatted = join(modulePath, content.functions[fnName].handler)
content.functions[fnName].handler = formatted
})
}
this.serverless.service = mergeWith(
this.serverless.service,
content,
(objValue, srcValue, key) => {
if (key === 'webpackConfig' && this.config.monorepo === true) {
return objValue;
}
if (isArray(objValue)) {
return objValue.concat(srcValue)
}
})
})
return BbPromise.resolve()
}
/**
* Show included / excluded files in console
*
* @param files
* @param excludes
* @private
*/
_showIncludedFiles({ files, excludes }) {
console.log()
this.serverless.cli.log(`${this.constructor.name} - found ${files.length} files`)
for (const file of files) {
console.log(' ', file)
}
console.log()
if (excludes.length > 0) {
this.serverless.cli.log(`${this.constructor.name} - files exclusion`)
for (const exclude of excludes) {
console.log(' ', exclude.replace('!', ''))
}
console.log()
}
}
/**
* Like print command but with the merged config
*
* @example serverless splitted
*/
showConfig() {
return this._mergeConfig()
.then(() => {
return this.serverless.variables.populateService(this.serverless.pluginManager.cliOptions)
})
.then(() => {
const config = pick(this.serverless.service, [
'custom',
'functions',
'package',
'provider',
'resources',
'service'
])
this.serverless.cli.log('Merged serverless.yml:\n')
console.log(YAML.dump(config))
return BbPromise.resolve()
})
}
} |
JavaScript | class UniversalAdId {
constructor () {
this._idRegistry = 'unknown'
this._idValue = 'unknown'
this._creativeIdentifier = null
}
// Attribute(s).
/**
* The registry URL for the unique creative identifier.
*
* @type {string}
*/
get idRegistry () {
return this._idRegistry
}
set idRegistry (value) {
this._idRegistry = value
}
/**
* A string for the unique creative identifier.
*
* @type {string}
*/
get idValue () {
return this._idValue
}
set idValue (value) {
this._idValue = value
}
// Content.
/**
* The string identifying the unique creative identifier.
*
* @type {string}
*/
get creativeIdentifier () {
return this._creativeIdentifier
}
set creativeIdentifier (value) {
this._creativeIdentifier = value
}
get $type () {
return 'UniversalAdId'
}
} |
JavaScript | class CKANResultConditionsField extends Component {
constructor(props) {
super(props);
const value = props.value && props.value[0] ? props.value[0] : {
'match-select': props.data.matchTypeDefault,
'match-text': '',
};
// Set initial state values
this.state = {
0: {
[this.getFieldName('match-select', props)]: value['match-select'],
[this.getFieldName('match-text', props)]: value['match-text'],
},
};
this.handleChange = this.handleChange.bind(this);
}
/**
* Returns the namespaced form field name for the given field
*
* @param {string} fieldName
* @param {object} props If provided, will be used instead of this.props
* @returns {string}
*/
getFieldName(fieldName, props = {}) {
const name = props.name || this.props.name;
return `${name}-${fieldName}`;
}
/**
* Gets the current value of the "must match" select
*
* @returns {string}
*/
getSelectValue() {
return `${this.state[0][this.getFieldName('match-select')]}`;
}
/**
* Gets the current value of the filter condition text input
*
* @returns {string}
*/
getInputValue() {
return this.state[0][this.getFieldName('match-text')];
}
/**
* Gets a copy of the state, used to store in the hidden input field
*
* @returns {object}
*/
getValue() {
return {
0: {
'match-select': this.getSelectValue(),
'match-text': this.getInputValue(),
},
};
}
/**
* Handles changes in the form fields which are then serialised into a hidden input field
*
* @param {object} event
*/
handleChange(event) {
const currentState = this.state;
this.setState({
0: {
...currentState[0],
[event.target.name]: event.target.value,
},
});
}
/**
* Renders the select dropdown to choose whether the filter text should or should not match
*
* @returns {SelectComponent}
*/
renderSelect() {
const { SelectComponent, data: { source } } = this.props;
return (
<SelectComponent
className={[
'no-change-track',
'ckan-result-conditions__match-select',
]}
name={this.getFieldName('match-select')}
source={source}
value={this.getSelectValue()}
onChange={this.handleChange}
/>
);
}
/**
* Renders the text input field to enter the string that should or should not be matched
*
* @returns {TextFieldComponent}
*/
renderTextInput() {
const { TextFieldComponent } = this.props;
return (
<TextFieldComponent
name={this.getFieldName('match-text')}
className={[
'no-change-track',
'ckan-result-conditions__match-text',
]}
onChange={this.handleChange}
value={this.getInputValue()}
/>
);
}
/**
* Renders a hidden input containing a JSON serialised set of values for this field
*
* @returns {HTMLElement}
*/
renderHiddenInput() {
const { name } = this.props;
const rawValue = this.getValue();
const value = rawValue[0]['match-text'].length ? JSON.stringify(rawValue) : '';
return (
<input
type="hidden"
name={name}
value={value}
/>
);
}
/**
* Render a simple <p> tag for read only mode
*
* @returns {HTMLElement|null}
*/
renderReadOnly() {
const { data: { source } } = this.props;
const input = this.getInputValue();
const type = source.find(candidate => `${candidate.value}` === this.getSelectValue());
if (!type) {
return null;
}
return <p className="form-control-static readonly">{type.title}: {input}</p>;
}
render() {
if (this.props.readOnly) {
return this.renderReadOnly();
}
return (
<div className="ckan-result-conditions">
<Row form>
<Col md={4} className="ckan-result-conditions__column-left">
{ this.renderSelect() }
</Col>
<Col md={8} className="ckan-result-conditions__column-right">
{ this.renderTextInput() }
</Col>
</Row>
{ this.renderHiddenInput() }
</div>
);
}
} |
JavaScript | class Bank {
constructor(bankName) {
this._bankName = bankName;
this.allCustomers = [];
}
newCustomer(customer) {
let client = this.allCustomers.find((c) => c.personalId == customer.personalId);
if (client) {
throw new Error(`${customer.firstName} ${customer.lastName} is already our customer!`);
}
this.allCustomers.push(customer);
return customer;
}
depositMoney(personalId, amount) {
let client = this.allCustomers.find((c) => c.personalId == personalId);
if (client == undefined) {
throw new Error(`We have no customer with this ID!`);
}
if (!client.hasOwnProperty('totalMoney')) {
client.totalMoney = amount;
} else {
client.totalMoney += amount;
}
if (!client.hasOwnProperty('transactions')) {
client.transactions = [];
client.transactions.push(`Svetlin Nakov made deposit of ${amount}$!`);
} else {
client.transactions.push(`Svetlin Nakov made deposit of ${amount}$!`);
}
return `${client.totalMoney}$`;
}
withdrawMoney(personalId, amount) {
let client = this.allCustomers.find((c) => c.personalId == personalId);
if (client == undefined) {
throw new Error(`We have no customer with this ID!`);
}
if (client.totalMoney < amount) {
throw new Error(`${client.firstName} ${client.lastName} does not have enough money to withdraw that amount!`);
}
client.transactions.push(`Svetlin Nakov withdrew ${amount}$!`);
client.totalMoney -= amount;
return `${client.totalMoney}$`;
}
customerInfo(personalId) {
let client = this.allCustomers.find((c) => c.personalId == personalId);
if (client == undefined) {
throw new Error(`We have no customer with this ID!`);
}
let result = [`Bank name: ${this._bankName}`, `Customer name: ${client.firstName} ${client.lastName}`, `Customer ID: ${client.personalId}`,
`Total Money: ${client.totalMoney}$`, `Transactions:`];
for (let i = client.transactions.length; i > 0; i--) {
result.push(`${i}. ${client.transactions[i - 1]}`);
}
return result.join('\n');
}
} |
JavaScript | class DesktopContainer extends Component {
state = {}
hideFixedMenu = () => this.setState({ fixed: false })
showFixedMenu = () => this.setState({ fixed: true })
render() {
const { children } = this.props
const { fixed } = this.state
return (
<Responsive getWidth={getWidth} minWidth={Responsive.onlyTablet.minWidth}>
<Visibility
once={false}
onBottomPassed={this.showFixedMenu}
onBottomPassedReverse={this.hideFixedMenu}
>
<Segment
inverted
textAlign='center'
style={{ minHeight: 700, padding: '1em 0em' }}
vertical
>
<Menu
fixed={fixed ? 'top' : null}
inverted={!fixed}
pointing={!fixed}
secondary={!fixed}
size='large'
>
<Container>
<Menu.Item as='a' active>
Home
</Menu.Item>
<Menu.Item as='a'>Work</Menu.Item>
<Menu.Item as='a'>Company</Menu.Item>
<Menu.Item as='a'>Careers</Menu.Item>
<Menu.Item position='right'>
<Button as='a' inverted={!fixed}>
Log in
</Button>
<Button as='a' inverted={!fixed} primary={fixed} style={{ marginLeft: '0.5em' }}>
Sign Up
</Button>
</Menu.Item>
</Container>
</Menu>
<HomepageHeading />
</Segment>
</Visibility>
{children}
</Responsive>
)
}
} |
JavaScript | class Point {
/**
* @param {number} x
* @param {number} y
*/
constructor(x = 0, y = 0) {
this._x = x;
this._y = y;
this._type = graphicTypes.POINT;
}
/**
* @param {number} x
* @param {number} y
*/
add(x, y) {
this._x += x;
this._y += y;
}
/**
* @param {number} c
*/
multiply(c) {
this._x *= c;
this._y *= c;
}
/**
* @param {Point} p
* @returns {Point}
*/
rotate90DegreesClockwiseAbout(p) {
return new Point(this._y + p.x - p.y, (-1 * this._x) + p.x + p.y);
}
/**
* @param {Point} p
* @param {number} threshold
* @returns {boolean}
*/
isNear(p, threshold) {
return Math.sqrt(
Math.pow(this._x - p.x, 2) + Math.pow(this._y - p.y, 2)
) < threshold;
}
/**
* @param {number} graphHeight
* @returns {JSON}
*/
asGraphic(graphHeight) {
return {
x: this._x,
y: graphHeight - this._y,
};
}
get x() {
return this._x;
}
set x(x) {
this._x = x;
}
get y() {
return this._y;
}
set y(y) {
this._y = y;
}
get type() {
return this._type;
}
} |
JavaScript | class PreloadPlugin {
constructor(jsPsych) {
this.jsPsych = jsPsych;
}
trial(display_element, trial) {
var success = null;
var timeout = false;
var failed_images = [];
var failed_audio = [];
var failed_video = [];
var detailed_errors = [];
var in_safe_mode = this.jsPsych.getSafeModeStatus();
// create list of media to preload //
var images = [];
var audio = [];
var video = [];
if (trial.auto_preload) {
var experiment_timeline = this.jsPsych.getTimeline();
var auto_preload = this.jsPsych.pluginAPI.getAutoPreloadList(experiment_timeline);
images = images.concat(auto_preload.images);
audio = audio.concat(auto_preload.audio);
video = video.concat(auto_preload.video);
}
if (trial.trials.length > 0) {
var trial_preloads = this.jsPsych.pluginAPI.getAutoPreloadList(trial.trials);
images = images.concat(trial_preloads.images);
audio = audio.concat(trial_preloads.audio);
video = video.concat(trial_preloads.video);
}
images = images.concat(trial.images);
audio = audio.concat(trial.audio);
video = video.concat(trial.video);
images = this.jsPsych.utils.unique(images.flat());
audio = this.jsPsych.utils.unique(audio.flat());
video = this.jsPsych.utils.unique(video.flat());
if (in_safe_mode) {
// don't preload video if in safe mode (experiment is running via file protocol)
video = [];
}
// render display of message and progress bar
var html = "";
if (trial.message !== null) {
html += trial.message;
}
if (trial.show_progress_bar) {
html += `
<div id='jspsych-loading-progress-bar-container' style='height: 10px; width: 300px; background-color: #ddd; margin: auto;'>
<div id='jspsych-loading-progress-bar' style='height: 10px; width: 0%; background-color: #777;'></div>
</div>`;
}
display_element.innerHTML = html;
const update_loading_progress_bar = () => {
loaded++;
if (trial.show_progress_bar) {
var percent_loaded = (loaded / total_n) * 100;
var preload_progress_bar = display_element.querySelector("#jspsych-loading-progress-bar");
if (preload_progress_bar !== null) {
preload_progress_bar.style.width = percent_loaded + "%";
}
}
};
// called if all files load successfully
const on_success = () => {
if (typeof timeout !== "undefined" && timeout === false) {
// clear timeout immediately after finishing, to handle race condition with max_load_time
this.jsPsych.pluginAPI.clearAllTimeouts();
// need to call cancel preload function to clear global jsPsych preload_request list, even when they've all succeeded
this.jsPsych.pluginAPI.cancelPreloads();
success = true;
end_trial();
}
};
// called if all_files haven't finished loading when max_load_time is reached
const on_timeout = () => {
this.jsPsych.pluginAPI.cancelPreloads();
if (typeof success !== "undefined" && (success === false || success === null)) {
timeout = true;
if (loaded_success < total_n) {
success = false;
}
after_error("timeout"); // call trial's on_error event handler here, in case loading timed out with no file errors
detailed_errors.push("<p><strong>Loading timed out.</strong><br>" +
"Consider compressing your stimuli files, loading your files in smaller batches,<br>" +
"and/or increasing the <i>max_load_time</i> parameter.</p>");
if (trial.continue_after_error) {
end_trial();
}
else {
stop_with_error_message();
}
}
};
const stop_with_error_message = () => {
this.jsPsych.pluginAPI.clearAllTimeouts();
this.jsPsych.pluginAPI.cancelPreloads();
// show error message
display_element.innerHTML = trial.error_message;
// show detailed errors, if necessary
if (trial.show_detailed_errors) {
display_element.innerHTML += "<p><strong>Error details:</strong></p>";
detailed_errors.forEach((e) => {
display_element.innerHTML += e;
});
}
};
const end_trial = () => {
// clear timeout again when end_trial is called, to handle race condition with max_load_time
this.jsPsych.pluginAPI.clearAllTimeouts();
var trial_data = {
success: success,
timeout: timeout,
failed_images: failed_images,
failed_audio: failed_audio,
failed_video: failed_video,
};
// clear the display
display_element.innerHTML = "";
this.jsPsych.finishTrial(trial_data);
};
// do preloading
if (trial.max_load_time !== null) {
this.jsPsych.pluginAPI.setTimeout(on_timeout, trial.max_load_time);
}
var total_n = images.length + audio.length + video.length;
var loaded = 0; // success or error count
var loaded_success = 0; // success count
if (total_n == 0) {
on_success();
}
else {
const load_video = (cb) => {
this.jsPsych.pluginAPI.preloadVideo(video, cb, file_loading_success, file_loading_error);
};
const load_audio = (cb) => {
this.jsPsych.pluginAPI.preloadAudio(audio, cb, file_loading_success, file_loading_error);
};
const load_images = (cb) => {
this.jsPsych.pluginAPI.preloadImages(images, cb, file_loading_success, file_loading_error);
};
if (video.length > 0) {
load_video(() => { });
}
if (audio.length > 0) {
load_audio(() => { });
}
if (images.length > 0) {
load_images(() => { });
}
}
// helper functions and callbacks
// called when a single file loading fails
function file_loading_error(e) {
// update progress bar even if there's an error
update_loading_progress_bar();
// change success flag after first file loading error
if (success == null) {
success = false;
}
// add file to failed media list
var source = "unknown file";
if (e.source) {
source = e.source;
}
if (e.error && e.error.path && e.error.path.length > 0) {
if (e.error.path[0].localName == "img") {
failed_images.push(source);
}
else if (e.error.path[0].localName == "audio") {
failed_audio.push(source);
}
else if (e.error.path[0].localName == "video") {
failed_video.push(source);
}
}
// construct detailed error message
var err_msg = "<p><strong>Error loading file: " + source + "</strong><br>";
if (e.error.statusText) {
err_msg += "File request response status: " + e.error.statusText + "<br>";
}
if (e.error == "404") {
err_msg += "404 - file not found.<br>";
}
if (typeof e.error.loaded !== "undefined" &&
e.error.loaded !== null &&
e.error.loaded !== 0) {
err_msg += e.error.loaded + " bytes transferred.";
}
else {
err_msg +=
"File did not begin loading. Check that file path is correct and reachable by the browser,<br>" +
"and that loading is not blocked by cross-origin resource sharing (CORS) errors.";
}
err_msg += "</p>";
detailed_errors.push(err_msg);
// call trial's on_error function
after_error(source);
// if this is the last file
if (loaded == total_n) {
if (trial.continue_after_error) {
// if continue_after_error is false, then stop with an error
end_trial();
}
else {
// otherwise end the trial and continue
stop_with_error_message();
}
}
}
// called when a single file loads successfully
function file_loading_success(source) {
update_loading_progress_bar();
// call trial's on_success function
after_success(source);
loaded_success++;
if (loaded_success == total_n) {
// if this is the last file and all loaded successfully, call success function
on_success();
}
else if (loaded == total_n) {
// if this is the last file and there was at least one error
if (trial.continue_after_error) {
// end the trial and continue with experiment
end_trial();
}
else {
// if continue_after_error is false, then stop with an error
stop_with_error_message();
}
}
}
function after_error(source) {
// call on_error function and pass file name
if (trial.on_error !== null) {
trial.on_error(source);
}
}
function after_success(source) {
// call on_success function and pass file name
if (trial.on_success !== null) {
trial.on_success(source);
}
}
}
simulate(trial, simulation_mode, simulation_options, load_callback) {
if (simulation_mode == "data-only") {
load_callback();
this.simulate_data_only(trial, simulation_options);
}
if (simulation_mode == "visual") {
this.simulate_visual(trial, simulation_options, load_callback);
}
}
create_simulation_data(trial, simulation_options) {
const default_data = {
success: true,
timeout: false,
failed_images: [],
failed_audio: [],
failed_video: [],
};
const data = this.jsPsych.pluginAPI.mergeSimulationData(default_data, simulation_options);
return data;
}
simulate_data_only(trial, simulation_options) {
const data = this.create_simulation_data(trial, simulation_options);
this.jsPsych.finishTrial(data);
}
simulate_visual(trial, simulation_options, load_callback) {
const display_element = this.jsPsych.getDisplayElement();
this.trial(display_element, trial);
load_callback();
}
} |
JavaScript | class World {
/**
* Creates a new world.
*
* @param {String} id the uuid of the world.
* @param {String} name the name of the world.
* @param {boolean} isDefault states if this world is default.
* @param {Vector3} spawnPoint the spawn point of the world.
*/
constructor(id, name, isDefault, spawnPoint) {
/**
* @type {String} the name of the world.
*/
this.name = name;
/**
* @type {String} the uuid of this world.
*/
this.uuid = id;
/**
* @type {Vector3} the player spawn point of this world.
*/
this.spawnPoint = spawnPoint;
/**
* @type {boolean} states if this world is the default world of a server.
*/
this.isDefault = isDefault;
/**
* @type {WorldBorder | null} the world border for this world.
*/
this.worldBorder = null;
/**
* @type {Map<String, Map<int, Map<int, Chunk>>>} a map of chunks for this world.
*/
this.chunkMap = new Map();
/**
* @type {Camera} the camera for viewing this world.
*/
this.camera = new Camera(this.spawnPoint);
/**
* @type {Map<String, Player>} the map of players which are on this server.
*/
this.playerMap = new Map();
}
/**
* @param {number} x the x position.
* @param {number} z the z position.
* @return {Chunk | null} the chunk at the given position or null if not found.
*/
getChunkOrNull(x, z) {
let xMap = this.chunkMap.get(x);
return xMap != null ? xMap.get(z) : null;
}
} |
JavaScript | class CapitalizeValueConverter {
toView(value) {
return value && value.charAt(0).toUpperCase() + value.slice(1);
}
} |
JavaScript | class SPA extends App {
/**
* Create a single-page app.
* @param {Object} [settings={}] Settings for the application.
* @param {String} [settings.name="@fabric/maki"] Name of the app.
* @param {Boolean} [settings.offline=true] Hint offline mode to browsers.
* @return {App} Instance of the application.
*/
constructor (settings = {}) {
super(settings);
this.settings = Object.assign({
name: '@fabric/maki',
synopsis: 'Making beautiful apps a breeze.',
handle: 'html',
language: 'en',
components: {},
offline: false
}, settings);
// TODO: enable Web Worker integration
/* this.worker = new Worker('./worker', {
type: 'module'
}); */
this.router = new Router(this.settings);
this.store = new Store(this.settings);
this.routes = [];
this.bindings = {
'click': this._handleClick.bind(this)
};
this.title = `${this.settings.synopsis} · ${this.settings.name}`;
return this;
}
define (name, definition) {
this.router.define(name, definition);
this.types.state[name] = definition;
this.resources[name] = definition;
return this.resources[name];
}
register () {
return this;
}
route (path) {
for (let i = 0; i < this.routes.length; i++) {
console.log('[MAKI:SPA]', 'testing route:', this.routes[i]);
}
}
_handleClick (e) {
console.log('SPA CLICK EVENT:', e);
}
_setTitle (title) {
this.title = `${title} · ${this.settings.name}`;
document.querySelector('title').innerHTML = this.title;
}
_renderWith (html) {
let hash = crypto.createHash('sha256').update(html).digest('hex');
return `<!DOCTYPE html>
<html lang="${this.settings.language}"${(this.settings.offline) ? 'manifest="cache.manifest"' : ''}>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>${this.title}</title>
<!-- <link rel="manifest" href="/manifest.json"> -->
<link rel="stylesheet" type="text/css" href="/styles/screen.css" />
<!-- <link rel="stylesheet" type="text/css" href="/styles/semantic.css" /> -->
</head>
<body data-bind="${hash}">${html}</body>
</html>`;
}
/**
* Return a string of HTML for the application.
* @return {String} Fully-rendered HTML document.
*/
render () {
let body = super.render();
// TODO: define Custom Element
// let app = SPA.toString('base64');
// definition = customElements.define(name, SPA);
return this._renderWith(body);
}
async stop () {
if (this.settings.verbosity >= 4) console.log('[HTTP:SPA]', 'Stopping...');
try {
await this.router.stop();
} catch (E) {
console.error('Could not stop SPA router:', E);
}
try {
await this.store.stop();
} catch (E) {
console.error('Could not stop SPA store:', E);
}
// await super.stop();
if (this.settings.verbosity >= 4) console.log('[HTTP:SPA]', 'Stopped!');
return this;
}
async start () {
if (this.settings.verbosity >= 4) console.log('[HTTP:SPA]', 'Starting...');
// await super.start();
try {
await this.store.start();
} catch (E) {
console.error('Could not start SPA store:', E);
}
for (let name in this.settings.resources) {
let definition = this.settings.resources[name];
let resource = await this.define(name, definition);
// console.log('[AUDIT]', 'Created resource:', resource);
}
try {
await this.router.start();
} catch (E) {
console.error('Could not start SPA router:', E);
}
if (this.settings.verbosity >= 4) console.log('[HTTP:SPA]', 'Started!');
return this;
}
} |
JavaScript | class App extends Component {
// Static propTypes definition (formerly )
static propTypes = {
url: PropTypes.string.isRequired,
pollInterval: PropTypes.number
}
static defaultProps = {
pollInterval: 5000
}
state = {
comments: []
}
componentDidMount() {
this._loadCommentsFromServer();
this._pollId = setInterval(
this._loadCommentsFromServer.bind(this),
this.props.pollInterval
);
}
componentWillUnmount() {
clearInterval(this._pollId);
}
async _loadCommentsFromServer() {
// fetch API is Promised-based. As a result we can `await` it in an
// async function to have synchronous control flow without any callback
// functions. After we await the response, we convert to JSON then set
// that to state. If the request fails, we fall into the `catch`
try {
let res = await fetch(this.props.url);
let comments = await res.json();
this.setState({comments});
}
catch (ex) {
console.error(this.props.url, ex)
}
}
async _handleCommentSubmit(comment) {
// Optimistically set an id on the new comment. It will be replaced by an
// id generated by the server. In a production application you would likely
// not use Date.now() for this and would have a more robust system in place.
let {comments} = this.state;
// We want to ensure that we maintain immutability so we can't just set
// the `id` property of `comment`. We need to clone it first and then set
// the `id proprety`. So instead of that multi-step property (which would
// require an additional library like lodash), or using `Object.assign`,
// we use the spread operator with object literals to do it all in a
// single statement.
let newComment = {...comment, id: Date.now()};
// Similarly we can't just push onto `comments`. We must clone it and then
// add to it. We could just `.concat(newComment)` or we can use the spread
// operator.
let newComments = [...comments, newComment];
// update the state optimistically
this.setState({comments: newComments});
// Same as above fetch except we have to pass options for the POST request.
// Also in the case of failure we need to go back to the previous set
// of comments since we updated optimistically
try {
let res = await fetch(this.props.url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(comment)
});
newComments = await res.json();
}
catch (ex) {
console.error(this.props.url, ex);
// undo the optimistic update
newComments = comments;
}
// update the state with final data
this.setState({comments: newComments});
}
render() {
let {comments} = this.state;
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList comments={comments} />
<CommentForm onCommentSubmit={this._handleCommentSubmit.bind(this)} />
</div>
);
}
} |
JavaScript | class Variant {
/**
*
* @param {ComValue} [value]
* @param {boolean} [isByref]
* @param {Boolean} [FLAG]
*/
constructor(value, isByref, FLAG)
{
this._init();
this.EMPTY = {};
this.EMPTY_BYREF = this.EMPTY; // TO-DO; maybe it should be Variant
this.NULL = {};
this.OPTIONAL_PARAM = {};
this.SCODE = SCODE;
this.member = null;
this.serialVersionUUID = "5101290038004040628L;"
/* this.VT_NULL = 0x00000001;
this.VT_EMPTY = 0x00000000;
this.VT_I4 = 0x00000003;
this.VT_UI1 = 0x00000011;
this.VT_I2 = 0x00000002;
this.VT_R4 = 0x00000004;
this.VT_R8 = 0x00000005;
this.VT_VARIANT = 0x0000000c;
this.VT_BOOL = 0x0000000b;
this.VT_ERROR = 0x0000000a;
this.VT_CY = 0x00000006;
this.VT_DATE = 0x00000007;
this.VT_BSTR = 0x00000008;
this.VT_UNKNOWN = 0x0000000d;
this.VT_DECIMAL = 0x0000000e;
this.VT_DISPATCH = 0x00000009;
this.VT_ARRAY = 0x00002000;
this.VT_BYREF = 0x00004000;
this.VT_BYREF_VT_UI1 = this.VT_BYREF|this.VT_UI1;//0x00004011;
this.VT_BYREF_VT_I2 = this.VT_BYREF|this.VT_I2;//0x00004002;
this.VT_BYREF_VT_I4 = this.VT_BYREF|this.VT_I4;//0x00004003;
this.VT_BYREF_VT_R4 = this.VT_BYREF|this.VT_R4;//0x00004004;
this.VT_BYREF_VT_R8 = this.VT_BYREF|this.VT_R8;//0x00004005;
this.VT_BYREF_VT_BOOL = this.VT_BYREF|this.VT_BOOL;//0x0000400b;
this.VT_BYREF_VT_ERROR = this.VT_BYREF|this.VT_ERROR;//0x0000400a;
this.VT_BYREF_VT_CY = this.VT_BYREF|this.VT_CY;//0x00004006;
this.VT_BYREF_VT_DATE = this.VT_BYREF|this.VT_DATE;//0x00004007;
this.VT_BYREF_VT_BSTR = this.VT_BYREF|this.VT_BSTR;//0x00004008;
this.VT_BYREF_VT_UNKNOWN = this.VT_BYREF|this.VT_UNKNOWN;//0x0000400d;
this.VT_BYREF_VT_DISPATCH = this.VT_BYREF|this.VT_DISPATCH;//0x00004009;
this.VT_BYREF_VT_ARRAY = this.VT_BYREF|this.VT_ARRAY;//0x00006000;
this.VT_BYREF_VT_VARIANT = this.VT_BYREF|this.VT_VARIANT;//0x0000400c;
this.VT_I1 = 0x00000010;
this.VT_UI2 = 0x00000012;
this.VT_UI4 = 0x00000013;
this.VT_I8 = 0x00000014;
this.VT_INT = 0x00000016;
this.VT_UINT = 0x00000017;
this.VT_BYREF_VT_DECIMAL = this.VT_BYREF|this.VT_DECIMAL;//0x0000400e;
this.VT_BYREF_VT_I1 = this.VT_BYREF|this.VT_I1;//0x00004010;
this.VT_BYREF_VT_UI2 = this.VT_BYREF|this.VT_UI2;//0x00004012;
this.VT_BYREF_VT_UI4 = this.VT_BYREF|this.VT_UI4;//0x00004013;
this.VT_BYREF_VT_I8 = this.VT_BYREF|this.VT_I8;//0x00004014;
this.VT_BYREF_VT_INT = this.VT_BYREF|this.VT_INT;//0x00004016;
this.VT_BYREF_VT_UINT = this.VT_BYREF|this.VT_UINT;//0x00004017;*/
/* this.FADF_AUTO = 0x0001; // array is allocated on the stack
this.FADF_STATIC = 0x0002; // array is staticly allocated
this.FADF_EMBEDDED = 0x0004; // array is embedded in a structure
this.FADF_FIXEDSIZE = 0x0010; // may not be resized or reallocated
this.FADF_RECORD = 0x0020; // an array of records
this.FADF_HAVEIID = 0x0040; // with FADF_DISPATCH, FADF_UNKNOWN array has an IID for interfaces
this.FADF_HAVEVARTYPE = 0x0080; // array has a VT type
this.FADF_BSTR = 0x0100; // an array of BSTRs
this.FADF_UNKNOWN = 0x0200; // an array of IUnknown
this.FADF_DISPATCH = 0x0400; // an array of IDispatch
this.FADF_VARIANT = 0x0800; // an array of VARIANTs
this.FADF_RESERVED = 0xF008; // reserved bits
// array types
this.VT_BOOL_ARRAY = this.VT_ARRAY | this.VT_BOOL;
this.VT_BSTR_ARRAY = this.VT_ARRAY | this.VT_BSTR;
this.VT_DECIMAL_ARRAY = this.VT_ARRAY | this.VT_DECIMAL;
this.VT_ERROR_ARRAY = this.VT_ARRAY | this.VT_ERROR;
this.VT_I1_ARRAY = this.VT_ARRAY | this.VT_I1;
this.VT_I2_ARRAY = this.VT_ARRAY | this.VT_I2;
this.VT_I4_ARRAY = this.VT_ARRAY | this.VT_I4;
this.VT_R4_ARRAY = this.VT_ARRAY | this.VT_R4;
this.VT_R8_ARRAY = this.VT_ARRAY | this.VT_R8;
this.VT_UI1_ARRAY = this.VT_ARRAY | this.VT_UI1;
this.VT_UI2_ARRAY = this.VT_ARRAY | this.VT_UI2;
this.VT_UI4_ARRAY = this.VT_ARRAY | this.VT_UI4;
this.VT_UINT_ARRAY = this.VT_ARRAY | this.VT_UINT;
this.VT_UNKNOWN_ARRAY = this.VT_ARRAY | this.VT_UNKNOWN;
this.VT_VARIANT_ARRAY = this.VT_ARRAY | this.VT_VARIANT;*/
this.outTypeMap = new HashMap();
// populate those hashes
this.outTypeMap.set(Number, new Number(0));
this.outTypeMap.set(Boolean, false);
this.outTypeMap.set(String, "");
// TO-DO: find a way to do this.outTypeMap.set(Currency, new Currency("0.0"));
this.outTypeMap.set(Date, new Date());
// init Arrays
this.arryInits = new Array();
this.arryInits.push(types.COMSTRING);
this.arryInits.push(types.POINTER);
this.arryInits.push(types.COMOBJECT);
// TO-DO: if IDispatch support is desired: this.arryInits.push(Dispatch);
// this.arryInits.push(Unknown);
if (value) {
switch(value.getType()){
case types.INTEGER:
case types.FLOAT:
case types.LONG:
case types.DOUBLE:
case types.BYTE:
case types.SHORT:
case types.BOOLEAN:
case types.CHARACTER:
case types.STRING:
case types.COMSTRING:
case types.COMOBJECT:
case types.UNSIGNEDBYTE:
case types.UNSIGNEDSHORT:
case types.UNSIGNEDINTEGER:
// TO-DO: if IDispatch com is desired it must be implemented here to set the correct flag
case types.DATE:
case types.CURRENCY:
this.init(value, isByref? isByref : false);
break;
case types.COMARRAY:
this.initArrays(value, isByref? isByref : false, FLAG? FLAG : Flags.FLAG_NULL);
break;
}
}
}
_init(){
if (inited) return;
ErrorCodes = require('../common/errorcodes.js');
System = require('../common/system.js');
HashMap = require('hashmap');
Flags = require('./flags.js');
ComString = require('./string');
ComArray = require('./comarray');
ComObject = require('./comobject');
ComObjectImpl = require('./comobjcimpl');
types = require('./types');
ComValue = require('./comvalue');
MarshalUnMarshalHelper = require('./marshalunmarshalhelper');
Pointer = require('./pointer');
Struct = require('./struct');
InterfacePointer = require('./interfacepointer');
variantTypes = require('./varianttypes').variantTypes;
supportedTypes = require('./varianttypes').supportedTypes;
supportedTypes_classes = require('./varianttypes').supportedTypes_classes;
inited = true;
}
OUTPARAMforType(c, isArray)
{
var variant = null;
if (!isArray) {
variant = this.makeVariant(this.outTypeMap.get(c), true);
if (c instanceof ComObject) {
return this.OUT_UNKNOWN();
} else if (c instanceof Variant) {
return this.EMPTY_BYREF();
} else if (c instanceof String) {
return new Variant("", true);
}
} else {
var oo = this.outTypeMap.get(c);
if (oo != null) {
var x = new Array(1);
x[0] = oo;
variant = new Variant(new ComArray(x, true), true);
}
if (c instanceof ComObject) {
var arry = [new ComObjectImpl(null, new InterfacePointer(null, -1, null))];
variant = new Variant(new ComArray(arry, true), true);
variant.setFlag(FLags.FLAG_REPRESENTATION_UNKNOWN_NULL_FOR_OUT |
Flags.FLAG_REPRESENTATION_SET_INTERFACEPTR_NULL_FOR_VARIANT);
} else if (c instanceof Variant) {
return VARIANTARRAY();
} else if (c instanceof ComString || c instanceof String) {
return BSTRARRAY();
}
}
return variant;
}
makeVariant(o, isByref)
{
isByref = (isByref == undefined) ? false : isByref;
if (o == null || o instanceof Object) {
if (isByref) {
return Variant.EMPTY_BYREF();
} else {
return Variant.EMPTY();
}
}
var c = typeof o;
if (c instanceof Array) {
throw new Error("Illegal Argument.");
}
if (c instanceof Variant) {
return new Variant(o);
}
// here is the catch, on j-interop they use reflections and
// heavly use function overloading. Since JS do not support function overloading
// this piece of code is sipmlified. If any problem arises, remember to check
// if the problem isnt here
try {
return new Variant(o, isByref);
} catch (e){}
return null;
}
getSupportedClass(type)
{
return supportedTypes_classes.get(type);
}
getSupportedType(c, FLAG)
{
var retVal = supportedTypes.get(c.getType());
if (retVal == null && c == types.COMOBJECT) {
retVal = variantTypes.VT_UNKNOWN;
}
if (retVal == variantTypes.VT_I4 && (FLAG & Flags.FLAG_REPRESENTATION_VT_INT) ==
Flags.FLAG_REPRESENTATION_VT_INT) {
retVal = variantTypes.VT_INT;
} else if (retVal == variantTypes.VT_UI4 &&
(FLAG & Flags.FLAG_REPRESENTATION_VT_UINT) == Flags.FLAG_REPRESENTATION_VT_UINT) {
retVal = variantTypes.VT_UINT;
}
return retVal;
}
getSupportedTypeObj(o, defaultType)
{
var c = o.constructor;
var retVal = supportedTypes.get(c);
if (retVal == null && o instanceof ComObject) {
retval = new Number(variantTypes.VT_UNKNOWN);
}
return retval;
}
EMPTY()
{
return new Variant(new EMPTY());
}
EMPTY_BYREF()
{
return new Variant(this.EMPTY());
}
OUT_UNKNOWN()
{
var retVal = new Variant(new ComValue(new ComObjectImpl(null, new InterfacePointer(null, -1, null)), types.COMOBJECT), true);
retval.setFlag(Flags.FLAG_REPRESENTATION_UNKNOWN_NULL_FOR_OUT |
Flags.FLAG_REPRESENTATION_SET_INTERFACEPTR_NULL_FOR_VARIANT);
return retval;
}
OUT_DISPATCH()
{
var retVal = new Variant(new ComObjectImpl(null, new InterfacePointer(null, -1, null)), true);
retVal.setFlag(Flags.FLAG_REPRESENTATION_DISPATCH_NULL_FOR_OUT |
FLags.FLAG_REPRESENTATION_SET_INTERFACEPTR_NULL_FOR_VARIANT);
return retval;
}
NULL()
{
return new Variant(new NULL());
}
OPTIONAL_PARAM()
{
return new Variant(variantTypes.SCODE, new ErrorCodes().DISP_E_PARAMNOTFOUND);
}
BSTRARRAY()
{
return new Variant(new IArray([""], true), true);
}
VARIANTARRAY()
{
return new Variant(new IArray([Variant.EMPTY()], true), true);
}
/**
*
* @param {ComValue} obj
* @param {Boolean} isByref
*/
init(obj, isByref)
{
isByref = (isByref == undefined) ? false : isByref;
if (obj != null && obj.getType() == types.ARRAY) {
throw new Error("Ilegal Argument: " + new ErrorCodes().VARIANT_ONLY_ARRAY_EXCEPTED);
}
if (obj != null && obj.getType() == types.INTERFACEPOINTER) {
throw new Error("Ilegal Argument:" + new ErrorCodes().VARIANT_TYPE_INCORRECT);
}
if (obj.getType() == types.VARIANTBODY) {
this.member = new ComValue(new Pointer(obj), types.POINTER);
}else {
var variantBody = new VariantBody(1, {referent: obj, dataType: obj.getType(), isByref: isByref});
this.member = new ComValue(new Pointer(new ComValue(variantBody, types.VARIANTBODY)), types.POINTER);
}
this.member.getValue().setReferent(0x72657355);
}
setDeffered(deffered)
{
if (this.member != null && !this.member.getValue().isReference()) {
this.member.getValue().setDeffered(deffered);
}
}
setFlag(FLAG)
{
var variantBody = this.member.getValue().getReferent();
variantBody.FLAG |= FLAG;
}
getFlag()
{
var variantBody = this.member.getValue().getReferent();
return variantBody.FLAG;
}
isNull()
{
if (this.member == null) {
return true;
}
var variantBody = this.member.getValue().getReferent();
return variantBody == null ? true : variantBody.isNull();
}
functions(fs)
{
var self = {};
fs.forEach(function(f){
self[f.length] = f
});
return function(){
self[arguments.length].apply(this, arguments);
};
}
Variant(){
this.functions([
]);
}
VariantValBool(value, isByref, errorCode){
isByref = (isByref == undefined) ? false : isByref;
errorCode = (errorCode == undefined) ? false: errorCode;
if (value instanceof Number)
{
this.init(new Number(value), isByref);
}
else if (value instanceof Boolean)
{
this.init(new Boolean(value), isByref);
}
else if (value instanceof IString)
{
this.init(value, isByref);
}
else if (value instanceof String)
{
this.init(new IString(value), isByref);
}
else if (value instanceof Date)
{
this.init(value, isByref);
}
else if (value instanceof Currency)
{
this.init(value, isByref);
}
else if (value instanceof SCODE)
{
this.init(new VariantBody(VariantBody.SCODE, errorCode, false));
}
else if (value instanceof EMPTY)
{
this.init(null);
}
else if (value instanceof NULL)
{
this.init(new VariantBody(VariantBody.NULL));
}
else if (value instanceof ComObject)
{
this.init(value, isByref);
this.setFlag(Flags.FLAG_REPRESENTATION_UNKNOWN_IID);
}
}
VariantArray(array, isByref, FLAG)
{
isByref = (isByref == undefined) ? false : isByref;
FLAG = (FLAG == undefined) ? Flags.FLAG_NULL : FLAG;
this.initArrays(array, isByref, FLAG);
}
// TO-DO: this will take some time, postpone it until it is needed
initArrays(array, isByref, FLAG)
{
var variant2 = null;
var array2 = null;
var c = NULL;
var newArrayObj = null;
var is2Dim = false;
if (array == null) {
this.init(null, false);
return;
}
var dimension = 1;
if (array.getValue().getDimensions() == 1 && (array.getValue().memberArray[0] instanceof Array)) {
dimension = 2;
}
switch (array.getValue().getDimensions()) {
case 1:
var obj = array.getValue().getArrayInstance();
newArrayObj = (obj.length == 0)? null : obj;
c = (obj[0])? obj[0].getType() : 9;
break;
case 2:
var obj2 = array.getValue().getArrayInstance();
var name = typeof obj2[0][0].getType();
var subArray = obj2;
name = name.substring(1);
let firstDim = subArray.length;
subArray = subArray[0];
let secondDim = subArray.length;
let k = 0;
newArrayObj = new Array(array.getNumElementsInAllDimensions());
for (let i = 0; i < secondDim; i++) {
for (let j = 0;j < firstDim; j++) {
newArrayObj[k++] = obj2[j][i];
}
}
c = subArray[0].getType();
is2Dim = true;
break;
default:
throw new Error(new ErrorCodes().VARIANT_VARARRAYS_2DIMRES);
}
array2 = new ComArray(new ComValue(newArrayObj, c),true); // should always be conformant since this is part of a safe array.
let safeArray = new Struct();
try {
safeArray.addMember(new ComValue(array.getValue().getDimensions(), types.SHORT));// dim
let elementSize = -1;
let flags = variantTypes.FADF_HAVEVARTYPE;
if (c == types.VARIANT) {
flags = (flags | variantTypes.FADF_VARIANT);
elementSize = 16; // (Variant is pointer whose size is 16)
}
else if (this.arryInits.includes(c)) {
if (c == types.COMSTRING) {
flags = (flags | variantTypes.FADF_BSTR);
} else if (c == types.COMOBJECT) {
flags = (flags | variantTypes.FADF_UNKNOWN);
FLAG |= Flags.FLAG_REPRESENTATION_USE_IUNKNOWN_IID;
} else
elementSize = 4; // Since all these are pointers inherently
} else {
elementSize = MarshalUnMarshalHelper.getLengthInBytes(new ComValue(null, c), null, c == types.BOOLEAN ? Flags.FLAG_REPRESENTATION_VARIANT_BOOL : Flags.FLAG_NULL); // All other types, basic types
}
let safeArrayBound = null;
let upperBounds = array.getValue().getUpperBounds();
let arrayOfSafeArrayBounds = new Array(array.getValue().getDimensions());
for (let i = 0; i < array.getValue().getDimensions(); i++) {
safeArrayBound = new Struct();
safeArrayBound.addMember(upperBounds[i]);
safeArrayBound.addMember(new ComValue(0, types.INTEGER)); // starts at 0
arrayOfSafeArrayBounds[i] = new ComValue(safeArrayBound, types.STRUCT);
}
let arrayOfSafeArrayBounds2 = new ComArray(new ComValue(arrayOfSafeArrayBounds, types.STRUCT),true);
safeArray.addMember(new ComValue(flags, types.SHORT));// flags
if (elementSize > 0) {
safeArray.addMember(new ComValue(elementSize, types.INTEGER));
} else {
elementSize = MarshalUnMarshalHelper.getLengthInBytes(obj[0], null, FLAG);
safeArray.addMember(new ComValue(elementSize, types.INTEGER));// size
}
safeArray.addMember(new ComValue(0, types.SHORT));// locks
safeArray.addMember(new ComValue(new Variant().getSupportedType(new ComValue(null, c), FLAG), types.SHORT));// variant array, safearrayunion
// peculiarity here, windows seems to be sending the signed type in VarType32...
if (c == types.BOOLEAN) {
safeArray.addMember(new Variant().getSupportedType(new ComValue(null, types.SHORT),FLAG));// safearrayunion
} else if (c == types.LONG) {
safeArray.addMember(new Variant().getSupportedType(new ComValue(null, types.LONG),FLAG));// safearrayunion
} else {
safeArray.addMember(new Variant().getSupportedType(new ComValue(null, c),FLAG));// safearrayunion
}
safeArray.addMember(new ComValue(array2.getNumElementsInAllDimensions(), types.INTEGER));// size in safearrayunion
let ptr2RealArray = new Pointer(new ComValue(array2, types.COMARRAY));
safeArray.addMember(new ComValue(ptr2RealArray, types.POINTER));
safeArray.addMember(new ComValue(arrayOfSafeArrayBounds2, types.COMARRAY));
} catch (e) {
throw new Error(e);
}
variant2 = new VariantBody(3,
{safeArray: new ComValue(safeArray,types.STRUCT), nestedClass: new ComValue(null, c),is2Dimensional: is2Dim,isByref: isByref,FLAG: FLAG});
this.init(new ComValue(variant2, types.VARIANTBODY),false);
}
getObject()
{
this.checkValidity();
return (this.member.getValue().getReferent());
}
getObjectAsInt(){
this.checkValidity();
return (this.member.getValue().getReferent()).getObjectAsInt();
}
getObjectAsFloat(){
this.checkValidity();
return (this.member.getValue().getReferent()).getObjectAsFloat();
}
getObjectAsCODE(){
this.checkValidity();
return (this.member.getValue().getReferent()).getObjectAsCODE();
}
getObjectAsDouble(){
this.checkValidity();
return (this.member.getValue().getReferent()).getObjectAsDouble();
}
getObjectAsShort(){
this.checkValidity();
return (this.member.getValue().getReferent()).getObjectAsShort();
}
getObjectAsBoolean(){
this.checkValidity();
return (this.member.getValue().getReferent()).getObjectAsBoolean();
}
getObjectAsString(){
this.checkValidity();
return (this.member.getValue().getReferent()).getObjectAsString();
}
// TO-DO: asString2
getObjectAsDate(){
this.checkValidity();
return (this.member.getValue().getReferent()).getObjectAsDate();
}
getObjectAsComObject(){
this.checkValidity();
return (this.member.getValue().getReferent()).getObjectAsComObject();
}
getObjectAsVariant(){
this.checkValidity();
return (this.member.getValue().getReferent()).getObjectAsVariant();
}
getObjectAsArray(){
this.checkValidity();
return (this.member.getValue().getReferent()).getObjectAsArray();
}
getObjectAsLong(){
this.checkValidity();
return (this.member.getValue().getReferent()).getObjectAsLong();
}
encode(ndr, defferedPointers, FLAG)
{
var ref = this.member.getValue();
ref.setDeffered(true);
MarshalUnMarshalHelper.serialize(ndr, new ComValue(ref, types.POINTER), defferedPointers, FLAG);
}
decode(ndr, defferedPointers, FLAG, addionalData)
{
var variant = new Variant();
var ref = new Pointer(new ComValue(null, types.VARIANTBODY));
ref.setDeffered(true);
variant.member = MarshalUnMarshalHelper.deSerialize(ndr, new ComValue(ref, types.POINTER), defferedPointers, FLAG, addionalData);
return new ComValue(variant, types.VARIANT);
}
isArray()
{
this.checkValidity();
return (this.member.getValue().getReferent()).isArray();
}
getLengthInBytes(FLAG)
{
this.checkValidity();
return MarshalUnMarshalHelper.getLengthInBytes(new ComValue(this.member.getValue().getReferent(), types.VARIANTBODY), FLAG);
}
isByRefFlagSet()
{
this.checkValidity();
return (this.member.getValue().getReferent()).isByref();
}
getType()
{
this.checkValidity();
return (this.member.getValue().getReferent()).getObject().getType();
}
checkValidity()
{
if (this.member == null || this.member.getValue().isNull()) {
throw new Error(new ErrorCodes().VARIANT_IS_NULL);
}
}
toString()
{
return this.member == null ? "[null]" : String('[' + this.member.getValue().toString() + ']');
}
} |
JavaScript | class Repo {
/**
* @param {Config} config Configuration
* @param {Logger} logger Logger
*/
constructor(config, logger) {
this.config = config || new Config();
this.logger = logger || new Logger(this.config);
this.crawledBillIds = [];
this.doneFile = path.join(this.config.outputDir, this.config.doneFile);
}
/**
* Creates output directory, then loads bill IDs from done-file.
*
* @returns {Repo} This object
*/
init() {
this.logger.verbose(`Könyvtár létrehozása: ${this.config.outputDir}`);
mkdirp(this.config.outputDir);
this.logger.verbose(`Kész-lista beolvasása: ${this.doneFile}`);
if (fs.existsSync(this.doneFile)) {
this.crawledBillIds = fs.readFileSync(this.doneFile, 'utf8').trim().split('\n');
}
this.logger.verbose(`${this.crawledBillIds.length} db számla van a kimeneti mappában`);
return this;
}
/**
* Creates new directory for given bill, returns directory path.
*
* @param {Bill} bill Bill
* @returns {string} Download directory for given bill
*/
directoryFor(bill) {
const d = path.join(this.config.outputDir, `${bill.serviceProvider} - ${bill.billIssuerId}`, bill.dateOfIssue);
mkdirp(d);
return d;
}
/**
* @param {Bill} bill Bill
* @returns {boolean} Whether bill is already downloaded completely (false means it is new)
*/
isDone(bill) {
return this.crawledBillIds.includes(this.normalizeBillId(bill));
}
/**
* @param {Bill} bill Bill
* @returns {boolean} Whether bill is new (false means it is already downloaded)
*/
isNew(bill) {
return !this.isDone(bill);
}
/**
* Marks given bill as downloaded completely.
*
* @param {Bill} bill Bill
*/
markAsDone(bill) {
fs.appendFileSync(this.doneFile, `${this.normalizeBillId(bill)}\n`);
}
/**
* Normalizes bill ID by removing newline characters.
*
* @param {Bill} bill Bill
* @returns {string} Normalized bill ID
*/
normalizeBillId(bill) {
return bill.billId.replace(/[\r\n]+/g, ' ').trim();
}
} |
JavaScript | class MultiLanguageGenerator extends multiLanguageGeneratorBase_1.MultiLanguageGeneratorBase {
constructor() {
super(...arguments);
/**
* Gets or sets the language generators for multiple languages.
*/
this.languageGenerators = new Map();
}
/**
* Implementation of lookup by locale.
* @param dialogContext Context for the current turn of conversation with the user.
* @param locale Locale to lookup.
*/
tryGetGenerator(dialogContext, locale) {
if (this.languageGenerators.has(locale)) {
return { exist: true, result: this.languageGenerators.get(locale) };
}
else {
return { exist: false, result: undefined };
}
}
} |
JavaScript | class Stream extends EventEmitter {
/**
* Holds subscriptions
*/
subscriptions = new Set();
/**
* Pre-auth queue
*/
queue = [];
/**
* If you're authenticated or not
*/
authenticated = false;
/**
* Stores the websocket connection
* @type {WebSocket | null}
*/
connection = null;
// The constructor
constructor(client, host, { auto = false }) {
// Makes a new event emitter :D
super();
// Pls provide client
if(!client)
throw new Error("You need to input a client to authenticate a stream");
// Since host is required.
if(!host)
throw new Error("You need to provide a host url to connect to!\n(Don't forget you can only have 1 websocket per host ;)");
// Stores client
this.client = client;
// Stores Host
this.host = host;
// If you want to auto connect
if (auto)
this.connect();
}
/**
* Sends a message to the connected websocket.
* @param {any} message The message itself
*/
send(message) {
// You need to be authenticated to send further messages
if(!this.authenticated)
this.queue.push(message);
// Sends the message.
else this.connection.send(Buffer.from(typeof message === "string" ? message : JSON.stringify(message)));
// Returns instance, making this chainable
return this;
}
/**
* Subscribes to channels
* @param {string[] | string} channels The channels you want to subscribe to
*/
subscribe(channels) {
// You need to have channels you want to subscribe to
if(!channels)
return this;
// Makes your channels an array forcefully
if (typeof channels !== "string")
channels = [channels];
// Your channels simply need to be an array xP
if (!Array.isArray(channels))
return this;
// If listens exists, it limits your channels to it
if(this.listens)
channels = channels.filter(c => this.listens.some(l => new RegExp(l).test(c)));
// Filters channels based on subscriptions
channels = channels.filter(this.subscriptions.has);
// Just return if there are no channels left over
if(!channels)
return this;
// Adds all subscriptions
this.subscriptions.add(...channels)
// Sends a message specifying to subscribe.
return this.send({
action: 'listen',
data: { streams: channels }
});
}
/**
* Unsubscribes from given channels
* @param {string[] | Set<string>} channels - The channels you want to unsubscribe from
* @returns {this}
*/
unsubscribe(channels) {
// Removes these channels
for (let i of channels)
if (this.subscriptions.has(i))
this.subscriptions.delete(i);
// Send the removal to the websocket
return this.send({
action: 'unlisten',
data: { streams: channels }
});
}
/**
* Connects to the websocket
* @returns {this}
*/
connect() {
// Connect to the host
this.connection = new WebSocket(this.host)
// Emits when the websocket is open
.once('open', () => {
// Listens for reply to authentication
this.connection.once("message", msg => {
// Converts the received buffer into an object
msg = JSON.parse(msg.toString());
// Checks status and terminates stream if you didn't authorize
if(msg.data?.status !== "authorized") {
this.connection.terminate(); throw new Error("There was an error in authorizing your websocket connection. Object received: " + JSON.stringify(msg, null, 2)); }
// else just send queued messages and emit the authorization event
else this.authenticated = true, this.queue.forEach(m => this.send(m)), this.emit("authentication", this);
})
// Sends the message for authentication
.send('{"action":"authenticate","data":{"key_id":"' + this.client.key + '","secret_key":"' + this.client.secret + '"}}');
// Emits the open event
this.emit("open", this)
})
// Emit a close event on websocket close.
.once('close', () => this.emit("close", this))
// listen to incoming messages
.on('message', message => this.emit("message", JSON.parse(message.toString())))
// Emits an error event.
.on('error', err => this.emit("error", err));
// For chainability
return this;
}
} |
JavaScript | class Account extends Stream {
// What you can listen to
listens = ["trade_updates", "account_updates"]
// The constructor
constructor(client, opts = {}) {
// Calls Stream
super(client, opts.paper ? urls.account.stream : urls.account.paper.stream, opts);
// Sets up custom message listener for account and trade updates
this.on("message", m => m.stream === "account_updates" ? this.emit("account_updates", m.data) : m.stream === "trade_updates" && this.emit("trade_updates", m.data));
}
} |
JavaScript | class Tab {
/**
* Constructor.
* @param {string} id The ID to track the element by
* @param {string} label The user facing label of the tab
* @param {string} icon The icon to display
* @param {string} template The template to compile
* @param {Object=} opt_data The optional data for the tab
*/
constructor(id, label, icon, template, opt_data) {
/**
* @type {string}
*/
this['id'] = id;
/**
* @type {string}
*/
this['label'] = label;
/**
* @type {string}
*/
this['icon'] = icon;
/**
* @type {string}
*/
this['template'] = template;
/**
* @type {*}
*/
this['data'] = opt_data || null;
}
} |
JavaScript | class GeometryEditor extends Eventable(Class) {
/**
* @param {Geometry} geometry geometry to edit
* @param {Object} [opts=null] options
* @param {Object} [opts.symbol=null] symbol of being edited.
*/
constructor(geometry, opts) {
super(opts);
this._geometry = geometry;
if (!this._geometry) {
return;
}
}
/**
* Get map
* @return {Map} map
*/
getMap() {
return this._geometry.getMap();
}
/**
* Prepare to edit
*/
prepare() {
const map = this.getMap();
if (!map) {
return;
}
/**
* reserve the original symbol
*/
if (this.options['symbol']) {
this._originalSymbol = this._geometry.getSymbol();
this._geometry.setSymbol(this.options['symbol']);
}
this._prepareEditStageLayer();
}
_prepareEditStageLayer() {
const map = this.getMap();
const uid = UID();
const stageId = EDIT_STAGE_LAYER_PREFIX + uid,
shadowId = EDIT_STAGE_LAYER_PREFIX + uid + '_shadow';
this._editStageLayer = map.getLayer(stageId);
this._shadowLayer = map.getLayer(shadowId);
if (!this._editStageLayer) {
this._editStageLayer = new VectorLayer(stageId);
map.addLayer(this._editStageLayer);
}
if (!this._shadowLayer) {
this._shadowLayer = new VectorLayer(shadowId);
map.addLayer(this._shadowLayer);
}
}
/**
* Start to edit
*/
start() {
if (!this._geometry || !this._geometry.getMap() || this._geometry.editing) {
return;
}
const map = this.getMap();
this.editing = true;
const geometry = this._geometry;
this._geometryDraggble = geometry.options['draggable'];
geometry.config('draggable', false);
this.prepare();
//edits are applied to a shadow of geometry to improve performance.
const shadow = geometry.copy();
shadow.setSymbol(geometry._getInternalSymbol());
//geometry copy没有将event复制到新建的geometry,对于编辑这个功能会存在一些问题
//原geometry上可能绑定了其它监听其click/dragging的事件,在编辑时就无法响应了.
shadow.copyEventListeners(geometry);
if (geometry._getParent()) {
shadow.copyEventListeners(geometry._getParent());
}
shadow._setEventTarget(geometry);
//drag shadow by center handle instead.
shadow.setId(null).config({
'draggable': false
});
this._shadow = shadow;
this._switchGeometryEvents('on');
geometry.hide();
if (geometry instanceof Marker ||
geometry instanceof Circle ||
geometry instanceof Rectangle ||
geometry instanceof Ellipse) {
//ouline has to be added before shadow to let shadow on top of it, otherwise shadow's events will be overrided by outline
this._createOrRefreshOutline();
}
this._shadowLayer.bringToFront().addGeometry(shadow);
this._editStageLayer.bringToFront();
this._addListener([map, 'zoomstart', () => { this._editStageLayer.hide(); }]);
this._addListener([map, 'zoomend', () => {
this._editStageLayer.show();
}]);
if (!(geometry instanceof Marker)) {
this._createCenterHandle();
} else {
shadow.config('draggable', true);
shadow.on('dragend', this._onMarkerDragEnd, this);
}
if (geometry instanceof Marker) {
this.createMarkerEditor();
} else if (geometry instanceof Circle) {
this.createCircleEditor();
} else if (geometry instanceof Rectangle) {
this.createEllipseOrRectEditor();
} else if (geometry instanceof Ellipse) {
this.createEllipseOrRectEditor();
} else if (geometry instanceof Sector) {
// TODO: createSectorEditor
} else if ((geometry instanceof Polygon) ||
(geometry instanceof LineString)) {
this.createPolygonEditor();
}
}
/**
* Stop editing
*/
stop() {
delete this._history;
delete this._historyPointer;
delete this._editOutline;
this._switchGeometryEvents('off');
const map = this.getMap();
if (!map) {
return;
}
delete this._shadow;
this._geometry.config('draggable', this._geometryDraggble);
delete this._geometryDraggble;
this._geometry.show();
this._editStageLayer.remove();
this._shadowLayer.remove();
this._clearAllListeners();
this._refreshHooks = [];
if (this.options['symbol']) {
this._geometry.setSymbol(this._originalSymbol);
delete this._originalSymbol;
}
this.editing = false;
}
/**
* Whether the editor is editing
* @return {Boolean}
*/
isEditing() {
if (isNil(this.editing)) {
return false;
}
return this.editing;
}
_getGeometryEvents() {
return {
'symbolchange': this._onGeoSymbolChange,
'positionchange shapechange': this._exeAndReset
};
}
_switchGeometryEvents(oper) {
if (this._geometry) {
const events = this._getGeometryEvents();
for (const p in events) {
this._geometry[oper](p, events[p], this);
}
}
}
_onGeoSymbolChange(param) {
if (this._shadow) {
this._shadow.setSymbol(param.target._getInternalSymbol());
}
}
_onMarkerDragEnd() {
this._update('setCoordinates', this._shadow.getCoordinates().toArray());
this._refresh();
}
/**
* create rectangle outline of the geometry
* @private
*/
_createOrRefreshOutline() {
const geometry = this._geometry;
let outline = this._editOutline;
if (!outline) {
outline = geometry.getOutline();
this._editStageLayer.addGeometry(outline);
this._editOutline = outline;
this._addRefreshHook(this._createOrRefreshOutline);
} else {
outline.remove();
this._editOutline = outline = geometry.getOutline();
this._editStageLayer.addGeometry(outline);
}
return outline;
}
_createCenterHandle() {
const center = this._shadow.getCenter();
const symbol = this.options['centerHandleSymbol'];
let shadow;
const handle = this.createHandle(center, {
'symbol': symbol,
'cursor': 'move',
onDown: () => {
shadow = this._shadow.copy();
const symbol = lowerSymbolOpacity(shadow._getInternalSymbol(), 0.5);
shadow.setSymbol(symbol).addTo(this._editStageLayer);
},
onMove: (v, param) => {
const offset = param['coordOffset'];
shadow.translate(offset);
},
onUp: () => {
this._update('setCoordinates', Coordinate.toNumberArrays(shadow.getCoordinates()));
shadow.remove();
this._refresh();
}
});
this._addRefreshHook(() => {
const center = this._shadow.getCenter();
handle.setCoordinates(center);
});
}
_createHandleInstance(coordinate, opts) {
const symbol = opts['symbol'];
const handle = new Marker(coordinate, {
'draggable': true,
'dragShadow': false,
'dragOnAxis': opts['axis'],
'cursor': opts['cursor'],
'symbol': symbol
});
return handle;
}
createHandle(coordinate, opts) {
if (!opts) {
opts = {};
}
const map = this.getMap();
const handle = this._createHandleInstance(coordinate, opts);
const me = this;
function onHandleDragstart(param) {
if (opts.onDown) {
/**
* change geometry shape start event, fired when drag to change geometry shape.
*
* @event Geometry#handledragstart
* @type {Object}
* @property {String} type - handledragstart
* @property {Geometry} target - the geometry fires the event
*/
this._geometry.fire('handledragstart');
opts.onDown.call(me, param['viewPoint'], param);
}
return false;
}
function onHandleDragging(param) {
me._hideContext();
const viewPoint = map._prjToViewPoint(handle._getPrjCoordinates());
if (opts.onMove) {
/**
* changing geometry shape event, fired when dragging to change geometry shape.
*
* @event Geometry#handledragging
* @type {Object}
* @property {String} type - handledragging
* @property {Geometry} target - the geometry fires the event
*/
this._geometry.fire('handledragging');
opts.onMove.call(me, viewPoint, param);
}
return false;
}
function onHandleDragEnd(ev) {
if (opts.onUp) {
/**
* changed geometry shape event, fired when drag end to change geometry shape.
*
* @event Geometry#handledragend
* @type {Object}
* @property {String} type - handledragend
* @property {Geometry} target - the geometry fires the event
*/
this._geometry.fire('handledragend');
opts.onUp.call(me, ev);
}
return false;
}
function onHandleRemove() {
handle.config('draggable', false);
handle.off('dragstart', onHandleDragstart, me);
handle.off('dragging', onHandleDragging, me);
handle.off('dragend', onHandleDragEnd, me);
handle.off('removestart', onHandleRemove, me);
delete handle['maptalks--editor-refresh-fn'];
}
handle.on('dragstart', onHandleDragstart, this);
handle.on('dragging', onHandleDragging, this);
handle.on('dragend', onHandleDragEnd, this);
handle.on('removestart', onHandleRemove, this);
//拖动移图
if (opts.onRefresh) {
handle['maptalks--editor-refresh-fn'] = opts.onRefresh;
}
this._editStageLayer.addGeometry(handle);
return handle;
}
/**
* create resize handles for geometry that can resize.
* @param {Array} blackList handle indexes that doesn't display, to prevent change a geometry's coordinates
* @param {fn} onHandleMove callback
* @private
*/
_createResizeHandles(blackList, onHandleMove, onHandleUp) {
//cursor styles.
const cursors = [
'nw-resize', 'n-resize', 'ne-resize',
'w-resize', 'e-resize',
'sw-resize', 's-resize', 'se-resize'
];
//defines dragOnAxis of resize handle
const axis = [
null, 'y', null,
'x', 'x',
null, 'y', null
];
const geometry = this._geometry;
function getResizeAnchors(ext) {
return [
// ext.getMin(),
new Point(ext['xmin'], ext['ymax']),
new Point((ext['xmax'] + ext['xmin']) / 2, ext['ymax']),
new Point(ext['xmax'], ext['ymax']),
new Point(ext['xmin'], (ext['ymax'] + ext['ymin']) / 2),
new Point(ext['xmax'], (ext['ymax'] + ext['ymin']) / 2),
new Point(ext['xmin'], ext['ymin']),
new Point((ext['xmax'] + ext['xmin']) / 2, ext['ymin']),
new Point(ext['xmax'], ext['ymin']),
];
}
if (!blackList) {
blackList = [];
}
const me = this;
const resizeHandles = [],
anchorIndexes = {},
map = this.getMap(),
handleSymbol = this.options['vertexHandleSymbol'];
const fnLocateHandles = () => {
const pExt = geometry._getPainter().get2DExtent(),
anchors = getResizeAnchors(pExt);
for (let i = 0; i < anchors.length; i++) {
//ignore anchors in blacklist
if (Array.isArray(blackList)) {
const isBlack = blackList.some(ele => ele === i);
if (isBlack) {
continue;
}
}
const anchor = anchors[i],
coordinate = map.pointToCoordinate(anchor);
if (resizeHandles.length < (anchors.length - blackList.length)) {
const handle = this.createHandle(coordinate, {
'symbol': handleSymbol,
'cursor': cursors[i],
'axis': axis[i],
onMove: (function (_index) {
return function (handleViewPoint) {
me._updating = true;
onHandleMove(handleViewPoint, _index);
geometry.fire('resizing');
};
})(i),
onUp: () => {
me._updating = false;
onHandleUp();
this._refresh();
}
});
handle.setId(i);
anchorIndexes[i] = resizeHandles.length;
resizeHandles.push(handle);
} else {
resizeHandles[anchorIndexes[i]].setCoordinates(coordinate);
}
}
};
fnLocateHandles();
//refresh hooks to refresh handles' coordinates
this._addRefreshHook(fnLocateHandles);
return resizeHandles;
}
/**
* Create marker editor
* @private
*/
createMarkerEditor() {
const geometryToEdit = this._geometry,
shadow = this._shadow,
map = this.getMap();
if (!shadow._canEdit()) {
if (console) {
console.warn('A marker can\'t be resized with symbol:', shadow.getSymbol());
}
return;
}
if (!this._history) {
this._recordHistory(getUpdates());
}
//only image marker and vector marker can be edited now.
const symbol = shadow._getInternalSymbol();
const dxdy = new Point(0, 0);
if (isNumber(symbol['markerDx'])) {
dxdy.x = symbol['markerDx'];
}
if (isNumber(symbol['markerDy'])) {
dxdy.y = symbol['markerDy'];
}
let blackList = null;
if (Symbolizers.VectorMarkerSymbolizer.test(symbol)) {
if (symbol['markerType'] === 'pin' || symbol['markerType'] === 'pie' || symbol['markerType'] === 'bar') {
//as these types of markers' anchor stands on its bottom
blackList = [5, 6, 7];
}
} else if (Symbolizers.ImageMarkerSymbolizer.test(symbol) ||
Symbolizers.VectorPathMarkerSymbolizer.test(symbol)) {
blackList = [5, 6, 7];
}
//defines what can be resized by the handle
//0: resize width; 1: resize height; 2: resize both width and height.
const resizeAbilities = [
2, 1, 2,
0, 0,
2, 1, 2
];
let aspectRatio;
if (this.options['fixAspectRatio']) {
const size = shadow.getSize();
aspectRatio = size.width / size.height;
}
const resizeHandles = this._createResizeHandles(null, (handleViewPoint, i) => {
if (blackList && blackList.indexOf(i) >= 0) {
//need to change marker's coordinates
const newCoordinates = map.viewPointToCoordinate(handleViewPoint.sub(dxdy));
const coordinates = shadow.getCoordinates();
newCoordinates.x = coordinates.x;
shadow.setCoordinates(newCoordinates);
this._updateCoordFromShadow(true);
// geometryToEdit.setCoordinates(newCoordinates);
//coordinates changed, and use mirror handle instead to caculate width and height
const mirrorHandle = resizeHandles[resizeHandles.length - 1 - i];
const mirrorViewPoint = map.coordToViewPoint(mirrorHandle.getCoordinates());
handleViewPoint = mirrorViewPoint;
}
//caculate width and height
const viewCenter = map._pointToViewPoint(shadow._getCenter2DPoint()).add(dxdy),
symbol = shadow._getInternalSymbol();
const wh = handleViewPoint.sub(viewCenter);
if (blackList && handleViewPoint.y > viewCenter.y) {
wh.y = 0;
}
//if this marker's anchor is on its bottom, height doesn't need to multiply by 2.
const r = blackList ? 1 : 2;
let width = Math.abs(wh.x) * 2,
height = Math.abs(wh.y) * r;
if (aspectRatio) {
width = Math.max(width, height * aspectRatio);
height = width / aspectRatio;
}
const ability = resizeAbilities[i];
if (!(shadow instanceof TextBox)) {
if (aspectRatio || ability === 0 || ability === 2) {
symbol['markerWidth'] = width;
}
if (aspectRatio || ability === 1 || ability === 2) {
symbol['markerHeight'] = height;
}
shadow.setSymbol(symbol);
geometryToEdit.setSymbol(symbol);
} else {
if (aspectRatio || ability === 0 || ability === 2) {
shadow.setWidth(width);
geometryToEdit.setWidth(width);
}
if (aspectRatio || ability === 1 || ability === 2) {
shadow.setHeight(height);
geometryToEdit.setHeight(height);
}
}
}, () => {
this._update(getUpdates());
});
function getUpdates() {
const updates = [
['setCoordinates', shadow.getCoordinates().toArray()]
];
if (shadow instanceof TextBox) {
updates.push(['setWidth', shadow.getWidth()]);
updates.push(['setHeight', shadow.getHeight()]);
} else {
updates.push(['setSymbol', shadow.getSymbol()]);
}
return updates;
}
function onZoomEnd() {
this._refresh();
}
this._addListener([map, 'zoomend', onZoomEnd]);
}
/**
* Create circle editor
* @private
*/
createCircleEditor() {
const circle = this._geometry,
shadow = this._shadow;
const map = this.getMap();
if (!this._history) {
this._recordHistory([
['setCoordinates', shadow.getCoordinates().toArray()],
['setRadius', shadow.getRadius()]
]);
}
this._createResizeHandles(null, handleViewPoint => {
const center = circle.getCenter();
const mouseCoordinate = map.viewPointToCoordinate(handleViewPoint);
const wline = new LineString([[center.x, center.y], [mouseCoordinate.x, center.y]]);
const hline = new LineString([[center.x, center.y], [center.x, mouseCoordinate.y]]);
const r = Math.max(map.computeGeometryLength(wline), map.computeGeometryLength(hline));
// const viewCenter = map._pointToViewPoint(shadow._getCenter2DPoint());
// const wh = handleViewPoint.sub(viewCenter);
// const w = Math.abs(wh.x),
// h = Math.abs(wh.y);
// let r;
// if (w > h) {
// r = map.pixelToDistance(w, 0);
// } else {
// r = map.pixelToDistance(0, h);
// }
shadow.setRadius(r);
circle.setRadius(r);
}, () => {
this._update('setRadius', shadow.getRadius());
});
}
/**
* editor of ellipse or rectangle
* @private
*/
createEllipseOrRectEditor() {
//defines what can be resized by the handle
//0: resize width; 1: resize height; 2: resize both width and height.
const resizeAbilities = [
2, 1, 2,
0, 0,
2, 1, 2
];
const geometryToEdit = this._geometry,
shadow = this._shadow;
if (!this._history) {
this._recordHistory(getUpdates());
}
const map = this.getMap();
const isRect = this._geometry instanceof Rectangle;
let aspectRatio;
if (this.options['fixAspectRatio']) {
aspectRatio = geometryToEdit.getWidth() / geometryToEdit.getHeight();
}
const resizeHandles = this._createResizeHandles(null, (mouseViewPoint, i) => {
//ratio of width and height
const r = isRect ? 1 : 2;
let pointSub, w, h;
const targetPoint = mouseViewPoint;
const ability = resizeAbilities[i];
if (isRect) {
const mirror = resizeHandles[7 - i];
const mirrorViewPoint = map.coordToViewPoint(mirror.getCoordinates());
pointSub = targetPoint.sub(mirrorViewPoint);
const absSub = pointSub.abs();
w = map.pixelToDistance(absSub.x, 0);
h = map.pixelToDistance(0, absSub.y);
const size = geometryToEdit.getSize();
const firstMirrorCoordinate = resizeHandles[0].getCoordinates();
const mouseCoordinate = map.viewPointToCoordinate(mouseViewPoint);
const mirrorCoordinate = mirror.getCoordinates();
const wline = new LineString([[mirrorCoordinate.x, mirrorCoordinate.y], [mouseCoordinate.x, mirrorCoordinate.y]]);
const hline = new LineString([[mirrorCoordinate.x, mirrorCoordinate.y], [mirrorCoordinate.x, mouseCoordinate.y]]);
//fix distance cal error
w = map.computeGeometryLength(wline);
h = map.computeGeometryLength(hline);
if (ability === 0) {
// changing width
// - - -
// 0 0
// - - -
// Rectangle's northwest's y is (y - height / 2)
if (aspectRatio) {
// update rectangle's height with aspect ratio
absSub.y = absSub.x / aspectRatio;
size.height = Math.abs(absSub.y);
h = w / aspectRatio;
}
targetPoint.y = mirrorViewPoint.y - size.height / 2;
mouseCoordinate.y = firstMirrorCoordinate.y;
if (i === 4) {
mouseCoordinate.x = Math.min(mouseCoordinate.x, firstMirrorCoordinate.x);
} else {
mouseCoordinate.x = Math.min(mouseCoordinate.x, mirrorCoordinate.x);
}
} else if (ability === 1) {
// changing height
// - 1 -
// | |
// - 1 -
// Rectangle's northwest's x is (x - width / 2)
if (aspectRatio) {
// update rectangle's width with aspect ratio
absSub.x = absSub.y * aspectRatio;
size.width = Math.abs(absSub.x);
w = h * aspectRatio;
}
targetPoint.x = mirrorViewPoint.x - size.width / 2;
mouseCoordinate.x = firstMirrorCoordinate.x;
mouseCoordinate.y = Math.max(mouseCoordinate.y, mirrorCoordinate.y);
} else {
// corner handles, relocate the target point according to aspect ratio.
if (aspectRatio) {
if (w > h * aspectRatio) {
h = w / aspectRatio;
targetPoint.y = mirrorViewPoint.y + absSub.x * sign(pointSub.y) / aspectRatio;
} else {
w = h * aspectRatio;
targetPoint.x = mirrorViewPoint.x + absSub.y * sign(pointSub.x) * aspectRatio;
}
}
mouseCoordinate.x = Math.min(mouseCoordinate.x, mirrorCoordinate.x);
mouseCoordinate.y = Math.max(mouseCoordinate.y, mirrorCoordinate.y);
}
//change rectangle's coordinates
// const newCoordinates = map.viewPointToCoordinate(new Point(Math.min(targetPoint.x, mirrorViewPoint.x), Math.min(targetPoint.y, mirrorViewPoint.y)));
shadow.setCoordinates(mouseCoordinate);
this._updateCoordFromShadow(true);
// geometryToEdit.setCoordinates(newCoordinates);
} else {
// const viewCenter = map.coordToViewPoint(geometryToEdit.getCenter());
// pointSub = viewCenter.sub(targetPoint)._abs();
// w = map.pixelToDistance(pointSub.x, 0);
// h = map.pixelToDistance(0, pointSub.y);
// if (aspectRatio) {
// w = Math.max(w, h * aspectRatio);
// h = w / aspectRatio;
// }
const center = geometryToEdit.getCenter();
const mouseCoordinate = map.viewPointToCoordinate(targetPoint);
const wline = new LineString([[center.x, center.y], [mouseCoordinate.x, center.y]]);
const hline = new LineString([[center.x, center.y], [center.x, mouseCoordinate.y]]);
w = map.computeGeometryLength(wline);
h = map.computeGeometryLength(hline);
if (aspectRatio) {
w = Math.max(w, h * aspectRatio);
h = w / aspectRatio;
}
}
if (aspectRatio || ability === 0 || ability === 2) {
shadow.setWidth(w * r);
geometryToEdit.setWidth(w * r);
}
if (aspectRatio || ability === 1 || ability === 2) {
shadow.setHeight(h * r);
geometryToEdit.setHeight(h * r);
}
}, () => {
this._update(getUpdates());
});
function getUpdates() {
return [
['setCoordinates', shadow.getCoordinates().toArray()],
['setWidth', shadow.getWidth()],
['setHeight', shadow.getHeight()]
];
}
}
/**
* Editor for polygon
* @private
*/
createPolygonEditor() {
const map = this.getMap(),
shadow = this._shadow,
me = this,
projection = map.getProjection();
if (!this._history) {
this._recordHistory('setCoordinates', Coordinate.toNumberArrays(shadow.getCoordinates()));
}
const verticeLimit = shadow instanceof Polygon ? 3 : 2;
const propertyOfVertexRefreshFn = 'maptalks--editor-refresh-fn',
propertyOfVertexIndex = 'maptalks--editor-vertex-index';
//{ ringIndex:ring }
const vertexHandles = { 0: [] },
newVertexHandles = { 0: [] };
function getVertexCoordinates(ringIndex = 0) {
if (shadow instanceof Polygon) {
const coordinates = shadow.getCoordinates()[ringIndex] || [];
return coordinates.slice(0, coordinates.length - 1);
} else {
return shadow.getCoordinates();
}
}
function getVertexPrjCoordinates(ringIndex = 0) {
if (ringIndex === 0) {
return shadow._getPrjCoordinates();
}
return shadow._getPrjHoles()[ringIndex - 1];
}
function onVertexAddOrRemove() {
//restore index property of each handles.
for (const ringIndex in vertexHandles) {
for (let i = vertexHandles[ringIndex].length - 1; i >= 0; i--) {
vertexHandles[ringIndex][i][propertyOfVertexIndex] = i;
}
for (let i = newVertexHandles[ringIndex].length - 1; i >= 0; i--) {
newVertexHandles[ringIndex][i][propertyOfVertexIndex] = i;
}
}
me._updateCoordFromShadow();
}
function removeVertex(param) {
const handle = param['target'],
index = handle[propertyOfVertexIndex];
const ringIndex = isNumber(handle._ringIndex) ? handle._ringIndex : 0;
const prjCoordinates = getVertexPrjCoordinates(ringIndex);
if (prjCoordinates.length <= verticeLimit) {
return;
}
prjCoordinates.splice(index, 1);
if (ringIndex > 0) {
shadow._prjHoles[ringIndex - 1] = prjCoordinates;
} else {
shadow._setPrjCoordinates(prjCoordinates);
}
shadow._updateCache();
//remove vertex handle
vertexHandles[ringIndex].splice(index, 1)[0].remove();
//remove two neighbor "new vertex" handles
if (index < newVertexHandles[ringIndex].length) {
newVertexHandles[ringIndex].splice(index, 1)[0].remove();
}
let nextIndex;
if (index === 0) {
nextIndex = newVertexHandles[ringIndex].length - 1;
} else {
nextIndex = index - 1;
}
newVertexHandles[ringIndex].splice(nextIndex, 1)[0].remove();
//add a new "new vertex" handle.
newVertexHandles[ringIndex].splice(nextIndex, 0, createNewVertexHandle.call(me, nextIndex, ringIndex));
onVertexAddOrRemove();
me._refresh();
}
function moveVertexHandle(handleViewPoint, index, ringIndex = 0) {
const vertice = getVertexPrjCoordinates(ringIndex);
const nVertex = map._viewPointToPrj(handleViewPoint);
const pVertex = vertice[index];
pVertex.x = nVertex.x;
pVertex.y = nVertex.y;
shadow._updateCache();
shadow.onShapeChanged();
me._updateCoordFromShadow(true);
let nextIndex;
if (index === 0) {
nextIndex = newVertexHandles[ringIndex].length - 1;
} else {
nextIndex = index - 1;
}
//refresh two neighbor "new vertex" handles.
if (newVertexHandles[ringIndex][index]) {
newVertexHandles[ringIndex][index][propertyOfVertexRefreshFn]();
}
if (newVertexHandles[ringIndex][nextIndex]) {
newVertexHandles[ringIndex][nextIndex][propertyOfVertexRefreshFn]();
}
}
function createVertexHandle(index, ringIndex = 0) {
let vertex = getVertexCoordinates(ringIndex)[index];
const handle = me.createHandle(vertex, {
'symbol': me.options['vertexHandleSymbol'],
'cursor': 'pointer',
'axis': null,
onMove: function (handleViewPoint) {
moveVertexHandle(handleViewPoint, handle[propertyOfVertexIndex], ringIndex);
},
onRefresh: function () {
vertex = getVertexCoordinates(ringIndex)[handle[propertyOfVertexIndex]];
handle.setCoordinates(vertex);
},
onUp: function () {
me._refresh();
me._updateCoordFromShadow();
},
onDown: function (param, e) {
if (e && e.domEvent && e.domEvent.button === 2) {
return;
}
}
});
handle[propertyOfVertexIndex] = index;
handle._ringIndex = ringIndex;
handle.on(me.options['removeVertexOn'], removeVertex);
return handle;
}
function createNewVertexHandle(index, ringIndex = 0) {
let vertexCoordinates = getVertexCoordinates(ringIndex);
let nextVertex;
if (index + 1 >= vertexCoordinates.length) {
nextVertex = vertexCoordinates[0];
} else {
nextVertex = vertexCoordinates[index + 1];
}
const vertex = vertexCoordinates[index].add(nextVertex).multi(1 / 2);
const handle = me.createHandle(vertex, {
'symbol': me.options['newVertexHandleSymbol'],
'cursor': 'pointer',
'axis': null,
onDown: function (param, e) {
if (e && e.domEvent && e.domEvent.button === 2) {
return;
}
const prjCoordinates = getVertexPrjCoordinates(ringIndex);
const vertexIndex = handle[propertyOfVertexIndex];
//add a new vertex
const pVertex = projection.project(handle.getCoordinates());
//update shadow's vertice
prjCoordinates.splice(vertexIndex + 1, 0, pVertex);
if (ringIndex > 0) {
//update hole
shadow._prjHoles[ringIndex - 1] = prjCoordinates;
} else {
shadow._setPrjCoordinates(prjCoordinates);
}
shadow._updateCache();
const symbol = handle.getSymbol();
delete symbol['opacity'];
handle.setSymbol(symbol);
//add two "new vertex" handles
newVertexHandles[ringIndex].splice(vertexIndex, 0, createNewVertexHandle.call(me, vertexIndex, ringIndex), createNewVertexHandle.call(me, vertexIndex + 1, ringIndex));
},
onMove: function (handleViewPoint) {
moveVertexHandle(handleViewPoint, handle[propertyOfVertexIndex] + 1, ringIndex);
},
onUp: function (e) {
if (e && e.domEvent && e.domEvent.button === 2) {
return;
}
const vertexIndex = handle[propertyOfVertexIndex];
//remove this handle
removeFromArray(handle, newVertexHandles[ringIndex]);
handle.remove();
//add a new vertex handle
vertexHandles[ringIndex].splice(vertexIndex + 1, 0, createVertexHandle.call(me, vertexIndex + 1, ringIndex));
onVertexAddOrRemove();
me._updateCoordFromShadow();
me._refresh();
},
onRefresh: function () {
vertexCoordinates = getVertexCoordinates(ringIndex);
const vertexIndex = handle[propertyOfVertexIndex];
let nextIndex;
if (vertexIndex === vertexCoordinates.length - 1) {
nextIndex = 0;
} else {
nextIndex = vertexIndex + 1;
}
const refreshVertex = vertexCoordinates[vertexIndex].add(vertexCoordinates[nextIndex]).multi(1 / 2);
handle.setCoordinates(refreshVertex);
}
});
handle[propertyOfVertexIndex] = index;
return handle;
}
if (shadow instanceof Polygon) {
const rings = shadow.getHoles().length + 1;
for (let ringIndex = 0; ringIndex < rings; ringIndex++) {
vertexHandles[ringIndex] = [];
newVertexHandles[ringIndex] = [];
const vertexCoordinates = getVertexCoordinates(ringIndex);
for (let i = 0, len = vertexCoordinates.length; i < len; i++) {
vertexHandles[ringIndex].push(createVertexHandle.call(this, i, ringIndex));
if (i < len - 1) {
newVertexHandles[ringIndex].push(createNewVertexHandle.call(this, i, ringIndex));
}
}
//1 more vertex handle for polygon
newVertexHandles[ringIndex].push(createNewVertexHandle.call(this, vertexCoordinates.length - 1, ringIndex));
}
} else {
const ringIndex = 0;
const vertexCoordinates = getVertexCoordinates(ringIndex);
for (let i = 0, len = vertexCoordinates.length; i < len; i++) {
vertexHandles[ringIndex].push(createVertexHandle.call(this, i, ringIndex));
if (i < len - 1) {
newVertexHandles[ringIndex].push(createNewVertexHandle.call(this, i, ringIndex));
}
}
}
this._addRefreshHook(() => {
for (const ringIndex in newVertexHandles) {
for (let i = newVertexHandles[ringIndex].length - 1; i >= 0; i--) {
newVertexHandles[ringIndex][i][propertyOfVertexRefreshFn](ringIndex);
}
}
for (const ringIndex in vertexHandles) {
for (let i = vertexHandles[ringIndex].length - 1; i >= 0; i--) {
vertexHandles[ringIndex][i][propertyOfVertexRefreshFn](ringIndex);
}
}
});
}
_refresh() {
if (this._refreshHooks) {
for (let i = this._refreshHooks.length - 1; i >= 0; i--) {
this._refreshHooks[i].call(this);
}
}
}
_hideContext() {
if (this._geometry) {
this._geometry.closeMenu();
this._geometry.closeInfoWindow();
}
}
_addListener(listener) {
if (!this._eventListeners) {
this._eventListeners = [];
}
this._eventListeners.push(listener);
listener[0].on(listener[1], listener[2], this);
}
_clearAllListeners() {
if (this._eventListeners && this._eventListeners.length > 0) {
for (let i = this._eventListeners.length - 1; i >= 0; i--) {
const listener = this._eventListeners[i];
listener[0].off(listener[1], listener[2], this);
}
this._eventListeners = [];
}
}
_addRefreshHook(fn) {
if (!fn) {
return;
}
if (!this._refreshHooks) {
this._refreshHooks = [];
}
this._refreshHooks.push(fn);
}
_update(method, ...args) {
this._exeHistory([method, args]);
this._recordHistory(method, ...args);
}
_updateCoordFromShadow(ignoreRecord) {
if (!this._shadow) {
return;
}
const coords = this._shadow.getCoordinates();
const geo = this._geometry;
const updating = this._updating;
this._updating = true;
geo.setCoordinates(coords);
if (!ignoreRecord) {
this._recordHistory('setCoordinates', Coordinate.toNumberArrays(geo.getCoordinates()));
}
this._updating = updating;
}
_recordHistory(method, ...args) {
if (!this._history) {
this._history = [];
this._historyPointer = 0;
}
if (this._history.length) {
const lastOperation = this._history[this._history.length - 1];
if (lastOperation[0] === method && JSON.stringify(lastOperation[1]) === JSON.stringify(args)) {
return;
}
}
if (this._historyPointer < this._history.length - 1) {
// remove old 'next views'
this._history.splice(this._historyPointer + 1);
}
this._history.push([method, args]);
this._historyPointer = this._history.length - 1;
/**
* edit record event, fired when an edit happend and being recorded
*
* @event Geometry#editrecord
* @type {Object}
* @property {String} type - editrecord
* @property {Geometry} target - the geometry fires the event
*/
this._geometry.fire('editrecord');
}
cancel() {
if (!this._history || this._historyPointer === 0) {
return this;
}
this._historyPointer = 0;
const record = this._history[0];
this._exeAndReset(record);
return this;
}
/**
* Get previous map view in view history
* @return {Object} map view
*/
undo() {
if (!this._history || this._historyPointer === 0) {
return this;
}
const record = this._history[--this._historyPointer];
this._exeAndReset(record);
return this;
}
/**
* Get next view in view history
* @return {Object} map view
*/
redo() {
if (!this._history || this._historyPointer === this._history.length - 1) {
return this;
}
const record = this._history[++this._historyPointer];
this._exeAndReset(record);
return this;
}
_exeAndReset(record) {
if (this._updating) {
return;
}
this._exeHistory(record);
const history = this._history,
pointer = this._historyPointer;
this.stop();
this._history = history;
this._historyPointer = pointer;
this.start();
}
_exeHistory(record) {
if (!Array.isArray(record)) {
return;
}
const updating = this._updating;
this._updating = true;
const geo = this._geometry;
if (Array.isArray(record[0])) {
record[0].forEach(o => {
const m = o[0],
args = o.slice(1);
this._shadow[m].apply(this._shadow, args);
geo[m].apply(geo, args);
});
} else {
this._shadow[record[0]].apply(this._shadow, record[1]);
geo[record[0]].apply(geo, record[1]);
}
this._updating = updating;
}
} |
JavaScript | class Lesson extends Component {
constructor( props, session ) {
super( props );
this.state = {
visible: session.lessonID ? ( session.isActive() || session.isOwner() ) : true
};
}
componentDidMount() {
const session = this.context;
session.onLessonMount();
this.unsubscribe = session.subscribe( ( type, value ) => {
if (
type === RECEIVED_LESSON_INFO ||
type === RECEIVED_USER_RIGHTS
) {
this.setState({
visible: session.isActive() || session.isOwner()
});
}
});
}
addNote = ({ left, top, visibility, noteID }) => {
const session = this.context;
session.saveStickyNote({
left, top, visibility
});
if ( !noteID ) {
noteID = randomstring( 3 );
const session = this.context;
session.log({
id: 'lesson',
type: INSERT_STICKY_NOTE,
value: {
top,
left,
noteID
}
});
}
}
render() {
if ( !this.state.visible ) {
return (
<I18nextProvider i18n={i18n} >
<Forbidden />
</I18nextProvider>
);
}
return (
<I18nextProvider i18n={i18n} >
<ContextMenuTrigger
attributes={{
className: 'contextmenu-fullscreen'
}}
holdToDisplay={-1}
disableIfShiftIsPressed
id="lessonWindow"
>
<div
id="Lesson"
className={this.props.className}
style={this.props.style}
>
{this.props.children}
<StickyNotes />
<InterfaceTourButton />
<LanguageSwitcher />
</div>
</ContextMenuTrigger>
<LessonContextMenu
addNote={this.addNote}
session={this.context}
/>
<ReactNotificationSystem
ref={( div ) => {
global.notificationSystemISLE = div;
}}
allowHTML={true}
style={NOTIFICATION_STYLE}
/>
</I18nextProvider>
);
}
} |
JavaScript | class LogIn extends Component {
constructor(props) {
super(props)
this.state = {
email: '',
password: '',
errorMessage: '',
wrongInfo: false
}
}
handleChange = event => {
this.setState({ [event.target.name]: event.target.value })
}
handleSubmit = async e => {
e.preventDefault()
const result = await login(this.state.email, this.state.password)
if (
result.error != null &&
(result.error.response.status === 400 || result.error.response.status === 500)
) {
this.setState({
wrongInfo: !this.state.wrongInfo,
errorMessage: result.error.response.data.message
})
return
}
let token = result.response.data.result.token
if (!token) {
this.setState({
wrongInfo: !this.state.wrongInfo,
errorMessage: result.response.message
})
} else {
this.setState({
wrongInfo: !this.state.wrongInfo
})
await setCookie('token', token)
let role = await verify()
if (role.error) {
this.props.history.push('/oops')
} else {
role = role.response.data.result.role
if (role === 'fp') {
let fp = await getFPByEmail(this.state.email)
if (fp) {
this.props.history.push('/dashboard/fp/' + fp._id)
} else {
this.setState({
wrongInfo: !this.state.wrongInfo,
errorMessage: 'Provided Field Partner does not exist!'
})
}
} else {
let pm = await getPMByEmail(this.state.email)
if (pm) {
this.props.history.push('/overview/' + pm._id)
} else {
this.setState({
wrongInfo: !this.state.wrongInfo,
errorMessage: 'Provided Portfolio Manager does not exist!'
})
}
}
}
}
}
languages = {
English: {
email: 'Email',
password: 'Password',
logIn: 'Log in',
register: 'Register',
forgotPassword: 'Forgot password?'
},
Spanish: {
email: 'Correo electronico',
password: 'Contraseña',
logIn: 'Iniciar sesión',
register: 'Regístrate',
forgotPassword: 'Olvidaste la contraseña?'
},
French: {
email: 'Courrier électronique',
password: 'Mot de passe',
logIn: 'Se connecter',
register: "S'enregistrer",
forgotPassword: 'Mot de passe oublié?'
},
Portuguese: {
email: 'Email',
password: 'Senha',
logIn: 'Acessar',
register: 'Inscrever-se',
forgotPassword: 'Esqueceu a senha?'
}
}
render() {
let text = this.languages[this.props.language]
if (!text) {
text = this.languages['English']
}
return (
<div>
<Navbar className="nav-absolute" />
<div className="background">
<BackgroundSlideshow images={[b1, b3, b4, b5, b6]} animationDelay={5000} />
</div>
<div className="foreground">
<Card className="interview-card center-background">
<CardBody>
<div className="text-centered" id="login-kiva-logo">
<img src={kivaLogo} alt="Kiva logo" />
</div>
<Form onSubmit={this.handleSubmit}>
<FormGroup>
<Input
type="email"
name="email"
placeholder={text.email}
id="exampleEmail"
maxLength="64"
pattern={EMAIL_REGEX}
value={this.state.email}
onChange={this.handleChange}
required
/>
</FormGroup>
<FormGroup>
<Input
type="password"
name="password"
placeholder={text.password}
id="examplePassword"
minLength="8"
maxLength="64"
value={this.state.password}
onChange={this.handleChange}
required
/>
</FormGroup>
<div className="text-centered">
<Button
type="submit"
color="success"
size="lg"
onClick={this.handleSubmit}
className="right"
>
{text.logIn}
</Button>
{''}
<Button
color="success"
size="lg"
onClick={() => this.props.history.push('/register')}
className="left left-margin-lg"
>
{text.register}
</Button>
</div>
</Form>
<p style={{ color: 'red', textAlign: 'center' }}>
{this.state.errorMessage ? this.state.errorMessage : ''}
</p>
<Link
id="forgot"
className="text-centered margin-center"
to="/forgotPassword"
href="/forgotPassword"
>
{text.forgotPassword}
</Link>
</CardBody>
</Card>
<br />
</div>
</div>
)
}
} |
JavaScript | class ThanksNextPetition extends React.Component {
constructor(props) {
super(props)
this.startSeconds = 10
this.state = {
cancelled: false,
secondsLeft: this.startSeconds + 1,
intervalListener: null
}
this.startCountdown = this.startCountdown.bind(this)
this.tickCounter = this.tickCounter.bind(this)
}
componentWillMount() {
// Start countdown on refocusing to this window
window.addEventListener('focus', this.startCountdown)
}
startCountdown() {
window.removeEventListener('focus', this.startCountdown)
// Guard against running twice -- countdown should be a singleton
if (this.state.secondsLeft > this.startSeconds) {
if (this.state.intervalListener) {
clearInterval(this.state.intervalListener)
}
this.setState({ intervalListener: setInterval(this.tickCounter, 1000) })
}
}
tickCounter() {
if (this.state.cancelled) {
if (this.state.intervalListener) {
clearInterval(this.state.intervalListener)
this.setState({
intervalListener: null,
secondsLeft: this.startSeconds + 1
})
}
return
}
const newSecondsLeft = this.state.secondsLeft - 1
this.setState({ secondsLeft: newSecondsLeft })
if (newSecondsLeft <= 0) {
this.redirectToNext()
}
}
nextUrl() {
const { nextPetition } = this.props
return nextPetition ? `/sign/${nextPetition.name}?source=share_chain` : ''
}
redirectToNext() {
if (this.state.intervalListener) {
clearInterval(this.state.intervalListener)
this.setState({ intervalListener: null })
}
const nextUrl = this.nextUrl()
if (nextUrl) {
appLocation.push(nextUrl)
}
}
render() {
if (!this.props.nextPetition || this.state.cancelled) {
return null
}
return (
<ThanksNextPetitionComponent
secondsLeft={this.state.secondsLeft}
onCancel={() => this.setState({ cancelled: true })}
/>
)
}
} |
JavaScript | class MatchesList extends blessed.list {
constructor(matches, config) {
config = _.merge({}, defaultConfig, config || {});
super(config);
this.config = config;
this.matches = matches;
this.matchesData = mapMatches(matches);
this.actionsList = null;
this.searchBox = null;
// Set list, bind watchers, and display
this.setItems(matches);
this.on('select', this.selectMatch);
this.key('right', this.selectMatch);
this.key('left', Utils.quit);
this.key('/', this.search);
this.focus();
screen.render();
}
appendMatches(matches) {
if (matches.length) {
this.spliceItem(this.matches.length, 0, ...matches);
this.matches = this.matches.concat(matches);
this.matchesData = this.matchesData.concat(mapMatches(matches));
screen.render();
}
}
getSelectedMatch() {
return this.matchesData[this.selected];
}
async getSelectedMatchType() {
return await this.getSelectedMatch().type;
}
onChildCancel() {
this.actionsList = this.searchBox = null;
this.focus();
}
async selectMatch() {
this.actionsList = new ActionsList(
this.getSelectedMatch().match,
await this.getSelectedMatchType(),
this.onChildCancel.bind(this),
{ parent: this.config.parent }
);
}
search() {
this.searchBox = new Search(
this.matches,
this.highlightMatch.bind(this),
this.onChildCancel.bind(this),
this.selectMatch.bind(this),
{ parent: this.config.parent }
);
}
highlightMatch(index) {
this.select(index);
}
} |
JavaScript | class Board extends React.Component {
renderSquare(i) {
return (
<Square
i={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
/>
);
// return <Square i={this.props.squares[i]} />; // custom React component // pass data through props
// return <Square>aaaa{i}</Square>; // custom React components
}
render() {
return (
<div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
} |
JavaScript | class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
history: [
{
squares: Array(9).fill(null),
}
],
xIsNext: true,
};
}
// conventional in React apps to
// use on* names for the attributes and
// use handle* for the handler methods
handleClick(i) {
const history = this.state.history;
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
const squares1 = squares.slice();
squares1[i] = this.state.xIsNext ? 'X' : 'O';
history.push({ squares: squares1, });
this.setState(
{
xIsNext: !this.state.xIsNext
}
);
}
render() {
let status;
const history = this.state.history;
const current = history[history.length - 1];
const winner = calculateWinner(current.squares);
// array.map( function(currentValue, index, arr), thisValue)
const moves =
history
.map(
(step, move) => {
const desc = move ? 'Go to move #' + move : 'Go to game start';
return (
<li key={move}>
<button onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
);
}
);
if (winner) {
status = 'Winner: ' + winner;
} else {
status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
}
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClick={(i) => this.handleClick(i)}
/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{moves}</ol>
</div>
</div >
);
// Component keys like in
//
// <li key={user.id}>{user.name}: {user.taskCount} tasks left</li>
//
// key is a special property that’s reserved by React (along with ref, a more advanced feature).
// When an element is created,
// React
// pulls off the key property and
// stores the key directly on the returned element.
// Even though it may look like it is part of props,
// it cannot be referenced with this.props.key.
// React uses the key automatically
// while deciding which children to update;
// There is no way for a component to inquire about its own key.
//
// When a list is rerendered,
// React takes each element in the new version and
// looks for one with a matching key in the previous list.
// When a key of a component is added to the set, a component is created;
// when a key of a component is removed, a component is destroyed.
// when a key of a component is changed, it will be completely destroyed & recreated with a new state.
// Keys tell React about the identity of each component,
// so that it can maintain the state across rerenders.
// It’s strongly recommended that you assign proper keys whenever you build dynamic lists.
// If you don’t have an appropriate key handy,
// you may want to consider restructuring your data so that you do.
//
// If you don’t specify any key,
// React will warn you and
// fall back to using the array index as a key
// – which is not the correct choice if you ever reorder elements in the list or
// add / remove items anywhere but the bottom of the list.
// Explicitly passing key= { i } silences the warning but
// has the same problem so isn’t recommended in most cases.
//
// Component keys like in
// <ol>{moves}</ol> when li are populated
// <li key={user.id}>{user.name}: {user.taskCount} tasks left</li>
// don’t need to be globally unique,
// only unique relative to the immediate siblings.
}
} |
JavaScript | class TransactionDetailScreen extends Component {
static navigationOptions = ({ navigation }) => ({
header: (
<Header>
<Left>
<Button transparent onPress={() => navigation.goBack()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>Transaction</Title>
</Body>
<Right />
</Header>
),
});
state = {
confirmBlocks: null,
inputPinCode: null,
loading: false,
};
componentDidMount = () => {
this._fetchTransactionDetail();
};
_fetchTransactionDetail = async () => {
const { navigation } = this.props;
const { transaction, wallet } = navigation.state.params;
if (transaction.txid === '' || transaction.dropped) {
return;
}
try {
const { confirmBlocks, data } = await Wallets.getTransactionInfo(
wallet.currency,
transaction.txid
);
this.setState({ confirmBlocks });
} catch (error) {
console.log('Wallets.getTransactionInfo failed', error);
toastError(error);
}
};
_explorer = () => {
const { navigation } = this.props;
const { transaction, wallet } = navigation.state.params;
const uri = getTransactionExplorerUri({ ...wallet, ...transaction });
if (uri) {
Linking.openURL(uri).catch(console.error);
}
};
_increaseTransactionFee = async pinSecret => {
const { navigation } = this.props;
const { transaction, wallet } = navigation.state.params;
this.setState({ loading: true });
try {
await Wallets.increaseTransactionFee(
wallet.walletId,
transaction.txid,
LARGER_TX_FEE,
pinSecret
);
navigation.goBack();
} catch (error) {
console.log('Wallets.increaseTransactionFee failed', error);
toastError(error);
this._finishInputPinCode();
}
this.setState({ loading: false });
};
_cancelTransaction = async pinSecret => {
const { navigation } = this.props;
const { transaction, wallet } = navigation.state.params;
this.setState({ loading: true });
try {
await Wallets.cancelTransaction(
wallet.walletId,
transaction.txid,
LARGER_TX_FEE,
pinSecret
);
navigation.goBack();
} catch (error) {
console.log('Wallets.cancelTransaction failed', error);
toastError(error);
this._finishInputPinCode();
}
this.setState({ loading: false });
};
_inputPinCode = action => {
this.setState({ inputPinCode: action });
};
_finishInputPinCode = () => {
this.setState({ inputPinCode: null });
};
render() {
const { navigation } = this.props;
const { transaction, wallet, isFungibleToken } = navigation.state.params;
const withdraw = transaction.fromAddress === wallet.address;
const { confirmBlocks, inputPinCode, loading } = this.state;
// console.log('TX', transaction);
return (
<Container>
<Content
style={{ flex: 1 }}
contentContainerStyle={{
padding: 16,
}}
>
<View
style={{
flexDirection: 'row',
alignSelf: 'center',
alignItems: 'center',
}}
>
<CurrencyIcon {...wallet} dimension={42} />
<CurrencyText
{...wallet}
textStyle={{
fontSize: 24,
marginStart: 8,
}}
/>
</View>
<View
style={[
styles.label,
{
flexDirection: 'row',
alignItems: 'center',
},
]}
>
<Text>From</Text>
{withdraw && (
<Badge warning style={styles.badge}>
<Text>WITHDRAW</Text>
</Badge>
)}
</View>
<Text style={styles.value}>{transaction.fromAddress}</Text>
<View
style={[
styles.label,
{
flexDirection: 'row',
alignItems: 'center',
},
]}
>
<Text>To</Text>
{!withdraw && (
<Badge success style={styles.badge}>
<Text>DEPOSIT</Text>
</Badge>
)}
</View>
<Text style={styles.value}>{transaction.toAddress}</Text>
<View
style={[
styles.label,
{
flexDirection: 'row',
alignItems: 'center',
},
]}
>
<Text>{isFungibleToken ? 'Token ID' : 'Amount'}</Text>
{transaction.platformFee && (
<Badge info style={styles.badge}>
<Text>PLATFORM FEE</Text>
</Badge>
)}
</View>
<Text style={styles.value}>
{transaction.amount} {!isFungibleToken && wallet.currencySymbol}
</Text>
<Text style={styles.label}>Transaction fee</Text>
<Text style={styles.value}>{transaction.transactionFee}</Text>
<View
style={[
styles.label,
{
flexDirection: 'row',
alignItems: 'center',
},
]}
>
<Text>TXID</Text>
{transaction.pending && (
<Badge style={[styles.badge, { backgroundColor: 'gray' }]}>
<Text>PENDING</Text>
</Badge>
)}
{!transaction.success && (
<Badge danger style={styles.badge}>
<Text>FAILED</Text>
</Badge>
)}
{transaction.dropped && (
<Badge danger style={styles.badge}>
<Text>DROPPED</Text>
</Badge>
)}
{transaction.replaced && (
<Badge info style={styles.badge}>
<Text>REPLACED</Text>
</Badge>
)}
{confirmBlocks != null && (
<Badge success style={styles.badge}>
<Text>{confirmBlocks} CONFIRMED</Text>
</Badge>
)}
</View>
{!!transaction.txid && (
<Text
style={[
styles.value,
{
textDecorationLine:
transaction.dropped || transaction.replaced
? 'line-through'
: 'none',
},
]}
>
{transaction.txid}
</Text>
)}
{!!transaction.replaceTxid && (
<Text style={[styles.value]}>{transaction.replaceTxid}</Text>
)}
{!!transaction.error && (
<Text style={[styles.value, { color: colorDanger }]}>
{transaction.error}
</Text>
)}
<Text style={styles.label}>Memo</Text>
<Text style={styles.value}>{transaction.memo || '-'}</Text>
<Text style={styles.label}>Time</Text>
<DisplayTime textStyle={styles.value} unix={transaction.timestamp} />
<Text style={styles.label}>Description</Text>
<Text style={styles.value}>{transaction.description || '-'}</Text>
</Content>
<View
style={{
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center',
width: '50%',
margin: 16,
}}
>
<Button
style={{ marginHorizontal: 4 }}
bordered
onPress={this._explorer}
>
<Text>Explorer</Text>
</Button>
{transaction.replaceable && (
<>
<Button
style={{ marginHorizontal: 4 }}
success
onPress={() => this._inputPinCode(ACTION_UPDATE_FEE)}
>
<Text>Speed up</Text>
</Button>
<Button
style={{ marginHorizontal: 4 }}
danger
onPress={() => this._inputPinCode(ACTION_CANCEL)}
>
<Text>Cancel</Text>
</Button>
</>
)}
</View>
<InputPinCodeModal
isVisible={!!inputPinCode}
onCancel={() => {
this._finishInputPinCode();
}}
loading={loading}
onInputPinCode={pinSecret => {
if (inputPinCode === ACTION_UPDATE_FEE) {
this._increaseTransactionFee(pinSecret);
} else {
// cancel
this._cancelTransaction(pinSecret);
}
}}
/>
</Container>
);
}
} |
JavaScript | class TContentCards01 extends React.Component {
constructor() {
super();
this.state = {
modalIsOpen: false,
id: '',
title: '',
singer: '',
thumbnail: '',
audio: ''
};
}
closeModal = () => {
this.setState({
modalIsOpen: false,
id: '',
title: '',
singer: '',
thumbnail: '',
audio: ''
});
}
render() {
let {
title,
tag,
tagBg,
centerIconName,
bgPhoto,
description,
bottomIconName,
bottomIconSize,
centerIconSize,
bottomIconColor,
centerIconColor,
onClick,
...other
} = this.props;
let cards;
let { styleDisplay } = this.props;
return (
<React.Fragment>
<Modal
visible={this.state.modalIsOpen}
width="1000" height="800"
effect="fadeInUp"
onClickAway={() => this.closeModal()}
>
<Row style={{ display: 'flex'}}>
<div style={{
backgroundImage: `url(${this.state.id})` ,
height: "800px",
width: "1000px",
backgroundSize: 'cover',
backgroundPosition: 'center center',
}}
>
{/* <Lyriccrawl> */}
<div style={{
position: 'absolute',
left: '85%',
marginLeft: '-110px',
marginTop: '370px'}}>
<ReactWebMediaPlayer
width={200} height={200}
title={this.state.title}
thumbnail={this.state.thumbnail}
audio={this.state.audio}
vinyl={{
img: this.state.thumbnail,
rpm: 15}}
style={{
backgroundColor: "transparent",
background: "transparent",
}}
/>
</div>
{/*</Lyriccrawl>*/}
</div>
</Row>
</Modal>
<Row style={{display: 'flex'}}>
<Col xs="2" lg="2" md="6">
<Tcontentcard2
className="plzwork"
onClick={ () => { this.setState({
modalIsOpen: true,
id: ChemTrails,
title: song[0].title,
singer: song[0].singer,
thumbnail: song[0].thumbnail,
audio: song[0].audio
}) } }
title='ChemTrails'
tag={[
<div>
<FaPlay focusable="false" aria-hidden="true" />
</div>
]}
centerIconName="fa fa-play"
centerIconColor="white"
tagBg="rgba(0,0,0,0.45)"
tagColor="white"
centerIconSize="4rem"
bgPhoto={ChemTrails} />
</Col>
<Col xs="2" lg="2" md="6">
<Tcontentcard2
className="plzwork"
onClick={ () => { this.setState({
modalIsOpen: true,
id: Feedthepeople,
title: song[1].title,
singer: song[1].singer,
thumbnail: song[1].thumbnail,
audio: song[1].audio
}) } }
title='Feed The People'
tag={[
<div>
<FaPlay focusable="false" aria-hidden="true" />
</div>
]}
centerIconName="fa fa-play"
centerIconColor="white"
tagBg="rgba(0,0,0,0.45)"
tagColor="white"
centerIconSize="4rem"
bgPhoto={Feedthepeople} />
</Col >
<Col xs="2" lg="2" md="6">
<Tcontentcard2
className="plzwork"
onClick={ () => { this.setState({
modalIsOpen: true,
id: Burn,
title: song[2].title,
singer: song[2].singer,
thumbnail: song[2].thumbnail,
audio: song[2].audio
}) } }
title='Burn'
tag={[
<div>
<FaPlay focusable="false" aria-hidden="true" />
</div>
]}
centerIconName="fa fa-play"
centerIconColor="white"
tagBg="rgba(0,0,0,0.45)"
tagColor="white"
centerIconSize="4rem"
bgPhoto={Burn} />
</Col>
<Col xs="2" lg="2" md="6">
<Tcontentcard2
className="plzwork"
onClick={ () => { this.setState({
modalIsOpen: true,
id: Another,
title: song[3].title,
singer: song[3].singer,
thumbnail: song[3].thumbnail,
audio: song[3].audio
}) } }
title='Another Thing'
tag={[
<div>
<FaPlay focusable="false" aria-hidden="true" />
</div>
]}
centerIconName="fa fa-play"
centerIconColor="white"
tagBg="rgba(0,0,0,0.45)"
tagColor="white"
centerIconSize="4rem"
bgPhoto={Another} />
</Col>
<Col xs="2" lg="2" md="6">
<Tcontentcard2
className="plzwork"
onClick={ () => { this.setState({
modalIsOpen: true,
id: Hate,
title: song[4].title,
singer: song[4].singer,
thumbnail: song[4].thumbnail,
audio: song[4].audio
}) } }
title='Hate'
tag={[
<div>
<FaPlay focusable="false" aria-hidden="true" />
</div>
]}
centerIconName="fa fa-play"
centerIconColor="white"
tagBg="rgba(0,0,0,0.45)"
tagColor="white"
centerIconSize="4rem"
bgPhoto={Hate} />
</Col>
</Row>
</React.Fragment>
);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.