language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class VeloxSqlSync{
/**
* @typedef VeloxSqlSyncOption
* @type {object}
* @property {function|Array|object} [tablesToTrack] the table to track configuration. If not given all tables are tracked.
* it can be :
* - a function that take the table name as argument and return true/false
* - an array of table to track
* - an object {include: []} where include is array of tables to track
* - an object {exclude: []} where exclude is array of tables we should not track
*/
/**
* Create the VeloxSqlSync extension
*
* @example
*
* @param {VeloxSqlSyncOption} [options] options
*/
constructor(){
this.name = "VeloxSqlSync";
this.dependencies = [
new VeloxSqlModifTracker(),
new VeloxSqlDeleteTracker()
] ;
var self = this ;
this.extendsProto = {
syncChangeSet : function(changeSet, callback){
//this is the VeloxDatabase object
self.applyChangeSet(this.backend, changeSet, callback) ;
}
} ;
this.extendsExpress = {
sync: function(changeSet, callback){
//this is the VeloxDatabaseExpress object, this.db is VeloxDatabase
self.applyChangeSet(this.db, changeSet, callback) ;
},
syncGetTime: function(date, callback){
//this is use to get the timelapse between client and server
var clientDate = new Date(date) ;
var serverDate = new Date() ;
callback(null, serverDate.getTime() - clientDate.getTime()) ;
}
} ;
}
/**
* Apply a changeset in database. The change set is done in a single transaction
*
* The change set format is :
* {
* date : date of the modification
* timeGap : the gap between time of client that create the modification and the server
* changes : [
* table : table name
* record: {record to sync}
* ]
* }
*
* @param {object} changeSet the changeset to sync in database
* @param {function(Error)} callback called on finished
*/
applyChangeSet(db, changeSet, callback){
db.transaction((tx, done)=>{
let job = new AsyncJob(AsyncJob.SERIES) ;
let changeDateTimestampMilli = new Date(changeSet.date).getTime() ;
let localTimeGap = changeSet.timeLapse ;
changeDateTimestampMilli += localTimeGap ;
for(let change of changeSet.changes){
let record = change.record ;
let table = change.table ;
job.push((cb)=>{
if(change.action === "remove"){
return tx.remove(table, record, cb) ;
}
tx.getByPk(table, record, (err, recordDb)=>{
if(err){ return cb(err); }
if(!recordDb){
//record does not exists yet, insert it
tx.insert(table, record, cb) ;
}else{
//record exist in database
if(recordDb.velox_version_record < record.velox_version_record){
//record in database is older, update
tx.update(table, record, cb) ;
}else{
//record in database is more recent, compare which column changed
let changedColumns = Object.keys(record).filter((col)=>{
return col.indexOf("velox_") !== 0 &&
record[col] != recordDb[col]; //don't do !== on purpose because 1 shoud equals "1"
}) ;
if(changedColumns.length === 0){
//no modifications to do, no need to go further
return cb() ;
}
tx.getPrimaryKey(table, (err, pkNames)=>{
if(err){ return cb(err); }
tx.search("velox_modif_track", {
table_name: table,
table_uid: pkNames[0],
version_record: {ope: ">", value: record.velox_version_record-1}
}, "version_record", (err, modifications)=>{
if(err){ return cb(err); }
let jobUpdateModif = new AsyncJob(AsyncJob.SERIES) ;
for(let modif of modifications){
let index = changedColumns.indexOf(modif.column_name);
if(index !== -1){
//conflicting column
let modifDateMilli = new Date(modif.version_date).getTime() ;
if(modifDateMilli <= changeDateTimestampMilli){
//the modif date is older that our new modification
//this can happen if 2 offline synchronize but the newest user synchronize after the oldest
}else{
//the modif date is newer, we won't change in the table but we must modify the modif track
// from oldval -> dbVal to oldval -> myVal -> dbVal
var oldestVal = modif.column_before;
var midWayVal = "" + record[modif.column_name] ;
jobUpdateModif.push((cbModif)=>{
//modifying existing modif by setting our change value as old value
modif.column_before = midWayVal ;
tx.update("velox_modif_track", modif, (err)=>{
if(err){ return cbModif(err); }
//create a new modif with our value to newer value
modif.version_date = new Date(changeDateTimestampMilli) ;
modif.column_before = oldestVal;
modif.column_after = midWayVal;
modif.version_user = record.velox_version_user ;
modif.version_table = recordDb.version_table ;
tx.insert("velox_modif_track", modif, cbModif) ;
}) ;
}) ;
//remove from changed column
changedColumns.splice(index, 1) ;
//remove column from record
delete record[modif.column_name] ;
}
}
}
jobUpdateModif.async((err)=>{
if(err){ return cb(err); }
if(changedColumns.length === 0){
//no modifications left to do
return cb() ;
} else {
// still some modification to do, apply them
tx.update(table, record, cb) ;
}
}) ;
}) ;
}) ;
}
}
}) ;
}) ;
}
job.async(done) ;
}, callback) ;
}
} |
JavaScript | class Stream {
constructor(symbolSize) {
this._symbolSize = symbolSize;
this._symbols = [];
this._totalSymbols = round(random(5, 35));
this._speed = random(5, 22);
}
/**
* Generates a bunch of Symbol instances
*/
generateSymbols(x, y) {
let opacity = 255;
let first = round(random(0, 4)) === 1;
for (let i =0; i <= this._totalSymbols; i++) {
const symbol = new Symbol(
x,
y,
this._speed,
first,
opacity
);
symbol.setToRandomSymbol();
this._symbols.push(symbol);
opacity -= (255 / this._totalSymbols) / fadeInterval;
y -= this._symbolSize;
first = false;
}
}
/**
* Renders all instanciated symbols
* Is called by the draw-function in script.js
*/
render() {
this._symbols.forEach( symbol => {
if (symbol.first) {
fill(140, 255, 170, symbol.opacity);
} else {
fill(0, 255, 70, symbol.opacity);
}
text(symbol.value, symbol.x, symbol.y);
symbol.rain();
symbol.setToRandomSymbol();
});
}
} |
JavaScript | class StateNode extends GraphNode {
constructor(name, description = '') {
super('state');
super.setAttr('name', name);
super.setAttr('description', description);
}
get name() {
return super.getAttr('name');
}
set name(value) {
super.setAttr('name', value);
}
get description() {
return super.getAttr('description', '');
}
set description(value) {
super.setAttr('description', value);
}
static restore(p) {
const r = new StateNode(p.attrs.name);
return r.restore(p);
}
/**
* this state consists of the following objects
* @returns {ObjectNode<any>[]}
*/
get consistsOf() {
return this.outgoing.filter(GraphEdge.isGraphType('consistsOf')).map((e) => e.target);
}
/**
* returns the actions leading to this state
* @returns {ActionNode[]}
*/
get resultsFrom() {
return this.incoming.filter(GraphEdge.isGraphType('resultsIn')).map((e) => e.source);
}
/**
*
* @returns {any}
*/
get creator() {
//results and not a inversed actions
const from = this.incoming.filter(GraphEdge.isGraphType('resultsIn')).map((e) => e.source).filter((s) => !s.isInverse);
if (from.length === 0) {
return null;
}
return from[0];
}
get next() {
return this.outgoing.filter(GraphEdge.isGraphType('next')).map((e) => e.target).filter((s) => !s.isInverse);
}
get previousState() {
const a = this.creator;
if (a) {
return StateNode.previous(a);
}
return null;
}
get previousStates() {
return this.resultsFrom.map((n) => StateNode.previous(n));
}
get nextStates() {
return this.next.map((n) => StateNode.resultsIn(n));
}
get nextState() {
const r = this.next[0];
return r ? StateNode.resultsIn(r) : null;
}
get path() {
const p = this.previousState, r = [];
r.unshift(this);
if (p) {
p.pathImpl(r);
}
return r;
}
pathImpl(r) {
const p = this.previousState;
r.unshift(this);
if (p && r.indexOf(p) < 0) { //no loop
//console.log(p.toString() + ' path '+ r.join(','));
p.pathImpl(r);
}
}
toString() {
return this.name;
}
static resultsIn(node) {
const r = node.outgoing.filter(GraphEdge.isGraphType('resultsIn'))[0];
return r ? r.target : null;
}
static previous(node) {
const r = node.incoming.filter(GraphEdge.isGraphType('next'))[0];
return r ? r.source : null;
}
} |
JavaScript | class TrackedMap extends Map {
/**
* @param {string} component
* @param {string} name
* @param {import('.')} metrics
*/
constructor (component, name, metrics) {
super()
this._component = component
this._name = name
this._metrics = metrics
this._metrics.updateComponentMetric(this._component, this._name, this.size)
}
/**
* @param {K} key
* @param {V} value
*/
set (key, value) {
super.set(key, value)
this._metrics.updateComponentMetric(this._component, this._name, this.size)
return this
}
/**
* @param {K} key
*/
delete (key) {
const deleted = super.delete(key)
this._metrics.updateComponentMetric(this._component, this._name, this.size)
return deleted
}
} |
JavaScript | class Vector {
constructor(x, y) {
this.x = x || 0;
this.y = y || 0;
}
// If you don't want to modify this object
clone() { return new Vector(this.x, this.y); }
toArray() { return [this.x, this.y]; }
toString() { return this.x + ', ' + this.y; }
_xPx() { return this.x + 'px'; }
_yPx() { return this.y + 'px'; }
add(vector) {
this.x += vector.x;
this.y += vector.y;
return this;
}
subtract(vector) {
this.x = this.x - vector.x;
this.y = this.y - vector.y;
return this;
}
multiply(vector) {
this.x *= vector.x;
this.y *= vector.y;
return this;
}
} |
JavaScript | class DataNode {
constructor(sum, users) {
this._sum = sum || 0;
this._users = users || {};
}
/**
* Add received raw event data object int to this data node.
*
* Degree of "value" associated with an object is 1 for all event data objects
* except for the Cheer event. For Cheer, it's bits / 100.
*
* This some what normalize value of data across all events for easier comparisons
* as Cheers is likely to overshadow other events in comparison charts.
*
* @param {Object} raw event data
* @returns {undefined}
*/
add(raw) {
const value = raw.bits ? raw.bits / 100 : 1;
this._sum += value;
this._users[raw.displayName] = (this._users[raw.displayName] || 0) + value;
}
/**
* get a copy of data node that returns a new object
*
* @returns {DataNode} new object with same data as this
*/
getCopy() {
return new DataNode(this._sum, { ...this._users });
}
/**
* merge targetDataNode's values into this
*
* @param {DataNode} targetDataNode to be added into this
* @param {boolean} isIgnoreFilter ignore filter or not
* @returns {DataNode} this
*/
merge(targetDataNode, isIgnoreFilter) {
if (targetDataNode) {
Object.keys(targetDataNode._users).forEach(key => {
if (isIgnoreFilter || users.getUserByName(key).isApplicable()) {
this._users[key] = (this._users[key] || 0) + targetDataNode._users[key];
this._sum += targetDataNode._users[key];
}
});
}
return this;
}
} |
JavaScript | class RESTerHotkeysCheatSheet extends RESTerHotkeysMixin(PolymerElement) {
static get template() {
return html`
<style>
.hotkeys {
display: table;
border-spacing: 8px;
border-collapse: separate;
}
.hotkey {
display: table-row;
}
.hotkey__combos {
display: table-cell;
}
.hotkey__combo {
box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.2),
0px 1px 1px 0px rgba(0, 0, 0, 0.14),
0px 2px 1px -1px rgba(0, 0, 0, 0.12);
background-color: #00bcd4;
padding: 4px 8px;
border-radius: 2px;
display: inline-block;
margin-right: 4px;
text-transform: capitalize;
}
.hotkey__combo:last-child {
margin-right: 0;
}
.hotkey__description {
display: table-cell;
}
</style>
<paper-dialog
id="dialog"
entry-animation="scale-up-animation"
exit-animation="fade-out-animation"
with-backdrop
restore-focus-on-close
>
<h2>Shortcuts</h2>
<paper-dialog-scrollable>
<div class="hotkeys">
<template
is="dom-repeat"
items="[[hotkeys]]"
as="hotkey"
>
<div class="hotkey">
<span class="hotkey__combos">
<template
is="dom-repeat"
items="[[hotkey.combosFormatted]]"
as="combo"
>
<span class="hotkey__combo"
>[[combo]]</span
>
</template>
</span>
<span class="hotkey__description"
>[[hotkey.description]]</span
>
</div>
</template>
</div>
</paper-dialog-scrollable>
<div class="buttons">
<paper-button dialog-dismiss autofocus>Close</paper-button>
</div>
</paper-dialog>
`;
}
static get is() {
return 'rester-hotkeys-cheat-sheet';
}
static get properties() {
return {
hotkeys: {
type: Array,
readOnly: true,
},
};
}
static get resterHotkeys() {
return {
'?': {
description: 'Shows this cheat sheet.',
callback: 'show',
},
};
}
show() {
this._setHotkeys([...getAll()]);
this.$.dialog.open();
}
} |
JavaScript | class EntitySearch {
setup() {
this.entityId = this.$opts.entityId;
this.entityType = this.$opts.entityType;
this.contentView = this.$refs.contentView;
this.searchView = this.$refs.searchView;
this.searchResults = this.$refs.searchResults;
this.searchInput = this.$refs.searchInput;
this.searchForm = this.$refs.searchForm;
this.clearButton = this.$refs.clearButton;
this.loadingBlock = this.$refs.loadingBlock;
this.setupListeners();
}
setupListeners() {
this.searchInput.addEventListener('change', this.runSearch.bind(this));
this.searchForm.addEventListener('submit', e => {
e.preventDefault();
this.runSearch();
});
onSelect(this.clearButton, this.clearSearch.bind(this));
}
runSearch() {
const term = this.searchInput.value.trim();
if (term.length === 0) {
return this.clearSearch();
}
this.searchView.classList.remove('hidden');
this.contentView.classList.add('hidden');
this.loadingBlock.classList.remove('hidden');
const url = window.baseUrl(`/search/${this.entityType}/${this.entityId}`);
window.$http.get(url, {term}).then(resp => {
this.searchResults.innerHTML = resp.data;
}).catch(console.error).then(() => {
this.loadingBlock.classList.add('hidden');
});
}
clearSearch() {
this.searchView.classList.add('hidden');
this.contentView.classList.remove('hidden');
this.loadingBlock.classList.add('hidden');
this.searchInput.value = '';
}
} |
JavaScript | class Shadow {
constructor(morningImages, treeObj) {
this.x = 0;
this.y = 0;
this.imgs = morningImages; // shadow present
this.frameCt = 0;
this.tree = treeObj;
}
checkWiggle() {
return this.tree.wiggle;
}
display() {
if (isMorning && isDay && !isWinter && mode==0) {
image(this.imgs[this.frameCt],this.x,this.y);
if (this.tree.wiggle && mode==0) {
this.frameCt++;
if (this.frameCt >= this.imgs.length) {
this.frameCt = 0;
}
}
}
}
} |
JavaScript | class Setting {
constructor() {
/**-------必须修改的配置---------------------**/
//是否采用后台检查模式,
//如果采用,大屏展示和归档处理目标是:upload/p目录,否则直接处理upload目录
this.bCheck = true;
//图片根目录
if(path.sep=='/')
this.pic_root = "/Users/c4w/git/pics";
else
this.pic_root = "d:\\bhere\\pics";
/**-------可以默认的配置---------------------**/
this.version='2016.12.13';
//必须是唯一的名称,将其hash值作为云端唯一标识
this.sn = '杭州工艺美术博物馆';
this.thumbnails_size=450; //抽点宽度
this.thumbnails_uri ='tbnails'; //抽点目录标志
this.uri_pics ='/pics'; //图片uri起始
this.pic_upload = 'upload'; //上传目录
this.pic_archive = 'archive'; //归档目录
this.pic_wallpaper = 'wallpaper'; //墙纸目录
this.cron_archive = '0 1 * * *'; //归档检查周期,每天凌晨1点,服务启动时会立即检查
this.stabilityThreshold=1000; //文件监测延时,ms
this.cacheSpan = 200;//缓存延时,避免cpu阻塞
//calc md5 of sn
//this.sn_md5 = '81949faebfe3c5ff42bcbd5c06a06511';
//this.sn_md5 = crypto.createHash('md5').update(this.sn).digest("hex");
//console.log('sn:'+this.sn+' md5:'+this.sn_md5);
}
} |
JavaScript | class TileMortonIndex {
// TODO for a hashmap-based index like this, there's an efficiency tradeoff
// between storing single locations and storing coarser granularities, say a
// 4x4 patch of locations in one hashmap entry, and then using an inner for
// loop over those chunks when querying. However this is likely to be more
// material to range queries, than single-point queries, so going with the
// finest granularity for now.
/**
* Maps spatial keys to sets of tile IDs; used for point queries.
*
* @type {Map<number, Set<string>>}
*/
_fore = new Map();
/**
* Maps tile IDs to last-indexed spatial key; used to remove (invalidate)
* prior _fore entry when updated.
*
* @type {Map<string, number>}
*/
_back = new Map();
/**
* Updates index mappings when tile locations change.
*
* @param {string[]} ids - batch of updated tile IDs
* @param {Point[]} pos - aligned list of positions for each updated id
*/
update(ids, pos) {
for (let i = 0; i < ids.length; ++i) {
const id = ids[i];
const key = mortonKey(pos[i]);
const prior = this._back.get(id);
if (prior !== undefined) this._fore.get(prior)?.delete(id);
const at = this._fore.get(key);
if (at) at.add(id);
else this._fore.set(key, new Set([id]));
this._back.set(id, key);
}
}
/**
* @param {Point} at - query location
* @return {Iterable<string>} - set of tile IDs present at at
*/
*tilesAt(at) {
const got = this._fore.get(mortonKey(at));
if (got) yield* got;
}
} |
JavaScript | class EventBus {
constructor() {
this._cache = {}
}
on(type, callback) {
let fns = (this._cache[type] = this._cache[type] || [])
if (fns.indexOf(callback) === -1) {
fns.push(callback)
}
return this
}
trigger(type, data) {
let fns = this._cache[type]
if (Array.isArray(fns)) {
fns.forEach((fn) => {
fn(data)
})
}
return this
}
off(type, callback) {
let fns = this._cache[type]
if (Array.isArray(fns)) {
if (callback) {
let index = fns.indexOf(callback)
if (index !== -1) {
fns.splice(index, 1)
}
} else {
fns.length = 0
}
}
return this
}
} |
JavaScript | class TableChart extends React.Component {
// constructor(props) {
// super(props);
// }
getData(chartData) {
// console.log("chartdata: "+JSON.stringify(chartData))
var tempData = {
row: [],
columnHeader: [],
rowValue: []
};
chartData
.filter(Boolean)
.map(rowName => tempData.row.push(rowName.headerName));
// console.log("New row: "+tempData.row);
chartData
.filter(Boolean)
.map(columnHeading =>
tempData.columnHeader.push(columnHeading.plots.map(label => label.name))
);
// console.log("New columnHeader: "+tempData.columnHeader);
chartData
.filter(Boolean)
.map(value =>
tempData.rowValue.push(value.plots.map(label => label.value))
);
// console.log("New rowValue: "+tempData.rowValue);
return tempData;
}
render() {
let { chartData } = this.props;
let _data = this.getData(chartData);
// console.log("Table data: "+JSON.stringify(_data));
// let intPie;
// intPie = setInterval(() => (this.getData(chartData)), 10000);
// localStorage.setItem("intPie", intPie);
// console.log("PieChart chartData", chartData);
// console.log("PieChart _data", _data);
// console.log("Data: "+JSON.stringify(this.data));
// let row = [];
// this.data.responseData.data.map((rowName) => row.push(rowName.headerName));
// console.log("rowName: "+row);
// let columnHeader = [];
// this.data.responseData.data.map((columnHeading) => columnHeader.push(columnHeading.plots.map(label => label.name)));
// console.log("columnHeading: "+columnHeader[0]);
// columnHeader.map((field) => columns.dataField = field.toLowerCase);
// columns[0].dataField = columnHeader[0].map((field) => field.toLowerCase());
// columns[0].text = columnHeader[0].map((field) => field);
// let rowValue = [];
// this.data.responseData.data.map((value) => rowValue.push(value.plots.map(label => label.value)));
// console.log("rowValue: "+rowValue);
// console.log("Data: "+JSON.stringify(_data));
if (_data) {
return (
<div className="table-responsive" id="tableChart">
{_data.columnHeader.length && (
<table className="table table-hover metricTextColor">
<thead>
<tr>
{_data.columnHeader[0].map((value, index) => (
<th key={index} scope="col">
{value}
</th>
))}
</tr>
</thead>
<tbody>
{_data.row.map((value, index) => (
<tr key={index}>
<th scope="row">{index + 1}</th>
<td>{value}</td>
{_data.rowValue[index]
.filter(i => i !== null)
.map((text, id) => (
<td key={id}>{Math.round(text)}</td>
))}
</tr>
))}
</tbody>
</table>
)}
{/*<nav aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item"><a class="page-link" href="#">Previous</a></li>
<li class="page-item"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
<li class="page-item"><a class="page-link" href="#">Next</a></li>
</ul>
</nav>*/}
</div>
);
}
return <div>Loading...</div>;
}
} |
JavaScript | class Gate extends Agent {
constructor() {
super({ inputs: ['value'], outputs: ['value'] });
this._control = new Control();
}
/**
*
* Shortcut for `.in('value')`, the input pin receiving values.
* [Read this](https://connective.dev/docs/gate#signature) for more details.
*
*/
get input() { return this.in('value'); }
/**
*
* Shortcut for `.out('value')`, the output emitting allowed values.
* [Read this](https://connective.dev/docs/gate#signature) for more details.
*
*/
get output() { return this.out('value'); }
/**
*
* Each pin connected to this pin should emit a boolean value for each
* value sent to `.input`, and if all are true, the value is emitted via `.output`.
* [Read this](https://connective.dev/docs/gate) for more details.
*
*/
get control() { return this._control; }
createOutput(label) {
this.checkOutput(label);
return group(this.control, this.input)
.to(new Control())
.to(filter(([ctrl, _]) => ctrl.every(signal => !!signal)))
.to(map(([_, input]) => input));
}
createEntries() { return [this.input]; }
createExits() { return [this.output]; }
clear() {
this.control.clear();
return super.clear();
}
} |
JavaScript | class SubtitleControl extends ControlContainer {
constructor (player, options={}) {
options = $.extend({}, {
iconName : 'commenting-o',
title : 'Субтитры',
name : 'subtitle',
className : 'subtitle-control',
disable : true
}, options);
super(player, options);
this.player.on('playing', this.update.bind(this));
this.player.on('trackschange', this.update.bind(this));
}
onClick (e) {
super.onClick(e);
const video = this.player.video;
video.track = null
}
onItemClick (e) {
e.preventDefault();
e.stopPropagation()
const item = $(e.target)
const video = this.player.video;
if (item.data()) {
video.track = item.data();
}
this.dropdownContent.hide()
}
onPlayerInited(e, data) {
this.update()
}
update() {
super.update();
const hasValue = !!(this.getCurrentValue() && this.getCurrentValue().name != null);
this.element.toggleClass(
'control-checkbox--checked',
hasValue
)
}
getData() {
return this.player.video.subtitles;
}
getCurrentValue() {
return this.player.video.track;
}
} |
JavaScript | class ToastedNotes extends React.Component{
render = () => {
return <ToastedNotesContainer ref={el => elementRef = el} />
};
} |
JavaScript | class ClippedDrawer extends Component {
render() {
const { classes } = this.props;
const { isDrawerOpen } = this.props.drawer;
return (
<Drawer
variant="persistent"
open={true}
classes={{
paper: classNames(
classes.drawerPaper,
isDrawerOpen ? null : classes.hide,
),
}}
>
<div className={classes.toolbar} />
<List>
<div>
<Tooltip id="tooltip-top" title="Home" placement="top">
<ListItem
button
component={Link}
to="/main"
>
<ListItemIcon>
<HomeIcon />
</ListItemIcon>
</ListItem>
</Tooltip>
<Tooltip id="tooltip-top" title="Calendar" placement="top">
<ListItem
button
component={Link}
to="/main/calendar"
>
<ListItemIcon>
<CalendarIcon />
</ListItemIcon>
</ListItem>
</Tooltip>
<Tooltip id="tooltip-top" title="Chart" placement="top">
<ListItem
button
component={Link}
to="/main/requirement"
>
<ListItemIcon>
<ChartIcon />
</ListItemIcon>
</ListItem>
</Tooltip>
<Tooltip id="tooltip-top" title="Chat" placement="top">
<ListItem
button
component={Link}
to="/main/chat"
>
<ListItemIcon>
<ChatIcon />
</ListItemIcon>
</ListItem>
</Tooltip>
<Tooltip id="tooltip-top" title="Review" placement="top">
<ListItem
button
component={Link}
to="/main/review"
>
<ListItemIcon>
<ReviewIcon />
</ListItemIcon>
</ListItem>
</Tooltip>
<Tooltip id="tooltip-top" title="Search" placement="top">
<ListItem
button
component={Link}
to="/main/search"
>
<ListItemIcon>
<SearchIcon />
</ListItemIcon>
</ListItem>
</Tooltip>
</div>
</List>
<Divider />
<List>
<div>
<Tooltip id="tooltip-top" title="Settings" placement="top">
<ListItem
button
color="primary"
component={Link}
to="/main/settings"
>
<ListItemIcon
className={classNames(classes.iconRotate)}
>
<SettingsIcon />
</ListItemIcon>
</ListItem>
</Tooltip>
<Tooltip id="tooltip-top" title="Report" placement="top">
<ListItem
button
component={Link}
to="/main/report"
>
<ListItemIcon
className={classNames(classes.iconHoverRed)}
>
<ReportIcon />
</ListItemIcon>
</ListItem>
</Tooltip>
</div>
</List>
</Drawer >
);
}
} |
JavaScript | class cajas extends ModeloBase {
constructor() {
let servicio = "Servicios/PVenta/WcfCajas.svc/";
let campos = "_id,Nombre,Almacen.Nombre,CobroPredet";
super(servicio, campos);
}
searchXCajasAbiertas(text) {
return this.url + "?searchBy=getXCajasAbiertas&Nombrebusqueda="+text;
}
searchXCajasCerradas(text) {
return this.url + "?searchBy=getXCajasCerradas&tipoMovimiento=ABIERTA&Nombrebusqueda="+text;
}
} |
JavaScript | class PhotoSection extends React.Component {
// This component is the child of another and we can pass properties down the chain from a parent
// to its child components (children)
// in this case we are defining data as being a mandatory property which this component can't run without
static propTypes = {
data: React.PropTypes.object,
}
// The following function is responsible for rendering to the browser
render () {
// Display a little loading message whilst we load data in
if (this.props.data.loading) {
return (<div>Loading</div>)
}
// Now for the JSX template that defines how our component actually looks!
return (
<div className="tl bt b--black-10 pa3 pa5-ns bg-black white">
<div className="mw9 center">
<h1 className="f5 ttu tracked fw6 pa3">{this.props.title}</h1>
<section className="lh-copy">
<div className="cf pa2">
{ /* The following piece of code loops through the photo data (see below) */ }
{this.props.data.allPhotos.map((photo) =>
<Photo key={photo.id} photo={photo} />
)}
</div>
</section>
</div>
</div>
)
}
} |
JavaScript | class BaseHandler extends Handler {
/**
* Service Base Name.
*
* @returns {string} - The service Base Name.
* @abstract
*/
get name() {
return 'BrewHandler';
}
/**
* @inheritdoc
*/
static get dependencies() {
return ['app'];
}
/**
* @inheritdoc
*/
async start(...parameters) {
await this.spawn('brew', `services start ${this.getServiceCommand(...parameters)}`, true);
return {
message: `${this.getServiceCommand(...parameters)} is started.`
};
}
/**
* @inheritdoc
*/
async restart(...parameters) {
await this.spawn('brew', `services restart ${this.getServiceCommand(...parameters)}`, true);
return {
message: `${this.getServiceCommand(...parameters)} is restarted.`
};
}
/**
* @inheritdoc
*/
async stop(...parameters) {
await this.spawn('brew', `services stop ${this.getServiceCommand(...parameters)}`, true);
return {
message: `${this.getServiceCommand(...parameters)} is stopped.`
};
}
/**
* @inheritdoc
*/
async status(...parameters) {
const serviceName = this.getServiceCommand(...parameters);
const serviceOptions = serviceName !== 'brew' ? `| sed -e '1p' -e '/${serviceName}/!d'` : '';
await this.spawn('bash', ['-c', `brew services list ${serviceOptions}`.trim()], true);
}
/**
* @inheritdoc
*/
get privileged() {
return false;
}
/**
* @inheritdoc
*/
getServiceCommand(...parameters) {
return (this.serviceName || '') + parameters.join(' ');
}
} |
JavaScript | class Window {
/**
* @param size number
* @return number[]
*/
static rectangle(size) {
const xs = new Array(size);
for (let i = 0; i < size; i++) {
xs[i] = 1.0;
}
return xs;
}
/**
* @param size number
* @return number[]
*/
static bartlett(size) {
const xs = new Array(size);
for (let i = 0; i < size; i++) {
xs[i] = 2 / (size - 1) * ((size - 1) / 2 - Math.abs(i - (size - 1) / 2));
}
return xs;
}
/**
* @param size number
* @return number[]
*/
static blackman(size) {
const alpha = 0.16; // the "exact" Blackman
const a0 = (1 - alpha) / 2;
const a1 = 0.5;
const a2 = alpha * 0.5;
const xs = new Array(size);
for (let i = 0; i < size; i++) {
xs[i] = a0 - a1 * Math.cos(2.0 * Math.PI * i / (size - 1))
+ a2 * Math.cos(4 * Math.PI * i / (size - 1));
}
return xs;
}
/**
* @param size number
* @return number[]
*/
static cosine(size) {
const xs = new Array(size);
for (let i = 0; i < size; i++) {
xs[i] = Math.cos(Math.PI * i / (size - 1) - Math.PI / 2);
}
return xs;
}
/**
* @param size number
* @return number[]
*/
static gauss(size) {
const xs = new Array(size);
const alpha = 1.0;
for (let i = 0; i < size; i++) {
xs[i] = Math.exp(-0.5 * (((i - (size - 1) / 2) / (alpha * (size - 1) / 2)) ** 2));
}
return xs;
}
/**
* @param size number
* @return number[]
*/
static hamming(size) {
const xs = new Array(size);
for (let i = 0; i < size; i++) {
xs[i] = 0.54 - 0.46 * Math.cos(2.0 * Math.PI * i / (size - 1));
}
return xs;
}
/**
* @param size number
* @return number[]
*/
static hann(size) {
const xs = new Array(size);
for (let i = 0; i < size; i++) {
xs[i] = 0.5 - 0.5 * Math.cos(2.0 * Math.PI * i / (size - 1));
}
return xs;
}
} |
JavaScript | class NumberHelper {
/**
* Is the value an integer.
* @param value Object to test for its integerness.
* @returns True if the object is a integer.
*/
static isInteger(value) {
return typeof value === "number" && !Number.isNaN(value) && Number.isFinite(value) && Math.floor(value) === value;
}
/**
* Is the value a number.
* @param value Object to test for its numberyness.
* @returns True if the object is a number.
*/
static isNumber(value) {
return value !== undefined && value !== null && typeof value === "number" && !Number.isNaN(value) && Number.isFinite(value);
}
} |
JavaScript | class ScrollView extends Panel {
/**
* @constructor
* @param {MANTICORE.enumerator.ui.PANEL_GRAPHIC_TYPE} [graphicType = MANTICORE.enumerator.ui.PANEL_GRAPHIC_TYPE.NONE] - Type of graphic that use panel.
* @param {?string | ?int} [data = null] - Data that need to init panel. If type Color this is color, if Sprite it link to texture.
*/
constructor(graphicType = PANEL_GRAPHIC_TYPE.NONE, data = null) {
super(graphicType, data);
/**
* @desc Container with elements.
* @type {MANTICORE.ui.Widget}
* @private
*/
this._innerContainer = Widget.create();
/**
* @type {?MANTICORE.ui.Slider}
* @private
*/
this._verticalSlider = null;
/**
* @type {?MANTICORE.ui.Slider}
* @private
*/
this._horizontalSlider = null;
/**
* @desc Custom event for drag start.
* @type {?string}
* @private
*/
this._eventDragStart = null;
/**
* @desc Custom event for drag.
* @type {?string}
* @private
*/
this._eventDrag = null;
/**
* @desc Custom event for drag finish.
* @type {?string}
* @private
*/
this._eventDragFinish = null;
/**
* @desc Inner event for drag start.
* @type {string}
* @private
*/
this._innerEventDragStart = Format.generateEventName(this, LOCAL_EVENT.DRAG_START);
/**
* @desc Inner event for drag.
* @type {string}
* @private
*/
this._innerEventDrag = Format.generateEventName(this, LOCAL_EVENT.DRAG);
/**
* @desc Inner event for drag finish.
* @type {string}
* @private
*/
this._innerEventDragFinish = Format.generateEventName(this, LOCAL_EVENT.DRAG_FINISH);
/**
* @desc Component for update scroll in scroll view.
* @type {MANTICORE.component.ui.ComScroller}
* @private
*/
this._scroller = ComScroller.create();
this.componentManager.addComponent(this._scroller);
this._initInnerListeners();
this.uiType = UI_ELEMENT.SCROLL_VIEW;
super.addChild(this._innerContainer);
this._innerContainer.interactive = true;
}
/**
* PUBLIC METHODS
* -----------------------------------------------------------------------------------------------------------------
*/
/**
* @desc Calls by pool when object get from pool. Don't call it only override.
* @method
* @public
* @param {MANTICORE.enumerator.ui.PANEL_GRAPHIC_TYPE} [graphicType = MANTICORE.enumerator.ui.PANEL_GRAPHIC_TYPE.NONE] - Type of graphic that use panel.
* @param {?string | ?int} [data = null] - Data that need to init panel. If type Color this is color, if Sprite it link to texture.
*/
reuse(graphicType, data) {
super.reuse(graphicType, data);
this._innerContainer = Widget.create();
this._verticalSlider = null;
this._horizontalSlider = null;
this._eventDragStart = null;
this._eventDrag = null;
this._scrollDirection = SCROLL_DIRECTION.BOTH;
this._scroller = ComScroller.create();
this.componentManager.addComponent(this._scroller);
this._initInnerListeners();
}
/**
* @method
* @public
* @override
* @param {...PIXI.DisplayObject} var_args
* @returns {PIXI.DisplayObject | PIXI.DisplayObject[]}
*/
addChild(var_args) {
const argumentCount = arguments.length;
const result = [];
for (let i = 0; i < argumentCount; ++i) {
result.push(this._innerContainer.addChild(arguments[i]));
}
return result.length === 1 ? result[0] : result;
}
/**
* @method
* @public
* @override
* @param {PIXI.DisplayObject} child
* @param {int} index
* @returns {PIXI.DisplayObject}
*/
addChildAt(child, index) {
return this._innerContainer.addChildAt(child, index);
}
/**
* @method
* @public
* @override
* @param {...PIXI.DisplayObject} var_args
* @returns {?PIXI.DisplayObject | ?PIXI.DisplayObject[]}
*/
removeChild(var_args) {
const argumentCount = arguments.length;
const result = [];
for (let i = 0; i < argumentCount; ++i) {
result.push(this._innerContainer.removeChild(arguments[i]));
}
return result.length === 1 ? result[0] : result;
}
/**
* @method
* @public
* @override
* @param {int} index
* @returns {?PIXI.DisplayObject}
*/
removeChildAt(index) {
return this._innerContainer.removeChildAt(index);
}
/**
* @method
* @public
* @override
* @param {int} [beginIndex = 0]
* @param {int} [endIndex]
* @returns {PIXI.DisplayObject[]}
*/
removeChildren(beginIndex = 0, endIndex = this._innerContainer.children.length) {
return this._innerContainer.removeChildren(beginIndex, endIndex);
}
/**
* @method
* @public
* @override
* @param {PIXI.DisplayObject} child
* @param {int} index
*/
setChildIndex(child, index) {
this._innerContainer.setChildIndex(child, index);
}
/**
* @method
* @public
* @override
* @param {int} index
* @returns {?PIXI.DisplayObject}
*/
getChildAt(index) {
this._innerContainer.getChildAt(index);
}
/**
* @method
* @public
* @override
* @param {string} name - Instance name.
* @returns {?PIXI.DisplayObject}
*/
getChildByName(name) {
this._innerContainer.getChildByName(name);
}
/**
* @method
* @public
* @override
* @param {PIXI.DisplayObject} child
* @returns {int}
*/
getChildIndex(child) {
return this._innerContainer.getChildIndex(child);
}
/**
* @method
* @public
* @override
* @param {PIXI.DisplayObject} child1
* @param {PIXI.DisplayObject} child2
*/
swapChildren(child1, child2) {
this._innerContainer.swapChildren(child1, child2);
}
/**
* @desc Move inner container to bottom boundary of ScrollView.
* @method
* @public
*/
jumpToBottom() {
this._scroller.jumpToBottom();
}
/**
* @desc Move inner container to bottom and left boundary of ScrollView.
* @method
* @public
*/
jumpToBottomLeft() {
this._scroller.jumpToBottomLeft();
}
/**
* @desc Move inner container to bottom and right boundary of ScrollView.
* @method
* @public
*/
jumpToBottomRight() {
this._scroller.jumpToBottomRight();
}
/**
* @desc Move inner container to left boundary of ScrollView.
* @method
* @public
*/
jumpToLeft() {
this._scroller.jumpToLeft();
}
/**
* @desc Move inner container to right boundary of ScrollView.
* @method
* @public
*/
jumpToRight() {
this._scroller.jumpToRight();
}
/**
* @desc Move inner container to top boundary of ScrollView.
* @method
* @public
*/
jumpToTop() {
this._scroller.jumpToTop();
}
/**
* @desc Move inner container to top and left boundary of ScrollView.
* @method
* @public
*/
jumpToTopLeft() {
this._scroller.jumpToTopLeft();
}
/**
* @desc Move inner container to top and right boundary of ScrollView.
* @method
* @public
*/
jumpToTopRight() {
this._scroller.jumpToTopRight();
}
/**
* @desc Move inner container to both direction percent position of ScrollView.
* @method
* @public
* @param {number} percent
*/
jumpToPercentBothDirection(percent) {
this._scroller.jumpToPercentBothDirection(percent);
}
/**
* @desc Move inner container to horizontal percent position of ScrollView.
* @method
* @public
* @param {number} percent
*/
jumpToPercentHorizontal(percent) {
this._scroller.jumpToPercentHorizontal(percent);
}
/**
* @desc Move inner container to vertical percent position of ScrollView.
* @method
* @public
* @param {number} percent
*/
jumpToPercentVertical(percent) {
this._scroller.jumpToPercentVertical(percent);
}
/**
* @desc Scroll inner container to top.
* @method
* @public
* @param {number} time
*/
scrollToLeft(time) {
this._scroller.scrollToLeft(time);
}
/**
* @desc Scroll inner container to top.
* @method
* @public
* @param {number} time
*/
scrollToRight(time) {
this._scroller.scrollToRight(time);
}
/**
* @desc Scroll inner container to top.
* @method
* @public
* @param {number} time
*/
scrollToTop(time) {
this._scroller.scrollToTop(time);
}
/**
* @desc Scroll inner container to bottom.
* @method
* @public
* @param {number} time
*/
scrollToBottom(time) {
this._scroller.scrollToBottom(time);
}
/**
* @desc Scroll inner container to top left.
* @method
* @public
* @param {number} time
*/
scrollToTopLeft(time) {
this._scroller.scrollToTopLeft(time);
}
/**
* @desc Scroll inner container to top left.
* @method
* @public
* @param {number} time
*/
scrollToTopRight(time) {
this._scroller.scrollToTopRight(time);
}
/**
* @desc Scroll inner container to bottom left.
* @method
* @public
* @param {number} time
*/
scrollToBottomLeft(time) {
this._scroller.scrollToBottomLeft(time);
}
/**
* @desc Scroll inner container to bottom right.
* @method
* @public
* @param {number} time
*/
scrollToBottomRight(time) {
this._scroller.scrollToBottomRight(time);
}
/**
* @desc Scroll to percent inner container in horizontal direction.
* @method
* @public
* @param {number} time
* @param {number} percent
*/
scrollToPercentHorizontal(time, percent) {
this._scroller.scrollToPercentHorizontal(time, percent);
}
/**
* @desc Scroll to percent inner container in vertical direction.
* @method
* @public
* @param {number} time
* @param {number} percent
*/
scrollToPercentVertical(time, percent) {
this._scroller.scrollToPercentVertical(time, percent);
}
/**
* @desc Scroll to percent inner container in vertical direction.
* @method
* @public
* @param {number} time
* @param {number} percentH
* @param {number} [percentV]
*/
scrollToPercentBoth(time, percentH, percentV) {
this._scroller.scrollToPercentBoth(...arguments);
}
/**
* PROTECTED METHODS
* -----------------------------------------------------------------------------------------------------------------
*/
/**
* @desc Clear data before disuse and destroy.
* @method
* @protected
*/
clearData() {
this._innerContainer = null;
this._verticalSlider = null;
this._horizontalSlider = null;
this._eventDragStart = null;
this._eventDrag = null;
this._eventDragFinish = null;
this._scrollDirection = SCROLL_DIRECTION.BOTH;
this._scroller = null;
super.clearData();
}
/**
* @method
* @protected
* @returns {boolean}
*/
isVertical() {
return this._scroller.isVertical();
}
/**
* @method
* @protected
* @returns {boolean}
*/
isHorizontal() {
return this._scroller.isHorizontal();
}
/**
* @method
* @protected
* @param {MANTICORE.eventDispatcher.EventModel} event
*/
onDragStartInnerContainerHandler(event) {
this.listenerManager.dispatchEvent(this._eventDragStart, event.data);
this._scroller.updateDragStart(event.data.data.global);
}
/**
* @method
* @protected
* @param {MANTICORE.eventDispatcher.EventModel} event
*/
onDragInnerContainerHandler(event) {
this.listenerManager.dispatchEvent(this._eventDrag, event.data);
this._scroller.updateDragMove(event.data.data.global);
}
/**
* @method
* @protected
* @param {MANTICORE.eventDispatcher.EventModel} event
*/
onDragFinishInnerContainerHandler(event) {
this.listenerManager.dispatchEvent(this._eventDragFinish, event.data);
this._scroller.updateDragFinish(event.data.data.global);
}
/**
* @method
* @protected
* @param {MANTICORE.eventDispatcher.EventModel} event
*/
onScrollHorizontalHandler(event) {
this._scroller.updateScrollDimension(event.data, SCROLL_DIRECTION.HORIZONTAL);
}
/**
* @method
* @protected
* @param {MANTICORE.eventDispatcher.EventModel} event
*/
onScrollVerticalHandler(event) {
this._scroller.updateScrollDimension(event.data, SCROLL_DIRECTION.VERTICAL);
}
/**
* PRIVATE METHODS
* -----------------------------------------------------------------------------------------------------------------
*/
/**
* @desc Update slider.
* @method
* @private
* @param {?MANTICORE.ui.Slider} prvSlider
* @param {?MANTICORE.ui.Slider} nxtSlider
* @param {MANTICORE.enumerator.ui.SCROLL_DIRECTION} direction
* @param {Function} handler
* @returns {?MANTICORE.ui.Slider}
*/
_initSlider(prvSlider, nxtSlider, direction, handler) {
let event;
const eventName = direction === SCROLL_DIRECTION.HORIZONTAL ? LOCAL_EVENT.HORIZONTAL_SCROLL : LOCAL_EVENT.VERTICAL_SCROLL;
if (Type.isNull(nxtSlider)) {
event = prvSlider.eventScroll;
this.listenerManager.removeEventListener(event);
prvSlider.eventScroll = null;
return nxtSlider;
}
event = Format.generateEventName(this, eventName);
nxtSlider.eventScroll = event;
this.listenerManager.addEventListener(event, handler);
this._scroller.updateScrollDimension(nxtSlider.progress, direction);
return nxtSlider;
}
/**
* @desc Init inner listeners for drag.
* @method
* @private
*/
_initInnerListeners() {
this.listenerManager.addEventListener(this._innerEventDrag, this.onDragInnerContainerHandler);
this.listenerManager.addEventListener(this._innerEventDragStart, this.onDragStartInnerContainerHandler);
this.listenerManager.addEventListener(this._innerEventDragFinish, this.onDragFinishInnerContainerHandler);
this._innerContainer.interactionManager.eventDrag = this._innerEventDrag;
this._innerContainer.interactionManager.eventDragStart = this._innerEventDragStart;
this._innerContainer.interactionManager.eventDragFinish = this._innerEventDragFinish;
this._innerContainer.interactionManager.propagateChildrenEvents = true;
this._innerContainer.interactive = true;
}
/**
* PROPERTIES
* -----------------------------------------------------------------------------------------------------------------
*/
/**
* @public
* @type {int}
*/
get width() {
return super.width;
}
set width(value) {
super.width = value;
this._scroller.innerBoundary.x = this.width - this._innerContainer.width;
}
/**
* @public
* @type {int}
*/
get height() {
return super.height;
}
set height(value) {
super.height = value;
this._scroller.innerBoundary.y = this.height - this._innerContainer.height;
}
/**
* @public
* @type {boolean}
*/
get interactive() {
return this._innerContainer.interactive;
}
set interactive(value) {
if (this._innerContainer.interactive === value) {
return;
}
this._innerContainer.interactive = value;
}
/**
* @public
* @type {MANTICORE.enumerator.ui.SCROLL_DIRECTION}
*/
get scrollDirection() {
return this._scroller.scrollDirection;
}
set scrollDirection(value) {
this._scroller.scrollDirection = value;
}
/**
* @public
* @type {?MANTICORE.ui.Slider}
*/
get horizontalSlider() {
return this._horizontalSlider;
}
set horizontalSlider(value) {
if (this._horizontalSlider === value || this.isVertical()) {
return;
}
this._horizontalSlider = this._initSlider(this._horizontalSlider, value, SCROLL_DIRECTION.HORIZONTAL, this.onScrollHorizontalHandler);
}
/**
* @public
* @type {?MANTICORE.ui.Slider}
*/
get verticalSlider() {
return this._verticalSlider;
}
set verticalSlider(value) {
if (this._verticalSlider === value || this.isHorizontal()) {
return;
}
this._verticalSlider = this._initSlider(this._verticalSlider, value, SCROLL_DIRECTION.VERTICAL, this.onScrollVerticalHandler);
}
/**
* @public
* @type {MANTICORE.ui.Widget}
*/
get innerContainer() {
return this._innerContainer;
}
/**
* @public
* @type {int}
*/
get innerWidth() {
return this._innerContainer.width;
}
set innerWidth(value) {
this._innerContainer.width = value;
this._scroller.innerBoundary.x = this.width - this._innerContainer.width;
}
/**
* @public
* @type {int}
*/
get innerHeight() {
return this._innerContainer.height;
}
set innerHeight(value) {
this._innerContainer.height = value;
this._scroller.innerBoundary.y = this.height - this._innerContainer.height;
}
/**
* @public
* @return {MANTICORE.manager.InteractionManager}
*/
get interactionManager() {
return this._innerContainer.interactionManager;
}
/**
* @desc Flag is bounce enabled for scroll view.
* @public
* @return {boolean}
*/
get bounceEnabled() {
return this._scroller.bounceEnabled;
}
set bounceEnabled(value) {
this._scroller.bounceEnabled = value;
}
} |
JavaScript | class StorageQueueMessage {
/**
* Create a StorageQueueMessage.
* @member {string} [storageAccount] Gets or sets the storage account name.
* @member {string} [queueName] Gets or sets the queue name.
* @member {string} [sasToken] Gets or sets the SAS key.
* @member {string} [message] Gets or sets the message.
*/
constructor() {
}
/**
* Defines the metadata of StorageQueueMessage
*
* @returns {object} metadata of StorageQueueMessage
*
*/
mapper() {
return {
required: false,
serializedName: 'StorageQueueMessage',
type: {
name: 'Composite',
className: 'StorageQueueMessage',
modelProperties: {
storageAccount: {
required: false,
serializedName: 'storageAccount',
type: {
name: 'String'
}
},
queueName: {
required: false,
serializedName: 'queueName',
type: {
name: 'String'
}
},
sasToken: {
required: false,
serializedName: 'sasToken',
type: {
name: 'String'
}
},
message: {
required: false,
serializedName: 'message',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class SheetsAPI extends GoogleAuthorize {
/**
* Creating an instance of SheetsAPI prepares to obtain an authorized
* OAuth2 clent from GoogleAuthorize by setting the 'scope' (access) of
* this class to 'spreadsheets'
* (See https://developers.google.com/identity/protocols/googlescopes). To
* obtain the authorized OAuth2 client, call 'authorize'.
*
* @param {String} credentialsPath The absolute path to the
* Google credentials.json file. Defaults to 'credentials.json' in
* GoogleAuthorize
*
*/
constructor(credentialsPath) {
super(['spreadsheets'], credentialsPath);
this.sheets = googleapis.sheets('v4');
}
/**
* Returns a Promise returned from GoogleAuthorize.authorize that
* resolves the OAuth2 client that is used to make authorized requests
* to the Sheets API.
*
* @return {Promise} The promise that resolves the OAuth2 client (auth)
*/
authorize() {
return super.authorize();
}
/**
* A generic wrapper to distinguish what collection from the Sheets API
* we want.
*
* @param {object} collection The collection from the sheets API we want.
* @param {string} method The name of the method from the corresponding
* collection.
* @param {google.auth.OAuth2} auth The OAuth2 authorized client
* @param {object} payload The object to pass to the request to the API
* @return {Promise} The chainable Promise that resolves the response
* from the request to the API and the
* {google.auth.OAuth2} for additional work.
*/
_collection(collection, method, auth, payload) {
if (!payload.auth) payload.auth = auth;
return new Promise((resolve, reject) => {
collection[method](payload, (err, response) => {
if (err) reject(err);
resolve({
auth: auth,
response: response,
});
});
});
}
/**
* Collection: spreadsheets
* https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets
* This function corresponds the spreadsheets collection of the Sheets API.
* See _collection for param definitions.
*
* @param {String} method
* @param {google.auth.OAuth2} auth
* @param {Object} payload
* @return {Promise}
* @memberof SheetsAPI
*/
spreadsheets(method, auth, payload) {
return this._collection(this.sheets.spreadsheets, method, auth, payload);
}
/**
*/
/**
* Collection: spreadsheets.sheets
* //developers.google.com/sheets/api/reference/rest/v4/spreadsheets.sheets
* This function corresponds the sheets collection of the Sheets API.
* See _collection for param definitions.
*
* @param {String} method
* @param {google.auth.OAuth2} auth
* @param {Object} payload
* @return {Promise}
* @memberof SheetsAPI
*/
sheets(method, auth, payload) {
return this._collection(
this.sheets.spreadsheets.sheets, method, auth, payload);
}
/**
* Collection: spreadsheets.values
* //developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values
* This function corresponds the values collection of the Sheets API.
* See _collection for param definitions.
*
* @param {String} method
* @param {google.auth.OAuth2} auth
* @param {Object} payload
* @return {Promise}
* @memberof SheetsAPI
*/
values(method, auth, payload) {
return this._collection(
this.sheets.spreadsheets.values, method, auth, payload);
}
} |
JavaScript | class EntityListener {
constructor() {
this._href;
this._token;
this._onChange;
this._removeListener;
}
add(href, token, onChange, entity) {
if (!this._validate(href, onChange, entity)) {
return;
}
this._href = href;
this._token = token;
this._onChange = onChange;
window.D2L.Siren.EntityStore.addListener(this._href, this._token, this._onChange).then((removeListener) => {
this._removeListener = removeListener;
window.D2L.Siren.EntityStore.get(this._href, this._token).then((storedEntity) => {
if (storedEntity) {
this._onChange(storedEntity);
return;
}
if (entity) {
window.D2L.Siren.EntityStore.update(href, token, entity);
} else {
window.D2L.Siren.EntityStore.fetch(href, token);
}
});
});
}
update(href, token, onChange, entity) {
if (href === this._href || token === this._token || onChange === this._onChange) {
return;
}
this._removeListener();
this._addListener(href, token, onChange, entity);
}
remove() {
this._removeListener && this._removeListener();
}
_validate(href, onChange, entity) {
href = href && href.href || href;
const entityIsGood = !entity || (entity.hasLinkByRel('self') && entity.getLinkByRel('self').href === href);
// token can be empty.
return href && typeof onChange === 'function' && entityIsGood;
}
} |
JavaScript | class AEMHeadless extends AEMHeadlessApi {
/**
* Constructor.
*
* If param is a string, it's treated as AEM server URL, default GraphQL endpoint is used.
* For granular params, use config object
*
* @param {string|object} config - Configuration object, or AEM server URL string
* @param {string} [config.serviceURL] - AEM server URL
* @param {string} [config.endpoint] - GraphQL endpoint
* @param {(string|Array)} [config.auth] - Bearer token string or [user,pass] pair array
* @param {object} [config.fetch] - custom Fetch instance - default cross-fetch
*/
constructor (config) {
let extendedConfig = {
fetch
}
if (typeof config !== 'string') {
extendedConfig = {
fetch,
...config
}
} else {
extendedConfig.serviceURL = config
}
super(extendedConfig)
}
} |
JavaScript | class Kadira {
constructor(_options) {
this._options = Object.assign({}, DEFAULTS, _options);
this._headers = {
'content-type': 'application/json',
accepts: 'application/json',
'KADIRA-APP-ID': this._options.appId,
'KADIRA-APP-SECRET': this._options.appSecret,
'MONTI-AGENT-VERSION': this._options.agentVersion,
};
this._clock = new Clock({
endpoint: this._options.endpoint + '/simplentp/sync',
});
this._clockSyncInterval = null;
}
connect() {
logger('connecting with', this._options);
return this._checkAuth()
.then(() => this._clock.sync())
.then(() => {
this._clockSyncInterval = setInterval(
() => this._clock.sync(),
this._options.clockSyncInterval
);
});
}
disconnect() {
logger('disconnect');
clearInterval(this._clockSyncInterval);
}
getJob(id) {
const data = {action: 'get', params: {}};
Object.assign(data.params, {id});
const url = this._options.endpoint + '/jobs';
const params = {
data,
headers: this._headers,
};
logger('get job', id);
return this._send(url, params);
}
updateJob(id, diff) {
const data = {action: 'set', params: {}};
Object.assign(data.params, diff, {id});
const url = this._options.endpoint + '/jobs';
const params = {
data,
headers: this._headers,
};
logger('update job', id);
return this._send(url, params);
}
// send the given payload to the server
sendData(_payload) {
const payload = {
..._payload,
host: this._options.hostname
};
const url = this._options.endpoint;
const data = JSON.stringify(payload);
const params = {
data,
headers: this._headers,
};
logger(`send data - ${data.substr(0, 50)}...`);
return this._send(url, params);
}
get(path, options = {}) {
const url = this._options.endpoint + path;
const params = {
headers: {
...this._headers
},
noRetry: options.noRetry
};
logger(`get request to ${url}`);
return this._send(url, params);
}
sendStream(path, stream) {
const url = this._options.endpoint + path;
const params = {
data: stream,
headers: {
...this._headers,
'content-type': 'application/octet-stream'
},
};
logger(`send stream to ${url}`);
return this._send(url, params);
}
// ping the server to check whether appId and appSecret
// are valid and correct. Data sent inside http headers.
_checkAuth() {
const uri = this._options.endpoint + '/ping';
const params = {headers: this._headers};
return this._send(uri, params);
}
// communicates with the server with http
// Also handles response http status codes and retries
_send(url, params) {
let retryEnabled = true;
if (params.noRetry) {
retryEnabled = false;
delete params.noRetry;
}
return retry(() => {
return new Promise((resolve, reject) => {
axios({
url,
// Axios defaults to 10mb. Increases limit to 100mb.
maxBodyLength: 100 * 1024 * 1024,
...params,
method: params.method || 'POST'
}).then((res) => {
return resolve(res.data);
})
.catch(err => {
if (err.response && err.response.status) {
let status = err.response.status;
if (status === 401) {
logger('Error: Unauthorized');
return reject(new ByPassRetryError('Unauthorized'));
} else if (status >= 400 && status < 500) {
const message = `Agent Error: ${status}`;
logger(`Error: ${message}`);
return reject(new ByPassRetryError(message));
}
const message = `Request failed: ${status}`;
const ErrConstructor = retryEnabled ? Error : ByPassRetryError;
logger(`Error: ${message}`);
return reject(new ErrConstructor(message));
}
if (!retryEnabled) {
let oldErr = err;
// eslint-disable-next-line no-param-reassign
err = new ByPassRetryError(oldErr.message);
err.stack = oldErr.stack;
}
return reject(err);
});
});
});
}
} |
JavaScript | class Home extends Component {
static propTypes = {};
render() {
return (
<div className={`${styles.mainContainer} some-other-class`}>
<h3>Home page</h3>
<ProjectsList/>
</div>
);
}
} |
JavaScript | class AuroFlightline extends LitElement {
constructor() {
super();
this.canceled = false;
this.cq = defaultContainerWidth;
/** @private */
this.showAllStops = false;
}
static get properties() {
return {
canceled: { type: Boolean },
showAllStops: { type: Boolean },
cq: { type: Number }
};
}
static get styles() {
return css`
${styleCss}
`;
}
firstUpdated() {
const setShowAllStops = (val) => {
this.showAllStops = val > this.cq;
};
this.observedNode = this;
observeResize(this.observedNode, setShowAllStops);
}
disconnectedCallback() {
unobserve(this.observedNode);
}
// function that renders the HTML and CSS into the scope of the component
render() {
const isMultiple = this.children.length > 1;
const classes = {
'slot-container': true,
'nonstop': !this.children.length && !this.canceled,
'multiple': isMultiple,
'canceled': this.canceled,
'show-all-stops': this.showAllStops
};
return html`
<div class="${classMap(classes)}">
${this.canceled ? html`` : html` <slot></slot>`}
${isMultiple && !this.canceled ? html`
<auro-flight-segment iata="${this.children.length} stops"></auro-flight-segment>
` : html``}
</div>`;
}
} |
JavaScript | class Oracle {
constructor( connection ) {
this.connection = connection
this.pool = null
this.cnxn = null
this._inTransaction = false
oracledb.autoCommit = true
oracledb.outFormat = oracledb.OBJECT
}
/**
* Creates a database connection on demand.
*
* @returns Promise< Connection >
*/
async _connect() {
if ( !this.pool ) {
const options = {
user: this.connection.Username,
password: this.connection.Password,
connectString: this.connection.Hostname
}
if ( this.connection.Parameters ) {
const extraParams = require('database-js-common').parseConnectionParams(this.connection.Parameters, true);
Object.assign( options, extraParams )
}
this.pool = await oracledb.createPool( options )
}
if ( !this.cnxn ) {
this.cnxn = await this.pool.getConnection()
}
return this.cnxn
}
/**
* Performs a query or data manipulation command
*
* @param {string} sql
* @returns Promise< Array< Object > >
*/
async query(sql) {
let connection = await this._connect()
let result = await connection.execute(sql)
return result.rows
}
/**
* Performs a data manipulation command
*
* @param {string} sql
* @returns Promise< Array< Object > >
*/
async execute(sql) {
return await query(sql)
}
/**
* Closes a database connection
*
* @returns Promise<>
*/
async close() {
if ( this.cnxn ) {
await this.rollback()
await this.cnxn.close()
this.cnxn = null
}
if ( this.pool ) {
await this.pool.close(0)
this.pool = null
}
}
isTransactionSupported() {
return true
}
inTransaction() {
return this._inTransaction
}
beginTransaction() {
this._inTransaction = true
oracledb.autoCommit = false
}
async commit() {
if(this._inTransaction) {
await this.connection.commit()
this._inTransaction = false
oracledb.autoCommit = true
}
}
async rollback() {
if(this._inTransaction) {
await this.connection.rollback()
this._inTransaction = false
oracledb.autoCommit = true
}
}
} |
JavaScript | class Stateful extends React.Component {
constructor(props) {
super(props);
const { initialState } = props;
const state = watchable.object(
typeof initialState === 'function' ? initialState() : initialState,
);
this.state = {
state,
data: props.compute({ state }),
};
}
componentDidMount() {
this._watchableCompute = watchable.value({
get: () => this.props.compute,
});
this._handle = watch(() => {
const { state } = this.state;
this.setState({
data: this._watchableCompute.get()({ state }),
});
});
}
componentDidUpdate(prevProps) {
if (this.props.compute !== prevProps.compute) {
this._watchableCompute.set();
}
}
componentWillUnmount() {
if (this._handle) {
this._handle.stop();
}
}
render() {
return this.props.children(this.state.data);
}
} |
JavaScript | class Timeline {
// constructor method to initialize Timeline object
constructor(parentElement, data){
this._parentElement = parentElement;
this._data = data;
// No data wrangling, no update sequence
this._displayData = data[0];
console.log("Timeline data loaded", this._displayData)
}
// create initVis method for Timeline class
initVis() {
// store keyword this which refers to the object it belongs to in variable vis
let vis = this;
vis.margin = {top: 0, right: 40, bottom: 30, left: 40};
vis.width = document.getElementById(vis._parentElement).getBoundingClientRect().width - vis.margin.left - vis.margin.right;
vis.height = document.getElementById(vis._parentElement).getBoundingClientRect().height - vis.margin.top - vis.margin.bottom;
// SVG drawing area
vis.svg = d3_7.select("#" + vis._parentElement).append("svg")
.attr("width", vis.width + vis.margin.left + vis.margin.right)
.attr("height", vis.height + vis.margin.top + vis.margin.bottom)
.append("g")
.attr("transform", "translate(" + vis.margin.left + "," + vis.margin.top + ")");
// Scales and axes
vis.x = d3_7.scaleTime()
.range([0, vis.width])
.domain(d3_7.extent(vis._displayData, function(d) { return d.Year; }));
vis.y = d3_7.scaleLinear()
.range([vis.height, 0])
.domain([0, d3_7.max(vis._displayData, function(d) { return d.Expenditures; })]);
vis.xAxis = d3_7.axisBottom()
.scale(vis.x);
// SVG area path generator
vis.area = d3_7.area()
.x(function(d) { return vis.x(d.Year); })
.y0(vis.height)
.y1(function(d) { return vis.y(d.Expenditures); });
// Draw area by using the path generator
vis.svg.append("path")
.datum(vis._displayData)
.attr("fill", "#ccc")
.attr("d", vis.area);
// Initialize brush component
let brush = d3_7.brushX()
.extent([[0, 0], [vis.width, vis.height]])
.on("brush", brushed);
// TO-DO: Append brush component here
vis.svg.append("g")
.attr("class", "brush")
.call(brush)
.selectAll("rect")
.attr("y", -6)
.attr("height", vis.height + 7);
// Append x-axis
vis.svg.append("g")
.attr("class", "x-axis axis")
.attr("transform", "translate(0," + vis.height + ")")
.call(vis.xAxis);
}
} |
JavaScript | class UintAnimation extends Animation {
readMdxValue(stream) {
return stream.readUint32Array(1);
}
writeMdxValue(stream, value) {
stream.writeUint32(value[0]);
}
readMdlValue(stream) {
return new Uint32Array([stream.readInt()]);
}
writeMdlValue(stream, name, value) {
stream.writeNumberAttrib(name, value[0]);
}
} |
JavaScript | class FloatAnimation extends Animation {
readMdxValue(stream) {
return stream.readFloat32Array(1);
}
writeMdxValue(stream, value) {
stream.writeFloat32(value[0]);
}
readMdlValue(stream) {
return new Float32Array([stream.readFloat()]);
}
writeMdlValue(stream, name, value) {
stream.writeNumberAttrib(name, value[0]);
}
} |
JavaScript | class Vector3Animation extends Animation {
readMdxValue(stream) {
return stream.readFloat32Array(3);
}
writeMdxValue(stream, value) {
stream.writeFloat32Array(value);
}
readMdlValue(stream) {
return stream.readVector(new Float32Array(3));
}
writeMdlValue(stream, name, value) {
stream.writeVectorAttrib(name, value);
}
} |
JavaScript | class Vector4Animation extends Animation {
readMdxValue(stream) {
return stream.readFloat32Array(4);
}
writeMdxValue(stream, value) {
stream.writeFloat32Array(value);
}
readMdlValue(stream) {
return stream.readVector(new Float32Array(4));
}
writeMdlValue(stream, name, value) {
stream.writeVectorAttrib(name, value);
}
} |
JavaScript | class Search extends Component {
state = {
search: "",
employees: [],
filtered: [],
error: "",
sortDir: "asc"
};
// When the component mounts, get a list of all available employees and update this.state.employees and also this.state.filtered
componentDidMount() {
// call getEmployees to return the random list of employees
API.getEmployees()
.then(res => {
// store returned list into state variable of employees (this will be static)
this.setState({ employees: res.data.results})
// also store returned list into state variable of filtered (this will change over time)
this.setState({ filtered: res.data.results})
})
.catch(err => console.log(err));
}
handleInputChange = event => {
// check if a search term exists within input form field
if(event) {
var filter = (event.target.value).toLowerCase();
const filteredList = this.state.employees.filter(result => {
// check search string exists within any of the fields and return the array value if a match
return (result.name.first.toLowerCase().indexOf(filter) !== -1)
|| (result.name.last.toLowerCase().indexOf(filter) !== -1)
|| (result.phone.toLowerCase().indexOf(filter) !== -1)
|| (result.location.street.number.toString().indexOf(filter) !== -1)
|| (result.location.street.name.toLowerCase().indexOf(filter) !== -1)
|| (result.location.city.toLowerCase().indexOf(filter) !== -1)
|| (result.location.state.toLowerCase().indexOf(filter) !== -1);
});
// set filtered array state to be the new filtered list
this.setState({filtered: filteredList});
// console.log(this.state.filtered);
}
else {
// since no search term, need to restore filtered list back to original full employee list
this.setState({filtered: this.state.employees});
}
};
// function to sort table of employees by selected column heading name
sortField = (field) => {
var sortList;
// check if sorting by first or last name
if((field === "first") || (field ==="last")) {
// check if ascending sortDir state
if(this.state.sortDir === "asc") {
// perform sort - need this because first/last is buried below "name" not at root
sortList = this.state.filtered.sort((a, b) => {
return a.name[field].localeCompare(b.name[field])
})
// change sortDir state to descending
this.setState({sortDir: "desc"});
}
else {
// perform sort - need this because first/last is buried below "name" not at root
sortList = this.state.filtered.sort((a, b) => {
return b.name[field].localeCompare(a.name[field])
})
// change sortDir state to ascending
this.setState({sortDir: "asc"});
}
}
// check if sorting by street
else if((field === "street")) {
// check if ascending sortDir state
if(this.state.sortDir === "asc") {
// perform sort - need this because name is buried under location & street not at root
sortList = this.state.filtered.sort((a, b) => {
return a.location[field].name.localeCompare(b.location[field].name)
})
// change sortDir state to descending
this.setState({sortDir: "desc"});
}
else {
// perform sort - need this because name is buried under location & street not at root
sortList = this.state.filtered.sort((a, b) => {
return b.location[field].name.localeCompare(a.location[field].name)
})
// chnage sortDir state to ascending
this.setState({sortDir: "asc"});
}
}
// check if sorting by city or state
else if((field === "city") || (field === "state")) {
// check if ascending sortDir state
if(this.state.sortDir === "asc") {
// perform sort - need this because city/state are buried under location not at root
sortList = this.state.filtered.sort((a,b) => {
return a.location[field].localeCompare(b.location[field])
})
// change sortDir state to descending
this.setState({sortDir: "desc"});
}
else {
// perform sort - need this because city/state are buried under location not at root
sortList = this.state.filtered.sort((a, b) => {
return b.location[field].localeCompare(a.location[field]);
});
// change sortDir state to ascending
this.setState({sortDir: "asc"});
}
}
else {
// check if ascending sortDir state
if(this.state.sortDir === "asc") {
// use filtered list of employees to sort on
sortList = this.state.filtered.sort((a, b) => {
// compare the values of each array record for sorting based upon field name passed in
return a[field].localeCompare(b[field])
})
// change sortDir state to descending
this.setState({sortDir: "desc"});
}
else {
// use filtered list of employees to sort on
sortList = this.state.filtered.sort((a, b) => {
// compare the values of each array record for sorting based upon field name passed in
return b[field].localeCompare(a[field])
})
// change sortDir state to ascending
this.setState({sortDir: "asc"});
}
}
// update the state variable filtered with new sorted list
this.setState({filtered: sortList});
}
render() {
return (
<div className="container-fluid">
<Container style={{ minHeight: "80%" }}>
<SearchForm
handleInputChange={this.handleInputChange}
/>
<EmployeeTable
sortField = {this.sortField}
results={this.state.filtered} />
</Container>
</div>
);
}
} |
JavaScript | class CheckDone extends SimpleEvent {
constructor (request_id) {
super(NAME, { request_id })
}
static NAME () {
return NAME
}
} |
JavaScript | class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [
{
username: "Jeff",
online: true,
},
{
username: "Alan",
online: false,
},
{
username: "Mary",
online: true,
},
{
username: "Jim",
online: false,
},
{
username: "Sara",
online: true,
},
{
username: "Laura",
online: true,
},
],
};
}
render() {
const usersOnline = this.state.users.filter((i) => i.online == true);
//console.log(this.state.users[0].online)
const renderOnline = usersOnline.map((i) => (
<li key={i.username + 1}>{i.username}</li>
)); // change code here
return (
<div>
<h1>Current Online Users:</h1>
<ul>{renderOnline}</ul>
</div>
);
}
} |
JavaScript | class StitchClient {
constructor(clientAppID, options) {
let baseUrl = common.DEFAULT_STITCH_SERVER_URL;
if (options && options.baseUrl) {
baseUrl = options.baseUrl;
}
this.clientAppID = clientAppID;
this.authUrl = (
clientAppID ?
`${baseUrl}/api/client/v1.0/app/${clientAppID}/auth` :
`${baseUrl}/api/public/v1.0/auth`
);
this.rootURLsByAPIVersion = {
[v1]: {
public: `${baseUrl}/api/public/v1.0`,
client: `${baseUrl}/api/client/v1.0`,
app: (clientAppID ?
`${baseUrl}/api/client/v1.0/app/${clientAppID}` :
`${baseUrl}/api/public/v1.0`)
},
[v2]: {
public: `${baseUrl}/api/public/v2.0`,
client: `${baseUrl}/api/client/v2.0`,
app: (clientAppID ?
`${baseUrl}/api/client/v2.0/app/${clientAppID}` :
`${baseUrl}/api/public/v2.0`)
}
};
this.auth = new Auth(this, this.authUrl);
this.auth.handleRedirect();
this.auth.handleCookie();
// deprecated API
this.authManager = {
apiKeyAuth: (key) => this.authenticate('apiKey', key),
localAuth: (email, password) => this.login(email, password),
mongodbCloudAuth: (username, apiKey, opts) =>
this.authenticate('mongodbCloud', Object.assign({ username, apiKey }, opts))
};
this.authManager.apiKeyAuth =
deprecate(this.authManager.apiKeyAuth, 'use `client.authenticate("apiKey", "key")` instead of `client.authManager.apiKey`');
this.authManager.localAuth =
deprecate(this.authManager.localAuth, 'use `client.login` instead of `client.authManager.localAuth`');
this.authManager.mongodbCloudAuth =
deprecate(this.authManager.mongodbCloudAuth, 'use `client.authenticate("mongodbCloud", opts)` instead of `client.authManager.mongodbCloudAuth`');
}
/**
* Login to stitch instance, optionally providing a username and password. In
* the event that these are omitted, anonymous authentication is used.
*
* @param {String} [email] the email address used for login
* @param {String} [password] the password for the provided email address
* @param {Object} [options] additional authentication options
* @returns {Promise}
*/
login(email, password, options = {}) {
if (email === undefined || password === undefined) {
return this.authenticate('anon', options);
}
return this.authenticate('userpass', Object.assign({ username: email, password }, options));
}
/**
* Send a request to the server indicating the provided email would like
* to sign up for an account. This will trigger a confirmation email containing
* a token which must be used with the `emailConfirm` method of the `userpass`
* auth provider in order to complete registration. The user will not be able
* to log in until that flow has been completed.
*
* @param {String} email the email used to sign up for the app
* @param {String} password the password used to sign up for the app
* @param {Object} [options] additional authentication options
* @returns {Promise}
*/
register(email, password, options = {}) {
return this.auth.provider('userpass').register(email, password, options);
}
/**
* Submits an authentication request to the specified provider providing any
* included options (read: user data). If auth data already exists and the
* existing auth data has an access token, then these credentials are returned.
*
* @param {String} providerType the provider used for authentication (e.g. 'userpass', 'facebook', 'google')
* @param {Object} [options] additional authentication options
* @returns {Promise} which resolves to a String value: the authed userId
*/
authenticate(providerType, options = {}) {
// reuse existing auth if present
const existingAuthData = this.auth.get();
if (existingAuthData.hasOwnProperty('accessToken')) {
return Promise.resolve(existingAuthData.userId);
}
return this.auth.provider(providerType).authenticate(options)
.then(authData => authData.userId);
}
/**
* Ends the session for the current user.
*
* @returns {Promise}
*/
logout() {
return this._do('/auth', 'DELETE', { refreshOnFailure: false, useRefreshToken: true })
.then(() => this.auth.clear());
}
/**
* @return {*} Returns any error from the Stitch authentication system.
*/
authError() {
return this.auth.error();
}
/**
* Returns profile information for the currently logged in user
*
* @returns {Promise}
*/
userProfile() {
return this._do('/auth/me', 'GET')
.then(response => response.json());
}
/**
* @return {String} Returns the currently authed user's ID.
*/
authedId() {
return this.auth.authedId();
}
/**
* Factory method for accessing Stitch services.
*
* @method
* @param {String} type The service type [mongodb, {String}]
* @param {String} name The service name.
* @return {Object} returns a named service.
*/
service(type, name) {
if (this.constructor !== StitchClient) {
throw new StitchError('`service` is a factory method, do not use `new`');
}
if (!ServiceRegistry.hasOwnProperty(type)) {
throw new StitchError('Invalid service type specified: ' + type);
}
const ServiceType = ServiceRegistry[type];
return new ServiceType(this, name);
}
/**
* Executes a named pipeline.
*
* @param {String} name Name of the named pipeline to execute.
* @param {Object} args Arguments to the named pipeline to execute.
* @param {Object} [options] Additional options to pass to the execution context.
*/
executeNamedPipeline(name, args, options = {}) {
const namedPipelineStages = [
{
service: '',
action: 'namedPipeline',
args: { name, args }
}
];
return this.executePipeline(namedPipelineStages, options);
}
/**
* Executes a service pipeline.
*
* @param {Array} stages Stages to process.
* @param {Object} [options] Additional options to pass to the execution context.
*/
executePipeline(stages, options = {}) {
let responseDecoder = (d) => EJSON.parse(d, { strict: false });
let responseEncoder = (d) => EJSON.stringify(d);
stages = Array.isArray(stages) ? stages : [ stages ];
stages = stages.reduce((acc, stage) => acc.concat(stage), []);
if (options.decoder) {
if ((typeof options.decoder) !== 'function') {
throw new Error('decoder option must be a function, but "' + typeof (options.decoder) + '" was provided');
}
responseDecoder = options.decoder;
}
if (options.encoder) {
if ((typeof options.encoder) !== 'function') {
throw new Error('encoder option must be a function, but "' + typeof (options.encoder) + '" was provided');
}
responseEncoder = options.encoder;
}
if (options.finalizer && typeof options.finalizer !== 'function') {
throw new Error('finalizer option must be a function, but "' + typeof (options.finalizer) + '" was provided');
}
return this._do('/pipeline', 'POST', { body: responseEncoder(stages) })
.then(response => response.text())
.then(body => responseDecoder(body))
.then(collectMetadata(options.finalizer));
}
_do(resource, method, options) {
options = Object.assign({}, {
refreshOnFailure: true,
useRefreshToken: false,
apiVersion: v1
}, options);
if (!options.noAuth) {
if (!this.authedId()) {
return Promise.reject(new StitchError('Must auth first', ErrUnauthorized));
}
}
const appURL = this.rootURLsByAPIVersion[options.apiVersion].app;
let url = `${appURL}${resource}`;
let fetchArgs = common.makeFetchArgs(method, options.body);
if (!!options.headers) {
Object.assign(fetchArgs.headers, options.headers);
}
if (!options.noAuth) {
let token =
options.useRefreshToken ? this.auth.getRefreshToken() : this.auth.getAccessToken();
fetchArgs.headers.Authorization = `Bearer ${token}`;
}
if (options.queryParams) {
url = `${url}?${queryString.stringify(options.queryParams)}`;
}
return fetch(url, fetchArgs)
.then((response) => {
// Okay: passthrough
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response);
}
if (response.headers.get('Content-Type') === common.JSONTYPE) {
return response.json()
.then((json) => {
// Only want to try refreshing token when there's an invalid session
if ('errorCode' in json && json.errorCode === ErrInvalidSession) {
if (!options.refreshOnFailure) {
this.auth.clear();
const error = new StitchError(json.error, json.errorCode);
error.response = response;
error.json = json;
throw error;
}
return this.auth.refreshToken()
.then(() => {
options.refreshOnFailure = false;
return this._do(resource, method, options);
});
}
const error = new StitchError(json.error, json.errorCode);
error.response = response;
error.json = json;
return Promise.reject(error);
});
}
const error = new Error(response.statusText);
error.response = response;
return Promise.reject(error);
});
}
// Deprecated API
authWithOAuth(providerType, redirectUrl) {
return this.auth.provider(providerType).authenticate({ redirectUrl });
}
anonymousAuth() {
return this.authenticate('anon');
}
} |
JavaScript | class LoggedMessageChannel {
onmessage = () => { /* */
console.log('test');
};
constructor(messageChannel) {
this.messageChannel = messageChannel;
this.messageChannel.onmessage = this.onMessage;
}
onMessage = (evt) => {
console.log(`[UEF] From Learn Ultra:`, evt.data);
this.onmessage(evt);
};
postMessage = (msg) => {
console.log(`[UEF] To Learn Ultra`, msg);
this.messageChannel.postMessage(msg);
}
} |
JavaScript | class Pagination extends React.Component {
static displayName = 'Pagination';
static propTypes = {
current: PropTypes.number,
count: PropTypes.number,
formatter: PropTypes.func,
};
static defaultProps = {
formatter: p => p,
};
constructor(props) {
super(props);
this.pages = Array.apply(null, { length: props.count }).map((item, index) => index + 1); // eslint-disable-line
}
render() {
let { current = 1 } = this.props;
const { count = 1, formatter = p => p } = this.props;
current = Number(current);
if (count === 1) {
return null;
}
return (
<ul className={styles.pagin}>
<li className={classnames(current === 1 && styles['is-disabled'])}>
<Link to={formatter(current - 1)}><Icon name="arrow-left" /></Link>
</li>
{
this.pages.map(page => (
<li className={classnames(current === page && styles['is-active'])} key={page}>
<Link to={formatter(page)}>{page}</Link>
</li>
))
}
<li className={classnames(current === count && styles['is-disabled'])}>
<Link to={formatter(current + 1)}><Icon name="arrow-right" /></Link>
</li>
</ul>
);
}
} |
JavaScript | class ParroquiasSearch {
constructor($scope, $reactive, $sce, userHelpers, googleLoader) {
'ngInject';
console.log(`started ${componentName}`);
$reactive(this).attach($scope);
userHelpers.setupUserHelpers(this);
//map related stuff
this.availableMap = false;
this.showMap = false;
this.google = null;
googleLoader.promise.then((google) => {
this.availableMap = true;
this.google = google;
this.map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 23.6345, lng: -102.5528 },
zoom: 4,
scrollwheel: false
});
});
this.markers = [];
//map watcher for hide/show map so that it will be correctly visible
$scope.$watch(
() => {
return $('#map').is(":visible");
},
(newValue, oldValue) => {
console.log(`map is now ${newValue}`);
if(newValue){
this.refreshMap();
this.displayResultsOnMap();
}
}
);
//suggestions
this.suggest = debounce(this._suggest, 200);
this.suggestions = [];
//search related stuff
this.q = "";
this._searched_parroquias = [];
this.$scope = $scope;
//this.search = debounce(this._search, 300);
this.search = this._search;
this.numParroquias = 0;
this.pageInfo = {
page: 0,
perPage: 10
};
this.isSearching = false;
this.search();
this.$sce = $sce;
}
/**
* toggle maps show flag
*/
toggleShowMap(){
this.showMap = !(this.showMap);
this.refreshMap();
}
/**
* refresh map if the map is visible
*/
refreshMap(){
if(this.showMap){
if(!_.isNil(this.google) && !_.isNil(this.map)){
this.google.maps.event.trigger(this.map, 'resize');
}
}
}
/**
* _suggest
*
* This function is debounced to 200ms and therefore will be called only
* after the function suggest() has not been called in the last 200ms. This
* function returns suggestions for the search field.
*/
_suggest(){
this.call('parroquias.search.suggest', this.q, (error, result) => {
if(error){
throw error;
}
if(_.isNil(result.options)){
return;
}
//console.log(result.options);
this.suggestions = result.options;
});
}
/**
* suggestionSelected
*
* When a suggestion is selected this will change the query text.
*/
suggestionSelected(){
if(_.isNil(this.selectedSuggestion) || _.isNil(this.selectedSuggestion.text)){
return;
}
//console.log(`selected suggestion ${this.selectedSuggestion.text}`);
this.q = this.selectedSuggestion.text;
this.search();
}
/**
* _search
*/
_search(){
//console.log(`searching ${this.q}`);
this.isSearching = true;
this.call('parroquias.search', this.q, this.pageInfo, (error, result) => {
this.isSearching = false;
if(error){
throw error;
}
this._searched_parroquias = result.hits;
this.numParroquias = result.total;
//console.log(this._searched_parroquias);
this.displayResultsOnMap();
});
}
/**
* displayResultsOnMap
*
* Check which results have lon/lat and display them on a map. The map
* will be resized to fit the results
*/
displayResultsOnMap(){
// check we have a map and it is visible
if(_.isNil(this.map) || !this.showMap || _.isNil(this.google)){
//clean old parroquias on markers here
this.clearMarkers();
return;
}
// get all of the parroquias with locations
if(!this._searched_parroquias || this._searched_parroquias.length <= 0){
//clean old parroquias on markers here
this.clearMarkers();
return;
}
let locatedParroquias = _.filter(
this._searched_parroquias,
(parroquia) => {
return (_.has(parroquia, 'location.lat') &&
_.has(parroquia, 'location.lon'));
}
);
// remove old markers
this.clearMarkers();
// add markers for each parroquias to map
this.markers = _.map(
locatedParroquias,
(parroquia) => {
let pLocation = parroquia.location;
let location = {
lat: _.toNumber(pLocation.lat),
lng: _.toNumber(pLocation.lon)
};
let infoWindow = new this.google.maps.InfoWindow({
content: `<div>${parroquia.name}</div>`
});
let marker = new this.google.maps.Marker({
position: location,
map: this.map,
title: parroquia.name
});
marker.addListener('click', () => {
let iWindow = infoWindow;
iWindow.open(this.map, marker);
});
return marker;
}
);
// change map to fit markers
let bounds = new this.google.maps.LatLngBounds();
for(let marker of this.markers){
bounds.extend(marker.getPosition());
}
this.map.setCenter(bounds.getCenter());
this.map.fitBounds(bounds);
}
/**
* clearMarkers
*
* removes all markers from the map
*/
clearMarkers(){
for(let marker of this.markers){
marker.setMap(null);
}
this.markers = [];
}
/**
* This procedure is called every time the page is changed from within
* the pagination controls.
*/
changePage(newPage){
//console.log(newPage);
this.pageInfo.page = newPage-1;
this.search();
}
} |
JavaScript | class ShiftHourlyEntryModel extends BaseModel
{
/**
* ShiftHourlyEntryModel Constructor
*
* @protected
*/
constructor()
{
super();
/**
* The Shift Hourly Entry ID
*
* @type {string}
* @public
*/
this.id = undefined;
/**
* The Packing Line ID this Hourly Entry is associated with
*
* @type {string}
* @public
*/
this.packingLineId = undefined;
/**
* The Shift ID this Hourly Entry is asssociated with
*
* @type {string}
* @public
*/
this.shiftId = undefined;
/**
* When this Hourly Entry was Created
*
* @type {Date}
* @public
*/
this.createdTimestamp = undefined;
/**
* The Start Timestamp of this Hourly Entry
*
* @type {Date}
* @public
*/
this.startTimestamp = undefined;
/**
* The End Timestamp of this Hourly Entry
*
* @type {Date}
* @public
*/
this.endTimestamp = undefined;
/**
* The Number of People working in all Areas except Class 2 for this Hour
*
* @type {?number}
* @public
*/
this.class1Manning = undefined;
/**
* The Number of People working in the Class 2 Area for this Hour
*
* @type {?number}
* @public
*/
this.class2Manning = undefined;
/**
* The Average Target Number of People that should be working for this Hour
*
* @type {?number}
* @public
*/
this.averageManningTarget = undefined;
/**
* The Percentage of Total Tray Equivalents that are Layered for this Hour
*
* @type {?number}
* @public
*/
this.layeredTrayPercentage = undefined;
/**
* The Average Class 1 Percentage for this Hour
*
* @type {?number}
* @public
*/
this.averageClass1Percentage = undefined;
/**
* The Number of Quality R600 Samples that were Ideal for this Hour
*
* @type {?number}
* @public
*/
this.qualityR600IdealSamplesPercentage = undefined;
/**
* An Array of Custom Quality Data Items for this Hour
*
* @type {Array<{id: string, name: string, type: string, value: number}>}
* @public
*/
this.customQualityData = undefined;
/**
* The Total Number of Bins Tipped for this Hour
*
* @type {number}
* @public
*/
this.totalBinsTipped = undefined;
/**
* The Target Number of Bins to Tip for this Hour
*
* @type {number}
* @public
*/
this.binsTippedTarget = undefined;
/**
* The Total Downtime for this Hour expressed in Seconds
*
* @type {number}
* @public
*/
this.totalDowntime = undefined;
/**
* The Total Time that could be Utilized for Packing Fruit (excludes Planned Downtime such as Smoko Breaks) for this Hour expressed in Seconds
*
* @type {number}
* @public
*/
this.totalProductionTime = undefined;
/**
* The Total Number of Class 1 Tray Equivalents Packed for this Hour
*
* @type {number}
* @public
*/
this.totalClass1Trays = undefined;
/**
* The Total Number of Class 2 Tray Equivalents Packed for this Hour
*
* @type {number}
* @public
*/
this.totalClass2Trays = undefined;
/**
* The Target Number of Class 1 Tray Equivalents that should be Packed excluding all Downtime for this Hour
*
* @type {number}
* @public
*/
this.class1TraysPerHourExcludingDowntimeTarget = undefined;
/**
* The Primary Issue Category for this Hourly Entry
*
* @type {?string}
* @public
*/
this.primaryIssueCategory = undefined;
/**
* The Primary Issue Tag for this Hourly Entry
*
* @type {?string}
* @public
*/
this.primaryIssueTag = undefined;
/**
* The Secondary Issue Category for this Hourly Entry
*
* @type {?string}
* @public
*/
this.secondaryIssueCategory = undefined;
/**
* The Secondary Issue Tag for this Hourly Entry
*
* @type {?string}
* @public
*/
this.secondaryIssueTag = undefined;
/**
* An Optional Focus for the Next Hour
*
* @type {?string}
* @public
*/
this.nextHourFocus = undefined;
/**
* An Optional Rating between 1 and 10 on how Satisfied the Line Manager was with this Hour
*
* @type {?number}
* @public
*/
this.satisfactionRating = undefined;
/**
* The Status of this Hourly Entry
*
* @type {string}
* @public
*/
this.status = undefined;
/**
* The Number of Class 1 Tray Equivalents that would have been Packed this Hour without Planned Downtime (e.g. Smoko Breaks)
*
* @type {number}
* @public
*/
this.class1TraysPerHourPotential = undefined;
/**
* The Number of Class 1 Tray Equivalents that would have been Packed this Hour with Zero Downtime
*
* @type {number}
* @public
*/
this.class1TraysPerHourExcludingDowntime = undefined;
/**
* The Number of Class 1 Tray Equivalents that would have been Packed per Person this Hour without Planned Downtime (e.g. Smoko Breaks)
*
* @type {?number}
* @public
*/
this.class1TraysPerManHourPotential = undefined;
/**
* The Number of Class 1 Tray Equivalents that would have been Packed per Person this Hour with Zero Downtime
*
* @type {?number}
* @public
*/
this.class1TraysPerManHourExcludingDowntime = undefined;
/**
* The Manning Percentage based on the Average Target for this Hour
*
* @type {?number}
* @public
*/
this.manningPercentage = undefined;
/**
* The Total Number of People working for this Hour
*
* @type {?number}
* @public
*/
this.totalManning = undefined;
/**
* The Percentage of Production Time without Downtime for this Hour
*
* @type {number}
* @public
*/
this.uptimePercentage = undefined;
/**
* The Percentage of Downtime for this Hour
*
* @type {number}
* @public
*/
this.downtimePercentage = undefined;
/**
* Whether the Shift Hourly Entry has been deleted
*
* @type {boolean}
* @public
*/
this.deleted = undefined;
/**
* When the Shift Hourly Entry was last updated
*
* @type {Date}
* @public
*/
this.updateTimestamp = undefined;
}
/**
* Create a new **ShiftHourlyEntryModel** from a JSON Object or JSON String
*
* @static
* @public
* @param {Object<string, any>|string} json A JSON Object or JSON String
* @return {ShiftHourlyEntryModel}
*/
static fromJSON(json)
{
let model = new ShiftHourlyEntryModel();
/**
* The JSON Object
*
* @type {Object<string, any>}
*/
let jsonObject = {};
if(typeof json === 'string')
{
jsonObject = JSON.parse(json);
}
else if(typeof json === 'object')
{
jsonObject = json;
}
if('id' in jsonObject)
{
model.id = (function(){
if(typeof jsonObject['id'] !== 'string')
{
return String(jsonObject['id']);
}
return jsonObject['id'];
}());
}
if('packingLineId' in jsonObject)
{
model.packingLineId = (function(){
if(typeof jsonObject['packingLineId'] !== 'string')
{
return String(jsonObject['packingLineId']);
}
return jsonObject['packingLineId'];
}());
}
if('shiftId' in jsonObject)
{
model.shiftId = (function(){
if(typeof jsonObject['shiftId'] !== 'string')
{
return String(jsonObject['shiftId']);
}
return jsonObject['shiftId'];
}());
}
if('createdTimestamp' in jsonObject)
{
model.createdTimestamp = (function(){
if(typeof jsonObject['createdTimestamp'] !== 'string')
{
return new Date(String(jsonObject['createdTimestamp']));
}
return new Date(jsonObject['createdTimestamp']);
}());
}
if('startTimestamp' in jsonObject)
{
model.startTimestamp = (function(){
if(typeof jsonObject['startTimestamp'] !== 'string')
{
return new Date(String(jsonObject['startTimestamp']));
}
return new Date(jsonObject['startTimestamp']);
}());
}
if('endTimestamp' in jsonObject)
{
model.endTimestamp = (function(){
if(typeof jsonObject['endTimestamp'] !== 'string')
{
return new Date(String(jsonObject['endTimestamp']));
}
return new Date(jsonObject['endTimestamp']);
}());
}
if('class1Manning' in jsonObject)
{
model.class1Manning = (function(){
if(jsonObject['class1Manning'] === null)
{
return null;
}
if(typeof jsonObject['class1Manning'] !== 'number')
{
return Number.isInteger(Number(jsonObject['class1Manning'])) ? Number(jsonObject['class1Manning']) : Math.floor(Number(jsonObject['class1Manning']));
}
return Number.isInteger(jsonObject['class1Manning']) ? jsonObject['class1Manning'] : Math.floor(jsonObject['class1Manning']);
}());
}
if('class2Manning' in jsonObject)
{
model.class2Manning = (function(){
if(jsonObject['class2Manning'] === null)
{
return null;
}
if(typeof jsonObject['class2Manning'] !== 'number')
{
return Number.isInteger(Number(jsonObject['class2Manning'])) ? Number(jsonObject['class2Manning']) : Math.floor(Number(jsonObject['class2Manning']));
}
return Number.isInteger(jsonObject['class2Manning']) ? jsonObject['class2Manning'] : Math.floor(jsonObject['class2Manning']);
}());
}
if('averageManningTarget' in jsonObject)
{
model.averageManningTarget = (function(){
if(jsonObject['averageManningTarget'] === null)
{
return null;
}
if(typeof jsonObject['averageManningTarget'] !== 'number')
{
return Number.isInteger(Number(jsonObject['averageManningTarget'])) ? Number(jsonObject['averageManningTarget']) : Math.floor(Number(jsonObject['averageManningTarget']));
}
return Number.isInteger(jsonObject['averageManningTarget']) ? jsonObject['averageManningTarget'] : Math.floor(jsonObject['averageManningTarget']);
}());
}
if('layeredTrayPercentage' in jsonObject)
{
model.layeredTrayPercentage = (function(){
if(jsonObject['layeredTrayPercentage'] === null)
{
return null;
}
if(typeof jsonObject['layeredTrayPercentage'] !== 'number')
{
return Number(jsonObject['layeredTrayPercentage']);
}
return jsonObject['layeredTrayPercentage'];
}());
}
if('averageClass1Percentage' in jsonObject)
{
model.averageClass1Percentage = (function(){
if(jsonObject['averageClass1Percentage'] === null)
{
return null;
}
if(typeof jsonObject['averageClass1Percentage'] !== 'number')
{
return Number(jsonObject['averageClass1Percentage']);
}
return jsonObject['averageClass1Percentage'];
}());
}
if('qualityR600IdealSamplesPercentage' in jsonObject)
{
model.qualityR600IdealSamplesPercentage = (function(){
if(jsonObject['qualityR600IdealSamplesPercentage'] === null)
{
return null;
}
if(typeof jsonObject['qualityR600IdealSamplesPercentage'] !== 'number')
{
return Number(jsonObject['qualityR600IdealSamplesPercentage']);
}
return jsonObject['qualityR600IdealSamplesPercentage'];
}());
}
if('customQualityData' in jsonObject)
{
model.customQualityData = (function(){
if(Array.isArray(jsonObject['customQualityData']) !== true)
{
return [];
}
return jsonObject['customQualityData'].map((customQualityDataItem) => {
return (function(){
let customQualityDataItemObject = {};
if(typeof customQualityDataItem === 'object' && 'id' in customQualityDataItem)
{
customQualityDataItemObject.id = (function(){
if(typeof customQualityDataItem.id !== 'string')
{
return String(customQualityDataItem.id);
}
return customQualityDataItem.id;
}());
}
else
{
customQualityDataItemObject.id = "";
}
if(typeof customQualityDataItem === 'object' && 'name' in customQualityDataItem)
{
customQualityDataItemObject.name = (function(){
if(typeof customQualityDataItem.name !== 'string')
{
return String(customQualityDataItem.name);
}
return customQualityDataItem.name;
}());
}
else
{
customQualityDataItemObject.name = "";
}
if(typeof customQualityDataItem === 'object' && 'type' in customQualityDataItem)
{
customQualityDataItemObject.type = (function(){
if(typeof customQualityDataItem.type !== 'string')
{
return String(customQualityDataItem.type);
}
return customQualityDataItem.type;
}());
}
else
{
customQualityDataItemObject.type = "";
}
if(typeof customQualityDataItem === 'object' && 'value' in customQualityDataItem)
{
customQualityDataItemObject.value = (function(){
if(typeof customQualityDataItem.value !== 'number')
{
return Number(customQualityDataItem.value);
}
return customQualityDataItem.value;
}());
}
else
{
customQualityDataItemObject.value = 0;
}
return customQualityDataItemObject;
}());
});
}());
}
if('totalBinsTipped' in jsonObject)
{
model.totalBinsTipped = (function(){
if(typeof jsonObject['totalBinsTipped'] !== 'number')
{
return Number.isInteger(Number(jsonObject['totalBinsTipped'])) ? Number(jsonObject['totalBinsTipped']) : Math.floor(Number(jsonObject['totalBinsTipped']));
}
return Number.isInteger(jsonObject['totalBinsTipped']) ? jsonObject['totalBinsTipped'] : Math.floor(jsonObject['totalBinsTipped']);
}());
}
if('binsTippedTarget' in jsonObject)
{
model.binsTippedTarget = (function(){
if(typeof jsonObject['binsTippedTarget'] !== 'number')
{
return Number.isInteger(Number(jsonObject['binsTippedTarget'])) ? Number(jsonObject['binsTippedTarget']) : Math.floor(Number(jsonObject['binsTippedTarget']));
}
return Number.isInteger(jsonObject['binsTippedTarget']) ? jsonObject['binsTippedTarget'] : Math.floor(jsonObject['binsTippedTarget']);
}());
}
if('totalDowntime' in jsonObject)
{
model.totalDowntime = (function(){
if(typeof jsonObject['totalDowntime'] !== 'number')
{
return Number.isInteger(Number(jsonObject['totalDowntime'])) ? Number(jsonObject['totalDowntime']) : Math.floor(Number(jsonObject['totalDowntime']));
}
return Number.isInteger(jsonObject['totalDowntime']) ? jsonObject['totalDowntime'] : Math.floor(jsonObject['totalDowntime']);
}());
}
if('totalProductionTime' in jsonObject)
{
model.totalProductionTime = (function(){
if(typeof jsonObject['totalProductionTime'] !== 'number')
{
return Number.isInteger(Number(jsonObject['totalProductionTime'])) ? Number(jsonObject['totalProductionTime']) : Math.floor(Number(jsonObject['totalProductionTime']));
}
return Number.isInteger(jsonObject['totalProductionTime']) ? jsonObject['totalProductionTime'] : Math.floor(jsonObject['totalProductionTime']);
}());
}
if('totalClass1Trays' in jsonObject)
{
model.totalClass1Trays = (function(){
if(typeof jsonObject['totalClass1Trays'] !== 'number')
{
return Number.isInteger(Number(jsonObject['totalClass1Trays'])) ? Number(jsonObject['totalClass1Trays']) : Math.floor(Number(jsonObject['totalClass1Trays']));
}
return Number.isInteger(jsonObject['totalClass1Trays']) ? jsonObject['totalClass1Trays'] : Math.floor(jsonObject['totalClass1Trays']);
}());
}
if('totalClass2Trays' in jsonObject)
{
model.totalClass2Trays = (function(){
if(typeof jsonObject['totalClass2Trays'] !== 'number')
{
return Number.isInteger(Number(jsonObject['totalClass2Trays'])) ? Number(jsonObject['totalClass2Trays']) : Math.floor(Number(jsonObject['totalClass2Trays']));
}
return Number.isInteger(jsonObject['totalClass2Trays']) ? jsonObject['totalClass2Trays'] : Math.floor(jsonObject['totalClass2Trays']);
}());
}
if('class1TraysPerHourExcludingDowntimeTarget' in jsonObject)
{
model.class1TraysPerHourExcludingDowntimeTarget = (function(){
if(typeof jsonObject['class1TraysPerHourExcludingDowntimeTarget'] !== 'number')
{
return Number.isInteger(Number(jsonObject['class1TraysPerHourExcludingDowntimeTarget'])) ? Number(jsonObject['class1TraysPerHourExcludingDowntimeTarget']) : Math.floor(Number(jsonObject['class1TraysPerHourExcludingDowntimeTarget']));
}
return Number.isInteger(jsonObject['class1TraysPerHourExcludingDowntimeTarget']) ? jsonObject['class1TraysPerHourExcludingDowntimeTarget'] : Math.floor(jsonObject['class1TraysPerHourExcludingDowntimeTarget']);
}());
}
if('primaryIssueCategory' in jsonObject)
{
model.primaryIssueCategory = (function(){
if(jsonObject['primaryIssueCategory'] === null)
{
return null;
}
if(typeof jsonObject['primaryIssueCategory'] !== 'string')
{
return String(jsonObject['primaryIssueCategory']);
}
return jsonObject['primaryIssueCategory'];
}());
}
if('primaryIssueTag' in jsonObject)
{
model.primaryIssueTag = (function(){
if(jsonObject['primaryIssueTag'] === null)
{
return null;
}
if(typeof jsonObject['primaryIssueTag'] !== 'string')
{
return String(jsonObject['primaryIssueTag']);
}
return jsonObject['primaryIssueTag'];
}());
}
if('secondaryIssueCategory' in jsonObject)
{
model.secondaryIssueCategory = (function(){
if(jsonObject['secondaryIssueCategory'] === null)
{
return null;
}
if(typeof jsonObject['secondaryIssueCategory'] !== 'string')
{
return String(jsonObject['secondaryIssueCategory']);
}
return jsonObject['secondaryIssueCategory'];
}());
}
if('secondaryIssueTag' in jsonObject)
{
model.secondaryIssueTag = (function(){
if(jsonObject['secondaryIssueTag'] === null)
{
return null;
}
if(typeof jsonObject['secondaryIssueTag'] !== 'string')
{
return String(jsonObject['secondaryIssueTag']);
}
return jsonObject['secondaryIssueTag'];
}());
}
if('nextHourFocus' in jsonObject)
{
model.nextHourFocus = (function(){
if(jsonObject['nextHourFocus'] === null)
{
return null;
}
if(typeof jsonObject['nextHourFocus'] !== 'string')
{
return String(jsonObject['nextHourFocus']);
}
return jsonObject['nextHourFocus'];
}());
}
if('satisfactionRating' in jsonObject)
{
model.satisfactionRating = (function(){
if(jsonObject['satisfactionRating'] === null)
{
return null;
}
if(typeof jsonObject['satisfactionRating'] !== 'number')
{
return Number.isInteger(Number(jsonObject['satisfactionRating'])) ? Number(jsonObject['satisfactionRating']) : Math.floor(Number(jsonObject['satisfactionRating']));
}
return Number.isInteger(jsonObject['satisfactionRating']) ? jsonObject['satisfactionRating'] : Math.floor(jsonObject['satisfactionRating']);
}());
}
if('status' in jsonObject)
{
model.status = (function(){
if(typeof jsonObject['status'] !== 'string')
{
return String(jsonObject['status']);
}
return jsonObject['status'];
}());
}
if('class1TraysPerHourPotential' in jsonObject)
{
model.class1TraysPerHourPotential = (function(){
if(typeof jsonObject['class1TraysPerHourPotential'] !== 'number')
{
return Number.isInteger(Number(jsonObject['class1TraysPerHourPotential'])) ? Number(jsonObject['class1TraysPerHourPotential']) : Math.floor(Number(jsonObject['class1TraysPerHourPotential']));
}
return Number.isInteger(jsonObject['class1TraysPerHourPotential']) ? jsonObject['class1TraysPerHourPotential'] : Math.floor(jsonObject['class1TraysPerHourPotential']);
}());
}
if('class1TraysPerHourExcludingDowntime' in jsonObject)
{
model.class1TraysPerHourExcludingDowntime = (function(){
if(typeof jsonObject['class1TraysPerHourExcludingDowntime'] !== 'number')
{
return Number.isInteger(Number(jsonObject['class1TraysPerHourExcludingDowntime'])) ? Number(jsonObject['class1TraysPerHourExcludingDowntime']) : Math.floor(Number(jsonObject['class1TraysPerHourExcludingDowntime']));
}
return Number.isInteger(jsonObject['class1TraysPerHourExcludingDowntime']) ? jsonObject['class1TraysPerHourExcludingDowntime'] : Math.floor(jsonObject['class1TraysPerHourExcludingDowntime']);
}());
}
if('class1TraysPerManHourPotential' in jsonObject)
{
model.class1TraysPerManHourPotential = (function(){
if(jsonObject['class1TraysPerManHourPotential'] === null)
{
return null;
}
if(typeof jsonObject['class1TraysPerManHourPotential'] !== 'number')
{
return Number(jsonObject['class1TraysPerManHourPotential']);
}
return jsonObject['class1TraysPerManHourPotential'];
}());
}
if('class1TraysPerManHourExcludingDowntime' in jsonObject)
{
model.class1TraysPerManHourExcludingDowntime = (function(){
if(jsonObject['class1TraysPerManHourExcludingDowntime'] === null)
{
return null;
}
if(typeof jsonObject['class1TraysPerManHourExcludingDowntime'] !== 'number')
{
return Number(jsonObject['class1TraysPerManHourExcludingDowntime']);
}
return jsonObject['class1TraysPerManHourExcludingDowntime'];
}());
}
if('manningPercentage' in jsonObject)
{
model.manningPercentage = (function(){
if(jsonObject['manningPercentage'] === null)
{
return null;
}
if(typeof jsonObject['manningPercentage'] !== 'number')
{
return Number(jsonObject['manningPercentage']);
}
return jsonObject['manningPercentage'];
}());
}
if('totalManning' in jsonObject)
{
model.totalManning = (function(){
if(jsonObject['totalManning'] === null)
{
return null;
}
if(typeof jsonObject['totalManning'] !== 'number')
{
return Number.isInteger(Number(jsonObject['totalManning'])) ? Number(jsonObject['totalManning']) : Math.floor(Number(jsonObject['totalManning']));
}
return Number.isInteger(jsonObject['totalManning']) ? jsonObject['totalManning'] : Math.floor(jsonObject['totalManning']);
}());
}
if('uptimePercentage' in jsonObject)
{
model.uptimePercentage = (function(){
if(typeof jsonObject['uptimePercentage'] !== 'number')
{
return Number(jsonObject['uptimePercentage']);
}
return jsonObject['uptimePercentage'];
}());
}
if('downtimePercentage' in jsonObject)
{
model.downtimePercentage = (function(){
if(typeof jsonObject['downtimePercentage'] !== 'number')
{
return Number(jsonObject['downtimePercentage']);
}
return jsonObject['downtimePercentage'];
}());
}
if('deleted' in jsonObject)
{
model.deleted = (function(){
if(typeof jsonObject['deleted'] !== 'boolean')
{
return Boolean(jsonObject['deleted']);
}
return jsonObject['deleted'];
}());
}
if('updateTimestamp' in jsonObject)
{
model.updateTimestamp = (function(){
if(typeof jsonObject['updateTimestamp'] !== 'string')
{
return new Date(String(jsonObject['updateTimestamp']));
}
return new Date(jsonObject['updateTimestamp']);
}());
}
return model;
}
} |
JavaScript | class Domain {
// constants
//private static BASE_SERVICE_MODULE_NAME = "services";
//private static BASE_FACTORY_MODULE_NAME = "factories"
//private static BASE_REPOSITORY_MODULE_NAME = "repositories";
/**
* We keep the constructor private because Domain is a singleton.
*/
constructor() {
this.container = new verdic_1.VerdicContainer();
this._eventStream = new event_module_1.EventStream();
//this.createBaseSubmodulesForModule();
}
/**
* CreateModule()
*
* creates a new module.
* @param path The the path of the module to create.
*/
static CreateModule(path) {
Domain.instance().container.createModule(path);
//Domain.instance().createBaseSubmodulesForModule(path);
}
/**
* ContainsModule()
*
* determines if the module exists
* @param path The path of the module.
* @returns TRUE if the domain contains the module. FALSE otherwise.
*/
static ContainsModule(path) {
return Domain.instance().container.containsModule(path);
}
/**
* instance()
*
* instance() gets the instance of the context.
* @returns the instance of the context.
*/
static instance() {
if (!Domain._instance) {
Domain._instance = new Domain();
}
return Domain._instance;
}
/**
* EventStream()
*
* gets the domain event stream.
* @returns the event stream.
*/
static EventStream() {
return Domain.instance().eventStream();
}
/**
* Factory()
*
* Factory() gets the factory container at the specified module.
* @param modulePath The path of the module.
* @returns The container that contains the factories specified by the modules. If the modulePath is omitted,
* it defaults to the root module.
* @throws ModuleNotFoundException when the specified module could not be found.
* @throws InvalidModuleException when the module path is invalid.
*/
// public static Factory(modulePath: string = ''): VerdicContainer {
// const absolutePath = modulePath.length === 0 ? Domain.BASE_FACTORY_MODULE_NAME :`${modulePath}.${Domain.BASE_FACTORY_MODULE_NAME}`;
// return Domain.instance().container.module(absolutePath);
// }
/**
* Module()
*
* Module() gets a module specified by the path.
* @param path The path of the module.
* @returns the module specified by the path.
*/
static Module(path = "") {
if (path.length == 0) {
return Domain.instance().container;
}
else {
return Domain.instance().container.module(path);
}
}
/**
* PublishEvents()
*
* Publishes all the events in the event stream.
*/
static async PublishEvents() {
Domain.EventStream().publishEvents();
}
/**
* Repository()
*
* Repository() gets the repository container at the specified module. If modulePath is omitted,
* it defaults to the root container.
* @param modulePath the path to the module.
* @returns the container containing the repositories in the specified module.
* @throws ModuleNotFoundException when the specified module could not be found.
* @throws InvalidModuleException when the module path is invalid.
*/
// public static Repository(modulePath: string = ""): VerdicContainer {
// const absolutePath = modulePath.length === 0 ? Domain.BASE_REPOSITORY_MODULE_NAME : `${modulePath}.${Domain.BASE_REPOSITORY_MODULE_NAME}`;
// return Domain.instance().container.module(absolutePath);
// }
/**
* Service()
*
* Service() gets the service container at the specified module. If modulePath is omitted,
* it defaults to the root container.
* @param modulePath the path to the module.
* @returns the container containing the services in the specified module.
* @throws ModuleNotFoundException when the specified module could not be found.
* @throws InvalidModuleException when the module path is invalid.
*/
// public static Service(modulePath: string = ''): VerdicContainer {
// const absolutePath = modulePath.length === 0 ? Domain.BASE_SERVICE_MODULE_NAME : `${modulePath}.${Domain.BASE_SERVICE_MODULE_NAME}`;
// return Domain.instance().container.module(absolutePath);
// }
/**
* eventStream()
*
* eventStream() gets the event stream.
*/
eventStream() {
return this._eventStream;
}
} |
JavaScript | class Pin extends EventEmitter {
constructor({name, size = 1, value = 0}) {
super();
this._name = name;
if (size < 1 || size > WORD_SIZE) {
throw new Error(
`Invalid "size" for ${name} pin, should be ` +
`in 1-${WORD_SIZE} range.`
);
}
this._size = size;
this._maxAllowed = Math.pow(2, this._size) - 1;
this.setValue(value);
// There might be more than 11 pins (default in Node).
this.setMaxListeners(Infinity);
// The pins which listen to 'change' event of this pin.
this._listeningPinsMap = new Map();
// The pin which is connected to this pin, and provides source value.
this._sourcePin = null;
}
/**
* Returns name of this pin.
*/
getName() {
return this._name;
}
/**
* Returns size of this bus.
*/
getSize() {
return this._size;
}
/**
* Sets the value for this pin/bus.
*/
setValue(value) {
const oldValue = this._value;
if (typeof value === 'string') {
value = Number.parseInt(value, 2);
}
if (value > this._maxAllowed) {
throw new TypeError(
`Pin "${this.getName()}": value ${value} doesn't match pin's width. ` +
`Max allowed is ${this._maxAllowed} (size ${this._size}).`
);
}
this._value = int16(value);
this.emit('change', this._value, oldValue);
}
/**
* Returns value of this pin bus.
*/
getValue() {
return this._value;
}
/**
* Updates the value of a particular bit in this bus.
*/
setValueAt(index, value) {
this._checkIndex(index);
const oldValue = this._value;
// Always adjust to int16 on individual bits set
this._value = int16(setBitAt(this._value, index, value));
this.emit('change', this._value, oldValue, index);
}
/**
* Returns the value of a particular bit of this bus.
*/
getValueAt(index) {
this._checkIndex(index);
return getBitAt(this._value, index);
}
/**
* Returns range (sub-bus) of this bus.
*/
getRange(from, to) {
this._checkIndex(from);
this._checkIndex(to);
return getBitRange(this._value, from, to);
}
/**
* Sets a value of a range.
*
* Value: 0b1010
* Range: 0b101
* From: 0
* To: 2
*
* Result: 0b1101
*/
setRange(from, to, range) {
this._checkIndex(from);
this._checkIndex(to);
const oldValue = this._value;
this._value = setBitRange(this._value, from, to, range);
this.emit('change', this._value, oldValue, from, to);
}
/**
* Connects this pin to another one. The other pin
* then listens to the 'change' event of this pin.
*
* If the specs are passed, the values are updated according
* to these specs. E.g. {index: 3} spec updates a[3] bit,
* and {range: {from: 1, to: 3}} updates a[1..3].
*/
connectTo(pin, {sourceSpec = {}, destinationSpec = {}} = {}) {
if (this._listeningPinsMap.has(pin)) {
return;
}
const thisPinValueGetter = createPinValueGetter(this, sourceSpec);
const pinValueSetter = createPinValueSetter(pin, destinationSpec);
const listener = () => pinValueSetter(thisPinValueGetter());
const connectInfo = {
listener,
sourceSpec,
destinationSpec,
};
this._listeningPinsMap.set(pin, connectInfo);
pin._sourcePin = this;
this.on('change', listener);
return this;
}
/**
* Unplugs this pin from other pin.
*/
disconnectFrom(pin) {
if (!this._listeningPinsMap.has(pin)) {
return;
}
const {listener} = this._listeningPinsMap.get(pin);
this._listeningPinsMap.delete(pin);
pin._sourcePin = null;
this.removeListener('change', listener);
return this;
}
/**
* Returns listening pins map. The key is a pin, the
* value is a ConnectionInfo, which includes the listener
* function, and connection properties (index, range, etc).
*/
getListeningPinsMap() {
return this._listeningPinsMap;
}
/**
* Returns the pin which is a source value provider
* for this pin. Usually the source is set via `connectTo`
* method.
*/
getSourcePin() {
return this._sourcePin;
}
/**
* Builds a full name of a pin or pin bus:
*
* 'a' -> 'a'
* {name: 'a'} -> 'a'
* {name: 'a', size: 1} -> 'a'
* {name: 'a', size: 16} -> 'a[16]'
*/
static toFullName(name) {
// Simple string name from Spec.
if (typeof name === 'string') {
return name;
}
return name.size > 1 ? `${name.name}[${name.size}]` : name.name;
}
/**
* Checks the bounds of the index.
*/
_checkIndex(index) {
if (index < 0 || index > this._size - 1) {
throw new TypeError(
`Pin "${this.getName()}": out of bounds index ${index}, ` +
`while the size is ${this._size}.`
);
}
}
} |
JavaScript | class GameManager {
/**
* @param {number} player Player's checkers, default value is 2
* @param {number} AIplayer Which one (black or white) checkers the AI will be playing, default value is 1
*/
constructor(player = 2, AIplayer = 1) {
// Game board
this.gameBoard = new Board();
// Draw manager
this.drawManager = new DrawManger(this.gameBoard);
this.playerTurn = 2;
this.player = player;
// AI
this.AI = new AI(AIplayer);
};
/**
* Initializes by drawing the board and checkers
*/
Initialize() {
// Draw board
this.drawManager.DrawBoard();
};
/**
* Stops the game
*/
Stop() {
this.AI.Stop();
}
/**
* Called by 'click' event on tile, performs move action and moves selected checker
*/
Select() {
// Get all checkers with 'selected' class
let checkers = document.querySelectorAll('div.tile div.selected');
// If there's none then return
if (checkers.length === 0) {
return;
} else {
// Lets check if the player can move at all
let possible = gameManager.gameBoard.GetPossibleMoves(gameManager.gameBoard.GetAllEmptyTiles(),
gameManager.gameBoard.checkers.filter(checker => checker.player === gameManager.player));
if (possible[1].length === 0 || possible[0].length === 0) {
// If not then he loses
gameManager.EndTheGame(1);
return;
}
let tileId = this.getAttribute('id').replace('tile', '');
let tile = gameManager.gameBoard.tiles[tileId];
let checker = gameManager.gameBoard.checkers[checkers.item(0).getAttribute('id')];
// Is this in range?
let inRange = tile.InRange(checker);
if (inRange) {
gameManager.drawManager.RemoveMovedTilesHighlight();
// To check if we can do more than one jump
if (inRange === 2) {
if (checker.Attack(tile)) {
checker.Move(tile);
if (checker.CanMove()) {
checker.element.classList.add('selected');
} else {
setTimeout(() => {
gameManager.AI.TryToMove();
}, 1000);
gameManager.ChangePlayerTurn();
}
}
// Otherwise just move
} else if (inRange === 1) {
if (!checker.CanMove()) {
if (checker.Move(tile)) {
setTimeout(() => {
gameManager.AI.TryToMove();
}, 1000);
gameManager.ChangePlayerTurn();
}
}
}
}
}
};
/**
* Ends the game, logs and displays the winner
* @param {number} player Player who won
*/
EndTheGame(player) {
let messageText = 'Player ' + player + ' wins!';
Logger.Log(messageText);
let message = document.createElement('p');
if (player === 1) {
message.innerHTML = messageText;
} else {
message.innerHTML = 'Congratulations';
}
new Message(message, player === 1 ? 'You lose!' : 'You win!').ShowWithHeader();
// Stop the game
this.Stop();
}
/**
* Checks victory for both players and displays it if someone won
*/
CheckVictory() {
if (this.CheckIfAnyLeft(1)) {
this.EndTheGame(2);
} else if (this.CheckIfAnyLeft(2)) {
this.EndTheGame(1);
}
};
/**
* Checks if the player has any checkers left
* @param {number} player Player to check
* @returns {boolean} ture if the player lost
*/
CheckIfAnyLeft(player) {
let counter = 0;
for (let i = 0; i < this.gameBoard.boardSize; i++) {
if (!this.gameBoard.board[i].includes(player)) {
counter++;
}
}
if (counter === this.gameBoard.boardSize) {
return true;
} else {
return false;
}
};
/**
* Changes turn between players
*/
ChangePlayerTurn() {
if (this.playerTurn === 1) {
this.playerTurn = 2;
} else {
this.playerTurn = 1;
}
gameManager.CheckVictory();
};
} |
JavaScript | class FormLayout extends Component {
render() {
return (
<Layout.Content style={{ width: 700, margin: '0 auto' }}>
<Switch>
{/* Form Layout Routes */}
<Route exact path="/terms/new" component={CreateTerm} />
<Route exact path="/terms/:id/edit" component={EditTerm} />
<Route exact path="/events/new" component={CreateEvent} />
<Route exact path="/events/:id" component={ViewEvent} />
<Route exact path="/events/:id/edit" component={EditEvent} />
<Route exact path="/invite" component={Invite} />
{/* No Matching Route */}
<Route component={DeadEnd} />
</Switch>
</Layout.Content>
);
}
} |
JavaScript | class Mod {
/**
* Mod Target
* @type {string}
*/
#target;
/**
* List of mod objects
* @type Array<ItemResolvable>
*/
#mods;
/**
* @type {WorldStateClient}
*/
#ws;
constructor({ target, mods }, ws) {
this.#target = target;
this.#mods = mods?.flat()?.map((mod) => {
if (mod.uniqueName) return mod;
return ws.mod(mod);
});
this.#ws = ws;
}
serialize() {
return {
target: this.#target,
mods: this.#mods.flat().map(mod => mod.uniqueName).filter(m => m),
};
}
/**
* Get the list of mods
* @returns {Array<BuildResolvable>}
*/
get mods() {
return this.#mods;
}
/**
* Target
* @returns {string}
*/
get target() {
return this.#target;
}
} |
JavaScript | class NodeLinkView extends ComponentJSON{
constructor(props){
super(props);
this.objectType="nodelink";
this.objectClass=".node-link";
this.rerenderEvents = "ports-rendered."+this.props.data.id;
}
render(){
let data = this.props.data;
if(!this.source_node||!this.source_node.outerWidth()||!this.target_node||!this.target_node.outerWidth()){
this.source_node = $(this.props.node_div.current);
this.source_port_handle = d3.select(
"g.port-"+data.source_node+" circle[data-port-type='source'][data-port='"+Constants.port_keys[data.source_port]+"']"
);
this.target_node = $("#"+data.target_node+".node");
this.target_port_handle = d3.select(
"g.port-"+data.target_node+" circle[data-port-type='target'][data-port='"+Constants.port_keys[data.target_port]+"']"
);
this.source_node.on(this.rerenderEvents,this.rerender.bind(this));
this.target_node.on(this.rerenderEvents,this.rerender.bind(this));
}
var source_dims = {width:this.source_node.outerWidth(),height:this.source_node.outerHeight()};
var target_dims = {width:this.target_node.outerWidth(),height:this.target_node.outerHeight()};
if(!source_dims.width||!target_dims.width)return null;
var selector=this;
return(
<div>
{reactDom.createPortal(
<NodeLinkSVG source_port_handle={this.source_port_handle} source_port={data.source_port} target_port_handle={this.target_port_handle} target_port={data.target_port} clickFunction={(evt)=>this.props.renderer.selection_manager.changeSelection(evt,selector)} selected={this.state.selected} source_dimensions={source_dims} target_dimensions={target_dims}/>
,$(".workflow-canvas")[0])}
{this.addEditable(data)}
</div>
);
}
rerender(){
this.setState({});
}
componentWillUnmount(){
if(this.target_node&&this.target_node.length>0){
this.source_node.off(this.rerenderEvents);
this.target_node.off(this.rerenderEvents);
}
}
} |
JavaScript | class Dropdown extends Component {
static propTypes = {
/**
* Label for the dropdown. Try to keep this within 25 characters
*/
label: PropTypes.string,
/**
* List of options that will appear in the dropdown. Each option is represented by an object with the following shape
*/
options: PropTypes.arrayOf(PropTypes.shape({
/**
* An unique number representing the option.
*/
id: PropTypes.number.isRequired,
/**
* The number or string label for the option
*/
value: PropTypes.oneOfType([PropTypes.number,PropTypes.string]).isRequired,
/**
* Set `disabled` to `true` to disable selection of this option
*/
disabled: PropTypes.bool
})).isRequired,
/**
* Selected value. Must correspond to the type passed in the `value` property of objects in the options array. Remember to update this value when the `onChange` callback is fired.
*/
value: PropTypes.shape({
/**
* An unique number representing the option.
*/
id: PropTypes.number.isRequired,
/**
* The number or string label for the option
*/
value: PropTypes.oneOfType([PropTypes.number,PropTypes.string]).isRequired,
}),
/**
* Callback fired when the user selects a new option on the dropdown. The callback takes the form of
* `callback(value)`
* where `value` is an object with the keys `id` and `value`
*
* __Remember to update the `value` prop everytime this callback is fired__
*/
onChange: PropTypes.func,
/**
* Set this boolean to disable the dropdown component completely
*/
disabled: PropTypes.bool,
/**
* The `onMouseEnter` callback is fired when the mouse is moved over the button. Mouse event is passed as a param.
*/
onMouseEnter: PropTypes.func,
/**
* The `onMouseLeave` callback is fired when the mouse is moved out of the buttons hit area. Mouse event is passed as a param.
*/
onMouseLeave: PropTypes.func,
/**
* Callback for user focus event. Mouse event is passed as a param.
*/
onFocus: PropTypes.func,
/**
* Callback for loss of focus from the component. Mouse event is passed as a param.
*/
onBlur: PropTypes.func,
/**
* Prop used to render mini version of dropdown inside datepicker component. NOT FOR EXTERNAL USE
* @ignore
*/
mini: PropTypes.bool,
}
constructor(props) {
super(props)
this.state = {
open: false
};
this.clickHandler = this.clickHandler.bind(this)
this.blurHandler = this.blurHandler.bind(this)
this.optionClickHandler = this.optionClickHandler.bind(this)
}
componentDidUpdate(prevProps, prevState) {
}
clickHandler(e) {
this.setState({open: !this.state.open})
}
optionClickHandler(value) {
if(!value.disabled && !this.props.disabled) {
this.setState({open:false})
if(this.props.onChange instanceof Function) this.props.onChange(value)
}
}
blurHandler(e) {
if(this.state.open) {
this.setState({open: false})
}
if(this.props.onBlur instanceof Function) this.props.onBlur(e)
e.stopPropagation()
e.preventDefault()
}
render() {
const {
label,
value,
options,
disabled,
mini
} = this.props
const optionsList = options.map((option, key) =>
<li key={option.id?option.id:key} onClick={() => this.optionClickHandler(option)} className={option.disabled?styles.disabled:''}>
<div className={styles.list_bg}></div>
<div className={styles.option_label}>{option.value}</div>
</li>
)
return (
<div
className={mini?styles.mini_dropdown_container:styles.dropdown_container}
onMouseEnter={this.props.onMouseEnter}
onMouseLeave={this.props.onMouseLeave}
onFocus={this.props.onFocus}
onBlur={this.blurHandler}
tabIndex={disabled?"":"0"}>
<div className={value?styles.focus_label:styles.float_label}>{label}</div>
<div className={this.state.open?styles.open_list:styles.list}>
<div className={this.state.open?styles.open_header:(disabled?styles.disabled_header:styles.header)} onClick={this.clickHandler}>
{value?'':label}
<div className={styles.selected_option}>{value?value.value:''}</div>
<img className={styles.arrow} src={DropdownSVG} />
</div>
<ul className={styles.options}>
{optionsList}
</ul>
</div>
</div>
)
}
} |
JavaScript | class CardValidator {
/**
* Check if control contains numbers only
* @param {?} abstractCtrl
* @return {?}
*/
static numbersOnly(abstractCtrl) {
/** @type {?} */
const ccNum = abstractCtrl.value;
/** @type {?} */
const NUMBERS_ONLY = new RegExp(/^[0-9]+$/);
return !NUMBERS_ONLY.test(ccNum) ? CardValidator.NUMBERS_ONLY_ERR : null;
}
/**
* Check checksum number in card number using Luhn algorithm
* @param {?} abstractCtr
* @return {?}
*/
static checksum(abstractCtr) {
/** @type {?} */
const ccNumber = abstractCtr.value;
/** @type {?} */
const luhnArray = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
/** @type {?} */
let length = ccNumber ? ccNumber.length : 0;
/** @type {?} */
let sum = 0;
/** @type {?} */
let shouldMultiply = true;
while (length) {
/** @type {?} */
const val = parseInt(ccNumber.charAt(--length), 10);
sum += (shouldMultiply = !shouldMultiply) ? luhnArray[val] : val;
}
return !(sum && sum % 10 === 0) ? CardValidator.CHECKSUM_INVALID : null;
}
/**
* Check validity of the card
* @param {?} formGroup
* @return {?}
*/
static expiration(formGroup) {
/** @type {?} */
const expirationMonth = Number(formGroup.get('expirationMonth').value);
/** @type {?} */
const expirationYear = Number(formGroup.get('expirationYear').value);
/** @type {?} */
const expirationDate = new Date(expirationYear, expirationMonth + 1, 0);
return new Date().getTime() > expirationDate.getTime() ? CardValidator.CARD_EXPIRED : null;
}
} |
JavaScript | class File {
/**
* Constructor
*
* @param {string} fileType Type of file
* @param {any[]} fileParts Parts to include in file blob
*/
constructor(fileType, fileParts) {
// Bindings
this.download = this.download.bind(this);
this.downloadViaApi = this.downloadViaApi.bind(this);
this.onChangedListener = this.onChangedListener.bind(this);
// Init
this.url = '';
this.blobId = undefined;
this.downloadError = 'File: File Could not download file';
this.filenameRequiredError = 'File: Filename is required';
this.apiUnavailableError = 'File: Extension Download API Unavailable';
this.NoDownloadableFileError = 'File: Could Not Create Downloadable Object';
this.blob = new Blob(fileParts, { type: fileType });
}
/**
* Download the file
*
* @param {string} filename Name for file
* @returns {Promise<void>} Resolves after cleanup has completed
*/
download(filename) {
if (!filename) {
debug(this.filenameRequiredError);
return Promise.reject(new Error(this.filenameRequiredError));
}
debug(`File: initiating download of ${filename}`);
return new Promise((resolve, reject) => {
if (chrome && chrome.downloads) {
this.url = URL.createObjectURL(this.blob);
return this.downloadViaApi(this.url, filename);
}
debug(this.apiUnavailableError);
return reject(new Error(this.apiUnavailableError));
});
}
/**
* Download via the extension API (requires permissions in manifest)
*
* @param {string} filename Name of file
* @param {string} url Url for file
* @param {function} resolve Promise resolution function
* @returns {void}
*/
downloadViaApi(url, filename) {
if (!url) {
debug(this.NoDownloadableFileError);
return Promise.reject(new Error(this.NoDownloadableFileError));
}
const { downloads } = chrome;
const { download } = downloads;
// handle revoking object url here
downloads.onChanged.addListener(this.onChangedListener);
return new Promise((resolve) => {
download({ url, filename, conflictAction: 'uniquify' },
(id) => {
if (id) {
this.blobId = id;
return resolve(id);
}
// if id is undefined, then download failed
downloads.onChanged.removeListener(this.onChangedListener);
throw new Error(this.downloadError);
});
});
}
/**
* OnChanged listener that reports the state of the download item
*
* @param {object} delta The delta of download item
* @returns undefined
*/
onChangedListener(delta) {
const hasId = this.blobId && this.blobId === delta.id;
const isComplete = delta.state && delta.state.current === 'complete';
if (hasId && isComplete) {
URL.revokeObjectURL(this.url);
chrome.downloads.onChanged.removeListener(this.onChangedListener);
}
}
} |
JavaScript | class Hoverable extends Component {
constructor(props) {
super(props);
this.state = {
isHovered: false,
};
this.toggleHoverState = this.toggleHoverState.bind(this);
}
/**
* Toggles the hover state of this component and executes the callback provided in props for that state transition.
*/
toggleHoverState() {
if (this.state.isHovered) {
this.props.onHoverOut();
this.setState({isHovered: false});
} else {
this.props.onHoverIn();
this.setState({isHovered: true});
}
}
render() {
return (
<View
onMouseEnter={this.toggleHoverState}
onMouseLeave={this.toggleHoverState}
>
{ // If this.props.children is a function, call it to provide the hover state to the children.
_.isFunction(this.props.children)
? this.props.children(this.state.isHovered)
: this.props.children
}
</View>
);
}
} |
JavaScript | class AbstractAPIController extends AbstractAppController {
/**
* @param {import('gmf/controllers/AbstractAppController.js').Config} config A part of the application
* @param {angular.IScope} $scope Scope.
* @param {angular.auto.IInjectorService} $injector Main injector.
* @ngInject
*/
constructor(config, $scope, $injector) {
const viewConfig = {
projection: getProjection(`EPSG:${config.srid || 2056}`),
};
Object.assign(viewConfig, config.mapViewConfig || {});
const scaleline = document.getElementById('scaleline');
if (!scaleline) {
throw new Error('Missing scaleline');
}
const map = new olMap({
pixelRatio: config.mapPixelRatio,
layers: [],
view: new olView(viewConfig),
controls: config.mapControls || [
new olControlScaleLine({
target: scaleline,
}),
new olControlZoom({
target: 'ol-zoom-control',
zoomInTipLabel: '',
zoomOutTipLabel: '',
}),
new olControlRotate({
label: getLocationIcon(),
tipLabel: '',
}),
],
interactions:
config.mapInteractions ||
interactionsDefaults({
pinchRotate: true,
altShiftDragRotate: true,
}),
});
map.addInteraction(
new olInteractionDragPan({
condition: dragPanCondition,
})
);
super(config, map, $scope, $injector);
}
} |
JavaScript | class AsyncTestCompleter {
constructor() {
this._completer = new PromiseCompleter();
}
done(value) { this._completer.resolve(value); }
fail(error, stackTrace) { this._completer.reject(error, stackTrace); }
get promise() { return this._completer.promise; }
} |
JavaScript | class TheStrangeAlien extends CustomCypherSheet {
/** @override */
static get defaultOptions() {
return foundry.utils.mergeObject(super.defaultOptions, {
template: "modules/cyphersheets/templates/thestrange/thestrange-alien.html"
});
}
} |
JavaScript | class PydioResponse {
/**
* Constructs a new <code>PydioResponse</code>.
* Generic container for messages after successful operations or errors
* @alias module:model/PydioResponse
* @class
*/
constructor() {
}
/**
* Constructs a <code>PydioResponse</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/PydioResponse} obj Optional instance to populate.
* @return {module:model/PydioResponse} The populated <code>PydioResponse</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PydioResponse();
if (data.hasOwnProperty('message')) {
obj['message'] = ApiClient.convertToType(data['message'], 'String');
}
if (data.hasOwnProperty('level')) {
obj['level'] = ApiClient.convertToType(data['level'], 'String');
}
if (data.hasOwnProperty('errorCode')) {
obj['errorCode'] = ApiClient.convertToType(data['errorCode'], 'Number');
}
if (data.hasOwnProperty('nodesDiff')) {
obj['nodesDiff'] = NodesDiff.constructFromObject(data['nodesDiff']);
}
if (data.hasOwnProperty('bgAction')) {
obj['bgAction'] = BgAction.constructFromObject(data['bgAction']);
}
if (data.hasOwnProperty('tasks')) {
obj['tasks'] = ApiClient.convertToType(data['tasks'], [Task]);
}
}
return obj;
}
/**
* @member {String} message
*/
message = undefined;
/**
* @member {String} level
*/
level = undefined;
/**
* @member {Number} errorCode
*/
errorCode = undefined;
/**
* @member {module:model/NodesDiff} nodesDiff
*/
nodesDiff = undefined;
/**
* @member {module:model/BgAction} bgAction
*/
bgAction = undefined;
/**
* @member {Array.<module:model/Task>} tasks
*/
tasks = undefined;
} |
JavaScript | class QueryManager {
constructor(_world) {
this._world = _world;
this._queries = {};
}
/**
* Adds a query to the manager and populates with any entities that match
* @param query
*/
_addQuery(query) {
this._queries[buildTypeKey(query.types)] = query;
for (const entity of this._world.entityManager.entities) {
query.addEntity(entity);
}
}
/**
* Removes the query if there are no observers left
* @param query
*/
maybeRemoveQuery(query) {
if (query.observers.length === 0) {
query.clear();
delete this._queries[buildTypeKey(query.types)];
}
}
/**
* Adds the entity to any matching query in the query manage
* @param entity
*/
addEntity(entity) {
for (const queryType in this._queries) {
if (this._queries[queryType]) {
this._queries[queryType].addEntity(entity);
}
}
}
/**
* Removes an entity from queries if the removed component disqualifies it
* @param entity
* @param component
*/
removeComponent(entity, component) {
for (const queryType in this._queries) {
if (this._queries[queryType].matches(entity.types.concat([component.type]))) {
this._queries[queryType].removeEntity(entity);
}
}
}
/**
* Removes an entity from all queries it is currently a part of
* @param entity
*/
removeEntity(entity) {
for (const queryType in this._queries) {
this._queries[queryType].removeEntity(entity);
}
}
/**
* Creates a populated query and returns, if the query already exists that will be returned instead of a new instance
* @param types
*/
createQuery(types) {
const maybeExistingQuery = this.getQuery(types);
if (maybeExistingQuery) {
return maybeExistingQuery;
}
const query = new Query(types);
this._addQuery(query);
return query;
}
/**
* Retrieves an existing query by types if it exists otherwise returns null
* @param types
*/
getQuery(types) {
const key = buildTypeKey(types);
if (this._queries[key]) {
return this._queries[key];
}
return null;
}
} |
JavaScript | class ItemSearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
search: '',
};
}
/**
* renders search bar
*
* @return rendered search bar
*/
render() {
return (
<View style={styles.container}>
<SearchBar
platform="android"
placeholder="Grocery Item Name Here"
onChangeText={search => this.setState({ search })}
value={this.state.search}
onSubmitEditing={() => this.props.onSearch(this.state.search)}
containerStyle={styles.input}
/>
<Button
raised
icon={<Ionicons name="ios-camera" size={24} color="white" />}
onPress={this.props.onPressCamera}
containerStyle={styles.scanbutton}
/>
</View>
);
}
} |
JavaScript | class Character extends React.Component {
/**
* Affiche les propriétée reçues par le parent, et sinon, celles stockées en local (si l'utilisateur recharge la page, il ne perd pas le résultat)
*/
render() {
const {stats} = {...this.props};
return (
<div className="character">
<Card style={{ width: '18rem' }}>
<Card.Title>Vous êtes désormais:</Card.Title>
<Card.Body>
<Card.Img variant="top" src={stats.avatar || localStorage["avatar"]} />
<ul>
{Object.keys(stats).map((e, i) =>
!Boolean(e.match(/(id|type|avatar)/gi)) && (<li key = {i}>{`${e.charAt(0).toUpperCase() + e.slice(1)}: ${stats[e] || localStorage[e]}`}</li>)
)}
</ul>
</Card.Body>
</Card>
</div>
)
}
} |
JavaScript | class Utilities {
/**
* @param {string} camelCase
* @return {string}
*/
static sentenceCaseFromCamelCase(camelCase) {
if (!camelCase) return '';
const result = camelCase.replace(/([A-Z])/g, " $1");
return result.trim();
}
/**
* @param {Date} date
* @return {string}
*/
static displayDate(date) {
if (!date) return '';
return date.toLocaleDateString();
}
/**
* @param {Date} date
* @return {string}
*/
static displayTime(date) {
if (!date) return '';
return date.toLocaleTimeString();
}
/**
* @param {Date} date
* @return {string}
*/
static displayDateTime(date) {
if (!date) return '';
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
}
/**
* @param {File} file
* @param {function} callback
* @param {function} errorCallback
*/
static base64DataFromFile(file, callback, errorCallback) {
// Setup
const reader = new FileReader();
reader.onload = () => {
const base64Data = reader.result.substring(reader.result.indexOf(',') + 1);
callback(base64Data);
};
reader.onerror = error => {
console.log(error);
errorCallback(error);
};
// Go
reader.readAsDataURL(file);
}
/**
* This will ALWAYS return an array, but it may be blank
*
* This will preform TRIM on all lines of the string, rejecting anything of 0 length
*
* @param {string} text
* @return {string[]}
*/
static getLineArray(text) {
const returnArray = [];
if (!text) return returnArray;
text.trim().split("\n").forEach(line => {
if (line.trim().length) {
returnArray.push(line.trim());
}
});
return returnArray;
}
/**
* Given a standard string with linebreaks, this will return React Elements
* that can be rendered which will include those same linebreaks.
*
* @param {string} text
* @return {React.Fragment[]}
*/
static renderTextBlock(text) {
if (!text) return null;
const lineArray = [];
text.trim().split("\n").forEach(line => {
lineArray.push(line.trim());
});
return lineArray.map((value, index) => {
if (index !== (lineArray.length - 1)) {
return (
<React.Fragment key={"text-block-" + index}>
{value}
<br/>
</React.Fragment>
);
} else {
return (
<React.Fragment key={"text-block-" + index}>
{value}
</React.Fragment>
);
}
});
}
/**
* Given any partial phone text, it will parse to xxx-xxx-xxxx (or a partial version of it)
* @param {string} text
* @return {string}
*/
static parsePhone(text) {
if (!text) return '';
text = text.replace(/\D/g, '');
if (text.length > 10) {
text = text.substring(0, 10);
}
if (text.length >= 6) {
return text.replace(/^(\d{3})(\d{3})/, "$1-$2-");
}
if (text.length >= 3) {
return text.replace(/^(\d{3})/, "$1-");
}
return text;
}
} |
JavaScript | class CommandHandler {
constructor() {
this.commands = [];
this.chineseCommands = [];
}
async init(isReload) {
console.log(`${Tools.showdownText()}${isReload ? "Rel" : "L"}oading commands...`);
await Promise.all([
this.loadDirectory(COMMANDS_DIRECTORY, Commands.ShowdownCommand, "Bot", isReload),
this.loadDirectory(CHINESE_COMMANDS_DIRECTORY, Commands.ChineseCommand, "Chinese", isReload),
this.loadDirectory(DEV_COMMANDS_DIRECTORY, Commands.DevCommand, "Dev", isReload),
this.loadDirectory(DEX_COMMANDS_DIRECTORY, Commands.DexCommand, "Dex", isReload),
this.loadDirectory(PRIVATE_COMMANDS_DIRECTORY, Commands.PrivateCommand, "Private", isReload),
]);
for (let i = 0; i < this.chineseCommands.length; i++) {
for (let j = 0; j < this.chineseCommands.length; j++) {
if (i === j || this.chineseCommands[j].commandType === "ChineseCommand" || this.chineseCommands[i].name !== this.chineseCommands[j].name) continue;
this.chineseCommands.splice(j, 1);
}
}
}
loadDirectory(directory, Command, type, isReload) {
console.log(`${Tools.showdownText()}${isReload ? "Rel" : "L"}oading ${type.cyan} commands...`);
return new Promise((resolve, reject) => {
fs.readdir(directory, (err, files) => {
if (err) {
reject(`Error reading commands directory: ${err}`);
} else if (!files) {
reject(`No files in directory ${directory}`);
} else {
for (let name of files) {
if (name.endsWith(".js")) {
try {
name = name.slice(0, -3); // remove extention
const command = new Command(name, require(`${directory}/${name}.js`));
if (command.commandType !== "ChineseCommand") this.commands.push(command);
this.chineseCommands.push(command);
/*fs.readdir(databaseDirectory, (err, dbs) => {
for (let id of dbs) {
if (id.endsWith(".json")) {
id = id.slice(0, -5); // remove extention
if (client.guilds.cache.get(id) !== undefined) {
utilities.populateDb(id, name, type);
}
}
}
});*/
if (!(isReload)) console.log(`${Tools.showdownText()}${isReload ? "Rel" : "L"}oaded command ${type === "Private" ? (`${name.charAt(0)}*****`).green : name.green}`);
} catch (e) {
console.log(`${Tools.showdownText()}${"CommandHandler loadDirectory() error: ".brightRed}${e} while parsing ${name.yellow}${".js".yellow} in ${directory}`);
console.log(e.stack);
}
}
}
console.log(`${Tools.showdownText()}${type.cyan} commands ${isReload ? "rel" : "l"}oaded!`);
resolve();
}
});
});
}
get(name, list) {
const commandsList = list ? list : this.commands;
for (const command of commandsList) {
if ([command.name, ...command.aliases].includes(Tools.toId(name))) return command;
}
throw new Error(`commandHandler error: Command "${name}" not found!`);
}
async executeCommand(message, room, user, time) {
let passDex = Dex;
message = message.substr(1); // Remove command character
const spaceIndex = message.indexOf(" ");
let args = [];
let cmd = "";
if (spaceIndex !== -1) {
cmd = message.substr(0, spaceIndex);
args = message.substr(spaceIndex + 1).split(",");
} else {
cmd = message;
}
const commandsList = room.id === "chinese" ? this.chineseCommands : this.commands;
for (let i = 0; i < commandsList.length; i++) {
const command = commandsList[i];
if (command.trigger(cmd)) {
// Permissions checking
if (!user.isDeveloper()) {
if (command.developerOnly) return user.say("You do not have permission to use this command!");
if (command.roomRank && !(user.hasRoomRank(room, command.roomRank) || user.hasGlobalRank(command.roomRank))) return user.say(`You do not have permission to use \`\`${psConfig.commandCharacter}${command.name}\`\` in <<${room.id}>>.`);
if (command.globalRank && !user.hasGlobalRank(command.globalRank)) return user.say(`You do not have permission to use \`\`${psConfig.commandCharacter}${command.name}\`\` in <<${room.id}>>.`);
if (command.rooms && !command.rooms.includes(room.id)) return;
if (command.noPm && room.isPm()) return user.say(`\`\`${psConfig.commandCharacter}${command.name}\`\` is not available in PMs!`);
if (command.pmOnly && !room.isPm()) return user.say(`\`\`${psConfig.commandCharacter}${command.name}\`\` is only available in PMs!`);
}
if (command.commandType === "DexCommand") {
for (let i = 0; i < args.length; i++) {
if (["lgpe", "gen7", "gen6", "gen5", "gen4", "gen3", "gen2", "gen1", "usum", "sm", "oras", "xy", "bw2", "bw", "hgss", "dppt", "adv", "rse", "frlg", "gsc", "rby"].includes(Tools.toId(args[i]))) {
switch (Tools.toId(args[i])) {
case "lgpe":
passDex = Dex.mod("lgpe");
break;
case "gen7":
case "usum":
case "sm":
passDex = Dex.mod("gen7");
break;
case "gen6":
case "oras":
case "xy":
passDex = Dex.mod("gen6");
break;
case "gen5":
case "bw2":
case "bw":
passDex = Dex.mod("gen5");
break;
case "gen4":
case "hgss":
case "dppt":
passDex = Dex.mod("gen4");
break;
case "gen3":
case "adv":
case "rse":
case "frlg":
passDex = Dex.mod("gen3");
break;
case "gen2":
case "gsc":
passDex = Dex.mod("gen2");
break;
case "gen1":
case "rby":
case "rbyg":
passDex = Dex.mod("gen1");
break;
default:
passDex = Dex.mod("gen7");
}
args.splice(i, 1);
break;
}
}
}
const hrStart = process.hrtime();
console.log(`${Tools.showdownText()}Executing command: ${command.name.cyan}`);
try {
if (command.commandType === "DexCommand") {
await command.execute(args, room, user, passDex);
} else {
await command.execute(args, room, user);
}
} catch (e) {
let stack = e.stack;
stack += "Additional information:\n";
stack += `Command = ${command.name}\n`;
stack += `Args = ${args}\n`;
stack += `Time = ${new Date(time).toLocaleString()}\n`;
stack += `User = ${user.name}\n`;
stack += `Room = ${room instanceof psUsers.User ? "in PM" : room.id}`;
console.log(stack);
}
const hrEnd = process.hrtime(hrStart);
const timeString = hrEnd[0] > 3 ? `${hrEnd[0]}s ${hrEnd[1]}ms`.brightRed : `${hrEnd[0]}s ${hrEnd[1]}ms`.grey;
console.log(`${Tools.showdownText()}Executed command: ${command.name.green} in ${timeString}`);
}
}
}
helpCommand(message, room, user, time) {
const hrStart = process.hrtime();
const commandsList = room.id === "chinese" ? this.chineseCommands : this.commands;
console.log(`${Tools.showdownText()}Executing command: ${"help".cyan}`);
const botCommands = [];
const devCommands = [];
const dexCommands = [];
let sendMsg = [];
if (!(message.trim().includes(" "))) {
user.say(`List of commands; use \`\`${psConfig.commandCharacter}help <command name>\`\` for more information:`);
for (let i = 0; i < commandsList.length; i++) {
const command = commandsList[i];
if (!command.disabled && command.commandType !== "PrivateCommand") {
const cmdText = `${psConfig.commandCharacter}${command.name}${command.desc ? ` - ${command.desc}` : ""}`;
switch (command.commandType) {
case "BotCommand":
botCommands.push(cmdText);
break;
case "DevCommand":
devCommands.push(cmdText);
break;
case "DexCommand":
dexCommands.push(cmdText);
break;
}
}
}
const hrEnd = process.hrtime(hrStart);
const timeString = hrEnd[0] > 3 ? `${hrEnd[0]}s ${hrEnd[1]}ms`.brightRed : `${hrEnd[0]}s ${hrEnd[1]}ms`.grey;
console.log(`${Tools.showdownText()}Executed command: ${"help".green} in ${timeString}`);
if (botCommands.length > 0) {
user.say("**Bot commands**");
for (const line of botCommands) user.say(line);
}
if (devCommands.length > 0) {
user.say("**Dev Commands**");
for (const line of devCommands) user.say(line);
}
if (dexCommands.length > 0) {
user.say("**Dex Commands**");
for (const line of dexCommands) user.say(line);
}
return true;
}
const lookup = Tools.toId(message.split(" ")[1]);
let command;
let matched = false;
console.log(commandsList);
for (let i = 0; i < commandsList.length; i++) {
if (matched) break;
command = commandsList[i];
if (command.name === lookup || (command.aliases && command.aliases.includes(lookup))) matched = true;
}
if (!matched) return user.say(`No command "${lookup}" found!`);
sendMsg = [
`Help for: ${command.name}`,
`Usage: \`\`${psConfig.commandCharacter}${command.name}${command.usage.length > 0 ? ` ${command.usage}` : ""}\`\``,
`Description: ${command.longDesc}`,
`${command.aliases.length > 0 ? `Aliases: ${command.aliases.join(", ")}` : ""}`,
];
if (command.options) {
for (let i = 0; i < command.options.length; i++) {
sendMsg.push(`${command.options[i].toString()}: ${command.options[i].desc}`);
}
}
const hrEnd = process.hrtime(hrStart);
const timeString = hrEnd[0] > 3 ? `${hrEnd[0]}s ${hrEnd[1]}ms`.brightRed : `${hrEnd[0]}s ${hrEnd[1]}ms`.grey;
console.log(`${Tools.showdownText()}Executed command: ${"help".green} in ${timeString}`);
for (const line of sendMsg) user.say(line);
return;
}
} |
JavaScript | class Checks {
static _classInit(){
this.resetTypes()
this.resetChecks()
}
/** Add custom type to config */
static addType(name, config){
this.types[name] = config
return this
}
/** Add custom type to config */
static addCheck(name, config){
this.all[name] = config
return this
}
/** Reset all types back to source */
static resetTypes(){
this.types = this.loadCheckConfig(check_types)
return this
}
/** Reset all checks back to source */
static resetChecks(){
this.all = this.loadCheckConfig(check_strings, check_numbers, check_things)
return this
}
static loadCheckConfig(...classes){
let checks = reduce(classes, (acc, cls) => {
debug('loading cls', cls.name)
return assign(acc, cls)
}, {})
forEach(checks, (check) => {
if ( typeof check.message === 'string' ){
check.messageFn = this.compileObjectTemplate(check.message)
}
})
debug('checks loaded: %s', Object.keys(checks).length)
return checks
}
/**
* If you have a common template string that is replaced a
* lot, compile it first to remove some of the repeated string
* processing.
* @param {string} str - Template string to compile `a {{param}} replacer`
* @param {object} options - Options
* @param {RegExp} options.re - Regular Expression for the param tags to be replaced
* @returns {function} Templating function
*/
static compileObjectTemplate( str, options = {} ){
let re = options.re || /({{(\w+?)}})/ //Note the two capture groups.
let arr = str.split(re)
let end = arr.length
let return_arr = new Array(arr.length)
let templateCompiledObject = (arr.length === 1)
? function templateCompiledObject(){ return str }
: function templateCompiledObject( params ){
for ( let i = 0; i < end; i+=3 ){
return_arr[i] = arr[i]
let p = params[arr[i+2]]
if ( p === undefined ) p = arr[i+1] // Leave {{param}} in there
return_arr[i+1] = p // 1600k
}
return return_arr.join('')
}
templateCompiledObject.string = str
return templateCompiledObject
}
} |
JavaScript | class UserError extends ApolloError {
constructor(message, properties = null) {
super(message, 'USER_ERROR', properties);
}
} |
JavaScript | class Api {
/**
* Performs a GET request
*
* @route: String
* @params: Object
*
* @return: Object
**/
static async get({ route = null, params = {} }, { single } = false) {
Console.message({
type: 'log',
title: `Performing GET request ${params && 'with the below parameters'}`,
result: params
})
try {
let {
data,
success
} = await this.request(route, { params }, { method: 'GET' }, single)
if (success) return data
} catch (error) {
Console.message({
type: 'error',
title: `Failed to perform GET request`,
result: error
})
}
}
/**
* Performs a POST request
*
* @route: String
* @params: Object
*
* @return: Object
**/
static async post({ route = null, params = {} }, { single } = false) {
Console.message({
type: 'log',
title: `Performing POST request ${params && 'with the below parameters'}`,
result: params
})
try {
let {
data,
success
} = await this.request(route, { params }, { method: 'POST' }, single)
if (success) return data
} catch (error) {
Console.message({
type: 'error',
title: `Failed to perform POST request`,
result: error
})
}
}
/**
* Submit a request to an endpoint
*
* @route: String
* @params: Object
* @verb: String
*
* @return: Object
**/
static async request(route = null, { params = {} }, { method = '' }, single = false) {
Console.message({
type: 'log',
title: 'Is this a single result set that we need returned from the request?',
result: single ? 'Yes' : 'No'
})
let uri = `${this.endpoint}${route ? `/${route}` : ''}`
let endpoint = this.modifyApiQueryEndpoint(uri, params)
// Modifiy the endpoint if its a single object being called
// from an ID. example {category}/{ID}
// This is for the RMS API but needs to have a cleaner solution
if (single) endpoint = `${uri}/${params.id}`
let response = await fetch(endpoint, { ...this.headers, method })
let result = await response.json()
Console.message({
type: 'log',
title: 'Requested endpoint below',
result: endpoint
})
Console.message({
type: 'log',
title: 'Endpoint responed with',
result: result
})
return result
}
/**
* Modifies the query endpoint before
* a request for data is performed
*
* @url: String
* @params: Object
*
* @return: String
**/
static modifyApiQueryEndpoint(url = false, params = {}) {
if (url && typeof params === 'object') {
let output = `${url}?`
Object.keys(params).map((value, key, object) => {
return output += `${value}=${params[value]}${object.length && '&'}`
})
return output.replace(/&$/, "")
}
return null
}
} |
JavaScript | class ToggleButton extends PureComponent {
componentWillMount() {
this.labelID = uuid();
this.uniqueID = uuid();
}
onToggle = () => {
const { isChecked, onChange } = this.props;
onChange(!isChecked);
};
render() {
const { className, children, nodeOn, nodeOff, isChecked } = this.props;
const classNameComposed = [styles.toggleButton, className].join(' ');
return (
<div className={classNameComposed}>
<If expression={!!children}>
<label id={this.labelID} htmlFor={this.uniqueID}>
{children}
</label>
</If>
<button
id={this.uniqueID}
aria-labelledby={this.labelID}
aria-checked={isChecked}
role="switch"
onClick={this.onToggle}
title={isChecked ? nodeOn : nodeOff}
/>
</div>
);
}
} |
JavaScript | class TerminalManager {
constructor () {
this.instances = new Map();
}
/**
* Try to get the instance for the given
*
* @param {string|number} key of the instance
* @returns {Terminal|undefined} instance for the key
* @memberof TerminalManager
*/
get(key) {
debug(`get(${key})`);
return this.instances.get(key);
}
/**
* Set a new instance for the given key
*
* @param {string|number} key of the instance
* @param {Terminal} instance to use as a value
* @returns {void}
* @memberof TerminalManager
*/
set(key, instance) {
this.instances.set(key, instance);
}
/**
* Checks if the manager holds currently a value for the given key.
*
* @param {string|number} key to check
* @returns {boolean} true if the key exists
* @memberof TerminalManager
*/
has(key) {
return this.instances.has(key);
}
/**
* Removes the instance for the given key.
* If the given instance has an destroy method, it will be called.
*
* @param {string|number} key to remove
* @returns {boolean} true if there was an instance
* @memberof TerminalManager
*/
remove(key) {
const term = this.instances.get(key);
// Destroy the term if it still exists
if (term != null && isFunction(term.destroy)) {
term.destroy();
}
return this.instances.delete(key);
}
} |
JavaScript | class DynamicHeader extends Component {
state = {
normal: false, // only affects the dark header
};
handleScroll = () => {
if (window.scrollY > 300 && !this.state.normal) {
this.setState({ normal: true });
} else if (window.scrollY < 300 && this.state.normal) {
this.setState({ normal: false });
}
};
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleScroll);
}
render() {
const headerComp = <Header {...this.props} />;
// Dark header which transitions to normal after scrolling 300px
const darkHeader = (
<div
className={this.state.normal ? "header-wrapper" : "header-wrapper dark"}
>
{headerComp}
</div>
);
// default header
const defaultHeader = (
<div className="header-wrapper default">{headerComp}</div>
);
return (
<Switch>
<Route exact path="/:path(movie|tv)/:id" render={() => darkHeader} />
<Route render={() => defaultHeader} />
</Switch>
);
}
} |
JavaScript | class Factory {
/** @param {string} method @return {function} */
extract (method) {
return this[`${method}`]
}
} |
JavaScript | class TimelinePeriodLabels extends React.PureComponent {
findOptimalDurationFit(period, { durationMsPerPixel }) {
const minimalDurationMs = durationMsPerPixel * 1.1 * MIN_TICK_SPACING_PX;
return find(
TICK_SETTINGS_PER_PERIOD[period].periodIntervals,
p => moment.duration(p, period).asMilliseconds() >= minimalDurationMs
);
}
getTicksForPeriod(period, timelineTransform) {
// First find the optimal duration between the ticks - if no satisfactory
// duration could be found, don't render any ticks for the given period.
const { parentPeriod } = TICK_SETTINGS_PER_PERIOD[period];
const periodInterval = this.findOptimalDurationFit(
period,
timelineTransform
);
if (!periodInterval) return [];
// Get the boundary values for the displayed part of the timeline.
const halfWidth = this.props.width / 2;
const timeScale = getTimeScale(timelineTransform);
const momentStart = moment(timeScale.invert(-halfWidth)).utc();
const momentEnd = moment(timeScale.invert(halfWidth)).utc();
// Start counting the timestamps from the most recent timestamp that is not shown
// on screen. The values are always rounded up to the timestamps of the next bigger
// period (e.g. for days it would be months, for months it would be years).
let momentTimestamp = moment(momentStart)
.utc()
.startOf(parentPeriod || period);
while (momentTimestamp.isBefore(momentStart)) {
momentTimestamp = moment(momentTimestamp).add(periodInterval, period);
}
momentTimestamp = moment(momentTimestamp).subtract(periodInterval, period);
// Make that hidden timestamp the first one in the list, but position
// it inside the visible range with a prepended arrow to the past.
const ticks = [
{
isBehind: true,
position: -halfWidth,
timestamp: formattedTimestamp(momentTimestamp),
},
];
// Continue adding ticks till the end of the visible range.
do {
// If the new timestamp enters into a new bigger period, we round it down to the
// beginning of that period. E.g. instead of going [Jan 22nd, Jan 29th, Feb 5th],
// we output [Jan 22nd, Jan 29th, Feb 1st]. Right now this case only happens between
// days and months, but in theory it could happen whenever bigger periods are not
// divisible by the duration we are using as a step between the ticks.
let newTimestamp = moment(momentTimestamp).add(periodInterval, period);
if (
parentPeriod &&
newTimestamp.get(parentPeriod) !== momentTimestamp.get(parentPeriod)
) {
newTimestamp = moment(newTimestamp)
.utc()
.startOf(parentPeriod);
}
momentTimestamp = newTimestamp;
// If the new tick is too close to the previous one, drop that previous tick.
const position = timeScale(momentTimestamp);
const previousPosition = last(ticks) && last(ticks).position;
if (position - previousPosition < MIN_TICK_SPACING_PX) {
ticks.pop();
}
ticks.push({ position, timestamp: formattedTimestamp(momentTimestamp) });
} while (momentTimestamp.isBefore(momentEnd));
return ticks;
}
getVerticalShiftForPeriod(period, { durationMsPerPixel }) {
const { childPeriod, parentPeriod } = TICK_SETTINGS_PER_PERIOD[period];
let shift = 1;
if (parentPeriod) {
const durationMultiplier = 1 / MAX_TICK_SPACING_PX;
const parentInterval =
TICK_SETTINGS_PER_PERIOD[parentPeriod].periodIntervals[0];
const parentIntervalMs = moment
.duration(parentInterval, parentPeriod)
.asMilliseconds();
const fadedInDurationMs = parentIntervalMs * durationMultiplier;
const fadedOutDurationMs = fadedInDurationMs * FADE_OUT_FACTOR;
const transitionFactor =
Math.log(fadedOutDurationMs) - Math.log(durationMsPerPixel);
const transitionLength =
Math.log(fadedOutDurationMs) - Math.log(fadedInDurationMs);
shift = clamp(transitionFactor / transitionLength, 0, 1);
}
if (childPeriod) {
shift += this.getVerticalShiftForPeriod(childPeriod, {
durationMsPerPixel,
});
}
return shift;
}
isOutsideOfClickableRange(timestamp) {
const { clickableStartAt, clickableEndAt } = this.props;
const beforeClickableStartAt =
clickableStartAt && clickableStartAt > timestamp;
const afterClickableEndtAt = clickableEndAt && clickableEndAt < timestamp;
return beforeClickableStartAt || afterClickableEndtAt;
}
render() {
const { period } = this.props;
const periodFormat = TICK_SETTINGS_PER_PERIOD[period].format;
const ticks = this.getTicksForPeriod(period, this.props);
const ticksRow =
MAX_TICK_ROWS - this.getVerticalShiftForPeriod(period, this.props);
// Ticks quickly fade in from the bottom and then slowly start
// fading out towards the top until they are pushed out of canvas.
const focusedRow = MAX_TICK_ROWS - 1;
const opacity =
ticksRow > focusedRow
? linearGradientValue(ticksRow, [MAX_TICK_ROWS, focusedRow])
: linearGradientValue(ticksRow, [-2, focusedRow]);
const isBarelyVisible = opacity < 0.4;
return (
<TimelineLabels
className={period}
opacity={opacity}
y={ticksRow * TICKS_ROW_SPACING}
>
{map(ticks, ({ timestamp, position, isBehind }) => (
<TimelineLabel
key={timestamp}
timestamp={timestamp}
position={position}
isBehind={isBehind}
periodFormat={periodFormat}
disabled={
isBarelyVisible || this.isOutsideOfClickableRange(timestamp)
}
onClick={this.props.onClick}
/>
))}
</TimelineLabels>
);
}
} |
JavaScript | class SubjectSeries {
/**
* Constructs a new <code>SubjectSeries</code>.
* a subjectSeries
* @alias module:model/SubjectSeries
* @class
* @param subjectId {Number} 专题id
* @param seriesId {Number} 剧集id
* @param coverUrl {String} 图片
*/
constructor(subjectId, seriesId, coverUrl) {
this['subject_id'] = subjectId;this['series_id'] = seriesId;this['cover_url'] = coverUrl;
}
/**
* Constructs a <code>SubjectSeries</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/SubjectSeries} obj Optional instance to populate.
* @return {module:model/SubjectSeries} The populated <code>SubjectSeries</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new SubjectSeries();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'Number');
}
if (data.hasOwnProperty('subject_id')) {
obj['subject_id'] = ApiClient.convertToType(data['subject_id'], 'Number');
}
if (data.hasOwnProperty('series_id')) {
obj['series_id'] = ApiClient.convertToType(data['series_id'], 'Number');
}
if (data.hasOwnProperty('cover_url')) {
obj['cover_url'] = ApiClient.convertToType(data['cover_url'], 'String');
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
}
return obj;
}
/**
* id
* @member {Number} id
*/
id = undefined;
/**
* 专题id
* @member {Number} subject_id
*/
subject_id = undefined;
/**
* 剧集id
* @member {Number} series_id
*/
series_id = undefined;
/**
* 图片
* @member {String} cover_url
*/
cover_url = undefined;
/**
* 剧集名称
* @member {String} name
*/
name = undefined;
} |
JavaScript | class PlayerPhysics {
constructor(scene, sprite, x, y, scale) {
this.sprite = sprite;
this.scale = scale;
//const {width : w, height: h} = this.sprite;
console.log("local sprite physics");
console.log(sprite.width);
console.log(sprite.height);
this.scene = scene;
this.isTouching = {
left: false,
right: false,
ground: false,
top: false,
nearground: false,
sensor: false,
};
this.onPlatform = false;
// within the platform fall state
this.platformFall = false;
this.collisionList = [collisionData.category.hard];
this.debugtext = scene.add.text(10, 100, "");
console.log(`set scale ${scale}`);
//this.sprite.setScale(scale);
console.log("--player--");
console.log(`width ${w} height: ${h}`);
this.hitbox = PhysicsEditorParser.parseBody(
0,
0,
this.scene.frameData["adventurer-idle-00"]
);
const w = (this.hitbox.bounds.max.x - this.hitbox.bounds.min.x) * scale;
const h = (this.hitbox.bounds.max.y - this.hitbox.bounds.min.y) * scale;
this.sensors = {
nearbottom: Bodies.rectangle(0, h / 2 + 20, w, 50, {
isSensor: true,
}),
bottom: Bodies.rectangle(0, h / 2 - 10, w * 0.8, 20, {
isSensor: true,
}),
left: Bodies.rectangle(-w / 2, 0, 5, h * 0.5, {
isSensor: true,
}),
right: Bodies.rectangle(w / 2, 0, 5, h * 0.5, {
isSensor: true,
}),
top: Bodies.rectangle(0, -h / 2 + 10, w * 0.8, 20, {
isSensor: true,
}),
neartop: Bodies.rectangle(0, -h / 2 - 20, w, 50, {
isSensor: true,
}),
};
const compoundBody = Body.create({
parts: [
this.sensors.bottom,
this.sensors.left,
this.sensors.right,
this.sensors.top,
this.sensors.nearbottom,
this.sensors.neartop,
],
frictionStatic: 0,
frictionAir: 0.02,
friction: 0.1,
collisionFilter: {
mask: collisionData.category.hard,
},
});
// create a player container sprite
this.physicsprite = this.scene.matter.add.sprite(x, y, "");
this.physicsprite
.setExistingBody(compoundBody)
.setFixedRotation()
.setCollisionGroup(collisionData.group.noplayer);
this.sprite
.setExistingBody(this.hitbox)
.setScale(scale)
.setFixedRotation()
.setPosition(x, y)
.setCollisionCategory(collisionData.category.player);
this.unsubscribers = [
this.scene.matterCollision.addOnCollideStart({
objectA: [
this.sensors.bottom,
this.sensors.left,
this.sensors.right,
this.sensors.top,
this.sensors.nearbottom,
],
callback: this.onSensorCollide,
context: this,
}),
this.scene.matterCollision.addOnCollideActive({
objectA: [
this.sensors.bottom,
this.sensors.left,
this.sensors.right,
this.sensors.top,
this.sensors.nearbottom,
],
callback: this.onSensorCollide,
context: this,
}),
this.scene.matterCollision.addOnCollideStart({
objectA: [this.sensors.bottom],
objectB: this.scene.objectgroup.soft,
callback: () => {
console.log("collide with platform");
this.onPlatform = true;
this.collisionList = [
collisionData.category.hard,
collisionData.category.soft,
];
this.sprite.setCollidesWith(this.collisionList);
this.physicsprite.setCollidesWith(this.collisionList);
},
context: this,
}),
this.scene.matterCollision.addOnCollideActive({
objectA: [this.sensors.bottom],
objectB: this.scene.objectgroup.soft,
callback: () => {
console.log("keep colliding");
if (!this.platformFall) {
this.onPlatform = true;
this.collisionList = [
collisionData.category.hard,
collisionData.category.soft,
];
this.sprite.setCollidesWith(this.collisionList);
this.physicsprite.setCollidesWith(this.collisionList);
} else {
this.collisionList = [collisionData.category.hard];
this.sprite.setCollidesWith(this.collisionList);
this.physicsprite.setCollidesWith(this.collisionList);
}
},
context: this,
}),
this.scene.matterCollision.addOnCollideEnd({
objectA: [this.sensors.bottom],
objectB: this.scene.objectgroup.soft,
callback: () => {
console.log("platform end collide");
this.platformFall = false;
this.onPlatform = false;
this.collisionList = [collisionData.category.hard];
this.sprite.setCollidesWith(this.collisionList);
this.physicsprite.setCollidesWith(this.collisionList);
},
context: this,
}),
];
this.scene.events.on("update", this.setBody, this);
this.scene.events.on("update", this.debugUpdate, this);
//this.sprite.world.on('beforeupdate', this.doublegravity, this);
this.scene.matter.world.on("beforeupdate", this.resetTouching, this);
//this.scene.input.on('pointermove', function (pointer) {
// //console.log(this.clicksensor);
// this.physicsprite.setPosition(pointer.x, pointer.y);
// //this.clicksensor.setPosition(pointer.x, pointer.y);
//
//}.bind(this));
//this.scene.matter.world.on('beforeupdate', this.cancelgravity, this);
}
debugUpdate() {
//this.debugtext.setText(`top:${this.isTouching.top} right: ${this.isTouching.right} left: ${this.isTouching.left} \n
// bottom: ${this.isTouching.ground} nearbottom: ${this.isTouching.nearground} \n sensor: ${this.isTouching.sensor}`);
}
setBody() {
//console.log(this.sprite.body);
//console.log(this.isTouching);
const { x: x, y: y } = this.sprite;
this.physicsprite.setPosition(x, y);
//console.log(this.isTouching);
//const {x: x, y: y} = this.sprite;
if (this.sprite.anims.currentFrame) {
var sx = this.sprite.x;
var sy = this.sprite.y;
var sav = this.sprite.body.angularVelocity;
var sv = this.sprite.body.velocity;
var flipX = this.sprite.flipX;
const hitbox = PhysicsEditorParser.parseBody(
0,
0,
this.scene.frameData[this.sprite.anims.currentFrame.textureFrame]
);
//console.log(hitbox.friction);
//console.log(hitbox.frictionStatic);
//console.log(hitbox.frictionAir);
//const compoundBody = Body.create({
// parts: [hitbox],
// frictionStatic: 0,
// frictionAir: 0.02,
// friction: 0.1,
// collisionFilter: {
// mask: collisionData.category.hard
// }
//})
this.sprite
.setScale(1)
.setExistingBody(hitbox)
.setScale(2)
.setPosition(sx, sy)
.setVelocity(sv.x, sv.y)
.setAngularVelocity(sav)
.setCollisionCategory(collisionData.category.player)
.setCollidesWith(this.collisionList)
.setFixedRotation();
if (flipX) {
Body.scale(hitbox, -1, 1);
//this.sprite.setOriginFromFrame();
this.sprite.setOrigin(1 - this.sprite.originX, this.sprite.originY);
}
//this.sprite.setCollidesWith(this.collisionList);
//this.container.setCollidesWith(this.collisionList);
//console.log(this.collisionList);
//this.sprite.setOriginFromFrame();
//Body.setPosition(this.compoundBody, {x : sx, y: sy});
}
}
cancelgravity() {
var gravity = this.scene.matter.world.localWorld.gravity;
Body.applyForce(this.physicsprite.body, this.physicsprite.body.position, {
x: -gravity.x * gravity.scale * this.physicsprite.body.mass,
y: -gravity.y * gravity.scale * this.physicsprite.body.mass,
});
}
resetTouching() {
this.isTouching.left = false;
this.isTouching.right = false;
this.isTouching.ground = false;
this.isTouching.top = false;
this.isTouching.nearground = false;
this.isTouching.sensor = false;
}
onSensorCollide({ bodyA, bodyB, pair }) {
if (bodyB.isSensor) {
return;
}
//console.log(bodyB);
if (bodyB.parent === this.sprite.body) {
//console.log('hit parent body');
return;
}
if (bodyA === this.sensors.left) {
//console.log('left');
this.isTouching.left = true;
// if other object is player seperate both players
//if (pair.separation > 0.5) {
// this.sprite.x += (pair.separation - 0.5);
//}
} else if (bodyA === this.sensors.right) {
this.isTouching.right = true;
//if (pair.separation > 0.5) {
// this.sprite.x -= (pair.separation - 0.5);
//}
} else if (bodyA === this.sensors.bottom) {
this.isTouching.ground = true;
} else if (bodyA === this.sensors.top) {
this.isTouching.top = true;
//console.log(bodyB);
} else if (bodyA === this.sensors.nearbottom) {
this.isTouching.nearground = true;
} else if (bodyA === this.mainBody) {
}
}
destroy() {
this.unsubscribers.forEach((unsubscribe) => {
unsubscribe();
});
}
} |
JavaScript | class OutputStrategy
{
emit(life)
{
throw new ReferenceError('not implemented in superclass');
}
} |
JavaScript | class ChannelConfigItem {
constructor(client, config) {
logger = new Logger(client, 'channelconfig');
/**
* The bot client
* @type Client
* @private
*/
this._client = client;
for (let key in config) {
if (config.hasOwnProperty(key)) {
this[key] = config[key];
}
}
this.repos = [].concat(this.repos);
}
/**
* Set a specific config property to a value for this config item
* @param {String} prop Property to modify
* @param {String} value The new value for the property
* @see ChannelConfig#set
* @return {Promise}
*/
set(prop, value) {
return this._client.set(this.channelID, prop, value);
}
/**
* Delete repo events from channel
* @param {String} repo Repo events to delete from channel
* @return {Promise}
*/
deleteRepo(repo) {
let repos = this.repos;
repos.splice(repos.indexOf(repo), 1);
return this.set('repos', repos);
}
} |
JavaScript | class ChannelConfig {
constructor() {
/**
* All the config
* @type {Collection}
* @private
*/
this._data = new Collection();
this.setup();
this.validKeys = [
'repos',
'repo',
'embed',
'disabledEvents',
'ignoredUsers',
'ignoredBranches',
];
this.setupEvents = false;
/**
* Loaded
* @type {Boolean}
*/
this.loaded = false;
}
/**
* Get config from database and add to this._data
*/
setup() {
channelConfig.find({}).then(configs => {
this.loaded = true;
configs.forEach(row => {
this._data.set(row.channelID, new ChannelConfigItem(this, row._doc));
});
}).catch(Log.error);
}
/**
* Initialize configuration and Discord bot events
* @param {external:Client} bot Client instance
*/
init(bot) {
if (!this.loaded) {
setTimeout(() => this.init(bot), 5000);
return;
}
for (const ch of bot.channels) {
const channel = ch[1];
if (!channel || channel.type !== 'text') continue;
if (!this.has(channel.id)) {
Log.info(`ChannelConf | Adding "${channel.guild.name}"'s #${channel.name} (${channel.id})`);
this.add(channel).catch(e => bot.emit('error', e));
}
}
if (!this.setupEvents) {
this.setupEvents = true;
bot.on('channelDelete', channel => {
if (!channel || channel.type !== 'text') return;
Log.info(`ChannelConf | Deleting "${channel.guild.name}"'s #${channel.name} (${channel.id})`);
this.delete(channel.id).catch(Log.error);
});
bot.on('channelCreate', channel => {
if (!channel || channel.type !== 'text') return;
if (this.has(channel.id)) return;
Log.info(`ChannelConf | Adding "${channel.guild.name}"'s #${channel.name} (${channel.id})`);
if (!channel.name || !channel.guild.name || !channel.id) {
Log.warning('ChannelConf | Some info for channel not found', channel);
logger.log('Error when adding channel config to database', util.inspect(channel, { depth: 2 }), 'YELLOW');
} else {
this.add(channel).catch(e => bot.emit('error', e));
}
});
}
}
/**
* Find channels with events for repo
* @param {String} repo Repo for the events
* @return {ChannelConfigItem}
*/
findByRepo(repo) {
let re = repo.toLowerCase();
return this._data.filter(e => e.repos.filter(r => r === re)[0]);
}
/**
* Get channel config
* @param {String} channel Channel ID
* @return {ChannelConfigItem}
*/
get(channel) {
return this._data.get(channel);
}
/**
* Has channel in config
* @param {String} channel Channel ID
* @return {Boolean}
*/
has(channel) {
return this._data.has(channel);
}
/**
* Delete all repo events from channel
* @param {String} channelID Channel ID with the events to delete
* @return {Promise<ChannelConfig>}
*/
delete(channelID) {
return channelConfig.findOneAndRemove({
channelID: channelID,
}).then(() => {
this._data.delete(channelID);
return Promise.resolve(this);
});
}
/**
* Delete all channels from guild
* @param {String} guildID Guild ID to delete channel configs for
* @return {Promise}
*/
deleteFromGuild(guildID) {
return Promise.all(
this._data
.filter(c => c.guildID === guildID)
.map(c => {
Log.info(`ChannelConf | Deleting "${c.guildName}"'s #${c.channelName} (${c.channelID})`);
return this.delete(c.channelID);
})
).then(() => this);
}
/**
* Add channel to config
* @param {Channel} channel Channel to add repo events
* @return {Promise<ChannelConfig>}
*/
add(channel) {
if (!channel || !channel.id) return Promise.reject(`No channel passed!`);
if (channel && channel.id && this.get(channel.id)) return Promise.reject(`Channel already has an entry in database`);
const conf = {
guildID: channel.guild && channel.guild.id,
guildName: channel.guild && channel.guild.name,
channelID: channel.id,
channelName: channel.name,
repos: [],
prefix: `GL! `,
disabledEvents: [
'merge_request/update',
'pipeline',
],
};
return channelConfig.create(conf).then(() => {
const item = new ChannelConfigItem(this, conf);
this._data.set(conf.channelID, item);
return item;
});
}
/**
* Add all channels from guild
* @param {Guild} guild Guild obj to add channel configs for
* @return {Promise}
*/
addFromGuild(guild) {
return Promise.all(
guild.channels
.filter(c => c.type === 'text')
.map(c => {
Log.info(`ChannelConf | Adding "${c.guildName}"'s #${c.channelName} (${c.channelID})`);
return this.add(c);
})
).then(() => this);
}
/**
* Replace specific channel config prop with value
* @param {String} channel Channel with the repo events
* @param {String} prop Property to set
* @param {String} value Value to set property to
* @return {Promise<ChannelConfig>} updated config item
*/
set(channel, prop, value) {
return new Promise((resolve, reject) => {
let oldConfig = this._data.find(e => e.channelID === channel);
let newConfig = oldConfig;
newConfig[prop] = value;
channelConfig.findOneAndUpdate({
channelID: channel,
}, newConfig, {
new: true,
}, (err) => {
if (err) return reject(err);
this._data.set(channel, new ChannelConfigItem(this, newConfig));
resolve(this);
});
});
}
/**
* Add repo to channel
* @param {Channel} channel Channel to add repo to
* @param {String} repo repo to add to channel
* @see ChannelConfig#set
* @return {Promise<ChannelConfig>}
*/
addRepoToChannel(channel, repo) {
if (!channel || !repo) return Promise.reject(`Invalid arguments.`);
let conf = this.get(channel);
let repos = conf.repos;
repos.push(repo.toLowerCase());
return this.set(channel, 'repos', repos);
}
/**
* Delete repo events from specific channel
* @param {String} channel Channel with the repo events
* @param {String} repo Repo event to remove from Channel
* @see ChannelConfig#set
* @return {Promise<ChannelConfig>}
*/
deleteRepo(channel, repo) {
return channelConfig.findOneAndRemove({
repo,
}).then(() => {
let oldRepos = this._data.find(e => e.channelID === channel);
let newRepos = oldRepos.slice(0, oldRepos.indexOf(repo));
return this.set(channel, 'repos', newRepos);
});
}
} |
JavaScript | class SeekState extends ui.states.BaseState {
constructor(block, timeline, options = {}) {
super(timeline);
this.block = block;
this.options = options;
}
handleEvent(e) {
if (
e.type === 'mousedown' ||
e.type === 'mousemove' ||
e.type === 'dblclick'
) {
const { timeToPixel, offset } = this.timeline.timeContext;
const time = timeToPixel.invert(e.x) - offset;
this.block.seek(time);
if (e.type === 'dblclick' && this.options.startOnDblClick === true)
this.block.start();
}
}
} |
JavaScript | class LiteratureSearch extends Morph {
async initialize() {
this.windowTitle = "LiteratureSearch";
this.updateView()
}
get mode() {
return this.getAttribute("mode")
}
set mode(s) {
this.setAttribute("mode", s)
}
get queryString() {
return this.getAttribute("query")
}
set queryString(s) {
this.setAttribute("query", s)
}
get literatureListing() {
return this._literatureListing || lively.query(this, "literature-listing")
}
// for testing
set literatureListing(element) {
this._literatureListing = element
}
get renameURL() {
return this.getAttribute("rename-url")
}
set renameURL(s) {
this.setAttribute("rename-url", s)
}
get baseURL() {
return this.getAttribute("base-url")
}
set baseURL(s) {
this.setAttribute("base-url", s)
}
get details() {
return this.get("#content")
}
updateView() {
if (this.queryString) {
this.findBibtex(this.queryString)
}
}
close(fireNoEvent=false) {
if (!fireNoEvent){
this.dispatchEvent(new CustomEvent("closed"))
}
if (this.literatureListing) {
this.literatureListing.details.hidden = true
this.literatureListing.details.innerHTML = "" // self destruct...
}
}
async findBibtex(queryString) {
queryString = queryString.replace(/[-_,]/g, " ")
var div = <div></div>;
this.details.innerHTML = ""
var input = <input id="searchBibtexInput" value={queryString} style="width:400px"></input>
input.addEventListener("keyup", event => {
if (event.keyCode == 13) { // ENTER
this.findBibtexSearch(input.value, div)
}
});
this.details.appendChild(<div>
<h3>Searched:{input}</h3>
<span style="position:absolute; top: 0px; right:0px">
<a title="close" click={() => this.close()}>
<i class="fa fa-close" aria-hidden="true"></i>
</a></span>{div}</div>)
this.findBibtexSearch(queryString, div)
}
async findBibtexSearch(queryString, div) {
div.innerHTML = "searching..."
var entries
try {
var bibEntries = this.mode == "fuzzy" ?
await this.findBibtexEntriesFuzzy(queryString, div) :
await this.findBibtexEntriesSimple(queryString, div);
div.innerHTML = ""
var rows = []
let allBibtexEntries = await FileIndex.current().db.bibliography.toArray()
for(let bib of bibEntries) {
let id = bib.value.entryTags.microsoftid
let existing = allBibtexEntries
.filter(ea => ea.key == bib.value.citationKey)
.filter(ea => !this.baseURL || ea.url.startsWith(this.baseURL))
let rename = <a title="rename file" class="method"
click={async () => {
await this.literatureListing.renameFile(this.renameURL, bib.generateFilename() + ".pdf")
this.close(true) // we need to close it... because literatureListing will change..., oder does it?
}}>
rename
</a>
let importBibtex = <a class="method" click={async () => {
await lively.html.highlightBeforeAndAfterPromise(importBibtex, Paper.importBibtexId(id))
importBibtex.remove()
}}>
import
</a>
rows.push(<tr>
<td style="vertical-align: top">
</td>
<td>
<span class="methods" >
{this.literatureListing ? rename : ""} {(existing.length == 0) && id ? importBibtex : ""}
</span> <br />
{bib}</td>
</tr>)
}
div.appendChild(
<table> {... rows}</table>)
} catch(err) {
div.innerHTML = "ERROR: " + err
}
}
async findBibtexEntriesSimple(queryString, div) {
var bibEntries = []
var entries = await lively.files.loadJSON("academic://" + queryString)
div.innerHTML = "loading paper"
for(var ea of entries) {
let foundPaper = await Paper.ensure(ea)
var bib = await (<lively-bibtex-entry style="display: inline-block"> </lively-bibtex-entry>)
bib.setFromBibtex(foundPaper.toBibtex())
bib.updateView()
bibEntries.push(bib)
}
return bibEntries
}
async findBibtexEntriesFuzzy(queryString, div) {
var bibEntries = []
var json = await fetch("https://academic.microsoft.com/api/search", {
method: "POST",
headers: {
"content-type": "application/json; charset=utf-8"
},
body: JSON.stringify({
query: queryString, queryExpression: "",
filters: [],
orderBy: 0,
skip: 0,
sortAscending: true,
take: 5})
}).then(r => r.json())
if (!json || !json.pr) {
div.innerHTML = "nothing found"
return []
}
for(var ea of json.pr) {
var bib = await (<lively-bibtex-entry mode="readonly"> </lively-bibtex-entry>)
var entry = {
entryTags: {
author: ea.paper.a.map(author => author.dn.replace(/<\/?[a-z]+>/g,"")).join(" and "),
title: ea.paper.dn.replace(/<\/?[a-z]+>/g,""),
microsoftid: ea.paper.id,
year: moment(ea.paper.v.publishedDate).year(),
publisher: ea.paper.v.displayName,
keywords: ea.paper.fos.map(kw => kw.dn),
abstract: ea.paper.d,
},
entryType: "article"
}
entry.citationKey = Bibliography.generateCitationKey(entry)
bib.value = entry
bib.updateView()
bibEntries.push(bib)
}
return bibEntries
}
livelyMigrate(other) {
this.literatureListing = other.literatureListing
}
async livelyExample() {
this.queryString = "Kiczales 1996 Aspect-oriented programming"
this.mode = "fuzzy"
this.literatureListing = await (<literature-listing></literature-listing>)
this.renameURL = "https://bal.blu/aop.pdf"
this.updateView()
}
} |
JavaScript | class StringUtil {
/**
* Performs a series of functions to clean the given string of unwanted characters.
*
* @param {string} value
* String to clean.
*
* @returns {string}
*/
static cleanString(value) {
value = this.unescapeDoubleQuotes(value);
value = this.unescapeSingleQuotes(value);
return value;
}
/**
* Unescapes single quotes.
*
* @param {string} value
*
* @returns {string}
*/
static unescapeSingleQuotes(value) {
return value.replace(/\\'/g, "'");
}
/**
* Unescapes double quotes.
*
* @param {string} value
*
* @returns {string}
*/
static unescapeDoubleQuotes(value) {
return value.replace(/\\"/g, '"');
}
} |
JavaScript | class PromiseButton extends React.Component {
render() {
const {
children,
...other
} = this.props
return (
<PromiseButtonBase
{...other}
renderOnPending={() => (
<PulseLoader color="#FF6663" size={6} margin="4px"/>
)}
renderOnFulfilled={() => children}
renderOnRejected={() => children}
>
{children}
</PromiseButtonBase>
)
}
} |
JavaScript | class Ontology extends BlockchainInterface {
/**
* Create a new instance of the {Fabric} class.
* @param {string} config_path The path of the Fabric network configuration file.
*/
constructor(config_path) {
super(config_path);
let blockChainConfig = JSON.parse(fs.readFileSync(this.configPath, 'utf-8'));
this.contractConfig = blockChainConfig.ontology.contract;
this.peerWallets = blockChainConfig.ontology.peers;
this.server = blockChainConfig.ontology.server;
this.password = blockChainConfig.ontology.password; // peers and self password is same
let walletFileContent = fs.readFileSync(blockChainConfig.ontology.wallet, 'utf-8');
this.wallet = ontSdk.Wallet.parseJson(walletFileContent);
this.account = this.wallet.accounts[0];
try {
const saltHex = Buffer.from(this.account.salt, 'base64').toString('hex');
const encryptedPrivateKeyObj = new ontSdk.Crypto.PrivateKey(this.account.encryptedKey.key);
let decryptParam = {
cost: this.wallet.scrypt.n,
blockSize: this.wallet.scrypt.r,
parallel: this.wallet.scrypt.p,
size: this.wallet.scrypt.dkLen
};
this.privateKey = encryptedPrivateKeyObj.decrypt(this.password,
this.account.address, saltHex, decryptParam);
} catch (err) {
throw Error('decrypt wallet failed');
}
this.monitorOnly = true;
}
/**
* ontology no need init
* @return {Promise} The return promise.
*/
init() {
return Promise.resolve();
}
/**
* retrun a random server address, for request load balance
* @return {string} server address
*/
getRandomServerAddr() {
let serverIndex = Math.floor(Math.random() * this.server.length);
return this.server[serverIndex];
}
/**
* sendTx ont to a specific account
*/
async initAsset() {
const pks = [];
const pris = [];
for (const peerWallet of this.peerWallets) {
let wallet = ontSdk.Wallet.parseJson(fs.readFileSync(peerWallet, 'utf-8'));
pks.push(new ontSdk.Crypto.PublicKey(wallet.accounts[0].publicKey));
const p = new ontSdk.Crypto.PrivateKey(wallet.accounts[0].encryptedKey.key);
let params = {
cost: wallet.scrypt.n,
blockSize: wallet.scrypt.r,
parallel: wallet.scrypt.p,
size: wallet.scrypt.dkLen
};
pris.push(p.decrypt(this.password, wallet.accounts[0].address, wallet.accounts[0].salt, params));
}
let multiSignNum = Math.floor((5 * this.peerWallets.length + 6) / 7);
const mulAddr = ontSdk.Crypto.Address.fromMultiPubKeys(multiSignNum, pks);
log('mulAddr is ', mulAddr.toBase58());
const transferOntTx = ontSdk.OntAssetTxBuilder.makeTransferTx('ONT', mulAddr, this.account.address, 1000000000,
'0', '20000', mulAddr);
const amount = 20000 * 1e9; // multiply 1e9 to set the precision
const transferOngTx = ontSdk.OntAssetTxBuilder.makeWithdrawOngTx(mulAddr, this.account.address, amount, mulAddr,
'0', '20000');
for (let i = 0; i < multiSignNum; i++) {
ontSdk.TransactionBuilder.signTx(transferOntTx, multiSignNum, pks, pris[i]);
ontSdk.TransactionBuilder.signTx(transferOngTx, multiSignNum, pks, pris[i]);
}
NetUtil.postTx(this.getRandomServerAddr(), transferOntTx.serialize());
await this.waitABlock();
log('after transfer ont, balance is ', await NetUtil.getBalance(this.getRandomServerAddr(),
this.account.address.toBase58()));
NetUtil.postTx(this.getRandomServerAddr(), transferOngTx.serialize());
await this.waitABlock();
log('after transfer ong, balance is ', await NetUtil.getBalance(this.getRandomServerAddr(),
this.account.address.toBase58()));
}
/**
* ontology no need install smart contract
* @return {Promise} The return promise.
*/
async installSmartContract() {
this.contractConfig.forEach((item, index) => {
let name = item.name;
let codeVersion = item.version;
let author = item.author;
let email = item.email;
let desp = item.description;
let needStorage = item.needStorage;
let vmCode = fs.readFileSync(item.path, 'utf-8');
let tx = ontSdk.TransactionBuilder.makeDeployCodeTransaction(vmCode, name, codeVersion, author, email, desp,
needStorage, '0', '20000000', this.account.address);
ontSdk.TransactionBuilder.signTransaction(tx, this.privateKey);
NetUtil.postTx(this.getRandomServerAddr(), tx.serialize());
});
await this.waitABlock();
return Promise.resolve();
}
/**
* ontology no need context
* @param {string} name The name of the callback module as defined in the configuration files.
* @param {object} args Unused.
* @return {object} The assembled Fabric context.
*/
getContext(name, args) {
return Promise.resolve();
}
/**
* ontology no need context
* @param {object} context The Fabric context to release.
* @return {Promise} The return promise.
*/
releaseContext(context) {
return Promise.resolve();
}
/**
* send transaction
* @param {Object} context context object
* @param {string} txHash transaction data
* @param {string} txData transaction hash
* @return {TxStatus}The txStatus for the transaction
*/
sendTx(context, txHash, txData) {
if (context.engine) {
context.engine.submitCallback(1);
}
let invokeStatus = new TxStatus(txHash);
return NetUtil.postTx(this.getRandomServerAddr(), txData).then((result) => {
if (result < 0) {
invokeStatus.SetStatusFail();
log('tx failed', invokeStatus.GetID());
}
return invokeStatus;
});
}
/**
* generate invoke smart contract/submit transactions
* @param {AbiInfo} abiInfo contract abi info
* @param {String} contractVer version of the contract
* @param {Array} args array of JSON formatted arguments for multiple transactions
* @return {Transaction} invoke smart contract transaction
*/
genInvokeSmartContractTx(abiInfo, contractVer, args) {
let abiFunc = abiInfo.getFunction(args.func);
if (typeof abiFunc === 'undefined') {
throw new Error('not define invoke contract func!');
}
for (let i = 0; i < abiFunc.parameters.length; i++) {
let param = new ontSdk.Parameter(abiFunc.parameters[i].getName(), abiFunc.parameters[i].getType(),
args.args[i]);
abiFunc.setParamsValue(param);
}
let tx = ontSdk.TransactionBuilder.makeInvokeTransaction(abiFunc.name, abiFunc.parameters,
ontSdk.Crypto.Address.fromVmCode(abiInfo.vmCode), '0', '20000000', this.account.address);
ontSdk.TransactionBuilder.signTransaction(tx, this.privateKey);
return tx;
}
/**
* get current height
* @return {int} current height
*/
getHeight() {
// in case of block height not sync problem, fix request server
return NetUtil.getHeight(this.getRandomServerAddr());
}
/**
* get tx hashes of this height
* @param {int} height block height
* @return {string[]} all tx hashes in the block
*/
getBlockTxHashes(height) {
// in case of block height not sync problem, fix request server
return NetUtil.getBlockTxHashes(this.getRandomServerAddr(), height);
}
/**
* insure tx
* @param {string} txHash tx hash
* @return {Promise} tx is success or failed
*/
insureTx(txHash) {
// in case of block height not sync problem, fix request server
return NetUtil.insureTx(this.getRandomServerAddr(), txHash);
}
/**
* wait a block to catch up destHeight
* @param {int} destHeight start height
* @return {Promise} empty promise
*/
async waitABlock(destHeight) {
if (typeof destHeight === 'undefined') {
let curr = await this.getHeight();
destHeight = curr + 1;
log('wait a block, current height is', curr, ', destHeight is', destHeight);
}
let newHeight;
while (true) {
newHeight = await this.getHeight();
log('wait a block, current height is', newHeight, ', destHeight is', destHeight);
if (newHeight >= destHeight) {
break;
}
await Util.sleep(1000).then(() => {
});
}
return Promise.resolve();
}
/**
* get block generated time
* @param{int} height is block height
* @return {Promise} block timestamp
*/
getBlockGenerateTime(height) {
return this.getBlockByHeight(height).then((block) => {
if (typeof block === 'undefined'){
return;
}
return block.Header.Timestamp;
});
}
/**
* get block by height
* @param{int} height is block height
* @return {Promise} block timestamp
*/
getBlockByHeight(height) {
return NetUtil.getBlock(this.getRandomServerAddr(), height);
}
} |
JavaScript | class NoBlobError extends Error {
constructor(id) {
super(`Blob ID (${id}) does not exist`);
this.name = 'NoBlobError';
this.id = id;
}
} |
JavaScript | class FundGranterAddress {
/**
* Constructor to fund granter address with eth / ost / stable coin.
*
* @param {string} ethOwnerPrivateKey
* @param {string} ethAmount
* @param {string} stakeCurrencySymbol
* @param {string} stakeCurrencyOwnerPrivateKey
* @param {string} stakeCurrencyAmount
*
* @constructor
*/
constructor(ethOwnerPrivateKey, ethAmount, stakeCurrencySymbol, stakeCurrencyOwnerPrivateKey, stakeCurrencyAmount) {
const oThis = this;
oThis.ethOwnerPrivateKey = ethOwnerPrivateKey;
oThis.ethAmount = ethAmount;
oThis.stakeCurrencySymbol = stakeCurrencySymbol;
oThis.stakeCurrencyOwnerPrivateKey = stakeCurrencyOwnerPrivateKey;
oThis.stakeCurrencyAmount = stakeCurrencyAmount;
}
/**
* Perform.
*
* @return {Promise<result>}
*/
perform() {
const oThis = this;
return oThis._asyncPerform().catch(function(error) {
if (responseHelper.isCustomResult(error)) {
return error;
}
logger.error('lib/setup/originChain/FundGranterAddress.js::perform::catch');
logger.error(error);
return responseHelper.error({
internal_error_identifier: 'l_s_oc_fga_1',
api_error_identifier: 'unhandled_catch_response',
debug_options: {}
});
});
}
/**
* Async perform.
*
* @return {Promise<result>}
* @private
*/
async _asyncPerform() {
const oThis = this;
if (basicHelper.isMainSubEnvironment()) {
logger.info('Grants are not allowed in main sub env.');
return Promise.reject(
responseHelper.error({
internal_error_identifier: 'l_s_oc_fga_2',
api_error_identifier: 'something_went_wrong',
debug_options: ''
})
);
}
await oThis._getGranterAddress();
logger.info('originGranterAddress -> ', oThis.originGranterAddress);
if (oThis.ethOwnerPrivateKey && oThis.ethAmount) {
logger.step(`* Chain Owner funding granter address with ${oThis.ethAmount} ETH.`);
await oThis._fundGranterAddressWithEth(); // From master internal funder.
}
if (oThis.stakeCurrencySymbol && oThis.stakeCurrencyAmount && oThis.stakeCurrencyOwnerPrivateKey) {
logger.step(
`* Stake Currency Owner funding granter address with ${oThis.stakeCurrencyAmount} ${oThis.stakeCurrencySymbol}.`
);
await oThis._fundGranterAddressWithStakeCurrency();
}
return responseHelper.successWithData({});
}
/**
* Fetch granter address.
*
* @sets oThis.originGranterAddress
*
* @return {Promise<void>}
* @private
*/
async _getGranterAddress() {
const oThis = this;
// Fetch all addresses associated with origin chain id.
const chainAddressCacheObj = new ChainAddressCache({ associatedAuxChainId: 0 }),
chainAddressesRsp = await chainAddressCacheObj.fetch();
if (chainAddressesRsp.isFailure()) {
return Promise.reject(
responseHelper.error({
internal_error_identifier: 'l_s_oc_fga_3',
api_error_identifier: 'something_went_wrong'
})
);
}
oThis.originGranterAddress = chainAddressesRsp.data[chainAddressConstants.originGranterKind].address;
}
/**
* Fund address with eth.
*
* @return {Promise<void>}
* @private
*/
async _fundGranterAddressWithEth() {
const oThis = this;
const providers = await oThis._getProvidersFromConfig(),
provider = providers[0], // Select one provider from provider endpoints array.
amountInWei = basicHelper.convertToLowerUnit(String(oThis.ethAmount), coreConstants.ETH_DECIMALS).toString(10); // Transfer amount.
await new TransferEthUsingPK({
toAddress: oThis.originGranterAddress,
fromAddressPrivateKey: oThis.ethOwnerPrivateKey,
amountInWei: amountInWei,
originChainId: oThis.chainId,
provider: provider
}).perform();
}
/**
* Fund address with ost.
*
* @return {Promise<void>}
* @private
*/
async _fundGranterAddressWithStakeCurrency() {
const oThis = this;
let stakeCurrencyBySymbolCache = new StakeCurrencyBySymbolCache({
stakeCurrencySymbols: [oThis.stakeCurrencySymbol]
});
let response = await stakeCurrencyBySymbolCache.fetch(),
decimals = response.data[oThis.stakeCurrencySymbol].decimal;
const providers = await oThis._getProvidersFromConfig(),
provider = providers[0], // Select one provider from provider endpoints array
amountInWei = basicHelper.convertToLowerUnit(String(oThis.stakeCurrencyAmount), decimals).toString(10); // Transfer amount
await new TransferERC20UsingPK({
toAddress: oThis.originGranterAddress,
fromAddressPrivateKey: oThis.stakeCurrencyOwnerPrivateKey,
amountInWei: amountInWei,
originChainId: oThis.chainId,
provider: provider,
tokenSymbol: oThis.stakeCurrencySymbol
}).perform();
}
/**
* Get providers from config.
*
* @sets oThis.chainId
*
* @return {Promise<void>}
* @private
*/
async _getProvidersFromConfig() {
const oThis = this;
const csHelper = new ConfigStrategyHelper(0),
csResponse = await csHelper.getForKind(configStrategyConstants.originGeth),
configForChain = csResponse.data[configStrategyConstants.originGeth],
readWriteConfig = configForChain[configStrategyConstants.gethReadWrite],
providers = readWriteConfig.wsProvider ? readWriteConfig.wsProviders : readWriteConfig.rpcProviders;
oThis.chainId = configForChain.chainId;
return providers;
}
} |
JavaScript | class Sized extends ConcreteCell {
constructor(props, ...args){
super(props, ...args);
this.getStyle = this.getStyle.bind(this);
}
build() {
let res = h('div', {
id: this.getElementId(),
class: "allow-child-to-fill-space overflow-hidden",
style: this.getStyle()
}, [this.renderChildNamed('content')]);
this.applySpacePreferencesToClassList(res);
return res;
}
allotedSpaceIsInfinite(child) {
let isInfinite = this.parent.allotedSpaceIsInfinite();
if (this.props.height !== null) {
isInfinite.vertical = false;
}
if (this.props.width !== null) {
isInfinite.horizontal = false;
}
return isInfinite;
}
_computeFillSpacePreferences() {
let res = Object.assign(
{},
this.namedChildren['content'].getFillSpacePreferences()
);
if (this.props.height !== null) {
res.vertical = false;
}
if (this.props.width !== null) {
res.horizontal = false;
}
return res;
}
getStyle() {
let styles = [];
if (this.props.height !== null) {
styles.push(
`height:${this.props.height}px`
);
}
if (this.props.width !== null) {
styles.push(
`width:${this.props.width}px`
);
}
return styles.join(";");
}
} |
JavaScript | @customElement('ids-separator')
@scss(styles)
class IdsSeparator extends IdsElement {
constructor() {
super();
}
template() {
let tagName = 'div';
if (this.parentElement?.tagName === 'IDS-MENU-GROUP') {
tagName = 'li';
}
return `<${tagName} class="ids-separator"></${tagName}>`;
}
} |
JavaScript | class ViewInterface extends Model {
/**
* get ViewModel class bind with Model
* @return {ViewModel} - ViewModel class
*/
getViewModel() {
return require('../vm/ViewInterface');
}
} |
JavaScript | class Graph {
constructor() {
this.INFINITY = 1 / 0;
this.vertices = {};
}
addVertex(name, edges) {
this.vertices[name] = edges;
}
shortestPath(start, finish) {
const nodes = new PriorityQueue();
const distances = {};
const previous = {};
const path = [];
let smallest;
let vertex;
let neighbor;
let alt;
// Assign to every node a tentative distance value:
// set it to zero for our initial node and to infinity
// for all other nodes.
for (vertex in this.vertices) {
if (vertex === start) {
// Set the initial node as current.
distances[vertex] = 0;
nodes.enqueue(0, vertex);
} else {
// Mark all other nodes unvisited.
// Create a set of all the unvisited nodes
// called the unvisited set.
distances[vertex] = this.INFINITY;
nodes.enqueue(this.INFINITY, vertex);
}
previous[vertex] = null;
}
// Loop through all of the nodes until we run out of nodes,
// or we find the node we were looking for
while (!nodes.isEmpty()) {
smallest = nodes.dequeue();
// If the current smallest node is the node we are looking for
if (smallest === finish) {
while (previous[smallest]) {
path.push(smallest);
smallest = previous[smallest];
}
break;
}
if (!smallest || distances[smallest] === this.INFINITY) {
continue;
}
// For the current node, consider all of its unvisited
// neighbors and calculate their tentative distances.
for (neighbor in this.vertices[smallest]) {
// Compare the newly calculated tentative distance to the
// current assigned value and assign the smaller one.
// For example, if the current node A is marked with a
// distance of 6, and the edge connecting it with a
// neighbor B has length 2,
// then the distance to B (through A) will be 6 + 2 = 8.
// If B was previously marked with a distance greater than 8 then change it to 8.
// Otherwise, keep the current value.
alt = distances[smallest] + this.vertices[smallest][neighbor];
// If the newly calculated tentative distance is smaller
// than the currently assigned value then assign the smaller one.
if (alt < distances[neighbor]) {
distances[neighbor] = alt;
previous[neighbor] = smallest;
nodes.enqueue(alt, neighbor);
}
}
}
return path;
}
} |
JavaScript | class Passage {
/**
* @method Passage
* @constructor
*/
constructor (name = "", tags = [], metadata = {}, text = "", pid = 1) {
this.name = name;
this.tags = tags;
this.metadata = metadata;
this.text = text;
this.pid = pid;
}
} |
JavaScript | class XAtomDebugPackage {
activate() {
const { XAtomDebug } = require('./XAtomDebug');
this.xAtomDebug = new XAtomDebug();
}
deactivate() {
if (this.xAtomDebug) {
this.xAtomDebug.destroy();
}
}
providePlugin() {
return this.xAtomDebug.getProvider();
}
deserializeBreakpointNavigatorView(serialized) {
const { BreakpointNavigatorView } = require('./Breakpoint');
return new BreakpointNavigatorView(null);
}
} |
JavaScript | class BlockPolledLiquityStore extends lib_base_1.LiquityStore {
constructor(readable) {
super();
this.connection = readable.connection;
this._readable = readable;
this._provider = EthersLiquityConnection_1._getProvider(readable.connection);
}
async _getRiskiestTroveBeforeRedistribution(overrides) {
const riskiestTroves = await this._readable.getTroves({ first: 1, sortedBy: "ascendingCollateralRatio", beforeRedistribution: true }, overrides);
if (riskiestTroves.length === 0) {
return new lib_base_1.TroveWithPendingRedistribution(constants_1.AddressZero, "nonExistent");
}
return riskiestTroves[0];
}
async _get(blockTag) {
const { userAddress, frontendTag } = this.connection;
const { blockTimestamp, _feesFactory, calculateRemainingLQTY, ...baseState } = await _utils_1.promiseAllValues({
blockTimestamp: this._readable._getBlockTimestamp(blockTag),
_feesFactory: this._readable._getFeesFactory({ blockTag }),
calculateRemainingLQTY: this._readable._getRemainingLiquidityMiningLQTYRewardCalculator({
blockTag
}),
price: this._readable.getPrice({ blockTag }),
numberOfTroves: this._readable.getNumberOfTroves({ blockTag }),
totalRedistributed: this._readable.getTotalRedistributed({ blockTag }),
total: this._readable.getTotal({ blockTag }),
lusdInStabilityPool: this._readable.getLUSDInStabilityPool({ blockTag }),
totalStakedLQTY: this._readable.getTotalStakedLQTY({ blockTag }),
_riskiestTroveBeforeRedistribution: this._getRiskiestTroveBeforeRedistribution({ blockTag }),
totalStakedUniTokens: this._readable.getTotalStakedUniTokens({ blockTag }),
remainingStabilityPoolLQTYReward: this._readable.getRemainingStabilityPoolLQTYReward({
blockTag
}),
frontend: frontendTag
? this._readable.getFrontendStatus(frontendTag, { blockTag })
: { status: "unregistered" },
...(userAddress
? {
accountBalance: this._provider.getBalance(userAddress, blockTag).then(_utils_1.decimalify),
lusdBalance: this._readable.getLUSDBalance(userAddress, { blockTag }),
lqtyBalance: this._readable.getLQTYBalance(userAddress, { blockTag }),
uniTokenBalance: this._readable.getUniTokenBalance(userAddress, { blockTag }),
uniTokenAllowance: this._readable.getUniTokenAllowance(userAddress, { blockTag }),
liquidityMiningStake: this._readable.getLiquidityMiningStake(userAddress, { blockTag }),
liquidityMiningLQTYReward: this._readable.getLiquidityMiningLQTYReward(userAddress, {
blockTag
}),
collateralSurplusBalance: this._readable.getCollateralSurplusBalance(userAddress, {
blockTag
}),
troveBeforeRedistribution: this._readable.getTroveBeforeRedistribution(userAddress, {
blockTag
}),
stabilityDeposit: this._readable.getStabilityDeposit(userAddress, { blockTag }),
lqtyStake: this._readable.getLQTYStake(userAddress, { blockTag }),
ownFrontend: this._readable.getFrontendStatus(userAddress, { blockTag })
}
: {
accountBalance: lib_base_1.Decimal.ZERO,
lusdBalance: lib_base_1.Decimal.ZERO,
lqtyBalance: lib_base_1.Decimal.ZERO,
uniTokenBalance: lib_base_1.Decimal.ZERO,
uniTokenAllowance: lib_base_1.Decimal.ZERO,
liquidityMiningStake: lib_base_1.Decimal.ZERO,
liquidityMiningLQTYReward: lib_base_1.Decimal.ZERO,
collateralSurplusBalance: lib_base_1.Decimal.ZERO,
troveBeforeRedistribution: new lib_base_1.TroveWithPendingRedistribution(constants_1.AddressZero, "nonExistent"),
stabilityDeposit: new lib_base_1.StabilityDeposit(lib_base_1.Decimal.ZERO, lib_base_1.Decimal.ZERO, lib_base_1.Decimal.ZERO, lib_base_1.Decimal.ZERO, constants_1.AddressZero),
lqtyStake: new lib_base_1.LQTYStake(),
ownFrontend: { status: "unregistered" }
})
});
return [
{
...baseState,
_feesInNormalMode: _feesFactory(blockTimestamp, false),
remainingLiquidityMiningLQTYReward: calculateRemainingLQTY(blockTimestamp)
},
{
blockTag,
blockTimestamp,
_feesFactory
}
];
}
/** @internal @override */
_doStart() {
this._get().then(state => {
if (!this._loaded) {
this._load(...state);
}
});
const blockListener = async (blockTag) => {
const state = await this._get(blockTag);
if (this._loaded) {
this._update(...state);
}
else {
this._load(...state);
}
};
this._provider.on("block", blockListener);
return () => {
this._provider.off("block", blockListener);
};
}
/** @internal @override */
_reduceExtra(oldState, stateUpdate) {
var _a, _b, _c;
return {
blockTag: (_a = stateUpdate.blockTag) !== null && _a !== void 0 ? _a : oldState.blockTag,
blockTimestamp: (_b = stateUpdate.blockTimestamp) !== null && _b !== void 0 ? _b : oldState.blockTimestamp,
_feesFactory: (_c = stateUpdate._feesFactory) !== null && _c !== void 0 ? _c : oldState._feesFactory
};
}
} |
JavaScript | class KeyServerCaller {
/**
* Creates a CallBuilder instance.
*
* @constructor
* @param {Object} axios Axios.js instance.
* @param {TokenD} [sdk] TokenD SDK instance.
*/
constructor (opts) {
this._axios = opts.axios
this._sdk = opts.sdk
this._wallet = null
this._urlSegments = []
}
addWallet (wallet) {
this._wallet = wallet
return this
}
post (urlSegment, data) {
this._appendUrlSegment(urlSegment)
let config = this._getRequestConfig({
method: 'post',
data,
url: this._getUrl()
}, false)
return this._axios(config)
}
postWithSignature (urlSegment, data, wallet) {
this._appendUrlSegment(urlSegment)
this.addWallet(wallet)
let config = this._getRequestConfig({
method: 'post',
data,
url: this._getUrl()
}, true)
return this._axios(config)
}
get (urlSegment, query) {
this._appendUrlSegment(urlSegment)
let config = this._getRequestConfig({
method: 'get',
params: query,
url: this._getUrl()
}, false)
return this._axios(config)
}
getWithSignature (urlSegment, query, wallet) {
this._appendUrlSegment(urlSegment)
this.addWallet(wallet)
let config = this._getRequestConfig({
method: 'get',
params: query,
url: this._getUrl()
}, true)
return this._axios(config)
}
patch (urlSegment, data) {
this._appendUrlSegment(urlSegment)
let config = this._getRequestConfig({
method: 'patch',
data
}, false)
return this._axios(config)
}
patchWithSignature (urlSegment, data, wallet) {
this._appendUrlSegment(urlSegment)
this.addWallet(wallet)
let config = this._getRequestConfig({
method: 'patch',
data,
url: this._getUrl()
}, true)
return this._axios(config)
}
delete (urlSegment) {
this._appendUrlSegment(urlSegment)
let config = this._getRequestConfig({
method: 'delete',
url: this._getUrl()
}, false)
return this._axios(config)
}
deleteWithSignature (urlSegment, wallet) {
this._appendUrlSegment(urlSegment)
this.addWallet(wallet)
let config = this._getRequestConfig({
method: 'delete',
url: this._getUrl()
}, true)
return this._axios(config)
}
_getRequestConfig (config, needSign = false) {
if (this._wallet) {
this._signRequestLegacy(config)
}
config.headers = config.headers || {}
config.headers['Content-Type'] = CONTENT_TYPE.applicationJson
config.withCredentials = false
return config
}
_signRequestLegacy (config) {
let validUntil = Math
.floor(this._getTimestamp() + SIGNATURE_VALID_SEC)
.toString()
let fullUrl = this._getFullUrl(config)
let signatureBase = `{ uri: '${fullUrl}', valid_untill: '${validUntil.toString()}'}`
let data = hash(signatureBase)
let signature = this._wallet.keypair.signDecorated(data)
Object.assign(config, {
headers: {
'X-AuthValidUnTillTimestamp': validUntil.toString(),
'X-AuthPublicKey': this._wallet.keypair.accountId(),
'X-AuthSignature': signature.toXDR('base64')
}
})
}
_appendUrlSegment (segment) {
if (isNumber(segment)) {
this._urlSegments.push(segment)
} else if (isString(segment)) {
if (segment.includes('/')) {
// multiple segments in a single string e.g. "/foo/bar/x"
let parsedLink = uri(segment)
let segments = parsedLink.path()
.split('/')
.filter((x) => x.length > 0)
segments.forEach((s) => this._urlSegments.push(s))
} else {
this._urlSegments.push(segment)
}
} else {
throw new TypeError('Invalid segment.')
}
}
_getUrl () {
return this._urlSegments.reduce((prev, next) => {
return `${prev}/${encodeURIComponent(next)}`
}, '')
}
_getFullUrl (config) {
let fullUrl = uri(config.url)
if (config.params) {
fullUrl = fullUrl.addQuery(config.params)
}
return fullUrl.toString()
}
_getTimestamp () {
let now = Math.floor(new Date().getTime() / 1000)
return now - this._sdk.clockDiff
}
} |
JavaScript | class CountryPicker extends React.Component {
constructor(props) {
super(props);
this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.state = {
dataSource: this.ds.cloneWithRows(props.data),
};
}
componentWillReceiveProps(nProps) {
this.setState(prevState => ({
dataSource: prevState.dataSource.cloneWithRows(nProps.data),
}));
}
render() {
const props = this.props;
return (
<View style={styles.container}>
<View style={styles.countryList}>
<ListView
keyboardShouldPersistTaps
initialListSize={5}
pageSize={1}
dataSource={this.state.dataSource}
enableEmptySections
renderRow={code => (
<CountryItem
country={R.merge(countries[code], { cca2: code })}
onSelect={() => props.onSelect(code)}
/>
)}
/>
</View>
<View style={styles.lettersContainer}>
<View style={styles.backIcon}>
<TouchableOpacity onPress={this.props.close}>
<Icon name="arrow-back" size={30} color="grey" />
</TouchableOpacity>
</View>
<ScrollView
keyboardShouldPersistTaps
contentContainerStyle={styles.lettersList}
style={{ flex: 1 }}
>
{
props.letters.map((letter, i) => (
<Letter key={i} filterLetter={props.filterLetter}>
{letter}
</Letter>
))
}
</ScrollView>
</View>
</View>
);
}
} |
JavaScript | class EventEmitter extends EE {
// constructor () {
// super()
// }
emit () {
const event = arguments[0]
let events = [event]
if (NGN.typeof(event) === 'regexp' || event.indexOf('*') >= 0) {
let re = event
if (NGN.typeof(re) !== 'regexp') {
re = new RegExp(event.replace('*', '.*', 'gi'))
}
events = this.eventNames().filter(function (eventName) {
return re.test(eventName) && eventName !== event
})
}
let args = Array.from(arguments)
args.shift()
let context = this
for (let index in events) {
args.unshift(events[index])
context.event = events[index]
super.emit.apply(context, args)
args.shift()
}
}
/**
* @method off
* Remove an event handler. If no handler is specified, all handlers for
* the spcified event will be removed.
* @param {string} eventName
* Name of the event to remove.
* @param {function} [handlerFn]
* The handler function to remove from the event handlers.
*/
off (eventName, callback) {
this.removeListener(eventName, callback)
}
/**
* @method onceoff
* Remove an event handler that was originally created using #once. If no
* handler is specified, all handlers for the spcified event will be removed.
* @param {string} eventName
* Name of the event to remove.
* @param {function} handlerFn
* The handler function to remove from the event handlers.
*/
onceoff (eventName, callback) {
this.off(eventName, callback)
}
/**
* @method clear
* Remove all event handlers from the EventEmitter (both regular and adhoc).
*/
clear () {
const me = this
this.eventNames().forEach(function (eventName) {
me.removeAllListeners(eventName)
})
}
} |
JavaScript | class Category {
constructor(collections, id, names) {
this.id = id == null ? new ObjectID() : id;
// Hash of all the names by local ('en-us') etc
// { 'en-us': 'computers' }
this.names = names || {};
// Collections used
this.categories = collections['categories'];
this.products = collections['products'];
}
/*
* Add a new name local to the category, update relevant products
*/
async addLocal(local, name, options = {}) {
// Build set statement
var setStatement = {}
// Set the new local
setStatement[`names.${local}`] = name;
// Update the category with the new local for the name
var r = await this.categories.updateOne({
_id: this.id
}, {
$set: setStatement
}, options);
if(r.modifiedCount == 0 && r.n == 0) {
throw new Error(`could not modify category with id ${this.id}`);
}
if(r.result.writeConcernError) {
throw r.result.writeConcernError;
}
// Set up the update statement
var updateStatement = {};
updateStatement[`categories.$.names.${local}`] = name;
// Update all the products that have the category cached
var r = await this.products.updateMany({
'categories._id': this.id
}, {
$set: updateStatement
}, options);
if(r.result.writeConcernError) {
throw r.result.writeConcernError;
}
}
/*
* Remove a new name local from the category, update relevant products
*/
async removeLocal(local, options = {}) {
// Build set statement
var setStatement = {}
// UnSet the new local
setStatement[`names.${local}`] = '';
// Update the category with the new local for the name
var r = await this.categories.updateOne({
_id: this.id
}, {
$unset: setStatement
}, options);
if(r.modifiedCount == 0 && r.n == 0) {
throw new Error(`could not modify category with id ${this.id}`);
}
if(r.result.writeConcernError) {
throw r.result.writeConcernError;
}
// Set up the update statement
var updateStatement = {};
updateStatement[`categories.$.names.${local}`] = '' ;
// Update all the products that have the category cached
var r = await this.products.updateMany({
'categories._id': this.id
}, {
$unset: updateStatement
}, options);
if(r.result.writeConcernError) {
throw r.result.writeConcernError;
}
}
/*
* Create a new mongodb category document
*/
async create(options = {}) {
// Insert a new category
var r = await this.categories.insertOne({
_id: this.id
, names: this.names
}, options);
if(r.result.writeConcernError) {
throw r.result.writeConcernError;
}
return this;
}
/*
* Reload the category information
*/
async reload() {
var doc = await this.categories.findOne({_id: this.id});
this.names = doc.names;
return this;
}
/*
* Create the optimal indexes for the queries
*/
static async createOptimalIndexes(collections) {
}
} |
JavaScript | class TreeNode {
constructor(val) {
this.value = val
this.left = null
this.right = null
}
} |
JavaScript | class Queue {
constructor() {
this.list = new ListNode();
}
get size() {
let elem = this.list;
let counter = 0;
while (elem.next !== null) {
counter++;
elem = elem.next;
}
return counter;
}
enqueue(element) {
let temp = this.list;
while (temp.next !== null) {
temp = temp.next;
}
temp.next = new ListNode(element);
if (this.list.value === undefined) {
this.list = this.list.next;
}
}
dequeue() {
const temp = this.list.value;
this.list = this.list.next;
return temp;
}
} |
JavaScript | class LocalizedUtils extends DateFnsUtils {
getDatePickerHeaderText(date) {
return format(date, "dd.mm.yyyy");
}
} |
JavaScript | class FakePlugin extends Plugin {
init() {
const schema = this.editor.model.schema;
const conversion = this.editor.conversion;
schema.register( 'foo', {
isObject: true,
isBlock: true,
allowWhere: '$block'
} );
schema.register( 'caption', {
allowIn: 'foo',
allowContentOf: '$block',
isLimit: true
} );
conversion.elementToElement( {
view: 'foo',
model: 'foo'
} );
conversion.elementToElement( {
view: 'caption',
model: 'caption'
} );
}
} |
JavaScript | class FileStore extends DataStore {
constructor(options) {
super(options);
this.directory = options.directory || options.path.replace(/^\//, '');
this.extensions = ['creation'];
this._checkOrCreateDirectory();
}
/**
* Ensure the directory exists.
*/
_checkOrCreateDirectory() {
fs.mkdir(this.directory, MASK, (error) => {
if (error && error.code !== IGNORED_MKDIR_ERROR) {
throw error;
}
});
}
/**
* Create an empty file.
*
* @param {File} file
* @return {Promise}
*/
create(file) {
super.create(file);
return new Promise((resolve, reject) => {
fs.open(`${this.directory}/${file.id}`, 'w', (err, fd) => {
if (err) {
console.log(err);
reject(err);
}
fs.close(fd, (exception) => {
if (exception) {
reject(exception);
}
resolve();
});
});
});
}
/**
* Write to the file, starting at the provided offset
*
* @param {object} req http.incomingMessage
* @param {string} file_name Name of file
* @param {integer} offset starting offset
* @return {Promise}
*/
write(req, file_name, offset) {
return new Promise((resolve, reject) => {
const path = `${this.directory}/${file_name}`;
const options = {
flags: 'r+',
start: offset,
};
const stream = fs.createWriteStream(path, options);
if (!stream) {
reject(500);
}
let new_offset = 0;
req.on('data', (buffer) => {
new_offset += buffer.length;
});
req.on('end', () => {
console.info(`[FileStore] write: ${new_offset} bytes written to ${path}`);
offset += new_offset;
console.info(`[FileStore] write: File is now ${offset} bytes`);
resolve(offset);
});
stream.on('error', (e) => {
console.warn('[FileStore] write: Error', e);
reject(500);
});
req.pipe(stream);
});
}
/**
* Return file stats, if they exits
*
* @param {string} file_name name of the file
* @return {object} fs stats
*/
getOffset(file_name) {
return new Promise((resolve, reject) => {
const file_path = `${this.directory}/${file_name}`;
fs.stat(file_path, (error, stats) => {
if (error && error.code === FILE_DOESNT_EXIST) {
console.warn(`[FileStore] getOffset: No file found at ${file_path}`);
reject(404);
}
if (error) {
console.warn(error);
reject(error);
}
resolve(stats);
});
});
}
/**
* Save the metadata.
*
* @param {string} file_name filename
* @param {object} metadata filename
* @return {Promise}
*/
saveMetadata(file_name, metadata) {
super.saveMetadata(file_name, metadata);
const file_path = `${this.directory}/${file_name}.json`;
return new Promise((resolve, reject) => {
fs.writeFile(file_path, JSON.stringify(metadata), (err) => {
if (err) {
reject(err);
}
resolve();
});
});
}
/**
* Return metadata, if it exits
*
* @param {string} file_name name of the file
* @return {Promise} resolves to metadata
*/
getMetadata(file_name) {
const file_path = `${this.directory}/${file_name}.json`;
return new Promise((resolve, reject) => {
fs.readFile(file_path, (err, metadata) => {
if (err) {
reject(err);
}
resolve(metadata);
});
});
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.